Sparse Arrays in C - HackerRank Solution
Solution for hackerRank problem Sparse Arrays in C
Problem :
There is a collection of input strings and a collection of query strings. For each query string, determine how many times it occurs in the list of input strings. Return an array of the results.
Example,
stringList = [ 'ab', 'ab' , 'abc' ]
queries = [ 'ab' , 'abc' , 'bc' ]
There are 2 instances of 'ab', 1 of 'abc' and 0 of 'bc'. For each query, add an element to the return array,
results = [2,1,0].
Function Description
Complete the function matchingStrings in the editor below. The function must return an array of integers representing the frequency of occurrence of each query string in stringList.
matchingStrings has the following parameters:
- string stringList[n] - an array of strings to search
- string queries[q] - an array of query strings
Returns
- int[q]: an array of results for each query
Input Format
The first line contains and integer n, the size of stringList[].
Each of the next n lines contains a string stringList[i].
The next line contains q, the size of queries[].
Each of the next q lines contains a string queries[i].
Constraints
1 <= n <= 1000
1 <= q <= 1000
1 <= |stringList[i], |queries[i]| <= 20
Sample Input 1
Sample Output 1
Explanation 1
Here, "aba" occurs twice, in the first and third string. The string "xzxb" occurs once in the fourth string, and "ab" does not occur at all.
Sample Input 2
Sample Output 2
#include <assert.h>
#include <limits.h>
#include <math.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* readline();
// Complete the matchingStrings function below.
// Please store the size of the integer array to be returned in result_count pointer. For example,
// int a[3] = {1, 2, 3};
//
// *result_count = 3;
//
// return a;
//
int main()
{
char str1[1000][20],str2[1000][20];
int flag = 0,n, strings_count, queries_count;
scanf("%d",&strings_count);
for(int i = 0 ; i < strings_count ; i++)
{
scanf("%s",str1[i]);
}
scanf("%d",&queries_count);
for(int j = 0 ; j < queries_count ; j++)
{
scanf("%s",str2[j]);
}
for(int j = 0 ; j < queries_count ; j++)
{
flag = 0;
for(int i = 0 ; i < strings_count ; i++)
{
n = strcmp(str2[j],str1[i]);
if(n == 0)
flag += 1;
}
printf("%d\n", flag);
}
}
char* readline() {
size_t alloc_length = 1024;
size_t data_length = 0;
char* data = malloc(alloc_length);
while (true) {
char* cursor = data + data_length;
char* line = fgets(cursor, alloc_length - data_length, stdin);
if (!line) { break; }
data_length += strlen(cursor);
if (data_length < alloc_length - 1 || data[data_length - 1] == '\n') { break; }
size_t new_length = alloc_length << 1;
data = realloc(data, new_length);
if (!data) { break; }
alloc_length = new_length;
}
if (data[data_length - 1] == '\n') {
data[data_length - 1] = '\0';
}
data = realloc(data, data_length);
return data;
}
Comments
Post a Comment