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 hash map 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:

Map<Integer, Integer> counts = new HashMap<>(); for (int item : array) { Integer count = counts.get(item); int incrementedCount = (count == null) ? 1 : count + 1; counts.put(item, incrementedCount); }

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.

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

. . .