The Wayback Machine - https://web.archive.org/web/20240707000450/https://www.geeksforgeeks.org/find-the-maximum-repeating-number-in-ok-time/
Open In App

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

Last Updated : 20 Jun, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Given an array of size n, the array contains numbers in the range from 0 to k-1 where k is a positive integer and k <= n. Find the maximum repeating number in this array. For example, let k be 10 the given array be arr[] = {1, 2, 2, 2, 0, 2, 0, 2, 3, 8, 0, 9, 2, 3}, the maximum repeating number would be 2. The expected time complexity is O(n) and extra space allowed is O(1). Modifications to array are allowed. 

Recommended Practice

The naive approach is to run two loops, the outer loop picks an element one by one, and the inner loop counts a number of occurrences of the picked element. Finally, return the element with a maximum count. The time complexity of this approach is O(n^2).
A better approach is to create a count array of size k and initialize all elements of count[] as 0. Iterate through all elements of input array, and for every element arr[i], increment count[arr[i]]. Finally, iterate through count[] and return the index with maximum value. This approach takes O(n) time, but requires O(k) space.

Following is the O(n) time and O(1) extra space approach. 
Let us understand the approach with a simple example where arr[] = {2, 3, 3, 5, 3, 4, 1, 7}, k = 8, n = 8 (number of elements in arr[]).

  1. Iterate though input array arr[], for every element arr[i], increment arr[arr[i]%k] by k (arr[] becomes {2, 11, 11, 29, 11, 12, 1, 15 })
  2. Find the maximum value in the modified array (maximum value is 29). Index of the maximum value is the maximum repeating element (index of 29 is 3).
  3. If we want to get the original array back, we can iterate through the array one more time and do arr[i] = arr[i] % k where i varies from 0 to n-1.

How does the above algorithm work? Since we use arr[i]%k as index and add value k at the index arr[i]%k, the index which is equal to maximum repeating element will have the maximum value in the end. Note that k is added maximum number of times at the index equal to maximum repeating element and all array elements are smaller than k.
Following is C++ implementation of the above algorithm. 

C++




// C++ program to find the maximum repeating number
 
#include<iostream>
using namespace std;
 
// Returns maximum repeating element in arr[0..n-1].
// The array elements are in range from 0 to k-1
int maxRepeating(int* arr, int n, int k)
{
    // Iterate though input array, for every element
    // arr[i], increment arr[arr[i]%k] by k
    for (int i = 0; i< n; i++)
        arr[arr[i]%k] += k;
 
    // Find index of the maximum repeating element
    int max = arr[0], result = 0;
    for (int i = 1; i < n; i++)
    {
        if (arr[i] > max)
        {
            max = arr[i];
            result = i;
        }
    }
 
    /* Uncomment this code to get the original array back
       for (int i = 0; i< n; i++)
          arr[i] = arr[i]%k; */
 
    // Return index of the maximum element
    return result;
}
 
// Driver program to test above function
int main()
{
    int arr[] = {2, 3, 3, 5, 3, 4, 1, 7};
    int n = sizeof(arr)/sizeof(arr[0]);
    int k = 8;
 
    cout << "The maximum repeating number is " <<
         maxRepeating(arr, n, k) << endl;
 
    return 0;
}


Java




// Java program to find the maximum repeating number
import java.io.*;
 
class MaxRepeating {
 
    // Returns maximum repeating element in arr[0..n-1].
    // The array elements are in range from 0 to k-1
    static int maxRepeating(int arr[], int n, int k)
    {
        // Iterate though input array, for every element
        // arr[i], increment arr[arr[i]%k] by k
        for (int i = 0; i< n; i++)
            arr[(arr[i]%k)] += k;
 
        // Find index of the maximum repeating element
        int max = arr[0], result = 0;
        for (int i = 1; i < n; i++)
        {
            if (arr[i] > max)
            {
                max = arr[i];
                result = i;
            }
        }
 
        /* Uncomment this code to get the original array back
        for (int i = 0; i< n; i++)
          arr[i] = arr[i]%k; */
 
        // Return index of the maximum element
        return result;
    }
 
    /*Driver function to check for above function*/
    public static void main (String[] args)
    {
 
        int arr[] = {2, 3, 3, 5, 3, 4, 1, 7};
        int n = arr.length;
        int k=8;
        System.out.println("Maximum repeating element is: " +
                           maxRepeating(arr,n,k));
    }
}
/* This code is contributed by Devesh Agrawal */


Python3




