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 each j where 0 ≤ j + 1 < k.
  • words[iⱼ] and words[iⱼ₊₁] are equal in length, and the hamming distance between them is 1, where 0 ≤ 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
Longest Unequal Adjacent Groups Subsequence IIInput:abcabdacdaceg=0g=1g=0g=1Constraints:• Adjacent groups must be different• Adjacent words same length, hamming distance = 1Valid Chain:abdacdg=1g=0✓ Groups: 1 ≠ 0 ✓ Hamming distance: 1 (b≠c)Output: ["abd", "acd"]
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
Asked in
Google 15 Amazon 12 Microsoft 8
12.5K Views
Medium Frequency
~25 min Avg. Time
485 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen