Problem solution · C++

Finding MK Average

Finding MK Average: a C++ solution using breadth-first search. Learn the idea, check the complexity, and read the full code, with credit to walkccc LeetCode Solutions.

Technique
Breadth-first search
Source
walkccc LeetCode Solutions
Length
71 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Breadth-first search

For Finding MK Average, the implementation explores reachable states in layers, which is the standard shape for unweighted shortest paths and minimum-step transitions.

  1. Model each valid configuration as a state and each legal move as an edge.
  2. Seed the queue with the starting state and mark it immediately.
  3. Expand each state once, recording distance or reachability for unseen neighbours.

Code notes

  • 71 lines of C++ from the credited upstream file 1825-2.cpp.
  • The implementation visibly relies on ordered lookup, work queue.
  • No explicit loop blocks detected.

Complexity

Verify that each state and transition is processed only a bounded number of times; that determines the traversal cost.

Check the problem constraints before deciding whether this complexity will pass.

Source

Code and credit

This code comes from walkccc LeetCode Solutions by P.-Y. Chen (walkccc) and is used under the MIT licence.

Full codeFinding MK Average · C++C++
Use this to learn the idea, then write your own version.
struct MyMap {  map<int, int> map;  int size = 0;  long sum = 0;}; class MKAverage { public:  MKAverage(int m, int k) : m(m), k(k), kMidSize(m - 2 * k) {}   void addElement(int num) {    q.push(num);    add(num);     if (q.size() > m) {      const int removed = q.front();      q.pop();      remove(removed);    }  }   int calculateMKAverage() {    return q.size() == m ? mid.sum / kMidSize : -1;  }  private:  const int m;  const int k;  const int kMidSize;  queue<int> q;  MyMap top;  MyMap mid;  MyMap bot;   void add(int num) {    add(bot, num);    if (bot.size > k)      add(mid, remove(bot, bot.map.rbegin()->first));    if (mid.size > kMidSize)      add(top, remove(mid, mid.map.rbegin()->first));  }   void remove(int num) {    if (bot.map.contains(num))      remove(bot, num);    else if (mid.map.contains(num))      remove(mid, num);    else      remove(top, num);     if (bot.size < k)      add(bot, remove(mid, mid.map.begin()->first));    if (mid.size < kMidSize)      add(mid, remove(top, top.map.begin()->first));  }   void add(MyMap& m, int num) {    ++m.map[num];    ++m.size;    m.sum += num;  }   int remove(MyMap& m, int num) {    if (--m.map[num] == 0)      m.map.erase(num);    --m.size;    m.sum -= num;    return num;  }}; 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