Skip to content

Commit 7485eb2

Browse files
committed
leetcode
1 parent c3e02c2 commit 7485eb2

File tree

2 files changed

+63
-10
lines changed

2 files changed

+63
-10
lines changed

LeetCode/ArraysAndHashing/GroupAnagrams.py

Lines changed: 21 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -5,21 +5,32 @@
55
An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase,
66
typically using all the original letters exactly once.
77
"""
8-
# from collections import UserList
9-
# class Solution:
10-
# def groupAnagrams(self, strs: UserList[str]) -> UserList[UserList[str]]:
8+
from collections import UserList
9+
class Solution:
10+
def groupAnagrams(self, strs: UserList[str]) -> UserList[UserList[str]]:
1111

12+
hashmap = {}
1213

14+
for word in strs:
15+
# we sort the word so we can append it as a key because all words that are anagrams when sorted are the same
16+
sortedWords= ''.join(sorted(word))
1317

18+
if sortedWords not in hashmap:
19+
hashmap[sortedWords] = [word] # value is a list that will contain the word
20+
else:
21+
hashmap[sortedWords].append(word) #if key exists we append the current word
22+
23+
ans= [] # list that will contains all the lists of anagrams
1424

15-
16-
17-
18-
25+
for value in hashmap.values():
26+
ans.append(value)
27+
28+
return ans
29+
1930

20-
# test=Solution()
31+
test=Solution()
2132

22-
# list=["eat","tea","tan","ate","nat","bat"]
33+
list=["eat","tea","tan","ate","nat","bat"]
2334

24-
# print(test.groupAnagrams(list))
35+
print(test.groupAnagrams(list))
2536

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
from typing import List
2+
3+
4+
class Solution:
5+
def longestConsecutive(self, nums: List[int]) -> int:
6+
"""
7+
sort array
8+
variable counter to keep count of consecutive elements
9+
once nums[i+1] - nums[i] > 1
10+
append current counter to a list
11+
and reset count and continue the pass
12+
until list is done
13+
append the current counter
14+
15+
return the max element in the list that contains the counters
16+
"""
17+
18+
#base cases
19+
if len(nums) <= 1:
20+
return len(nums)
21+
22+
sortedNums = sorted(nums)
23+
print(sortedNums)
24+
counter=1
25+
counters=[]
26+
for i in range(1 , len(sortedNums)):
27+
if sortedNums[i] - sortedNums[i-1] == 1:
28+
counter +=1
29+
elif sortedNums[i] - sortedNums[i-1] <= 0:
30+
counter = counter
31+
else:
32+
counters.append(counter)
33+
counter=0
34+
35+
36+
counters.append(counter)
37+
print(counters)
38+
return max(counters)
39+
40+
a =Solution()
41+
arr= [9,1,4,7,3,-1,0,5,8,-1,6]
42+
print(a.longestConsecutive(arr))

0 commit comments

Comments
 (0)