Sparse Arrays

Sort by

recency

|

244 Discussions

|

  • + 0 comments

    Java using a map to save the frequencies. This solution iterates each list only once.

        public static List<Integer> matchingStrings(List<String> strings, List<String> queries) {
        // Write your code here
            HashMap<String, Integer> stringsMap = new HashMap<>();
            for(String string : strings){
                if(stringsMap.containsKey(string)){
                    stringsMap.put(string, stringsMap.get(string) + 1);
                }else{
                    stringsMap.put(string, 1);
                }
            }
            
            ArrayList<Integer> results = new ArrayList<>(queries.size());
            for(String query: queries){
                Integer frequency = stringsMap.get(query);
                results.add(frequency == null ? 0 : frequency);
            }
            return results;
        }
    
  • + 0 comments

    Here is the typescript solution for the better time complexity and space complexity. The time complexity over here will be o(n + q). I have created a hash map for the faster retrival of the information: Python:

    def matchingStrings(strings, queries):
        strings_frequency = {}
        for string in strings:
            strings_frequency[string] = strings_frequency.get(string, 0) + 1
    
        return [strings_frequency.get(query, 0) for query in queries]
    
  • + 0 comments

    Here is the typescript solution for the better time complexity and space complexity. The time complexity over here will be o(n + q). I have created a hash map for the faster retrival of the information: Typescript:

    function matchingStrings(strings: string[], queries: string[]): number[] {
      // Write your code here
      const stringsFreq: { [key: string]: number } = {};
      for (const s of strings) {
        stringsFreq[s] = (stringsFreq[s] || 0) + 1;
      }
      return queries.map(q => stringsFreq[q] || 0);
    }
    
  • + 0 comments

    Guys, the go code won't compile because you guys used strings as a name of a variable in the test code

  • + 0 comments

    GO: your provided code in Go has a bug: you used the name "strings" for a var.