Data Structures & AlgorithmsVery hardGoldman Sachs OA · LeetCode medium-hard
Problem: Insert +, − or between the digits of num (or leave digits joined) so that the expression equals target. Count the expressions (no operand may have a leading zero).
Problem: Insert +, − or * between the digits of num (or leave digits joined) so that the expression equals target. Count the expressions (no operand may have a leading zero).
def count(num, target):
res = 0
def go(i, val, last):
nonlocal res
if i == len(num):
res += val == target; return
for j in range(i + 1, len(num) + 1):
s = num[i:j]
if len(s) > 1 and s[0] == '0': break
x = int(s)
if i == 0: go(j, x, x)
else:
go(j, val + x, x); go(j, val - x, -x)
go(j, val - last + last * x, last * x)
go(0, 0, 0)
return res
print(count("2322", 10))What is printed?- A. 1
- B. 3
- C. 2
- D. 4
Correct answer: D. 4
Tracking the last operand lets '*' undo it: val − last + last·x respects precedence. For '2322' and 10 the expressions are 2+3*2+2, 2*3+2+2, 2*3+2*2 and 2*3*2-2: 4 in all, matching a brute force over all 4³ operator choices. Evaluating strictly left to right would accept wrong ones such as 2+3*2-… and miss precedence.
More Coding Interview Problems questions
- Problem: Check whether a number is a power of four with bit tricks. python def p4(n): return n > 0 and n & (n - 1) == 0 and n & 0x55555555…
- Problem: A number is 'happy' if repeatedly replacing it by the sum of the squares of its digits reaches 1. Cycle detection uses a set…
- Problem: Break n into at least two positive integers to maximise their product. python def brk(n): dp = [0, 1] + [0] (n - 1) for i in…
- A suffix array of a string of length n is built by putting all suffixes in a list and sorting them with a comparison sort, where each…
- What is the solution of T(n) = T(n/2) + T(n/4) + n?
- Edge case: Java's int arithmetic wraps around in two's complement. The Python code below emulates exactly what this Java line computes…