Rearrange a list of integers so that elements alternate between less-than and greater-than their neighbors, creating a zigzag pattern: a < b > c < d > e...

For example, given [4, 3, 7, 8, 6, 2, 1], a valid zigzag arrangement would be [3, 7, 4, 8, 2, 6, 1] where 3 < 7 > 4 < 8 > 2 < 6 > 1.

The method should modify the list in-place and return it. For null input, return null. For lists with one or zero elements, return the list unchanged.

Examples:

Input: nums = [1, 4, 3, 2] Output: [1, 4, 2, 3] (or any valid zigzag pattern) Explanation: The output follows the pattern 1 < 4 > 2 < 3 Input: nums = [4, 3, 7, 8, 6, 2, 1] Output: [3, 7, 4, 8, 2, 6, 1] (or any valid zigzag pattern) Explanation: Each element alternates between less-than and greater-than its neighbors Input: nums = [1] Output: [1] Explanation: Single element is already in valid zigzag pattern Input: nums = null Output: null Explanation: Null input returns null
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 account

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 Feb 2026

Contest runs February 1 - 28. Complete challenges to climb the leaderboard!

Points are calculated for challenges completed during the contest period.