Locate Target in Strictly Increasing Array

Medium · Coding & Algorithms · Software Engineer · Onsite

Problem Statement

Implement find_target_index(nums, target) to locate an integer target inside a list nums whose integers appear in strictly ascending order.

def find_target_index(nums: list[int], target: int) -> int:
  • Report the 0-indexed location i satisfying nums[i] == target. Because consecutive elements strictly increase, no value repeats and at most one index matches.
  • Whenever target is absent from nums, return -1.
  • Treat nums as read-only (never mutate its elements or length).
  • Your implementation must achieve O(log n) worst-case runtime, where n = len(nums).

Examples

Example 1

Input: nums = [-12, -5, 1, 6, 9, 18, 24], target = 9
Output: 4

Counting from index 0, element nums[4] equals 9, so 4 is returned.

Example 2

Input: nums = [-12, -5, 1, 6, 9, 18, 24], target = 10
Output: -1

Value 10 sits between nums[4] = 9 and nums[5] = 18 without appearing anywhere in nums, producing -1.

Example 3

Input: nums = [-3], target = -3
Output: 0

The single entry at index 0 matches -3.

Constraints

  • 1 <= len(nums) <= 10^4
  • -10^4 < nums[i] < 10^4 for every 0 <= i < len(nums)
  • -10^4 < target < 10^4
  • nums[i] < nums[i + 1] for every 0 <= i < len(nums) - 1

