Continue learning
Practice related DSA questions in the same topic.
Return the last matching position in sorted order, or -1.
Return the last matching position in sorted order, or -1.
def solve(values, target): left = 0 right = len(values) while (left < right): mid = (left + ((right - left) // 2)) if (values[mid] <= target): left = (mid + 1) else: right = mid candidate = (left - 1) if ((candidate >= 0) and (values[candidate] == target)): return candidate return -1Check which side of the boundary contains the midpoint.
Check which side of the boundary contains the midpoint.
Locate the dividing line between two adjacent seating sections; the first seat of one ends the other.
Maintain a half-open range. Every item removed on the left is on the known lower side of the boundary.
O(log n) time · O(1) auxiliary space
Worked example · {"values":[1,3,3,3,7],"target":3} ⇒ 3
Edge case 1 · {"values":[],"target":5} ⇒ -1
Edge case 2 · {"values":[1,2],"target":4} ⇒ -1
Stopping at the first equality can land in the middle of duplicate values.
Which inequality moves the boundary beyond every duplicate?