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
28 changes: 28 additions & 0 deletions Problem_1.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
# https://leetcode.com/problems/sort-colors/

# Time complexity: O(n)
# Space complexity: O(1)
# Explanation: Use 3 pointers, and move every 0 to the left, every 2 to the right, and keep the 1s in the middle;
# while swapping make sure left side swaps increment both p0 and curr pointer because those values have been checked
# but right side swaps increment only p2 because those values have not been checked

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


33 changes: 33 additions & 0 deletions Problem_2.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
# https://leetcode.com/problems/3sum/

# Time complexity: O(n^2)
# Space complexity: O(n)
# Explanation: Take each number that is less than 0, and try to find subarrays whhere sum is 0;
# to find subarray assume the search space is for current index i to end of array

class Solution:
def twoSum(self, nums: list[int], i: int, res: list[list[int]]):
low, high = i + 1, len(nums) - 1
while low < high:
sum = nums[i] + nums[low] + nums[high]
if sum < 0:
low += 1
elif sum > 0:
high -= 1
else:
res.append([nums[i], nums[low], nums[high]])
low += 1
high -= 1
while low < high and nums[low - 1] == nums[low]:
low += 1


def threeSum(self, nums: list[int]) -> list[list[int]]:
res = []
nums.sort()
for i in range(len(nums)):
if nums[i] > 0:
break
if i == 0 or nums[i - 1] != nums[i]:
self.twoSum(nums, i, res)
return res
21 changes: 21 additions & 0 deletions Problem_3.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# https://leetcode.com/problems/container-with-most-water/

# TC: O(n)
# SC: O(1)
# Explanation: Maintain two pointers starting at index 0 and n - 1; keep moving the pointers based on highest point;
# at each pass find the max area; return the final max area

class Solution:
def maxArea(self, height: List[int]) -> int:
n = len(height)
l, r = 0, n - 1
m_height = 0

while l < r:
m_height = max(m_height, min(height[l], height[r]) * (r - l))
if height[l] < height[r]:
l += 1
else:
r -= 1

return m_height