Bird
Raised Fist0
Interview Preptop-k-elementseasyAmazonGoogleFacebook

Kth Largest in a Stream (Online)

Choose your preparation mode4 modes available
🎯
Kth Largest in a Stream (Online)
easyHEAPAmazonGoogleFacebook

Imagine you are monitoring live stock prices and want to continuously know the 3rd highest price at any moment as new prices stream in.

💡 This problem involves maintaining a dynamic data structure that updates as new elements arrive. Beginners often struggle because they try to sort the entire stream repeatedly, which is inefficient. Understanding how to maintain only the necessary elements efficiently is key.
📋
Problem Statement

Design a class that finds the kth largest element in a stream of integers. The class should be initialized with an integer k and an initial list of integers. Then, it should support adding new integers to the stream and return the kth largest element after each addition. Input: - An integer k - An initial array of integers nums - A sequence of integers to add to the stream Output: - After each addition, return the kth largest element in the updated stream.

1 ≤ k ≤ 10^40 ≤ nums.length ≤ 10^4-10^4 ≤ nums[i] ≤ 10^4-10^4 ≤ val ≤ 10^4At most 10^4 calls to add()
💡
Example
Input"k = 3, nums = [4, 5, 8, 2]\nadd(3)\nadd(5)\nadd(10)\nadd(9)\nadd(4)"
Output[4, 5, 5, 8, 8]

Initially, the 3rd largest element is 4. After adding 3, the 3rd largest remains 4. Adding 5 updates the 3rd largest to 5. Adding 10 updates it to 5. Adding 9 updates it to 8. Adding 4 keeps it at 8.

  • k is 1 and nums is empty → returns the largest element seen so far
  • nums is empty and multiple adds happen → kth largest updates correctly
  • k is larger than the number of elements in the stream → returns the smallest element in the stream so far
  • All elements are the same → kth largest is that element
⚠️
Common Mistakes
Sorting entire stream on every add

Time limit exceeded on large inputs

✅ Use a min-heap of size k to maintain kth largest efficiently

Using max-heap instead of min-heap for kth largest

Incorrect kth largest element returned

✅ Use min-heap to keep track of k largest elements, root is kth largest

Not handling initial nums properly

Heap size may exceed k or initial elements ignored

✅ Add initial nums elements using add() logic or heapify and pop excess

Returning wrong index in sorted list approaches

Off-by-one errors cause wrong kth largest

✅ Return element at index len(nums) - k when sorted ascending

Not maintaining heap property after insertion

Heap becomes invalid, wrong results or runtime errors

✅ Use heapify, heap push/pop, or implement heapify up/down correctly

🧠
Brute Force (Sort Entire Stream on Each Add)
💡 This approach exists to establish a baseline understanding. It is simple but inefficient, helping beginners grasp the problem before optimizing.

Intuition

Store all elements seen so far. Each time a new element is added, sort the entire list and pick the kth largest element.

Algorithm

  1. Initialize a list with the given nums.
  2. For each add(val) call, append val to the list.
  3. Sort the list in descending order.
  4. Return the element at index k-1.
💡 The main challenge is realizing that sorting the entire list every time is expensive, but this approach is easy to implement and understand.
</>
Code
class KthLargest:
    def __init__(self, k: int, nums: list[int]):
        self.k = k
        self.nums = nums

    def add(self, val: int) -> int:
        self.nums.append(val)
        self.nums.sort(reverse=True)
        return self.nums[self.k - 1]

# Driver code
if __name__ == '__main__':
    kthLargest = KthLargest(3, [4, 5, 8, 2])
    print(kthLargest.add(3))  # returns 4
    print(kthLargest.add(5))  # returns 5
    print(kthLargest.add(10)) # returns 5
    print(kthLargest.add(9))  # returns 8
    print(kthLargest.add(4))  # returns 8
Line Notes
self.k = kStore k to know which largest element to track
self.nums = numsKeep all numbers seen so far in a list
self.nums.append(val)Add the new value to the list
self.nums.sort(reverse=True)Sort descending to find kth largest easily
return self.nums[self.k - 1]Return the kth largest element after sorting
import java.util.*;

