Sparse Arrays

Sort by

recency

|

403 Discussions

|

  • + 0 comments

    Swift solution:

    func matchingStrings(strings: [String], queries: [String]) -> [Int] {
        queries.reduce(into: [Int]()) { partialResult, query in
            let occurrences = strings
                .filter { $0 == query }
                .count
            partialResult.append(occurrences)
        }
    }
    
  • + 0 comments
    def matchingStrings(strings, queries):
        query_results = []
        for i in range(len(queries)):
            occ = 0
            for j in range(len(strings)):
                if queries[i] == strings[j]:
                    occ += 1
            query_results.append(occ) 
        return query_results
    
  • + 0 comments
    • Python 3

    One liner with list comprehensions and no aux/temp variables:

    def matchingStrings(strings, queries):
    
        return [
            sum(int(q == s) for s in strings)
            for q in queries
        ]
    
  • + 0 comments

    JavaScript solution:

    function matchingStrings(strings, queries) {    
        const counts = new Map();
        
        strings.forEach(string => {
            const existingCount = counts.get(string);
            if (existingCount) {
                counts.set(string, existingCount + 1);
            } else {
                counts.set(string, 1);
            }
        })
            
        return queries.map(query => counts.get(query) || 0);
    }
    
  • + 0 comments

    C# Code

    public static List matchingStrings(List strings, List queries) { var resultList = new List();

        foreach(string queryItem in queries)
        {
            resultList.Add(strings.Count(e => e == queryItem));
        }
    
        return resultList;
    }