Friday, January 17, 2020

Sorting Array of Strings - Hacker Rank Solution

Sorting Array of Strings - Hacker Rank Solution

You can use any sorting algorithm to sort strings in . Bubble sort is fast enough for the constraints in this problem. Let's look how should the bodies of the comparing functions look like.
For the lexicographical sort you should use  from the library . It does exactly what the problem wants. You should not forget to use different signs in the functions:  means  is lexicographically bigger than  vice versa.
For the  you should calculate number of distinct characters in the strings. In order to do this, declare an array  of length  with all items equal to . Go through all characters of your string and when you meet the letter with the corresponding item in  equal to  set it to  and add  to the number of distinct letters.
For the sorting by length you should use  from . It returns exactly the length of the string you wanted.
int lexicographic_sort(const char* a, const char* b){
    return strcmp(a, b) > 0;
}

int lexicographic_sort_reverse(const char* a, const char* b){
    return strcmp(a, b) <= 0;
}

int sort_by_number_of_distinct_characters(const char* a, const char* b){
    int c1 = 0, c2 = 0;
    int hsh1[26] = {0}, hsh2[26] = {0};
    int n1 = strlen(a);
    int n2 = strlen(b);

    for(int i = 0; i < n1; i++){
        hsh1[a[i] - 'a'] = 1;   
    }

    for(int i = 0; i < n2; i++){
        hsh2[b[i] - 'a'] = 1;   
    }

    for(int i = 0; i < 26; i++){
        if(hsh1[i])
            c1++;
        if(hsh2[i])
            c2++;
    }
    if( c1 != c2)
        return c1 > c2;
    else
        return strcmp(a, b)  > 0;

}

int sort_by_length(const char* a, const char* b){
    if(strlen(a) != strlen(b))
        return strlen(a) > strlen(b);
    else
        return strcmp(a, b) >  0;
}

void string_sort(char** arr,const int len,int (*cmp_func)(const char* a, const char* b)){
    for(int i = 1; i < len; i++){
        int j = i;
        char* p = arr[i];
        while(j > 0){
            if((*cmp_func)(arr[j-1],p) > 0 )
                arr[j] = arr[j-1];
            else
                break;
            j--;
        }
        arr[j] = p;
    }
}

1 comment:

Powered by Blogger.