Created
May 15, 2025 17:03
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @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