- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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.

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));

The output in the console will be −

2

- Related Questions & Answers
- Find the smallest positive integer value that cannot be represented as sum of any subset of a given array in Python
- Removing smallest subarray to make array sum divisible in JavaScript
- Count numbers which can be represented as sum of same parity primes in C++
- Operators that cannot be overloaded in C++
- Functions that cannot be overloaded in C++
- Check if a number can be represented as sum of non zero powers of 2 in C++
- Check if a number can be represented as a sum of 2 triangular numbers in C++
- Maximum length of subarray such that sum of the subarray is even in C++
- Maximum contiguous sum of subarray in JavaScript
- Check if N can be represented as sum of integers chosen from set {A, B} in Python
- Returning the value of (count of positive / sum of negatives) for an array in JavaScript
- Left right subarray sum product - JavaScript
- Find smallest subarray that contains all elements in same order in C++
- Sum of two numbers where one number is represented as array of digits in C++
- Path with smallest sum in JavaScript

Advertisements