class KthLargest {
    private int k;
    private List<Integer> nums;

    public KthLargest(int k, int[] nums) {
        this.k = k;
        this.nums = new ArrayList<>();
        for (int num : nums) {
            this.nums.add(num);
        }
    }

    public int add(int val) {
        nums.add(val);
        Collections.sort(nums, Collections.reverseOrder());
        return nums.get(k - 1);
    }

    public static void main(String[] args) {
        KthLargest kthLargest = new KthLargest(3, new int[]{4, 5, 8, 2});
        System.out.println(kthLargest.add(3));  // 4
        System.out.println(kthLargest.add(5));  // 5
        System.out.println(kthLargest.add(10)); // 5
        System.out.println(kthLargest.add(9));  // 8
        System.out.println(kthLargest.add(4));  // 8
    }
}
Line Notes
this.k = k;Store k for kth largest tracking
this.nums = new ArrayList<>();Initialize list to hold all numbers
nums.add(val);Add new value to the list
Collections.sort(nums, Collections.reverseOrder());Sort descending to find kth largest
return nums.get(k - 1);Return kth largest element after sorting
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

class KthLargest {
    int k;
    vector<int> nums;
public:
    KthLargest(int k, vector<int>& nums) {
        this->k = k;
        this->nums = nums;
    }

    int add(int val) {
        nums.push_back(val);
        sort(nums.rbegin(), nums.rend());
        return nums[k - 1];
    }
};

int main() {
    vector<int> nums = {4, 5, 8, 2};
    KthLargest kthLargest(3, nums);
    cout << kthLargest.add(3) << "\n";  // 4
    cout << kthLargest.add(5) << "\n";  // 5
    cout << kthLargest.add(10) << "\n"; // 5
    cout << kthLargest.add(9) << "\n";  // 8
    cout << kthLargest.add(4) << "\n";  // 8
    return 0;
}
Line Notes
this->k = k;Store k for kth largest element tracking
this->nums = nums;Initialize vector with initial numbers
nums.push_back(val);Add new value to the vector
sort(nums.rbegin(), nums.rend());Sort descending to get kth largest easily
return nums[k - 1];Return kth largest element after sorting
class KthLargest {
    constructor(k, nums) {
        this.k = k;
        this.nums = nums;
    }

    add(val) {
        this.nums.push(val);
        this.nums.sort((a, b) => b - a);
        return this.nums[this.k - 1];
    }
}

// Driver code
const kthLargest = new KthLargest(3, [4, 5, 8, 2]);
console.log(kthLargest.add(3));  // 4
console.log(kthLargest.add(5));  // 5
console.log(kthLargest.add(10)); // 5
console.log(kthLargest.add(9));  // 8
console.log(kthLargest.add(4));  // 8
Line Notes
this.k = k;Store k to track kth largest element
this.nums = nums;Keep all numbers seen so far
this.nums.push(val);Add new value to the array
this.nums.sort((a, b) => b - a);Sort descending to find kth largest
return this.nums[this.k - 1];Return kth largest element after sorting
⏱
Complexity
TimeO(n log n) per add call due to sorting
SpaceO(n) to store all elements

Each add inserts an element and sorts the entire list of size n, which costs O(n log n). Over multiple adds, this becomes very expensive.

💡 For n=10000, sorting each time means about 10000 * 10000 * log(10000) operations, which is too slow for large inputs.
Interview Verdict: TLE for large inputs; only useful to introduce the problem

This approach is too slow for real interviews but helps understand the problem before optimizing.

🧠
Better Approach (Maintain Sorted List with Binary Insertion)
💡 This approach improves over brute force by avoiding full sorts, but still inefficient for large streams. It introduces binary search to insert elements in order.

Intuition

Keep the list sorted at all times. When adding a new element, insert it at the correct position using binary search, then return the kth largest element.

