← All coursesDSA Foundations

Lesson 6 of 19

Character frequency

A scanner reads tickets marked A, B or C. Give each letter a counter. As a ticket passes, which counter should go up?

One ticket adds one to its letter’s count

After each ticket, a letter’s counter equals its frequency among the tickets already scanned. Start every counter at zero so even a missing letter has an answer. For n tickets from the fixed alphabet A, B, C, one direct counter update per ticket gives O(n) time with O(1) extra space.

Work through an example

A gate records ACABA. How many tickets of each letter passed through?

Step-by-step solution
  1. Start A, B and C at zero. The first two tickets, A and C, bring those two counters to one each.
  2. The next A brings its count to two. B then gets its first ticket.
  3. The last A brings the totals to A = 3, B = 1 and C = 1. Their sum is five, one count for every ticket.
JavaScript example
const counts = { A: 0, B: 0, C: 0 };
for (const ticket of "ACABA") {
  counts[ticket]++;
}
counts;
DSA compiler

Try it yourself

Finish the animation to unlock this question.

After scanning A, B, A, the counters read A = 2, B = 1 and C = 0. Another B arrives. What changes?

Related exercise · Counting a Character · See this stage of the beginner path