Example 1
ready- Input
nums = [ -7, -1, 4, 9, 15 ] target = 4- Expected
2- Why
- 4 sits at zero-based index 2
A sorted list is a quiet superpower: one comparison can rule out half of it.
You're given an integer array nums in strictly increasing order, meaning every
value is larger than the one before it, plus an integer target. If target appears,
return its zero-based index. If it doesn't, return -1.
A few ground rules:
1 <= nums.length <= 100_000-1_000_000_000 <= nums[i], target <= 1_000_000_000nums is strictly increasing.Hints
Track the first and last indices where target could still be. Compare the value
halfway between them with target.
If the middle value is too small, the middle and everything left of it are too small. If it's too large, the middle and everything right of it are too large.
Continue while the interval is valid: left <= right. Once left > right, no
candidate remains, so return -1.
How would you change the search to return the index where a missing target should be inserted while keeping the array sorted?
Visible cases
nums = [
-7,
-1,
4,
9,
15
]
target = 42nums = [
3,
8,
12,
21
]
target = 30nums = [
-5,
0,
6,
14
]
target = 7-1Interview signal
Walk from left to right and stop when you find target. This is correct, but it treats
a sorted array like an unsorted one.
def search(nums: list[int], target: int) -> int:
for index, value in enumerate(nums):
if value == target:
return index
return -1Time O(n). Space O(1). In the worst case, you inspect every value.
Keep a closed interval [left, right] containing every index that could still hold the
answer. Compare its middle value with target:
left = middle + 1.right = middle - 1.def search(nums: list[int], target: int) -> int:
left, right = 0, len(nums) - 1
while left <= right:
middle = left + (right - left) // 2
if nums[middle] == target:
return middle
if nums[middle] < target:
left = middle + 1
else:
right = middle - 1
return -1Each comparison cuts the live interval roughly in half. Moving past middle matters:
you've already proved that position isn't the answer, and keeping it would risk an
infinite loop.
Time O(log n). Space O(1). The interval shrinks in place; no extra collection is needed.
Ready to run.
3 cases are queued.
Visible testcase
Case 1
Expected
2