Square Root by Newton's Method and Odd/Even Index Partitioning
Math & Bit ManipulationModel answerLast updated
Implement sqrt from scratch with range reduction plus Newton's method, and rearrange an array in O(1) space so even-positioned values all beat odd-positioned ones.
This is a two-part coding screen covering numerical approximation and space-efficient array restructuring.
Part 1 — Compute a square root yourself
Write a function that takes a non-negative floating-point value x and returns an approximation y to its square root, using nothing beyond +, -, *, / and ordinary control flow. Library sqrt, pow, ** and similar are off limits.
- Return
ysuch that the relative error against the true root is tiny (target roughly1e-12, i.e. near full double precision). State explicitly what precision guarantee you are promising and why an absolute bound like1e-6on|y*y - x|cannot hold for every input. - Say what happens for
x = 0, negativex,infandNaN. - Explain how you keep the method fast for very large and very small magnitudes — a naive starting guess degrades badly at the extremes.
Part 2 — Split the array by index parity
Given an integer array, reorder it in place so that, counting positions from 1, every element sitting at an even position is strictly less than every element at an odd position. Any ordering meeting the rule is accepted.
- Example:
[1,2,3,4,5]→[5,1,4,2,3]works, since even positions hold{1,2}and odd positions hold{5,4,3}. - Hard requirement: O(1) auxiliary space — no full sort, no helper array.
- Target O(n log n) or better time.
- Identify when no arrangement exists at all (hint: duplicates) and handle that case explicitly.
For each part, give the approach, prove or argue correctness, and state time/space complexity alongside the code.
Hints
Hint 1
For the root, express x as m * 4^e with m in [0.25, 1). Halving the exponent keeps multiplication exact and puts the seed guess in a narrow band, which kills the slow convergence at the extremes.
Hint 2
For the array, translate 1-based even positions into 0-based odd indices: the requirement becomes 'the k = floor(n/2) smallest values occupy odd indices'. That is a selection problem, not a sorting problem — quickselect with a three-way partition does it in O(n) expected time and O(1) space.
Hint 3
Strictness is the trap: it fails exactly when the k-th and (k+1)-th order statistics are equal. Compare the two after selection and report impossibility rather than emitting a bad array.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Part 1: square root without a library
Approach: range reduction plus Newton's method. Newton's iteration for f(y) = y² − x is
y_{k+1} = (y_k + x / y_k) / 2
which converges quadratically: near the answer the number of correct digits roughly doubles per step. The problem is the starting point. Seeding with y = x is fine for x near 1, but for x = 1e300 you spend hundreds of steps walking down, and for x = 1e-300 the guess sits far below the root and the first step overshoots enormously.
Fix that with range reduction. Write x = m · 4^e where m ∈ [0.25, 1) and e is an integer; then √x = √m · 2^e. Dividing and multiplying by 4 is exact in binary floating point, so this composition introduces no rounding error at all, and after reduction the root lies in [0.5, 1). Seeding y = 1.0 there gives convergence in roughly six iterations regardless of the original magnitude.
Why it works. For y > 0, AM–GM gives (y + m/y)/2 ≥ √m, so after one step every iterate is at or above the root; from then on the sequence decreases monotonically and cannot oscillate. The error obeys e_{k+1} ≈ e_k²/(2y_k), the quadratic law. Stop when the update is small relative to the current estimate, and cap iterations to escape floating-point stalls.
Precision promise — state it honestly. An absolute bound |y² − x| < 1e-6 is unachievable across all doubles: near x = 1e300 consecutive doubles are ~1e284 apart, so no algorithm can do better than a few hundred ULPs. Promise a relative bound instead: y is within ~1e-12 relative of √x, hence |y² − x| ≲ 2e-12 · x, which does imply the 1e-6 absolute bound for x up to about 5e5.
Edge cases. x = 0 returns 0 immediately (otherwise a zero divisor appears). Negative input raises ValueError — or returns NaN; pick one and say so. inf and NaN pass through unchanged. Subnormals are fine because the scale factor stays normal.
Complexity. O(log log x) reduction steps (bounded by ~540 for doubles) plus O(1) Newton steps — effectively constant time, O(1) space.
def my_sqrt(x: float, rel_tol: float = 1e-12) -> float:
if x != x: # NaN
return x
if x < 0:
raise ValueError("square root of negative number")
if x == 0.0 or x == float("inf"):
return x
m, scale = x, 1.0
while m >= 1.0: # shrink into [0.25, 1)
m /= 4.0
scale *= 2.0
while m < 0.25: # grow into [0.25, 1)
m *= 4.0
scale /= 2.0
y = 1.0 # root of m lies in [0.5, 1)
for _ in range(60):
nxt = 0.5 * (y + m / y)
if abs(nxt - y) <= rel_tol * nxt:
y = nxt
break
y = nxt
return y * scale
Binary search on [0, max(1, x)] is a valid fallback but converges linearly (~50–60 halvings for double precision); Newton is the better answer.
Part 2: parity rearrangement
Reframe the constraint. Move to 0-based indices. 1-based even positions become odd indices — there are k = ⌊n/2⌋ of them, and these must hold values strictly smaller than everything on even indices. So the k smallest elements belong on the odd indices; order inside each group is irrelevant.
Existence check. Such an assignment exists iff the k-th smallest value is strictly less than the (k+1)-th smallest. [2, 2] is a counterexample: no arrangement satisfies strictness. Flag this rather than silently returning something invalid.
Algorithm — three steps, no sorting.
- Quickselect (randomized pivot, three-way Dutch-flag partition so duplicates stay cheap) places the k-th order statistic at index k, leaving
arr[:k] <= arr[k] <= arr[k+1:]. Expected O(n), O(1) space, iterative so no recursion stack. - Verify
max(arr[:k]) < arr[k]; if not, report impossibility. - Repair positions with swaps. The prefix [0, k) holds the small set S. Odd indices inside the prefix are already correct; the misplaced ones are the even indices in the prefix, ⌈k/2⌉ of them. Correspondingly, the odd indices in the suffix [k, n) hold large values that are misplaced, also ⌈k/2⌉. Pair them one-by-one and swap. Counts match, so a single pass finishes the job.
Correctness. After step 2 the prefix is exactly the k smallest values, and each is strictly below every value outside. Step 3 is a bijection between wrong small elements and wrong large elements, so after it every odd index holds a member of S and every non-S value sits on an even index. Conversely, if the strict comparison fails, any valid assignment would need k values strictly below the remaining n − k, which forces the order statistics to differ — contradiction.
Trace on [1,2,3,4,5]. k = 2, array already partitioned, check 2 < 3 passes. Misplaced even-in-prefix index is 0; misplaced odd-in-suffix index is 3. Swap → [4,2,3,1,5]. Even positions hold {2,1}, odd hold {4,3,5}. Valid.
Complexity. Expected O(n) time, O(n²) worst case with random pivots; switch to in-place heapsort (O(n log n) guaranteed) or median-of-medians (O(n) guaranteed) if the interviewer wants a hard bound. O(1) extra space — note Python's list.sort() violates this, since Timsort may allocate O(n) scratch.
Edge cases. n ≤ 1 is trivially valid (no even positions). n = 2 with equal values is impossible. Heavy duplicates exercise the three-way partition and the strictness check.