Data Structures & AlgorithmsModerateTCS NQT · prefix sums
Problem: How many contiguous subarrays of [1, 2, 3, 4, 5] have sum exactly 5? Run the code.
Problem: How many contiguous subarrays of [1, 2, 3, 4, 5] have sum exactly 5? Run the code.
a = [1, 2, 3, 4, 5] print(sum(1 for i in range(len(a)) for j in range(i, len(a)) if sum(a[i:j + 1]) == 5))What is printed?
- A. 2
- B. 1
- C. 3
- D. 4
Correct answer: A. 2
The qualifying subarrays are [2, 3] and [5], so the answer is 2. The subarray [1, 2, 3] sums to 6, which is not 5, and the prefix-sum hash count gives the same result.
More Coding Interview Problems questions
- Problem: What is the length of the longest zigzag subsequence (values alternate strictly up and down) of [1, 7, 4, 9, 2, 5]? Run the DP…
- Problem: Two piles of stones (values [1, 6, 11, 5]) are to be divided into two groups whose sums differ as little as possible. What is the…
- Problem: You have 2 eggs and a building with 10 floors. What is the minimum number of drops needed in the worst case to find the highest…
- Problem: How many distinct ways can the string 'leetcode' be segmented into words from the dictionary {'leet', 'code', 'leetcode', 'lee'…
- Problem: Count the connected components of the undirected graph on 6 vertices with edges (0,1), (1,2), (3,4), (5,5) using DFS. Run the…
- Problem: Check whether the directed graph with edges 0->1, 1->2, 2->0, 2->3 contains a cycle using Kahn's algorithm (count the nodes that…