Sort by

recency

|

1049 Discussions

|

  • + 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)
    
  • + 0 comments

    C# solution:

    public static int gemstones(List<string> arr)
        {
            HashSet<char> common = new HashSet<char>(arr[0]);
            for (int i = 1; i < arr.Count; i++)
            {
                common.IntersectWith(arr[i]);
            }
            return common.Count;
        }
    
  • + 0 comments
    def gemstones(arr):
        # Write your code here
        common = set(arr[0])
        
        for i in range(1, len(arr)):
            common &= set(arr[i])
            
        return len(common)