Algorithm

  1. Initialize a sorted list from nums.
  2. For each add(val), use binary search to find the insertion index.
  3. Insert val at the found index to keep list sorted.
  4. Return the element at index len(list) - k.
💡 The tricky part is maintaining sorted order efficiently and understanding how binary search helps.
</>
Code
import bisect

class KthLargest:
    def __init__(self, k: int, nums: list[int]):
        self.k = k
        self.nums = sorted(nums)

    def add(self, val: int) -> int:
        bisect.insort(self.nums, val)
        return self.nums[-self.k]

# Driver code
if __name__ == '__main__':
    kthLargest = KthLargest(3, [4, 5, 8, 2])
    print(kthLargest.add(3))  # 4
    print(kthLargest.add(5))  # 5
    print(kthLargest.add(10)) # 5
    print(kthLargest.add(9))  # 8
    print(kthLargest.add(4))  # 8
Line Notes
self.k = kStore k for kth largest tracking
self.nums = sorted(nums)Keep nums sorted initially
bisect.insort(self.nums, val)Insert val maintaining sorted order efficiently
return self.nums[-self.k]Return kth largest element from the end
import java.util.*;

class KthLargest {
    private int k;
    private List<Integer> nums;

    public KthLargest(int k, int[] nums) {
        this.k = k;
        this.nums = new ArrayList<>();
        for (int num : nums) {
            numsAdd(num);
        }
    }

    private void numsAdd(int val) {
        int idx = Collections.binarySearch(nums, val);
        if (idx < 0) idx = -idx - 1;
        nums.add(idx, val);
    }

    public int add(int val) {
        numsAdd(val);
        return nums.get(nums.size() - k);
    }

    public static void main(String[] args) {
        KthLargest kthLargest = new KthLargest(3, new int[]{4, 5, 8, 2});
        System.out.println(kthLargest.add(3));  // 4
        System.out.println(kthLargest.add(5));  // 5
        System.out.println(kthLargest.add(10)); // 5
        System.out.println(kthLargest.add(9));  // 8
        System.out.println(kthLargest.add(4));  // 8
    }
}
Line Notes
this.k = k;Store k for kth largest tracking
this.nums = new ArrayList<>();Initialize list to hold elements
int idx = Collections.binarySearch(nums, val);Find insertion index using binary search
nums.add(idx, val);Insert val at correct position to keep sorted
return nums.get(nums.size() - k);Return kth largest element from the end
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

class KthLargest {
    int k;
    vector<int> nums;
public:
    KthLargest(int k, vector<int>& nums) {
        this->k = k;
        this->nums = nums;
        sort(this->nums.begin(), this->nums.end());
    }

    int add(int val) {
        auto it = lower_bound(nums.begin(), nums.end(), val);
        nums.insert(it, val);
        return nums[nums.size() - k];
    }
};

int main() {
    vector<int> nums = {4, 5, 8, 2};
    KthLargest kthLargest(3, nums);
    cout << kthLargest.add(3) << "\n";  // 4
    cout << kthLargest.add(5) << "\n";  // 5
    cout << kthLargest.add(10) << "\n"; // 5
    cout << kthLargest.add(9) << "\n";  // 8
    cout << kthLargest.add(4) << "\n";  // 8
    return 0;
}
Line Notes
sort(this->nums.begin(), this->nums.end());Sort initial nums to maintain order
auto it = lower_bound(nums.begin(), nums.end(), val);Find insertion point with binary search
nums.insert(it, val);Insert val at correct position to keep sorted
return nums[nums.size() - k];Return kth largest element from the end
class KthLargest {
    constructor(k, nums) {
        this.k = k;
        this.nums = nums.sort((a, b) => a - b);
    }

    add(val) {
        let left = 0, right = this.nums.length;
        while (left < right) {
            let mid = Math.floor((left + right) / 2);
            if (this.nums[mid] < val) left = mid + 1;
            else right = mid;
        }
        this.nums.splice(left, 0, val);
        return this.nums[this.nums.length - this.k];
    }
}

