Skip to content

Coding Interview Patters: Frequency Counter

Posted on:February 5, 2026 at 03:17 PM

Table of Contents

Open Table of Contents

Introduction

The frequency counter is a technique used in coding interviews to solve problems that involve counting the frequency of elements in a data structure, such as an array or a string.

This technique is often used to optimize solutions that would otherwise require nested loops, resulting in a more efficient algorithm.

Frequency Counter Implementation

type Frequency = Map<string, number>

const countFrequency = (s: string): Frequency => {
  const frequency: Frequency = new Map()

  for (let c of s) {
    frequency.set(c, (frequency.get(c) ?? 0) + 1)
  }

  return frequency
}

Example Problem: Anagram Check

An anagram is a word or phrase formed by rearranging the letters of a different word or phrase. For example, “listen” and “silent” are anagrams.

Here’s how you can use the frequency counter technique to check if two strings are anagrams:

const isAnagram = (s: string, t: string): boolean => {
  if (s.length !== t.length) return false

  const frequency1 = countFrequency(s)
  const frequency2 = countFrequency(t)

  for (let [char, count] of frequency1) {
    if (frequency2.get(char) !== count) {
      return false
    }
  }

  return true
}

Conclusion

The frequency counter technique is a powerful tool for solving problems that involve counting elements in data structures. By using this technique, you can optimize your solutions and improve the efficiency of your algorithms.

Next Steps

Ready to practice? Try solving these problems using the two pointers technique:

Happy learning!