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
41 changes: 41 additions & 0 deletions 3sum.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
"""
time - n^2(log(n))
space - o(1)
we sort the array, we take three pointers, one main pointer that iterates through the array, another two where left starts
from main pointer +1 and right starts at the end. We take the complement as 0-nums[i] and using the left and right pointers
we find the two sum solution for the compliment.
"""

from typing import List


class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
nums.sort()
print(nums)
result = []
for i in range(len(nums)):
if nums[i] > 0:
break
if i > 0 and nums[i] == nums[i - 1]:
continue
two_sum = 0 - nums[i]
l = i + 1
r = len(nums) - 1
while l < r:
left = nums[l]
right = nums[r]
temp_sum = left + right
if temp_sum == two_sum:
result.append([nums[i], nums[l], nums[r]])
while l < r and nums[l] == left:
l += 1
while l < r and nums[r] == right:
r -= 1
elif temp_sum > two_sum:
while l < r and nums[r] == right:
r -= 1
else:
while l < r and nums[l] == left:
l += 1
return result
22 changes: 22 additions & 0 deletions container_water.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
"""
time - o(n)
space - o(1)
we use two pointers that start at the ends, we calculate the area by multiplying distance between two pointers and least height among
the two. We take a greedy approach by moving the smaller of the two heights
"""

from typing import List


class Solution:
def maxArea(self, height: List[int]) -> int:
left = 0
right = len(height) - 1
maxArea = float("-inf")
while left < right:
maxArea = max(maxArea, min(height[left], height[right]) * (right - left))
if height[left] <= height[right]:
left += 1
else:
right -= 1
return maxArea
26 changes: 26 additions & 0 deletions dutchflag.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
"""
time - o(n)
space - o(1)
we take three pointers, one to iterate and two as place holders, left and right are placeholder pointers that keep a track of 0s and 2s
as and when the third pointer encounters a 0 or 2, we swap it with the left and right pointers, if it comes across a one we move the pointers
"""

from typing import List


class Solution:
def sortColors(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
l, r, m = 0, len(nums) - 1, 0
while m <= r:
if nums[m] == 0:
nums[l], nums[m] = nums[m], nums[l]
l += 1
m += 1
elif nums[m] == 2:
nums[m], nums[r] = nums[r], nums[m]
r -= 1
else:
m += 1