Generate the Collatz sequence starting from a given positive integer. The sequence follows these rules: if the current number is even, divide it by 2; if it is odd, multiply it by 3 and add 1. The sequence ends when it reaches 1 (include 1 in the result). Return null for null input and an empty list for values less than 1.

Examples:

Input: n = 6 Output: [6, 3, 10, 5, 16, 8, 4, 2, 1] Explanation: 6 is even so 6/2=3, 3 is odd so 3*3+1=10, 10/2=5, 5*3+1=16, 16/2=8, 8/2=4, 4/2=2, 2/2=1 Input: n = 1 Output: [1] Explanation: The sequence starts and ends at 1 Input: n = 8 Output: [8, 4, 2, 1] Explanation: 8 is even so 8/2=4, 4/2=2, 2/2=1 Input: n = null Output: null Explanation: Null input returns null Input: n = 0 Output: [] Explanation: Values less than 1 return an empty list
Apex Code Editor

Welcome to Lightning Challenge!

How It Works

  • • Write your solution in the code editor
  • • Connect your Salesforce org to test
  • • Submit to check if your solution passes
  • • Use hints if you get stuck

Contest Alert

🏆 #CodeEveryDay September 2026 (Sep 16–30)Sponsored by FLXBL

Contest runs September 16 - 30. Complete challenges to climb the leaderboard!

Prizes 1 & 2: Salesforce certification exam voucher — won by random drawing, where every point is a ticket. see all prizes

Only the 15 daily challenges shown during this contest count toward points. Earlier dailies don't carry over.

Wally can't hear you

Please sign in to access the AI Assistant

Sign In