SystemTutor
About
Sign in
Loading course documentation…
SystemTutor

COURSES

  • Data Structures & Algorithms
  • CSS MasterclassNew course
  • System DesignNew course

PRACTICE

  • Algorithm practice
  • CSS practice

LEGAL

  • Privacy Policy
  • Terms of Service
  • About

© 2026 SystemTutor. All rights reserved.

Built with 🫶 by Shatlyk

Course Overview
Algorithm Patterns OverviewFrequency CountersTwo SumValid AnagramGroup AnagramsFrequency Counters and Hash-Map LookupTwo PointersValid PalindromeTwo Sum IIContainer With Most WaterTwo-Pointer ReasoningSliding WindowMaximum Average Subarray ILongest Substring Without Repeating CharactersMinimum Size Subarray SumSliding-Window Reasoning
Algorithm Patterns

Frequency Counters

Learn how frequency counters turn arrays and strings into value-frequency profiles for comparing squared values, anagrams, matching contents, and repeated frequencies, while avoiding nested-loop solutions.

A frequency counter is a hash map (or record) that stores each value together with the number of times it appears. It turns an array or string into a compact value-frequency profile that is easy to compare.

For example, the array [a, b, a, c, b, a] produces:

A frequency map counts a three times, b twice, and c once in the input a, b, a, c, b, a.

Once inputs are represented this way, compare the profiles instead of repeatedly searching through the original data.

Why use a hash map?

Searching an array for a value inside another loop often creates a quadratic O(n²) solution. A hash map gives average O(1) lookup and update, so a single pass can build the information needed for the comparison.

Core idea

Count first, then compare counts. This turns problems about squared values, anagrams, matching contents, and repeated frequencies into profile comparisons.

Basic workflow

  1. Create a profile for the first array or string.
  2. Create a profile for the second input, or update it while scanning.
  3. Compare the values and their frequencies.

Follow the scan through [a, b, a, c, b, a]. Each step highlights the current letter and the map entry it updates.

Enter a JSON array of up to 64 double-quoted strings. Each string is one item. Use [] for an empty array.

Step 1 of 6Distinct keys 1
  1. Index 0a, highlighted↑i
  2. Index 1b
  3. Index 2a
  4. Index 3c
  5. Index 4b
  6. Index 5a
Count of “a”, updated
1

Step 1 of 6. This is the first “a”. Create its map entry with a count of 1.

The update operation is usually written as “the old count, or zero, plus one”:

function count(items) {
  const profile = new Map();

  for (const item of items) {
    profile.set(item, (profile.get(item) ?? 0) + 1);
  }

  return profile;
}

For ["tea", "coffee", "tea"], the profile is { tea: 2, coffee: 1 }. The keys describe which values are present; the counts describe how often they occur.

Comparing frequency profiles

Two inputs have matching contents when every value appears the same number of times in both profiles. Order does not matter, but missing keys and different counts do.

function sameContents(first, second) {
  if (first.length !== second.length) return false;

  const firstProfile = count(first);
  const secondProfile = count(second);

  for (const [value, frequency] of firstProfile) {
    if (secondProfile.get(value) !== frequency) return false;
  }

  return true;
}

The length check is an early exit: if the inputs contain different numbers of items, their frequency profiles cannot match.

Common use cases

Squared values

To check whether one array contains the squared values of another:

  1. Check that the arrays have equal lengths.
  2. Square each number in the first array before updating its count.
  3. Count the original values in the second array, then compare the two profiles.

For example, [-2, 2, 3] produces the squared profile 4 → 2, 9 → 1, which matches [4, 4, 9]. The values -2 and 2 must contribute to the same key. Comparing their original counts separately would miss this.

Anagrams

For strings, count each character. Two strings are anagrams when their character profiles match.

function areAnagrams(first, second) {
  if (first.length !== second.length) return false;

  const profile = new Map();

  for (const char of first) {
    profile.set(char, (profile.get(char) ?? 0) + 1);
  }

  for (const char of second) {
    const remaining = profile.get(char);
    if (!remaining) return false;

    if (remaining === 1) profile.delete(char);
    else profile.set(char, remaining - 1);
  }

  return profile.size === 0;
}

The second pass consumes counts from the first string. This avoids creating a second profile and can stop immediately when an unexpected character appears.

Repeated frequencies

When a problem asks whether frequencies repeat or match, first build the value-frequency profile. Then compare the frequency information required by the problem instead of comparing every pair of elements.

For example, [a, a, b, b, c, c] has frequencies [2, 2, 2]. It has one repeated frequency, 2, appearing three times. A second map can count those frequencies if the problem asks whether two values occur equally often.

When the map should store an index

A count answers “how many?” For Two Sum you need to return positions, so store an earlier index for each value. With [3, 3] and target 6, the first 3 needs another 3. Check the empty map, then save its index 0. At index 1, the lookup finds index 0. Looking up the complement before storing the current index keeps the two positions distinct.

Frequency counters vs. nested loops

ApproachMain methodTime pattern
Frequency counterBuild profiles, then compare countsLinear-time approach, usually O(n)
Nested loopsRepeatedly search and compare elementsQuadratic-time approach, often O(n²)

Frequency counters keep the work to passes over the input. Nested-loop solutions repeat searches as the input grows, making them less efficient for these comparison tasks.

Complexity and trade-offs

  • Time: Building the profiles takes O(n) average time for n total input items. Comparing the profiles takes O(k), where k is the number of distinct values.
  • Space: A profile uses O(k) additional space. In the worst case, every input item is distinct, so k = n.
  • Lookup assumption: Hash-map operations are average O(1). A language or runtime may have different worst-case guarantees, but the pattern is designed around constant-time average lookup.

When to reach for this pattern

Use a frequency counter when the problem asks whether two collections contain the same values, the same number of values, or a transformed version of those values. If order matters, a direct sequence comparison may be enough; if you need contiguous ranges, consider a sliding window instead.


Key Takeaways

  • Count First, Compare Later: Store element counts in a hash map to avoid slow O(n²) nested loops and compare profiles in fast O(n) time.
  • Two-Pass Workflow: Check lengths first, count items from the first input, then compare or decrease counts while scanning the second input.
  • Common Uses: Great for anagrams, matching squared values, checking duplicate counts, and finding repeated frequencies.
  • Memory vs. Speed: Uses O(k) extra space (where k is the count of unique values) to achieve fast O(n) average runtime.
  • When to Choose: Use a Frequency Counter when order does not matter and you only care about item counts. If order or contiguous items matter, use Two Pointers or Sliding Window.

How is this lesson?

Previous lessonAlgorithm Patterns OverviewNext lessonTwo Sum
Edit on GitHubReport on GitHub
On this page
%

On this page

Why use a hash map?Basic workflowComparing frequency profilesCommon use casesSquared valuesAnagramsRepeated frequenciesWhen the map should store an indexFrequency counters vs. nested loopsComplexity and trade-offsKey Takeaways