Ad
  • Custom User Avatar

    Two pointer approach: It would be a lot faster if the array was sorted to begin with, but the solution still performs much better than a brute force approach using a nested for loop. I ran a script with various implementations of this function in Python (including using a HashMap / dictionary) implementation which came back with the following results:


    Two Sum Performance Comparison

    Small Arrays (Size: 500, Cases: 10)

    • Hash Map O(n): 0.291ms ± 0.042ms
    • Two Pointer + Sort: 1.126ms ± 0.117ms
    • Brute Force O(n²): 27.062ms ± 0.596ms

    Medium Arrays (Size: 2500, Cases: 10)

    • Hash Map O(n): 0.142ms ± 0.031ms
    • Two Pointer + Sort: 5.486ms ± 0.175ms
    • Brute Force O(n²): 6.302ms ± 0.177ms

    Large Arrays (Size: 15000, Cases: 5)

    • Hash Map O(n): 2.898ms ± 0.106ms
    • Two Pointer + Sort: 26.501ms ± 0.697ms
    • Brute Force O(n²): 12105.761ms ± 142.374ms

    Extra Large Arrays (Size: 50000, Cases: 3)

    • Hash Map O(n): 4.853ms ± 0.332ms
    • Two Pointer + Sort: 68.914ms ± 9.171ms
    • Brute Force O(n²): N/A (Execution stopped)

    Note: Two Pointer + Sort is the solution I came up with above. Clearly in this case, a Hash Map implementation is the best choice. Even with a list containing 50,000 elements, the HashMap is able to conjure up a solution in less than 5ms on average. The divergence between the HashMap and two pointer solutions begins to grow larger as the sorting method (which for practical purposes has a time complexity of O(n log(n)), has to deal with increasingly large arrays.

  • Custom User Avatar

    The use of the ternary operator to define the base case (return s.toFixed(2) when n is 0) is quite clever. Not the most readable solution, but definitely a clever one!

  • Custom User Avatar

    In retrospect, toFixed would have been the correct method to use as it only deals with decimals, not the number of digits in the number.

  • Custom User Avatar

    My goal for this one was to keep the code clean and modular, without using the filter function.

  • Custom User Avatar

    I didn't think to define templates like this. Clear, clean code. Great!

  • Custom User Avatar

    I'm trying to understand why if the function is passed a window length of 0, and an offset of 1, the output is expected to be an array of n+1 elements, where n is the length of the array. So for window(0,1, [2, 3]), the expected output would be [[], [], []].

    Shouldn't the output correspond to the number of elements in the array?

  • Custom User Avatar

    Peak programming right here - normalize descriptive variable names like this in massive codebases!

  • Custom User Avatar
  • Custom User Avatar

    This comment is hidden because it contains spoiler information about the solution

  • Custom User Avatar

    I never would've thought of this solution!
    It's super interesting to look at, but quite intuitive if you understand the Array.from() method.