Map

CSCI 1913 – Introduction to Algorithms, Data Structures, and Program Development
Adriana Picoral

Map

  • map, dictionary, associative array, or hash table
  • data structure that stores key-value pairs
  • allows for efficient look up of a value by its associated key

A map lets you use any type as the “index” - strings, objects, whatever you want. We call these keys instead of indices, and what you store are values.

Why Maps Matter

Maps solve a really common problem: associating related data.

Phone books, student records, caching web pages, counting word frequencies - these all need to link one piece of data to another.

Limitations

  • Map keys must be immutable
  • Keys should be evenly distributed to minimize collisions

Implementation

  • Array – map integer keys directly as an array index, \(O(1)\)
  • Two arrays of same size (sorted/unsorted) – one holds the keys, another the values
  • Binary Search Trees – \(O(\log n)\) – iterate through keys in order

Hash Tables are the most popular implementation of Map

Implementation

  • Arrays are good at read/write given an index
  • Arrays are bad are “rearranging” (add/remove)
  • Array search is slow when not sorted
  • BST are good enough for all operations \(O(\log n)\)

Runtime

add get remove search
simple array \(O(n)\) \(O(1)\) \(O(n)\) \(O(n)\)
unsorted array \(O(n)\) \(O(n)\) \(O(n)\) \(O(n)\)
sorted array \(O(n)\) \(O(\log n)\) \(O(n)\) \(O(\log n)\)
binary search tree \(O(\log n)\) \(O(\log n)\) \(O(\log n)\) \(O(\log n)\)
hash tables \(O(1)\) \(O(1)\) \(O(1)\) \(O(1)\)