DSA interview question
A maths club is exploring the Collatz sequence. Start from any positive integer n. If it's even, halve it; if it's odd, replace it with 3n + 1. Repeat until you reach 1. Nobody has proved that every starting number reaches 1, and nobody can predict in advance how many steps it will take, which makes this the perfect use of a while loop, where you loop until a condition changes rather than a fixed number of times. The club also wants a helper that counts the digits of a number, where the number 0 must count as having one digit. That's a natural fit for a do-while loop, which always runs its body at least once.
Example: 6 → 3 → 10 → 5 → 16 → 8 → 4 → 2 → 1 takes 8 steps.
long long collatzSteps(long long n); // steps to reach 1; -1 if n < 1
int countDigits(long long n); // number of decimal digits; countDigits(0) == 1
| Input | Output | Explanation |
|---|---|---|
collatzSteps(1) | 0 | Already at 1; the loop body never runs |
collatzSteps(2) | 1 | 2 → 1 |
collatzSteps(6) | 8 | 6 → 3 → 10 → 5 → 16 → 8 → 4 → 2 → 1 |
collatzSteps(7) | 16 | Climbs as high as 52 before falling |
collatzSteps(27) | 111 | Peaks at 9232, famous for how long it takes |
collatzSteps(0) | -1 | Invalid; 0 would loop forever |
countDigits(0) | 1 | do-while runs once even when n is 0 |
countDigits(12345) | 5 | |
countDigits(-4096) | 4 | The sign is not a digit |
(Confirm: n fits in a long long; intermediate Collatz values (3n + 1) can exceed the int range for large starting values.)
int.)while over for?"while and do-while?"long long for Collatz?"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