Tensorum
YouTubeகற்கத் தொடங்குங்கள்
LeetCode 69 · Basics / Lower & Upper Bound

Sqrt(x)

LeetCode 69 · எளிது · தீர்வு, intuition & படிப்படியான வாக்த்ரூ

Binary search for the last m with m² ≤ x.

எளிதுMathBinary SearchNewton's Method
LeetCode இல் திற ↗

நான் Sqrt(x) (LeetCode 69) ஐ இப்படித் தீர்த்தேன் — Basics / Lower & Upper Bound பேட்டர்னின் ஒரு எளிது பிராப்ளம். கீழே: intuition, படிப்படியான approach, என் accepted Python கோட், animated test cases மற்றும் line-by-line debugger.

கீழேயுள்ள விளக்கம் ஆங்கிலத்தில் உள்ளது.

Intuition

The integer square root is the largest m with m² ≤ x. Squares grow monotonically, so binary search over m: too big → search lower, too small → search higher. When the loop ends, high is the answer.

Approach

  1. 1

    Linear scan works but is O(√x).

  2. 2

    Binary search on [1, x].

  3. 3

    mid² == x → return mid; > x → high = mid − 1; else low = mid + 1.

  4. 4

    Return high.

நான் எப்படித் தீர்த்தேன் · முதல் யோசனையிலிருந்து இறுதித் தீர்வு வரை

1
Linear scanO(√x) time

Try every i.

2
Binary searchAcceptedO(log x) time · O(1) space

Floor of the square root.

Linear scanPythonO(√x) time
#TC- O(sqrt of N)
class Solution:
    def mySqrt(self, x: int) -> int:
        for i in range(x+1):
            if i*i==x:
                return i
            elif (i*i)>x:
                return i-1
Binary searchPythonO(log x) time · O(1) space
class Solution:
    def getAnsRange(self,ans, x):
        ans = ans*ans
        if ans==x:
            return 1
        elif ans>x:
            return 2
        else:
            return 0
    def mySqrt(self, x: int) -> int:
        if x<2:
            return x
        low = 1
        high = x
        while low<=high:
            mid = (low+high)//2
            range = self.getAnsRange(mid,x)
            if range==1:
                return mid
            elif range==2:
                high=mid-1
            else:
                low = mid+1
        return high
ஸ்டெப்-த்ரூ ஏற்றுகிறது…

Sqrt(x) — அடிக்கடி கேட்கப்படும் கேள்விகள்

Sqrt(x) பின்னாலுள்ள intuition என்ன?

The integer square root is the largest m with m² ≤ x. Squares grow monotonically, so binary search over m: too big → search lower, too small → search higher. When the loop ends, high is the answer.

Sqrt(x) (LeetCode 69) ஐ எப்படித் தீர்ப்பது?

1. Linear scan works but is O(√x). 2. Binary search on [1, x]. 3. mid² == x → return mid; > x → high = mid − 1; else low = mid + 1. 4. Return high.

Sqrt(x) இன் time மற்றும் space complexity என்ன?

Time: O(log x). Space: O(1). (Accepted approach: Binary search.)

Sqrt(x) இல் பொதுவான தவறுகள் என்ன?

x < 2 returns x directly.

Sqrt(x) ஐத் தீர்க்க ஒன்றுக்கு மேற்பட்ட வழிகள் உள்ளனவா?

Linear scan (O(√x) time): Try every i. Binary search (O(log x) time · O(1) space): Floor of the square root.