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

๐Ÿ“š Reference Solution

โ–ผ
โŒ˜K Search โŒ˜โ†ฉ Run โŒ˜S Submit