Sparse Arrays

Sort by

recency

|

245 Discussions

|

  • + 0 comments
    public static List<Integer> matchingStrings(List<String> strings, List<String> queries) {
    // Write your code here
        List<Integer> finalList = new ArrayList<>();
        Integer tempValue=0;
        for(String s1 :queries){
            for(String s2 :strings){
                if((s1.equals(s2))){
                    tempValue ++;
                }
            }
            finalList.add(tempValue);
            tempValue = 0;
        }
        return finalList;
    }
    
  • + 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