Check if a string has balanced brackets?
Short answer: public bool IsBalanced(string s) { Stack<char> stack = new Stack<char>(); Dictionary<char, char> pairs = new Dictionary<char, char> { {')', '('}, {']', '['}, {'}', '{'} }; foreach (char c in s) { if ("([{".Contains(c)) stack.Push(c); else if (")]}".Contains(c)) { if (stack.Count == 0 || stack.Pop() != pairs[c]) return false; } } return stack.Count == 0; } Follow on: Explanation: Use a stack to match opening and…
Example code
public bool IsBalanced(string s) {
Stack<char> stack = new Stack<char>();
Dictionary<char, char> pairs = new Dictionary<char, char> { {')', '('}, {']', '['}, {'}', '{'} }; foreach (char c in s) {
if ("([{".Contains(c)) stack.Push(c); else if (")]}".Contains(c)) { if (stack.Count == 0 || stack.Pop() != pairs[c])
return false;
}
}
return stack.Count == 0;
} Follow on: Explanation: Use a stack to match opening and closing brackets properly.
Real-world example (ShopNest)
In coding rounds, state complexity aloud, write a clear ShopNest-flavored example (orders, carts), then handle edge cases (empty list, null, overflow).
Say this in the interview
- Define — one clear sentence (the short answer above).
- Example — relate it to a project like ShopNest or your real work.
- Trade-off — when you would not use it.
Share this Q&A
Share preview image: https://www.toolliyo.com/images/toolliyo-logo.png