Smallest positive value that cannot be represented as sum of subarray JavaScript


We have a sorted array of positive integers like this −

const arr = [1, 3, 6, 10, 11, 15];

We are required to write a function, say findSmallest() that takes in one such array and returns the smallest positive integer that cannot be represented as the sum of some subarray of this original array.

For example −

For this array written above 2 is the smallest positive integer which cannot be reached by summing any subarray of this original array. So, now let's write the code for this function. As the array is sorted, we can achieve the solution to this problem in linear time. We initially consider that the required number is 1, because 1 is the smallest value it can take We will iterate over the array and keep adding the corresponding element to the required number.

If at any iteration, the corresponding number happens to be greater than required number, means that we found our required number otherwise we keep iterating.

Example

const arr = [1, 3, 6, 10, 11, 15];
const findSmallest = arr => {
   let res = 1;
   for(let ind = 0; ind < arr.length && arr[ind] <= res; ind++){
      res += arr[ind];
   }
   return res;
};
console.log(findSmallest(arr));

Output

The output in the console will be −

2

Updated on: 31-Aug-2020

82 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements