Longest Unequal Adjacent Groups Subsequence I - Problem

You are given a string array words and a binary array groups both of length n.

A subsequence of words is alternating if for any two consecutive strings in the sequence, their corresponding elements at the same indices in groups are different (that is, there cannot be consecutive 0 or 1).

Your task is to select the longest alternating subsequence from words.

Return the selected subsequence. If there are multiple answers, return any of them.

Note: The elements in words are distinct.

Input & Output

Example 1 — Basic Alternating Pattern
$ Input: words = ["e","a","b"], groups = [0,0,1]
Output: ["e","b"]
💡 Note: Start with "e" (group 0). Skip "a" (group 0, same as previous). Add "b" (group 1, different). Result: ["e","b"] alternates 0→1.
Example 2 — All Different Groups
$ Input: words = ["a","b","c","d"], groups = [1,0,1,1]
Output: ["a","b","c"]
💡 Note: Start with "a" (group 1). Add "b" (group 0, different). Add "c" (group 1, different). Skip "d" (group 1, same as "c").
Example 3 — Single Element
$ Input: words = ["x"], groups = [1]
Output: ["x"]
💡 Note: Only one element, so return it as the longest (and only) alternating subsequence.

Constraints

  • 1 ≤ words.length == groups.length ≤ 105
  • 1 ≤ words[i].length ≤ 10
  • groups[i] is either 0 or 1
  • All strings in words are distinct

Visualization

Tap to expand
Longest Unequal Adjacent Groups SubsequenceInput: words = ["e","a","b"], groups = [0,0,1]"e""a""b"group: 0group: 0group: 1Select subsequence with alternating group values:"e"0"b"1Output: ["e", "b"] (alternates 0→1)
Understanding the Visualization
1
Input
Array of words with corresponding binary group values
2
Process
Select words to create alternating 0,1 pattern
3
Output
Longest subsequence with alternating groups
Key Takeaway
🎯 Key Insight: Greedy selection works because we can always extend an alternating subsequence when a different group appears
Asked in
Amazon 15 Google 12 Microsoft 8
22.3K Views
Medium Frequency
~15 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen