Sparse Arrays

Sort by

recency

|

410 Discussions

|

  • + 0 comments

    A O(strings+queries) solution in C++ using unordered_map where all operations used below are at O(1) according to to implementation document.

    vector<int> matchingStrings(vector<string> strings, vector<string> queries) {
        unordered_map<string, int> frequency;
        vector<int>results;
        
        //counts all occurances of str in strings and populates the frequency map
        for(string str: strings)
            frequency[str]++;
        //writes out the queries occurances in result
        for(string str: queries)
            results.push_back(frequency[str]);
        
         return results;
    }
    
  • + 0 comments

    Hi! This was my attempt using Javascript. I think its o(n) time or o(n+q) technically. I could probably avoid storing them in arrays in the groupedStrings array in hindsight

    function matchingStrings(strings, queries) {
        // Write your code here
        
        const groupedStrings = {};
        
        strings.forEach((string) => {
            if (!groupedStrings[string]) {
                groupedStrings[string] = []
            }
            groupedStrings[string].push(string);
        })
        
        queries.forEach((query) => {
            if (groupedStrings[query] == undefined) { 
                console.log(0);
                return;
            }
            console.log(groupedStrings[query].length);
        })
        
    }
    
  • + 0 comments

    Javascript solution

    function matchingStrings(strings, queries) {

    let freqObj = {}
    for(let i=0; i < strings.length; i++) {
        let str = strings[i];  
        freqObj[str] = (freqObj[str] || 0) + 1; 
        }
        return queries.map(querie => freqObj[querie]) 
    
    
    return queries.map(querie => freqObj[querie] || 0); 
    

    }

  • + 0 comments

    from collections import Counter

    def matchingStrings(strings, queries): count = Counter(strings) results = [] for i in queries: if i in count: results.append(count[i]) else: results.append(0) return results

  • + 0 comments

    Kotlin Solution

    fun matchingStrings(strings: Array<String>, queries: Array<String>): Array<Int> {
        val counts = strings.groupingBy { it }.eachCount()
        return queries.map {query -> counts[query] ?: 0 }.toTypedArray()
    }