Skip to the solution
MediumDSAAsked in 20245 min read

Count Occurrences of Each Element in an Array (Frequency Counter)

2.0k views

The problem

Problem, as an interviewer would state it: "Count how many times each distinct element appears in an array. Discuss edge cases, runtime, and alternative approaches."

Examples:

Code
count(["a", "b", "a", "c", "a", "b"]); // a: 3, b: 2, c: 1

Clarifying questions expected:

  • Should 1 and "1" be counted separately? What about NaN?
  • Are the elements guaranteed to be safe strings, or could one be the word constructor?
  • Do you also want the results sorted by frequency, or just the counts?

Code / implementation expected: Yes — real, direct proof of the correct counter and of exactly how the naive object counter goes wrong.

  • js-coding
  • utility
  • algorithm

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

5 min read · 9 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

JavaScriptReal, direct proof: a Map-based frequency counter is correct, while a plain-object counter corrupts the word constructor and merges 1 with the string 1

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 71 of 154 in JavaScript coding

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextMedium

Custom Object.assign polyfill

Continue