HackerRank Gold Badge In C | All Problem Solution

HackerRank Gold Badge In C | All Problem Solution

HackerRank Gold Badge In C | All Problem Solution is available here. Practice them and get a gold badge in C programming. Total 25 solved problems of hackerRank in C. Solution of C hackerRank.

Join For More Challenge Solution & Updates

"Hello World!" in C

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>

int main() 
{
    char s[100];
    scanf("%[^\n]%*c", &s);
    printf("Hello, World!\n%s",s);
    return 0;
}

Playing With Characters

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>

int main() 
{
    char a,b[10],c[50];
    scanf("%c%s\n",&a,b);
    fflush(stdin);
    scanf("%[^\n]%*c", c);
    printf("%c\n%s\n%s",a,b,c);
    return 0;
}

Sum and Difference of Two Numbers

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>

int main()
{
    int a,b;
    float c,d;
    scanf("%d%d",&a,&b);
    scanf("%f%f",&c,&d);
    printf("%d %d\n",a+b,a-b);
	printf("%.1f %.1f",c+d,c-d);
    
    return 0;
}

Functions in C

#include <stdio.h>
int main() {
    int a, b, c, d;
    scanf("%d %d %d %d", &a, &b, &c, &d);
    int ans = max_of_four(a, b, c, d);
    printf("%d", ans);
    return 0;
}
max_of_four(int a,int b,int c, int d){
        if(a>b&&a>c&&a>d){
            return a;
        }
        else if(b>a&&b>c&&b>d){
            return b;
        }
        else if(c>a&&c>b&&c>d){
            return c;
        }
        else{
            return d;
        }
    }

Pointers in C

#include <stdio.h>
#include <stdlib.h>

void update(int *a,int *b) {
    // Complete this function 
    int x,y;
    x = *a + *b;
    y = *a - *b;
    *a = x;
    *b =abs(y); 
}

int main() {
    int a, b;
    int *pa = &a, *pb = &b;
    
    scanf("%d %d", &a, &b);
    update(pa, pb);
    printf("%d\n%d", a, b);

    return 0;
}

Conditional Statements in C

#include <stdio.h>

static const char *strings[] = {"one","two","three","four","five",
                                "six","seven","eight","nine"};
int main()
{
    int n = 0;
    if (scanf("%d",&n) < 1)
        return 1;
    
    if (n >= 1 && n <= 9)
        printf("%s",strings[n-1]);
    else
        printf("Greater than 9");
    
    return 0;
}

For Loop In C

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>

int main() 
{
    int a, b;
    scanf("%d\n%d", &a, &b);
    char *s[]={"one","two","three","four","five","six","seven","eight","nine"};
    for(int i=a;i<=b;i++){
        if(i<=9){
            printf("%s\n",s[i-1]);
        }
        else{
            if(i%2==0){
                printf("even\n");
            }
            else{
                printf("odd\n");
            }
        }
    }
  	// Complete the code.

    return 0;
}

Sum of Digits of a Five Digit Number

#include<stdio.h>
int main() {

int n;
scanf("%d", &n);
int digit, temp, sum = 0;
temp = n;
//Complete the code to calculate the sum of the five digits on n.
while(temp > 0)
{
    digit = temp % 10;
    sum = sum + digit;
    temp = temp / 10;
}
printf("%d\n",sum);
return 0;
}

Bitwise Operators

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>

void calculate_the_maximum(int n, int k) {
  //Write your code here.
  int maxA=0;
  int maxO=0;
  int maxX=0;
  int i,j;
  for(i=1;i<n;i++){
      for(j=i+1;j<=n;j++){
          if(((i&j)>maxA)&&(i&j)<k){
              maxA=i&j;
            }
          if((i|j)>maxO&&(i|j)<k){
              maxO=i|j;
            }
          if((i^j)>maxX&&(i^j)<k){
              maxX=i^j;
            }
        }
    }
    printf("%d\n%d\n%d\n", maxA, maxO, maxX);
}