# Python program to find the maximum repeating number
 
# Returns maximum repeating element in arr[0..n-1].
# The array elements are in range from 0 to k-1
def maxRepeating(arr, n,  k):
 
    # Iterate though input array, for every element
    # arr[i], increment arr[arr[i]%k] by k
    for i in range(0,  n):
        arr[arr[i]%k] += k
 
    # Find index of the maximum repeating element
    max = arr[0]
    result = 0
    for i in range(1, n):
     
        if arr[i] > max:
            max = arr[i]
            result = i
 
    # Uncomment this code to get the original array back
    #for i in range(0, n):
    #    arr[i] = arr[i]%k
 
    # Return index of the maximum element
    return result
 
 
# Driver program to test above function
arr = [2, 3, 3, 5, 3, 4, 1, 7]
n = len(arr)
k = 8
print("The maximum repeating number is",maxRepeating(arr, n, k))
 
# This code is contributed by
# Smitha Dinesh Semwal


C#




//C# program to find the maximum repeating
// number
using System;
 
class GFG {
     
    // Returns maximum repeating element
    // in arr[0..n-1].
    // The array elements are in range
    // from 0 to k-1
    static int maxRepeating(int []arr,
                             int n, int k)
    {
        // Iterate though input array, for
        // every element arr[i], increment
        // arr[arr[i]%k] by k
        for (int i = 0; i< n; i++)
            arr[(arr[i]%k)] += k;
 
        // Find index of the maximum
        // repeating element
        int max = arr[0], result = 0;
         
        for (int i = 1; i < n; i++)
        {
            if (arr[i] > max)
            {
                max = arr[i];
                result = i;
            }
        }
 
        // Return index of the
        // maximum element
        return result;
    }
 
    /*Driver function to check for
     above function*/
    public static void Main ()
    {
 
        int []arr = {2, 3, 3, 5, 3, 4, 1, 7};
        int n = arr.Length;
        int k=8;
         
        Console.Write("Maximum repeating "
                          + "element is: "
                  + maxRepeating(arr,n,k));
    }
}
 
// This code is contributed by Sam007.


PHP




<?php
// PHP program to find the
// maximum repeating number
 
// Returns maximum repeating
// element in arr[0..n-1].
// The array elements are
// in range from 0 to k-1
function maxRepeating($arr, $n, $k)
{
     
    // Iterate though input array,
    // for every element arr[i],
    // increment arr[arr[i]%k] by k
    for ($i = 0; $i< $n; $i++)
        $arr[$arr[$i] % $k] += $k;
 
        // Find index of the
        // maximum repeating
        // element
        $max = $arr[0];
        $result = 0;
    for ($i = 1; $i < $n; $i++)
    {
        if ($arr[$i] > $max)
        {
            $max = $arr[$i];
            $result = $i;
        }
    }
 
    /* Uncomment this code to
       get the original array back
       for (int i = 0; i< n; i++)
       arr[i] = arr[i] % k; */
 
    // Return index of the
    // maximum element
    return $result;
}
 
    // Driver Code
    $arr = array(2, 3, 3, 5, 3, 4, 1, 7);
    $n = sizeof($arr);
    $k = 8;
 
    echo "The maximum repeating number is ",
        maxRepeating($arr, $n, $k);
 
// This Code is contributed by Ajit
?>


Javascript




<script>
 
// JavaScript program to find the maximum repeating number
 
// Returns maximum repeating element in arr[0..n-1].
// The array elements are in range from 0 to k-1
function maxRepeating(arr, n, k)
{
    // Iterate though input array, for every element
    // arr[i], increment arr[arr[i]%k] by k
    for (let i = 0; i< n; i++)
        arr[arr[i]%k] += k;
 
    // Find index of the maximum repeating element
    let max = arr[0], result = 0;
    for (let i = 1; i < n; i++)
    {
        if (arr[i] > max)
        {
            max = arr[i];
            result = i;
        }
    }
 
    /* Uncomment this code to get the original array back
    for (int i = 0; i< n; i++)
        arr[i] = arr[i]%k; */
 
    // Return index of the maximum element
    return result;
}
 
// Driver program to test above function
 
    let arr = [2, 3, 3, 5, 3, 4, 1, 7];
    let n = arr.length;
    let k = 8;
 
    document.write("The maximum repeating number is " +
        maxRepeating(arr, n, k) + "<br>");
 
// This code is contributed by Surbhi Tyagi.
 
</script>


Output

The maximum repeating number is 3

