FRom hackerrank

John has collected various rocks. Each rock has various minerals embeded in it. Each type of mineral is designated by a lowercase letter in the range . 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 John's collection.
Given a list of minerals embedded in each of John's rocks, display the number of types of gemstones he has in his collection.
For example, the array of mineral composition strings . The minerals  and  appear in each composite, so there are  gemstones.

Solution in C# -

class Solution {
    static int gemstones(string[] arr) {
        string s = arr[0];
        int gems = 0;
        for(int i=0; i<s.Length; i++)
        {
            int count = 1;
            for(int j=1; j<arr.Length; j++)
            {
                if(arr[j].Contains(s[i]))
                {
                    count++;
                    int index = arr[j].IndexOf(s[i]);
                    arr[j] = arr[j].Substring(0,index)+arr[j].Substring(index+1);
                }
            }
            if(count>=arr.Length)
            gems++;
        }
        return gems;
    }
    static void Main(string[] args) {
        TextWriter textWriter = new StreamWriter(@System.Environment.GetEnvironmentVariable("OUTPUT_PATH"), true);
        int n = Convert.ToInt32(Console.ReadLine());
        string[] arr = new string [n];
        for (int i = 0; i < n; i++) {
            string arrItem = Console.ReadLine();
            arr[i] = arrItem;
        }
        int result = gemstones(arr);
        textWriter.WriteLine(result);
        textWriter.Flush();
        textWriter.Close();
    }
}

Post a Comment

Previous Post Next Post