Sort by

recency

|

1041 Discussions

|

  • + 0 comments

    python 3

    def gemstones(arr):
        gems = set(arr[0])
        
        for stone in arr[1:]:
            gems = set(stone).intersection(gems)
        
        return len(gems)
    
  • + 0 comments

    Here are my c++ approaches of solving this problem, video explanation here : https://youtu.be/EjhdJXN3a3c

    Solution 1 : Using a list of all possible characters

    int gemstones(vector<string> arr) {
        int result = 0;
        string liste = "abcdefghijklmnopqrstuvwxyz";
        for(int j = 0; j < liste.size(); j++){
            int cp = 0;
            for(int i = 0; i < arr.size(); i++){
                if(arr[i].find(liste[j]) != string::npos) cp++;
            }
            if(cp == arr.size())result++;
        }
        return result;
    }
    

    Solution 2 : Using set of the shortest element of the array of string

    string getShortest(vector<string> arr) {
        string result = arr[0];
        for(int i = 1; i < arr.size(); i++){
            if(arr[i].size() < result.size()) result = arr[i];
        }
        return result;
    }
    int gemstones(vector<string> arr) {
        int result = 0;
        string shortest = getShortest(arr);
        set<char> liste(shortest.begin(), shortest.end());
        for(auto j = liste.begin(); j != liste.end(); j++){
            int cp = 0;
            for(int i = 0; i < arr.size(); i++){
                if(arr[i].find(*j) != string::npos) cp++;
            }
            if(cp == arr.size())result++;
        }
        return result;
    }
    
  • + 0 comments

    My Java solution:

    public static int gemstones(List<String> arr) {
            //given an array of strings, determine the number of characters that appear in all strings 
            //get the set of chars in the first string
            Set<Character> commonSet = new HashSet<>();
            for(char mineral: arr.get(0).toCharArray()){
                commonSet.add(mineral);
            }
            //iterate through every other string, add their chars to currentset, and use retain all to find the intersection
            for(int i = 1; i < arr.size(); i++){
                Set<Character> currentSet = new HashSet<>();
                for(char mineral: arr.get(i).toCharArray()){
                    currentSet.add(mineral);
                }
                commonSet.retainAll(currentSet); //intersection to find common chars
            }
            //return size of the og set
            return commonSet.size();
        }
    
  • + 0 comments
    def gemstones(arr):
        m=set(arr[0])
        for i in (arr):
            m=set(i).intersection(m)
        return len(m)
    
  • + 0 comments

    def gemstones(arr):

    string_set = set(arr[0])
    
    
    for i in range(1, len(arr)):
    
        temp_set = set(arr[i])
        string_set = string_set.intersection(temp_set)
    
    return len(string_set)