15% off all plans & roadmaps Use code
See plansLeetCode 69 · Solution & editorial
Given a non-negative integer x, return the square root of x rounded down to the nearest integer. The returned integer should be non-negative as well.
Sqrt(x) is a Binary Search Patterns problem, in the On Sorted Array/List subpattern. The pattern covers standard binary search, rotated arrays, first/last occurrence, and search on answer space
Master standard binary search on sorted arrays. Learn search insert position, sqrt calculation, and 2D matrix search.
The reference solution runs in O(logn) time and O(1) space.
Sqrt(x) has been reported in interviews at Microsoft, Bloomberg, Amazon, Uber, LinkedIn, Google.
The full editorial is part of Pro
It explains the core insight, the complexity analysis and the common mistakes, with a worked solution.
Sqrt(x) is a Binary Search Patterns problem, in the On Sorted Array/List subpattern. Once the approach above makes sense, write it yourself and then work through the neighbouring problems that reuse it.