Search for a Range (First and Last Position)

Algorithms
Medium
Spotify
23K views

Given a sorted array of integers `nums` and a target value, find the starting and ending position of the target. Your algorithm's runtime complexity should be $O(\log n)$. Use two Binary Searches.

Why Interviewers Ask This

Spotify evaluates candidates on algorithmic precision and edge-case handling. This question tests if you can optimize a linear scan to logarithmic time using binary search variants. It specifically assesses your ability to maintain sorted array invariants while finding boundary conditions, a skill critical for their large-scale data processing pipelines.

How to Answer This Question

1. Clarify constraints: Confirm the array is sorted and handle empty inputs immediately. 2. Define strategy: State clearly that you will use two separate binary searches—one to find the first occurrence and another for the last. 3. Implement lower bound logic: Write code that moves the right pointer when the target is found or greater, ensuring you capture the leftmost index. 4. Implement upper bound logic: Create a mirrored function that moves the left pointer when the target is found or smaller to locate the rightmost index. 5. Validate edge cases: Explicitly check if the target exists before returning ranges to avoid returning incorrect indices like -1 for both. 6. Analyze complexity: Conclude by explaining why this approach meets the O(log n) requirement compared to a naive O(n) scan.

Key Points to Cover

  • Explicitly state the O(log n) constraint and how two binary searches satisfy it
  • Demonstrate clear separation between finding the lower and upper bounds
  • Handle the case where the target does not exist in the array correctly
  • Explain the specific pointer movement logic (left vs right) for each search variant
  • Reference Spotify's focus on efficiency when dealing with large sorted datasets

Sample Answer

To solve the Search for a Range problem efficiently within Spotify's performance standards, I would avoid a simple linear scan which takes O(n). Instead, I will leverage the sorted nature of the input to perform two distinct binary searches, achieving the required O(log n) runtime. First, I need to find the starting position. I'll implement a helper function that searches for the target but, upon finding it, continues searching the left half to ensure we capture the very first instance. If the target isn't present, this returns -1. Second, I will run a similar binary search to find the ending position. Here, when the target is found, I continue searching the right half to find the last occurrence. Finally, I will combine these results. If the initial search returns -1, I return an empty range immediately. Otherwise, I return the pair of indices. For example, given nums = [5,7,7,8,8,10] and target = 8, the first search finds index 3, and the second finds index 4, resulting in [3, 4]. This method handles duplicates gracefully and ensures optimal performance even with massive datasets common in music streaming infrastructure.

Common Mistakes to Avoid

  • Using a single binary search and assuming it finds all occurrences, leading to O(n) worst-case scenarios
  • Failing to check if the target actually exists before calculating the range boundaries
  • Incorrectly updating pointers during the binary search, causing infinite loops or missing the boundary
  • Ignoring edge cases such as arrays with only one element or targets outside the array range

Practice This Question with AI

Answer this question orally or via text and get instant AI-powered feedback on your response quality, structure, and delivery.

Start Practicing

Related Interview Questions

Browse all 145 Algorithms questionsBrowse all 30 Spotify questions