Hiprup

How do you count character occurrences in a string?

Tally how many times each character appears in a string.

  1. Create an empty object or Map.

  2. Loop over the characters.

  3. Increment the count for each character (starting from 0).

Reusable technique: this frequency map also solves anagrams, duplicate-finding, and "first unique character".

// Method 1: For loop + object
function charCount(str) {
  const freq = {};
  for (const char of str) {
    freq[char] = (freq[char] || 0) + 1;
  }
  return freq;
}
console.log(charCount('hello')); // { h: 1, e: 1, l: 2, o: 1 }

// Method 2: Reduce
const charFreq = str => [...str].reduce((acc, char) => {
  acc[char] = (acc[char] || 0) + 1;
  return acc;
}, {});

// Method 3: Find specific character count
function countChar(str, char) {
  return [...str].filter(c => c === char).length;
}
console.log(countChar('hello', 'l')); // 2

// Method 4: Using split
function countCharSplit(str, char) {
  return str.split(char).length - 1;
}
console.log(countCharSplit('hello', 'l')); // 2

// Find first non-repeating character
function firstUnique(str) {
  const freq = charCount(str);
  return [...str].find(c => freq[c] === 1) || null;
}
console.log(firstUnique('aabbc')); // 'c'

charCount builds a frequency map in O(n). reduce does the same functionally. countChar filters for a specific character. split trick: 'hello'.split('l') = ['he', '', 'o'] — length-1 = number of 'l's. firstUnique combines frequency map with find for the first character appearing only once.

The frequency map (for...of + object) is the standard approach. The first non-repeating character follow-up is very commonly asked.

The split trick for counting a specific character is a clever one-liner. All are O(n) time.

How do you count character occurrences in a string? | Hiprup