Locate Element in Sorted Array
Heaps, Sorting & SearchAuto-graded · 25 test casesLast updated
Perform logarithmic-time binary search on a strictly increasing array of distinct integers to find a target value's index or detect its absence.
Given a list of distinct integers a sorted in strictly ascending order and an integer k, determine the zero-based index of k within a. If k does not exist in a, return -1.
Your solution must run in $O(\log n)$ time, where $n$ is the length of a.
Constraints
1 <= len(a) <= 10^4-10^4 < a[i] < 10^4for all valid indicesi-10^4 < k < 10^4a[i] < a[i + 1]for all0 <= i < len(a) - 1(strictly increasing sequence)
Examples
Example 1
Input: find_target_index([-7, -2, 0, 4, 11, 15], 4)
Output: 3
Example 2
Input: find_target_index([-7, -2, 0, 4, 11, 15], 5)
Output: -1
Example 3
Input: find_target_index([8], 8)
Output: 0
Hints
Hint 1
Since the input list is strictly sorted, comparing a target against an element allows you to rule out half of the remaining elements at each step.
Hint 2
Maintain two pointers, `left` and `right`, representing the bounds of the active search range.
Hint 3
Update `left = mid + 1` if `a[mid] < k`, or `right = mid - 1` if `a[mid] > k`.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach: Binary Search
To locate k in $O(\log n)$ time, we use classic binary search on the sorted list a.
- Initialize two pointers:
left = 0andright = len(a) - 1. - Compute the midpoint index
mid = (left + right) // 2. - Compare
a[mid]withk:- If
a[mid] == k, we have found the target and returnmid. - If
a[mid] < k,kmust lie to the right ofmid. We narrow the search toleft = mid + 1. - If
a[mid] > k,kmust lie to the left ofmid. We narrow the search toright = mid - 1.
- If
- If
left > right, the search space has collapsed without findingk, so we return-1.
Complexity Analysis
- Time Complexity: $O(\log n)$. The search range is halved during each iteration, requiring at most $\lceil \log_2 n \rceil + 1$ iterations.
- Space Complexity: $O(1)$. Memory usage is constant as only a few pointer variables are tracked.
Python Reference Solution
from typing import List
def find_target_index(a: List[int], k: int) -> int:
left, right = 0, len(a) - 1
while left <= right:
mid = (left + right) // 2
if a[mid] == k:
return mid
elif a[mid] < k:
left = mid + 1
else:
right = mid - 1
return -1