Data Structures & AlgorithmsHardGATE CS · ICPC regional
Given an array that may contain negative numbers, which method counts the subarrays whose sum equals exactly k in O(n) expected time?
- A. Two pointers (sliding window)
- B. Prefix sums with a hash map of counts
- C. Binary search on the answer
- D. Monotonic stack
Correct answer: B. Prefix sums with a hash map of counts
Negative numbers break the monotonicity a sliding window needs, but prefix sums with counts handle any sign: each earlier equal prefix value pairs with the current one.
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
- Which structure returns the maximum of every window of size k in a sliding pass in O(n) total time?
- To test whether string s2 is a rotation of string s1 in linear time, which approach is standard?
- For each element of an array of distinct integers, the task is to count how many earlier elements are smaller. Which structure achieves…
- What is the length of the longest common subsequence of the three strings "ABCBDAB", "BDCABA" and "BCADB"?
- How many non-empty subsequences of "abcbab" (chosen by index, so the same letters at different positions count as different subsequences)…
- How many index triples i < j < k in [3, 1, 4, 1, 5, 9, 2, 6] satisfy a[i] < a[j] < a[k] (strictly increasing)?