2901. Longest Unequal Adjacent Groups Subsequence II
Difficulty: Medium
Topics: Array, String, Dynamic Programming
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 subsequence1 from an array of indices [0, 1, ..., n - 1], such that for the subsequence denoted as [i0, i1, ..., ik-1] having length k, the following holds:
- For adjacent indices in the subsequence, their corresponding groups are unequal, i.e.,
groups[ij] != groups[ij+1], for eachjwhere0 < j + 1 < k. -
words[ij]andwords[ij+1]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.
Example 1:
- Input: words = ["bab","dab","cab"], groups = [1,2,2]
- Output: ["bab","cab"]
-
Explanation:
- A subsequence that can be selected is
[0,2]. groups[0] != groups[2]-
words[0].length == words[2].length, and the hamming distance between them is1. - So, a valid answer is
[words[0],words[2]] = ["bab","cab"]. - Another subsequence that can be selected is
[0,1]. groups[0] != groups[1]-
words[0].length == words[1].length, and the hamming distance between them is1. - So, another valid answer is
[words[0],words[1]] = ["bab","dab"]. - It can be shown that the length of the longest subsequence of indices that satisfies the conditions is
2.
- A subsequence that can be selected is
Example 2:
- Input: words = ["a","b","c","d"], groups = [1,2,3,4]
- Output: ["a","b","c","d"]
-
Explanation:
- We can select the subsequence
[0,1,2,3]. - It satisfies both conditions.
- Hence, the answer is
[words[0],words[1],words[2],words[3]] = ["a","b","c","d"]. - It has the longest length among all subsequences of indices that satisfy the conditions.
- Hence, it is the only answer.
- We can select the subsequence
Constraints:
1 <= n == words.length == groups.length <= 10001 <= words[i].length <= 101 <= groups[i] <= n-
wordsconsists of distinct strings. -
words[i]consists of lowercase English letters.
Hint:
- Let
dp[i]represent the length of the longest subsequence ending withwords[i]that satisfies the conditions. -
dp[i] =(maximum value ofdp[j])+ 1for indicesj < i, wheregroups[i] != groups[j],words[i]andwords[j]are equal in length, and the hamming distance betweenwords[i]andwords[j]is exactly1. - Keep track of the
jvalues used to achieve the maximumdp[i]for each indexi. - The expected array's length is
max(dp[0:n]), and starting from the index having the maximum value indp, we can trace backward to get the words.
Solution:
We need to find the longest subsequence of indices from given arrays words and groups such that adjacent elements in the subsequence have different groups and their corresponding words have a Hamming distance of 1. The solution involves dynamic programming to track the longest valid subsequence ending at each index and backtracking to reconstruct the subsequence.
Approach
-
Dynamic Programming (DP) Setup: Use a DP array where
dp[i]represents the length of the longest valid subsequence ending at indexi. Initialize each element ofdpto 1 since each element by itself is a valid subsequence of length 1. -
Track Previous Indices: Maintain a
prevarray to track the previous index in the subsequence for each element, allowing us to reconstruct the path later. -
Conditions Check: For each index
i, check all previous indicesjto see if they can form a valid subsequence withiby ensuring:- Different groups.
- Words of the same length.
- Hamming distance of exactly 1 between the words.
-
Update DP and Previous Indices: If the conditions are met, update the DP value and previous index for
ibased on the longest valid subsequence found. -
Find Maximum Length Subsequence: Identify the maximum value in the DP array and backtrack from the corresponding index to reconstruct the subsequence using the
prevarray.
Let's implement this solution in PHP: 2901. Longest Unequal Adjacent Groups Subsequence II
<?php
/**
* @param String[] $words
* @param Integer[] $groups
* @return String[]
*/
function getWordsInLongestSubsequence($words, $groups) {
...
...
...
/**
* go to ./solution.php
*/
}
// Example usage:
$words1 = array("bab", "dab", "cab");
$groups1 = array(1, 2, 2);
print_r(getWordsInLongestSubsequence($words1, $groups1)); // Possible output: ["bab", "cab"] or ["bab", "dab"]
$words2 = array("a", "b", "c", "d");
$groups2 = array(1, 2, 3, 4);
print_r(getWordsInLongestSubsequence($words2, $groups2)); // Output: ["a", "b", "c", "d"]
?>
Explanation:
-
Dynamic Programming Initialization: The
dparray starts with each element as 1, and theprevarray is initialized to -1 to indicate no previous elements initially. -
Check Valid Pairs: For each index
i, iterate over all previous indicesjto check if they can form a valid pair withibased on group differences, word length equality, and Hamming distance. -
Update DP Values: If a valid pair is found, update the DP value for
iand set the previous index tojto track the path. -
Find Longest Subsequence: After processing all indices, determine the maximum length of valid subsequences and backtrack from the corresponding index to reconstruct the subsequence using the
prevarray. - Reconstruct Result: The result is built by backtracking from the index with the maximum DP value, ensuring the subsequence is in the correct order.
This approach efficiently computes the longest valid subsequence using dynamic programming and ensures correctness by adhering to the problem constraints.
Contact Links
If you found this series helpful, please consider giving the repository a star on GitHub or sharing the post on your favorite social networks 😍. Your support would mean a lot to me!
If you want more helpful content like this, feel free to follow me:
-
Subsequence:
A subsequence is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.↩
Top comments (0)