Last Occurrence
Return the last matching position in sorted order, or -1.
EXECUTION LAB
Return the last matching position in sorted order, or -1.
Input and constraints
- Values must be in nondecreasing order.
- Use at most 32 integers. Each numeric input is between -1000 and 1000.
Code inspector
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 -1Visualizer
Step 1 of 401left
13
23mid
33
47
Inspect the current state
Check which side of the boundary contains the midpoint.
Variable watch
left 0mid 2right 5target 3
Step explanation
Check which side of the boundary contains the midpoint.
comparisons 1reads 0writes 0swaps 0recursiveCalls 0
Educational simulation · O(log n) time · O(1) space
Worked explanation
Locate the dividing line between two adjacent seating sections; the first seat of one ends the other.
Guided solution
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
Examples
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
Progressive hints
Hint 1
Locate the dividing line between two adjacent seating sections; the first seat of one ends the other.Hint 2
Maintain a half-open range. Every item removed on the left is on the known lower side of the boundary.Hint 3
Step through the worked example and inspect the highlighted variables before each update.Common mistake
Stopping at the first equality can land in the middle of duplicate values.
Interview follow-up
Which inequality moves the boundary beyond every duplicate?