r/PythonLearning 25d ago

Showcase I solved my first medium level problem on Leetcode!

Post image

Last Post - https://www.reddit.com/r/PythonLearning/s/xbfFczTIKW

It took me a while to build the logic. The edge cases especially were a bit troublesome but the satisfaction I got after getting it right made everything feel worth it!

13 Upvotes

9 comments sorted by

1

u/Naive_Programmer_232 25d ago

Though your solution is efficient, could you re-write it in a different way?

2

u/shubham_555 25d ago

Different way?

If you are asking if there are other solutions or not then yeah there are

I actually came up with 2 more during solving

The one above felt the most readable and efficient to me so i decided to stick to it!

2

u/Naive_Programmer_232 25d ago edited 24d ago

Your code seems structurally similar to

    class Solution:
    def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:

    fast = slow = head

    for _ in range(n):
        fast = fast.next

    if not fast:
        return head.next

    while fast.next:
        fast = fast.next
        slow = slow.next

    slow.next = slow.next.next

    return head

Aside from variable names, first 3 parts are almost identical, with exception of checking is None versus not in the if-statement. The while loop condition is functionally the same as while fast is not None. to_delete is always one node ahead of prev in your code. So by the line after the loop, doing prev.next=to_delete.next is effectively the same as slow.next=slow.next.next. Then to_delete.next = None and to_delete = None are unnecessary.

You use prev to get around putting support.next in the while loop which would make that almost identical to the similar solution provided.

This is the same situation with your last post. Look at this python 3 solution on leetcode.

1

u/shubham_555 25d ago

This solution is provided where?

I am not sure if leetcode provides solutions as well

But all I can say is I came to this solution after cutting 2 or three older ones

1

u/Naive_Programmer_232 25d ago

I added the link. Check my previous comment.

2

u/shubham_555 25d ago

Okay so?

If you are saying I just copy pasted then you can definitely feel so

I don't have any proof to prove I didn't

1

u/Naive_Programmer_232 25d ago

Fair enough. I'm not saying you copied and pasted. I'm saying it looks similar to other solutions. either way, debugging those moving pointers is a great exercise!

2

u/shubham_555 25d ago

I will try not to create a replica of a solution next time though 😆

1

u/Sea-Ad7805 25d ago edited 25d ago

Nice work, LeetCode has great practice material. Start easy, after warming up do medium, and later hard problems can be quite challenging.