Wiggle Sort II solution explained

Wiggle Sort II is solved by sorting a copy, splitting it into a smaller half and a larger half, and filling even positions from the smaller half and odd positions from the larger half, both read from the back. Reading from the back is what keeps equal middle values apart. That is O(n log n) time; the O(n) follow-up finds the median with quickselect and partitions around it using a remapped index.

By Published 8 min read

The problem in plain words

You get a list of integers and must reorder it in place so the values zigzag strictly: the value at index 0 is less than the value at index 1, which is greater than the value at index 2, which is less than index 3, and so on to the end. Strict means no two neighbors may be equal. You are told the input always has at least one valid arrangement, and any valid arrangement is accepted.

Small examples, written for this page
InputOne valid outputComment
[3, 3, 1, 2, 2, 4][2, 4, 2, 3, 1, 3]Duplicates of the middle values are the tricky part
[1, 2, 2, 3][2, 3, 1, 2]The two 2s must not end up side by side
[9, 7, 8][8, 9, 7]Odd length: the last slot is a valley
[5, 6][5, 6]Two distinct values are already a wiggle
Small examples, written for this page. Scroll sideways on a small screen.

This is the strict sibling of an easier problem where neighbors may be equal (less than or equal, then greater than or equal). The relaxed version has a simple one-pass swap fix. That trick fails here, and recognizing why is part of the interview.

What the interviewer is watching for

Most candidates find the sort-and-interleave idea within a few minutes. The separating moment comes when the interviewer hands over an input with many copies of the median. A naive interleave puts two copies next to each other and the output breaks. Candidates who test with duplicates before declaring victory, and then explain the reversed fill, do well. Mentioning that an O(n) average solution exists, even without coding it fully, shows range.

Slow approach: search permutations

The most literal idea is to try every ordering and keep the first one that zigzags. With n values that is up to n! orderings, each checked in O(n). It is hopeless beyond about ten elements, but it is useful in one way: it makes a perfect reference when you test a faster version on small random inputs.

from itertools import permutations

def zigzags(seq):
    return all(
        seq[i] < seq[i + 1] if i % 2 == 0 else seq[i] > seq[i + 1]
        for i in range(len(seq) - 1)
    )

def wiggle_brute(nums):
    for p in permutations(nums):
        if zigzags(p):
            nums[:] = p
            return True
    return False
Permutation search: O(n! × n) time. Use only to check other code.

Main approach: sort, split, and fill from the back

Sort a copy. The first half (rounded up) holds the small values, which belong in the valleys at even indexes. The second half holds the large values, which belong on the peaks at odd indexes. Every value in the large half is at least as big as every value in the small half, so a valley next to a peak can only fail when both equal the median.

Here is the failure with [1, 2, 2, 3]. The halves are [1, 2] and [2, 3]. Filling forward gives 1, 2, 2, 3, and the middle pair is 2 next to 2. Now fill both halves from their ends instead: valleys get 2 then 1, peaks get 3 then 2, producing 2, 3, 1, 2. The copies of the median land at the far left of the valleys and the far right of the peaks, so they never touch. Because a valid answer is promised, the median cannot occupy more than about half the slots, and the reversed fill always separates its copies.

def wiggle_sort(nums):
    ordered = sorted(nums)
    half = (len(nums) + 1) // 2
    nums[::2] = ordered[:half][::-1]
    nums[1::2] = ordered[half:][::-1]
Python: O(n log n) time, O(n) extra space for the sorted copy.
function wiggleSort(nums) {
  const ordered = [...nums].sort((a, b) => a - b);
  const n = nums.length;
  let low = Math.floor((n + 1) / 2) - 1;
  let high = n - 1;
  for (let i = 0; i < n; i++) {
    nums[i] = i % 2 === 0 ? ordered[low--] : ordered[high--];
  }
}
JavaScript: the same reversed fill with two moving pointers.

Python's slice assignment does the interleave in two lines: nums[::2] covers the even indexes and nums[1::2] the odd ones, and the half sizes match those slices exactly for both even and odd lengths.

Follow-up: O(n) average time with a virtual index

If the interviewer asks for linear time, the sort has to go. You do not need the full order, only which values are above, at, or below the median. Find the median with quickselect in O(n) on average. Then run a three-way partition (the Dutch national flag scheme) that sends larger values to the odd slots first, then the remaining odd slots and even slots get the median copies, and smaller values fill the even slots from the far end.

The trick is the index mapping. The function (1 + 2i) mod (n | 1) walks the slots in the order 1, 3, 5, and so on, then 0, 2, 4. Partitioning in that virtual order puts the large values on the peaks and the small values in the valleys, with median copies spread between them. It is hard to derive under pressure, so explain the mapping with a small example before writing it.

import random

