Sqrt(x) - Problem

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.

Important: You must not use any built-in exponent function or operator. For example, do not use pow(x, 0.5) in C++ or x ** 0.5 in Python.

Input & Output

Example 1 — Perfect Square
$ Input: x = 4
Output: 2
💡 Note: The square root of 4 is exactly 2, so we return 2
Example 2 — Non-Perfect Square
$ Input: x = 8
Output: 2
💡 Note: √8 = 2.828..., rounded down to nearest integer is 2
Example 3 — Edge Case Zero
$ Input: x = 0
Output: 0
💡 Note: The square root of 0 is 0

Constraints

  • 0 ≤ x ≤ 231 - 1
  • Must not use built-in exponent functions

Visualization

Tap to expand
Sqrt(x) - Binary Search Approach INPUT x = 4 Non-negative integer Search Space 0 1 2 3 4 Range: [0, 4] Find largest n where n * n <= x Input: x = 4 ALGORITHM STEPS 1 Initialize Pointers left=0, right=4, ans=0 2 Calculate Mid mid = (0+4)/2 = 2 3 Compare mid*mid 2*2=4 <= 4? Yes! 4 Update Answer ans=2, search right Binary Search Table L R M M*M Ans 0 4 2 4 2 3 4 3 9 2 3 2 - STOP 2 FINAL RESULT Square Root of 4 2 Verification 2 * 2 = 4 [OK] Output 2 Time: O(log x) Space: O(1) CORRECT Key Insight: Binary search works because if mid*mid > x, then all values greater than mid are too large. We track the last valid answer where mid*mid <= x, giving us the floor of the square root. This approach avoids using built-in exponent operators and achieves O(log x) time complexity. TutorialsPoint - Sqrt(x) | Binary Search Approach
Asked in
Google 15 Amazon 12 Facebook 8 Apple 6
892.2K Views
Medium Frequency
~15 min Avg. Time
3.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen