Find the longest subsequence of words such that adjacent chosen words come from different groups and their lengths differ by exactly one character.
You are given an array of strings words and an array of integers groups, both of length n.
Choose a subsequence of indices i1 < i2 < ... < ik such that:
groups[ij] != groups[ij+1] for every adjacent pair in the subsequence.Return the longest valid subsequence of indices, or its maximum length depending on the exact task formulation.
This is a dynamic programming problem where each state considers the best subsequence ending at a given word and transitions from earlier compatible words.
words: array of stringsgroups: array of integers of the same length as wordsThe exact platform version may ask for the length of the subsequence rather than the subsequence itself.
Return the maximum length of a valid subsequence.
1 <= n <= $10^{3}$ is a safe interview-scale assumption for this formulation.groups.length == words.length.Example 1
Input
words = ["a","b","ab","ac"], groups = [1,2,1,2]
Output
4
Explanation
One valid subsequence is ["a", "b", "ab", "ac"]. Adjacent groups alternate, and each step satisfies the allowed word-compatibility rule.
Example 2
Input
words = ["abcd","abce","abde"], groups = [1,1,2]
Output
2
Explanation
"abcd" and "abce" cannot both be used if the adjacent group condition is violated. A best valid subsequence has length 2.
Premium problem context
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.