Skip to content

Commit 7863b7f

Browse files
committed
LeetCode 24. Swap Nodes in Pairs
1 parent 78bfc97 commit 7863b7f

File tree

2 files changed

+75
-0
lines changed

2 files changed

+75
-0
lines changed

README.md

+3
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@ Solutions to LeetCode problems. The first column links to the problem in LeetCod
3535
| [21. Merge Two Sorted Lists][lc21] | 🟢 Easy | [![python](res/py.png)][lc21py] |
3636
| [22. Generate Parentheses][lc22] | 🟠 Medium | [![python](res/py.png)][lc22py] |
3737
| [23. Merge k Sorted Lists][lc23] | 🔴 Hard | [![python](res/py.png)][lc23py] |
38+
| [24. Swap Nodes in Pairs][lc24] | 🟠 Medium | [![python](res/py.png)][lc24py] |
3839
| [26. Remove Duplicates from Sorted Array][lc26] | 🟢 Easy | [![python](res/py.png)][lc26py] |
3940
| [27. Remove Element][lc27] | 🟢 Easy | [![python](res/py.png)][lc27py] |
4041
| [29. Divide two integers][lc29] | 🟠 Medium | [![python](res/py.png)][lc29py] |
@@ -373,6 +374,8 @@ Solutions to LeetCode problems. The first column links to the problem in LeetCod
373374
[lc22py]: leetcode/generate-parentheses.py
374375
[lc23]: https://leetcode.com/problems/merge-k-sorted-lists/
375376
[lc23py]: leetcode/merge-k-sorted-lists.py
377+
[lc24]: https://leetcode.com/problems/swap-nodes-in-pairs/
378+
[lc24py]: leetcode/swap-nodes-in-pairs.py
376379
[lc26]: https://leetcode.com/problems/remove-duplicates-from-sorted-array/
377380
[lc26py]: leetcode/remove-duplicates-from-sorted-array.py
378381
[lc27]: https://leetcode.com/problems/remove-element/

leetcode/swap-nodes-in-pairs.py

+72
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
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

Comments
 (0)