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
isatisfyingnums[i] == target. Because consecutive elements strictly increase, no value repeats and at most one index matches. - Whenever
targetis absent fromnums, return-1. - Treat
numsas read-only (never mutate its elements or length). - Your implementation must achieve
O(log n)worst-case runtime, wheren = 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^4for every0 <= i < len(nums)-10^4 < target < 10^4nums[i] < nums[i + 1]for every0 <= i < len(nums) - 1
Step-by-step walkthrough
Restate the goal and the O(log n) rule
We are given a strictly increasing array
numsof distinct integers and an integertarget: - Iftargetappears innums, return its 0-based index (unique because all elements are distinct). - Iftargetis absent, return-1. - Do not modifynums, and finish inO(log n)time.That
O(log n)requirement immediately rules outfor x in nums,target in nums, andnums.index(target)— all three scan element by element from index0and takeO(n)time in the worst case.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 -1Why is that wasteful? When
nums = [-12, -5, 1, 6, 9, 18, 24]andtarget = 18, checkingnums[0] = -12only rules out one index. Becausenumsis sorted, checking the middle index rules out half the array in a single comparison! Forn = 10,000, halving10,000takes at most14comparisons (2^14 = 16,384 > 10,000) instead of10,000.Maintain an inclusive search window [left, right]
Keep two integer pointers,
leftandright, marking the inclusive range of indices[left, right]wheretargetcould still live. Initiallyleft = 0andright = len(nums) - 1.At each step, inspect the middle index
mid = left + (right - left) // 2and readmid_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 - 1Every iteration keeps one rock-solid invariant: if
targetexists anywhere innums, its index is inside[left, right].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:right = len(nums) - 1: Bothleftandrightare valid array indices inside our inclusive window.while left <= right:(not<): Whenleft == right, the window[left, right]still contains one candidate index (nums[left]) that has not been tested yet! Stopping atleft < rightwould skip that final element and fail on[-3]withtarget = -3.left = mid + 1andright = mid - 1(nevermid): We already checkednums[mid] != target, somidcannot be the answer. Excludingmidshrinks the window by at least 1 element every step, guaranteeing the loop always terminates.- Store
mid_val = nums[mid]once: Readingnums[mid]into a variable avoids indexing the list twice per iteration, keeping total array reads to at mostfloor(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 -1Trace Example 1 and Example 2 side by side
Let
nums = [-12, -5, 1, 6, 9, 18, 24](indices0..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 finds9on that step, and Example 2 proves10is missing right after it.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 awaymidplus one entire half of[left, right], cutting the window size to at mostfloor((size - 1) / 2). Starting fromnelements, the window can be halved at mostfloor(log2(n)) + 1times before becoming empty (at most14reads forn = 10,000), and each step doesO(1)arithmetic and one array lookup. - Space:
O(1). We only store four integers (left,right,mid,mid_val) and never copy or mutatenums.
Edge cases
- Single-element array (
nums = [-3]): Starts withleft = 0andright = 0. Because the condition isleft <= right, the loop runs once atmid = 0, returning0whentarget == -3and-1whentargetis-4or-2. - Target at index
0or indexn - 1: Repeatedly movingright = mid - 1reachesmid = 0, and repeatedly movingleft = mid + 1reachesmid = n - 1, so neither extreme endpoint is ever skipped. - Target smaller than
nums[0]or larger thannums[-1]: Eitherrightdrops to-1(crossingleft = 0) orleftclimbs ton(crossingright = 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 = 10between9and18): The window narrows to[4, 4], checks9 < 10, advancesleft = 5 > right = 4, and returns-1. - Empty array (
nums = []): Even though the constraints guaranteen >= 1,right = len(nums) - 1initializes to-1, soleft <= right(0 <= -1) is immediatelyFalseand-1is returned safely.
Common mistakes
- Writing
while left < right:with an inclusiveright = len(nums) - 1: That stops as soon as the window shrinks to 1 element (left == right) without ever testing that last element, returning-1onnums = [-3], target = -3and on Example 1 (target = 9). - Updating
left = midorright = midon an inclusive window: Because// 2rounds down, whenleft = 2andright = 3,midequals2; settingleft = midleaves[left, right]stuck at[2, 3]in an infinite loop! Always step pastmidwithmid + 1andmid - 1. - Slicing
nums[:mid]ornums[mid + 1:]inside recursion: Slicing copies elements inO(k)time, turningO(log n)work intoO(n) + O(n/2) + O(n/4) + ... = O(n)time andO(n)extra memory. - Reading
nums[mid]multiple times per iteration: Cachingmid_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 indexiwherenums[i] >= target, orlen(nums)if all elements are smaller) inO(log n)time; you then returnidxifidx < len(nums) and nums[idx] == targetelse-1. In interviews, knowbisect_left, but write the explicit loop unless the interviewer invites library helpers. - Half-open window
[left, right): Initializeleft = 0, right = len(nums), loopwhile left < right:, and updateleft = mid + 1orright = mid. Both conventions areO(log n)time andO(1)space; just never mix inclusiveright = len(nums) - 1with half-openright = 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, recordfirst_pos = midand keep searching the left half by settingright = mid - 1to see if an even earlier copy exists. Whenleft > right, returnfirst_pos(initialized to-1), which still runs inO(log n)time andO(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< leftwas proven< targetand every index>= leftwas proven> target! Returningleftinstead of-1gives 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 checkingnums[left] <= nums[mid]. Check whethertargetlies inside that sorted half's endpoint values (nums[left] <= target < nums[mid], ornums[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
- How would you modify the search if duplicate integers were allowed and you needed the leftmost matching index?
- If the sought value is missing, how can you return the index where it belongs to keep the list sorted?
- How can you still achieve O(log n) runtime if the strictly increasing array was rotated around an unknown pivot?
Similar questions
- Reachable Positive Totals with Limited Coin Counts
- Counting Transitive Clusters in an Adjacency Matrix
- Pair Sum Count Across Two Arrays
- Counting Landmasses on a Read-Only Grid
- Counting Valid Letter-and-Punctuation Tokens
- Counting Parity-Alternating Subsequences
More Visa interview questions
- Java Method Dispatch and Service Architecture Trade-offs Medium
- Build and Explain a Grounded RAG Pipeline Medium
- Lean Solutions to Complex Problems and Project Decomposition Medium Pro
- Counting Transitive Clusters in an Adjacency Matrix Medium Pro
- Pair Sum Count Across Two Arrays Medium Pro
- Counting Landmasses on a Read-Only Grid Medium Pro
- Counting Valid Letter-and-Punctuation Tokens Medium Pro
- Order Price Snapshots and 30-Day Spend Indexing Medium Pro
- Architecting an On-Demand Ride Dispatch Backend Medium Pro
- Cyclic Warehouse Package Routing with Closures Medium Pro