Data Structures & AlgorithmsHardProduct company OA · Amazon/Microsoft-style OA
What does this program print?
What does this program print?
a = [1, -1, 2, -2, 3]
seen = {0: 0}
s = 0; out = []
for i, x in enumerate(a, 1):
s += x
if s in seen:
out.append((seen[s], i))
else:
seen[s] = i
print(out)- A. [(0, 2), (2, 4)]
- B. [(0, 2), (0, 4)]
- C. [(0, 2), (1, 4)]
- D. [(0, 1), (2, 4)]
Correct answer: B. [(0, 2), (0, 4)]
The program records the first index of each prefix sum and reports a pair whenever a prefix repeats. The running sums after each element are 1, 0, 2, 0, 3, so the value 0 repeats at indices 2 and 4, each paired with the first occurrence at index 0.
More Coding Interview Problems questions
- What does this program print? python best = None s = 0 for x in [4, -2, -2, 3, -1]: s += x best = s if best is None else max(best, s)…
- Array [1, 3, 2, 6, 4, 5, 7, 8]. How many inversions does it have (index pairs i < j with a[i] > a[j])?
- Sequence [5, 2, 9, 1, 7, 3]. Consider only index pairs i < j with j - i <= 2. What is the largest value of |a[i] - a[j]| over these pairs?
- What is the length of the longest strictly increasing subsequence of [3, 1, 4, 1, 5, 9, 2, 6, 5, 3]? Use the patience-sorting method with…
- Sorted array [1, 2, 7, 8, 11, 15]. How many index triples i < j < k satisfy a[i] + a[j] + a[k] = 18?
- Four jobs have processing times [6, 3, 5, 2]. They run one at a time in some order, and job at position i (1-based) incurs cost i times…