Algorithms
2 Jan 2025

The Battle of 3 Kings - Binary Search vs Hashmap vs Linear Search

When dealing with a dataset, sometimes the most important thing is to find the data as quickly as possible. Sometimes this means sacrificing memory and sometimes performance.In this article we will make a brief comparison of 3 data search algorithms for 1M (1.000.000) entries.

1 - Use a Hashmap (Best for Fast Exact Matches)

When to Choose

  • You need exact match searches (e.g., "Does this exact string exist?").
  • Searches are frequent (e.g., user types a query in real-time).
  • You can afford extra memory (~40-100 MB for 1M entries).

Pros

  • Lookup Time: O(1) (instant after hashmap creation).
  • Setup Time: O(n) (one-time cost).
  • Dynamic Data: Supports quick additions/removals (unlike sorted arrays).

Cons

  • Memory overhead (duplicates keys).
  • Only works for exact matches, not substrings or ranges.

Example

// Preprocess once
const hashMap = new Map();
 
// Use a unique key like "id"
data.forEach(item => hashMap.set(item.id, item));
 
// Real-time search
const result = hashMap.get(userInput);

Conclusion

  • For Exact Matches: Hashmap is the clear winner (speed trumps memory for large data).
  • For Range Queries or Memory Constraints: Sort the data and use binary search.
  • Never Use Linear Search for 1M entries unless you have no other choice.
Algorithms and data structures: complexity, classic problems, and step-by-step examples.