Skip to content
Problem 376 · LeetCode 376(opens in a new tab)

Wiggle Subsequence

MediumArrays

A wiggle sequence is one where each step from a number to the next goes the opposite way from the step before: up, down, up, and so on, or down, up, down. Every step must really move; two equal neighbours break the pattern. A single number, or two different numbers, already count as a wiggle.

For an integer array nums, find how long its longest wiggling subsequence is. A subsequence keeps the original order but may skip any elements.

Example 1

Input:  nums = [4, 10, 6, 6, 12, 3]
Output: 5
Why:    4, 10, 6, 12, 3 goes up, down, up, down
2 more examples and the constraints

Example 2

Input:  nums = [5, 5, 5]
Output: 1
Why:    no step ever moves, so one number is the best

Example 3

Input:  nums = [2, 4, 6, 8, 10]
Output: 2
Why:    only rises; keep any two numbers

Constraints

  • 1 ≤ length of nums ≤ 1,000
  • 0 ≤ nums[i] ≤ 1,000

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. DP over every earlier numberO(n²)
  2. Two counters, one passO(n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 1,000 numbersVerdict
DP over every earlier numberO(n²)
Passes; easy to argue
Two counters, one passO(n)
Best; answers the follow-up

n = length of nums.

Edge cases to test

  • One number. [7] is a wiggle of length 1.
  • All equal. [5, 5, 5] never moves, so the answer is 1, not 0 or 3.
  • Only rising or only falling. Any two different numbers make a wiggle, so the answer is 2.
  • Flat stretches. In [1, 3, 3, 3, 5, 2] the repeated 3s are skipped: 1, 5, 2 gives 3.

Common mistakes

  • Counting equal neighbours as a step, which breaks the strict up-down rule.
  • Returning 0 for a single number or for all-equal input; the answer is at least 1.
  • Counting sign changes of the differences without skipping zeros, which miscounts flat runs.

How to talk through it

  1. 1Clarify. Do equal neighbours count? Is a single number a wiggle? Is it a subsequence or a subarray?
  2. 2Name the state. What can come next depends only on whether the wiggle ended going up or down.
  3. 3Give the DP. up[i] and down[i] over every earlier k, O(n²), which is fine at 1,000.
  4. 4Collapse it. Only the previous number matters, so two counters give O(n) time and O(1) space.
  5. 5Test out loud. Run [7], [5, 5, 5], an only-rising list and Example 1 before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?