Data Structures & AlgorithmsHard
How many contiguous subarrays of [1, 2, 1, 3, 3, 2, 2, 1] contain at most 2 distinct values?
- A. 8
- B. 11
- C. 36
- D. 21
Correct answer: D. 21
A sliding window with a count map gives the at-most-k count, but it must add right−left+1 per right end, not one per right end. The exactly-2 count and the at-most-3 count are different quantities and are common confusions.
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
- For the array [1, 3, 2, 6, 7, 4, 8, 12, 5], how many index pairs i < j have (J[i] + J[j]) divisible by 4?
- In the binary array [1, 0, 0, 1, 0, 1, 1, 0, 0, 0], how many contiguous subarrays contain equal numbers of 0s and 1s?
- What is the length of the longest contiguous subarray of [2, -4, 3, 1, 6, -2, 5, 4] whose sum is divisible by 6?
- How many contiguous subarrays of [1, 2, 1, 3, 4, 2, 3] contain no repeated value?
- Count the inversions of [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]: pairs of positions i < j with N[i] > N[j]. Equal values are not inversions.
- How many indices i satisfy: the sum of the elements before i equals the sum of the elements after i, excluding P2[i] itself? (P2 = [1, 2…