How do you implement binary search to find a target in a sorted array?

Coding
Easy
Goldman Sachs
117.6K views

This classic problem checks your grasp of divide-and-conquer strategies on sorted data structures. It verifies your ability to write efficient search algorithms with logarithmic time complexity.

Why Interviewers Ask This

Binary search is a foundational concept for financial trading systems and large datasets. Interviewers ask this to ensure you understand how to reduce search space exponentially. They evaluate your coding precision, especially regarding boundary conditions and index calculations that often lead to off-by-one errors in production code.

How to Answer This Question

Define left and right pointers and calculate the mid-point carefully. Explain why the algorithm requires a sorted array before starting. Walk through the logic of adjusting pointers based on comparison results. Always mention the O(log n) time complexity and discuss potential integer overflow issues when calculating mid.

Key Points to Cover

  • Divide and conquer strategy
  • Logarithmic time complexity O(log n)
  • Handling boundary conditions correctly
  • Requirement for sorted input data

Sample Answer

I initialize left and right pointers to the start and end of the array. In each iteration, I calculate the middle index and compare the value there with the target. If the middle value is less than the target, I move the left pointer to mid + 1; otherwise, I move the right pointer to mid - 1. I repeat this until the target is found or the pointers cross, returning the index or -1 respectively.

Common Mistakes to Avoid

  • Calculating mid as (left + right) / 2 causing overflow
  • Infinite loops due to incorrect pointer updates
  • Ignoring the requirement for sorted arrays

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 39 Coding questionsBrowse all 22 Goldman Sachs questions