Problem solution · Python

Finding Mk Average

Finding Mk Average: a Python solution using breadth-first search. Learn the idea, check the complexity, and read the full code, with credit to Kamyu LeetCode Solutions.

Technique
Breadth-first search
Source
Kamyu LeetCode Solutions
Length
64 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

  • 64 lines of Python from the credited upstream file finding-mk-average.py.
  • The implementation visibly relies on 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 Kamyu LeetCode Solutions by kamyu104 and is used under the MIT licence.

Full codeFinding Mk Average · PythonPython
Use this to learn the idea, then write your own version.
# Time:  ctor:           O(1)#        add_element:    O(logn)#        calc_mkaverage: O(1)# Space: O(m) import collectionsfrom sortedcontainers import SortedList  class MKAverage(object):     def __init__(self, m, k):        """        :type m: int        :type k: int        """        self.__m = m        self.__k = k        self.__dq = collections.deque()        self.__sl = SortedList()        self.__total = self.__first_k = self.__last_k = 0     def addElement(self, num):        """        :type num: int        :rtype: None        """        if len(self.__dq) == self.__m:            self.__remove(self.__dq.popleft())        self.__dq.append(num)        self.__add(num)     def calculateMKAverage(self):        """        :rtype: int        """        if len(self.__sl) < self.__m:            return -1        return (self.__total-self.__first_k-self.__last_k)//(self.__m-2*self.__k)     def __add(self, num):        self.__total += num        idx = self.__sl.bisect_left(num)        if idx < self.__k:            self.__first_k += num            if len(self.__sl) >= self.__k:                self.__first_k -= self.__sl[self.__k-1]        if idx > len(self.__sl)-self.__k:            self.__last_k += num            if len(self.__sl) >= self.__k:                self.__last_k -= self.__sl[-self.__k]        self.__sl.add(num)     def __remove(self, num):        self.__total -= num        idx = self.__sl.index(num)        if idx < self.__k:            self.__first_k -= num            self.__first_k += self.__sl[self.__k]        elif idx > (len(self.__sl)-1)-self.__k:            self.__last_k -= num            self.__last_k += self.__sl[-1-self.__k]        self.__sl.remove(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 ↗