Data Structures & AlgorithmsEasyTCS NQT Digital · Product Company SDE
Problem: Check whether a string of brackets ()[]{} is balanced.
Problem: Check whether a string of brackets ()[]{} is balanced.
def balanced(s):
pair = {')': '(', ']': '[', '}': '{'}
st = []
for ch in s:
if ch in pair:
if not st or st.pop() != pair[ch]:
return False
else:
st.append(ch)
return not st
print(balanced("{[()()]}"), balanced("([)]"), balanced("(("))What is printed?- A. True True False
- B. True False False
- C. True False True
- D. False False False
Correct answer: B. True False False
Push openers; a closer must match the most recent opener. "([)]" closes '(' while '[' is on top → False. "((" never fails during the scan but leaves items on the stack, so the final 'return not st' check makes it False – forgetting that check gives True. O(n).
More Coding Interview Problems questions
- Problem: For each day's temperature, find how many days you must wait for a warmer day (0 if never). python def wait(t): res, st = [0]…
- Problem: Find the largest rectangle that fits under a histogram of bar heights. python def largest(h): st, best = [], 0 for i, x in…
- Problem: Evaluate an expression in Reverse Polish notation; division truncates toward zero. python def rpn(tokens): st = [] for t in…
- Problem: Simulate asteroids on a line: positive moves right, negative left; on collision the smaller explodes, equal sizes both explode…
- Problem: Remove k digits from a number string to make the smallest possible number (no leading zeros in the result, "0" if empty). python…
- Problem: Design a stack that returns its minimum in O(1). The implementation below stores pairs. python st = [] def push(x): st.append((x…