Skip to main content
Back to problems
#2900
Easy Algorithms

Longest unequal adjacent groups subsequence i

Array String Dynamic Programming Greedy
67.0% acceptance
Feb 25, 2026
483
275
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.

Solution

Rust
Time O(n)
Space O(n)
LeetCode
solution.rs
impl Solution {
  pub fn get_longest_subsequence(words: Vec<String>, groups: Vec<i32>) -> Vec<String> {
    let mut result: Vec<String> = vec![];
    let mut last_group = -1;
    for (i, &g) in groups.iter().enumerate() {
      if g != last_group {
        result.push(words[i].clone());
        last_group = g;
      }
    }
    result
  }
}