DEV Community

seonglinchua
seonglinchua

Posted on

Mastering Stack<T> in C# for Coding Interviews

๐Ÿงฑ Stack in C# โ€” Solving Problems the LIFO Way

A Stack<T> is a Last-In-First-Out (LIFO) collection โ€” the last element added is the first one removed. It's commonly used in parsing, expression evaluation, and backtracking.


โœ… When to Use Stack

Use Case Why Use Stack
Reversing elements Natural LIFO behavior
Nested structures / matching e.g., parentheses, XML, recursion stack
Backtracking Push state, pop to revert
Undo features Store previous states

โœ๏ธ Declaring and Using Stack

var stack = new Stack<int>();

stack.Push(10);        // Add to top
stack.Push(20);
int top = stack.Peek(); // Peek top (20)
stack.Pop();            // Remove top (20)
Enter fullscreen mode Exit fullscreen mode

๐Ÿ” Iterating Through Stack

foreach (int item in stack)
{
    Console.WriteLine(item);
}
Enter fullscreen mode Exit fullscreen mode

๐Ÿงช Interview Example 1: Valid Parentheses

public bool IsValid(string s)
{
    var stack = new Stack<char>();
    var map = new Dictionary<char, char> {
        {')', '('}, {']', '['}, {'}', '{'}
    };

    foreach (char c in s)
    {
        if (map.ContainsValue(c))
            stack.Push(c);
        else if (map.ContainsKey(c))
        {
            if (stack.Count == 0 || stack.Pop() != map[c])
                return false;
        }
    }

    return stack.Count == 0;
}
Enter fullscreen mode Exit fullscreen mode

๐Ÿงช Interview Example 2: Evaluate Reverse Polish Notation

public int EvalRPN(string[] tokens)
{
    var stack = new Stack<int>();

    foreach (var token in tokens)
    {
        if (int.TryParse(token, out int num))
            stack.Push(num);
        else
        {
            int b = stack.Pop();
            int a = stack.Pop();
            switch (token)
            {
                case "+": stack.Push(a + b); break;
                case "-": stack.Push(a - b); break;
                case "*": stack.Push(a * b); break;
                case "/": stack.Push(a / b); break;
            }
        }
    }

    return stack.Pop();
}
Enter fullscreen mode Exit fullscreen mode

๐Ÿ“Œ Summary

Feature Syntax Example
Declare new Stack<T>()
Push stack.Push(value)
Pop stack.Pop()
Peek stack.Peek()
Count stack.Count
Iterate foreach (var item in stack)

Up next: Queue and Deque โ€” perfect for BFS traversal and sliding window problems!

Top comments (2)

Collapse
 
davinceleecode profile image
davinceleecode

These interview problems are reminding me of LeetCode ๐Ÿ˜….

Collapse
 
ghost_engineer_2883a1ca0a profile image
Ghost Engineer

try this if you get stuck during the interview. its an AI co-pilot that solves the questions for you so you can focus on the more important part of the interview, the communication part. its also a really good study tool: ghostengineer.com