Skip to content

Instantly share code, notes, and snippets.

@KeshariPiyush24
Last active September 21, 2024 05:28
Show Gist options
  • Save KeshariPiyush24/19bda13ec38ae4a7b91c4607b212162b to your computer and use it in GitHub Desktop.
Save KeshariPiyush24/19bda13ec38ae4a7b91c4607b212162b to your computer and use it in GitHub Desktop.
Sqrt(x)

Question: 69. Sqrt(x)

Intution:

Time Complexity: $$O(log(n))$$

Space Complexity: $$O(1)$$

Solution:

class Solution {
    public int mySqrt(int x) {
        long low = 1;
        long high = x;
        long mid = -1;
        while (low <= high) {
            mid = low + (high - low) / 2;
            if (mid * mid == x) return (int) mid;
            else if (mid * mid < x) low = mid + 1;
            else high = mid - 1;
        }
        return (int) high;
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment