Since a C/C++ solution is required then a 2D Array can be used.
All the missing values can be represented by -1 (or any number which is not expected in valid numbers involved in search).
So a empty row can be represented by all -1. See the code below.
Since in C/C++, 2D array is continuously represented in memory. So we can convert 2D array to 1D array.
Now we can sort the array. After sorting, all the '-1' will be at the beginning which can be discarded.
From the leftover elements we can find the max frequency of an element.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int compare (const void * a, const void * b)
{
return ( *(int*)a - *(int*)b );
}
int main()
{
int i, prev, max = -1, count = 0, maxvalue = -1;
int a[4][4] = {{5, 7, 8, -1}, {6, 6, -1, -1}, {-1, -1, -1, -1}, {5, 6, 8, 9}};
//int a[4][4] = {{-1, -1, -1, -1}, {-1, -1, -1, -1}, {-1, -1, -1, -1}, {-1, -1, -1, -1}};
int *b = (int*)a;
int total = sizeof(a) / sizeof(int);
qsort(b, total, sizeof(int), compare);
for(i = 0; i < total; ++i)
{
if(b[i] != -1)
{
break;
}
}
//printf("\n");
i = i + 1;
prev = -1;
count = 0;
if(i < total)
{
prev = b[i];
count = 1;
}
for(i = i + 1; i < total; ++i)
{
//printf("prev=%d, b[i]=%d, max=%d, count=%d\n", prev, b[i], max, count);
if(prev == b[i])
{
count++;;
}
else
{
if(max < count)
{
max = count;
maxvalue = prev;
}
prev = b[i];
count = 1;
}
}
if(max != -1)
{
printf("Max Occurence of %d = %d\n", maxvalue, max);
}
else
{
printf("All the rows are of zero length\n");
}
return 0;
}
//Output:
Max Occurence of 6 = 3