KatInterview

Find Target Index in Sorted Array

Heaps, Sorting & SearchAuto-graded · 24 test cases
MediumAuto-gradedHeaps, Sorting & Searchbinary-searcharraysiterative

Last updated

Tests ability to implement iterative binary search with correct loop invariants, boundary handling, and termination conditions.

Write a function that searches for a target value in a sorted array of integers and returns its index. If the target appears multiple times, return any valid index. If the target is not present, return -1.

The array is sorted in ascending order and may contain duplicates.

Your implementation must use an iterative approach with logarithmic time complexity.

Constraints

  • 0 ≤ len(nums) ≤ 10⁵
  • -10⁹ ≤ nums[i] ≤ 10⁹
  • -10⁹ ≤ target ≤ 10⁹
  • nums is sorted in non-decreasing order

Examples

Example 1

Input: find_target_index([1, 3, 5, 7, 9], 5)

Output: 2

Example 2

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

Output: -1

Example 3

Input: find_target_index([], 10)

Output: -1

Example 4

Input: find_target_index([2, 2, 2, 2], 2)

Output: 1

Hints

Hint 1

Maintain a search window that shrinks by half each iteration by comparing the middle element to the target.

Hint 2

Use an inclusive range [left, right] with the loop condition left <= right, and update boundaries with mid ± 1 to avoid infinite loops.

Hint 3

Calculate mid as left + (right - left) // 2 to prevent potential overflow issues in other languages.