// Driver code
const kthLargest = new KthLargest(3, [4, 5, 8, 2]);
console.log(kthLargest.add(3));  // 4
console.log(kthLargest.add(5));  // 5
console.log(kthLargest.add(10)); // 5
console.log(kthLargest.add(9));  // 8
console.log(kthLargest.add(4));  // 8
Line Notes
this.k = k;Store k for kth largest tracking
this.nums = nums.sort((a, b) => a - b);Sort initial nums ascending
while (left < right)Binary search to find insertion index
this.nums.splice(left, 0, val);Insert val at correct position
return this.nums[this.nums.length - this.k];Return kth largest element from the end
⏱
Complexity
TimeO(n) per add due to insertion in array
SpaceO(n) to store all elements

Binary search takes O(log n), but insertion in array costs O(n) due to shifting elements.

💡 For n=10000, each add could take up to 10000 operations, which is better than sorting but still slow.
Interview Verdict: Better than brute force but still inefficient for large inputs

This approach shows improvement but is not optimal for large streams.

🧠
Optimal Approach (Min-Heap of Size k)
💡 This approach is the standard efficient solution. It maintains only k elements in a min-heap, ensuring fast updates and queries.

Intuition

Keep a min-heap of size k containing the k largest elements seen so far. The smallest element in this heap is the kth largest overall. When a new element arrives, if it is larger than the smallest in the heap, replace it to maintain the k largest.

Algorithm

  1. Initialize a min-heap with the first k elements from nums (or fewer if nums has less than k).
  2. For each remaining element in nums, if it is larger than the heap root, pop root and push the new element.
  3. For each add(val) call, if val is larger than the heap root, pop root and push val; else ignore val.
  4. Return the heap root as the kth largest element.
💡 The key is maintaining a heap of fixed size k to keep track of the kth largest efficiently.
</>
Code
import heapq

class KthLargest:
    def __init__(self, k: int, nums: list[int]):
        self.k = k
        self.heap = nums
        heapq.heapify(self.heap)
        while len(self.heap) > k:
            heapq.heappop(self.heap)

    def add(self, val: int) -> int:
        if len(self.heap) < self.k:
            heapq.heappush(self.heap, val)
        elif val > self.heap[0]:
            heapq.heapreplace(self.heap, val)
        return self.heap[0]

# Driver code
if __name__ == '__main__':
    kthLargest = KthLargest(3, [4, 5, 8, 2])
    print(kthLargest.add(3))  # 4
    print(kthLargest.add(5))  # 5
    print(kthLargest.add(10)) # 5
    print(kthLargest.add(9))  # 8
    print(kthLargest.add(4))  # 8
Line Notes
self.k = kStore k for kth largest tracking
self.heap = numsInitialize heap with given numbers
heapq.heapify(self.heap)Convert list to min-heap in O(n)
while len(self.heap) > k: heapq.heappop(self.heap)Remove smallest elements to keep heap size k
if len(self.heap) < self.k: heapq.heappush(self.heap, val)Add val if heap not full
elif val > self.heap[0]: heapq.heapreplace(self.heap, val)Replace smallest if val is bigger
return self.heap[0]Heap root is kth largest element
import java.util.*;

class KthLargest {
    private PriorityQueue<Integer> minHeap;
    private int k;

    public KthLargest(int k, int[] nums) {
        this.k = k;
        minHeap = new PriorityQueue<>();
        for (int num : nums) {
            add(num);
        }
    }

    public int add(int val) {
        if (minHeap.size() < k) {
            minHeap.offer(val);
        } else if (val > minHeap.peek()) {
            minHeap.poll();
            minHeap.offer(val);
        }
        return minHeap.peek();
    }

