Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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 the array written above, 2 is the smallest positive integer which cannot be reached by summing any subarray of this original array.
Algorithm Approach
Since 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 positive 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 the required number, it means that we found our required number. Otherwise, we keep iterating.
How It Works
The algorithm maintains a variable res that represents the smallest number that cannot be formed yet. For each element in the array:
- If
arr[i] <= res, we can form all numbers from 1 tores + arr[i] - 1 - If
arr[i] > res, thenresis our answer because we cannot form it
Example
const arr = [1, 3, 6, 10, 11, 15];
const findSmallest = arr => {
let res = 1;
for(let ind = 0; ind
2
Step by Step Execution
const arr = [1, 3, 6, 10, 11, 15];
const findSmallestWithSteps = arr => {
let res = 1;
console.log("Initial res:", res);
for(let ind = 0; ind
Initial res: 1
Step 1: arr[0] = 1, res = 1
After adding: res = 2
Step 2: arr[1] = 3, res = 2
Final result: 2
Additional Examples
// Test with different arrays
const testCases = [
[1, 1, 1, 1],
[1, 2, 3, 4, 5],
[1, 1, 3, 4],
[2, 3, 4, 5]
];
testCases.forEach((arr, index) => {
const result = findSmallest(arr);
console.log(`Array ${index + 1}: [${arr.join(', ')}] ? ${result}`);
});
function findSmallest(arr) {
let res = 1;
for(let ind = 0; ind
Array 1: [1, 1, 1, 1] ? 5
Array 2: [1, 2, 3, 4, 5] ? 16
Array 3: [1, 1, 3, 4] ? 10
Array 4: [2, 3, 4, 5] ? 1
Time and Space Complexity
- Time Complexity: O(n) where n is the length of the array
- Space Complexity: O(1) as we use only constant extra space
Conclusion
This algorithm efficiently finds the smallest positive integer that cannot be represented as a sum of subarray elements in O(n) time. The key insight is that for a sorted array, we can incrementally build the range of representable numbers.
