Leetcode – Sqrt(x) in Python

Spread the love

In this article, we’ll take a deep dive into solving one such problem, ‘Sqrt(x)’, using Python.

Problem Statement

The ‘Sqrt(x)’ problem (LeetCode problem #69) is described as follows:

Compute and return the square root of x, where x is guaranteed to be a non-negative integer. Since the return type is an integer, the decimal digits are truncated, and only the integer part of the result is returned.

Here are a couple of examples for better understanding:

  • Input: 4 Output: 2
  • Input: 8 Output: 2 (The square root of 8 is 2.82842…, and since the decimal part is truncated, 2 is returned.)

Understanding the Problem

The problem asks for the square root of a given non-negative number x. However, rather than returning the exact square root, we only need to return the integer part. For instance, if the square root of the number is 3.605, we will return 3.

Approach to Solve the Problem

Python provides a built-in function, math.sqrt(), which can easily calculate the square root of a number. However, this function gives a floating-point number, and we need to truncate the decimal part and return only the integer. Let’s see how we can approach this:

Step 1: Import Necessary Libraries

First, we need to import the math library.

import math

Step 2: Create a Function

We will define a function, mySqrt(), that takes an integer x as its parameter:

def mySqrt(x):

Step 3: Calculate the Square Root and Truncate Decimal Part

The math.sqrt() function will give the square root of x, and we can use the int() function to remove the decimal part:

def mySqrt(x):
    return int(math.sqrt(x))

The int() function truncates the decimal part of a floating-point number and returns the integer part.

And that’s it! This function will now return the integer part of the square root of any non-negative integer x.

Testing the Solution

Let’s test our function with the sample inputs:

print(mySqrt(4)) # Output: 2
print(mySqrt(8)) # Output: 2

The function works as expected and correctly returns the integer part of the square roots.


The ‘Sqrt(x)’ problem from LeetCode is a relatively simple problem that can be solved easily using Python’s built-in functions. While this problem may seem straightforward, it’s a great way to familiarize yourself with using Python’s built-in libraries and functions, which are powerful tools that can significantly simplify the problem-solving process. It’s always essential to understand the underlying math and logic of the problem, and knowing the appropriate Python functions to use can save you a lot of time and effort.

Leave a Reply