two pointers 1#1865
Conversation
Arrange Colors (sort-colors.py)Your solution is on the right track and correctly implements the core logic of the Dutch National Flag algorithm. However, there are a few issues to address:
Here is the corrected version of your code: from typing import List
class Solution:
def sortColors(self, nums: List[int]) -> None:
low, mid, high = 0, 0, len(nums) - 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]
low += 1
mid += 1
else:
mid += 1Note that the algorithm correctly handles the pointers. When swapping with Overall, your solution is almost correct but needs minor adjustments. Keep up the good work! VERDICT: NEEDS_IMPROVEMENT 3 sum (three-sum.py)Your solution shows an understanding that the two-pointer technique can be used to achieve O(n^2) time complexity, which is a good start. However, there are several critical issues:
Here is a corrected version of your code in Python: class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
nums.sort()
res = []
n = len(nums)
for i in range(n):
if i > 0 and nums[i] == nums[i-1]:
continue
l, r = i+1, n-1
while l < r:
s = nums[i] + nums[l] + nums[r]
if s < 0:
l += 1
elif s > 0:
r -= 1
else:
res.append([nums[i], nums[l], nums[r]])
l += 1
while l < r and nums[l] == nums[l-1]:
l += 1
r -= 1
while l < r and nums[r] == nums[r+1]:
r -= 1
return resVERDICT: NEEDS_IMPROVEMENT Container With Most Water (container-most-water.py)Your solution is excellent! You've implemented the optimal algorithm with O(n) time and O(1) space complexity. The logic is sound: by moving the pointer pointing to the shorter line inward, you correctly explore potentially larger areas. This is because the area is limited by the shorter line, so moving the shorter pointer might lead to a larger area if a taller line is found. One minor suggestion for clarity: you could add a brief comment explaining why you move the pointer with the smaller height. This would help others understand the intuition behind the algorithm. For example: # Move the pointer pointing to the smaller height inward, as that might lead to a larger areaAlso, consider initializing Overall, great job! Your solution is efficient and correct. VERDICT: PASS |
No description provided.