KatInterview

Square Root by Newton's Method and Odd/Even Index Partitioning

Math & Bit ManipulationModel answer
MediumModel answerMath & Bit Manipulationnewton-methodquickselectin-place-partition

Last 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 y such that the relative error against the true root is tiny (target roughly 1e-12, i.e. near full double precision). State explicitly what precision guarantee you are promising and why an absolute bound like 1e-6 on |y*y - x| cannot hold for every input.
  • Say what happens for x = 0, negative x, inf and NaN.
  • 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.