Longest Unequal Adjacent Groups Subsequence II — LeetCode 2901 Python Solution

MediumArrayStringDynamic Programming
Problem
#2901
Reading time
5 min

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

Python
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

MeasureComplexity
TimeO(n^2 \times L)
SpaceO(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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview