Find the maximum repeating number in O(n) time and O(1) extra space in Python

PythonServer Side ProgrammingProgramming

Suppose we have an array of size n, if the elements in the array, are in range from 0 to k-1. Where k is denoted as a positive integer and k <= n. We have to find the maximum repeating number in this array.

So, if the input is like k = 8 and A = [3, 4, 4, 6, 4, 5, 2, 8], then the output will be 4.

To solve this, we will follow these steps −

  • n := size of A

  • for i in range 0 to n, do

    • A[A[i] mod k] := A[A[i] mod k] + k

  • max_val := A[0]

  • result := 0

  • for i in range 1 to n, do

    • if A[i] > max_val, then

      • max_val := A[i]

      • result := i

  • return result

Example 

Let us see the following implementation to get better understanding −

 Live Demo

def get_max_repeating(A, k):
   n = len(A)
   for i in range(n):
      A[A[i]%k] += k
   max_val = A[0]
   result = 0
   for i in range(1, n):
      if A[i] > max_val:
         max_val = A[i]
         result = i
   return result
A = [3, 4, 4, 6, 4, 5, 2, 8]
k = 8
print(get_max_repeating(A, k))

Input

[3, 4, 4, 6, 4, 5, 2, 8], 8

Output

4
raja
Published on 20-Aug-2020 07:57:46
Advertisements