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. [18]

  1. The space complexity is O(N 2 ). This is because the function creates the array called collection , which will end up holding N 2 strings.

  2. This implementation takes up O(N) space, as we create a newArray containing N items.

  3. The following implementation uses this algorithm: we swap the first item with the last item in place. Then, we swap the second item with the second-to-last item in place. We then proceed to swap the third item with the third-to-last item in place, and so on. Since everything is done in place and we don’t create any new data, this has a space complexity of O(1).

    <table><tbody><tr><td>​ <span>&nbsp;</span></td><td>​ <strong>function</strong> ​ reverse(array) {</td></tr><tr><td>​ <span>&nbsp;</span></td><td>​ <strong>for</strong> ​ (​ <strong>let</strong> ​ i = 0; i &lt; array.length / 2; i++) {</td></tr><tr><td>​ <span>&nbsp;</span></td><td>​ <em>// Newer JS way to swap values in an array:</em> ​</td></tr><tr><td>​ <span>&nbsp;</span></td><td>[array[i], array[(array.length - 1) - i]] =</td></tr><tr><td>​ <span>&nbsp;</span></td><td>[array[(array.length - 1) - i], array[i]];</td></tr><tr><td>​ <span>&nbsp;</span></td><td></td></tr><tr><td>​ <span>&nbsp;</span></td><td>​ <em>// Alternate, old-fashioned way of swapping:</em> ​</td></tr><tr><td>​ <span>&nbsp;</span></td><td></td></tr><tr><td>​ <span>&nbsp;</span></td><td>​ <em>// let temp = array[(array.length - 1) - i];</em> ​</td></tr><tr><td>​ <span>&nbsp;</span></td><td>​ <em>// array[(array.length - 1)- i] = array[i];</em> ​</td></tr><tr><td>​ <span>&nbsp;</span></td><td>​ <em>// array[i] = temp;</em> ​</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> ​ array;</td></tr><tr><td>​ <span>&nbsp;</span></td><td>}</td></tr></tbody></table>

    (While we may create a temporary variable to accomplish each swap, we never have more than that one piece of data at any given time throughout the algorithm.)

  4. Here is the completed table:

    Version Time Complexity Space Complexity
    Version #1 O(N) O(N)
    Version #2 O(N) O(1)
    Version #3 O(N) O(N)

    All three versions run for as many steps as there are numbers in the array, so the time complexity is O(N) for all of them.

    Version #1 creates a brand-new array to store the doubled numbers. This array will have the same length as the original array, so takes up O(N) space.

    Version #2 modifies the original array in place, so takes up zero extra space. This is expressed as O(1).

    Version #3 also modifies the original array in place. However, since the function is recursive, the call stack at its peak will have N calls on it, taking up O(N) space.