DSA interview question
A tiny microcontroller has no hardware divider, but the firmware must compute integer quotients for sensor scaling, truncated toward zero, like C++ division. Repeated subtraction is far too slow when the dividend is 2 billion and the divisor is 1. Long division in binary is fast: subtract the largest shifted copy of the divisor (divisor · 2^k) that still fits, add 2^k to the quotient, and repeat for smaller k, which is 32 steps at most. The one overflow case, INT_MIN / −1, must be clamped to INT_MAX.
Example: 10 / 3 → 3; 7 / −3 → −2.
int divide(int dividend, int divisor); // divisor != 0; result clamped to [INT_MIN, INT_MAX]
Input (dividend, divisor) | Output | Explanation |
|---|---|---|
(10, 3) | 3 | 3.33 truncated |
(7, -3) | -2 | −2.33 truncates toward zero |
(-2147483648, -1) | 2147483647 | 2³¹ doesn't fit, so it's clamped |
(-2147483648, 1) | -2147483648 | |
(0, 5) | 0 | |
(1, 1) | 1 |
(Confirm: no multiplication, division or modulo; shifts, addition and subtraction are fine; truncate toward zero.)
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