Wiggle Subsequence

Find the longest subsequence of an array whose steps alternate up and down, by keeping only the turning points.

Call a sequence of numbers a wiggle sequence when the differences between neighbouring numbers strictly alternate between positive and negative: up, down, up, and so on, or down, up, down. A difference of zero breaks the pattern. A single number counts as a wiggle, and so do two different numbers.

Given an integer array nums, return the length of its longest wiggle subsequence. A subsequence keeps some of the numbers, in their original order, and drops the rest.

Example 1
Input: nums = [1, 7, 4, 9, 2, 5]
Output: 6
Explanation: the whole array wiggles, with differences +6, -3, +5, -7, +3.
Example 2
Input: nums = [1, 17, 5, 10, 13, 15, 10, 5, 16, 8]
Output: 7
Explanation: one such subsequence is [1, 17, 5, 15, 5, 16, 8], with differences +16, -12, +10, -10, +11, -8.
Example 3
Input: nums = [1, 2, 3, 4, 5, 6, 7, 8, 9]
Output: 2
Explanation: every step goes up, so two different numbers, such as [1, 9], are the longest wiggle.
Solution

The Idea

Picture the numbers as heights along a mountain path, walked from left to right. Example 1, [1, 7, 4, 9, 2, 5], goes up, down, up, down, up. Every step changes direction, so the whole path is a wiggle and the answer is 6.

Example 2 is bumpier. After 5 the path climbs to 10, then 13, then 15 without turning, and then drops from 15 to 10 to 5. Two rises in a row break the up, down pattern, so a wiggle cannot keep all of these numbers. Some must be dropped, but which ones?

Look at the picture below. It draws each number of Example 2 as a point at its own height, above its index in the array.

The numbers 1, 17, 5, 10, 13, 15, 10, 5, 16, 8 drawn as heights. The turning points and the two ends, 1, 17, 5, 15, 5, 16 and 8, are kept and form a wiggle of length 7. The 10 and 13 inside the climb from 5 to 15 and the 10 inside the drop from 15 to 5 are skipped.

Take the stretch marked "one climb: 5, 10, 13, 15". A wiggle can use only one rise from it, from 5 up to one of the higher numbers. Ending that rise on the top, 15, is the best pick. The next step must be a fall, and the higher the number we fall from, the more numbers lie below it.

The stretch marked "one drop: 15, 10, 5" works the other way round: keep its bottom, 5, so the next rise has the most room. Keeping the top of each climb and the bottom of each drop, because it looks best for the very next step, is a greedy choice: it never looks further ahead, and here it never needs to.

The orange points are what remains: the turning points, where the path changes direction, plus the two ends. They are 1, 17, 5, 15, 5, 16 and 8, seven numbers, the answer to Example 2. The hollow points 10, 13 and 10 sit inside a climb or a drop and add nothing.

So the answer is a count. Treat each unbroken climb or drop as one, count them, and add one for the starting number. Example 2 has six: up to 17, down to 5, up to 15, down to 5, up to 16 and down to 8, so the answer is 7.

Solution Approach

Trying every subsequence works but is slow. Walking the array once is fast, and it means settling three things: what to remember along the way, how each step changes it, and what to do when two neighbours are equal.

Trying every subsequence

Why not list every subsequence and keep the longest wiggle? Each number is either kept or dropped, so an array of n numbers has 2n subsequences. That is 1,024 for the ten numbers of Example 2, and more than 1030 for 100 numbers. The picture shows that there is nothing to choose between: the turning points can be found in one walk from left to right.

What to remember while walking

What does the walk need to know at each position? Not the subsequence itself, only two lengths. up is the length of the longest wiggle among the numbers seen so far whose last step is a rise. down is the same for a wiggle whose last step is a fall. Both start at 1, because the first number alone is a wiggle of length 1.

Updating the two lengths

What happens when the next number is higher than the one before it? The step is a rise, and a rise can follow a wiggle that ended on a fall, so up becomes down + 1. A fall does the opposite: down becomes up + 1. In Example 2, the step from 1 to 17 sets up to 2, and the step from 17 to 5 sets down to 3.

Then comes the climb from 5 to 15. The step to 10 sets up to down + 1, which is 4. The steps to 13 and 15 set up to 4 again, because down has not changed. The length stays 4, but the wiggle behind it now ends on 15 instead of 10. Ending on 15 is the greedy choice of keeping the top of the climb, made without any extra code.

The drop from 15 to 5 sets down to 5, the rise to 16 sets up to 6, and the last fall, to 8, sets down to 7. The answer is the larger of the two lengths, 7.

Equal neighbours

What if two neighbours are equal, as in [3, 3, 3]? A difference of zero is neither a rise nor a fall, so no wiggle can use that step. Neither up nor down changes, and the answer for [3, 3, 3] stays 1.

Java Solution

The method wiggleMaxLength works in these steps:

  1. First, set up and down to 1, since the first number alone is a wiggle of length 1.
  2. Walk the array with one loop, moving i from index 1 to the end, and compare nums[i] with the number before it, nums[i - 1].
  3. If nums[i] is bigger, the step is a rise, so set up to down + 1. If it is smaller, the step is a fall, so set down to up + 1. If the two numbers are equal, change nothing.
  4. After the loop, return the larger length with Math.max(up, down).

The main method runs the three examples, an array with one number, an array of three equal numbers, and [1, 1, 2, 2, 1], where equal neighbours sit between the rises and falls.

Java
public class WiggleSubsequence {

    public static int wiggleMaxLength(int[] nums) {
        int up = 1;     // longest wiggle so far whose last step is a rise
        int down = 1;   // longest wiggle so far whose last step is a fall
        for (int i = 1; i < nums.length; i++) {
            if (nums[i] > nums[i - 1]) {
                up = down + 1;          // a rise extends a wiggle that ended on a fall
            } else if (nums[i] < nums[i - 1]) {
                down = up + 1;          // a fall extends a wiggle that ended on a rise
            }                           // equal neighbours change nothing
        }
        return Math.max(up, down);
    }

    public static void main(String[] args) {
        System.out.println(wiggleMaxLength(new int[] {1, 7, 4, 9, 2, 5}));
        System.out.println(wiggleMaxLength(new int[] {1, 17, 5, 10, 13, 15, 10, 5, 16, 8}));
        System.out.println(wiggleMaxLength(new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9}));
        System.out.println(wiggleMaxLength(new int[] {5}));
        System.out.println(wiggleMaxLength(new int[] {3, 3, 3}));
        System.out.println(wiggleMaxLength(new int[] {1, 1, 2, 2, 1}));
    }
}

Running it prints:

Output
6
7
2
1
1
3

The 6, 7 and 2 at the top match the three examples. The 2 for [1, 2, 3, 4, 5, 6, 7, 8, 9] is one long climb counted once: every step sets up to down + 1, and down stays 1.

The two 1s below come from [5], where the loop never runs, and from [3, 3, 3], where no step is a rise or a fall. The tests must be strict here: with nums[i] >= nums[i - 1] as the rise test, a flat step counts as a rise, and [3, 3, 3] returns 2 although no two of its numbers differ.

Look at the last line, 3, from [1, 1, 2, 2, 1]. The two equal pairs leave the lengths alone, and what remains is the wiggle 1, 2, 1.

Complexity

The method looks at each pair of neighbouring numbers once and keeps just two lengths.

  • Time: O(n), because the loop compares each of the n numbers with the one before it once, and each comparison changes at most one of up and down.
  • Space: O(1), because up and down are all the walk remembers, however long the array is.

Rearranging the whole array into a wiggle, instead of picking a subsequence, is the problem on the Wiggle Sort page.