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?
  1. A. [-3, -3, 5, 8, 12]
  2. B. [5]
  3. C. [-3, -3, 5, 8, 12, 14]
  4. 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

Exams that ask this topic