Skip to main content

2. Valid Parentheses

easyAsked at Flipkart

Validate that opening and closing brackets are balanced — Flipkart uses this to test stack intuition before scaling to nested order-state machines.

By Alex Chen, Founder, InterviewChamp.AI · Last verified

Problem

Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. An input is valid if brackets are closed in the correct order and every opening has a matching close.

Constraints

  • 1 <= s.length <= 10^4
  • s consists of parentheses only

Examples

Example 1

Input
s = "()[]{}"
Output
true

Example 2

Input
s = "(]"
Output
false

Approaches

1. Replace pairs

Repeatedly strip matched pairs until stable.

Time
O(n^2)
Space
O(n)
while (s.includes('()')||s.includes('[]')||s.includes('{}'))
  s = s.replace(/\(\)|\[\]|\{\}/g,'');
return s.length===0;

Tradeoff:

2. Stack

Push opens, pop on close and verify match. Linear single pass.

Time
O(n)
Space
O(n)
function isValid(s) {
  const stack = [];
  const pair = { ')': '(', ']': '[', '}': '{' };
  for (const c of s) {
    if (c in pair) {
      if (stack.pop() !== pair[c]) return false;
    } else {
      stack.push(c);
    }
  }
  return stack.length === 0;
}

Tradeoff:

Flipkart-specific tips

Flipkart interviewers grade hard on edge cases like empty input and odd-length strings — both are early-exit wins in their checkout-validator codebases.

Solve it now

Free. No sign-up. Python and JavaScript run instantly in your browser.

Output

Press Run or Cmd+Enter to execute

Practice these live with InterviewChamp.AI

Drill Valid Parentheses and other Flipkart interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →