Go step by step: try it yourself before the video and the visual. Progress saves on this device.
0 / 110 pointsSolved (Easy) 0/20Reviews 0/50Mastered 0/25Practice steps 0/15
Step 1
Know these before you start
Practise each one here, or tick what you already know
Builds on: Counting subarrays with a map of totals
Step 2
Try it on paper
5–10 minutes, no code yet
In the wild · Caches and duplicate detection: A hash map answers “have I seen this before?” in one step. It's how apps cache results, and how a photo app spots the same picture uploaded twice.
ProblemProblem statementGiven a collection of input strings and a collection of query strings, for each query string, determine how many times it occurs in the list of input strings. Return an array of the results.ReadHide
💡 Problem Statement
Given a collection of input strings and a collection of query strings, for each query string, determine how many times it occurs in the list of input strings. Return an array of the results.
Code it here
Tab / Shift+Tab indent · ⌘/Ctrl+/ comments · ⌘/Ctrl+Enter runs · Esc leaves the editor
Step 6
Get it accepted
All test cases pass
Step 7
Review it so it sticks
Re-solve from memory after
The step that matters most: without reviews most of a solved problem fades within weeks. Three short re-solves, each just as you start to forget, are what make it yours.
Your notes
Three lines in your own words. They come back with this problem's reviews, so you can check yourself after recalling the solution.
Solve it yourself before you look
Reading the solution first feels like progress, but it makes the next similar problem — and the interview version — much harder, because you skipped the part where you figure it out. Give it an honest 20–30 minutes. Stuck? Re-read the pattern, watch the concept video, or try the brute force first.
Hidden: approach · solution code · optimal solution
Approach
Use a Hash Map to count input string frequencies in O(N), then lookup queries in O(1).
🔑 Key Pattern: Frequency Counter
The core task is to find the count of many different items within a large list. The Brute Force approach involves nested loops, which is slow. The Frequency Counter pattern (using a Hash Map/Dictionary) converts the O(N × M) search complexity into a single linear pass.
| Pattern Name | Goal | Optimization Strategy |
|---|---|---|
| Frequency Counter | Count the occurrences of unique items in a list efficiently. | Pre-processing: Spend O(N) time to build a map of all unique strings and their counts. |
| The Trick | Look up the count of a query string directly from the map in O(1) time instead of scanning the entire input list (O(N)) repeatedly. |
🛠️ Brute Force Approach (O(N × M))
Approach: Use nested loops. For each query, iterate through the entire list of input strings and increment a counter every time a match is found.
Time Complexity: O(N × M), where N is the size of stringList and M is the size of queries. This will timeout for large inputs.
Space Complexity: O(1) (Excluding the output array)
⚡ Optimized Approach (O(N + M))
Approach: Use a Hash Map (Dictionary) to create a frequency count of all strings in stringList.
- Build Map (O(N)): Iterate through the
stringListonce. Store each unique string as a key and its count as the value in the hash map. - Query Lookup (O(M)): Iterate through the
queriesarray. For each query, check the hash map for its count inO(1)average time. If the string exists, append its count to the result array; otherwise, append0.
Time Complexity: O(N + M) (Time to build the map plus time to process all queries)
Space Complexity: O(U), where U is the number of unique strings in stringList.
Solution code
from collections import Counter
from typing import List
# --- Optimized Approach ---
# Time Complexity: O(N + M)
# Space Complexity: O(U)
def matchingStringsOptimized(stringList: List[str], queries: List[str]) -> List[int]:
"""
Uses the Hash Map (Frequency Counter) pattern for efficient lookups.
"""
# 1. Build Frequency Map using Counter (O(N))
freqMap = Counter(stringList)
# 2. Process Queries (O(M))
results = []
for query in queries:
# Dictionary lookup is O(1) average time.
# .get(key, 0) handles cases where the query string isn't present.
results.append(freqMap.get(query, 0))
return results
# --- Brute Force Approach ---
# Time Complexity: O(N * M)
# Space Complexity: O(1)
def matchingStringsBruteForce(stringList: List[str], queries: List[str]) -> List[int]:
"""
Uses nested loops to compare every query against every input string.
"""
results = []
# Iterate through every query (O(M))
for query in queries:
count = 0
# For every query, iterate through every string in the list (O(N))
for s in stringList:
if query == s:
count += 1
results.append(count)
return resultsOther ways to solve it
- Thought of another approach (slower, or cleverer)? Code it here: the same tests check any approach.
Revising this one?
- →Solve it from memory before peeking
- →Say the pattern out loud, not just the code
- →Explain it like you would to a friend
- →Try it again in a different language