Taro Logo

Sqrt(x)

#107 Most AskedEasy
Topics:
Binary Search

Given a non-negative integer x, return the square root of x rounded down to the nearest integer. The returned integer should be non-negative as well.

You must not use any built-in exponent function or operator.

  • For example, do not use pow(x, 0.5) in c++ or x ** 0.5 in python.

Example 1:

Input: x = 4
Output: 2
Explanation: The square root of 4 is 2, so we return 2.

Example 2:

Input: x = 8
Output: 2
Explanation: The square root of 8 is 2.82842..., and since we round it down to the nearest integer, 2 is returned.

Constraints:

  • 0 <= x <= 231 - 1

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What is the maximum possible value for the input integer $x$?
  2. Are we guaranteed that the input $x$ is always a non-negative integer, or should I handle negative inputs by throwing an exception or returning a specific value?
  3. Should I implement the square root function from scratch (e.g., using Binary Search or Newton's method), or am I allowed to use built-in math libraries or functions?
  4. How should I handle extreme edge cases such as $x = 0$ and $x = 1$?
  5. Since the decimal digits are to be truncated, is rounding down towards zero always the expected behavior for non-perfect squares?

Brute Force Solution

Approach

To find the square root of a number using the brute force approach, you systematically test every whole number starting from zero and going upwards. You stop and have your answer when multiplying a number by itself either matches your target number or just barely exceeds it.

Here's how the algorithm would work step-by-step:

  1. Begin by testing the number zero as the potential square root.
  2. Multiply this number by itself and check if the result matches your target number.
  3. If it matches, you have found your exact answer.
  4. If the result is smaller than your target, move on to the next whole number.
  5. Multiply this new number by itself and check the result again.
  6. Repeat this process of testing the next consecutive whole number one by one.
  7. Keep doing this until you reach a number whose square is greater than your target number.
  8. When that happens, the correct answer is the previous whole number you tested, since we are looking for the whole number part of the square root.

Code Implementation

def my_sqrt(target_number):
    # Handle zero explicitly since zero multiplied by itself is always zero
    if target_number == 0:
        return 0

    current_candidate = 0

    # Test consecutive numbers until the square exceeds the target value
    while current_candidate * current_candidate <= target_number:
        current_candidate += 1

    # Return the previous integer because the current one exceeded the target
    return current_candidate - 1

Big(O) Analysis

Time Complexity
O(√(x)) – The cost is driven by sequentially testing whole numbers starting from zero, incrementing by one in each step until their square exceeds the target input x. In the worst case, we must test up to the square root of x plus one numbers. This sequence of checks requires approximately √(x) iterations. Therefore, the total operations scale with the square root of the input, simplifying to O(√(x)).
Space Complexity
O(1) – The brute force approach to finding the square root only requires a few primitive variables to systematically test whole numbers and keep track of the current iteration. As the input integer x grows, these few scalar tracking variables do not scale in size. No auxiliary data structures, lists, or recursion stack frames are created during the process. Therefore, the extra memory used remains constant regardless of the input size, resulting in a space complexity of O(1).

Optimal Solution

Approach

Instead of testing every single number to find the square root, we can use a guessing game approach that narrows down the possibilities very quickly. By repeatedly splitting our range of possible answers in half, we can zero in on the correct whole number in just a few steps.

Here's how the algorithm would work step-by-step:

  1. Establish a starting range of numbers that definitely contains the square root, going from zero up to the target number itself.
  2. Look at the exact middle number of your current range.
  3. Multiply that middle number by itself to see how it compares to your target number.
  4. If the result is smaller than your target, throw away the lower half of your range because the answer must be larger.
  5. If the result is larger than your target, throw away the upper half of your range because the answer must be smaller.
  6. If the result matches your target, or if your range shrinks down so far that no numbers are left, you have found your answer.
  7. Repeat this halving process until you securely land on the largest whole number whose square does not exceed the target.

Code Implementation

class Solution:
    def mySqrt(self, target_number: int) -> int:
        if target_number < 2:
            return target_number
        
        lower_bound = 0
        upper_bound = target_number
        stored_result = 0
        
        # Halving the search range ensures logarithmic time complexity.
        while lower_bound <= upper_bound:
            middle_number = (lower_bound + upper_bound) // 2
            
            if middle_number * middle_number == target_number:
                return middle_number
            
            # Discarding halves prevents redundant checks and optimizes performance.
            elif middle_number * middle_number < target_number:
                stored_result = middle_number
                lower_bound = middle_number + 1
            
            else:
                upper_bound = middle_number - 1
        
        # Returning the floored value guarantees the integer square root constraint.
        return stored_result

Big(O) Analysis

Time Complexity
O(log n) – The algorithm repeatedly divides the search range in half during each step, starting from an initial range of zero to the input number n. In each iteration, we evaluate the midpoint to determine whether to discard the upper or lower half of the remaining possibilities. This halving process means the number of steps grows logarithmically relative to the size of n. Therefore, the total operations approximate log base 2 of n, which simplifies to O(log n).
Space Complexity
O(1) – To implement this guessing game approach, the algorithm only needs a few primitive variables to keep track of the starting range boundaries, the middle number, and the result. These variables require a fixed amount of memory regardless of how large the input number N is. Since no auxiliary data structures, lists, or recursive calls are utilized, the extra memory usage remains constant. Therefore, the space complexity is O(1).

Edge Cases

Input x is 0
How to Handle:
Binary search or iterative bounds must include 0 to return 0 immediately without division by zero errors.
Input x is 1
How to Handle:
The algorithm must correctly evaluate that the square root of 1 is 1 rather than 0.
Maximum 32-bit signed integer values near 2^31 - 1
How to Handle:
Midpoint calculations using (left + right) / 2 can overflow integers, so we use left + (right - left) / 2.
Squaring the midpoint during binary search like mid * mid
How to Handle:
Multiplying two 32-bit integers can exceed integer limits, requiring the use of 64-bit long data types for the product.
Non-perfect square numbers like 8 or 10
How to Handle:
The binary search naturally converges and truncates downwards by keeping the last valid lower bound where mid * mid <= x.
Negative integer inputs
How to Handle:
The problem description specifies non-negative integers, but robust code should handle this by throwing an exception or returning -1.
0/245 completed