Skip to content
TheCScience
TheCScience
  • Pages
    • About US
    • Contact US
    • Privacy Policy
    • DMCA
  • Human values
  • NCERT Solutions
  • HackerRank solutions
    • HackerRank Algorithms problems solutions
    • HackerRank C solutions
    • HackerRank C++ solutions
    • HackerRank Java problems solutions
    • HackerRank Python problems solutions
TheCScience

HackerRank Gemstones Problem Solution

Yashwant Parihar, April 26, 2023April 28, 2023

In this post, we will solve HackerRank Gemstones Problem Solution.

There is a collection of rocks where each rock has various minerals embeded in it. Each type of mineral is designated by a lowercase letter in the range ascii[a – z]. There may be multiple occurrences of a mineral in a rock. A mineral is called a gemstone if it occurs at least once in each of the rocks in the collection.
Given a list of minerals embedded in each of the rocks, display the number of types of gemstones in the collection.
Example
arr = [‘abc’, ‘abc’, ‘bc’]
The minerals b and c appear in each rock, so there are 2 gemstones.

Function Description

Complete the gemstones function in the editor below.

gemstones has the following parameter(s):

  • string arr[n]: an array of strings

Returns

  • int: the number of gemstones found

Input Format
The first line consists of an integer n, the size of arr.
Each of the next n lines contains a string arr[i] where each letter represents an occurence of
a mineral in the current rock.

Sample Input

STDIN       Function
-----       --------
3           arr[] size n = 3
abcdde      arr = ['abcdde', 'baccd', 'eeabg']
baccd
eeabg

Sample Output

2

Explanation

Only a and b occur in every rock.

HackerRank Gemstones Problem Solution
HackerRank Gemstones Problem Solution

Gemstones C Solution

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

int main(int argc, char *argv[]) {
    int N;
    scanf("%d", &N);
    
    char rocks[N][101];
    for(int i = 0; i < N; i++) {
        scanf("%s", rocks[i]);   
    }
    
    char alphabet[] = "abcdefghijklmnopqrstuvwxyz";
    char tested[27] = "\n";
    int nbGems = 0;
    
    for(int i = 0; i < strlen(alphabet); i++) {
        char element = alphabet[i];
        int isGem = 1;
        for(int j = 0; j < N; j++) {
            if(strchr(rocks[j], element) == NULL) {
                isGem = 0;
                break;
            }
        }
        
        if(isGem)
            nbGems++;
    }
    
    printf("%d", nbGems);
    
    return 0;
}

Gemstones C++ Solution

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <string>
#include <set>
using namespace std;


int main() {
    /* Enter your code here. Read input from STDIN. Print output to STDOUT */
    string s;
    int N;
    cin >> N;
    int used[26] = {0};
    for (int i = 0; i < N; ++i)
    {
        cin >> s;
        set<char> st(s.begin(), s.end());
//        bool curUsed[26] = {false};
        for (const char & c : st)
        {
//            if (!curUsed[c - 'a'])
              ++used[c - 'a'];
//            curUsed[c - 'a'] = true;
        }
        
        
    }
    
    cout << count(begin(used), end(used), N);
    
    return 0;
}

Gemstones C Sharp Solution

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace subROUTINE.HackerRank.Algorithms
{
    public class GemStones
    {
        public static void Main(string[] args)
        {
            int rockCount = Int32.Parse(Console.ReadLine());
            List<char> firstLineElements = Console.ReadLine().Distinct().ToList();
            rockCount--;

            for (int i = 0; i < rockCount; i++)
            {
                var currentLine = Console.ReadLine();
                firstLineElements.RemoveAll(x => !currentLine.Contains(x));
            }

            Console.WriteLine(firstLineElements.Count);
        }
    }
}

Gemstones Java Solution

import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.*;
import java.util.regex.*;
import java.util.stream.*;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;

class Result {

    /*
     * Complete the 'gemstones' function below.
     *
     * The function is expected to return an INTEGER.
     * The function accepts STRING_ARRAY arr as parameter.
     */

    public static int gemstones(List<String> arr) {
    // Write your code here
    List<Character> characters= new ArrayList<>();
        int count=0;
        int charCount=0;
        for (String word:arr) {
            for (int i = 0; i < word.length(); i++) {
                if (!characters.contains(word.charAt(i))){
                    characters.add(word.charAt(i));
                }
            }
        }

        for (int i = 0; i < characters.size(); i++) {
            for (int j = 0; j < arr.size(); j++) {
                if (arr.get(j).indexOf(characters.get(i))!=-1){
                    charCount++;
                }
            }
            if (charCount==arr.size()){
                count++;
            }
            charCount=0;
        }

        return count;

    }

}

public class Solution {
    public static void main(String[] args) throws IOException {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));

        int n = Integer.parseInt(bufferedReader.readLine().trim());

        List<String> arr = IntStream.range(0, n).mapToObj(i -> {
            try {
                return bufferedReader.readLine();
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        })
            .collect(toList());

        int result = Result.gemstones(arr);

        bufferedWriter.write(String.valueOf(result));
        bufferedWriter.newLine();

        bufferedReader.close();
        bufferedWriter.close();
    }
}

Gemstones JavaScript Solution

'use strict';

process.stdin.resume();
process.stdin.setEncoding('ascii');

var __input = ""
process.stdin.on('data', function (data) { __input += data; });
process.stdin.on('end', function() { processData(__input); });

function processData (input) {
    var lines = input.split("\n");
    var T = parseInt(lines.shift(), 10);
    var tests = lines.slice(0, T);
    var gems = [];
    var init = false;
    
    function countGems (str) {
        str = str.split("");
        if (!init) {
            init = true;
            for (var i = 0; i < str.length; i++) {
                if (gems.indexOf(str[i]) == -1) gems.push(str[i]);
            }
        } else {
            gems = gems.filter(function (gem) {
                if (str.indexOf(gem) == -1) return false;
                return true;
            });
        }
    }
    
    tests.map(countGems);
    process.stdout.write("" + gems.length + "\n"); 
}

Gemstones Python Solution

import fileinput

l = []
g = []
cnt = 0
flag = 1
for line in fileinput.input():
    l.append(line)    
l.pop(0)

for i in range(len(l[0])):
    if g.count(l[0][i]) == 0:
        g.append(l[0][i])

for char in g:
    for x in l:
        for i in range(len(x)):
            if x[i] == char:
                break
        else:
            flag = 0
            break
    if flag == 1:
        cnt = cnt + 1
    flag = 1
print(cnt)

Other Solutions

  • HackerRank Alternating Characters Solution
  • HackerRank The Full Counting Sort Solution
c C# C++ HackerRank Solutions java javascript python CcppCSharpHackerrank Solutionsjavajavascriptpython

Post navigation

Previous post
Next post

Leave a Reply

You must be logged in to post a comment.

Similar websites

  • Programming
  • Data Structures
©2025 TheCScience | WordPress Theme by SuperbThemes