Longest Unequal Adjacent Groups Subsequence II — LeetCode 2901 Python Solution
- Problem
- #2901
- Pattern
- Dynamic Programming
- Reading time
- 5 min
- Source
- leetcode.com
The 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.
Python solution
class Solution:
def getWordsInLongestSubsequence(
self, words: List[str], groups: List[int]
) -> List[str]:
def check(s: str, t: str) -> bool:
return len(s) == len(t) and sum(a != b for a, b in zip(s, t)) == 1
n = len(groups)
f = [1] * n
g = [-1] * n
mx = 1
for i, x in enumerate(groups):
for j, y in enumerate(groups[:i]):
if x != y and f[i] < f[j] + 1 and check(words[i], words[j]):
f[i] = f[j] + 1
g[i] = j
mx = max(mx, f[i])
ans = []
for i in range(n):
if f[i] == mx:
j = i
while j >= 0:
ans.append(words[j])
j = g[j]
break
return ans[::-1]Complexity
| Measure | Complexity |
|---|---|
| Time | O(n^2 \times L) |
| Space | O(n) auxiliary |
Pattern: Dynamic Programming
Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 2901. Longest Unequal Adjacent Groups Subsequence II is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming.
The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2901. Longest Unequal Adjacent Groups Subsequence II?
- LeetCode 2901. Longest Unequal Adjacent Groups Subsequence II is rated Medium on LeetCode.
- What is the time complexity of LeetCode 2901. Longest Unequal Adjacent Groups Subsequence II?
- The Python solution on this page runs in O(n^2 \times L).
- What is the space complexity of LeetCode 2901. Longest Unequal Adjacent Groups Subsequence II?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 2901. Longest Unequal Adjacent Groups Subsequence II cover?
- LeetCode 2901. Longest Unequal Adjacent Groups Subsequence II is tagged Array, String and Dynamic Programming on LeetCode.