Time Complexity : O(n) 
Auxiliary Space : O(1)

Exercise: The above solution prints only one repeating element and doesn’t work if we want to print all maximum repeating elements. For example, if the input array is {2, 3, 2, 3}, the above solution will print only 3. What if we need to print both of 2 and 3 as both of them occur maximum number of times. Write a O(n) time and O(1) extra space function that prints all maximum repeating elements. (Hint: We can use maximum quotient arr[i]/n instead of maximum value in step 2).
Note that the above solutions may cause overflow if adding k repeatedly makes the value more than INT_MAX.  



Similar Reads

Find maximum in a stack in O(1) time and O(1) extra space
Given a stack of integers. The task is to design a special stack such that the maximum element can be found in O(1) time and O(1) extra space. Examples: Given Stack : 2 5 1 64 --&gt; Maximum So Output must be 64 when getMax() is called. Below are the different functions designed to push and pop elements from the stack. Push(x) : Inserts x at the to
11 min read
Find duplicates in O(n) time and O(1) extra space | Set 1
Given an array of n elements that contains elements from 0 to n-1, with any of these numbers appearing any number of times. Find these repeating numbers in O(n) and use only constant memory space. Note: The repeating element should be printed only once. Example: Input: n=7 , array[]={1, 2, 3, 6, 3, 6, 1}Output: 1, 3, 6Explanation: The numbers 1 , 3
6 min read
Javascript Program to Rearrange positive and negative numbers in O(n) time and O(1) extra space
An array contains both positive and negative numbers in random order. Rearrange the array elements so that positive and negative numbers are placed alternatively. Number of positive and negative numbers need not be equal. If there are more positive numbers they appear at the end of the array. If there are more negative numbers, they too appear in t
3 min read
Rearrange positive and negative numbers in O(n) time and O(1) extra space
An array contains both positive and negative numbers in random order. Rearrange the array elements so that positive and negative numbers are placed alternatively. A number of positive and negative numbers need not be equal. If there are more positive numbers they appear at the end of the array. If there are more negative numbers, they too appear at
11 min read
Design a dynamic stack using arrays that supports getMin() in O(1) time and O(1) extra space
Design a special dynamic Stack using an array that supports all the stack operations such as push(), pop(), peek(), isEmpty(), and getMin() operations in constant Time and Space complexities. Examples: Assuming the right to left orientation as the top to bottom orientation and performing the operations: Push(10): 10 is added to the top of the stack
15+ min read
Duplicates in an array in O(n) time and by using O(1) extra space | Set-3
Given an array of n elements which contains elements from 0 to n-1, with any of these numbers appearing any number of times. Find these repeating numbers in O(n) and using only constant memory space. It is required that the order in which elements repeat should be maintained. If there is no repeating element present then print -1. Examples: Input :
10 min read
Merge Sort with O(1) extra space merge and O(n log n) time [Unsigned Integers Only]
We have discussed Merge sort. How to modify the algorithm so that merge works in O(1) extra space and algorithm still works in O(n Log n) time. We may assume that the input values are integers only. Examples: Input : 5 4 3 2 1 Output : 1 2 3 4 5 Input : 999 612 589 856 56 945 243 Output : 56 243 589 612 856 945 999Recommended PracticeMerge SortTry
10 min read
Design a stack that supports getMin() in O(1) time and O(1) extra space
Design a Data Structure SpecialStack that supports all the stack operations like push(), pop(), isEmpty(), isFull() and an additional operation getMin() which should return minimum element from the SpecialStack. All these operations of SpecialStack must have a time and space complexity of O(1). Note: To implement SpecialStack, you should only use s
15+ min read
Count frequencies of all elements in array in O(1) extra space and O(n) time
Given an unsorted array of n integers that can contain integers from 1 to n. Some elements can be repeated multiple times and some other elements can be absent from the array. Count the frequency of all elements that are present and print the missing elements. Examples: Input: arr[] = {2, 3, 3, 2, 5}Output: Below are frequencies of all elements 1 -
15+ min read
Find the two non-repeating elements in an array of repeating elements/ Unique Numbers 2
Given an array arr[] containing 2*N+2 positive numbers, out of which 2*N numbers exist in pairs whereas the other two number occur exactly once and are distinct. Find the other two numbers. Return in increasing order. Example: Input: N = 2, arr[] = {1, 2, 3, 2, 1, 4}Output:3 4 Explanation: 3 and 4 occur exactly once. Input: N = 1, arr[] = {2, 1, 3,
9 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg