DEV Community

seonglinchua
seonglinchua

Posted on

1

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

👋 Kindness is contagious

Delve into a trove of insights in this thoughtful post, celebrated by the welcoming DEV Community. Programmers of every stripe are invited to share their viewpoints and enrich our collective expertise.

A simple “thank you” can brighten someone’s day—drop yours in the comments below!

On DEV, exchanging knowledge lightens our path and forges deeper connections. Found this valuable? A quick note of gratitude to the author can make all the difference.

Get Started