logoNEURAL COOK
SearchAll PostsTagsNotesAuthor
logoNEURAL COOK

A posts created with Next.js and Tailwind.css

Explore

  • All posts
  • Notes
  • Snippets
  • Tags
  • RSS feed

Connect

instagramtwitterfacebookyoutubelinkedinmailgithub

© 2026 VIKI. All rights reserved.

Built with
Contents
Table Of Contents
13. Roman to Integer14. Longest Common Prefix20. Valid Parentheses26. Remove Duplicates from Sorted Array35. Search Insert Position69. Sqrt(x)70. Climbing Stairs88. Merge Sorted Array (In-Place)104. Maximum Depth of Binary Tree118. Pascal's Triangle121. Best Time to Buy and Sell Stock205. Isomorphic Strings242. Valid Anagram283. Move Zeroes345. Reverse Vowels of a String605. Can Place Flowers704. Binary Search796. Rotate String1071. Greatest Common Divisor of Strings1299. Replace Elements with Greatest Element on Right Side1431. Kids With the Greatest Number of Candies1614. Maximum Nesting Depth of the Parentheses1752. Check if Array Is Sorted and Rotated1768. Merge Strings Alternately1903. Largest Odd Number in String2965. Find Missing and Repeated Values
Code Scratch/leetcode/easy

69. Sqrt(x)

1 min read
On this pageIntuition
IntuitionComplexityCode

# Intuition

We are asked to compute the square root of a non-negative integer x, rounded down to the nearest integer, without using any built-in functions.
Since the square root function is monotonically increasing, we can use binary search to efficiently find the answer.

# Complexity

Space ComplexityTime Complexity
O(1)\text{O}(1)O(1)O(log⁡N)\text{O}(\log{N})O(logN)

# Code

public int mySqrt(int number) {
    if (number == 0) return 0; // Edge case for 0
 
    int left = 1, right = number;
    int squareRootFloor = 0; // Store the answer (floor of actual square root)
 
    while (left <= right) {
        // Avoid overflow with (right - left) / 2 + left
        int mid = (right - left) / 2 + left;
 
        long square = (long) mid * mid;
 
        if (square == number) {
            return mid; // Perfect square case
        }
 
        if (square < number) {
            squareRootFloor = mid;  // Store the closest value so far
            left = mid + 1;         // Try to find a larger valid sqrt
        } else {
            right = mid - 1;        // Search in the smaller half
        }
    }
 
    return squareRootFloor; // Return floor of sqrt
}
 
←Previous35. Search Insert PositionNext→70. Climbing Stairs

On this page

IntuitionComplexityCode