These are the solutions to the exercises found in the section, Exercises . The solutions provided here are in Ruby, but you can find the solutions in JavaScript and Python in the code download. [19]
-
We can optimize this algorithm if we ask ourselves, “If I could magically find a desired piece of information in O(1) time, can I make my algorithm faster?”
Specifically, as we iterate over one array, we’d want to “magically” look up that athlete from the other array in O(1) time. To accomplish this, we can first transform one of the arrays into a hash table. We’ll use the full name (that is, the first and last name) as the key, and true (or any arbitrary item) as the value.
Once we’ve turned one array into this hash table, we then iterate over the other array. As we encounter each athlete, we do an O(1) lookup in the hash table to see if that athlete already plays the other sport. If they do, we add that athlete to our multisport_athletes array, which we return at the end of the function.
Here is the code for this approach:
<table><tbody><tr><td> <span> </span></td><td> <strong>def</strong> <strong>find_multisport_athletes</strong> (array_1, array_2)</td></tr><tr><td> <span> </span></td><td>hash_table = {}</td></tr><tr><td> <span> </span></td><td>multisport_athletes = []</td></tr><tr><td> <span> </span></td><td></td></tr><tr><td> <span> </span></td><td>array_1. <strong>each</strong> <strong>do</strong> |athlete|</td></tr><tr><td> <span> </span></td><td>hash_table[athlete[ <em>:first_name</em> ] + <em>" "</em> + athlete[ <em>:last_name</em> ]] = <strong>true</strong> </td></tr><tr><td> <span> </span></td><td> <strong>end</strong> </td></tr></tbody></table>
<table><tbody><tr><td> <span> </span></td><td>array_2. <strong>each</strong> <strong>do</strong> |athlete|</td></tr><tr><td> <span> </span></td><td> <strong>if</strong> hash_table[athlete[ <em>:first_name</em> ] + <em>" "</em> + athlete[ <em>:last_name</em> ]]</td></tr><tr><td> <span> </span></td><td>multisport_athletes << athlete[ <em>:first_name</em> ] +</td></tr><tr><td> <span> </span></td><td> <em>" "</em> + athlete[ <em>:last_name</em> ]</td></tr><tr><td> <span> </span></td><td> <strong>end</strong> </td></tr><tr><td> <span> </span></td><td> <strong>end</strong> </td></tr><tr><td> <span> </span></td><td></td></tr><tr><td> <span> </span></td><td> <strong>return</strong> multisport_athletes</td></tr><tr><td> <span> </span></td><td> <strong>end</strong> </td></tr></tbody></table>
This algorithm is O(N + M) since we iterate through each set of players just once.
-
For this algorithm, generating examples to find a pattern will be immensely helpful.
Let’s take an array that has six integers and see what would happen if we removed a different integer each time:
<table><tbody><tr><td> <span> </span></td><td>[1, 2, 3, 4, 5, 6] : missing 0: sum = 21</td></tr><tr><td> <span> </span></td><td>[0, 2, 3, 4, 5, 6] : missing 1: sum = 20</td></tr><tr><td> <span> </span></td><td>[0, 1, 3, 4, 5, 6] : missing 2: sum = 19</td></tr><tr><td> <span> </span></td><td>[0, 1, 2, 4, 5, 6] : missing 3: sum = 18</td></tr><tr><td> <span> </span></td><td>[0, 1, 2, 3, 5, 6] : missing 4: sum = 17</td></tr><tr><td> <span> </span></td><td>[0, 1, 2, 3, 4, 6] : missing 5: sum = 16</td></tr></tbody></table>
Hmm. When we remove the 0, the sum is 21. When we remove the 1, the sum is 20. And when we remove the 2, the sum is 19, and so on. This definitely seems like a pattern!
Before we go further, let’s call the 21 in this case the “full sum.” This is the sum of the array when it’s just missing the 0.
If we analyze these cases carefully, we’ll see that the sum of any array is less than the “full sum” by the amount of the missing number. For example, when we’re missing the 4, the sum is 17, which is four less than 21. And when we’re missing the 1, the sum is 20, which is one less than 21.
So, we can begin our algorithm by calculating what the full sum is. We can then subtract the actual sum from the full sum, and that will be our missing number.
Here is the code for this:
<table><tbody><tr><td> <span> </span></td><td> <strong>def</strong> <strong>find_missing_number</strong> (array)</td></tr><tr><td> <span> </span></td><td> <em># Calculate the full sum (which is the sum if only the 0 were missing):</em> </td></tr><tr><td> <span> </span></td><td>full_sum = 0</td></tr><tr><td> <span> </span></td><td>(1..array. <strong>length</strong> ). <strong>each</strong> <strong>do</strong> |n|</td></tr><tr><td> <span> </span></td><td>full_sum += n</td></tr><tr><td> <span> </span></td><td> <strong>end</strong> </td></tr><tr><td> <span> </span></td><td></td></tr><tr><td> <span> </span></td><td> <em># Calculate the CURRENT sum:</em> </td></tr><tr><td> <span> </span></td><td>current_sum = 0</td></tr><tr><td> <span> </span></td><td></td></tr><tr><td> <span> </span></td><td>array. <strong>each</strong> <strong>do</strong> |n|</td></tr><tr><td> <span> </span></td><td>current_sum += n</td></tr><tr><td> <span> </span></td><td> <strong>end</strong> </td></tr><tr><td> <span> </span></td><td> <em># The difference between the two sums will be the missing number:</em> </td></tr><tr><td> <span> </span></td><td> <strong>return</strong> full_sum - current_sum</td></tr><tr><td> <span> </span></td><td> <strong>end</strong> </td></tr></tbody></table>
This algorithm is O(N). It takes N steps to calculate the full sum, and then another N steps to calculate the actual sum. This is 2N steps, which reduces to O(N).
-
We can make this function much faster if we use a greedy algorithm. (Perhaps this shouldn’t be a surprise given that our code is trying to make the greatest possible profit on stocks.)
To make the most profit, we want to buy as low as possible and sell as high as possible. Our greedy algorithm begins by assigning the very first price to be the buy_price . We then iterate over all the prices, and as soon as we find a lower price, we make it the new buy_price .
Similarly, as we iterate over the prices, we check how much profit we’d make if we sold at that price. This is calculated by subtracting the buy_price from the current price. In good greedy fashion, we save this profit in a variable called greatest_profit . As we iterate through all the prices, whenever we find a greater profit, we turn that into the greatest_profit .
By the time we’re done looping through the prices, the greatest_profit will hold the greatest possible profit we can make by buying and selling the stock one time.
Here’s the code for our algorithm:
<table><tbody><tr><td> <span> </span></td><td> <strong>def</strong> <strong>find_greatest_profit</strong> (array)</td></tr><tr><td> <span> </span></td><td>buy_price = array[0]</td></tr><tr><td> <span> </span></td><td>greatest_profit = 0</td></tr><tr><td> <span> </span></td><td></td></tr><tr><td> <span> </span></td><td>array. <strong>each</strong> <strong>do</strong> |price|</td></tr><tr><td> <span> </span></td><td>potential_profit = price - buy_price</td></tr><tr><td> <span> </span></td><td></td></tr><tr><td> <span> </span></td><td> <strong>if</strong> price < buy_price</td></tr><tr><td> <span> </span></td><td>buy_price = price</td></tr><tr><td> <span> </span></td><td> <strong>elsif</strong> potential_profit > greatest_profit</td></tr><tr><td> <span> </span></td><td>greatest_profit = potential_profit</td></tr><tr><td> <span> </span></td><td> <strong>end</strong> </td></tr><tr><td> <span> </span></td><td> <strong>end</strong> </td></tr><tr><td> <span> </span></td><td></td></tr><tr><td> <span> </span></td><td> <strong>return</strong> greatest_profit</td></tr><tr><td> <span> </span></td><td> <strong>end</strong> </td></tr></tbody></table>
Because we iterate over the N prices just once, our function takes O(N) time. Not just did we make a lot of money, but we made it fast.
-
This is another algorithm where generating examples to find a pattern will be the key to optimizing it.
As stated in the exercise, it’s possible for the greatest product to be a result of negative numbers. Let’s look at various examples of arrays and their greatest products formed by two numbers:
<table><tbody><tr><td> <span> </span></td><td>[-5, -4, -3, 0, 3, 4] -> Greatest product: 20 (-5 -4)</td></tr><tr><td> <span> </span></td><td>[-9, -2, -1, 2, 3, 7] -> Greatest product: 21 (3 7)</td></tr><tr><td> <span> </span></td><td>[-7, -4, -3, 0, 4, 6] -> Greatest product: 28 (-7 -4)</td></tr><tr><td> <span> </span></td><td>[-6, -5, -1, 2, 3, 9] -> Greatest product: 30 (-6 -5)</td></tr><tr><td> <span> </span></td><td>[-9, -4, -3, 0, 6, 7] -> Greatest product: 42 (6 * 7)</td></tr></tbody></table>
Seeing all these cases may help us realize that the greatest product can only be formed by either the greatest two numbers or the lowest two (negative) numbers.
With this in mind, we should design our algorithm to keep track of these four numbers:
- The greatest number
- The second-to-greatest number
- The lowest number
- The second-to-lowest number
We can then compare the product of the two greatest numbers versus the product of the two lowest numbers. And whichever product is greater is the greatest product in the array.
Now, how do we find the greatest two numbers and the lowest two numbers? If we sorted the array, that would be easy. But that’s still O(N log N), and the instructions say that we can achieve O(N).
In fact, we can find all four numbers in a single pass through the array. It’s time to get greedy again.
Here is the code, followed by its explanation:
<table><tbody><tr><td> <span> </span></td><td> <strong>def</strong> <strong>greatest_product</strong> (array)</td></tr><tr><td> <span> </span></td><td>greatest_number = -Float::INFINITY</td></tr><tr><td> <span> </span></td><td>second_to_greatest_number = -Float::INFINITY</td></tr><tr><td> <span> </span></td><td></td></tr><tr><td> <span> </span></td><td>lowest_number = Float::INFINITY</td></tr><tr><td> <span> </span></td><td>second_to_lowest_number = Float::INFINITY</td></tr></tbody></table>
<table><tbody><tr><td> <span> </span></td><td>array. <strong>each</strong> <strong>do</strong> |number|</td></tr><tr><td> <span> </span></td><td> <strong>if</strong> number >= greatest_number</td></tr><tr><td> <span> </span></td><td>second_to_greatest_number = greatest_number</td></tr><tr><td> <span> </span></td><td>greatest_number = number</td></tr><tr><td> <span> </span></td><td> <strong>elsif</strong> number > second_to_greatest_number</td></tr><tr><td> <span> </span></td><td>second_to_greatest_number = number</td></tr><tr><td> <span> </span></td><td> <strong>end</strong> </td></tr><tr><td> <span> </span></td><td></td></tr><tr><td> <span> </span></td><td> <strong>if</strong> number <= lowest_number</td></tr><tr><td> <span> </span></td><td>second_to_lowest_number = lowest_number</td></tr><tr><td> <span> </span></td><td>lowest_number = number</td></tr><tr><td> <span> </span></td><td> <strong>elsif</strong> number > lowest_number &&</td></tr><tr><td> <span> </span></td><td>number < second_to_lowest_number</td></tr><tr><td> <span> </span></td><td>second_to_lowest_number = number</td></tr><tr><td> <span> </span></td><td> <strong>end</strong> </td></tr><tr><td> <span> </span></td><td> <strong>end</strong> </td></tr><tr><td> <span> </span></td><td></td></tr><tr><td> <span> </span></td><td>greatest_product_from_two_highest =</td></tr><tr><td> <span> </span></td><td>greatest_number second_to_greatest_number</td></tr><tr><td> <span> </span></td><td></td></tr><tr><td> <span> </span></td><td>greatest_product_from_two_lowest =</td></tr><tr><td> <span> </span></td><td>lowest_number second_to_lowest_number</td></tr><tr><td> <span> </span></td><td></td></tr><tr><td> <span> </span></td><td> <strong>if</strong> greatest_product_from_two_highest > greatest_product_from_two_lowest</td></tr><tr><td> <span> </span></td><td> <strong>return</strong> greatest_product_from_two_highest</td></tr><tr><td> <span> </span></td><td> <strong>else</strong> </td></tr><tr><td> <span> </span></td><td> <strong>return</strong> greatest_product_from_two_lowest</td></tr><tr><td> <span> </span></td><td> <strong>end</strong> </td></tr><tr><td> <span> </span></td><td> <strong>end</strong> </td></tr></tbody></table>
Before we begin our loop, we set the greatest_number and second_to_greatest_number to be negative infinity. This ensures they start out lower than any number currently in the array.
We then iterate over each number. If the current number is greater than the greatest_number , we greedily turn the current number into the new greatest_number . If we’ve already found a second_to_greatest_number , we reassign the second_to_greatest_number to be whatever the greatest_number was before we reached the current number. This ensures the second_to_greatest_number will indeed be the second-to-greatest number.
If the current number we’re iterating over is less than the greatest_number but greater than then second_to_greatest_number , we update the second_to_greatest_number to be the current number.
We follow this very same process to find the lowest_number and the second_to_lowest_number .
Once we’ve found all four numbers, we compute the products from the two highest numbers and the products of the two lowest numbers and return whichever product is greater.
-
The key to optimizing this algorithm is the fact that we’re sorting a finite number of values. Specifically, there are only 21 types of temperature readings that we may find in this array, from:
<table><tbody><tr><td> <span> </span></td><td>97.0, 97.1, 97.2, 97.3 ... 98.7, 98.8, 98.9, 99.0</td></tr></tbody></table>
Let’s return to the example array mentioned in the exercise instructions:
<table><tbody><tr><td> <span> </span></td><td>[98.6, 98.0, 97.1, 99.0, 98.9, 97.8, 98.5, 98.2, 98.0, 97.1]</td></tr></tbody></table>
If were to imagine our array of temperatures as a hash table, we can store each temperature as a key and the number of occurrences as the value. This would look like something like this:
<table><tbody><tr><td> <span> </span></td><td>{98.6 => 1, 98.0 => 2, 97.1 => 2, 99.0 => 1,</td></tr><tr><td> <span> </span></td><td>98.9 => 1, 97.8 => 1, 98.5 => 1, 98.2 => 1}</td></tr></tbody></table>
With this in mind, we can run a loop that runs from 97.0 up to 99.0 and checks the hash table for how many occurrences of that temperature there are. Each of these lookups take just O(1) time.
Then, we use that number of occurrences to populate a new array. Because our loop is set to go up from 97.0 to 99.0, our array will end up in perfect ascending order.
Here’s the code for this:
<table><tbody><tr><td> <span> </span></td><td> <strong>def</strong> <strong>sort_temperatures</strong> (array)</td></tr><tr><td> <span> </span></td><td>hash_table = {}</td></tr><tr><td> <span> </span></td><td></td></tr><tr><td> <span> </span></td><td> <em># Populate hash table with occurrences of temperatures:</em> </td></tr><tr><td> <span> </span></td><td>array. <strong>each</strong> <strong>do</strong> |temperature|</td></tr><tr><td> <span> </span></td><td> <strong>if</strong> hash_table[temperature]</td></tr><tr><td> <span> </span></td><td>hash_table[temperature] += 1</td></tr><tr><td> <span> </span></td><td> <strong>else</strong> </td></tr><tr><td> <span> </span></td><td>hash_table[temperature] = 1</td></tr><tr><td> <span> </span></td><td> <strong>end</strong> </td></tr><tr><td> <span> </span></td><td> <strong>end</strong> </td></tr><tr><td> <span> </span></td><td></td></tr><tr><td> <span> </span></td><td>sorted_array = []</td></tr><tr><td> <span> </span></td><td></td></tr><tr><td> <span> </span></td><td> <em># We multiply the temperature by 10 on the outset</em> </td></tr><tr><td> <span> </span></td><td> <em># so that we can increment the temperature by a whole number</em> </td></tr><tr><td> <span> </span></td><td> <em># during the loop, and avoid floating-point math errors:</em> </td></tr><tr><td> <span> </span></td><td>temperature = 970</td></tr><tr><td> <span> </span></td><td></td></tr><tr><td> <span> </span></td><td> <em># Run loop from 970 up to 990</em> </td></tr><tr><td> <span> </span></td><td> <strong>while</strong> temperature <= 990</td></tr><tr><td> <span> </span></td><td></td></tr><tr><td> <span> </span></td><td> <em># If the hash table contains our the current temperature:</em> </td></tr><tr><td> <span> </span></td><td> <strong>if</strong> hash_table[temperature / 10.0]</td></tr><tr><td> <span> </span></td><td></td></tr><tr><td> <span> </span></td><td> <em># Populate the sorted_array with as many occurences</em> </td></tr><tr><td> <span> </span></td><td> <em># of the current temperature that there are:</em> </td></tr><tr><td> <span> </span></td><td>hash_table[temperature / 10.0]. <strong>times</strong> <strong>do</strong> </td></tr><tr><td> <span> </span></td><td>sorted_array << temperature / 10.0</td></tr><tr><td> <span> </span></td><td> <strong>end</strong> </td></tr><tr><td> <span> </span></td><td> <strong>end</strong> </td></tr><tr><td> <span> </span></td><td></td></tr><tr><td> <span> </span></td><td>temperature += 1</td></tr><tr><td> <span> </span></td><td> <strong>end</strong> </td></tr><tr><td> <span> </span></td><td></td></tr><tr><td> <span> </span></td><td> <strong>return</strong> sorted_array</td></tr><tr><td> <span> </span></td><td> <strong>end</strong> </td></tr></tbody></table>
You’ll note that for the loop, we deal with the temperatures multiplied by 10. That’s only to avoid floating arithmetic issues, because incrementing a variable by 0.1 in a loop causes weird things to happen, and the code doesn’t work correctly.
Let’s now analyze the efficiency of this algorithm. We take N steps to create the hash table. We then run a loop 21 times for all possible temperatures from 97.0 up to 99.0.
In each round of this loop, we run a nested loop to populate the sorted_array with the temperatures. However, this inner loop will never end up running more times than the N temperatures. This is because the inner loop only runs one time for each temperature in the original array.
Thus, we have N steps to create the hash table, 21 steps for the outer loop, and N steps for the inner loop. This is 2N + 21, which is reduced to a beautiful O(N).
-
This optimization employs the most brilliant use of magical lookups that I’ve ever seen.
Imagine we’re iterating over the array of numbers and we encounter a 5. Let’s ask ourselves the magical lookup question: “If I could magically find a desired piece of information in O(1) time, can I make my algorithm faster?”
Well, to determine whether the 5 is part of the longest consecutive sequence, we’d want to know whether there’s a 6 in the array. We’d also want to know if there’s a 7, and an 8, and so on.
Now, we can actually achieve each of those lookups in O(1) time if we first store all the numbers from our array in a hash table. That is, the array, [10, 5, 12, 3, 55, 30, 4, 11, 2] could look like this if we moved the data to a hash table:
<table><tbody><tr><td> <span> </span></td><td>{10 => true, 5 => true, 12 => true, 3 => true, 55 => true,</td></tr><tr><td> <span> </span></td><td>30 => true, 4 => true, 11 => true, 2 => true}</td></tr></tbody></table>
In this case, if we were to encounter the 2, we can then run a loop that keeps checking for the next number in the hash table. If it finds it, we increase the length of the current sequence by one. The loop repeats this process until it can’t find the next number in the sequence. Each of these lookups take just one step.
However, you may ask the following question: how does this help? Imagine our array is [6, 5, 4, 3, 2, 1] . When we iterate over the 6, we’ll find that there isn’t a sequence that builds up from there. When we reach the 5, we’ll find the sequence 5-6. When we reach the 4, we’ll find the sequence 4-5-6. When we reach the 3, we’ll find the sequence 3-4-5-6, and so on. We’ll still end up going through about N 2 / 2 steps finding all those sequences.
The answer to this is: we’ll only start building a sequence if the current number is the bottom number of the sequence. So, we won’t build 4-5-6 when there’s a 3 in the array.
But how do we know if the current number is the bottom of a sequence? By doing a magical lookup!
How? Before running a loop to find a sequence, we’ll do an O(1) lookup of the hash table to check whether there’s a number that’s 1 less than current number. So, if the current number is 4, we’ll first check to see whether there’s a 3 in the array. If there is, we won’t bother to build a sequence. We only want to build a sequence starting from the bottom number of that sequence; otherwise we have redundant steps.
Here’s the code for this:
<table><tbody><tr><td> <span> </span></td><td> <strong>def</strong> <strong>longest_sequence_length</strong> (array)</td></tr><tr><td> <span> </span></td><td>hash_table = {}</td></tr><tr><td> <span> </span></td><td>greatest_sequence_length = 0</td></tr><tr><td> <span> </span></td><td></td></tr><tr><td> <span> </span></td><td> <em># Populate hash table with the numbers as keys:</em> </td></tr><tr><td> <span> </span></td><td>array. <strong>each</strong> <strong>do</strong> |number|</td></tr><tr><td> <span> </span></td><td>hash_table[number] = <strong>true</strong> </td></tr><tr><td> <span> </span></td><td> <strong>end</strong> </td></tr><tr><td> <span> </span></td><td></td></tr><tr><td> <span> </span></td><td> <em># Iterate over each number in the array:</em> </td></tr><tr><td> <span> </span></td><td>array. <strong>each</strong> <strong>do</strong> |number|</td></tr></tbody></table>
| | # If the current number is the first in the sequence, |
| | # (that is, there isn't a number one lower than it): |
| | if !hash_table[number - 1] |
| | |
| | # We start counting the length of the current sequence, |
| | # starting with the current number. Since this is the |
| | # first number of the sequence, the length of the sequence |
| | # is currently 1: |
| | current_sequence_length = 1 |
| | |
| | # We establish a current_number for use in the |
| | # upcoming while loop: |
| | current_number = number |
| | |
| | # Run a while loop as long as there is |
| | # a next number in the sequence: |
| | while hash_table[current_number + 1] |
| | |
| | # Move on to the next number in the sequence: |
| | current_number += 1 |
| | |
| | # Increase the length of the sequence by 1: |
| | current_sequence_length += 1 |
| | |
| | # Greedily keep track of the greatest sequence length: |
| | if current_sequence_length > greatest_sequence_length |
| | greatest_sequence_length = current_sequence_length |
| | end |
| | end |
| | end |
| | end |
| | |
| | return greatest_sequence_length |
| | end |
In this algorithm, we take N steps to build the hash table. We take another N steps to iterate through the array. And we take about another N steps looking up numbers in the hash table to build the different sequences. All in all, this is about 3N, which is reduced to O(N).
Footnotes
[6]
https://pragprog.com/titles/jwdsal2/source_code
[7]
https://pragprog.com/titles/jwdsal2/source_code
[8]
https://pragprog.com/titles/jwdsal2/source_code
[9]
https://pragprog.com/titles/jwdsal2/source_code
[10]
https://pragprog.com/titles/jwdsal2/source_code
[11]
https://pragprog.com/titles/jwdsal2/source_code
[12]
https://pragprog.com/titles/jwdsal2/source_code
[13]
https://pragprog.com/titles/jwdsal2/source_code
[14]
https://pragprog.com/titles/jwdsal2/source_code
[15]
https://pragprog.com/titles/jwdsal2/source_code
[16]
https://pragprog.com/titles/jwdsal2/source_code
[17]
https://pragprog.com/titles/jwdsal2/source_code
[18]
https://pragprog.com/titles/jwdsal2/source_code
[19]
https://pragprog.com/titles/jwdsal2/source_code
Copyright © 2020, The Pragmatic Bookshelf.
Thank you!
How did you enjoy this book? Please let us know. Take a moment and email us at [email protected] with your feedback. Tell us your story and you could win free ebooks. Please use the subject line “Book Feedback.”
Ready for your next great Pragmatic Bookshelf book? Come on over to https://pragprog.com and use the coupon code BUYANOTHER2020 to save 30% on your next ebook.
Void where prohibited, restricted, or otherwise unwelcome. Do not use ebooks near water. If rash persists, see a doctor. Doesn’t apply to The Pragmatic Programmer ebook because it’s older than the Pragmatic Bookshelf itself. Side effects may include increased knowledge and skill, increased marketability, and deep satisfaction. Increase dosage regularly.
And thank you for your continued support,
Andy Hunt, Publisher