Data Structures & AlgorithmsEasyTCS NQT Digital · Product Company SDE
Problem: Given an unsorted array of n ≤ 10⁵ integers and a target, report whether two different positions hold values summing to the target. Which approach is optimal in time while passing comfortably?
- A. Check every pair with two nested loops – O(n²)
- B. Sort, then binary search each element's complement – O(n²)
- C. One pass with a hash set of values seen so far – O(n) average time, O(n) space
- D. Build a prefix-sum array and look for the target in it – O(n)
Correct answer: C. One pass with a hash set of values seen so far – O(n) average time, O(n) space
Storing each value in a hash set and checking target − x before inserting x finds a pair in a single O(n) pass. Sorting plus binary search is O(n log n), not O(n²), and still slower than hashing; nested loops are 5 × 10⁹ steps at n = 10⁵. Prefix sums find contiguous sums, not arbitrary pairs.
More Coding Interview Problems questions
- 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]…
- Problem: Every number in a list of sensor IDs appears twice except one. Find the lonely ID in O(n) time and O(1) space. python def…
- Problem: Return, for every index i, the product of all elements except a[i], without using division. Example: [1, 2, 3, 4] → [24, 12, 8…
- Problem: Given an array where values lie in 1..n, find the value that appears twice (exactly one does) without modifying the array. python…