Course contentsShow
← Computer Science
Lesson 259 of 2,8726. Arrays and Basic CollectionsFree lesson

Array Frequency Counting and Analysis

Count element occurrences using auxiliary arrays or in-place techniques for limited value ranges.

Array Frequency Counting and Analysis

You'll learn how to count how often each value appears in an array using simple tracking techniques.

When working with arrays, you often need to know how many times each element occurs. Think of it like tallying votes in an election — you need to count each candidate's name as it appears on ballots. In programming, we call this frequency counting.

The Core Idea

The basic approach uses a second array (an auxiliary array) where each index represents a possible value, and the value stored at that index is the count. For example, if you're counting numbers from 0 to 9, you'd create a frequency array of size 10, initialized to all zeros. Then, as you scan through your original array, each time you see a number (say, 5), you increment frequency[5].

When This Works Best

This technique shines when:

  • Your values fall within a small, known range (like 0–100)
  • You want a fast, single-pass solution

For example, counting grades (0–100), dice rolls (1–6), or character occurrences in text works beautifully.

A Simple Example (Concept)

Imagine you have scores: [85, 90, 85, 75, 90, 85]

  1. Create a frequency array covering 0–100 (all zeros)
  2. Scan each score: when you see 85, increment frequency[85]
  3. After one pass: frequency[85] = 3, frequency[90] = 2, frequency[75] = 1

Now you can instantly answer: "How many students scored 85?" — just look at frequency[85].

Limitations

If values are huge or sparse (like counting occurrences of employee IDs ranging into millions), this approach wastes memory. But for limited ranges, it's elegant and efficient.

Key Takeaway: Frequency counting uses an auxiliary array where indices represent values and stored numbers represent counts — perfect for analyzing element occurrences when values fall within a manageable range.