title: Find common numbers in array, algorithm efficiency in Javascript
body: <p>I'm solving the problem of finding the common numbers in two arrays.</p>
  
  <p>My first approach was:</p>
  
  <pre><code>    const findCommonNumbers = (array1,array2) =&gt; {
  
      const map = array1.reduce((accum, element)=&gt;{
          accum[element] = true;
          return accum;
      } , {});
  
      const result = [];
      array2.forEach((e)=&gt;{
          if (map[e]) {
              result.push(e);
          }
      });
      return result;
  }
  
  const array1 = [4, 2, 3, 6, 23];
  const array2 = [3, 2, 4, 7 ,9];
  
  
  
  const result = findCommonNumbers(array1, array2 );
  console.log('result', result);
  </code></pre>
  
  <p>But then, looking at the solution, the most efficient way seems to be:</p>
  
  <pre><code>const findCommonNumbers = (array1, array2) =&gt; {
  
      const result = [];
      let p1 = 0;
      let p2 = 0;
      while (p1 &lt; array1.length  &amp;&amp; p2 &lt; array2.length) {
          const e1 = array1[p1];
          const e2 = array2[p2];
  
          if (e1 === e2) {
              result.push(e1);
              p1++;
              p2++;
          }
          else if (e1 &lt; e2) {
              p1++;
          }
          else {
              p2++;
          }
      }
  
      return result;
  }
  
  const array1 = [2, 3, 4, 6, 23];
  const array2 = [2, 3, 4, 7, 9];
  
  
  const result = findCommonNumbers(array1, array2);
  console.log('result', result);
  </code></pre>
  
  <p>But, I see that in both cases, both arrays are iterated once, besides, my initial solution also works for unsorted arrays.
  What would be the complexity of both algorithms, and why?
  Is the proposed solution more efficient just by the fact that both arrays are iterated in the same loop, while in my case I iterate them sequentially?</p>