Skip to content

two pointers 1#1865

Open
spencerkrebs wants to merge 1 commit intosuper30admin:masterfrom
spencerkrebs:master
Open

two pointers 1#1865
spencerkrebs wants to merge 1 commit intosuper30admin:masterfrom
spencerkrebs:master

Conversation

@spencerkrebs
Copy link
Copy Markdown

No description provided.

@super30admin
Copy link
Copy Markdown
Owner

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:

  1. Return Statement: The problem requires in-place modification, so your function should not return anything. In Python, the function should return None. Remove the return nums statement.

  2. Import Statement: You are using List from the typing module without importing it. Add from typing import List at the top of your file.

  3. Edge Cases: Consider testing with edge cases like an empty list or a list with only one element to ensure correctness.

  4. Code Clarity: The code is concise and readable, which is good. However, adding comments to explain the algorithm (like the Dutch National Flag) would make it even clearer.

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 += 1

Note that the algorithm correctly handles the pointers. When swapping with high, we don't increment mid because the new value at mid (from high) needs to be checked again. When swapping with low, we increment both low and mid because the value at mid after the swap is 1 (since low points to the first 1 or 0, but after swapping with low, mid gets a 1 or 0? Actually, before swapping, low is at the first position where we might have a 1 (because 0s are moved to the left), so after swapping a 0 from mid to low, the value at mid becomes the value that was at low, which should be 1 (because low is at the boundary of 0s and 1s). Therefore, we can safely increment mid after swapping with low.

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:

  1. Sort the Array: The two-pointer technique requires the array to be sorted. Without sorting, you cannot guarantee that moving the left pointer right increases the sum and moving the right pointer left decreases the sum. Please sort the array at the beginning.

  2. Initialize Pointers Correctly: For each index i, you should initialize l to i+1 and r to len(nums)-1. Then, while l < r, calculate the sum s = nums[i] + nums[l] + nums[r]. If s > 0, decrement r; if s < 0, increment l; if s == 0, add the triplet to the result and then increment l and decrement r while skipping duplicates.

  3. Skip Duplicates: You need to skip duplicates for all three elements. For the outer loop, skip if i > 0 and nums[i] == nums[i-1]. Inside the while loop, after finding a triplet, skip duplicates for l and r by moving l to the right until nums[l] != nums[l-1] and r to the left until nums[r] != nums[r+1].

  4. Fix Logic Errors: Your current code has incorrect conditions for moving pointers. For example, when three > 0, you should decrement r, but your code does something else. Also, the code does not handle the case when the sum is negative.

  5. Improve Readability: Use descriptive variable names (e.g., left, right instead of l and r). Add comments to explain your logic.

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 res

VERDICT: 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 area

Also, consider initializing area to 0, which you've done correctly, but note that the problem constraints ensure at least two elements, so it's safe.

Overall, great job! Your solution is efficient and correct.

VERDICT: PASS

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants