-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMinValueInConstantTime.cs
More file actions
71 lines (61 loc) · 1.83 KB
/
MinValueInConstantTime.cs
File metadata and controls
71 lines (61 loc) · 1.83 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
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Stacks
{
/// <summary>
/// Get minimum value from stack in constant time.
/// </summary>
[TestClass]
public class MinValueInConstantTime
{
private Stack<int> stack = new Stack<int>();
private Stack<int> auxillaryStack = new Stack<int>();
public int GetMinimumValue()
{
return this.auxillaryStack.Peek();
}
public void Push(int value)
{
this.stack.Push(value);
// Use the aux stack (2nd) to push the value if the top of the aux stack is less than the value.
// Also push to aux stack if the stack is empty.
if (this.auxillaryStack.Count == 0 || this.auxillaryStack.Peek() > value)
{
this.auxillaryStack.Push(value);
}
else
{
int auxValue = this.auxillaryStack.Peek();
this.auxillaryStack.Push(auxValue);
}
}
public int Pop()
{
int value = this.stack.Pop();
// remove from the aux stack if the value is equal to the top of the stack.
if (this.auxillaryStack.Peek() == value)
{
this.auxillaryStack.Pop();
}
return value;
}
[TestMethod]
public void TestGetMinimumInConstantTime()
{
this.Push(10);
this.Push(8);
this.Push(11);
this.Push(5);
this.Push(2);
this.Push(20);
this.Push(17);
this.Push(1);
int value = this.GetMinimumValue();
Assert.AreEqual(value, 1);
}
}
}