Queue using Two Stacks

  • + 0 comments

    My C# solution

    Spent ages trying to find input from args when it actually comes from Console.ReadLine. Had to read up on two stacks before attempting question. Was failing a few test cases on time limit until I switched from using linq .Any() to checking .Count > 0

    class Solution {
        static void Main(String[] args) {
            /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution */
            (Stack<int> stack1, Stack<int> stack2) = (new(), new());
    
            var numberOfInputs = Int32.Parse(Console.ReadLine()!);
            
            for (int _ = 0; _ < numberOfInputs; _++)
            {
                var arg = Console.ReadLine()!.Split();
                switch(arg[0])
                {
                    case "1":
                        var enqueueValue = Int32.Parse(arg[1]);
                        stack1.Push(enqueueValue);
                        continue;
                    case "2":
                    case "3":
                        if (stack2.Count == 0) 
                        {
                            while(stack1.Count > 0)
                            {
                                stack2.Push(stack1.Pop());
                            }
                        }
                        if (arg[0] == "3")
                        {
                            Console.WriteLine(stack2.Count > 0 ? stack2.Peek() : stack1.Peek());
                            continue; 
                        }
                        stack2.Pop(); 
                        continue;
                    default:
                      throw new ArgumentException("Ffs Hackerrank");
                }
            }
        }
    }