Open In App

Working and need of Mo’s Algorithm

Mo’s Algorithm is a generic algorithm. It can be used in many problems that require processing range queries in a static array, i.e., the array values do not change between the queries. In each query, for a given range [a, b] the idea is to calculate the value based on the array elements between positions of a and b. Since the array is static, the queries can be processed in any order, and Mo’s Algorithm processes the queries in a special order which guarantees that the algorithm works efficiently.

It maintains an active range of the array, and the result of a query concerning the active range is known at each moment. The algorithm processes the queries one by one, and always moves the endpoints of the active range by inserting and removing elements.



Time Complexity: O(N√N*f(N)), where the array has N elements and there are N queries and each insertion and removal of an element takes O(f(N)) time.

The trick in Mo’s algorithm is the order in which the queries are processed:



Example: Consider a problem where there are given a set of queries, each of them corresponding to a range in an array, and the task is to calculate for each query the number of distinct elements in the range. In Mo’s algorithm, the queries are always sorted in the same way, but it depends on the problem of how the answer to the query is maintained. 

Article Tags :