Collatz Sequence - Problem

The Collatz sequence (also known as the 3n+1 problem) is a mathematical sequence defined by the following rules:

Starting with any positive integer n:

  • If n is even, divide it by 2
  • If n is odd, multiply by 3 and add 1
  • Repeat until you reach 1

Given a positive integer, generate and return the complete Collatz sequence as an array of integers, including the starting number and ending with 1.

Input & Output

Example 1 — Starting with 13
$ Input: n = 13
Output: [13, 40, 20, 10, 5, 16, 8, 4, 2, 1]
💡 Note: 13 is odd → 3×13+1=40, 40 is even → 40÷2=20, 20→10→5 (odd)→16→8→4→2→1
Example 2 — Starting with 6
$ Input: n = 6
Output: [6, 3, 10, 5, 16, 8, 4, 2, 1]
💡 Note: 6→3 (odd)→10→5→16→8→4→2→1, taking 9 steps total
Example 3 — Edge Case with 1
$ Input: n = 1
Output: [1]
💡 Note: Starting with 1 immediately satisfies the stopping condition

Constraints

  • 1 ≤ n ≤ 106
  • The sequence will always eventually reach 1 (Collatz conjecture)

Visualization

Tap to expand
INPUTALGORITHMRESULT13Starting NumberPositive Integer1Check if n = 12If even: n = n ÷ 2If odd: n = 3n + 13Add n to sequenceContinue until n = 14Return sequenceComplete arrayCollatz Sequence:[13, 40, 20, 10, 5,16, 8, 4, 2, 1]Length: 10Steps: 913→40→20→10→5→16→8→4→2→1Key Insight:The Collatz sequence requires following each mathematical rule step-by-step - there are no shortcutssince each number depends on the previous calculation, making iteration the optimal approach.TutorialsPoint - Collatz Sequence | Iterative Simulation
Asked in
Google 15 Microsoft 12 Amazon 8
25.0K Views
Medium Frequency
~15 min Avg. Time
850 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen