Data Structures & AlgorithmsHardProduct Company SDE pattern
What is printed? (difference array for range increments)
What is printed? (difference array for range increments)
n = 6
diff = [0] * (n + 1)
for l, r, v in [(0, 2, 5), (1, 4, 3), (3, 5, -2)]:
diff[l] += v; diff[r + 1] -= v
a, run = [], 0
for i in range(n):
run += diff[i]; a.append(run)
print(a)- A. [5, 8, 8, 1, 1, -2]
- B. [5, 8, 8, 3, 3, -2]
- C. [5, 8, 8, 1, 1, 0]
- D. [5, 3, 0, -2, 0, 2]
Correct answer: A. [5, 8, 8, 1, 1, -2]
Each range update touches two cells of the difference array; a final prefix sum rebuilds the values. Index 3: +3 − 2 = 1; index 5: −2 only. O(1) per update and O(n) to rebuild, instead of O(length) per update.
Practise more Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questionsArrays, Strings, Linked Lists, Stacks, Queues and Hashing: notes and key points
More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions
- What is printed? (Python sort stability with a key) python recs = [("amit", 82), ("bina", 90), ("chirag", 82), ("dev", 75), ("esha", 90)]…
- What is printed? (finding the k-th node from the end with two pointers) python vals = [11, 22, 33, 44, 55, 66] def kthend(k): lead = trail…
- What is printed? (C: array passed to a function decays to a pointer) c void f(int a[]) { printf("%zu ", sizeof(a) / sizeof(a[0])); } int…
- What is printed? (balanced brackets with a counter only) python def bycounter(s): c = 0 for ch in s: c += 1 if ch == '(' else -1 if c < 0…
- What is printed? (string rotation check) python def isrot(a, b): return len(a) == len(b) and b in a + a print(isrot("waterbottle"…
- What is printed? (sliding window: count subarrays with product less than k, positive values) python def countprod(a, k): if k <= 1: return…