def kth_smallest(values, k):
    lo, hi = 0, len(values) - 1
    while True:
        pivot = values[random.randint(lo, hi)]
        lt, i, gt = lo, lo, hi
        while i <= gt:
            if values[i] < pivot:
                values[lt], values[i] = values[i], values[lt]
                lt += 1
                i += 1
            elif values[i] > pivot:
                values[i], values[gt] = values[gt], values[i]
                gt -= 1
            else:
                i += 1
        if k < lt:
            hi = lt - 1
        elif k > gt:
            lo = gt + 1
        else:
            return pivot

def wiggle_sort_linear(nums):
    n = len(nums)
    if n < 2:
        return
    median = kth_smallest(list(nums), n // 2)
    slot = lambda i: (1 + 2 * i) % (n | 1)
    left, mid, right = 0, 0, n - 1
    while mid <= right:
        a = slot(mid)
        if nums[a] > median:
            b = slot(left)
            nums[a], nums[b] = nums[b], nums[a]
            left += 1
            mid += 1
        elif nums[a] < median:
            b = slot(right)
            nums[a], nums[b] = nums[b], nums[a]
            right -= 1
        else:
            mid += 1
Python: quickselect for the median, then a three-way partition in virtual order.

The quickselect above runs on a copy for clarity, which keeps the space at O(n). A fully in-place version runs quickselect on nums itself, since the partition step does not care about the order it receives.

Complexity

Time and extra space for each version
ApproachTimeExtra spaceNotes
Permutation searchO(n! × n)O(n)Testing aid only
Sort and reversed fillO(n log n)O(n)The answer most interviewers expect
Quickselect and virtual partitionO(n) average, O(n²) worstO(1) if quickselect runs in placeMention it; code it if asked
Time and extra space for each version. Scroll sideways on a small screen.

Edge cases to test

  • Many copies of the median, such as [4, 5, 5, 5, 6, 6]. This is the input that breaks a forward fill.
  • Odd length, where the even slots outnumber the odd ones by one.
  • Length one or two: nothing to do, or a single comparison.
  • Negative numbers and zero mixed in.
  • Already sorted input and reverse sorted input, to make sure the fill does not depend on the starting order.

Common mistakes

  • Filling both halves front to back. It passes inputs with distinct values and fails as soon as the median repeats.
  • Applying the swap-neighbors trick from the relaxed problem. Swapping adjacent pairs cannot fix a run of equal values.
  • Splitting at n // 2 instead of rounding up, which gives the valleys one slot too few on odd lengths.
  • Writing into nums while reading from it, instead of reading from a sorted copy.
  • Using JavaScript's sort without a comparator, so 10 sorts before 9.
  • Claiming the quickselect version is O(n) in the worst case. It is O(n) on average with a random pivot.

How to explain it out loud

Fictional example

Talking through the duplicate trap
Candidate
Valleys need small values and peaks need big ones, so I sort a copy and split it. The lower half goes to even indexes and the upper half to odd indexes.
Interviewer
Try it on one, two, two, three.
Candidate
Going forward I get 1, 2, 2, 3, which is broken. The median copies sit at the end of the small half and the start of the big half. If I read both halves backwards they end up at opposite ends instead: 2, 3, 1, 2. That works, and it costs O(n log n) for the sort.

Relative Sort Array is the gentler ordering problem, where a second list dictates the sequence and counting replaces most of the sorting. Pancake Sorting keeps the sorting theme but limits you to one operation, reversing a prefix. The algorithm interview questions page covers quickselect and partitioning in more general terms.

Practicing with Natively

Natively can capture a screenshot of a problem during practice and propose an approach and pattern, which is handy here for checking whether your reasoning about the median copies matches a second opinion after you finish your own attempt. Its on-device transcript of a mock round also lets you replay how clearly you explained the reversed fill. See an AI interview assistant for details on Mac and Windows.

Questions people ask

How do you solve Wiggle Sort II?

Sort a copy, split it into a lower half (rounded up) and an upper half, then place the lower half on even indexes and the upper half on odd indexes, reading both halves from the end. It runs in O(n log n) time with O(n) extra space.

Why do the halves have to be reversed?

Copies of the median sit at the end of the lower half and the start of the upper half. Filling forward can put two of them side by side; reading both halves backwards moves them to opposite ends of the array.

Can Wiggle Sort II be done in O(n) time?

On average, yes. Find the median with quickselect, then run a three-way partition over the index mapping (1 + 2i) mod (n | 1), which places larger values on odd slots and smaller values on even slots.

What is the difference between Wiggle Sort and Wiggle Sort II?

The first allows equal neighbors and is fixed with a single pass of adjacent swaps. The second requires strict inequalities, so duplicates must be separated and the swap trick no longer works.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP