Review the AI
Balanced Brackets
An interview favourite, three AI answers. Label each solution.Problem
balanced(s): s holds only ()[]. Return True if every bracket closes with the right kind in the right order: "([])" is fine, "([)]" is not.Solution A
1def balanced(s):
2 pairs = {")": "(", "]": "["}
3 stack = []
4 for ch in s:
5 if ch in pairs:
6 if not stack or stack.pop() != pairs[ch]:
7 return False
8 else:
9 stack.append(ch)
10 return not stack
Solution B
1def balanced(s):
2 return s.count("(") == s.count(")") and s.count("[") == s.count("]")
Solution C
1def balanced(s):
2 while "()" in s or "[]" in s:
3 s = s.replace("()", "").replace("[]", "")
4 return s == ""