Dictionary [ dik-shuh-ner-ee ]
Intro
Dictionaries are a powerful Data Structure in any language. In some languages they can be referred to as an object; in Java they are referred to as HashMaps but they are pretty much the same thing. We will interchange the names in this article. A HashMap is a list of key:value pairs. HashMaps are changeable and do not allow duplicate keys. They are printed (or depending on the language, written) with flower brackets {}
, and the keys and values are separated by an equal sign =
or colon :
.
Properties
HashMap keys and values can be any non-null object such as String
, int
, and List
data types.
In this example, we’ll use String
keys and values:
Many languages have built-in methods for dictionaries that can greatly expand their functionality and make it easier to do things like empty the dictionary or get a list of keys or values. Here are some methods for HashMaps:
put(K key, V value): Used to populate the HashMap
get(K key): Used to get the value of the given key, or null if the key doesn't exist
isEmpty(): Returns true if HashMap is empty
size(): Returns the number of key-value mappings in the HashMap
How to use a Dictionary?
Let's say we have a problem where we need to find a pair in an array that matches a given sum.
Input:
nums = [8, 7, 2, 5, 3, 1]
target = 10
Output: Pair found (8, 2)
Input:
nums = [5, 2, 6, 8, 1, 9]
target = 12
Output: No pair found
We can solve this using brute force which would most likely involve nested for loops, but we have a more elegant way to solve this using a HashMap.
In this solution, we have one for loop that goes through the array and looks through a HashMap to see if we have a key stored that when added to the current value would equal the target.
We can represent this logic with an equation: x + y = target
. To find x
the equation turns into x = target - y
. As we loop through the array we will check if x
(key stored in HashMap) equals target - y
(current value). If there is no x
in HashMap then we will add y
to HashMap and see if any of the following values will complete the equation.
This method will return the first pair found that equals the target.