Implement Integer Square Root
J.P. MorganData Scientist · Technical ScreenLast updated
This question evaluates numerical algorithm design and integer arithmetic competence, including robustness for edge cases and overflow handling, and is categorized in the Coding & Algorithms domain.
Given a non-negative integer x, implement sqrt(x) and return the integer part of its square root, i.e., floor(sqrt(x)).
Requirements:
- Do not use a built-in square root function or exponent operator.
- Your solution should handle large 32-bit signed integers without overflow.
- Explain the time and space complexity.
Examples:
x = 4returns2.x = 8returns2, becausesqrt(8) = 2.828...and the integer part is2.
Expected approach:
- First solve it using binary search.
- Follow-up: discuss whether there is a more efficient practical method, such as Newton's method, and compare it with binary search.
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.