Compute square root to 1 decimal
Company: Uber
Role: Data Scientist
Category: Coding & Algorithms
Difficulty: Medium
Interview Round: Technical Screen
Quick Answer: This question evaluates a candidate's understanding of numerical methods, floating-point precision, and implementation of approximate functions when producing a square root rounded to one decimal place.
Constraints
- 0 <= x <= 1e9
- x may be a non-integer real number
- Do not call any built-in square-root function
- Result must be accurate to 1 decimal place (error < 0.05)
Examples
Input: (2,)
Expected Output: 1.4
Explanation: sqrt(2) = 1.41421..., rounds to 1.4
Input: (9,)
Expected Output: 3.0
Explanation: Perfect square: sqrt(9) = 3.0
Input: (0,)
Expected Output: 0.0
Explanation: Edge case: sqrt(0) = 0.0
Input: (1,)
Expected Output: 1.0
Explanation: sqrt(1) = 1.0
Input: (16,)
Expected Output: 4.0
Explanation: Perfect square: sqrt(16) = 4.0
Input: (0.25,)
Expected Output: 0.5
Explanation: Non-integer < 1: sqrt(0.25) = 0.5 (root exceeds the input)
Input: (100,)
Expected Output: 10.0
Explanation: sqrt(100) = 10.0
Input: (2.25,)
Expected Output: 1.5
Explanation: Non-integer input: sqrt(2.25) = 1.5
Input: (1000000,)
Expected Output: 1000.0
Explanation: Large input: sqrt(1000000) = 1000.0
Input: (10,)
Expected Output: 3.2
Explanation: sqrt(10) = 3.16227..., rounds to 3.2
Hints
- The root of x lies in [0, max(1, x)] — note that for 0 < x < 1 the root is GREATER than x, which is why the upper bound is max(1, x), not x.
- Binary search: pick mid; if mid*mid < x the root is higher, else it is lower. Each iteration halves the error, so a fixed iteration count (e.g. 100-200) guarantees far better than 1-decimal precision.
- Newton's method converges faster: start with a guess g and repeat g = (g + x/g) / 2 until it stops changing.
- Only round to 1 decimal AFTER converging to full precision — rounding early loses accuracy. Use round(root, 1).