[Algorithm] Median Maintenance algorithm implementation using TypeScript / JavaScript
The median maintenance problem is a common programming challenge presented in software engineering job interviews.
In this lesson we cover an example of how this problem might be presented and what your chain of thought should be to tackle this problem efficiently.
Lets first refresh what is a median
- The median is the middle element in the sorted list
- Given a list of numbers
`
The median is the middle element in the sorted list. Given
13, 23, 11, 16, 15, 10, 26 Sort them
10, 11, 13, 15, 16, 23, 26
↑
Median If we have an even number of elements we average E.g.
10, 11, 13, 15, 16, 23, 26, 32
\ /
15.5
They way we solve the problem is by using two heaps (Low & High) to divide the array into tow parts.
Low | High
Max Heap | Min Heap
Low part is a max heap, high part is a min heap.
`
(n/2 ± 1) smallest items in a low MaxHeap (n/2 ± 1) biggest items in a high MinHeap peek => n/2th smallest peek => n/2th smallest
\ /
MEDIAN!
`
If low part size is equals to high part size, then we get avg value, otherwise, we get from larger size heap.
function MedianMaintaince() {
let lowMaxHeap = new Heap((b, a) => a - b);
let highMinHeap = new Heap((a, b) => a - b); return {
add(value) {
// For the first element, we add to lowMaxHeap by default
if (lowMaxHeap.size() === 0 || value < lowMaxHeap.peek()) {
lowMaxHeap.add(value);
} else {
highMinHeap.add(value);
} /**
* Reblance:
*
* If low.size = 2; high.size = 4, then we move the root of high to the low part
* so that low.size = 3, high.size = 3
*/
let smallerHeap =
lowMaxHeap.size() > highMinHeap.size() ? highMinHeap : lowMaxHeap;
let biggerHeap = smallerHeap === lowMaxHeap ? highMinHeap : lowMaxHeap;
if (biggerHeap.size() - smallerHeap.size() > 1) {
smallerHeap.add(biggerHeap.extractRoot());
} /**
* If low.szie === high.size, extract root for both and calculate the average value
*/
if (lowMaxHeap.size() === highMinHeap.size()) {
return (lowMaxHeap.peek() + highMinHeap.peek()) / 2;
} else {
// get peak value from the bigger size of heap
return lowMaxHeap.size() > highMinHeap.size()
? lowMaxHeap.peek()
: highMinHeap.peek();
}
}
};
} const mm = new MedianMaintaince();
console.log(mm.add(4)); //
console.log(mm.add(2)); //
console.log(mm.add(5)); //
console.log(mm.add(3)); // 3.5
We have heap data structure:
function printArray(ary) {
console.log(JSON.stringify(ary, null, 2));
} function Heap(cmpFn = () => {}) {
let data = [];
return {
data,
// 2n+1
leftInx(index) {
return 2 * index + 1;
},
//2n + 2
rightInx(index) {
return 2 * index + 2;
},
// left: (n - 1) / 2, left index is always odd number
// right: (n - 2) / 2, right index is always even number
parentInx(index) {
return index % 2 === 0 ? (index - 2) / 2 : (index - 1) / 2;
},
add(val) {
this.data.push(val);
this.siftUp(this.data.length - 1);
},
extractRoot() {
if (this.data.length > 0) {
const root = this.data[0];
const last = this.data.pop();
if (this.data.length > 0) {
// move last element to the root
this.data[0] = last;
// move last elemment from top to bottom
this.siftDown(0);
} return root;
}
},
siftUp(index) {
// find parent index
let parentInx = this.parentInx(index);
// compare
while (index > 0 && cmpFn(this.data[index], this.data[parentInx]) < 0) {
//swap parent and current node value
[this.data[index], this.data[parentInx]] = [
this.data[parentInx],
this.data[index]
];
//swap index
index = parentInx;
//move to next parent
parentInx = this.parentInx(index);
}
},
siftDown(index) {
const minIndex = (leftInx, rightInx) => {
if (cmpFn(this.data[leftInx], this.data[rightInx]) <= 0) {
return leftInx;
} else {
return rightInx;
}
};
let min = minIndex(this.leftInx(index), this.rightInx(index));
while (min >= 0 && cmpFn(this.data[index], this.data[min]) > 0) {
[this.data[index], this.data[min]] = [this.data[min], this.data[index]];
index = min;
min = minIndex(this.leftInx(index), this.rightInx(index));
}
},
peek() {
return this.data[0];
},
print() {
printArray(this.data);
},
size() {
return this.data.length;
}
};
}
[Algorithm] Median Maintenance algorithm implementation using TypeScript / JavaScript的更多相关文章
- [Algorithm] Maximum Contiguous Subarray algorithm implementation using TypeScript / JavaScript
Naive solution for this problem would be caluclate all the possible combinations: const numbers = [1 ...
- 一个"Median Maintenance"问题
题目要求: Download the text file here. The goal of this problem is to implement the "Median Mainten ...
- 如何在TypeScript/JavaScript项目里引入MD5校验和
摘要:MD5校验和则是其中一种数学算法,通常是使用工具对文件计算得出的一组32 个字符的十六进制字母和数字. 本文分享自华为云社区<TypeScript/JavaScript项目里如何做MD5校 ...
- 【Java】-NO.13.Algorithm.1.Java Algorithm.1.001-【Java 常用算法手册 】-
1.0.0 Summary Tittle:[Java]-NO.13.Algorithm.1.Java Algorithm.1.001-[Java 常用算法手册 ]- Style:Java Series ...
- Prim's Algorithm & Kruskal's algorithm
1. Problem These two algorithm are all used to find a minimum spanning tree for a weighted undirecte ...
- Method for finding shortest path to destination in traffic network using Dijkstra algorithm or Floyd-warshall algorithm
A method is presented for finding a shortest path from a starting place to a destination place in a ...
- TypeScript & JavaScript
http://www.typescriptlang.org/docs/tutorial.html handbook: Basic Types Variable Declarations Interfa ...
- 正则表达式(TypeScript, JavaScript)
课题 使用正则表达式匹配字符串 使用正则表达式 "\d{3}-(\d{4})-\d{2}" 匹配字符串 "123-4567-89" 返回匹配结果:'" ...
- [Algorithm] Radix Sort Algorithm
For example we have the array like this: [, , , , , ] First step is using Counting sort for last dig ...
随机推荐
- poj 1037 三维dp
A decorative fence Time Limit: 1000MS Memory Limit: 10000K Total Submissions: 7221 Accepted: 272 ...
- 控制属性为multiple的select
需求:实现点击查询,搜索对应渠道已投放.未投放批次.如图: html: <div class="form-inline margin-top-20"> <div ...
- Tomcat的context.xml说明、Context标签讲解
Tomcat的context.xml说明.Context标签讲解 1. 在tomcat 5.5之前 --------------------------- Context体现在/conf/server ...
- HDU5187 zhx's contest
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others) Total Submission ...
- php 内核变量 引用计数器写时复制
写时复制,是一个解决内存复用的方法,就是你在php语言层,如$d=$c=$b=$a='value';把$a赋给另一个或多个变量,这时这个变量都只占用一个内存块,当其中一个变量值改变时,才会开辟另一个内 ...
- android与java的关系
摘自:http://bbs.51cto.com/thread-944897-1.html 相信学习android的人都会想过或者想知道这个问题,那就请你耐心的看完这篇文章吧,你会对android与 ...
- Django和SQLAlchemy区别
译者注:本文首先介绍了什么是ORM,然后从多个方面对Python语言下的两个ORM库Django和SQLAlchemy进行比较,为ORM的选型提供了较为全面的指导建议.以下是译文. ORM是什么? 在 ...
- Centos7下zabbix部署(三)自定义监控项
引言 在前面的博客中我们介绍了zabbix自带的模板,并且完成了我们的一些比较常用的监控,现在我们如果想要监控我们磁盘的IO,这时候zabbix并没有给我们提供这么一个模板,所以我们需要自己来创建一个 ...
- 鸭子-策略模式(Strategy)
前言 万事开头难,最近对这句话体会深刻!这篇文章是这个系列正式开始介绍设计模式的第一篇,所以肩负着确定这个系列风格的历史重任,它在我脑袋里默默地酝酿了好多天,却只搜刮出了一点儿不太清晰的轮廓,可是时间 ...
- 使用sqlplus执行sql时,发现有中文有乱码解决方法
https://blog.csdn.net/fyyinjing/article/details/77877239