Skip to content

Commit b53ac12

Browse files
committed
May 16
1 parent b6ce995 commit b53ac12

File tree

2 files changed

+52
-2
lines changed

2 files changed

+52
-2
lines changed
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
class Solution:
2+
def __is_eligible(self, str1: str, str2: str) -> bool:
3+
if len(str1) != len(str2):
4+
return False
5+
flag = False
6+
for ch1, ch2 in zip(str1, str2):
7+
if ch1 != ch2:
8+
if flag is True:
9+
# hamming distance > 1
10+
return False
11+
flag = True
12+
# hamming distance == 1
13+
return flag
14+
15+
def getWordsInLongestSubsequence(self, words: list[str], groups: list[int]) -> list[str]:
16+
n = len(words)
17+
dp, parent = [1] * n, [-1] * n
18+
max_len = 0
19+
20+
for i in range(n):
21+
for j in range(i):
22+
if groups[i] != groups[j] and \
23+
self.__is_eligible(words[i], words[j]) and \
24+
dp[j] + 1 > dp[i]:
25+
dp[i] = dp[j] + 1
26+
parent[i] = j
27+
max_len = max(max_len, dp[i])
28+
29+
result = []
30+
for i in range(n):
31+
if dp[i] == max_len:
32+
while i != -1:
33+
result.append(words[i])
34+
i = parent[i]
35+
break
36+
return list(reversed(result))
37+
38+
39+
def main():
40+
words = ['bab', 'dab', 'cab']
41+
groups = [1, 2, 2]
42+
assert Solution().getWordsInLongestSubsequence(words, groups) == ['bab', 'dab']
43+
44+
words = ['a', 'b', 'c', 'd']
45+
groups = [1, 2, 3, 4]
46+
assert Solution().getWordsInLongestSubsequence(words, groups) == ['a', 'b', 'c', 'd']
47+
48+
49+
if __name__ == '__main__':
50+
main()

2025-05-May-LeetCoding-Challenge/README.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@
1919
| May 13 | [3335. Total Characters in String After Transformations I](https://leetcode.com/problems/total-characters-in-string-after-transformations-i/) | Medium | Solved |
2020
| May 14 | [3337. Total Characters in String After Transformations II](https://leetcode.com/problems/total-characters-in-string-after-transformations-ii/) | Hard | Unsolved |
2121
| May 15 | [2900. Longest Unequal Adjacent Groups Subsequence I](https://leetcode.com/problems/longest-unequal-adjacent-groups-subsequence-i/) | Easy | Solved |
22-
| May 16 | []() | | |
22+
| May 16 | [2901. Longest Unequal Adjacent Groups Subsequence II](https://leetcode.com/problems/longest-unequal-adjacent-groups-subsequence-ii/) | Medium | Unsolved |
2323
| May 17 | []() | | |
2424
| May 18 | []() | | |
2525
| May 19 | []() | | |
@@ -41,5 +41,5 @@
4141
| Level | Problems | Solved | Unsolved |
4242
| --- | --- | --- | --- |
4343
| Easy | 4 | 4 | 0 |
44-
| Medium | 7 | 7 | 0 |
44+
| Medium | 8 | 7 | 1 |
4545
| Hard | 3 | 1 | 2 |

0 commit comments

Comments
 (0)