The following exercises provide you with the opportunity to practice with optimizing for best- and worst-case scenarios. The solutions to these exercises are found in the section, ​ Chapter 6 ​ .

  1. Use Big O Notation to describe the efficiency of an algorithm that takes 3N 2 + 2N + 1 steps.

  2. Use Big O Notation to describe the efficiency of an algorithm that takes N + log N steps.

  3. The following function checks whether an array of numbers contains a pair of two numbers that add up to 10.

    <table><tbody><tr><td>​ <span>&nbsp;</span></td><td>​ <strong>function</strong> ​ twoSum(array) {</td></tr><tr><td>​ <span>&nbsp;</span></td><td>​ <strong>for</strong> ​ (​ <strong>let</strong> ​ i = 0; i &lt; array.length; i++) {</td></tr><tr><td>​ <span>&nbsp;</span></td><td>​ <strong>for</strong> ​ (​ <strong>let</strong> ​ j = 0; j &lt; array.length; j++) {</td></tr><tr><td>​ <span>&nbsp;</span></td><td>​ <strong>if</strong> ​ (i !== j &amp;&amp; array[i] + array[j] === 10) {</td></tr><tr><td>​ <span>&nbsp;</span></td><td>​ <strong>return</strong> ​ ​ <strong>true</strong> ​;</td></tr><tr><td>​ <span>&nbsp;</span></td><td>}</td></tr><tr><td>​ <span>&nbsp;</span></td><td>}</td></tr><tr><td>​ <span>&nbsp;</span></td><td>}</td></tr><tr><td>​ <span>&nbsp;</span></td><td>​ <strong>return</strong> ​ ​ <strong>false</strong> ​;</td></tr><tr><td>​ <span>&nbsp;</span></td><td>}</td></tr></tbody></table>

    What are the best-, average-, and worst-case scenarios? Then, express the worst-case scenario in terms of Big O Notation.

  4. The following function returns whether or not a capital “X” is present within a string.

    <table><tbody><tr><td>​ <span>&nbsp;</span></td><td>​ <strong>function</strong> ​ containsX(string) {</td></tr><tr><td>​ <span>&nbsp;</span></td><td></td></tr><tr><td>​ <span>&nbsp;</span></td><td>foundX = ​ <strong>false</strong> ​;</td></tr><tr><td>​ <span>&nbsp;</span></td><td></td></tr><tr><td>​ <span>&nbsp;</span></td><td>​ <strong>for</strong> ​(​ <strong>let</strong> ​ i = 0; i &lt; string.length; i++) {</td></tr><tr><td>​ <span>&nbsp;</span></td><td>​ <strong>if</strong> ​ (string[i] === ​ <em>"X"</em> ​) {</td></tr><tr><td>​ <span>&nbsp;</span></td><td>foundX = ​ <strong>true</strong> ​;</td></tr><tr><td>​ <span>&nbsp;</span></td><td>}</td></tr><tr><td>​ <span>&nbsp;</span></td><td>}</td></tr><tr><td>​ <span>&nbsp;</span></td><td></td></tr><tr><td>​ <span>&nbsp;</span></td><td>​ <strong>return</strong> ​ foundX;</td></tr><tr><td>​ <span>&nbsp;</span></td><td></td></tr><tr><td>​ <span>&nbsp;</span></td><td>}</td></tr></tbody></table>

    What is this function’s time complexity in terms of Big O Notation?

    Then, modify the code to improve the algorithm’s efficiency for best- and average-case scenarios.

Copyright © 2020, The Pragmatic Bookshelf.