Data Structures & AlgorithmsModerateTCS NQT · Infosys pattern
What is printed? (prefix sums for range queries)
What is printed? (prefix sums for range queries)
a = [3, -2, 5, 1, -4, 6] P = [0] for x in a: P.append(P[-1] + x) q = [(0, 2), (1, 4), (3, 5), (5, 5)] print([P[r + 1] - P[l] for l, r in q])
- A. [6, 0, 3, 0]
- B. [1, 0, 3, 6]
- C. [6, 0, 3, 6]
- D. [6, -4, 3, 6]
Correct answer: C. [6, 0, 3, 6]
P = [0, 3, 1, 6, 7, 3, 9]. Sum a[l..r] = P[r + 1] − P[l]: (0,2) → 6, (1,4) → 3 − 3 = 0, (3,5) → 9 − 6 = 3, (5,5) → 9 − 3 = 6. Using P[r] − P[l] drops the last element. O(1) per query after O(n) setup.
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? (difference array for range increments) python n = 6 diff = [0] (n + 1) for l, r, v in [(0, 2, 5), (1, 4, 3), (3, 5…
- 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"…