Monday 9 September 2013

Find the maximum repeating number in the array

Given an array of size n, the array contains numbers in 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 8 the given array be arr[] = {2, 3, 3, 5, 3, 4, 1, 7};  the maximum repeating number would be 3.

Implementation

Method 1:

static int findMaxRepeatingNumber(int []array, int k){
     //Boundary condition
if(array == null || array.length == 0)
return -1;

int maxCount = Integer.MIN_VALUE;  //max count
int number = -1;
     //Iterate over all the elements of the array
for(int i = 0; i < array.length; i++){
int count = 1; //count of current number
for(int j = 1; j < array.length; j++){
if(array[i] == array[j])
count++;
}
if(count > maxCount){
maxCount = count;
number = array[i];
}
}
return number;  //return the maximum repeating number
}

Time Complexity : O(N^2)
Space Complexity : O(1)

Method 2:

static int findMaxRepeatingNumber2(int []array, int k){
      //Boundary condition
if(array == null || array.length == 0)
return -1;

int []count = new int[k]; //hold the count of number
 
      for(int i = 0; i < array.length; i++){
count[ array[i] ] ++;
}

//get the max count
int max = Integer.MIN_VALUE;
int number = -1;
 
      for(int i = 0; i < k; i++){
if(max < count[i]){
max = count[i];
number = i;
}
}
return number;
}

Time Complexity : O(N)
Space Complexity : O(K)

1 comment:

  1. public static void main(String[] args) {
    int[] array = {1, 2, 4, 2, 5, 9, 4, 4, 5, 3, 5, 6, 1};
    System.out.println(maxRepeatInArray(array));
    }

    private static int maxRepeatInArray(int[] input) {

    Hashtable ht = new Hashtable();

    for(int i : input){
    if(ht.containsKey(i)){
    int currentValue = ht.get(i);
    ht.put(i, currentValue + 1);
    }
    else {
    ht.put(i, 1);
    }
    }

    int maxValueSoFar = 0;
    int maxRepeatedNumber = -1;

    for(Integer i: ht.keySet()){
    if(ht.get(i) > maxValueSoFar){
    maxValueSoFar = ht.get(i);
    maxRepeatedNumber = i;
    }
    }

    return maxRepeatedNumber;
    }

    ReplyDelete