How do you search for a target in a sorted array efficiently?

Coding
Easy
Goldman Sachs
87.7K views

Candidates are asked to write a function to find an element in a sorted array with specific constraints on time complexity. This is a standard test for binary search implementation skills.

Why Interviewers Ask This

This question assesses whether a candidate knows the most efficient algorithm for searching sorted data. Binary search is fundamental in computer science, reducing search time from linear to logarithmic. Interviewers want to verify that the candidate understands the prerequisites (sorted input) and can implement the divide-and-conquer strategy correctly. It also checks attention to detail regarding off-by-one errors and boundary conditions which are common pitfalls in binary search implementations.

How to Answer This Question

State immediately that binary search is the optimal approach due to the sorted nature of the array. Define the left and right boundaries and calculate the middle index. Explain the comparison logic: if the target is smaller, move the right boundary; if larger, move the left. Emphasize the O(log n) time complexity. Walk through a dry run with a small example array to demonstrate the halving process. Ensure the code handles cases where the target is not found by returning -1.

Key Points to Cover

  • Identify binary search as the correct algorithm
  • Define clear loop termination conditions
  • Handle edge cases like empty arrays
  • Achieve logarithmic time complexity

Sample Answer

Since the array is sorted, I will use binary search to achieve O(log n) time complexity. I initialize two pointers, left at 0 and right at the end of the array. In each iteration, I calculate the mid-point and compare th…

Common Mistakes to Avoid

  • Using linear search instead of binary search
  • Integer overflow when calculating the mid-index
  • Infinite loops caused by incorrect boundary updates

Sound confident on this question in 5 minutes

Answer once and get a 30-second AI critique of your structure, content, and delivery. First attempt is free — no signup needed.

Try it free

Related Interview Questions

Browse all 58 Coding questionsBrowse all 28 Goldman Sachs questions