Data Structures & AlgorithmsHardProduct Company SDE · heap round
Problem: A data stream needs the median of the last k elements. Which structure supports each slide in O(log k) time?
- A. A single sorted array with insertion by shifting
- B. A plain queue with linear search for the median
- C. Two heaps (a max-heap for the lower half and a min-heap for the upper half) with lazy deletion
- D. A hash map from value to count with the median read from the keys
Correct answer: C. Two heaps (a max-heap for the lower half and a min-heap for the upper half) with lazy deletion
Two balanced heaps give the median at the top, and lazy deletion removes the element that leaves the window in O(log k). A sorted array insertion costs O(k) per shift.
More Coding Interview Problems questions
- Problem: Consider a connected undirected graph whose edge weights are all distinct. Which statement is true?
- Problem: What is the standard time complexity of bitmask DP for the travelling salesman problem on n cities?
- Array a = [3, -1, 2, 6, -4, 5, 1, -2]. How many non-empty contiguous subarrays have a sum divisible by 4?
- Binary array a = [1, 0, 1, 1, 0, 0, 1, 0, 1]. How many contiguous subarrays have exactly two 1s?
- Array a = [4, 2, 7, 1, 8, 3, 6, 5]. What is the largest sum of a contiguous subarray whose length is between 2 and 4 inclusive?
- In the string "abcabcaab", count the non-empty substrings that contain equally many vowels and consonants (vowels are a, e, i, o, u).