The Sqrt(x) coding problem is a fundamental algorithm question that asks you to compute and return the square root of a non-negative integer . Since the return type is an integer, the decimal digits are truncated, and you only return the integer part of the result. For example, the square root of 8 is 2.828..., so you should return 2.
This is one of the most frequently asked questions across the entire tech industry (Apple, Microsoft, Uber, etc.). It tests whether you can apply Binary Search to a numerical range instead of just an array. It also assesses your awareness of integer overflow and your ability to optimize from a linear search to a logarithmic search.
The core pattern is Binary Search. Since the square root of must be between 0 and , we can search this range. For any number , if , it could be the answer, so we move our lower bound up. If , the answer must be smaller, so we move our upper bound down. This Binary Search interview pattern allows us to find the answer very quickly even for large values of .
Let's find the square root of .
for loop from 1 to , which is and too slow for large inputs.Binary search is not just for finding elements in a list; it's a powerful tool for searching any sorted space, including numerical ranges. Always check for overflow when multiplying middle values in these types of problems.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Sqrt(x) | Easy | Solve | |
| Valid Perfect Square | Easy | Solve | |
| Arranging Coins | Easy | Solve | |
| Nth Digit | Medium | Solve | |
| Reach a Number | Medium | Solve |