HackerRank Gemstones Solution

Hello Programmers, In this post, you will learn how to solve HackerRank Gemstones Solution. This problem is a part of the HackerRank Algorithms Series.

One more thing to add, don’t straight away look for the solutions, first try to solve the problems by yourself. If you find any difficulty after trying several times, then look for the solutions. We are going to solve the HackerRank Algorithms problems using C, CPP, JAVA, PYTHON, JavaScript & SCALA Programming Languages.

You can practice and submit all HackerRank problem solutions in one place. Find a solution for other domains and Sub-domain. I.e. Hacker Rank solution for HackerRank C ProgrammingHackerRank C++ ProgrammingHackerRank Java Programming, HackerRank Python ProgrammingHackerRank Linux ShellHackerRank SQL Programming, and HackerRank 10 days of Javascript.

HackerRank Gemstones Solution
HackerRank Gemstones Solution

As you already know that this site does not contain only the Hacker Rank solutions here, you can also find the solution for other problems. I.e. Web Technology, Data StructuresRDBMS ProgramsJava Programs Solutions,  Fiverr Skills Test answersGoogle Course AnswersLinkedin Assessment, and Coursera Quiz Answers.

HackerRank Gemstones


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.


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


  • 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.


  • 1 <= n <= 100
  • 1 <= | arr[i] | <= 100
  • Each composition arr[i] consists of only lower-case Latin letters (‘a’‘z’).

Sample Input

STDIN Function
—– —-
3 arr[] size n = 3
abcdde arr = [‘abcdde’, ‘baccd’, ‘eeabg’]

Sample Output



Only a and b occur in every rock.

HackerRank Gemstones Solution

Gemstones Solution in C


int main()
    int n,i,j,freq[150][27]={0},count;
    char str[200];
    return 0;

Gemstones Solution in Cpp

#include <cstdio>
#include <cmath>
#include <iostream>
#include <numeric>
#include <algorithm>
#include <string>
#include <memory.h>
#include <memory>
#include <functional>
#include <vector>
#include <ctime>
#include <cstdlib>
#include <iomanip>
#include <time.h>
#include <map>
#include <set>
#include <climits>
#include <queue>
#include <sstream>
#include <stack>
#include <iostream>
#include <vector>
#include <cstdlib>
#include <ctime>
#include <string>
#include <fstream>
#include <iterator>
#include <cmath>
#include <algorithm>
#include <functional>

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

using namespace std;

string s[101];

int main()
    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;
    cout << ans << "\n";
    return 0;

Gemstones Solution in Java

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;

