Sort by

recency

|

1051 Discussions

|

  • + 0 comments

    Efficient? No. Solution? Yes.

    void deDup(string &str) {
        sort(str.begin(), str.end()); 
        auto last = std::unique(str.begin(), str.end()); 
        str.erase(last, str.end()); 
    }
    
    int gemstones(vector<string> arr) {
        map<char, int> aparitions;
        
        for(int i=0; i<arr.size(); i++){
            deDup(arr[i]);
            for(int j=0; j<arr[i].size(); j++){
                aparitions[arr[i][j]] += 1; 
            }
        }
        
        int rocks = 0;
        for (auto& pair : aparitions){
            if(pair.second==arr.size()){
                rocks++;
            }
        }
        
        return rocks;
    }
    
  • + 0 comments

    *

    def gemstones(arr):
        # Write your code here
        ls = list(set(arr[0]))
        sm = len(ls)
        for x in ls:
            for i in range(1,len(arr)):
                if x not in arr[i]:
                   sm -=1
                   break
        return sm
    
  • + 0 comments

    One more solution

    public static int gemstones(List<String> arr) {
        Set<Set<String>> countset = arr.stream().map(s -> s.split("")).map(Arrays::stream)
                .map(stream -> {
                    Set<String> set = new HashSet<>();
                    stream.forEach(set::add);
                    return set;
                }).collect(Collectors.toSet());
        Iterator<Set<String>> iterator = countset.iterator();
        Set<String> firstSet = iterator.next();
        while(iterator.hasNext()) {
            Set<String> set = iterator.next();
            firstSet.retainAll(set);
        }
        return firstSet.size();
    }
    
  • + 0 comments
    public static int gemstones(List<String> arr) {
        Map<String, Long> countmap = arr.stream().map(s -> s.split("")).map(Arrays::stream)
                .map(stream -> {
                    Set<String> set = new HashSet<>();
                    stream.forEach(set::add);
                    return set;
                }).
                flatMap(Set::stream).
                collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
        return (int)countmap.entrySet().stream().filter(en -> en.getValue() == arr.size()).count();
    }
    
  • + 0 comments

    Here is a O(n+m) time and O(1) space solution in python.

    O(n+m) is the average of the worse case scenarion, where all 26 chars will be present in every string. This means in the worse case the time will be O(Ch*n).

    def gemstones(arr):
        res = set(arr[0])
        
        for i in range(1, len(arr)):
            res &= set(arr[i])
        
        return len(res)