Find Smallest Integer
You are given an array 'ARR' consisting of 'N' positive numbers and sorted in non-decreasing order, and your task is to find the smallest positive integer value that cannot be represented as a sum of elements of any proper subset of the given array.
An array 'B' is a subset of another array 'A' if each element of 'B' is present in 'A'.
For example:
For the given input array [1, 1, 3],
1 can be represented as the sum of elements of the subset [1],
2 can be represented as the sum of elements of a subset [1, 1],
3 can be represented as the sum of elements of a subset [3],
4 can be represented as the sum of elements of a subset [1, 3],
5 can be represented as the sum of elements of a subset [1, 1, 3]
So, the smallest positive integer value that cannot be represented as a sum of elements of any subset of a given array is 6.
Input Format:
The first line of input contains an integer ‘T’ representing the number of test cases. Then the test cases follow.
The first line of each test case contains an integer ‘N’ representing the size of the input array.
The second line of each test case contains elements of the array separated by a single space.
Output Format:
For each test case, the only line of output prints a single integer representing the smallest positive integer value that cannot be represented as a sum of any subset of the given array.
Output for each test case will be printed in a separate line.
Note:
You do not need to print anything; it has already been taken care of.
Constraints:
1 <= T <= 100
1 <= N <= 10^4
0 <= arr[i] <= 10^9
Where 'T' represents the number of test cases, 'N' represents the size of the array, and 'arr[i]' represents the elements of the array.
Time Limit: 1 sec.
CodingNinjas
author
2y
Brute force Approach
The brute force approach for this problem is explained below:
- We can generate all possible 2 ^ N subsets where ‘N’ is the number of elements in the array.
- Compute the sum of each sub...read more
CodingNinjas
author
2y
Optimized Approach
We can solve this problem in O(n) time using a simple loop. Let the input array be ARR[0..n-1]. We initialize the result as 1 (smallest possible outcome) and traverse the given array...read more
Help your peers!
Add answer anonymously...
Top Delhivery Software Developer interview questions & answers
Popular interview questions of Software Developer
Stay ahead in your career. Get AmbitionBox app
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+
Reviews
4 L+
Interviews
4 Cr+
Salaries
1 Cr+
Users/Month
Contribute to help millions
Get AmbitionBox app