Elements of Programming Interviews in Scala (Chapter 8)
Problem 8.1
Design a stack that supports a max operation. Time complexity must be O(1), memory complexity O(n).
Solution
Use a second stack to keep track of the maximum value, operate on it when operating on the other stack. Since stacks have O(1) time complexity, two stacks will still have O(1) time complexity.
Problem 8.2
Write a function that takes an arithmetic expression in Reverse Polish Notation and evaluates it.
Problem 8.5
Write a function that lists a sequence of operations to solve the Tower of Hanoi. Manual working of the solution below. For convenience, I’ve labelled the rings with a number. The constraint that we can’t put a larger ring on a smaller ring can than easily be expressed numerically.
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
1
2
3
4
5
6 . .
2
3
4
5
6 1 .
1 operation
2
3 3 3
4 4 4
5 5 5 1
6 1 . -> 6 1 2 -> 6 . 2
2 operations
1 1
3 2 2 2 2
4 4 4 4 4 4 4 4 4 1
5 1 5 1 5 1 5 1 5 5 5 5 2 5 2
6 . 2 -> 6 3 2 -> 6 3 2 -> 6 3 . -> 6 3 . -> 6 . 3 -> 6 1 3 -> 6 1 3 -> 6 . 3
3 1 1
4 4 4 4 4 1
5 1 5 1 5 5 2 5 2
6 . 2 -> 6 3 2 -> 6 3 2 -> 6 3 . -> 6 3 .
4 operations
1 1 1
4 1 1 2 2 2 2 2 2
5 2 5 2 5 2 1 5 1 5 5 3 5 3 5 3 5 3
6 3 . -> 6 3 4 -> 6 3 4 -> 6 3 4 -> 6 3 4 -> 6 . 4 -> 6 1 4 -> 6 1 4 -> 6 . 4
8 operations
1 1 1 1
2 2 2 1 1 2 2 2 2 1
5 3 3 1 3 1 2 3 2 3 3 2 3 2 1 3 1 3 3 4 3 4
6 . 4 -> 6 5 4 -> 6 5 4 -> 6 5 4 -> 6 5 4 -> 6 5 4 -> 6 5 4 -> 6 5 4 -> 6 5 4 -> 6 5 . -> 6 5 . ->
1
2 2
1 3 3 3 3
3 4 3 4 1 4 1 1 4 1 4 4
6 5 2 -> 6 5 2 -> 6 5 2 -> 6 5 2 -> 6 5 . -> 6 5 .
16 operations
etc.
The solution is:
- Recursively transfer n - 1 rings from P1 to P3 using P2.
- Transfer ring n - 1 from P1 to P2
- Recursively transfer n - 1 rings from P3 to P2 using P1.
In code:
Did you like that post?
You can suscribe to the
RSS feed
.