Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 45 additions & 0 deletions 3Sum.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
'''
Time: O(N^2)
Sapce: O(N)
'''
class Solution:
def threeSum(self, nums: list[int]) -> list[list[int]]:
"""
for a triplet to form one of the digit
should be negative or at least a 0
duplicate triplets should not be considered
in the final result
input is always at least 3 elements
need to finall 2 sum pairs for the first digit in the triplet
"""

def find_two_sum_pairs(nums, j, tgt):
k = len(nums) - 1
pairs = []
while j < k:
if nums[j] + nums[k] == tgt:
pairs.append([nums[j], nums[k]])
j += 1
while j < k and nums[j] == nums[j - 1]:
j += 1
elif nums[j] + nums[k] > tgt:
k -= 1
else:
j += 1
return pairs

if len(nums) < 3:
return []
res = []

nums.sort() # inward two pointer will not work without the list being sorted
for i in range(len(nums)):
if nums[i] > 0:
break # we cannot form triplets with only +ve numbers
if i > 0 and nums[i] == nums[i - 1]:
continue # we don't want the first number to be considered again if it duplicates
if i < len(nums) - 1:
pairs = find_two_sum_pairs(nums, i + 1, -nums[i])
for pair in pairs:
res.append([nums[i]] + pair)
return res
33 changes: 33 additions & 0 deletions SortColors.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
'''
Time complexity: O(N)
Space complexity: O(1)
'''
class Solution:
def sortColors(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
'''
red - 0
white - 1
blue - 2
sort() not allowed, in place, order shoulbe 0s,1s, 2s
0 1 2 2 1 0
This is a DNF algorithm problem
here low and high acts as 2 boundaries such that low will push 1s to middle and high will push 2s to end
'''
if nums is None:
return []
low, mid, high = 0,0,len(nums) - 1
while mid <= high:
if nums[mid] == 0:
nums[low], nums[mid] = nums[mid], nums[low]
low += 1
mid += 1
elif nums[mid] == 1:
mid += 1
else:
nums[mid],nums[high] = nums[high],nums[mid]
high -= 1
return nums

19 changes: 19 additions & 0 deletions container-wth-most-water.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
class Solution:
def maxArea(self, height: List[int]) -> int:
left = 0
right = len(height) - 1
max_vol = 0

while left != right:
w = right - left
h = min(height[left], height[right])
max_vol = max(max_vol, (w*h))

if height[left] < height[right]:
left += 1
else:
right -= 1

return max_vol