    public static void main(String[] args) {
        KthLargest kthLargest = new KthLargest(3, new int[]{4, 5, 8, 2});
        System.out.println(kthLargest.add(3));  // 4
        System.out.println(kthLargest.add(5));  // 5
        System.out.println(kthLargest.add(10)); // 5
        System.out.println(kthLargest.add(9));  // 8
        System.out.println(kthLargest.add(4));  // 8
    }
}
Line Notes
this.k = k;Store k for kth largest tracking
minHeap = new PriorityQueue<>();Min-heap to keep k largest elements
for (int num : nums) { add(num); }Add initial elements using add() logic
if (minHeap.size() < k) { minHeap.offer(val); }Add val if heap not full
else if (val > minHeap.peek()) { minHeap.poll(); minHeap.offer(val); }Replace smallest if val bigger
return minHeap.peek();Root of min-heap is kth largest
#include <iostream>
#include <vector>
#include <queue>

using namespace std;

class KthLargest {
    int k;
    priority_queue<int, vector<int>, greater<int>> minHeap;
public:
    KthLargest(int k, vector<int>& nums) {
        this->k = k;
        for (int num : nums) {
            add(num);
        }
    }

    int add(int val) {
        if ((int)minHeap.size() < k) {
            minHeap.push(val);
        } else if (val > minHeap.top()) {
            minHeap.pop();
            minHeap.push(val);
        }
        return minHeap.top();
    }
};

int main() {
    vector<int> nums = {4, 5, 8, 2};
    KthLargest kthLargest(3, nums);
    cout << kthLargest.add(3) << "\n";  // 4
    cout << kthLargest.add(5) << "\n";  // 5
    cout << kthLargest.add(10) << "\n"; // 5
    cout << kthLargest.add(9) << "\n";  // 8
    cout << kthLargest.add(4) << "\n";  // 8
    return 0;
}
Line Notes
priority_queue<int, vector<int>, greater<int>> minHeap;Min-heap to store k largest elements
for (int num : nums) { add(num); }Add initial elements using add() logic
if ((int)minHeap.size() < k) { minHeap.push(val); }Add val if heap not full
else if (val > minHeap.top()) { minHeap.pop(); minHeap.push(val); }Replace smallest if val bigger
return minHeap.top();Root of min-heap is kth largest
class KthLargest {
    constructor(k, nums) {
        this.k = k;
        this.minHeap = [];
        nums.forEach(num => this.add(num));
    }

    add(val) {
        if (this.minHeap.length < this.k) {
            this.minHeap.push(val);
            this._heapifyUp(this.minHeap.length - 1);
        } else if (val > this.minHeap[0]) {
            this.minHeap[0] = val;
            this._heapifyDown(0);
        }
        return this.minHeap[0];
    }

    _heapifyUp(index) {
        while (index > 0) {
            let parent = Math.floor((index - 1) / 2);
            if (this.minHeap[parent] <= this.minHeap[index]) break;
            [this.minHeap[parent], this.minHeap[index]] = [this.minHeap[index], this.minHeap[parent]];
            index = parent;
        }
    }

    _heapifyDown(index) {
        let length = this.minHeap.length;
        while (true) {
            let left = 2 * index + 1;
            let right = 2 * index + 2;
            let smallest = index;
            if (left < length && this.minHeap[left] < this.minHeap[smallest]) smallest = left;
            if (right < length && this.minHeap[right] < this.minHeap[smallest]) smallest = right;
            if (smallest === index) break;
            [this.minHeap[smallest], this.minHeap[index]] = [this.minHeap[index], this.minHeap[smallest]];
            index = smallest;
        }
    }
}

// Driver code
const kthLargest = new KthLargest(3, [4, 5, 8, 2]);
console.log(kthLargest.add(3));  // 4
console.log(kthLargest.add(5));  // 5
console.log(kthLargest.add(10)); // 5
console.log(kthLargest.add(9));  // 8
console.log(kthLargest.add(4));  // 8
Line Notes
this.k = k;Store k for kth largest tracking
this.minHeap = [];Initialize empty min-heap array
nums.forEach(num => this.add(num));Add initial elements using add() logic
if (this.minHeap.length < this.k) { this.minHeap.push(val); this._heapifyUp(...); }Add val if heap not full and restore heap
else if (val > this.minHeap[0]) { this.minHeap[0] = val; this._heapifyDown(0); }Replace root if val bigger and restore heap
return this.minHeap[0];Root of min-heap is kth largest
⏱
Complexity
TimeO(log k) per add call
SpaceO(k) to store the heap

