[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)); // 4
console.log(mm.add(2)); // 3
console.log(mm.add(5)); // 4
console.log(mm.add(3)); // 3.5
复制代码

 

We have heap data structure:

  

 

posted @   Zhentiw  阅读(498)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2016-01-04 [Javascript] JSON.parse API
2016-01-04 [React Testing] Setting up dependencies && Running tests
2016-01-04 [ES6] Array -- Destructuring and Rest Parameters && for ..of && Arrat.find()
2015-01-04 [AngularJS] Lazy Loading modules with ui-router and ocLazyLoad
2015-01-04 [AngularJS] Lazy loading Angular modules with ocLazyLoad
2015-01-04 [AngularJS] Consistency between ui-router states and Angular directives
点击右上角即可分享
微信分享提示