Posts

Showing posts with the label Segment Tree

Most Frequent IDs - Heap w/ Lazy Removal, Segment Tree [JS]

Description   Solution 1: Segment Tree Use a max segment tree to efficiently find and update the maximum frequency in the range  (0, 10^5) . n = length of nums ,  m = max(nums[i]) Time Complexity:  O(m + n log(m)) Space Complexity:  O(m)  (excluding output) var mostFrequentIDs = function ( nums, freq ) { let n = nums.length, m = Math .max(...nums), tree = new MaxSegmentTree(m); let ans = Array (n); for ( let i = 0 ; i < n; i++) { let id = nums[i] - 1 ; tree.add(id, freq[i]); ans[i] = tree.maxRange( 0 , m - 1 ); } return ans; }; class MaxSegmentTree { constructor ( n ) { this .size = n; this .segTree = Array (n * 2 ).fill( 0 ); } add ( index, value ) { let n = this .size, idx = index + n; this .segTree[idx] += value; idx = Math .floor(idx / 2 ); while (idx > 0 ) { this .segTree[idx] = Math .max( this .segTree[idx * 2 ], this .segTree[idx * 2 + 1 ]); idx = Math .floor(idx /...