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.
Example 1:
Input: words = ["e","a","b"], groups = [0,0,1]
Output: ["e","b"]
Explanation: A subsequence that can be selected is ["e","b"] because groups[0] != groups[2]. Another subsequence that can be selected is ["a","b"] because groups[1] != groups[2]. It can be demonstrated that the length of the longest subsequence of indices that satisfies the condition is 2.
Example 2:
Input: words = ["a","b","c","d"], groups = [1,0,1,1]
Output: ["a","b","c"]
Explanation: A subsequence that can be selected is ["a","b","c"] because groups[0] != groups[1] and groups[1] != groups[2]. Another subsequence that can be selected is ["a","b","d"] because groups[0] != groups[1] and groups[1] != groups[3]. It can be shown that the length of the longest subsequence of indices that satisfies the condition is 3.
Constraints:
1 <= n == words.length == groups.length <= 1001 <= words[i].length <= 10groups[i] is either 0 or 1.words consists of distinct strings.words[i] consists of lowercase English letters.When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
Imagine you have a row of different colored items and you want to pick a long chain of them by choosing items one by one, making sure no two chosen items next to each other are the same color. The brute force approach works by testing every single combination of items you could possibly pick to see which ones follow the color rule.
Here's how the algorithm would work step-by-step:
def get_longest_subsequence(words, groups):
total_items = len(words)
longest_valid_group = []
# Generate every possible combination of items to evaluate all potential alternating sequences
for combination_index in range(1 << total_items):
current_combination = []
for item_index in range(total_items):
if (combination_index >> item_index) & 1:
current_combination.append(item_index)
is_sequence_valid = True
for neighbor_index in range(len(current_combination) - 1):
current_group = groups[current_combination[neighbor_index]]
next_group = groups[current_combination[neighbor_index + 1]]
# Reject combinations with adjacent matching groups to enforce alternation rule
if current_group == next_group:
is_sequence_valid = False
break
# Track the longest valid sequence found so far across all tested combinations
if is_sequence_valid and len(current_combination) > len(longest_valid_group):
longest_valid_group = current_combination
result_sequence = [words[item_index] for item_index in longest_valid_group]
return result_sequence
Instead of testing every possible combination of items, the optimal strategy simply walks through the entire list from start to finish and keeps an item only if it belongs to a different category than the last one we decided to keep. This clever shortcut guarantees the longest possible chain where no two adjacent items are from the same category, using a clean greedy approach.
Here's how the algorithm would work step-by-step:
def get_longest_subsequence(words_list, groups_list):
# We must keep the first item to start any valid alternating sequence.
kept_indices = [0]
for current_index in range(1, len(groups_list)):
# Only include items that alternate groups to maximize length.
if groups_list[current_index] != groups_list[kept_indices[-1]]:
kept_indices.append(current_index)
# Reconstruct the final subsequence using the filtered indices.
return [words_list[index] for index in kept_indices]| Case | How to Handle |
|---|---|
| Arrays of length 1 containing a single word and group element | Return the single word array immediately since a subsequence of length one trivially has no adjacent elements from the same group. |
| All elements in the groups array are identical (e.g., all zeros or all ones) | The greedy algorithm will select only the very first element because any subsequent element would share the same group as the previously selected one. |
| Alternating groups (e.g., 0, 1, 0, 1, 0, 1) | The greedy approach will successfully include every single element in the output subsequence because every adjacent pair has differing group values. |
| Large inputs with maximum constraint limits on array lengths | A single-pass greedy scan operates in linear time O(n) which easily executes within standard time limits without stack overflow issues. |
| Arrays containing identical words at different indices | The algorithm tracks indices and group changes rather than word content, so identical words are treated as distinct elements based on their position. |
| Multiple valid longest subsequences existing due to identical alternating patterns | Any correct greedy implementation that picks the first encountered valid element at each transition point will satisfy the problem statement. |
| Long sequences of identical group values followed by a switch (e.g., 0, 0, 0, 1) | The algorithm keeps the first occurrence of group 0 and correctly waits until the group value flips to 1 to pick the next word. |