Data Structures & AlgorithmsModerate
How many contiguous subarrays of positive integers [2, 1, 4, 3, 1, 2] have a sum at most 6?
- A. 11
- B. 10
- C. 5
- D. 12
Correct answer: A. 11
With positive values a two-pointer window shrinks while the sum is too large, and each right end adds (right − left + 1) valid starts. Adding the left index instead of a width, or using < instead of ≤, changes the count.
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
- How many contiguous subarrays of [2, 4, 1, 3, 5, 2] have a sum in the closed range [5, 9]?
- In the array [2, 3, 1, 2, 4, 3] (all positive), what is the length of the shortest contiguous subarray whose sum is at least 7?
- How many contiguous subarrays of [1, 5, 2, 8, 3, 7] have a sum divisible by their own length?
- For [2, 3, 4, 6, 9, 5, 12], how many index pairs i < j have the product BB[i]·BB[j] divisible by 6?
- How many contiguous subarrays of [5, 5, 3, 3, 6, 6, 6] have XOR equal to 0?
- How many index pairs i < j in [1, 5, 3, 3, 3, 7, 2, 4, 6] have DD[i] + DD[j] = 6? Equal values at different indices are different pairs.