Amazon Interview Question
Software Engineer / DevelopersCountry: United States
Interview Type: Phone Interview
public class StackWithQueue
{
private Queue<char> Q1= new Queue<char>();
private Queue<char> Q2 = new Queue<char>();
public void Push(char ch)
{
if (Q1.Count == 0)
{
Q1.Enqueue(ch);
MoveQItems(Q2,Q1); // Move items from Q2 to Q1
}
else
{
Q2.Enqueue(ch);
MoveQItems(Q1, Q2);
}
}
public char Pop()
{
if (Q1.Count != 0)
{
return Q1.Dequeue();
}
else if (Q2.Count != 0)
{
return Q2.Dequeue();
}
return ' ';
}
private void MoveQItems(Queue<char> a, Queue<char> b)
{
while (a.Count != 0)
{
b.Enqueue(a.Dequeue());
}
}
}
Q1 and Q2
- soconfusedgrad October 31, 2012For O(1) push() and O(N) pop():
1. Enqueue into Q1.
2. If pop, check size of Q1, if size > 1, dequeue into Q2 until size == 1
3. Dequeue from Q1, return result
4. Switch back and forth
For O(N) push() and O(1) pop():
1. push() -> Enqueue into Q1
2. push() -> Enqueue into Q2, and Dequeue Q1 into Q2
3. repeat back and forth
4. pop() -> Dequeue from the Q that has element