|
| 1 | +# 24. Swap Nodes in Pairs |
| 2 | +# 🟠 Medium |
| 3 | +# |
| 4 | +# https://leetcode.com/problems/swap-nodes-in-pairs/ |
| 5 | +# |
| 6 | +# Tags: Linked List - Two Pointers |
| 7 | + |
| 8 | +import timeit |
| 9 | +from typing import Optional |
| 10 | + |
| 11 | +from data import LinkedList, ListNode |
| 12 | + |
| 13 | + |
| 14 | +# Keep a pointer to the node right before the current group, then swap |
| 15 | +# the pointers from the front node to the back node, and make the front |
| 16 | +# node point to the next node after the back one. |
| 17 | +# |
| 18 | +# Time complexity: O(n) - We iterate over the entire list one time. |
| 19 | +# Space complexity: O(1) - We only store pointers in memory. |
| 20 | +# |
| 21 | +# Runtime: 35 ms, faster than 89.78% |
| 22 | +# Memory Usage: 13.8 MB, less than 65.67% |
| 23 | +class Solution: |
| 24 | + def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]: |
| 25 | + if not head: |
| 26 | + return None |
| 27 | + # Use four pointers. |
| 28 | + dummy = ListNode(0, head) |
| 29 | + prev, one, two, next = dummy, head, head.next, None |
| 30 | + while one and two: |
| 31 | + # Update next and prev pointers. |
| 32 | + next, prev.next, prev = two.next, two, one |
| 33 | + # Update internal group pointers. |
| 34 | + one.next, two.next = two.next, one |
| 35 | + # Shuffle working node pointers. |
| 36 | + one = next |
| 37 | + if one: |
| 38 | + two = one.next |
| 39 | + return dummy.next |
| 40 | + |
| 41 | + |
| 42 | +def test(): |
| 43 | + executors = [Solution] |
| 44 | + tests = [ |
| 45 | + [[], []], |
| 46 | + [[1], [1]], |
| 47 | + [[1, 2], [2, 1]], |
| 48 | + [[1, 2, 3], [2, 1, 3]], |
| 49 | + [[1, 2, 3, 4], [2, 1, 4, 3]], |
| 50 | + [[1, 2, 3, 4, 5], [2, 1, 4, 3, 5]], |
| 51 | + [[1, 2, 3, 4, 5, 8], [2, 1, 4, 3, 8, 5]], |
| 52 | + ] |
| 53 | + for executor in executors: |
| 54 | + start = timeit.default_timer() |
| 55 | + for _ in range(1): |
| 56 | + for col, t in enumerate(tests): |
| 57 | + sol = executor() |
| 58 | + head = LinkedList.fromList(t[0]).getHead() |
| 59 | + result = LinkedList(sol.swapPairs(head)).toList() |
| 60 | + exp = t[1] |
| 61 | + assert result == exp, ( |
| 62 | + f"\033[93m» {result} <> {exp}\033[91m for" |
| 63 | + + f" test {col} using \033[1m{executor.__name__}" |
| 64 | + ) |
| 65 | + stop = timeit.default_timer() |
| 66 | + used = str(round(stop - start, 5)) |
| 67 | + cols = "{0:20}{1:10}{2:10}" |
| 68 | + res = cols.format(executor.__name__, used, "seconds") |
| 69 | + print(f"\033[92m» {res}\033[0m") |
| 70 | + |
| 71 | + |
| 72 | +test() |
0 commit comments