Heap operations (push/pop) take O(log k). Since heap size is fixed at k, this is efficient even for large streams.

💡 For k=1000, each add takes about 10 operations, which is very efficient compared to sorting the entire stream.
Interview Verdict: Accepted and optimal for large inputs

This approach is the best practice for this problem and expected in interviews.

📊
All Approaches - One-Glance Tradeoffs
💡 In interviews, always aim to code the optimal heap-based approach unless asked otherwise.
ApproachTimeSpaceStack RiskReconstructUse In Interview
1. Brute ForceO(n log n) per addO(n)NoN/AMention only - never code
2. Sorted List with Binary InsertionO(n) per addO(n)NoN/AMention as improvement, but not optimal
3. Min-Heap of Size kO(log k) per addO(k)NoN/ACode this approach in 95% of interviews
💼
Interview Strategy
💡 Use this guide to understand the problem deeply before your interview. Start by clarifying requirements, then explain the brute force approach to show understanding. Progress to the optimal heap-based solution and discuss tradeoffs.

How to Present

Step 1: Clarify the problem and constraints with the interviewer.Step 2: Describe the brute force approach to show baseline understanding.Step 3: Explain why brute force is inefficient and introduce the heap approach.Step 4: Implement the heap-based solution carefully.Step 5: Test with example inputs and discuss edge cases.

Time Allocation

Clarify: 2min → Approach: 5min → Code: 10min → Test: 3min. Total ~20min

What the Interviewer Tests

The interviewer tests your ability to handle streaming data efficiently, your knowledge of heaps, and your coding accuracy.

Common Follow-ups

  • What if k changes dynamically? → Use a balanced data structure or rebuild heap.
  • How to find kth smallest instead? → Use a max-heap of size k instead.
💡 Follow-ups test your flexibility and understanding of heap variants and dynamic data structures.
🔍
Pattern Recognition

When to Use

1) Need kth largest or smallest element 2) Data arrives as a stream or online 3) Need efficient updates after each insertion 4) Constraints allow using a heap of size k

Signature Phrases

kth largest element in a streamadd new element and return kth largest

NOT This Pattern When

Sorting entire array repeatedly or offline kth largest queries

Similar Problems

Top K Frequent Elements - also uses heaps to track top kFind Median from Data Stream - uses two heaps to track median

Practice

(1/5)
1. Consider the following Python code implementing a frequency stack using a max-heap with timestamp. After executing the sequence of operations below, what is the output of the last pop() call?
fs = FreqStack()
fs.push(1)
fs.push(2)
fs.push(1)
print(fs.pop())
print(fs.pop())
easy
A. 1 and then 1
B. 2 and then 1
C. 1 and then 2
D. 2 and then 2

Solution

  1. Step 1: Trace push operations

    Push 1: freq[1]=1, time=1, heap push (-1, -1, 1) Push 2: freq[2]=1, time=2, heap push (-1, -2, 2) Push 1: freq[1]=2, time=3, heap push (-2, -3, 1)
  2. Step 2: Trace pop operations

    First pop: heap pops (-2, -3, 1) -> returns 1, freq[1]=1 Second pop: heap now has (-1, -2, 2) and (-1, -1, 1). Max freq is 1, tie broken by time: -2 > -1, so pop (-1, -2, 2) returns 2.
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    Most frequent element 1 popped first, then next most recent with freq 1 is 2 [OK]
Hint: Most frequent and most recent element pops first [OK]
Common Mistakes:
  • Ignoring timestamp order in heap
  • Mixing up pop order when frequencies tie
2. You are given an integer array and asked to find the k elements that appear most frequently. Which of the following approaches guarantees an optimal time complexity solution for this problem?
easy
A. Use a bucket sort based on frequency counts, then iterate buckets from high to low frequency to collect top k elements.
B. Use a greedy approach that picks the most frequent element repeatedly without frequency counting.
C. Use a dynamic programming approach to build frequency tables and select top k elements.
D. Sort the entire array and then count frequencies to pick top k elements.

