DSA interview question
A game engine running on a microcontroller needs distances between objects, which means square roots, but the chip has no floating-point unit, and converting to double and back can also be off by one for large values. The task: compute ⌊√x⌋, the largest integer whose square doesn't exceed x, using only integer arithmetic. It's the classic first example of binary search on the answer: the answer lies in [0, x], and "does m² fit under x?" is true for small m and false for large m.
Example: x = 8 → 2 (since 2² = 4 ≤ 8 < 9 = 3²).
int mySqrt(int x); // floor(sqrt(x)) for x >= 0, integer arithmetic only
Input x | Output | Explanation |
|---|---|---|
| 4 | 2 | Perfect square |
| 8 | 2 | 2.828... rounded down |
| 0 | 0 | |
| 1 | 1 | |
| 15 | 3 | |
| 16 | 4 | |
| 2147395599 | 46339 | 46340² = 2147395600 is just too big |
| 2147483647 | 46340 | INT_MAX: 46340² fits, 46341² doesn't |
(Confirm: x ≥ 0; no floating-point functions; the result is truncated towards zero.)
sqrt from <cmath>? (Usually not.)(int)sqrt(x)?"On Practick another engineer interviews you live for 60 minutes on a question from this bank. They have the full interviewer guide beside the call: the expected answer to every follow-up, hints to give if you stall, and a scoring rubric. You get the model solution once the session settles. It is free: interview someone for an hour and you have earned your own.
Book a free mock interviewAll 474 dsa interview questions
DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in