DEV Community

Bukunmi Odugbesan
Bukunmi Odugbesan

Posted on

Coding Challenge Practice - Question 111

The task is to implement Math.sqrt().

The boilerplate code

function mySqrt(x) {
  // your code here   
}
Enter fullscreen mode Exit fullscreen mode

Convert whatever is input to a number

const num = Number(x)
Enter fullscreen mode Exit fullscreen mode

If the input is negative or invalid, return NaN

if(isNaN(num)) {
 return NaN
}

if(num < 0) {
return NaN
}
Enter fullscreen mode Exit fullscreen mode

If the input is 0 or 1, the square root is itself

if(num < 2) return num;
Enter fullscreen mode Exit fullscreen mode

Binary search will be used to find the square root between 1 and the input

let left = 1;
let right = Math.floor((left + right) / 2);
let ans = 0
Enter fullscreen mode Exit fullscreen mode

For any number greater than or equal to 2, the square root is less than or equal to half the number. That's why the upper boundary for the search is at half of the number; the square root can't be bigger than that.

To implement binary search, find the middle point of the search range

while(left <= right) {
const mid = Math.floor((left + right) / 2);
const square = mid * mid
Enter fullscreen mode Exit fullscreen mode

If the square is equal to the original value, the middle point is the square root

if (square === num) {
 return mid;
}
Enter fullscreen mode Exit fullscreen mode

If the square is less than the original value, search the right half. Otherwise, search the left half.

else if(square < num) {
    ans = mid;    
    left = mid + 1; 
  } else {
    right = mid - 1;
  }
Enter fullscreen mode Exit fullscreen mode

The final code

function mySqrt(x) {
  // your code here  
  const num = Number(x);

  if(isNaN(num)) {
    return NaN;
  }

  if(num < 0) {
    return NaN;
  }

  if(num < 2) return x;

  let left = 1;
  let right = Math.floor(num / 2);
  let ans = 0;

  while(left <= right) {
    const mid = Math.floor((left + right) / 2);
    const square =  mid * mid;

    if(square === num) {
      return mid;
    } else if(square < num) {
      ans = mid;
      left = mid + 1;
    } else {
      right = mid - 1;
    }
    }
  return ans;
}
Enter fullscreen mode Exit fullscreen mode

That's all folks!

Top comments (0)