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
36 changes: 36 additions & 0 deletions 3sum.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
''' 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 : Fix the 1st number and run 2sum on rest array using TWO - pointers
'''
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
nums.sort()
print(nums)
n = len(nums)
res = []
for i in range(n-1):
if i > 0 and nums[i] == nums[i-1]:
continue
l, r = i+1, n-1
while l < r:
summ = nums[i] + nums[l] + nums[r]
if summ == 0:
res.append([nums[i],nums[l],nums[r]])
l += 1
r -= 1
while l < r and nums[l] == nums[l-1]:
l += 1
while l < r and nums[r] == nums[r+1]:
r -= 1
elif summ > 0:
r -= 1
else:
l += 1
return res



21 changes: 21 additions & 0 deletions container-with-most-water.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
''' Time Complexity : O(n)
Space Complexity : O(1)
Did this code successfully run on Leetcode : Yes
Any problem you faced while coding this : No
'''

class Solution:
def maxArea(self, height: List[int]) -> int:
n= len(height)
l, r = 0, n-1
maxarea = 0
while l < r:
h = min(height[l],height[r])
w = (r - l)
area = h * w
maxarea = max(maxarea, area)
if height[l] < height[r]:
l += 1
else:
r -= 1
return maxarea
34 changes: 34 additions & 0 deletions sort-colors.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
''' 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 : Use 3 pointers, 1 for collecting 0, one for collecting 2, and mid to iterate array
swap the elements so that, 0s are at left, 2s are at right and 1s are at the middle

'''

class Solution:
def sortColors(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
n = len(nums)
l, mid, r = 0, 0 , n-1
def swap(nums, x, y):
temp = nums[x]
nums[x] = nums[y]
nums[y] = temp

while mid <= r:
if nums[mid] == 2:
swap(nums,mid,r)
r -= 1
elif nums[mid] == 0:
swap(nums,mid,l)
l += 1
mid += 1
else:
mid += 1