Data Structures & AlgorithmsVery hardProduct company OA
You must count pairs i < j with a[i] + a[j] ≤ T for n ≤ 2·10⁵ values up to 10⁹ in absolute value (time limit 1 s). Which plan passes?
- A. Nested loops over all pairs – about 2·10¹⁰ simple additions finish within 1 s in C++
- B. A hash map of complements as in two-sum, since a hash lookup answers '≤ T' in O(1)
- C. Prefix sums of the sorted array, since the number of valid pairs equals the prefix sum at index T
- D. Sort, then two pointers: for each left index move the right pointer down while the sum exceeds T and add (right − left) – O(n log n)
Correct answer: D. Sort, then two pointers: for each left index move the right pointer down while the sum exceeds T and add (right − left) – O(n log n)
After sorting, if a[l] + a[r] ≤ T then every partner l + 1..r works for l, so each step either fixes l's count or discards r – both pointers move at most n times. n²/2 = 2·10¹⁰ pairs is ~100× too many for 1 s. A hash map answers equality queries only, not ranges. Prefix sums of VALUES say nothing about pair counts, and T is a value, not an index. Note that the answer can reach ~2·10¹⁰, so it needs a 64-bit counter.
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
- A service stores n = 10⁵ integer keys in a chained hash table with m = 1000 buckets and h(k) = k mod m. An attacker sends keys that are…
- An empty queue performs: enqueue 7, enqueue 2, enqueue 9, dequeue, enqueue 4, dequeue. Which element is now at the front?
- In a doubly linked list you are given a pointer to a node X somewhere in the middle. What is the time to delete X?
- A hash table has 7 slots and uses h(k) = k mod 7. In which slot is the key 50 placed if that slot is empty?
- Operators have the usual precedence ( and / above + and −, all left-associative). What is the postfix form of A (B + C) / D − E?
- What is the value of the prefix expression + 3 4 − 9 / 8 2 ?