↓Skip to main content
  1. LeetCode/

LeetCode 69: Sqrt(x)

·1 min· ·
LeetCode Easy Math Binary-Search Newtons-Method
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2022-05-12

  • Submissions: Wrong Answer → Accepted → Wrong Answer → Accepted

Approach
#

Find the largest k with k² <= x (Binary Search Template 4). Binary search the closed [0, x]: if mid² <= x look right for larger, otherwise left. When the loop ends r sits on the last valid value.

My Attempts
#

In May 2022 attempt 1 used /, making mid a float: x = 5 returned 1.5; switching to // passed. An August rewrite came out one too high: x = 5 returned 3.

Solution
#

class Solution:
    def mySqrt(self, x: int) -> int:
        l, r = 0, x
        while l <= r:
            mid = (l + r) // 2
            if mid * mid <= x:
                l = mid + 1
            else:
                r = mid - 1
        return r

Complexity
#

Time O(log x), space O(1).

Mistakes to Avoid
#

  • Use integer division for mid.
  • The answer rounds down: return the last value with mid² <= x.

Interview Explanation
#

I binary search 0 to x, going right while the square fits and left otherwise; the right bound at the end is the largest integer whose square fits. Time O(log x).

Related

LeetCode 35: Search Insert Position
·2 mins
LeetCode Easy Array Binary-Search
LeetCode 35 note: find the first position >= target (lower bound); a half-open [l, r) needs r = mid, not r = mid - 1
LeetCode 66: Plus One
·2 mins
LeetCode Easy Array Math
LeetCode 66 note: add one from the last digit, turning 9s into 0s while carrying, and prepend 1 when every digit was 9
LeetCode 67: Add Binary
·2 mins
LeetCode Easy Math String Bit-Manipulation Simulation
LeetCode 67 note: add from the ends of both strings digit by digit, with carry sum // 2 and digit sum % 2
LeetCode 9: Palindrome Number
·2 mins
LeetCode Easy Math
LeetCode 9 note: negatives are never palindromes; without strings, reverse the second half of the digits and compare it with the first half
LeetCode 13: Roman to Integer
·1 min
LeetCode Easy Hash-Table Math String
LeetCode 13 note: add each symbol’s value left to right, subtracting instead when it is smaller than the symbol to its right
LeetCode 27: Remove Element
·1 min
LeetCode Easy Array Two-Pointers
LeetCode 27 note: the write pointer copies only values not equal to val, returning how many were written