Data Structures & AlgorithmsModerateTCS NQT · stack basics
Problem: Check bracket balance for '([]{})' and '([)]' with a stack. What is printed?
Problem: Check bracket balance for '([]{})' and '([)]' with a stack. What is printed?
def ok(s):
pairs = {')': '(', ']': '[', '}': '{'}
st = []
for c in s:
if c in '([{':
st.append(c)
elif not st or st.pop() != pairs[c]:
return False
return not st
print(ok('([]{})'), ok('([)]'))What is printed?- A. True True
- B. False False
- C. False True
- D. True False
Correct answer: D. True False
The first string nests correctly, while in '([)]' the ')' closes a '(' that is not on top of the stack. The stack check catches interleaving, not just count mismatches.
More Coding Interview Problems questions
- Problem: Sum the values of the next greater element of each position in [2, 1, 4, 3], where a position with no greater element contributes…
- Problem: Using at most one flip of a 0 to 1, what is the longest run of consecutive 1s in [1, 0, 1, 1, 0, 1]? Run the sliding-window code…
- Problem: How many unordered pairs of words in ['abc', 'bca', 'xyz', 'cab'] are anagrams of each other? Run the code. python from itertools…
- Problem: How many subsets of [1, 2, 3, 4, 5] have a sum of exactly 7? Run the code. python from itertools import combinations a = [1, 2…
- Problem: What is the length of the longest arithmetic subsequence of [1, 3, 5, 7, 4]? Run the O(n^2) DP code. python a = [1, 3, 5, 7, 4] n…
- Problem: What is the minimum path sum from the top to the bottom of the triangle [[2], [3, 4], [6, 5, 7], [4, 1, 8, 3]], moving to an…