Step-by-step walkthrough

  1. Restate the goal and the O(log n) rule

    We are given a strictly increasing array nums of distinct integers and an integer target: - If target appears in nums, return its 0-based index (unique because all elements are distinct). - If target is absent, return -1. - Do not modify nums, and finish in O(log n) time.

    That O(log n) requirement immediately rules out for x in nums, target in nums, and nums.index(target) — all three scan element by element from index 0 and take O(n) time in the worst case.

  2. Why linear scan wastes sorted order

    A plain left-to-right scan looks like this:

    def linear_find(nums: list[int], target: int) -> int:
        for i in range(len(nums)):
            if nums[i] == target:
                return i
        return -1
    

    Why is that wasteful? When nums = [-12, -5, 1, 6, 9, 18, 24] and target = 18, checking nums[0] = -12 only rules out one index. Because nums is sorted, checking the middle index rules out half the array in a single comparison! For n = 10,000, halving 10,000 takes at most 14 comparisons (2^14 = 16,384 > 10,000) instead of 10,000.

  3. Maintain an inclusive search window [left, right]

    Keep two integer pointers, left and right, marking the inclusive range of indices [left, right] where target could still live. Initially left = 0 and right = len(nums) - 1.

    At each step, inspect the middle index mid = left + (right - left) // 2 and read mid_val = nums[mid]:

    Case 1: mid_val == target  --> Found! Return mid immediately.
    
    Case 2: mid_val < target   --> Everything at or left of mid is even smaller:
            [ <= mid_val (< target) |   still possible   ]
             left                mid mid+1          right   --> set left = mid + 1
    
    Case 3: mid_val > target   --> Everything at or right of mid is even larger:
            [   still possible   | >= mid_val (> target) ]
             left          mid-1  mid               right   --> set right = mid - 1
    

    Every iteration keeps one rock-solid invariant: if target exists anywhere in nums, its index is inside [left, right].

  4. Get every boundary detail right

    Almost every binary search bug comes from mixing conventions on three lines. Here is why each boundary in our inclusive [left, right] template is written the way it is:

    1. right = len(nums) - 1: Both left and right are valid array indices inside our inclusive window.
    2. while left <= right: (not <): When left == right, the window [left, right] still contains one candidate index (nums[left]) that has not been tested yet! Stopping at left < right would skip that final element and fail on [-3] with target = -3.
    3. left = mid + 1 and right = mid - 1 (never mid): We already checked nums[mid] != target, so mid cannot be the answer. Excluding mid shrinks the window by at least 1 element every step, guaranteeing the loop always terminates.
    4. Store mid_val = nums[mid] once: Reading nums[mid] into a variable avoids indexing the list twice per iteration, keeping total array reads to at most floor(log2(n)) + 1.
    def find_target_index(nums: list[int], target: int) -> int:
        # Inclusive index window [left, right]: invariant is that if target is in nums, its index lies inside [left, right].
        left = 0
        right = len(nums) - 1
    
        # Phase 1: Repeatedly halve [left, right]; use `<=` because left == right still has 1 untested element.
        while left <= right:
            # Compute midpoint safely and read nums[mid] once per iteration.
            mid = left + (right - left) // 2
            mid_val = nums[mid]
    
            if mid_val == target:
                return mid
            elif mid_val < target:
                # Because nums is strictly increasing, indices <= mid are all < target; discard left half.
                left = mid + 1
            else:
                # Because nums is strictly increasing, indices >= mid are all > target; discard right half.
                right = mid - 1
    
        # Phase 2: Window is empty (left > right), so by the loop invariant target cannot exist in nums.
        return -1
    
  5. Trace Example 1 and Example 2 side by side

    Let nums = [-12, -5, 1, 6, 9, 18, 24] (indices 0..6):

    Example 1: target = 9
      Step 1: [left=0 .. right=6], mid = 3 -> nums[3] = 6  < 9  --> move left = 4
               idx:    0   1  2  3    4   5   6
               val: [-12, -5, 1, 6, | 9, 18, 24]
                                mid  ^-- new window [4..6]
    
      Step 2: [left=4 .. right=6], mid = 5 -> nums[5] = 18 > 9  --> move right = 4
               val: [-12, -5, 1, 6, | 9, | 18, 24]
                                     [4]   mid
    
      Step 3: [left=4 .. right=4], mid = 4 -> nums[4] = 9 == 9  --> return 4!
    
    Example 2: target = 10 (same Steps 1 and 2 narrow window to [4..4])
      Step 3: [left=4 .. right=4], mid = 4 -> nums[4] = 9  < 10 --> move left = 5
      End:    left = 5 > right = 4 (window is empty!)           --> return -1!
    

    Notice how both traces depend on running that final iteration where left == right == 4: Example 1 finds 9 on that step, and Example 2 proves 10 is missing right after it.

  6. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    
    def find_target_index(nums: list[int], target: int) -> int:
        # Inclusive index window [left, right]: invariant is that if target is in nums, its index lies inside [left, right].
        left = 0
        right = len(nums) - 1
    
        # Phase 1: Repeatedly halve [left, right]; use `<=` because left == right still has 1 untested element.
        while left <= right:
            # Compute midpoint safely and read nums[mid] once per iteration.
            mid = left + (right - left) // 2
            mid_val = nums[mid]
    
            if mid_val == target:
                return mid
            elif mid_val < target:
                # Because nums is strictly increasing, indices <= mid are all < target; discard left half.
                left = mid + 1
            else:
                # Because nums is strictly increasing, indices >= mid are all > target; discard right half.
                right = mid - 1
    
        # Phase 2: Window is empty (left > right), so by the loop invariant target cannot exist in nums.
        return -1
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Think of playing "Guess the Number" between 1 and 1,000 when your friend answers "too low" or "too high" after every guess. Guessing 1, then 2, then 3 could take 1,000 tries, whereas always guessing the middle of the remaining possibilities cuts the range in half every single turn and finishes in at most 10 guesses! That strategy is binary search (an algorithm that repeatedly inspects the middle element of a sorted range and discards whichever half cannot hold the target). To keep our indices bug-free, we maintain a loop invariant (a condition guaranteed to stay true before and after every iteration): if target exists in nums, its index is inside the inclusive window [left, right].

Why do simpler approaches fail here? Scanning from index 0 with a for loop, target in nums, or nums.index(target) ignores the sorted order and reads up to all n elements (10,000 comparisons instead of 14), violating the required O(log n) time bound. A recursive binary search that slices the list (nums[mid + 1:]) also secretly takes O(n) total time because Python allocates and copies up to n / 2 elements on the first slice alone!

Let's trace Example 1 (nums = [-12, -5, 1, 6, 9, 18, 24]) searching for target = 9:

Start:  left = 0, right = 6  (active window: [-12, -5, 1, 6, 9, 18, 24])
Turn 1: mid = 3, nums[3] = 6  < 9  -> discard 0..3 -> left = 4, right = 6 (window: [9, 18, 24])
Turn 2: mid = 5, nums[5] = 18 > 9  -> discard 5..6 -> left = 4, right = 4 (window: [9])
Turn 3: mid = 4, nums[4] = 9 == 9  -> match found! return 4

