EASY Binary Search
69. 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. 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.
๐ง Visual Learning Aid
1 Model the input into the right structure
2 Choose the core technique and invariant
3 Execute step-by-step with a sample
4 Validate complexity and edge cases
JS/TS Refreshers
- โขArray methods (`push`, `pop`, `shift`, `slice`)
- โขObject/Map/Set usage patterns
- โขFunction parameter and return typing
- โขMidpoint overflow-safe math
- โขLoop invariants
- โขMonotonic condition design
Logical Thinking Concepts
- โขDefine invariants before coding
- โขCheck edge cases first (`[]`, single element, duplicates)
- โขEstimate time/space before implementation
- โขApply Binary Search reasoning pattern
๐ก Approach
- โ Use binary search between 1 and x
- โ Square mid and compare with x
- โ If mid*mid > x, search left half
- โ If mid*mid < x, search right half
- โ Time: O(log x), Space: O(1)
๐ ๏ธ Hints & Pitfalls
Hints
- โขUse binary search between 1 and x
- โขSquare mid and compare with x
- โขIf mid*mid > x, search left half
Common Pitfalls
- โขIf mid*mid < x, search right half
- โขTime: O(log x), Space: O(1)
๐งช Test Cases
Hidden tests on submit: 4
Test Case 1
Not run Input:
mySqrt(4); Expected:
2 Test Case 2
Not run Input:
mySqrt(8); Expected:
2 Test Case 3
Not run Input:
mySqrt(0); Expected:
0 ๐ Code Editor
๐ค Output