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 Subsequence I INPUT words array: "e" idx: 0 "a" idx: 1 "b" idx: 2 groups array: 0 0 1 Input Values: words = ["e","a","b"] groups = [0, 0, 1] n = 3 (length) ALGORITHM STEPS 1 Initialize Add first word "e" lastGroup = 0 2 Check "a" (idx 1) groups[1]=0, same as last SKIP (0 == 0) 3 Check "b" (idx 2) groups[2]=1, different! ADD (1 != 0) 4 Complete Return result array Greedy Selection: "e" --> "a" --> "b" Green = selected, Red dashed = skipped FINAL RESULT Longest Alternating Subsequence: "e" "b" g=0 g=1 alternating Output: ["e", "b"] Verification: OK Length: 2 (maximum) Groups: [0, 1] 0 != 1 (Valid!) Key Insight: Greedy single-pass approach: Always include a word if its group differs from the last selected word's group. This guarantees the longest alternating subsequence because skipping never helps extend the sequence later. Time: O(n) | Space: O(n) for result storage TutorialsPoint - Longest Unequal Adjacent Groups Subsequence I | Greedy - Single Pass Selection
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