Wiggle Subsequence solution explained

Wiggle Subsequence asks for the length of the longest subsequence whose steps strictly alternate between going up and going down. Keep two counters, the best wiggle ending on a rise and the best ending on a fall; each rise sets the first to the second plus one, each fall does the reverse, and equal neighbors change nothing. That is one pass, O(n) time and O(1) memory.

By Published 7 min read

The problem, in plain terms

Picture a line of readings. You may drop any of them but must keep the rest in order. You want the longest selection that zigzags: up, down, up, down, or down, up, down. Every step must actually change direction, and a step of zero is not a step in either direction. Return the length of the longest such selection.

Case A: [5, 8, 3, 3, 7, 6, 6, 10, 2]
  steps:  +3  -5   0  +4  -1   0  +4  -8
  ignore the zero steps and every step alternates
  one longest wiggle: 5 8 3 7 6 10 2
  answer: 7

Case B: [4, 4, 4]          answer: 1
Case C: [1, 2, 3, 4, 5]    answer: 2   (e.g. 1 5)
Three cases, made up for this page

Clarify: does the first step have to go up? (No, either direction can start.) Do equal neighbors break the pattern or just get skipped? (Skipped, since you can drop them.) What about an empty array? (Return 0.) The answer to the second question is what most bugs come from.

Why interviewers like it

It starts as a DP with two states, which shows whether you can define states by how a subsequence ends rather than where. Then it collapses to a greedy one-pass solution, and the interviewer gets to hear whether you can justify that collapse instead of just remembering it. It is also short enough that edge cases like plateaus and length-one arrays carry a lot of the score.

Brute force and the two-state DP

Trying every subsequence is O(2^n × n), fine as a test oracle and nothing more. The first real answer keeps two arrays. up[i] is the longest wiggle that ends at position i with a rise into it; down[i] is the longest that ends at i with a fall into it. A rise into i can follow any wiggle that ended with a fall at an earlier, smaller value, so up[i] = max(down[j] + 1) over j with nums[j] < nums[i]. A fall is the mirror image. Every position starts at 1 in both arrays.

def wiggle_length_quadratic(nums):
    n = len(nums)
    if n == 0:
        return 0
    up = [1] * n
    down = [1] * n
    for i in range(n):
        for j in range(i):
            if nums[j] < nums[i]:
                up[i] = max(up[i], down[j] + 1)
            elif nums[j] > nums[i]:
                down[i] = max(down[i], up[j] + 1)
    return max(max(up), max(down))
Python: O(n²) DP with an up state and a down state

Optimal: two counters in one pass

Look only at neighbors. Let up be the longest wiggle so far that ends on a rise, and down the longest that ends on a fall. When the next value is higher than the current one, any wiggle that ended on a fall can be extended by this rise, so up becomes down + 1. When it is lower, down becomes up + 1. When it is equal, nothing changes, which is how plateaus get skipped. The answer is the larger counter.

Why is it safe to compare only neighbors? Within a run that keeps rising, the best place to end that rise is the run's highest point, because a higher endpoint leaves more room to fall afterward. The counters behave as if each wiggle always ends at the latest value, and the latest value of a rising run is its peak. The same holds for falling runs and valleys. So the greedy answer equals the number of turning points plus the endpoints, once flat stretches are removed.

def wiggle_length(nums):
    if not nums:
        return 0
    up = down = 1
    for prev, cur in zip(nums, nums[1:]):
        if cur > prev:
            up = down + 1
        elif cur < prev:
            down = up + 1
    return max(up, down)
Python: O(n) time, O(1) memory
function wiggleLength(nums) {
  if (nums.length === 0) return 0;
  let up = 1;
  let down = 1;
  for (let i = 1; i < nums.length; i++) {
    if (nums[i] > nums[i - 1]) up = down + 1;
    else if (nums[i] < nums[i - 1]) down = up + 1;
  }
  return Math.max(up, down);
}
JavaScript: the same two counters
value   step   up   down
  5       -     1     1
  8       +     2     1
  3       -     2     3
  3       0     2     3     (flat, nothing changes)
  7       +     4     3
  6       -     4     5
  6       0     4     5
 10       +     6     5
  2       -     6     7
