diff --git a/0528_swapping-nodes-in-a-linked-list/python3/solution.py b/0528_swapping-nodes-in-a-linked-list/python3/solution.py index e69de29..8a4a1bb 100644 --- a/0528_swapping-nodes-in-a-linked-list/python3/solution.py +++ b/0528_swapping-nodes-in-a-linked-list/python3/solution.py @@ -0,0 +1,25 @@ +# Time: O(N) +# Space: O(1) +class Solution: + def swapNodes(self, head: Optional[ListNode], k: int) -> Optional[ListNode]: + # We are using two pointer approach here + kth_node = kth_end_node = None + + n = 1 + ptr = head + while ptr != None: + if n == k: + kth_node = ptr + + # `kth_end_node` ptr will only start moving once + # we've traversed k nodes from the beginning of the + # linked list + if n >= k: + kth_end_node = head if kth_end_node is None else kth_end_node.next + + n += 1 + ptr = ptr.next + + kth_node.val, kth_end_node.val = kth_end_node.val, kth_node.val + + return head diff --git a/notes/linked_lists.md b/notes/linked_lists.md new file mode 100644 index 0000000..d3e9ec8 --- /dev/null +++ b/notes/linked_lists.md @@ -0,0 +1,14 @@ +--- +category: ds +title: Linked Lists +--- + +# Linked Lists + +## Finding nth node from beginning and nth node from end + +Use two pointer approach to avoid extra space. Initialize the `kth_node_from_end` pointer when the `tmp` pointer reaches `kth` node and keep incrementing from there on. + +### Related problems + +- https://leetcode.com/problems/swapping-nodes-in-a-linked-list