Imagine you have a collection of words and each word belongs to one of two groups (represented as 0 or 1). Your mission is to create the longest possible alternating sequence where no two consecutive words belong to the same group!
๐ฏ The Challenge: Given a string array words and a binary array groups (both of length n), find the longest subsequence where adjacent elements have different group values. Think of it like creating a pattern that alternates between groups: 0-1-0-1 or 1-0-1-0.
What you need to do:
- Select words from the array (maintaining their original order)
- Ensure no two consecutive selected words have the same group value
- Maximize the length of your selection
- Return the actual words in your optimal subsequence
Note: All words are distinct, and if multiple optimal solutions exist, you can return any of them.
Input & Output
Visualization
Time & Space Complexity
Single pass through the input arrays
Only storing the result array, no extra data structures needed
Constraints
- 1 โค words.length โค 105
- 1 โค words[i].length โค 10
- groups.length == words.length
- groups[i] is either 0 or 1
- All strings in words are distinct