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
47 changes: 47 additions & 0 deletions 3sum.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
'''
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
'''
class Solution:
def threeSum(self, nums):
n = len(nums)
result = []
nums.sort()
for i in range(n - 2):
if i > 0 and nums[i] == nums[i - 1]:
continue
left = i + 1
right = n - 1

while left < right:
total = nums[i] + nums[left] + nums[right]

if total == 0:
result.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:
left += 1
else:
right -= 1

return result



s = Solution()
nums = [-1,0,1,2,-1,-4]
print(s.threeSum(nums))
nums = [0,1,1]
print(s.threeSum(nums))
nums = [0,0,0]
print(s.threeSum(nums))
41 changes: 41 additions & 0 deletions container-with-most-water.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
class Solution:
'''
TC: O(n)
SC: O(1)
Leetcode: Solved the problem
Issue: No issue
'''
def maxArea(self, height):
low = 0
high = len(height) - 1
res = 0
while low <= high:
h = min(height[low], height[high])
w = high - low
res = max(res, h*w)
if height[low] < height[high]:
low += 1
else:
high -= 1
return res

'''
TC: O(n^2)
SC: O(1)
'''
def maxArea(self, height):
n = len(height)
res = 0
for i in range(n-1):
for j in range(1, n):
h = min(height[i], height[j])
w = j - i
res = max(res, h*w)
return res


s = Solution()
height = [1,8,6,2,5,4,8,3,7]
print(s.maxArea(height))
height = [1,1]
print(s.maxArea(height))
23 changes: 23 additions & 0 deletions sort-colors.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
'''
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 sortColors(self, nums):
n = len(nums)
low = 0
mid = 0
high = n - 1

while mid <= high:
if nums[mid] == 2:
nums[mid], nums[high] = nums[high], nums[mid]
high -= 1
elif nums[mid] == 0:
nums[mid], nums[low] = nums[low], nums[mid]
mid += 1
low += 1
elif nums[mid] == 1:
mid += 1