Leetcode 2900. Longest Unequal Adjacent Groups Subsequence I
Table of Contents
Problem Informations
- Problem Index: 2900
- Problem Link: Longest Unequal Adjacent Groups Subsequence I
- Topics: Array, String, Dynamic Programming, Greedy
Problem Description
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, \ldots, n - 1]$ denoted as $[i_0, i_1, \ldots, i_{k-1}]$, such that $groups[i_j] \neq groups[i_{j+1}]$ for each $0 \leq 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.
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] \neq groups[2]$. Another subsequence that can be selected is ["a","b"]
because $groups[1] \neq 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] \neq groups[1]$ and $groups[1] \neq groups[2]$. Another subsequence that can be selected is ["a","b","d"]
because $groups[0] \neq groups[1]$ and $groups[1] \neq groups[3]$. It can be shown that the length of the longest subsequence of indices that satisfies the condition is $3$.
Constraints:
- $1 \leq n == words.length == groups.length \leq 100$
- $1 \leq words[i].length \leq 10$
- $groups[i]$ is either $0$ or $1$.
words
consists of distinct strings.- $words[i]$ consists of lowercase English letters.
Intuition
The task requires us to find the longest alternating subsequence from a list of words, which is dictated by an associated binary array indicating the “group” of each word. The primary objective is to select words such that the group of any consecutive selected words differs. This alternating pattern is crucial for the subsequence. Given this, our approach will capitalize on the constraints: ensuring each consecutive pair in the subsequence has differing group values to maximize the length of this subsequence.
Approach
The solution iteratively examines each word and its associated group value in the given arrays. It initiates the process by including the first word, naturally establishing the starting point of our subsequence. As it progresses through the list of words, it compares the group value of the current word to the previously selected word’s group value:
Initial Setup: We start by establishing a list for our result which initially contains the first word, as this sets the foundational element of our subsequence.
Iterative Evaluation:
- Iterate through the
words
array starting from the second element. - For each word, check if its corresponding group (from the
groups
array) differs from the group of the previously included word in the result subsequence. - If the group is different, append the current word to our result list, thereby extending our subsequence.
- Update the record of the last encountered group to reflect the group of the newly added word.
- Iterate through the
Result Compilation: Once the iteration over the words is complete, the resultant list will contain the longest possible subsequence that adheres to the alternating group condition.
The algorithm operates linearly with respect to the number of words, examining each one only once while making each decision based on immediate comparisons. This straightforward greedy approach efficiently constructs the longest alternating subsequence by capitalizing on each qualifying opportunity to extend the sequence.
Code
C++
class Solution {
public:
vector<string> getLongestSubsequence(vector<string>& words, vector<int>& groups) {
int len = words.size(); // Length of the words array
int last_group = groups[0]; // Initialize the last group status with the first element's group
vector<string> result = {words[0]}; // Start the result with the first word
for (int i = 1; i < len; ++i) {
// Check if the current group is different from the last group
if (groups[i] != last_group) {
result.emplace_back(words[i]); // Add the word to the result if it alternates
last_group = groups[i]; // Update the last group status
}
}
return result; // Return the longest alternating subsequence
}
};
Python
class Solution:
def getLongestSubsequence(self, words: list[str], groups: list[int]) -> list[str]:
len_ = len(words) # Length of the words array
last_group = groups[0] # Initialize the last group status with the first element's group
result = [words[0]] # Start the result with the first word
for i in range(1, len_):
# Check if the current group is different from the last group
if groups[i] != last_group:
result.append(words[i]) # Add the word to the result if it alternates
last_group = groups[i] # Update the last group status
return result # Return the longest alternating subsequence
Complexity
- Time complexity: $O(n)$
The algorithm processes each element of the input arrayswords
andgroups
once in a single pass, leading to a time complexity of $O(n)$, where $n$ is the number of elements in the arrays. For each element, it checks a simple condition and potentially appends a word to the result array. - Space complexity: $O(n)$
The space complexity is $O(n)$ due to the space required to store the result array. In the worst-case scenario, the result array could contain up to $n$ elements, as each word could potentially be part of the alternating subsequence. The space used by auxiliary variables and input parameters is negligible in comparison.
Disclaimer: All reference materials on this website are sourced from the internet and are intended for learning purposes only. If you believe any content infringes upon your rights, please contact me at csnote.cc@gmail.com, and I will remove the relevant content promptly.
Feedback Welcome: If you notice any errors or areas for improvement in the articles, I warmly welcome your feedback and corrections. Your input will help this blog provide better learning resources. This is an ongoing process of learning and improvement, and your suggestions are valuable to me. You can reach me at csnote.cc@gmail.com.