Frequency Calculator
Given an array of items, count how many times each one appears and return the frequency map along with the most repeated and least repeated item. When several items share the highest (or lowest) count, return the one seen first. This is the classic "count with a hash map" pattern that underpins anagram checks, mode-finding, and many other interview questions.
Examples
Input: ['react', 'js', 'html', 'react', 'js', 'next', 'html', 'react']
Output: mostRepeated: 'react' (3), leastRepeated: 'next' (1)
// Counts → react:3, js:2, html:2, next:1. Highest is react; lowest is next.
Input: ['a']
Output: mostRepeated: 'a', leastRepeated: 'a'
// With one distinct item it is both the most and least repeated.
Input: [] (empty)
Output: mostRepeated: null, leastRepeated: null
Constraints
- Items can be strings or numbers.
- On a tie for most/least, return the item that appears first in the input.
- An empty array returns null for both most and least repeated.
hash-mapfrequencyarrayreduceobject
Important
Interview Tip
Reach for a Map (or plain object) to count in a single O(n) pass — interviewers want to see you avoid the O(n²) nested-loop count. Prefer a Map over a plain object when keys could be numbers or collide with prototype names (e.g. "constructor"). Clarify the tie-breaking rule before coding — it changes the expected output.
Approach: Brute Force
For each item, scan the entire array to count its occurrences, then walk the array again to track the running most/least. Correct but wasteful — it re-counts items it has already processed.
Complexity
Time: O(n²)Space: O(k)
Pros
- No extra concepts — just loops
- Easy to reason about
Cons
- O(n²) — re-scans the array per element
- Repeats work for duplicate items