Valid Parentheses

Determine if the input string of brackets is valid.

Easy

Examples

Example 1: "()[]{}" → true
Example 2: "(]" → false

Implementation

Ruby

  # 1. Valid Parentheses
  # Problem: Determine if the input string of brackets is valid.
  # Input: "()[]{}", Output: true
  # Input: "(]", Output: false
  # Time Complexity: O(n)
  def valid_parentheses(s)
    stack = []
    map = { ")" => "(", "}" => "{", "]" => "[" }
    s = s.gsub(/[^()\[\]{}]/, "") # remove all non parentheses characters
    s.each_char.with_index do |char, idx|
      if map.values.include?(char)
        stack.push(char)
        puts "Stack after push #{idx}: #{stack.inspect}"
      elsif map.keys.include?(char)
        top = stack.pop
        puts "Stack after pop #{idx}: #{stack.inspect} (popped: #{top})"
        return false if top != map[char]
      end
    end
    stack.empty?

Complexity Analysis

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

Patterns & Techniques

Problem Details

Category: Stack Queue Problems
Difficulty: Easy
Module: StackQueueProblems
Method: valid_parentheses
← Back to Stack Queue Problems