Solution

  1. Step 1: Understand the problem constraints

    The problem requires finding the top k frequent elements efficiently, which means counting frequencies and retrieving elements by frequency.
  2. Step 2: Evaluate approaches for optimality

    Sorting the entire array (A) is inefficient (O(n log n)). Dynamic programming (C) and greedy without frequency counting (B) do not apply here. Bucket sort by frequency (D) achieves O(n) time by grouping elements by frequency and iterating from highest frequency down.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Bucket sort groups elements by frequency and retrieves top k in linear time [OK]
Hint: Bucket sort by frequency is linear time [OK]
Common Mistakes:
  • Sorting entire array instead of unique elements
  • Using greedy without frequency counts
3. Consider the following buggy code for sorting characters by frequency. Which line contains the subtle bug that causes incorrect output?
from collections import Counter

def frequencySort(s: str) -> str:
    freq = Counter(s)
    max_freq = max(freq.values(), default=0)
    buckets = [[] for _ in range(max_freq + 1)]
    for char, count in freq.items():
        buckets[count].append(char)
    result = []
    for freq_count in range(max_freq, 0, -1):
        for char in buckets[freq_count]:
            result.append(str(count))  # Bug here: appending count instead of repeated char
    return ''.join(result)
medium
A. Line 7: appending characters to buckets
B. Line 10: appending str(count) instead of repeated characters
C. Line 5: max_freq calculation
D. Line 9: iterating freq_count from max_freq down to 1

Solution

  1. Step 1: Identify incorrect append operation

    Line 10 appends str(count) instead of repeating the character freq_count times.
  2. Step 2: Why this causes wrong output

    Appending count as string adds digits, not characters, breaking output correctness.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Correct code appends char * freq_count, not str(count) [OK]
Hint: Check what is appended to result list carefully [OK]
Common Mistakes:
  • Confusing variable names in loops
  • Appending count instead of repeated char
4. The following code attempts to find the top k frequent words using bucket sort. Identify the line containing the subtle bug that causes incorrect ordering when frequencies tie.
medium
A. Line with max_freq = max(freq.values())
B. Line with buckets[i].sort(reverse=True)
C. Line with freq[w] = freq.get(w, 0) + 1
D. Line with for i in range(max_freq, 0, -1)

Solution

  1. Step 1: Understand sorting within buckets

    Words in each bucket must be sorted lexicographically ascending to break ties correctly.
  2. Step 2: Identify incorrect sorting order

    Using sort(reverse=True) sorts words descending lex order, breaking tie rules.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Correct tie-break requires ascending lex order [OK]
Hint: Tie-break requires ascending lex sort, not descending [OK]
Common Mistakes:
  • Sorting buckets descending lex order
  • Using max heap instead of bucket
  • Incorrect iteration order over buckets
5. Suppose the problem changes: you must find the k closest points to the origin, but points can be repeated multiple times (i.e., duplicates allowed and must be counted separately). Which modification to the Quickselect approach correctly handles this scenario without increasing time complexity significantly?
hard
A. Use a max heap of size k to keep track of closest points, allowing duplicates naturally.
B. Use a min heap to store all points and pop k times to get closest points, handling duplicates automatically.
C. Sort all points by distance and then remove duplicates before returning the first k points.
D. Modify Quickselect to partition points by distance and include duplicates in the partitioning logic without skipping any points.

Solution

  1. Step 1: Understand duplicates impact

    Duplicates must be treated as distinct points; Quickselect partitions by distance and does not rely on uniqueness.
  2. Step 2: Modify partition to handle duplicates correctly

    Partition logic remains the same; all points, including duplicates, are compared and placed correctly without skipping.
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    Quickselect handles duplicates naturally if partitioning is correct [OK]
Hint: Quickselect partitions all points regardless of duplicates [OK]
Common Mistakes:
  • Using min heap instead of max heap
  • Removing duplicates before selection
  • Sorting all points unnecessarily
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard