Sqrt(x) - Problem

You're tasked with implementing your own integer square root function without using any built-in mathematical functions or operators like pow() or **.

Given a non-negative integer x, return the square root of x rounded down to the nearest integer. The returned integer should also be non-negative.

Key Challenge: You must implement this from scratch - no shortcuts allowed! This problem tests your understanding of mathematical algorithms and efficient searching techniques.

Example: For x = 8, the square root is approximately 2.828, so we return 2 (rounded down).

Input & Output

example_1.py — Basic Case
$ Input: x = 4
Output: 2
💡 Note: The square root of 4 is exactly 2, so we return 2.
example_2.py — Non-Perfect Square
$ Input: x = 8
Output: 2
💡 Note: The square root of 8 is approximately 2.828, but we round down to 2.
example_3.py — Edge Cases
$ Input: x = 0
Output: 0
💡 Note: The square root of 0 is 0.

Constraints

  • 0 ≤ x ≤ 231 - 1
  • No built-in functions allowed like pow(), sqrt(), or **
  • Must return integer result

Visualization

Tap to expand
Finding Square Root ≈ Finding Garden Plot SizeAvailable Tiles: 8Try 1×1: Uses 1 tile✓ Can make biggerTry 3×3: Uses 9 tiles✗ Too big (need 9, have 8)Try 2×2: Uses 4 tiles✓ Perfect fit!Binary search narrows down: 1 ≤ answer ≤ 2, so answer = 2
Understanding the Visualization
1
Set the boundaries
You know the side length is between 0 and the total number of tiles
2
Try the middle
Test if a middle side length works by calculating tiles needed (side²)
3
Adjust search area
If too many tiles needed, try smaller; if tiles left over, try larger
4
Converge to answer
Keep halving the search space until you find the perfect fit
Key Takeaway
🎯 Key Insight: Binary search transforms a linear O(√x) problem into a logarithmic O(log x) solution by intelligently narrowing the search space
Asked in
Amazon 45 Google 38 Microsoft 32 Apple 28
52.0K Views
High Frequency
~15 min Avg. Time
1.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