Problem Description
Implement a data structure that stores and retrieves integers. It must provide 3 operations:
constructor(): initializes the data structure.push(val: number): stores an integer in theFreqStack.pop(): number: removes and returns an element from theFreqStackaccording to the following rules:- If the
FreqStackcontains an element that occurs more often than the others, that element is popped (the most recently added one of its occurrences). - If several elements share the highest frequency, the one whose occurrence was pushed to the
FreqStackmost recently is popped. - If all elements in the
FreqStackhave the same frequency (e.g. each occurs only once), the element is popped as in a regular stack.
- If the
Constraints
- Pushed/popped values are in the range from 0 to 1 000 000 000
- At most 20 000 calls are made to
pushandpop - It is guaranteed that the
FreqStackcontains at least one element beforepopis called
Example
Initialization:
const stack = new FreqStack();
stack.push(5);
stack.push(7);
stack.push(5);
stack.push(7);
stack.push(4);
stack.push(5);Popping:
stack.pop(); // 5
stack.pop(); // 7
stack.pop(); // 5
stack.pop(); // 4Explanation:
5is popped first, since it's the most frequent element in the stack. The popped5is the one that was added last (as in a stack)7is popped second, since both5and7now occur twice, but the last7was pushed later than the remaining last5(the5from the lastpushwas popped by the firstpopcall)5is popped third, since it's now the most frequent element in the stack4is popped fourth, since all elements now have the same frequency (each occurs once), and4was pushed last
Solution
The data structure we need to implement is very similar to a classic structure from everyday development: the Priority Queue.
However, in our case the priority is the frequency of an element, and elements are retrieved like in a stack (LIFO)
rather than a queue (FIFO).
As with a Priority Queue, one of the most efficient data structures to build it on is a heap.
Heap properties
- Each node has a key greater/less than (depending on whether it's a max-heap or a min-heap) or equal to the keys of its children.
- A heap is an almost complete binary tree. This means all levels of the tree are completely filled, except possibly the last one, which is filled from left to right.
Implementing a heap with an array
A heap is a tree structure that can be implemented efficiently with an array, computing the element indices as follows:
- The parent of the node at index
iis at index(i - 1) / 2(integer division). - The left child of the node at index
iis at index2 * i + 1. - The right child of the node at index
iis at index2 * i + 2.
Designing the data structure
To implement the Maximum Frequency Stack we need the following structures:
class Item {
freq: number;
seq: number;
val: number;
}
class Heap {
items: Item[] = [];
}
class FreqStack {
private h: Heap;
private freqElem: Map<number, number>;
private curSeq: number;
}FreqStack is the main structure we need to implement. It consists of:
h: a heap implemented with an array.freqElem: a hash map that gives us the frequency of an element at the time of insertion.curSeq: the current maximum sequence number (an element counter).
We need to implement its push(val) and pop() methods.
push(val)
To insert an element into the heap, we need to determine its key (elements in a heap are compared by their keys). In our case the key consists of two values:
- The frequency of the element (which we can quickly get from
freqElem). It's enough to know the frequency at the time of insertion: we don't need to update elements already in the heap or change their positions. - The sequence number of the element (determined with
curSeq).
The element is first placed at the very end of the heap, and then a recursive "sift up" process restores the heap property.
Sifting up (upElement)
Sifting up is used after inserting a new element into the heap. The element is inserted at the end of the array (the last level of the tree) and then moves up until the heap property is restored.
The sift-up algorithm:
- Find the parent of the newly inserted element. Since the heap is implemented with an array, the parent is at index
(i - 1) / 2. - Compare the key of the new element with its parent's. In our case the key consists of the frequency and the sequence number. One element is considered greater than another if its frequency is higher (when the frequencies differ), or if its sequence number is higher.
- If the element is greater than its parent, swap them.
- Repeat steps 2 and 3 until the element is in place or reaches the root.
So the overall complexity of inserting an element into the heap is determined by the sift-up operation, which
is O(log n), since in the worst case we have to go all the way up the binary tree to the root.
pop()
When popping an element, we need to decrement its frequency and remove it from the heap.
Thanks to the heap properties, the element we need is always at the root (at index 0 of the array).
Similarly to insertion, after removing the root from the heap we need to run a "sift down" process
(heapify) that restores the heap property.
For that:
- Move the last element of the heap to the first position. This way we avoid shifting all elements of the heap one position to the left.
- Compare the parent with its children.
- If the element is smaller than one of its children, swap it with the larger child.
- Repeat steps 2 and 3 until the element is in place or reaches the last level of the tree.
Just like insertion, popping takes O(log n).
class Item {
freq: number;
seq: number;
val: number;
constructor(freq: number, seq: number, val: number) {
this.freq = freq;
this.seq = seq;
this.val = val;
}
more(second: Item): boolean {
if (this.freq !== second.freq) {
return this.freq > second.freq;
}
return this.seq > second.seq;
}
}
class Heap {
items: Item[] = [];
add(newItem: Item): void {
this.items.push(newItem);
this.upElement(this.items.length - 1);
}
pop(): Item | null {
if (this.items.length === 0) {
return null;
}
const res = this.items[0];
if (this.items.length > 1) {
this.items[0] = this.items.pop()!;
this.heapify(0);
} else {
this.items.pop();
}
return res;
}
private heapify(index: number): void {
const left = index * 2 + 1;
const right = left + 1;
let largest = index;
if (left < this.items.length && this.items[left].more(this.items[largest])) {
largest = left;
}
if (right < this.items.length && this.items[right].more(this.items[largest])) {
largest = right;
}
if (largest !== index) {
[this.items[index], this.items[largest]] = [this.items[largest], this.items[index]];
this.heapify(largest);
}
}
private upElement(index: number): void {
const parent = Math.floor((index - 1) / 2);
if (parent >= 0 && this.items[index].more(this.items[parent])) {
[this.items[index], this.items[parent]] = [this.items[parent], this.items[index]];
this.upElement(parent);
}
}
}
export class FreqStack {
private h: Heap;
private freqElem: Map<number, number>;
private curSeq: number;
constructor() {
this.h = new Heap();
this.freqElem = new Map();
this.curSeq = 0;
}
push(val: number): void {
this.curSeq++;
this.freqElem.set(val, (this.freqElem.get(val) || 0) + 1);
this.h.add(new Item(this.freqElem.get(val)!, this.curSeq, val));
}
pop(): number {
const item = this.h.pop();
if (item) {
this.freqElem.set(item.val, this.freqElem.get(item.val)! - 1);
if (this.freqElem.get(item.val) === 0) {
this.freqElem.delete(item.val);
}
return item.val;
}
return -1; // or throw an error
}
}Complexity Analysis
Time Complexity
Both inserting and popping take O(log n), since both run a recursive "sift" process that goes either
up the tree from a leaf (sift up) or down from the root to a leaf (sift down).
Space Complexity
The additional memory is O(n), since we use the heap and the extra hash map freqElem.
In the worst case their size equals the number of inserted elements.