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:
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.
Interview coming up?
Get the free 7-day email crash course. You'll learn how to think algorithmically, so you can break down tricky coding interview questions.
No prior computer science training necessary—we'll get you up to speed quickly, skipping all the overly academic stuff.
No spam. One-click unsubscribe whenever.
You're in! Head over to your email inbox right now to read day one!