Counting

Counting is a common pattern in time-saving algorithms. It can often get you runtime, but at the expense of adding space.

The idea is to define a dictionary or array (call it e.g. counts) where the keys/indices represent the items from the input set and the values represent the number of times the item appears. In one pass through the input you can fully populate counts:

var counts = new Dictionary<int, int>(); foreach (var item in array) { int count = 1; if (counts.TryGetValue(item, out count)) { count++; } counts[item] = count; }

Once you know how many times each item appears, it's trivial to:

  • generate a sorted array
  • find the item that appears the most times
  • etc.

Last updated: June 7, 2026

What's next?

If you're ready to start applying these concepts to some problems, check out our mock coding interview questions.

They mimic a real interview by offering hints when you're stuck or you're missing an optimization.

Try some questions now

. . .