Contiguous elements of the list sum to K The task:


  Given a list of integers and a number K, return which contiguous
  elements of the list sum to K.
  
  For example, if the list is [1, 2, 3, 4, 5] and K is 9, then it should
  return [2, 3, 4].


My solution

// init
const arr = [1, 2, 3, 4, 5];
const K = 9;

// main
const getContiguousElementsSum = (arr, K) =&gt; {
  if (arr.length === 0 || K &lt; 0) {
    return null;
  }
  let sum = 0;
  const returnResult = [];
  const found = arr.some(x =&gt; {
    sum += x;
    returnResult.push(x);
    return sum === K;
  });
  // exit case
  if (found) {
    return returnResult;
  }
  // recursive case
  return getContiguousElementsSum(arr.slice(1), K);
};
console.log(getContiguousElementsSum(arr, K));


Is there a shorter and/or more readable solution?
// init
const arr = [1, 2, 3, 4, 5];
const K = 9;

// main
const getContiguousElementsSum = (arr, K) =&gt; {



It seems to me to be unnecessarily confusing to alias variable identifiers like this.




  if (arr.length === 0 || K &lt; 0) {
    return null;
  }



I don't see this anywhere in the specification you've quoted. I would expect the function to handle K === 0 by returning [], and to give [-1,-2,-3] for getContiguousElementsSum([-1,-2,-3,-4], -6).

Also, since the specification doesn't say anything about error cases, I would assume by default that it should throw something (probably RangeError) if no matching subarray can be found.




  const found = arr.some(x =&gt; {
    sum += x;
    returnResult.push(x);
    return sum === K;
  });



It would be kinder to the garbage collector to just track indexes and use slice when you find a match.




  // recursive case
  return getContiguousElementsSum(arr.slice(1), K);



The overall complexity of this implementation is \$O(n^2)\$. It can be done quite easily in \$O(n \lg n)\$ in full generality using just arrays, and in \$O(n)\$ if you have an efficient set implementation, by using the property $$\sum_{i=a}^b A[i] = \left(\sum_{i=0}^a A[i]\right) - \left(\sum_{i=0}^{b-1} A[i]\right)$$To build an array of \$\left(\sum_{i=0}^a A[i]\right)\$ takes linear time; then either convert it into a set or sort it; and for each element in the array of partial sums you need to test for the presence of that partial sum minus the target.

And, of course, it can be done in \$O(n)\$ time with just arrays if you're guaranteed that the elements are positive, as described in janos' answer.