Gemstones Hackerrank problem solution

Gemstones Hackerrank

John has discovered various rocks.In which, each rock is composed of various elements, and each element is represented by a lower-case Latin letter from ‘a’ to ‘z’. An element can be present multiple times in a rock. So the condition is ” an element is called a gem-element if it occurs at least once in each of the rocks”.

Given the list of N rocks with their compositions, display the number of gem-elements that exist in those rocks.

Input Format

The first line consists of an integer, N, the number of rocks.
Each of the next N lines contains a rock’s composition. Each composition consists of lower-case letters of English alphabet.

Constraints

1 < =N <= 100
Each composition consists of only lower-case Latin letters (‘a’-‘z’).
1 <= length of each composition <= 100

Output Format

Print the number of gem-elements that are common in these rocks. If there are none, print 0.

Sample Input

3
abcdde
baccd
eeabg

Sample Output

2
Explanation

Only “a” and “b” are the two kinds of gem-elements, since these are the only characters that occur in every rock’s composition.

Solution

Each rock has a unique composition consisting of small alphabets of English. A gem stone consists of a single character only and it should be present in all the rocks. Given the list of rocks with their compositions, you have to print how many different kinds of gemstones he has.
Very simple simulation. For each character from ‘a’ to ‘z’, we can check if it’s present in all rocks, and print the answer accordingly.

Gemstones Hackerrank

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

#include <string>


#include <cstdio>
#include <cstring>
#include <vector>

using namespace std;

string s[101];

int main()
{
    ios::sync_with_stdio(0);
    int n;
    cin >> n;
    for(int i = 0 ; i < n ; ++i)
        cin >> s[i];
    
    int ans = 0;
    for(char ch = 'a' ; ch <= 'z' ; ++ch)
    {
        bool fl = 1;
        for(int i = 0 ; fl && i < n ; ++i)
        {
            fl = 0;
            for(int j = 0 ; j < s[i].size() ; ++j)
            if(s[i][j] == ch)
                fl = 1;
        }
        if(fl)
            ++ans;
    }
    cout << ans << "\n";
    return 0;
t=input()
assert t<=100 and t>=1
a=set(raw_input())
for _ in range(t-1):
  b=set(raw_input())
  a = a.intersection(b)
print len(a)

A web developer(Front end and Back end), and DBA at csdamu.com. Currently working as Salesforce Developer @ Tech Matrix IT Consulting Private Limited. Check me @about.me/s.saifi

Leave a reply:

Your email address will not be published.