Find square root of a number

Binary Search On answers Medium

Given a positive integer n. Find and return its square root. If n is not a perfect square, then return the floor value of sqrt(n).

Examples:

Input: n = 36

Output: 6

Explanation: 6 is the square root of 36.

Input: n = 28

Output: 5

Explanation: The square root of 28 is approximately 5.292. So, the floor value will be 5.

Input: n=50

Constraints

  •  0 <= n <= 231 - 1

Hints

  • The goal is to calculate the integer square root of n, which is the largest integer x such that x2≤n. This can be efficiently solved using binary search as the square root function is monotonic (increases steadily).
  • "Use binary search to find x between 0 and n. At each step, calculate the middle value (mid) and its square (mid^2): If mid^2 == n, you’ve found the square root. If mid^2 < n, adjust low = mid + 1 to move right. If mid^2 > n, adjust high = mid - 1 to move left."

Company Tags

Salesforce Nutanix Johnson & Johnson Oracle Instacart Riot Games Texas Instruments McKinsey & Company Deloitte Roblox Wayfair Red Hat Splunk IBM Zomato Freshworks Unity Technologies Bain & Company Teladoc Health Airbnb Activision Blizzard Goldman Sachs Square Epic Systems PwC TCS Cognizant Accenture Infosys Capgemini Wipro