Skip to content

Commit b6d6593

Browse files
authored
Merge pull request #2365 from yerim01/main
[yerim01] WEEK 01 solutions
2 parents 1f87eb7 + b9b9d91 commit b6d6593

2 files changed

Lines changed: 68 additions & 0 deletions

File tree

contains-duplicate/yerim01.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
# Leetcode 217: https://leetcode.com/problems/contains-duplicate/description/
2+
# Goal: Given an array of integers,
3+
# return True if the array has duplicates or return False if all elements are distinct.
4+
# Approach:
5+
# - Use a hash set to track elements we have already seen.
6+
# - Iterate through the array and if the current number already exists in the set, return True.
7+
# - Otherwise, add the current number to the set.
8+
# Time complexity: O(n)
9+
# - We iterate through the array once.
10+
# Space complexity: O(n)
11+
# - We store all elements in the set in the worst case.
12+
13+
class Solution:
14+
def containsDuplicate(self, nums: List[int]) -> bool:
15+
h = set()
16+
17+
for n in nums:
18+
if n not in h:
19+
h.add(n)
20+
else:
21+
return True
22+
return False
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
# Leetcode 128: https://leetcode.com/problems/longest-consecutive-sequence/
2+
# Goal: Given an unsorted array of integers nums,
3+
# return the length of the longest consecutive elements sequence.
4+
# Constraints:
5+
# - Unsorted array
6+
# - Must run in O(n) time
7+
# - Duplicates exist
8+
# Approach:
9+
# - Use a variable `longest=0` to track the length of the longest sequence.
10+
# - Convert nums into a hash set to check numbers in O(1).
11+
# - Iterate the nums.
12+
# - Use variables `currentL=1` to track the length of current sequence
13+
# and `j=1` to represent the distance from the current number.
14+
# - For checking larger numbers, do current num + j
15+
# and for checking smaller numbers, do current num - j
16+
# - Iterate through the set while consecutive number exists in the set.
17+
# If it founds the number, remove it from the set and update currentL & j.
18+
# - Update longest with the mximum length.
19+
# - Return longest.
20+
# Time complexity: O(n)
21+
# - Each number is removed from the set
22+
# Space complexity: O(n)
23+
# - Using a set. n -> size of the nums
24+
class Solution:
25+
def longestConsecutive(self, nums: List[int]) -> int:
26+
longest = 0
27+
s = set(nums)
28+
29+
for c in nums:
30+
currentL = 1
31+
j = 1
32+
33+
while c+j in s:
34+
s.remove(c+j)
35+
currentL += 1
36+
j += 1
37+
38+
j = 1
39+
while c-j in s:
40+
s.remove(c-j)
41+
currentL += 1
42+
j += 1
43+
44+
longest = max(longest, currentL)
45+
46+
return longest

0 commit comments

Comments
 (0)