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
44 changes: 44 additions & 0 deletions 3Sum.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
# Time Complexity : O(n^2)
# Space Complexity : O(1)
# Did this code successfully run on Leetcode : Yes
# Any problem you faced while coding this : No
# Approach : Sort the array to use two pointers.
# Fix a number and look for two other numbers using left and righ pointers.
# Skip duplicates to avoid repeating the same triplet in the result.

class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
n = len(nums)
res = []

nums.sort()

for i in range(n):
if i != 0 and nums[i] == nums[i-1]:
continue

if nums[i] > 0:
break

left, right = i+1, n-1

while left < right:

total = nums[i] + nums[left] + nums[right]

if total == 0:
res.append([nums[i], nums[left], nums[right]])
left += 1
right -= 1
while left < right and nums[left] == nums[left - 1]:
left += 1
while left < right and nums[right] == nums[right + 1]:
right -= 1
elif total > 0:
right -= 1
else:
left += 1

return res


27 changes: 27 additions & 0 deletions ContainerWithMostWater.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
# Time Complexity : O(n)
# Space Complexity : O(1)
# Did this code successfully run on Leetcode : Yes
# Any problem you faced while coding this : No
# Approach : Two pointers at both ends and keep checking the area between them.
# Move the pointer of shorter line

class Solution:
def maxArea(self, height: List[int]) -> int:
maxAmt = 0
left, right = 0, len(height) - 1

while left < right:
w = right - left

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

currAmt = h * w
maxAmt = max(maxAmt, currAmt)

return maxAmt

25 changes: 25 additions & 0 deletions SortColors.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# Time Complexity : O(n)
# Space Complexity : O(1)
# Did this code successfully run on Leetcode : Yes
# Any problem you faced while coding this : No
# Approach : 3 pointers ans swap elements accordingly to have 0s then 1s and then 2s.
# Move mid only if num is 0 or 1

class Solution:
def sortColors(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
left, mid, right = 0, 0, len(nums) - 1

while mid <= right:
if nums[mid] == 2:
nums[mid], nums[right] = nums[right], nums[mid]
right -= 1
elif nums[mid] == 0:
nums[left], nums[mid] = nums[mid], nums[left]
left += 1
mid += 1
else:
mid += 1