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!
Create an Account
Sign up to track your progress, earn points, and compete with others. Your solutions will be saved automatically.
Create accountHow 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 Mar 2026
Contest runs March 3 - 31. Complete challenges to climb the leaderboard!
Points are calculated for challenges completed during the contest period.