PPractick

DSA interview question

Integer Square Root

Medium · Algorithms · Topics: binary search, math

The problem

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²).

Function signature

int mySqrt(int x);  // floor(sqrt(x)) for x >= 0, integer arithmetic only

Test cases

Input xOutputExplanation
42Perfect square
822.828... rounded down
00
11
153
164
21473955994633946340² = 2147395600 is just too big
214748364746340INT_MAX: 46340² fits, 46341² doesn't

(Confirm: x ≥ 0; no floating-point functions; the result is truncated towards zero.)

How interviewers phrase it

Clarifying questions to ask

  1. Should the result be rounded down?
  2. Can I use sqrt from <cmath>? (Usually not.)
  3. What's the range of x? (m × m can overflow 32 bits.)

Follow-ups to expect

  1. "What's the monotonic predicate?"
  2. "How do you avoid overflow?"
  3. "Why not just (int)sqrt(x)?"
  4. "What about Newton's method?"
  5. "Complexity?"

Practise questions like this with a real engineer

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 interview

Related questions

All 474 dsa interview questions

DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in