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 = { '{' => '}', '[' => ']', '(' => ')' }  string.chars.each_with_object([]) do |bracket, stack|    if pairs.keys.include?(bracket)      stack << bracket    elsif pairs.values.include?(bracket)      return false unless pairs[stack.pop] == bracket    else      return false    end  end  trueendThe 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.
Balanced parenthesis in Ruby
algorithm;ruby;stack;balanced delimiters
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 = { '{' => '}', '[' => ']', '(' => ')' }  stack = []  string.chars do |bracket|    if expectation = pairs[bracket]      stack << expectation    else      return false unless stack.pop == bracket    end  end  stack.empty?end