answer: max(6, 7) = 7
Case A traced

Complexity summary

n array elements
ApproachTimeExtra memoryNote
Every subsequenceO(2^n × n)O(n)Test oracle
Up and down arraysO(n²)O(n)Good first answer, easy to justify
Two running countersO(n)O(1)Expected answer
n array elements. Scroll sideways on a small screen.

Edge cases to try

  • Empty array: 0.
  • One element: 1.
  • Two equal elements: 1, not 2.
  • Two different elements: 2.
  • All equal values: 1, however long the array.
  • A plateau at a turning point, such as [1, 2, 2, 2, 1]: the answer is 3, the flat 2s count once.
  • A long rise with no turn: 2, the first and last values.

Mistakes to avoid

  • Treating a zero step as a direction, which inflates the answer on flat runs.
  • Starting both counters at 0 instead of 1, which undercounts by one.
  • Writing up = up + 1 on a rise. A rise extends a wiggle that ended on a fall, so it must read the other counter.
  • Comparing each value to the last value kept in a stored subsequence instead of to its neighbor, and then forgetting to update that stored value when a run continues.
  • Requiring the first step to go up.

Follow-ups

  • Return the subsequence itself. Drop equal neighbors, then keep the first value, every local peak and valley, and the last value.
  • Require each swing to be at least some size d. The neighbor-only argument no longer holds directly; the quadratic DP with an extra condition is the safe answer to discuss.
  • Contiguous version. The longest contiguous zigzag run is a simpler sliding count that resets when the pattern breaks.
  • Count the wiggles of maximum length. Add count arrays to the quadratic DP, as in Number of Longest Increasing Subsequence.

How to explain it out loud

Fictional example

From two states to two counters
Candidate
A wiggle can end in two ways, on a rise or on a fall. So I will track the best length for each.
Candidate
If the next value goes up, it can extend any wiggle that ended on a fall: up becomes down plus one. Going down is the mirror. Equal values do nothing.
Interviewer
Why can you look only at the previous element?
Candidate
In a rising stretch, ending at the top is always at least as good, because it leaves the most room to fall next. The counters effectively keep the latest peak or valley, so nothing is lost.
Candidate
One pass, constant memory. For an empty array I return 0.

Arithmetic Slices also reads only neighboring differences, but counts runs where the step stays the same. Number of Longest Increasing Subsequence uses the same up-to-now DP with counting. Russian Doll Envelopes shows another subsequence DP that gets faster with the right observation. Best Time to Buy and Sell Stock is a good neighbor in spirit: a one-pass scan over price movements.

Practicing it with Natively

Wiggle Subsequence is short, so interviewers listen closely to your justification for the greedy step. Natively, the desktop assistant for Mac and Windows, can read the problem from a screenshot while you practice and outline the up and down counters; its transcript of your mock answer makes it easy to see whether you handled the flat stretch case in words, not only in code. See how AI helps in coding interviews.

Questions people ask

How do you solve Wiggle Subsequence?

Keep two counters starting at 1: the longest wiggle ending on a rise and the longest ending on a fall. When a value is higher than the one before, set the rise counter to the fall counter plus one; when lower, do the reverse; when equal, change nothing. Return the larger counter.

What is the time complexity of Wiggle Subsequence?

The greedy solution is O(n) time and O(1) memory. The two-array DP it comes from is O(n²) time and O(n) memory.

Why does the greedy solution only compare neighbors?

Inside a run that keeps rising, ending at its highest point is always at least as good, because it leaves the most room for the next fall. The counters act as if each wiggle ends at the latest peak or valley, so nothing better is skipped.

How are equal values handled in Wiggle Subsequence?

A step of zero is neither up nor down, so equal neighbors are skipped. An array of identical values has a longest wiggle of length 1.

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