Complexity

Let n = len(nums).

  • Time: O(log n). Every iteration either returns immediately or throws away mid plus one entire half of [left, right], cutting the window size to at most floor((size - 1) / 2). Starting from n elements, the window can be halved at most floor(log2(n)) + 1 times before becoming empty (at most 14 reads for n = 10,000), and each step does O(1) arithmetic and one array lookup.
  • Space: O(1). We only store four integers (left, right, mid, mid_val) and never copy or mutate nums.

Edge cases

  • Single-element array (nums = [-3]): Starts with left = 0 and right = 0. Because the condition is left <= right, the loop runs once at mid = 0, returning 0 when target == -3 and -1 when target is -4 or -2.
  • Target at index 0 or index n - 1: Repeatedly moving right = mid - 1 reaches mid = 0, and repeatedly moving left = mid + 1 reaches mid = n - 1, so neither extreme endpoint is ever skipped.
  • Target smaller than nums[0] or larger than nums[-1]: Either right drops to -1 (crossing left = 0) or left climbs to n (crossing right = n - 1); in both cases the loop exits cleanly without out-of-bounds indexing and returns -1.
  • Target falling in a gap between two neighbors (target = 10 between 9 and 18): The window narrows to [4, 4], checks 9 < 10, advances left = 5 > right = 4, and returns -1.
  • Empty array (nums = []): Even though the constraints guarantee n >= 1, right = len(nums) - 1 initializes to -1, so left <= right (0 <= -1) is immediately False and -1 is returned safely.

Common mistakes

  • Writing while left < right: with an inclusive right = len(nums) - 1: That stops as soon as the window shrinks to 1 element (left == right) without ever testing that last element, returning -1 on nums = [-3], target = -3 and on Example 1 (target = 9).
  • Updating left = mid or right = mid on an inclusive window: Because // 2 rounds down, when left = 2 and right = 3, mid equals 2; setting left = mid leaves [left, right] stuck at [2, 3] in an infinite loop! Always step past mid with mid + 1 and mid - 1.
  • Slicing nums[:mid] or nums[mid + 1:] inside recursion: Slicing copies elements in O(k) time, turning O(log n) work into O(n) + O(n/2) + O(n/4) + ... = O(n) time and O(n) extra memory.
  • Reading nums[mid] multiple times per iteration: Caching mid_val = nums[mid] avoids redundant lookups and keeps element accesses minimal.

Alternative approaches

  • Python's bisect.bisect_left: idx = bisect.bisect_left(nums, target) finds the lower bound (the first index i where nums[i] >= target, or len(nums) if all elements are smaller) in O(log n) time; you then return idx if idx < len(nums) and nums[idx] == target else -1. In interviews, know bisect_left, but write the explicit loop unless the interviewer invites library helpers.
  • Half-open window [left, right): Initialize left = 0, right = len(nums), loop while left < right:, and update left = mid + 1 or right = mid. Both conventions are O(log n) time and O(1) space; just never mix inclusive right = len(nums) - 1 with half-open right = mid.

Follow-up questions

  • How would you modify the search if duplicate integers were allowed and you needed the leftmost matching index? Instead of returning immediately when nums[mid] == target, record first_pos = mid and keep searching the left half by setting right = mid - 1 to see if an even earlier copy exists. When left > right, return first_pos (initialized to -1), which still runs in O(log n) time and O(1) space.
  • If the sought value is missing, how can you return the index where it belongs to keep the list sorted? Notice that when our exact loop exits with left > right (left == right + 1), every index < left was proven < target and every index >= left was proven > target! Returning left instead of -1 gives the exact sorted insertion index with zero extra code.
  • How can you still achieve O(log n) runtime if the strictly increasing array was rotated around an unknown pivot? At any midpoint mid, cutting a rotated sorted array (such as [18, 24, -12, -5, 1, 6, 9]) in half leaves at least one of the two halves [left, mid] or [mid, right] completely sorted, which you detect by checking nums[left] <= nums[mid]. Check whether target lies inside that sorted half's endpoint values (nums[left] <= target < nums[mid], or nums[mid] < target <= nums[right] when the right half is sorted); if so, narrow into that half, and otherwise narrow into the other half.

Follow-up questions

Similar questions

More Visa interview questions

All 27 Visa questions →