We use cookies for site analytics. Accept to help us understand how the site is used. See our Privacy Policy for details.
An easy binary search problem, graded against 6 test cases (3 of them hidden).
Halving a search space each step - on sorted arrays, and on answers themselves.
Reach for it when you see: A sorted input, or a monotonic "is this value feasible?" predicate you can binary search over.
More Binary Searchproblems →Squaring is monotonic over the positive integers, so the candidate roots form a sorted space even though nothing was handed to you as an array. Binary search `1..num`, compare `mid * mid` to the target, and narrow.
The practical hazard is overflow. With `num` up to 2^31 - 1, `mid` can approach 46341, and `mid * mid` exceeds 32-bit range in languages with fixed-width ints. The standard defences are comparing via division (`mid <= num / mid`) or widening the type. JavaScript's doubles and Python's arbitrary-precision ints avoid it, but this is the detail interviewers ask about, so it is worth naming aloud.
A tighter upper bound helps: no root exceeds `num / 2` for `num > 4`, which trims an iteration or two.
The elegant alternative is worth knowing: every perfect square is a sum of consecutive odd numbers (1, 1+3, 1+3+5, ...), so subtracting successive odds from `num` and checking for exactly zero is an O(sqrt n) solution with no multiplication at all. Newton's method converges even faster. Binary search remains the expected answer because it generalizes.
The full reference solution in every supported language stays in the editor above - reveal it there once you have had a real attempt.
These apply to the pattern as a whole, not just this problem.