1475. Real Cube Root

Easy1.5 points estimatedBinary SearchMaths

A materials lab knows the volume of a cubic sample as the real number x (it can be negative in the lab's signed convention) and wants the edge length that produces it. Return the real number r such that r * r * r == x.

Library routines for cube roots or general powers are not allowed in the intended solution. Since r^3 increases with r, bisect on the interval from -max(1, |x|) to max(1, |x|): keep the half that still brackets the root until the interval is tiny.

Any value within 1e-6 of the true root, measured as absolute or relative error, is accepted. Aim for O(log(|x| / eps)) time and O(1) extra space.

Example 1

Input:
x = 27
Output:
3
Explanation:

The cube of 3 is 27, so the answer is 3.

Example 2

Input:
x = -8
Output:
-2
Explanation:

The cube of -2 is -8, so the answer is -2.

Example 3

Input:
x = 2
Output:
1.259921049894873
Explanation:

The root of 2 is about 1.259921, found by repeatedly halving the bracket.

Constraints

-109 ≤ x ≤ 109

answers are checked to 1e-6 absolute or relative error

How this problem is judged

Answers
Numbers are accepted within a tolerance of 1.0E-6: |answer - expected| <= 1.0E-6 x max(1, |expected|).
Tolerance
0.000001
Time per case
Python 4,000 msC++ 1,000 msJava 2,000 msJavaScript 2,000 msTypeScript 2,000 ms

Expected complexity

Time
O(log(|x| / eps))
Space
O(1)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…