forked from keon/algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathswitch_pairs.py
More file actions
80 lines (64 loc) · 2.04 KB
/
switch_pairs.py
File metadata and controls
80 lines (64 loc) · 2.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
"""
Switch Pairs
Switch successive pairs of values in a stack starting from the bottom.
If there is an odd number of values, the top element is not moved.
Two approaches: one using an auxiliary stack, one using an auxiliary queue.
Reference: https://en.wikipedia.org/wiki/Stack_(abstract_data_type)
Complexity:
Time: O(n)
Space: O(n)
"""
from __future__ import annotations
import collections
def first_switch_pairs(stack: list[int]) -> list[int]:
"""Switch successive pairs using an auxiliary stack.
Args:
stack: A list representing a stack (bottom to top).
Returns:
The stack with successive pairs swapped.
Examples:
>>> first_switch_pairs([3, 8, 17, 9, 1, 10])
[8, 3, 9, 17, 10, 1]
"""
storage_stack: list[int] = []
for _ in range(len(stack)):
storage_stack.append(stack.pop())
for _ in range(len(storage_stack)):
if len(storage_stack) == 0:
break
first = storage_stack.pop()
if len(storage_stack) == 0:
stack.append(first)
break
second = storage_stack.pop()
stack.append(second)
stack.append(first)
return stack
def second_switch_pairs(stack: list[int]) -> list[int]:
"""Switch successive pairs using an auxiliary queue.
Args:
stack: A list representing a stack (bottom to top).
Returns:
The stack with successive pairs swapped.
Examples:
>>> second_switch_pairs([3, 8, 17, 9, 1, 10])
[8, 3, 9, 17, 10, 1]
"""
queue: collections.deque[int] = collections.deque()
for _ in range(len(stack)):
queue.append(stack.pop())
for _ in range(len(queue)):
stack.append(queue.pop())
for _ in range(len(stack)):
queue.append(stack.pop())
for _ in range(len(queue)):
if len(queue) == 0:
break
first = queue.pop()
if len(queue) == 0:
stack.append(first)
break
second = queue.pop()
stack.append(second)
stack.append(first)
return stack