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!
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 July 2026
Contest runs July 1 - 31. Complete challenges to climb the leaderboard!
Only the 31 daily challenges shown during this contest count toward points. Earlier dailies don't carry over.