int main() {
    int n, k;
    scanf("%d %d", &n, &k);
    calculate_the_maximum(n, k);
 
    return 0;
}

Printing Pattern Using Loops

#include <stdio.h>

int main() 
{

    int n;
    scanf("%d", &n);
    int len = n*2 - 1;
    for(int i=0;i<len;i++){
        for(int j=0;j<len;j++){
            int min = i < j ? i : j;
            min = min < len-i ? min : len-i-1;
            min = min < len-j-1 ? min : len-j-1;
            printf("%d ", n-min);
        }
        printf("\n");
    }
    return 0;
}

1D Arrays in C

#include <stdio.h>
int main()
{
    int n,val,sum=0;
    scanf("%d",&n);
    while(n--)
    {
        scanf("%d",&val);
        sum+=val;
    }
    printf("%i",sum);
}

Array Reversal

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int num, *arr, i;
    scanf("%d", &num);
    arr = (int*) malloc(num * sizeof(int));
    for(i = 0; i < num; i++) {
        scanf("%d", arr + i);
    }


    /* Write the logic to reverse the array. */
        int temp;
    for (i = 0; i < num / 2; i++) {
        temp = (int) *(arr + num - i - 1);
        *(arr + num - i - 1) = *(arr + i);
        *(arr + i) = temp;
    }  

    for(i = 0; i < num; i++)
        printf("%d ", *(arr + i));
    return 0;
}

Printing Tokens

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main() {

    char *s;
// Important approach to be remembered
    s = malloc(1024 * sizeof(char));
    scanf("%[^\n]", s);
    s = realloc(s, strlen(s) + 1);
    
//logic
    for(int i = 0; i < strlen(s) ; i++)
    {
        if(s[i] == ' ')
            printf("\n");
        else
            printf("%c",s[i]);
    }    
    return 0;
}

Digit Frequency

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>

int main() {
    int* nums = (int*) malloc(10 * sizeof(int));
    char c;
    
    for(int i = 0; i < 10; i++)
        *(nums+i) = 0;

    while(scanf("%c", &c) == 1)
        if(c >= '0' && c <= '9')
            (*(nums+(c-'0')))++;
    
    for(int i = 0; i < 10; i++)
        printf("%d ", *(nums+i));
    
    return EXIT_SUCCESS;
}

Dynamic Array in C



