-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFindallDuplicatesDay13.py
More file actions
46 lines (37 loc) · 1.21 KB
/
Copy pathFindallDuplicatesDay13.py
File metadata and controls
46 lines (37 loc) · 1.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#Brute Approach
# class Solution:
# def findDuplicates(self, nums: List[int]) -> List[int]:
# result = []
# for i in range(len(nums)):
# for j in range(i+1, len(nums)):
# if nums[i] == nums[j] and nums[i] not in result:
# result.append(nums[i])
# return result
# Time Complexity: O(n^2)
# Space Complexity: O(1) (Ignoring output list)
#Better Approach
# class Solution:
# def findDuplicates(self, nums: List[int]) -> List[int]:
# freq = {}
# result = []
# for num in nums:
# freq[num] = freq.get(num, 0) + 1
# for num in freq:
# if freq[num] == 2:
# result.append(num)
# return result
# Time Complexity: O(n)
# Space Complexity: O(n) (for frequency dictionary)
#Optimal Approach
class Solution:
def findDuplicates(self, nums: List[int]) -> List[int]:
result = []
for num in nums:
index = abs(num) - 1
if nums[index] < 0:
result.append(abs(num))
else:
nums[index] = -nums[index]
return result
# Time Complexity: O(n)
# Space Complexity: O(1) (in-place, excluding result)