Sparse Arrays Problem Of HackerRank

 Although this was a medium level problem but still was a fairly simple problem from HackerRank in which we were getting two lists or arrays, both containing strings and we just had to tell the number of occurrences of the queries(the second array) strings in the stringList(the first array), we had to return the ans in the form of a list. In python it was just completed by just using a list comprehension in the return statement, and then I thought of doing this in Cpp and it was obvious that the lines of code will increase. The difference is of 11 lines of code. In Cpp we don't have a function like count so I had to iteratively go through the entire vector and maintain the count, also I had to make a separate vector to return as the ans. Overall this question was fairly simple in Python than in Cpp.

Here's the accepted code in both the languages:-

vector<int> matchingStrings(vector<string> stringList, vector<string> queries) {
    int queries_size=queries.size(),stringList_size=stringList.size();
    vector<int> ans(queries_size,0);
    for(int i=0;i<queries_size;i++){
        for(int j=0;j<stringList_size;j++){
            if(stringList[j]==queries[i]){
                ans[i]+=1;
            }
        }
    }
    return ans;
}

/**** Python ****/
def matchingStrings(stringList, queries):
    return [stringList.count(elem) for elem in queries]

Comments

Popular Posts