Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started
Root Function With Edge Cases
00:00
5 left

Root Function With Edge Cases

MediumPython

Problem

Write a function to find the root of a number, ensuring you handle edge cases where x < 1 correctly.

Implement root(x) to return the integer square root, meaning the greatest integer r such that r * r <= x. Return 0 for any x < 1. Use an algorithm that avoids floating-point precision issues.

Input: An integer x.

Output: An integer representing floor(sqrt(x)).

Constraints

  • -10^9 <= x <= 2^31 - 1
  • Return 0 when x < 1
  • For x >= 1, return the greatest integer r such that r * r <= x
  • Do not use floating-point square-root operations

Function Signature

def root(x):
Interviewer

Your question is Root Function With Edge Cases. Start with the requirements in the Question tab.

Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.

You need to log in / sign up to run or submit.
CodePython 3
You need to log in / sign up to run or submit.Ln 2
Run your code to see test output here.