Sparse Arrays

  • + 0 comments

    This is a possible solution in Java:

    public static List<Integer> matchingStrings(List<String> strings, List<String> queries) {
        // Write your code here
            TreeMap<String, Integer> rMap = queries.stream().collect( Collectors.toMap(
                key -> key,
                val -> 0,
                (n, p) -> n,
                TreeMap::new
            ) );
            
            for (String str: strings) {
                if (rMap.containsKey(str)) {
                    rMap.put(str, rMap.get(str) + 1);
                }
            }
            return queries.stream().map( q -> rMap.get(q) ).collect( Collectors.toList() );
        }
    }
    

    This has a runtime complexity of O(m + n) where m is the length of strings and n the length of queries.