Problem
You are given a string array words and a binary array groups both of length n, where words[i] is associated with groups[i].
Your task is to select the longest alternating subsequence from words. A subsequence of words is alternating if for any two consecutive strings in the sequence, their corresponding elements in the binary array groups differ. Essentially, you are to choose strings such that adjacent elements have non-matching corresponding bits in the groups array.
Formally, you need to find the longest subsequence of an array of indices [0, 1, ..., n - 1] denoted as [i0, i1, ..., ik-1], such that groups[ij] != groups[ij+1] for each 0 <= j < k - 1 and then find the words corresponding to these indices.
Return the selected subsequence. If there are multiple answers, return any of them.
Note: The elements in words are distinct.
Examples
Example 1:
| |
Example 2:
| |
Constraints:
1 <= n == words.length == groups.length <= 1001 <= words[i].length <= 10groups[i]is either0or1.wordsconsists of distinct strings.words[i]consists of lowercase English letters.
Solution
Method 1 - Greedy
To solve this:
- Use a greedy approach to iterate through the array.
- Choose an element only if the alternating condition between its group and the previous group’s value is met.
- Keep track of the selected subsequence in an auxiliary list.
Algorithm
- Start iterating through the array with a
prevvariable to track the last selected group’s value. - Add the first element to the subsequence since there are no previous elements.
- If the current group’s value differs from
prev, include the element in the subsequence and updateprev. - Continue this until the end of the array.
- Return the selected subsequence.
Code
| |
| |
Complexity
- ⏰ Time complexity:
O(n)because we only iterate through the array once. - 🧺 Space complexity:
O(k)wherekis the size of the resulting subsequence, which is at mostn.