int main()
{
    int total_number_of_shelves;
    scanf("%d", &total_number_of_shelves);
    
    int total_number_of_queries;
    scanf("%d", &total_number_of_queries);
    
    total_number_of_books=(int*)malloc(sizeof(int)*total_number_of_shelves);
    
    total_number_of_pages=(int**)malloc(sizeof(int*)*total_number_of_shelves);
    
    for(int i=0; i<total_number_of_shelves; i++){
        total_number_of_books[i]=0;
        total_number_of_pages[i]=(int*)malloc(sizeof(int));
    }
    
    while (total_number_of_queries--) {
        int type_of_query;
        scanf("%d", &type_of_query);
        
        if (type_of_query == 1) {
            int x, y;
            scanf("%d %d", &x, &y);
            *(total_number_of_books+x)+=1;
            *(total_number_of_pages+x)=realloc(*(total_number_of_pages+x), *(total_number_of_books+x)*sizeof(int));
            *(*(total_number_of_pages+x)+*(total_number_of_books+x)-1)=y;

Calculate the Nth term

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
//Complete the following function.
int find_nth_term(int n, int a, int b, int c) {
    if(n == 1)
        return a;
    else if (n == 2)
        return b;
    else if (n == 3)
        return c;
    
    return find_nth_term(n-1,a,b,c)+find_nth_term(n-2,a,b,c)+find_nth_term(n-3,a,b,c);
    
}

int main() {
    int n, a, b, c;
  
    scanf("%d %d %d %d", &n, &a, &b, &c);
    int ans = find_nth_term(n, a, b, c);
 
    printf("%d", ans); 
    return 0;
}

Students Marks Sum

//Complete the following function.
int marks_summation(int* marks, int number_of_students, char gender) {
    int sum = 0;
    for (int i = (gender == 'b' ? 0 : 1); i < number_of_students; i = i + 2) 
        sum += *(marks + i);
    
    return sum;
}

Sorting Array of Strings


int lexicographic_sort(const char* a, const char* b) {
    int x = strcmp(a,b);
    if(x>0)
        return 1;
    else
        return 0;
}

int lexicographic_sort_reverse(const char* a, const char* b) {
   int x = strcmp(a,b);
    if(x>0)
        return 0;
    else
        return 1;
}
int distinct(const char *a){
    int x[26];
    
    for(int i = 0; i<26;i++){
        x[i] = 0;
         //printf("x[%d] = %d\t", i,x[i]);
    }
       
    for(int i=0;a[i] != '\0'; i++){
        x[a[i] - 'a']++;
    }
    int count = 0;
    for(int i=0;i<26;i++){
        if(x[i] >= 1)
            count++;
    }
   // printf("%s=%d\n", a, count);
    return count;
}

int sort_by_number_of_distinct_characters(const char* a, const char* b) {
    int d1 = distinct(a), d2 = distinct(b);
    int  x = strcmp(a,b);
    if(d1>d2){
        return 1;
    }else if(d1 == d2){
        if(x>0)
            return 1;
         else
            return 0;
    }else{
        return 0;
    }
}

int sort_by_length(const char* a, const char* b) {
    int x = strlen(a), y = strlen(b), z = strcmp(a,b);
    // printf("%s=%d %s=%d cmp = %d\n",a,x,b,y,z);
    if(x==y){
        if(z>0)
            return 1;
        else
            return 0;
    }else if(x>y){
        return 1;
    }else {
        return 0;
    }

}

void string_sort(char** arr,const int len,int (*cmp_func)(const char* a, const char* b)){
    for(int i=0;i<len;i++){
        for(int j=0;j<len-1;j++){
            if(cmp_func(arr[j], arr[j+1])){
             char *temp;
            //  strcpy(temp, arr[j]);
             
            //  strcpy(arr[j], arr[j+1]);
            //  strcpy(arr[j+1], temp);
            temp = arr[j];
             
            arr[j]= arr[j+1];
            arr[j+1]= temp;

            }
        }
    }
    
}

Permutations of Strings

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int next_permutation(int n, char **s){
    // Find non-increasing suffix
    int i = n-1;
    while(i>0 && strcmp(s[i-1],s[i])>=0) 
        i--;    // find key
    if (i<=0) return 0;
    
    // Swap key with its successor in suffix
    int j = n-1;
    while(strcmp(s[i-1],s[j])>=0) 
        j--;    // find rightmost successor to key
    char *tmp = s[i-1];
    s[i-1] = s[j];
    s[j] = tmp;
    
    // Reverse the suffix
    j = n-1;
    while(i<j) {
        tmp = s[i];
        s[i] = s[j];
        s[j] = tmp;
        i++;
        j--;
    }
    return 1;
}

Variadic functions in C


int  sum (int count,...) {
    int sum=0;
    va_list values;
    va_start(values,count);
    for(int i=0;i<count;i++){
        sum+=va_arg(values,int);
    }
    va_end(values);
    return sum;
}

int min(int count,...) {
    int min=MAX_ELEMENT,test;  
    va_list values;
    va_start(values,count);
    for(int i=0;i<count;i++){
        test=va_arg(values,int);
        if(min>test){
            min=test;
        }  
    }
    va_end(values);
    return min;
}

int max(int count,...) {
    int max=MIN_ELEMENT,test;
    va_list values;
    va_start(values,count);
    for(int i=0;i<count;i++){
        test=va_arg(values,int);
        if(max<test){
            max=test;
        }  
    }
    va_end(values);
    return max;
}

Querying the Document

char* kth_word_in_mth_sentence_of_nth_paragraph(char**** document, int k, int m, int n) {
    return document[n-1][m-1][k-1];
}

char** kth_sentence_in_mth_paragraph(char**** document, int k, int m) {
    return document[m-1][k-1];
}

char*** kth_paragraph(char**** document, int k) {
    return document[k-1];
}

char** split_string(char* text, char delim) {
    assert(text != NULL);
    char** result = malloc(1*sizeof(char*));
    int size = 1;
    
    char* temp = strtok(text, &delim);
    *result = temp;
    
    while(temp != NULL) {
        size++;
        result = realloc(result,size*sizeof(char*));
        temp = strtok(NULL, &delim);
        result[size-1] = temp;
    }
    return result;
}

char**** get_document(char* text) {
    assert(text != NULL);
    
    // split text by '\n' and count number of paragraphs
    char** paragraphs = split_string(text, '\n');
    int npar = 0;
    while (paragraphs[npar] != NULL) {
        npar++;
    }
    
    char**** doc = malloc((npar+1)*sizeof(char***));
    // set last position to NULL for the user
    // to know when the array ends.
    doc[npar] = NULL; 
    
    int i = 0;
    while (paragraphs[i] != NULL) {
        
        // split sentences of paragraph by '.' and count number of sentences
        char** sentences = split_string(paragraphs[i], '.');
        int nsen = 0;
        while(sentences[nsen] != NULL) {
            nsen++;
        }
        
        doc[i] = malloc((nsen+1)*sizeof(char**));
        doc[i][nsen] = NULL; 
        
        int j = 0;
        while (sentences[j] != NULL) {
            
            doc[i][j] = split_string(sentences[j], ' ');
            j++;
        }
        i++;
    }
    
    return doc; 
}

Boxes through a Tunnel

typedef struct {
    int height;
    int length;
    int width;
}box;

int get_volume(box b) {
    return b.length * b.height * b.width;
}

int is_lower_than_max_height(box b) {
    return b.height < 41 ? 1 : 0;
}

Small Triangles, Large Triangles


void sort_by_area(triangle *tr, int n) {
// Sort an array a of the length n
    int *p=malloc(n*sizeof(int)); 
//create array of size n to store "volumes"
    for(int i=0;i<n;i++)
    {
    float a=(tr[i].a+tr[i].b+tr[i].c)/2.0;
//use 2.0 compulsary int/int gives int, int/float gives float
       p[i]=(a*(a-tr[i].a)*(a-tr[i].b)*(a-tr[i].c));
//formula without sqrt as areas are different guarenteed 
//because sqrt dosent work well with float values
    }
//bubble sort
    for(int i=0;i<n;i++)    
    {
        for(int j=0;j<n-i-1;j++)
        {
            if(p[j]>p[j+1])     
            {
                int temp=p[j];
                p[j]=p[j+1];
                p[j+1]=temp;
//swapping array of areas in ascending
//and simuntaneously the structure contents
                temp=tr[j].a;
                tr[j].a=tr[j+1].a;
                tr[j+1].a=temp;
                temp=tr[j].b;
                tr[j].b=tr[j+1].b;
                tr[j+1].b=temp;
                temp=tr[j].c;
                tr[j].c=tr[j+1].c;
                tr[j+1].c=temp;
            }
        }
    }
}

Post Transition

#include <stdio.h>
#include <stdlib.h>
#define MAX_STRING_LENGTH 6

struct package
{
   char* id;
   int weight;
};

typedef struct package package;

struct post_office
{
   int min_weight;
   int max_weight;
   package* packages;
   int packages_count;
};

typedef struct post_office post_office;

struct town
{
   char* name;
   post_office* offices;
   int offices_count;
};

typedef struct town town;


void print_all_packages(town t)
{
    printf("%s:\n", t.name);
    for (int i = 0; i < t.offices_count; i++)
    {
        printf("\t%d:\n", i);
        for (int j = 0; j < t.offices[i].packages_count; j++)
            printf("\t\t%s\n", t.offices[i].packages[j].id);
    }
}

void send_all_acceptable_packages(town* source, int source_office_index, town* target, int target_office_index)
{
    int n = 0;
    for (int i = 0; i < source->offices[source_office_index].packages_count; i++)
        if (source->offices[source_office_index].packages[i].weight >= target->offices[target_office_index].min_weight &&
            source->offices[source_office_index].packages[i].weight <= target->offices[target_office_index].max_weight)
            ++n;
    package* newPackages = malloc(sizeof(package)*(n + target->offices[target_office_index].packages_count));
    package* oldPackages = malloc(sizeof(package)*(source->offices[source_office_index].packages_count - n));
    for (int i = 0; i < target->offices[target_office_index].packages_count; i++)
        newPackages[i] = target->offices[target_office_index].packages[i];
    n = target->offices[target_office_index].packages_count;
    int m = 0;
    for (int i = 0; i < source->offices[source_office_index].packages_count; i++)
        if (source->offices[source_office_index].packages[i].weight >= target->offices[target_office_index].min_weight &&
            source->offices[source_office_index].packages[i].weight <= target->offices[target_office_index].max_weight)
        {
            newPackages[n] = source->offices[source_office_index].packages[i];
            ++n;
        }
        else
        {
            oldPackages[m] = source->offices[source_office_index].packages[i];
            ++m;
        }
    target->offices[target_office_index].packages_count = n;
    free(target->offices[target_office_index].packages);
    target->offices[target_office_index].packages = newPackages;
    source->offices[source_office_index].packages_count = m;
    free(source->offices[source_office_index].packages);
    source->offices[source_office_index].packages = oldPackages;
}

int number_of_packages(town t)
{
    int ans = 0;
    for (int i = 0; i < t.offices_count; i++)
        ans += t.offices[i].packages_count;
    return ans;
}

town town_with_most_packages(town* towns, int towns_count)
{
    int ans;
    int max_packages = -1;
    for (int i = 0; i < towns_count; i++)
        if (number_of_packages(towns[i]) > max_packages)
        {
            max_packages = number_of_packages(towns[i]);
            ans = i;
        }
    return towns[ans];
}

town* find_town(town* towns, int towns_count, char* name)
{
    for (int i = 0; i < towns_count; i++)
        if (!strcmp(towns[i].name, name))
            return &(towns[i]);
    return &towns[0];
}

int main()
{
   int towns_count;
   scanf("%d", &towns_count);
   town* towns = malloc(sizeof(town)*towns_count);
   for (int i = 0; i < towns_count; i++) {
      towns[i].name = malloc(sizeof(char) * MAX_STRING_LENGTH);
      scanf("%s", towns[i].name);
      scanf("%d", &towns[i].offices_count);
      towns[i].offices = malloc(sizeof(post_office)*towns[i].offices_count);
      for (int j = 0; j < towns[i].offices_count; j++) {
         scanf("%d%d%d", &towns[i].offices[j].packages_count, &towns[i].offices[j].min_weight, &towns[i].offices[j].max_weight);
         towns[i].offices[j].packages = malloc(sizeof(package)*towns[i].offices[j].packages_count);
         for (int k = 0; k < towns[i].offices[j].packages_count; k++) {
            towns[i].offices[j].packages[k].id = malloc(sizeof(char) * MAX_STRING_LENGTH);
            scanf("%s", towns[i].offices[j].packages[k].id);
            scanf("%d", &towns[i].offices[j].packages[k].weight);
         }
      }
   }
   int queries;
   scanf("%d", &queries);
   char town_name[MAX_STRING_LENGTH];
   while (queries--) {
      int type;
      scanf("%d", &type);
      switch (type) {
      case 1:
         scanf("%s", town_name);
         town* t = find_town(towns, towns_count, town_name);
         print_all_packages(*t);
         break;
      case 2:
         scanf("%s", town_name);
         town* source = find_town(towns, towns_count, town_name);
         int source_index;
         scanf("%d", &source_index);
         scanf("%s", town_name);
         town* target = find_town(towns, towns_count, town_name);
         int target_index;
         scanf("%d", &target_index);
         send_all_acceptable_packages(source, source_index, target, target_index);
         break;
      case 3:
         printf("Town with the most number of packages is %s\n", town_with_most_packages(towns, towns_count).name);
         break;
      }
   }
   return 0;
}

Structuring the Document


typedef struct word word;
typedef struct sentence sentence;
typedef struct paragraph paragraph;
typedef struct document document;

void add_char(word* _word, char character)
{
    static int size;

    if (_word->data == NULL)
    {
        _word->data = (char*)malloc(0);
        size = 2;
    }

    _word->data = (char*)realloc(_word->data, size * sizeof(char));
    _word->data[size - 2] = character;
    _word->data[size - 1] = 0;

    size++;
}

void add_word(sentence* _sentence, word* _word)
{
    if (_sentence->data == NULL)
    {
        _sentence->data = (word*)malloc(0);
        _sentence->word_count = 0;
    }

    _sentence->word_count++;
    _sentence->data = (word*)realloc(_sentence->data, _sentence->word_count * sizeof(word));
    _sentence->data[_sentence->word_count - 1] = *_word;
    _word->data = NULL;
}

void add_sentence(paragraph* _paragraph, sentence* _sentence)
{
    if (_paragraph->data == NULL)
    {
        _paragraph->data = (sentence*)malloc(0);
        _paragraph->sentence_count = 0;
    }

    _paragraph->sentence_count++;
    _paragraph->data = (sentence*)realloc(_paragraph->data, _paragraph->sentence_count * sizeof(sentence));
    _paragraph->data[_paragraph->sentence_count - 1] = *_sentence;
    _sentence->data = NULL;
}

void add_paragraph(document* _document, paragraph* _paragraph)
{
    if (_document->data == NULL)
    {
        _document->data = (paragraph*)malloc(0);
        _document->paragraph_count = 0;
    }

    _document->paragraph_count++;
    _document->data = (paragraph*)realloc(_document->data, _document->paragraph_count * sizeof(paragraph));
    _document->data[_document->paragraph_count - 1] = *_paragraph;
    _paragraph->data = NULL;
}

struct document get_document(char* text)
{
    document _document;
    paragraph _paragraph;
    sentence _sentence;
    word _word;

    _document.data = NULL;
    _paragraph.data = NULL;
    _sentence.data = NULL;
    _word.data = NULL;

    for (unsigned int i = 0; i <= strlen(text); i++)
    {
        switch (text[i])
        {
        case ' ':
            add_word(&_sentence, &_word);
            break;

        case '.':
            add_word(&_sentence, &_word);
            add_sentence(&_paragraph, &_sentence);
            break;

        case '\n':
        case '\0':
            add_paragraph(&_document, &_paragraph);
            break;

        default:
            add_char(&_word, text[i]);
            break;
        }
    }

    return _document;
}

struct word kth_word_in_mth_sentence_of_nth_paragraph(struct document Doc, int k, int m, int n)
{
    return Doc.data[n - 1].data[m - 1].data[k - 1];
}

struct sentence kth_sentence_in_mth_paragraph(struct document Doc, int k, int m)
{
    return Doc.data[m - 1].data[k - 1];
}

struct paragraph kth_paragraph(struct document Doc, int k)
{
    return Doc.data[k - 1];
}

Here is the all 25 solution of C. You can understand and learn it from a single place easily. Do comment for more solutions and solved challenges.

Join For More Challenge Solution & Updates

Leave a Comment

Your email address will not be published. Required fields are marked *

0

Tech Info