Solution 1:
// declare an alphabet array
int counter[26] = {0};
char *string = "inputstringofcharacters";
char ch; int i=0;
// foreach alphabet in input string, increment counter by 1
while( ch = *(string + i++) ) {
*(counter + (int)ch)++;
}
// find the max of array.
int max_count = 0;
char max_element;
for( i=0; i<26 data-blogger-escaped-counter="" data-blogger-escaped-i="" data-blogger-escaped-if=""> max_count) {
max_count = counter[i];
max_element = (char)i;
}
}
Complexity:
Traverse complete array once, O(n)
Traverse the count array once, O(26)
Total complexity O(26*n) = O(n)
Solution 2:
typedef struct node {
char info;
node *left, *right;
}NODE;
// traverse input and construct binary search tree O(n)
// find the max element in the binary search tree O(log n)
Complexity: O(n log n)
No comments :
Post a Comment