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.