KatInterview

Locate Element in Sorted Array

Heaps, Sorting & SearchAuto-graded · 25 test cases
EasyAuto-gradedHeaps, Sorting & Searchbinary-searcharrayssearching

Last 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^4 for all valid indices i
  • -10^4 < k < 10^4
  • a[i] < a[i + 1] for all 0 <= 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`.