Longest Unequal Adjacent Groups Subsequence II - Problem
You are given a string array words and an array groups, both arrays having length n.
The hamming distance between two strings of equal length is the number of positions at which the corresponding characters are different.
You need to select the longest subsequence from an array of indices [0, 1, ..., n - 1], such that for the subsequence denoted as [i₀, i₁, ..., iₖ₋₁] having length k, the following holds:
- For adjacent indices in the subsequence, their corresponding groups are unequal, i.e.,
groups[iⱼ] != groups[iⱼ₊₁], for eachjwhere0 ≤ j + 1 < k. words[iⱼ]andwords[iⱼ₊₁]are equal in length, and the hamming distance between them is1, where0 ≤ j + 1 < k, for all indices in the subsequence.
Return a string array containing the words corresponding to the indices (in order) in the selected subsequence. If there are multiple answers, return any of them.
Note: strings in words may be unequal in length.
Input & Output
Example 1 — Basic Valid Chain
$
Input:
words = ["a","b","c","d"], groups = [1,0,1,1]
›
Output:
["a","b","c"]
💡 Note:
Chain a→b→c: groups [1,0,1] are alternating, hamming distances are 1 (a≠b at 1 position, b≠c at 1 position). Length = 3.
Example 2 — Different Length Words
$
Input:
words = ["a","ab","abc"], groups = [0,0,1]
›
Output:
["ab"]
💡 Note:
Words have different lengths so cannot form valid chain with hamming distance constraint. Best subsequence has length 1.
Example 3 — Same Groups
$
Input:
words = ["abc","def"], groups = [0,0]
›
Output:
["abc"]
💡 Note:
Both words have same group (0), so cannot form chain. Maximum subsequence length is 1.
Constraints
- 1 ≤ words.length ≤ 100
- 1 ≤ words[i].length ≤ 10
- groups.length == words.length
- 0 ≤ groups[i] ≤ 1
Visualization
Tap to expand
Understanding the Visualization
1
Input
Array of words with corresponding groups
2
Process
Find valid chains with alternating groups and hamming distance 1
3
Output
Return longest valid subsequence as string array
Key Takeaway
🎯 Key Insight: Use dynamic programming to efficiently build the longest valid chain by extending previous subsequences
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code