forked from keon/algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstutter.py
More file actions
68 lines (51 loc) · 1.61 KB
/
stutter.py
File metadata and controls
68 lines (51 loc) · 1.61 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
"""
Stutter
Replace every value in a stack with two occurrences of that value.
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_stutter(stack: list[int]) -> list[int]:
"""Stutter a stack using an auxiliary stack.
Args:
stack: A list representing a stack (bottom to top).
Returns:
The stack with each value duplicated.
Examples:
>>> first_stutter([3, 7, 1, 14, 9])
[3, 3, 7, 7, 1, 1, 14, 14, 9, 9]
"""
storage_stack: list[int] = []
for _ in range(len(stack)):
storage_stack.append(stack.pop())
for _ in range(len(storage_stack)):
val = storage_stack.pop()
stack.append(val)
stack.append(val)
return stack
def second_stutter(stack: list[int]) -> list[int]:
"""Stutter a stack using an auxiliary queue.
Args:
stack: A list representing a stack (bottom to top).
Returns:
The stack with each value duplicated.
Examples:
>>> second_stutter([3, 7, 1, 14, 9])
[3, 3, 7, 7, 1, 1, 14, 14, 9, 9]
"""
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)):
val = queue.pop()
stack.append(val)
stack.append(val)
return stack