Search code examples
c++arraysalgorithmintegerfind-occurrences

Find highest frequent element (the smallest one if possible) and its occurrences in integer array


Problems: Find 2 things

  • The highest occurrence in an given unsorted integer array
  • The element that has the highest occurrence and if there are more than one element satisfy (have the same highest occurrence) the result is the smallest element.

Please solve the problems simple as possible, don't use pointers or any advanced containers like hashtable, pair or map (I'm rather beginner)

For example:

{1, 2, 8, 2, 5, 0, 5}

The answer is 2 and 2 (Element 2 and 5 both occur twice but 2 is the smallest)

Here is the code but it only finds the highest occurrence right.

int A[] = {1, 2, 8, 2, 5, 0, 5};
int N = 7;
    int maxCount = 0;
    int minMode = 0;
    for (int i = 0; i <= N - 1; i++) {
           int count = 0;
           for (int j = 0; j <= N - 1; j++) {
             if (A[i] == A[j])
                 count++;
       }
      if (count >= maxCount)
        {
            maxCount = count;
            minMode = A[i];
        }

     }
        cout << maxCount << " " << minMode << endl;

Solution

  • This problem is O(n), but without using structures, it becomes O(n²).

    Here's a simple O(n²) solution:

    int main(){    
        int A[7] = {1, 2, 8, 2, 5, 0, 5};
        int value, occurrences;
        int maxValue = 99999999, maxOccurrences = 0;
        for(int i = 0; i < 7; i++){
            value = A[i]; occurrences = 0;
            for(int j = 0; j < 7; j++) if(A[j] == value) occurrences++;
            if(occurrences > maxOccurrences){
                maxValue = value; maxOccurrences = occurrences;
            }
            else if(occurrences == maxOccurrences){
                if(value < maxValue) {
                    maxValue = value; 
                    maxOccurrences = occurrences; 
                }
            }       
        }
        cout<<maxValue<<" occurs "<<maxOccurrences<<" times"<<endl;
    }
    

    We initialize maxValue being a very large number, just to help the fact that if two numbers occur the same number of times, the lowest will be the chosen.

    Then we just iterate and count.

    A possible optimization is: suppose you are searching for 5 in the array. Always you find a 5, add the occurrence to the amount and set the array value to -1, so when you eventually start from it, you know it is -1 and you can skip that element.