public class Solution {	
	BufferedReader reader;
    StringTokenizer tokenizer;
    PrintWriter out;
	public void solve() throws IOException {				
		int N = nextInt();
		boolean[] existed = new boolean[26];
		Arrays.fill(existed, true);
		for (int i = 0; i < N; i++) {
			boolean[] existed2 = new boolean[26];
			char[] s = reader.readLine().toCharArray();
			for (int j = 0; j < s.length; j++) {
				existed2[s[j] - 'a'] = true;
			for (int j = 0; j < 26; j++) {
				existed[j] &= existed2[j];
		int cnt = 0;
		for (int j = 0; j < 26; j++) {
			if (existed[j]) cnt++;
	 * @param args
	public static void main(String[] args) {
		new Solution().run();
	public void run() {
        try {
            reader = new BufferedReader(new InputStreamReader(System.in));
            tokenizer = null;
            out = new PrintWriter(System.out);
        } catch (Exception e) {

    int nextInt() throws IOException {
        return Integer.parseInt(nextToken());

    long nextLong() throws IOException {
        return Long.parseLong(nextToken());

    double nextDouble() throws IOException {
        return Double.parseDouble(nextToken());

    String nextToken() throws IOException {
        while (tokenizer == null || !tokenizer.hasMoreTokens()) {
            tokenizer = new StringTokenizer(reader.readLine());
        return tokenizer.nextToken();


Gemstones Solution in Python

from string import ascii_lowercase
chars = ascii_lowercase
n = input()
R = []
c = 0
for i in range(n):
for x in chars:
    present = True
    for r in R:
        if x not in r:
            present = False
    if present:
        c += 1
print c

Gemstones Solution using JavaScript

'use strict';

function processData(input) {
    var parse_fun = function (s) { return parseInt(s, 10); };

    var lines = input.split('\n');
    var N = parse_fun(lines.shift());
    var gems = {};

    for (var i = 0; i < N; i++) {
        var s = lines[i].split('');
        var gem = {};
        for (var j = 0; j < s.length; j++) {
            gem[s[j]] = 1;
        for (var j in gem) {
            if (gems[j] === undefined) {
                gems[j] = 0;

    var res = 0;
    for (var i in gems) {
        if (gems[i] == N) { res++; }


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

Gemstones Solution in Scala

object Solution {

  def main(args: Array[String]) {
    var elements:Map[Char, Int] = Map()
    val words = readInt()

    for (i <- 0 until words) {
      elements = incrementElements(elements, readLine())

    println(elements.foldLeft[Int](0)((acc, element) => if (element._2 >= words) acc + 1 else acc))

  def incrementElements(elements: Map[Char, Int], gem: String): Map[Char, Int] = {
    var items:Map[Char, Int] = elements

    gem.toList.foreach { p: Char =>
      items = if (elements.contains(p)) items.updated(p, elements(p) + 1) else items + (p -> 1)

    return items

Gemstones Solution in Pascal

var s:string;
d:array[1..1000,'a'..'z'] of boolean;
function check(u:char):boolean;
 var i:longint;
   for i:=1 to n do
    if d[i,u]=false then exit(false);
     for i:=1 to n do
       for j:=1 to  length(s) do
     for u:='a' to 'z' do
      if check(u) then

Disclaimer: This problem (Gemstones) is generated by HackerRank but the solution is provided by Chase2learn. This tutorial is only for Educational and Learning purposes.


1. How do you solve the first question in HackerRank?

If you want to solve the first question of Hackerrank then you have to decide which programing language you want to practice i.e C programming, Cpp Programing, or Java programming then you have to start with the first program HELLO WORLD.

2. How do I find my HackerRank ID?

You will receive an email from HackerRank to confirm your access to the ID. Once you have confirmed your email, the entry will show up as verified on the settings page. You will also have an option to “Make primary”. Click on that option. Read more

3. Does HackerRank detect cheating?

yes, HackerRank uses a powerful tool to detect plagiarism in the candidates’ submitted code. The Test report of a candidate highlights any plagiarized portions in the submitted code and helps evaluators to verify the integrity of answers provided in the Test.

4. Does HackerRank use camera?

No for coding practice Hackerrank does not use camera but for companies’ interviews code submission time Hackerrank uses the camera.

5. Should I put HackerRank certificate on resume?

These certificates are useless, and you should not put them on your resume. The experience you gained from getting them is not useless. Use it to build a portfolio, and link to it on your resume. 

6. Can I retake HackerRank test?

The company which sent you the HackerRank Test invite owns your Test submissions and results. It’s their discretion to permit a reattempt for a particular Test. If you wish to retake the test, we recommend that you contact the concerned recruiter who invited you to the Test and request a re-invite. 

7. What is HackerRank?

HackerRank is a tech company that focuses on competitive programming challenges for both consumers and businesses. Developers compete by writing programs according to provided specifications. Wikipedi

Finally, we are now, in the end, I just want to conclude some important message for you

Note:- I compile all programs, if there is any case program is not working and showing an error please let me know in the comment section. If you are using adblocker, please disable adblocker because some functions of the site may not work correctly.

Please share our posts on social media platforms and also suggest to your friends to Join Our Groups. Don’t forget to subscribe. 

Sharing Is Caring

Leave a Comment