Bird
Raised Fist0
Interview Prepgreedy-algorithmsmediumAmazonGoogle

Wiggle Subsequence

Choose your preparation mode4 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Steps
setup

Initialize count and last_diff

Start by setting count to 1 because the first element alone forms a wiggle subsequence. Initialize last_diff to 0 since no differences have been computed yet.

💡 This initialization sets the baseline for counting wiggles and prepares to track the direction of differences.
Line:count = 1 last_diff = 0
💡 The algorithm always counts at least one element as a wiggle subsequence.
📊
Wiggle Subsequence - Watch the Algorithm Execute, Step by Step
Watching each comparison and decision helps you understand how the greedy approach efficiently detects wiggle patterns without checking all subsequences.
Step 1/12
·Active fillAnswer cell
setup
1
0
7
1
4
2
9
3
2
4
5
5
Result: 1
compare
1
0
i
7
1
4
2
9
3
2
4
5
5
Result: 1
insert
1
0
i
7
1
4
2
9
3
2
4
5
5
Result: 2
compare
1
0
7
1
i
4
2
9
3
2
4
5
5
Result: 2
insert
1
0
7
1
i
4
2
9
3
2
4
5
5
Result: 3
compare
1
0
7
1
4
2
i
9
3
2
4
5
5
Result: 3
insert
1
0
7
1
4
2
i
9
3
2
4
5
5
Result: 4
compare
1
0
7
1
4
2
9
3
i
2
4
5
5
Result: 4
insert
1
0
7
1
4
2
9
3
i
2
4
5
5
Result: 5
compare
1
0
7
1
4
2
9
3
2
4
i
5
5
Result: 5
insert
1
0
7
1
4
2
9
3
2
4
i
5
5
Result: 6
record
1
0
7
1
4
2
9
3
2
4
5
5
Result: 6

Key Takeaways

The algorithm counts a wiggle subsequence by tracking the sign changes of consecutive differences.

This insight is hard to see from code alone because it requires understanding how sign changes relate to wiggle patterns.

Only differences that change direction relative to the last difference increment the count.

Visualizing each difference and decision clarifies why some differences are ignored.

The initial difference sets the direction and starts the count beyond the first element.

Seeing the first positive difference trigger a count increment helps understand the algorithm's base case.

Practice

(1/5)
1. You are given arrival and departure times of trains at a station. You need to find the minimum number of platforms required so that no train waits. Which algorithmic approach guarantees an optimal solution for this problem?
easy
A. Sort trains by arrival time and use a min-heap to track earliest departure times
B. Dynamic Programming to find the maximum number of overlapping intervals
C. Greedy approach by always assigning the next available platform without sorting
D. Brute force nested loops checking all pairs of trains for overlaps

Solution

  1. Step 1: Understand the problem requires tracking overlapping intervals

    We need to find the maximum number of trains simultaneously at the station, which corresponds to the maximum overlap of intervals.
  2. Step 2: Identify the optimal approach

    Sorting trains by arrival time and using a min-heap to track the earliest departure allows efficient detection of overlaps and platform reuse, guaranteeing an optimal solution.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Min-heap approach efficiently tracks platform usage [OK]
Hint: Min-heap tracks earliest departure for platform reuse [OK]
Common Mistakes:
  • Assuming greedy without sorting works optimally
  • Thinking DP is needed for interval overlaps
  • Using brute force for large inputs
2. Given the following Python code implementing the max heap approach to reorganize a string, what is the output when the input is "aab"?
import heapq
from collections import Counter

def reorganizeString(s: str) -> str:
    freq = Counter(s)
    max_heap = [(-count, ch) for ch, count in freq.items()]
    heapq.heapify(max_heap)
    prev_count, prev_char = 0, ''
    result = []

    while max_heap:
        count, ch = heapq.heappop(max_heap)
        result.append(ch)
        if prev_count < 0:
            heapq.heappush(max_heap, (prev_count, prev_char))
        prev_count, prev_char = count + 1, ch

    res_str = ''.join(result)
    if len(res_str) != len(s):
        return ""
    return res_str

print(reorganizeString("aab"))
easy
A. "baa"
B. "aab"
C. "aba"
D. "" (empty string)

Solution

  1. Step 1: Trace first iteration

    Heap contains [(' -2', 'a'), ('-1', 'b')]. Pop (-2, 'a'), append 'a', prev_count= -1, prev_char='a'.
  2. Step 2: Trace second iteration

    Pop (-1, 'b'), append 'b', push back (-1, 'a') since prev_count < 0, update prev_count=0, prev_char='b'. Next pop (-1, 'a'), append 'a'. Result is "aba".
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    Output "aba" has no two adjacent same chars and uses all letters [OK]
Hint: Trace heap pops and pushes carefully [OK]
Common Mistakes:
  • Returning input unchanged
  • Appending characters without heap pushback
  • Off-by-one in count update
3. Examine the following BFS-based code for Jump Game II. Which line contains a subtle bug that can cause incorrect jump counts or infinite loops?
medium
A. Line checking if next_pos == n - 1 to return jumps
B. Line incrementing jumps before processing current level
C. Line calculating furthest_jump without bounding by n-1
D. Line adding next_pos to visited set

Solution

  1. Step 1: Identify furthest_jump calculation

    furthest_jump = pos + nums[pos] can exceed array bounds, causing range() to go out of range or runtime error.
  2. Step 2: Check impact

    Without min(pos + nums[pos], n - 1), code may attempt invalid indices, causing incorrect behavior or crashes.
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    Bounding furthest_jump by n-1 prevents out-of-range errors [OK]
Hint: Always bound jump indices within array length [OK]
Common Mistakes:
  • Forgetting to limit furthest_jump to n-1
  • Incrementing jumps incorrectly
  • Missing visited set usage
4. What is the time complexity of the optimal min-heap based algorithm for finding the minimum number of platforms required for n trains?
medium
A. O(n²) due to nested loops checking all train pairs
B. O(n) because each train is processed once
C. O(n log n) due to sorting and heap operations for each train
D. O(n log k) where k is the maximum number of platforms needed

Solution

  1. Step 1: Identify sorting cost

    Sorting n trains by arrival time costs O(n log n).
  2. Step 2: Analyze heap operations

    Each train causes at most one push and one pop on the heap, each O(log n), so total O(n log n).
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    Sorting + heap operations dominate complexity [OK]
Hint: Sorting + heap push/pop per train -> O(n log n) [OK]
Common Mistakes:
  • Assuming O(n) ignoring sorting and heap costs
  • Confusing heap size k with n for complexity
  • Mistaking nested loops for optimal approach complexity
5. What is the time complexity of the optimal greedy algorithm for partitioning labels using a fixed-size array for last occurrences, given a string of length n?
medium
A. O(n) because each character is processed a constant number of times
B. O(n log n) due to sorting characters by last occurrence
C. O(n^2) due to nested scanning for last occurrences
D. O(n * 26) because of fixed alphabet size iteration

Solution

  1. Step 1: Analyze last occurrence computation

    We scan the string once to record last occurrence of each character in O(n).
  2. Step 2: Analyze partitioning loop

    We iterate over the string once more, updating partition end in O(1) per character.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Two linear scans over string length n -> O(n) time [OK]
Hint: Two passes over string -> O(n) time [OK]
Common Mistakes:
  • Assuming nested loops cause O(n^2)
  • Confusing fixed alphabet size iteration as O(n*26)
  • Thinking sorting is needed