#2901
Longest Unequal Adjacent Groups Subsequence II
MediumArrayStringDynamic ProgrammingDynamic ProgrammingGraph Traversal
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n²) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n²)Space O(n)
We can use dynamic programming to build up the solution by storing the lengths of the longest valid subsequences ending at each index. This reduces the number of checks needed compared to the brute force approach.
⚙️
Algorithm
3 steps- 1Step 1: Initialize a dp array where dp[i] represents the length of the longest valid subsequence ending at index i.
- 2Step 2: For each index i, check all previous indices j to see if they can form a valid pair with i based on the conditions.
- 3Step 3: Update dp[i] accordingly and keep track of the maximum length found.
solution.py27 lines
1# Full working Python code
2def longest_unequal_subsequence(words, groups):
3 n = len(words)
4 dp = [1] * n
5 prev = [-1] * n
6
7 for i in range(n):
8 for j in range(i):
9 if (groups[i] != groups[j] and \
10 len(words[i]) == len(words[j]) and \
11 hamming_distance(words[i], words[j]) == 1):
12 if dp[j] + 1 > dp[i]:
13 dp[i] = dp[j] + 1
14 prev[i] = j
15
16 max_length = max(dp)
17 index = dp.index(max_length)
18 result = []
19 while index != -1:
20 result.append(words[index])
21 index = prev[index]
22 return result[::-1]
23
24
25def hamming_distance(s1, s2):
26 return sum(c1 != c2 for c1, c2 in zip(s1, s2))
27ℹ
Complexity note: The time complexity remains O(n²) due to the nested loops for checking pairs, but we use O(n) space for the dp and prev arrays to store lengths and previous indices.
- 1Dynamic programming helps build solutions incrementally.
- 2Hamming distance checks can be efficiently implemented.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.