File tree Expand file tree Collapse file tree 4 files changed +71
-0
lines changed
longest-consecutive-sequence Expand file tree Collapse file tree 4 files changed +71
-0
lines changed Original file line number Diff line number Diff line change 1+ # Time Complexity: O(n)
2+ # Space Complexity: O(n)
3+
4+ class Solution :
5+ def containsDuplicate (self , nums : List [int ]) -> bool :
6+ # set to keep track of duplicates.
7+ duplicates = set ()
8+
9+ # go through each number in the list
10+ for num in nums :
11+ # if it's a duplicate, return true.
12+ if num in duplicates :
13+ return True
14+ # otherwise, add it to the set to check for duplicates.
15+ duplicates .add (num )
16+
17+ # if finish the loop and don't find duplicates, return false.
18+ return False
Original file line number Diff line number Diff line change 1+ # Time Complexity: O(n)
2+ # Space Complexity: O(n)
3+
4+ class Solution :
5+ def longestConsecutive (self , nums : List [int ]) -> int :
6+ # convert list to set to remove duplicates and allow quick lookups
7+ num_set = set (nums )
8+ longest_streak = 0
9+
10+ # loop through each number in the set
11+ for num in num_set :
12+ # only start counting if it's the beginning of a sequence
13+ if num - 1 not in num_set :
14+ current_num = num
15+ current_streak = 1
16+
17+ # keep counting while the next number in the sequence exists
18+ while current_num + 1 in num_set :
19+ current_num += 1
20+ current_streak += 1
21+
22+ # update the longest streak found so far
23+ longest_streak = max (longest_streak , current_streak )
24+
25+ return longest_streak
Original file line number Diff line number Diff line change 1+ # Time Complexity: O(n log n)
2+ # Space Complexity: O(n)
3+
4+ class Solution :
5+ def topKFrequent (self , nums : List [int ], k : int ) -> List [int ]:
6+ # count how many times each number appears
7+ counts = {}
8+ for num in nums :
9+ counts [num ] = counts .get (num , 0 ) + 1
10+
11+ # sort numbers by their count (most frequent first) and grab top k
12+ # counts.get gets the count of num
13+ # reverse=True sorts in descending order
14+ # [:k] gets the first k elements
15+ top_nums = sorted (counts , key = counts .get , reverse = True )
16+ return top_nums [:k ]
Original file line number Diff line number Diff line change 1+ # Time Complexity: O(n)
2+ # Space Complexity: O(n)
3+
4+ class Solution :
5+ def isPalindrome (self , s : str ) -> bool :
6+ # clean up the string: remove non-alphanumeric chars and convert to lowercase
7+ # isalnum() checks if the character is alphanumeric
8+ filtered = '' .join (filter (str .isalnum , s )).lower ()
9+
10+ # check if it reads the same forwards and backwards
11+ # filtered[::-1] flips the string
12+ return filtered == filtered [::- 1 ]
You can’t perform that action at this time.
0 commit comments