Balanced parenthesis in Ruby I'm solving the "Balanced Parenthesis" problem in Ruby, and I came up with this solution.

def balanced?(string)
  return false if string.length.odd?

  pairs = { '{' =&gt; '}', '[' =&gt; ']', '(' =&gt; ')' }

  string.chars.each_with_object([]) do |bracket, stack|
    if pairs.keys.include?(bracket)
      stack &lt;&lt; bracket
    elsif pairs.values.include?(bracket)
      return false unless pairs[stack.pop] == bracket
    else
      return false
    end
  end

  true
end


The first check is for the length of the string: If it's odd, the can't be balanced.

I then iterate over the chars of the string:


If I find an opening bracket, I add it to an array.
If I find a closing bracket, I remove the last element from the array and check if the brackets are a pair.
If I find neither an opening or a closing bracket, the string must be invalid.


Are there any edge cases I'm missing? Also, this doesn't seem efficient: First, there's an added dictionary. Second, there is a linear search on each iteration to check either the keys or the values of the dictionary. There's an \$O(n)\$ on the array resulting from the string, as well, but I'm not sure if we can avoid this.
To eliminate nested loop you may apply regex checking for invalid symbol from the start -- it would be O(n) + O(n) = O(n):

def balanced? string
  return false if string.length.odd?
  return false if string =~ /[^\[\]\(\)\{\}]/

  pairs = { '{' =&gt; '}', '[' =&gt; ']', '(' =&gt; ')' }

  stack = []
  string.chars do |bracket|
    if expectation = pairs[bracket]
      stack &lt;&lt; expectation
    else
      return false unless stack.pop == bracket
    end
  end

  stack.empty?
end