Magical Lookups

One of my favorite go-to optimization techniques is to ask myself, “If I could magically find a desired piece of information in O(1) time, can I make my algorithm faster?” If the answer to this is yes, I then use a data structure (often a hash table) to make that magic happen. I call this technique “magical lookups.”

Let me clarify this technique with an example.

Magically Looking Up Authors

Let’s say we’re writing library software and we have data about books and their authors contained in two separate arrays.

Specifically, the array of authors looks like this:

 const​ authors = [
  { authorId: 1, name: ​'Virginia Woolf'​ },
  { authorId: 2, name: ​'Leo Tolstoy'​ },
  { authorId: 3, name: ​'Dr. Seuss'​ },
  { authorId: 4, name: ...

Get A Common-Sense Guide to Data Structures and Algorithms in JavaScript, Volume 1 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.