Practice
JavaScriptData StructuresReactConcepts
Sign in
← Back to problems

Frequency Counter

Hash Mapseasy

Course · Section 9: Data Structures, Modern Operators and Strings · Lecture 124: Maps: Fundamentals

Implement `frequency(arr)` that returns an object mapping each unique element of `arr` to the number of times it appears. Example: `frequency(['a','b','a','c','b','a'])` → `{ a: 3, b: 2, c: 1 }`.

Sample tests

Input: frequency(["a","b","a","c","b","a"])
Output: {"a":3,"b":2,"c":1}
Input: frequency([])
Output: {}

+ 1 hidden test run on Submit.

Hints

Common pitfalls
  • Counting with nested loops is O(n^2); a map makes it linear.

Learning resources

  • MDN: Map
Approach & explanation (try first)

A hash map tallies each value in one pass. O(n) time and space.

Loading...
⌘/Ctrl + Enter

Run your code to see results.