PPractick

DSA interview question

While Loops: Collatz Steps and Digit Count

Easy · Algorithms · Topics: language basics

The problem

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.

Function signature

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

Test cases

InputOutputExplanation
collatzSteps(1)0Already at 1; the loop body never runs
collatzSteps(2)12 → 1
collatzSteps(6)86 → 3 → 10 → 5 → 16 → 8 → 4 → 2 → 1
collatzSteps(7)16Climbs as high as 52 before falling
collatzSteps(27)111Peaks at 9232, famous for how long it takes
collatzSteps(0)-1Invalid; 0 would loop forever
countDigits(0)1do-while runs once even when n is 0
countDigits(12345)5
countDigits(-4096)4The 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.)

How interviewers phrase it

Clarifying questions to ask

  1. What should happen for 0 or negative input? (Collatz on 0 never reaches 1.)
  2. How large can N be? (3N + 1 can overflow an int.)
  3. For digit counting, does the minus sign count, and how many digits does 0 have?
  4. Should I return the count, or also the sequence itself?

Follow-ups to expect

  1. "When do you pick while over for?"
  2. "What's the difference between while and do-while?"
  3. "How do you make sure a while loop terminates?"
  4. "Why long long for Collatz?"
  5. "Can you count digits without a loop?"

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