Longest Unequal Adjacent Groups Subsequence II - Problem
Imagine you're a linguist studying word evolution patterns! You have an array of words and a corresponding groups array that categorizes each word.
Your mission is to find the longest subsequence where:
- ๐ Adjacent groups alternate:
groups[i] != groups[j]for consecutive elements - ๐ Words have equal length: Adjacent words in your subsequence must be the same length
- ๐ฏ Hamming distance is exactly 1: Adjacent words differ by exactly one character
The hamming distance between two equal-length strings is the number of positions where characters differ. For example, "abc" and "aec" have hamming distance 1.
Return the words corresponding to the longest valid subsequence. If multiple answers exist, return any of them.
Input & Output
example_1.py โ Basic alternating groups
$
Input:
words = ["bab", "dab", "cab"], groups = [1, 2, 2]
โบ
Output:
["bab", "dab"]
๐ก Note:
"bab" (group 1) and "dab" (group 2) have different groups, same length (3), and hamming distance 1 (only 'b' vs 'd' differs). "cab" cannot be added because it has the same group as "dab".
example_2.py โ Single character differences
$
Input:
words = ["a", "b", "c", "d"], groups = [1, 2, 1, 2]
โบ
Output:
["a", "b", "c", "d"]
๐ก Note:
All adjacent pairs satisfy the conditions: different groups, same length (1), and hamming distance 1. This forms the longest possible alternating sequence.
example_3.py โ No valid extensions
$
Input:
words = ["abc", "def"], groups = [1, 1]
โบ
Output:
["abc"]
๐ก Note:
Both words belong to the same group, so no valid alternating subsequence of length > 1 exists. Return any single word.
Constraints
- 1 โค words.length โค 1000
- 1 โค words[i].length โค 10
- words[i] consists of lowercase English letters only
- 1 โค groups[i] โค 105
- Hamming distance is only defined for equal-length strings
Visualization
Tap to expand
Understanding the Visualization
1
Identify Candidates
Find all words that can potentially connect (different groups, same length)
2
Check Mutations
Verify hamming distance is exactly 1 (single character change)
3
Build Chains
Use DP to find longest valid evolutionary chain
4
Reconstruct Path
Follow parent pointers to get the actual word sequence
Key Takeaway
๐ฏ Key Insight: Use dynamic programming to build optimal subsequences by extending previous valid chains, checking three conditions: different groups, equal length, and hamming distance of exactly 1.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code