File tree Expand file tree Collapse file tree 5 files changed +103
-0
lines changed
encode-and-decode-strings
longest-consecutive-sequence
product-of-array-except-self Expand file tree Collapse file tree 5 files changed +103
-0
lines changed Original file line number Diff line number Diff line change 1+ class Solution :
2+ def threeSum (self , nums : List [int ]) -> List [List [int ]]:
3+
4+ nums .sort ()
5+ res = []
6+
7+ for i , ch in enumerate (nums ):
8+ if i > 0 and nums [i ] == nums [i - 1 ]: continue
9+
10+ l , r = i + 1 , len (nums ) - 1
11+ while l < r :
12+ threeSum = ch + nums [l ] + nums [r ]
13+
14+ if threeSum < 0 :
15+ l += 1
16+ elif threeSum > 0 :
17+ r -= 1
18+ else :
19+ res .append ([ch , nums [l ], nums [r ]])
20+ l += 1
21+ while l < r and nums [l ] == nums [l - 1 ]:
22+ l += 1
23+
24+ return res
25+
26+ ## TC: O(n^2), SC: O(1)
Original file line number Diff line number Diff line change 1+ class Codec :
2+ def encode (self , strs : List [str ]) -> str :
3+ """Encodes a list of strings to a single string.
4+ """
5+ res = ''
6+
7+ for s in strs :
8+ res += str (len (s )) + '#' + s
9+
10+ return res
11+
12+ def decode (self , s : str ) -> List [str ]:
13+ """Decodes a single string to a list of strings.
14+ """
15+ res = []
16+
17+ i = 0
18+ while i < len (s ):
19+ a = s .find ('#' , i )
20+ length = int (s [i :a ])
21+ res .append (s [a + 1 :a + 1 + length ])
22+ i = a + 1 + length
23+
24+ return res
25+
26+ ## TC: O(n), SC:O(n),n denotes sum of all len(s)
Original file line number Diff line number Diff line change 1+ class Solution :
2+ def longestConsecutive (self , nums : List [int ]) -> int :
3+
4+ seen = set (nums )
5+ longest = 0
6+
7+ for n in seen :
8+ if (n - 1 ) not in seen :
9+ length = 1
10+
11+ while (n + length ) in seen :
12+ length += 1
13+
14+ longest = max (length , longest )
15+
16+ return longest
17+
18+ ## TC: O(n), SC: O(n)
Original file line number Diff line number Diff line change 1+ class Solution :
2+ def productExceptSelf (self , nums : List [int ]) -> List [int ]:
3+ length = len (nums )
4+ res = [1 ] * length
5+ ltor = 1
6+ rtol = 1
7+
8+ for i in range (length ):
9+ res [i ] *= ltor
10+ ltor = ltor * nums [i ]
11+ res [length - i - 1 ] *= rtol
12+ rtol = rtol * nums [length - i - 1 ]
13+
14+ return res
15+
16+ ## TC: O(n), SC: O(1)
Original file line number Diff line number Diff line change 1+ class Solution :
2+ def topKFrequent (self , nums : List [int ], k : int ) -> List [int ]:
3+
4+ num_dict = collections .Counter (nums )
5+ freq = num_dict .most_common ()
6+ ans = []
7+
8+ for key , val in freq :
9+ if k == 0 :
10+ break
11+
12+ ans .append (key )
13+ k -= 1
14+
15+ return ans
16+
17+ ## TC: O(n * logn), SC: O(n)
You can’t perform that action at this time.
0 commit comments