#69

Sqrt(x)

Easy
MathBinary SearchBinary SearchMathematical Properties
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n)
O(log n)
Space
O(1)
O(1)
💡

Intuition

Time O(log n)Space O(1)

Using binary search allows us to efficiently narrow down the possible range of integers whose squares could equal x. This significantly reduces the number of checks needed.

⚙️

Algorithm

6 steps
  1. 1Step 1: Initialize left to 0 and right to x.
  2. 2Step 2: While left is less than or equal to right, calculate mid as (left + right) // 2.
  3. 3Step 3: If mid * mid equals x, return mid.
  4. 4Step 4: If mid * mid is less than x, move left to mid + 1.
  5. 5Step 5: If mid * mid is greater than x, move right to mid - 1.
  6. 6Step 6: Return right as the integer square root of x.
solution.py11 lines
1def mySqrt(x):
2    left, right = 0, x
3    while left <= right:
4        mid = (left + right) // 2
5        if mid * mid == x:
6            return mid
7        elif mid * mid < x:
8            left = mid + 1
9        else:
10            right = mid - 1
11    return right

Complexity note: The time complexity is O(log n) due to the binary search approach, which halves the search space with each iteration. The space complexity is O(1) since we only use a few variables.

  • 1Binary search is a powerful technique for problems involving sorted data or ranges.
  • 2Understanding the properties of squares helps in narrowing down the search space.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.