Skip to content

Commit 758ffa6

Browse files
authored
Create Longest Unequal Adjacent Groups Subsequence I.py
1 parent 111b570 commit 758ffa6

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
'''
2+
You are given a string array words and a binary array groups both of length n, where words[i] is associated with groups[i].
3+
4+
Your task is to select the longest alternating subsequence from words. A subsequence of words is alternating if for any two consecutive strings in the sequence, their corresponding elements in the binary array groups differ. Essentially, you are to choose strings such that adjacent elements have non-matching corresponding bits in the groups array.
5+
6+
Formally, you need to find the longest subsequence of an array of indices [0, 1, ..., n - 1] denoted as [i0, i1, ..., ik-1], such that groups[ij] != groups[ij+1] for each 0 <= j < k - 1 and then find the words corresponding to these indices.
7+
8+
Return the selected subsequence. If there are multiple answers, return any of them.
9+
10+
Note: The elements in words are distinct.
11+
'''
12+
13+
class Solution:
14+
def getLongestSubsequence(self, words: List[str], groups: List[int]) -> List[str]:
15+
n=len(groups)
16+
prev=groups[0]
17+
ans=[words[0]]
18+
i=1
19+
while i<n:
20+
while i<n and prev==groups[i]:
21+
i+=1
22+
if i<n:
23+
ans.append(words[i])
24+
prev=groups[i]
25+
i+=1
26+
return ans
27+
28+
---------------------------------------
29+
30+
class Solution:
31+
def getLongestSubsequence(self, words: List[str], groups: List[int]) -> List[str]:
32+
res = []
33+
last = -1
34+
35+
for i in range(len(words)):
36+
if groups[i]!= last:
37+
res.append(words[i])
38+
last = groups[i]
39+
return res

0 commit comments

Comments
 (0)