KatInterview

Find Leftmost Position Meeting Threshold

Heaps, Sorting & SearchAuto-graded · 22 test cases
MediumAuto-gradedHeaps, Sorting & Searchbinary-searchboundariesduplicates

Last updated

Tests understanding of lower-bound binary search with correct boundary handling and duplicate treatment.

Write a function that locates the leftmost position in a sorted array where a value meets or exceeds a threshold.

You're given a sorted array nums of integers and a threshold value target. Return the index of the first element that is greater than or equal to target. If no element meets this condition, return -1.

Your solution must handle arrays containing duplicate values correctly, returning the leftmost qualifying position.

Constraints

  • 0 <= len(nums) <= 10^5
  • -10^9 <= nums[i] <= 10^9
  • -10^9 <= target <= 10^9
  • nums is sorted in non-decreasing order
  • Your solution should run in O(log n) time

Examples

Example 1

Input: find_threshold_position([1, 3, 5, 7], 5)

Output: 2

Example 2

Input: find_threshold_position([1, 3, 5, 7], 4)

Output: 2

Example 3

Input: find_threshold_position([1, 3, 5, 7], 10)

Output: -1

Example 4

Input: find_threshold_position([1, 1, 2, 2, 4], 2)

Output: 2

Hints

Hint 1

Think about what property divides the array into two regions: elements below the threshold and elements at or above it.

Hint 2

Use a half-open interval [lo, hi) where hi starts at n (not n-1) to naturally handle the 'not found' case.

Hint 3

When you find an element >= target, don't return immediately—it might not be the leftmost one. Keep searching to the left.