Skip to content

Instantly share code, notes, and snippets.

@anil477
Created January 21, 2017 11:37
Show Gist options
  • Save anil477/510b09338a75940b5afc20ad854de89c to your computer and use it in GitHub Desktop.
Save anil477/510b09338a75940b5afc20ad854de89c to your computer and use it in GitHub Desktop.
Finding the first and last occurrence of a duplicate item in a sorted array using binary search. Also finds the count of duplicate element( and indices)
#searchFirst is a flag not for finding the first/last occurence
def binarySearch(arr, l, r, x, searchFirst):
result = -1
while l <= r:
mid = (l + r ) / 2
# Check if x is present at mid
if arr[mid] == x:
result = mid
if searchFirst:
r = mid - 1
else:
l = mid + 1
# If x is greater, ignore left half
elif arr[mid] < x:
l = mid + 1
# If x is smaller, ignore right half
else:
r = mid - 1
# If we reach here, then the element was not present
return result
# Test array
arr = [2, 3, 4, 10, 10, 10, 10, 40]
x = 10
# Function call
first = binarySearch(arr, 0, len(arr) - 1, x, True)
last = binarySearch(arr, 0, len(arr) - 1, x, False)
if first == -1 and last == -1:
print "Element not found"
else:
print "First Occurence Index", first
print "Last Occurence Index", last
print "Total Occurence", (last - first + 1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment