Data Structures & AlgorithmsHardInfosys SP/DSE · Product Company SDE
Problem: A problem requires finding all pairs in an array that sum to a target, allowing duplicate pairs to be counted once. Which is the best average-case approach and its complexity?
- A. A hash map counting value frequencies, achieving O(n) average time
- B. Only possible in O(n log n) via sorting, no faster approach exists
- C. Comparing every pair directly without any sorting or hashing, O(n^2), and this is optimal
- D. Sorting plus nested loops, O(n^2)
Correct answer: A. A hash map counting value frequencies, achieving O(n) average time
Counting how many times each value appears in a hash map, then for each distinct value checking whether its complement exists (handling the self-paired case separately), finds all valid pairs in a single O(n) average-case pass.
More Coding Interview Problems questions
- Problem: Which statement about the time complexity of building a suffix array naively (sorting all n suffixes with standard string…
- Problem: A delivery app logs the parcel weights of a day in an array. Return the indices of the two parcels whose weights add up exactly…
- Problem: Given an unsorted array of n ≤ 10⁵ integers and a target, report whether two different positions hold values summing to the…
- Problem: A stock tracker gets daily prices and must report the best profit from one buy followed by one later sell (0 if no profit is…
- Problem: Find the largest sum of a non-empty contiguous block of an array (values may be negative). python def best(a): cur = ans = a[0]…
- Problem: Rotate an array to the right by k steps in place, using O(1) extra space. Example: [1, 2, 3, 4, 5], k = 2 → [4, 5, 1, 2, 3]…