Data Structures & AlgorithmsHardInfosys SP/DSE · Product Company SDE
Problem: Return every value an arithmetic expression can take under all possible full parenthesisations (divide and conquer on each operator, memoised).
Problem: Return every value an arithmetic expression can take under all possible full parenthesisations (divide and conquer on each operator, memoised).
from functools import lru_cache
@lru_cache(None)
def ways(expr):
res = []
for i, c in enumerate(expr):
if c in "+-*":
for a in ways(expr[:i]):
for b in ways(expr[i + 1:]):
res.append(a + b if c == "+" else a - b if c == "-" else a * b)
return tuple(res) if res else (int(expr),)
print(sorted(ways("3-1*2+4")))What is printed?- A. [-3, -3, 5, 8, 12]
- B. [5]
- C. [-3, -3, 5, 8, 12, 14]
- D. [-3, 5, 8, 12]
Correct answer: A. [-3, -3, 5, 8, 12]
With 3 operators there are Catalan(3) = 5 bracketings: 3−(1·(2+4)) = −3, 3−((1·2)+4) = −3, (3−1)·(2+4) = 12, (3−(1·2))+4 = 5, ((3−1)·2)+4 = 8. Results are kept per bracketing, so −3 appears twice; a set would show 4 values. Normal precedence gives only 5. Growth is Catalan, ~4ⁿ/n^1.5.
More Coding Interview Problems questions
- Problem: A node is 'good' if no node on the path from the root to it has a greater value. Count good nodes. Trees are built from a…
- Problem: Exactly two keys of a BST were swapped by mistake. Find them with an inorder traversal: the first key is the left side of the…
- Problem: Trim a BST so that only keys in [lo, hi] remain (keeping BST structure), then print its preorder. Trees are built from a…
- Problem: Rebuild a BST from its preorder in O(n) using an upper bound per recursive call, then print its postorder and height (nodes on…
- Problem: Print the top view of a tree (the first node seen in each vertical column, left to right; root column 0, left child −1, right…
- Problem: Return the k-th permutation (1-based, lexicographic) of 1..n directly using the factorial number system. python from math import…