Skip to content

Instantly share code, notes, and snippets.

@tatsuyax25
Created May 15, 2025 17:03
Show Gist options
  • Save tatsuyax25/0e5555daece5deff6f0b1994a6454243 to your computer and use it in GitHub Desktop.
Save tatsuyax25/0e5555daece5deff6f0b1994a6454243 to your computer and use it in GitHub Desktop.
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 c
/**
* @param {string[]} words
* @param {number[]} groups
* @return {string[]}
*/
var getLongestSubsequence = function(words, groups) {
if (!words.length) return []; // If words array is empty, return an empty array
let result = [words[0]]; // Start with the first word in the sequence
let prevGroup = groups[0]; // Track the previous group value
// Loop through the remaining words
for (let i = 1; i < words.length; i++) {
// Only add words if their corresponding group value alternates
if (groups[i] !== prevGroup) {
result.push(words[i]); // Add the word to the result array
prevGroup = groups[i]; // Update the previous group value
}
}
return result; // Return the longest alternating subsequence
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment