These are the solutions to the exercises found in the section, Exercises . The solutions provided here are in JavaScript, but you can find the solutions in Python and Ruby in the code download. [7]
-
In Big O Notation, 2N 2 + 2N + 1 gets reduced to O(N 2 ). After getting rid of all the constants, we’re left with N 2 + N, but we also drop the N since it’s a lower order than N 2 .
-
log N is a lower order than N, so it’s simply reduced to O(N).
-
The important thing to note here is that the function ends as soon as we find a pair that sums to 10. The best-case scenario, then, is when the first two numbers add up to 10, since we can end the function before the loops even get underway. An average-case scenario may be when the two numbers are somewhere in the middle of the array. The worst-case scenarios are when there aren’t any two numbers that add up to 10, in which case we must exhaust both loops completely. This worst-case scenario is O(N 2 ), where N is the size of the array.
-
This algorithm has an efficiency of O(N), as the size of the array is N, and the loop iterates through all N elements.
This algorithm continues the loop even if it finds an "X" before the end of the array. We can make the code more efficient if we return true as soon as we find an "X" :
<table><tbody><tr><td> <span> </span></td><td> <strong>function</strong> containsX(string) {</td></tr><tr><td> <span> </span></td><td></td></tr><tr><td> <span> </span></td><td> <strong>for</strong> ( <strong>let</strong> i = 0; i < string.length; i++) {</td></tr><tr><td> <span> </span></td><td> <strong>if</strong> (string[i] === <em>"X"</em> ) {</td></tr><tr><td> <span> </span></td><td> <strong>return</strong> <strong>true</strong> ;</td></tr><tr><td> <span> </span></td><td>}</td></tr><tr><td> <span> </span></td><td>}</td></tr><tr><td> <span> </span></td><td></td></tr><tr><td> <span> </span></td><td> <strong>return</strong> <strong>false</strong> ;</td></tr><tr><td> <span> </span></td><td>}</td></tr></tbody></table>