Taro Logo

Find First and Last Position of Element in Sorted Array

Medium
Asked by:
Profile picture
Profile picture
Profile picture
Profile picture
+23
More companies
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
1.6K views
Topics:
ArraysBinary Search

Given an array of integers nums sorted in non-decreasing order, find the starting and ending position of a given target value.

If target is not found in the array, return [-1, -1].

You must write an algorithm with O(log n) runtime complexity.

Example 1:

Input: nums = [5,7,7,8,8,10], target = 8
Output: [3,4]

Example 2:

Input: nums = [5,7,7,8,8,10], target = 6
Output: [-1,-1]

Example 3:

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

Constraints:

  • 0 <= nums.length <= 105
  • -109 <= nums[i] <= 109
  • nums is a non-decreasing array.
  • -109 <= target <= 109

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What should we return if the target element does not exist in the array?
  2. Are there any constraints on the size of the array, or what type of integers can it contain?
  3. Is the input array guaranteed to be sorted in non-decreasing order?
  4. Can the array be empty, and if so, how should we handle that edge case?
  5. How should we handle duplicate values, and can we assume the array contains multiple instances of the target?

Brute Force Solution

Approach

Imagine you are given a long sorted list of items and asked to find where a specific target item first appears and where it last appears. The brute force approach involves looking at every single item in the collection from beginning to end to check for the target.

Here's how the algorithm would work step-by-step:

  1. Start by looking at the very first item in the collection.
  2. Check if this item matches the target you are searching for.
  3. If it matches, make a mental note that you found a spot where the target lives, and remember where you saw it.
  4. Move on to the next item in the collection and repeat the check.
  5. Continue this process for every single item until you reach the very end of the collection.
  6. Once you have checked everything, look back at all the mental notes you made.
  7. Identify the very first spot you recorded a match as your starting point, and the very last spot you recorded a match as your ending point.
  8. If you never found a match during your search, note that the target is completely missing.

Code Implementation

def search_range(sorted_numbers, target_value):
    # We record every index where the target appears so we can easily find the bounds later
    matched_indices = []

    for current_index in range(len(sorted_numbers)):
        if sorted_numbers[current_index] == target_value:
            matched_indices.append(current_index)

    # If the collection of matches is empty, the target was never present in the input array
    if len(matched_indices) == 0:
        return [-1, -1]

    first_position = matched_indices[0]
    last_position = matched_indices[-1]

    return [first_position, last_position]

Big(O) Analysis

Time Complexity
O(n) – To find the first and last position of the target using the described approach, a single loop iterates through all n elements in the collection from beginning to end. During this traversal, every single item is checked individually to see if it matches the target. This linear scan requires visiting each of the n items exactly once without any nested loops or repeated passes. Consequently, the total operations scale directly with the input size n, which simplifies to O(n).
Space Complexity
O(1) – The algorithm only uses a few primitive variables, such as loop counters and index trackers, to record the matching spots and scan the collection. These variables occupy a constant amount of memory regardless of the input size N. Since no auxiliary data structures like temporary lists or hash maps are created, the extra memory usage remains completely fixed. Therefore, the auxiliary space complexity simplifies to O(1) constant space.

Optimal Solution

Approach

Instead of scanning the entire collection sequentially, the optimal strategy takes advantage of the fact that the items are already arranged in order. It uses a clever guessing game to rapidly narrow down the search area from both directions independently.

Here's how the algorithm would work step-by-step:

  1. Begin by looking at the exact middle of the collection to see where your target value sits relative to that midpoint.
  2. If you are hunting for the very first appearance of the target, pretend that finding the target just means you need to keep searching further to the left to see if an identical twin appears earlier.
  3. If you are hunting for the very last appearance of the target, pretend that finding the target means you should keep searching further to the right to see if an identical twin appears later.
  4. Continuously repeat this shrinking process by halving the remaining search space until you successfully pin down the earliest possible spot.
  5. Reset your search and repeat the exact same halving process independently to pin down the latest possible spot.
  6. Combine your findings from both searches to report the exact starting and ending boundaries where your target lives.

Code Implementation

class Solution:
    def searchRange(self, nums: list[int], target: int) -> list[int]:
        def find_boundary(is_searching_left: bool) -> int:
            low_index = 0
            high_index = len(nums) - 1
            boundary_index = -1
            
            while low_index <= high_index:
                mid_index = (low_index + high_index) // 2
                
                if nums[mid_index] > target:
                    high_index = mid_index - 1
                elif nums[mid_index] < target:
                    low_index = mid_index + 1
                else:
                    boundary_index = mid_index
                    
                    # Keep searching left to find the earliest occurrence of the target.
                    if is_searching_left:
                        high_index = mid_index - 1
                    else:
                        # Keep searching right to find the latest occurrence of the target.
                        low_index = mid_index + 1
                        
            return boundary_index
            
        first_position = find_boundary(True)
        
        # Skip the second search if the target does not exist in the collection.
        if first_position == -1:
            return [-1, -1]
            
        last_position = find_boundary(False)
        return [first_position, last_position]

Big(O) Analysis

Time Complexity
O(log n) – To find both the first and last position of the target, the algorithm performs two independent binary searches over the input array of size n. Each binary search repeatedly halves the remaining search space, taking logarithmic time to pinpoint a boundary. Because we execute this halving process twice, the total operations scale as 2 * log(n). Dropping the constant factor yields a final runtime complexity of O(log n).
Space Complexity
O(1) – The algorithm relies entirely on a few primitive integer variables such as pointers for the left boundary, right boundary, and midpoint, which take up a constant amount of extra memory regardless of the input size. Because it uses binary search by repeatedly halving the search space in place, it does not allocate any dynamic data structures, temporary arrays, or recursive call stacks. Therefore, the auxiliary space complexity remains strictly constant as the input size N increases.

Edge Cases

Empty or null input array
How to Handle:
Check for null or empty array at the start and return [-1, -1] immediately to prevent null pointer exceptions or out of bounds errors.
Array with a single element matching the target
How to Handle:
Both the left and right binary search pointers will converge on index 0, correctly returning [0, 0].
Array with a single element not matching the target
How to Handle:
The binary search will fail to find the target and return [-1, -1] as required.
Target is not present in the array
How to Handle:
The modified binary search condition will fail to locate the target boundary and return [-1, -1].
All elements in the array are identical and equal to the target
How to Handle:
The left binary search will find index 0 and the right binary search will find the final array index, returning [0, n - 1].
Target is smaller than all elements or larger than all elements
How to Handle:
The binary search bounds will naturally exhaust outside the valid array indices and return [-1, -1].
Array contains negative numbers and zeros alongside positives
How to Handle:
Standard integer comparison used in binary search correctly handles negative ranges and zero without any special transformations.
Maximum possible array size leading to integer overflow during mid calculation
How to Handle:
Calculate the midpoint using low + (high - low) / 2 instead of (low + high) / 2 to prevent integer overflow.
0/75 completed