Given a 2D matrix of integers (represented as a List of Lists), return all elements in spiral order. Start from the top-left corner, move right, then down, then left, then up, and repeat this pattern moving inward until all elements are traversed.
Examples:
Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output: [1,2,3,6,9,8,7,4,5]
Explanation: Traverse right (1,2,3), down (6,9), left (8,7), up (4), then center (5)
Input: matrix = [[1,2],[3,4]]
Output: [1,2,4,3]
Explanation: Traverse right (1,2), down (4), left (3)
Input: matrix = [[1,2,3,4]]
Output: [1,2,3,4]
Explanation: Single row returns all elements in order
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.