Valid Parentheses

Algorithms
Easy
Apple
72.1K views

Given a string `s` containing just '(', ')', '{', '}', '[' and ']', determine if the input string is valid. Must use a Stack data structure.

Why Interviewers Ask This

Apple interviewers ask this to evaluate a candidate's ability to model real-world hierarchical structures using fundamental data structures. They specifically test if you can recognize patterns requiring Last-In-First-Out (LIFO) logic, such as nested scopes or matching pairs. The question assesses your grasp of stack operations, edge case handling like empty strings or mismatched brackets, and your capacity to write clean, efficient code under pressure without relying on complex libraries.

How to Answer This Question

1. Clarify Requirements: Immediately confirm the input constraints, such as whether the string can be null or empty, and define what constitutes 'valid' nesting (e.g., every opening bracket must have a corresponding closing one in the correct order). 2. Choose the Right Tool: Explicitly state that a Stack is the optimal choice because it naturally handles the LIFO requirement for nested structures, ensuring O(n) time complexity. 3. Define the Logic: Outline your algorithm: iterate through the string, push opening brackets onto the stack, and for closing brackets, check if they match the top of the stack. If they match, pop; otherwise, return false immediately. 4. Handle Edge Cases: Mention specific scenarios like an odd-length string, a stack that isn't empty at the end, or a string starting with a closing bracket. 5. Walk Through an Example: Verbally trace the logic with a concrete example like '{[()]}' to demonstrate your thought process clearly before writing code.

Key Points to Cover

  • Explicitly identifying the Stack as the required data structure due to LIFO properties
  • Demonstrating O(n) time complexity by iterating through the string only once
  • Handling the immediate failure condition when a closing bracket does not match the most recent opening bracket
  • Checking for an empty stack at the end of iteration to ensure no unclosed brackets remain
  • Addressing edge cases like empty input strings or odd-length inputs proactively

Sample Answer

To solve the Valid Parentheses problem efficiently, I would use a Stack data structure. This approach aligns perfectly with Apple's emphasis on elegant, low-level solutions that are both performant and easy to understand. My strategy involves a single pass through the string with O(n) time complexity. First, I will initialize an empty stack. As I iterate through each character in the input string, I need to distinguish between opening and closing delimiters. If I encounter an opening bracket—such as '(', '{', or '['—I simply push it onto the stack. This records the expectation of what comes next. When I hit a closing bracket, the logic becomes critical. I must first check if the stack is empty; if it is, there is no matching opening bracket, so the string is invalid. If the stack is not empty, I peek at the top element. I compare this top element against the current closing bracket. If they form a valid pair—for instance, '(' matches ')'—I pop the stack. If they do not match, or if the types don't align, the sequence is broken, and I return false immediately. Finally, after processing all characters, I check if the stack is empty. A non-empty stack means there are unmatched opening brackets remaining, indicating an invalid string. For example, tracing '{[()]}' works smoothly: we push '{', '[', '(', then pop them in reverse order as we see ')', ']', '}'. This ensures strict structural integrity.

Common Mistakes to Avoid

  • Using a simple counter instead of a stack, which fails to handle different bracket types correctly
  • Forgetting to check if the stack is empty before popping, leading to runtime errors on invalid inputs
  • Neglecting to verify the final stack state, resulting in false positives for strings like '(()'
  • Hardcoding specific bracket pairs without a flexible mapping mechanism, making the code brittle

Practice This Question with AI

Answer this question orally or via text and get instant AI-powered feedback on your response quality, structure, and delivery.

Start Practicing

Related Interview Questions

Browse all 145 Algorithms questionsBrowse all 54 Apple questions