মূল কনটেন্টে যান
🛰️
রিমোট DSA
প্যাটার্নটপিক 4 · Stacks & Queues

4.2 Expression Evaluation / Parentheses

চিনবেন কীভাবে
"valid parentheses", "evaluate expression", nesting/matching, infix/postfix, "backspace" — push what opens onto a stack, match and pop when it closes
Demo · approach · কোড — আগে নিজে চেষ্টা, আটকালে খুলুন

Demo: Longest Valid ParenthesesLC 32 (Hard — Google High)

Statement (Demo): Given a string s of only '(' and ')', return the length of the longest valid parentheses substring. Example: s=")()())"4 | ⚡ len ≤ 3×10⁴

Approach: Keep indices on a stack with -1 at the bottom as a base. Push on (. On ) pop — if the stack is now empty, this ) becomes the new base; otherwise the current valid length is i - stack.top.

function longestValidParentheses(s) {
  const stack = [-1]; // base index
  let best = 0;
  for (let i = 0; i < s.length; i++) {
    if (s[i] === "(") stack.push(i);
    else {
      stack.pop();
      if (stack.length === 0)
        stack.push(i); // new base
      else best = Math.max(best, i - stack[stack.length - 1]);
    }
  }
  return best;
}

Complexity: Time O(n), Space O(n)

প্রবলেম

  • Statement: Given a string s of only '(', ')', '{', '}', '[', ']', return whether every bracket closes in the correct order.
    Example: s="()[]{}"true | ⚡ len ≤ 10⁴

    নোট · ফাঁকা
  • Backspace String CompareLC 844
    (stack, or two pointers from the back in O(1) space)

    Statement: Given strings s and t where # is a backspace, return whether both produce the same text when typed into an editor.
    Example: s="ab#c", t="ad#c"true (both are "ac") | ⚡ len ≤ 200

    নোট · ফাঁকা