#376

Wiggle Subsequence

Medium
ArrayDynamic ProgrammingGreedyDynamic ProgrammingGreedy Algorithms
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

The optimal solution uses dynamic programming to keep track of the lengths of wiggle subsequences ending at each index. This is efficient because we only need to look at the previous element to determine if we can extend the wiggle sequence.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize two variables, 'up' and 'down', to track the length of wiggle subsequences ending with an upward or downward difference.
  2. 2Step 2: Iterate through the array, comparing each element with the previous one to determine if the difference is positive or negative.
  3. 3Step 3: Update 'up' or 'down' based on the comparison, ensuring to alternate the counts.
solution.py15 lines
1# Full working Python code
2
3def wiggle_length(nums):
4    if len(nums) < 2:
5        return len(nums)
6    up = down = 1
7    for i in range(1, len(nums)):
8        if nums[i] > nums[i - 1]:
9            up = down + 1
10        elif nums[i] < nums[i - 1]:
11            down = up + 1
12    return max(up, down)
13
14# Example usage
15print(wiggle_length([1, 7, 4, 9, 2, 5]))

Complexity note: The time complexity is O(n) because we only make a single pass through the array, and the space complexity is O(1) since we use only a fixed amount of extra space.

  • 1Wiggle sequences can be identified by the sign of differences between consecutive elements.
  • 2Dynamic programming can efficiently track the length of sequences without generating all subsequences.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.