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 directly look for the solutions, first try to solve the problems of Hackerrank by yourself. If you find any difficulty after trying several times, then you can look for solutions.
HackerRank Gemstones Solution
Task
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.
Constraints
- 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’]
baccd
eeabg
Sample Output
2
Explanation
Only a and b occur in every rock.
HackerRank Gemstones Solution
Gemstones Solution in C
#include<stdio.h> int main() { int n,i,j,freq[150][27]={0},count; char str[200]; scanf("%d",&n); for(i=0;i<n;i++) { scanf("%s\n",str); for(j=0;str[j]!='\0';j++) { freq[i][str[j]-97]++; } } count=0; for(i=0;i<26;i++) { for(j=0;j<n;j++) if(freq[j][i]>0) continue; else break; if(j==n) count++; } printf("%d\n",count); 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() { 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; }
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++; } out.println(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); solve(); reader.close(); out.close(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } 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): R.append(raw_input()) 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; } gems[j]++; } } var res = 0; for (var i in gems) { if (gems[i] == N) { res++; } } console.log(res); } process.stdin.resume(); process.stdin.setEncoding("ascii"); 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; kq,i,j,n:longint; u:char; d:array[1..1000,'a'..'z'] of boolean; function check(u:char):boolean; var i:longint; Begin for i:=1 to n do if d[i,u]=false then exit(false); exit(true); end; Begin fillchar(d,sizeof(d),false); readln(n); for i:=1 to n do Begin readln(s); for j:=1 to length(s) do d[i,s[j]]:=true; end; for u:='a' to 'z' do if check(u) then inc(kq); write(kq); end.
Disclaimer: This problem (Gemstones) is generated by HackerRank but the Solution is Provided by BrokenProgrammers. This tutorial is only for Educational and Learning purposes.