The Wayback Machine - https://web.archive.org/web/20240818165441/https://www.geeksforgeeks.org/find-smallest-value-represented-sum-subset-given-array/
Open In App

Find the smallest positive integer value that cannot be represented as sum of any subset of a given array

Last Updated : 14 Sep, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given an array of positive numbers, find the smallest positive integer value that cannot be represented as the sum of elements of any subset of a given set. 
The expected time complexity is O(nlogn).

Examples: 

Input:  arr[] = {1, 10, 3, 11, 6, 15};
Output: 2
Input: arr[] = {1, 1, 1, 1};
Output: 5
Input: arr[] = {1, 1, 3, 4};
Output: 10
Input: arr[] = {1, 2, 5, 10, 20, 40};
Output: 4
Input: arr[] = {1, 2, 3, 4, 5, 6};
Output: 22

A Simple Solution is to start from value 1 and check all values one by one if they can sum to values in the given array. This solution is very inefficient as it reduces to the subset sum problem which is a well-known NP-Complete Problem.

Using a simple loop, we can solve this problem in O(N log N) time. Let the input array be arr[0..n-1]. We first sort the array in non-decreasing order. Let the smallest element that cannot be represented by elements at indexes from 0 to (i-1) be ‘res’.  We initialize ‘res’ as 1 (smallest possible answer) and traverse the given array from i=0.  There are the following two possibilities when we consider element at index i:

  1. We decide that ‘res’ is the final result: If arr[i] is greater than ‘res’, then we found the gap which is ‘res’ because the elements after arr[i] are also going to be greater than ‘res’.
  2. The value of ‘res’ is incremented after considering arr[i]: If arr[i] is not greater than ‘res’, the value of ‘res’ is incremented by arr[i] so ‘res’ = ‘res’+arr[i] (why? If elements from 0 to (i-1) can 

represent 1 to ‘res-1’, then elements from 0 to i can represent from 1 to ‘res + arr[i] – 1’ by adding arr[i] to all subsets that represent 1 to ‘res-1’ which we have already determined to be represented)
Following is the implementation of the above idea. 

C++




// C++ program to find the smallest positive value that cannot be
// represented as sum of subsets of a given sorted array
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
 
// Returns the smallest number that cannot be represented as sum
// of subset of elements from set represented by sorted array arr[0..n-1]
long long smallestpositive(vector<long long> arr, int n) {
   long long int res = 1; // Initialize result
  
   sort(arr.begin(), arr.end());
   // Traverse the array and increment 'res' if arr[i] is
   // smaller than or equal to 'res'.
   for (int i = 0; i < n && arr[i] <= res; i++)
       res = res + arr[i];
  
   return res;
  }
 
// Driver program to test above function
int main() {
   vector<long long> arr1 = {1, 3, 4, 5};
   cout << smallestpositive(arr1, arr1.size()) << endl;
  
   vector<long long> arr2 = {1, 2, 6, 10, 11, 15};
   cout << smallestpositive(arr2, arr2.size()) << endl;
  
   vector<long long> arr3 = {1, 1, 1, 1};
   cout << smallestpositive(arr3, arr3.size()) << endl;
  
   vector<long long> arr4 = {1, 1, 3, 4};
   cout << smallestpositive(arr4, arr4.size()) << endl;
  
   return 0;
 }


Java




// Java program to find the smallest positive value that cannot be
// represented as sum of subsets of a given sorted array
import java.util.Arrays;
 
class FindSmallestInteger
{
    // Returns the smallest number that cannot be represented as sum
    // of subset of elements from set represented by sorted array arr[0..n-1]
    int findSmallest(int arr[], int n)
    {
        int res = 1; // Initialize result
 
          // sort the input array
          Arrays.sort(arr);
       
        // Traverse the array and increment 'res' if arr[i] is
        // smaller than or equal to 'res'.
        for (int i = 0; i < n; i++)
        {
          if(arr[i] > res){
            return res;
           }
          else{
            res+=arr[i];
          }
        }
             
        return res;
    }
 
    // Driver program to test above functions
    public static void main(String[] args)
    {
        FindSmallestInteger small = new FindSmallestInteger();
        int arr1[] = {1, 3, 4, 5};
        int n1 = arr1.length;
        System.out.println(small.findSmallest(arr1, n1));
 
        int arr2[] = {1, 2, 6, 10, 11, 15};
        int n2 = arr2.length;
        System.out.println(small.findSmallest(arr2, n2));
 
        int arr3[] = {1, 1, 1, 1};
        int n3 = arr3.length;
        System.out.println(small.findSmallest(arr3, n3));
 
        int arr4[] = {1, 1, 3, 4};
        int n4 = arr4.length;
        System.out.println(small.findSmallest(arr4, n4));
 
    }
}
 
// This code has been contributed by Mukul Sharma (msharma04)


Python3




# Python3 program to find the smallest
# positive value that cannot be
# represented as sum of subsets
# of a given sorted array
 
# Returns the smallest number
# that cannot be represented as sum
# of subset of elements from set
# represented by sorted array arr[0..n-1]
def findSmallest(arr, n):
 
    res = 1 #Initialize result
 
    # Traverse the array and increment
    # 'res' if arr[i] is smaller than
    # or equal to 'res'.
    for i in range (0, n ):
        if arr[i] <= res:
            res = res + arr[i]
        else:
            break
    return res
 
 
# Driver program to test above function
arr1 = [1, 3, 4, 5]
n1 = len(arr1)
print(findSmallest(arr1, n1))
 
arr2= [1, 2, 6, 10, 11, 15]
n2 = len(arr2)
print(findSmallest(arr2, n2))
 
arr3= [1, 1, 1, 1]
n3 = len(arr3)
print(findSmallest(arr3, n3))
 
arr4 = [1, 1, 3, 4]
n4 = len(arr4)
print(findSmallest(arr4, n4))
 
# This code is.contributed by Smitha Dinesh Semwal


C#




// C# program to find the smallest
// positive value that cannot be
// represented as sum of subsets
// of a given sorted array
using System;
 
class GFG {
     
    // Returns the smallest number that
    // cannot be represented as sum
    // of subset of elements from set
    // represented by sorted array
    // arr[0..n-1]
    static int findSmallest(int []arr, int n)
    {
         // Initialize result
         int res = 1;
 
        // Traverse the array and
        // increment 'res' if arr[i] is
        // smaller than or equal to 'res'.
        for (int i = 0; i < n &&
             arr[i] <= res; i++)
            res = res + arr[i];
 
        return res;
    }
 
    // Driver code
    public static void Main()
    {
        int []arr1 = {1, 3, 4, 5};
        int n1 = arr1.Length;
        Console.WriteLine(findSmallest(arr1, n1));
 
        int []arr2 = {1, 2, 6, 10, 11, 15};
        int n2 = arr2.Length;
        Console.WriteLine(findSmallest(arr2, n2));
 
        int []arr3 = {1, 1, 1, 1};
        int n3 = arr3.Length;
        Console.WriteLine(findSmallest(arr3, n3));
 
        int []arr4 = {1, 1, 3, 4};
        int n4 = arr4.Length;
        Console.WriteLine(findSmallest(arr4, n4));
 
    }
}
 
// This code is contributed by Sam007


Javascript




<script>
// javascript program to find the smallest positive value that cannot be
// represented as sum of subsets of a given sorted array
 
    // Returns the smallest number that cannot be represented as sum
    // of subset of elements from set represented by sorted array arr[0..n-1]
    function findSmallest(arr , n)
    {
        var res = 1; // Initialize result
 
        // Traverse the array and increment 'res' if arr[i] is
        // smaller than or equal to 'res'.
        for (i = 0; i < n && arr[i] <= res; i++)
            res = res + arr[i];
 
        return res;
    }
 
    // Driver program to test above functions
 
        var arr1 = [ 1, 3, 4, 5 ];
        var n1 = arr1.length;
        document.write(findSmallest(arr1, n1)+"<br/>");
 
        var arr2 = [ 1, 2, 6, 10, 11, 15 ];
        var n2 = arr2.length;
        document.write(findSmallest(arr2, n2)+"<br/>");
 
        var arr3 = [ 1, 1, 1, 1 ];
        var n3 = arr3.length;
        document.write(findSmallest(arr3, n3)+"<br/>");
 
        var arr4 = [ 1, 1, 3, 4 ];
        var n4 = arr4.length;
        document.write(findSmallest(arr4, n4)+"<br/>");
 
// This code is contributed by aashish1995
</script>


PHP




<?php
// PHP program to find the smallest
// positive value that cannot be
// represented as sum of subsets
// of a given sorted array
 
// Returns the smallest number that
// cannot be represented as sum of
// subset of elements from set
// represented by sorted array
// arr[0..n-1]
function findSmallest($arr, $n)
{
     
    // Initialize result
    $res = 1;
     
    // Traverse the array and
    // increment 'res' if arr[i] is
    // smaller than or equal to 'res'.
    for($i = 0; $i < $n and $arr[$i] <= $res; $i++)
        $res = $res + $arr[$i];
     
    return $res;
}
 
// Driver Code
$arr1 = array(1, 3, 4, 5);
$n1 = count($arr1);
echo findSmallest($arr1, $n1),"\n";
 
$arr2 = array(1, 2, 6, 10, 11, 15);
$n2 = count($arr2);
echo findSmallest($arr2, $n2),"\n" ;
 
$arr3 = array(1, 1, 1, 1);
$n3 = count($arr3);
echo findSmallest($arr3, $n3),"\n";
 
$arr4 = array(1, 1, 3, 4);
$n4 = count($arr4);
echo findSmallest($arr4, $n4);
 
// This code is contributed by anuj_67.
?>


Output

2
4
5
10



The Time Complexity of the above program is O(nlogn). 

The Space Complexity is O(1) in best case for heap sort.  

Approach#2: Using dynamic programming

In this approach, we can use dynamic programming to solve the problem. We can create a boolean array of size (sum+1), where sum is the sum of all the elements in the array. We can then use dynamic programming to mark all the possible sums that can be obtained by selecting some of the elements in the array. Finally, we can iterate through the boolean array to find the smallest positive integer that cannot be represented as a sum of any subset of the given array.

Algorithm

1. Calculate the sum of all elements in the given array.
2. Create a boolean array of size (sum+1), initialized to False.
3. Mark arr[0] as True, as a subset with sum equal to arr[0] can be formed.
4. For each element arr[i], iterate through the boolean array from right to left, and mark arr[i]+j as True if arr[i]+j is less than or equal to sum.
5. Finally, iterate through the boolean array from left to right, and return the index of the first False element plus 1.

C++




#include <iostream>
#include <vector>
using namespace std;
 
int smallest_positive_integer(vector<int>& arr) {
    int n = arr.size();
    int s = 0;
    for (int i = 0; i < n; i++) {
        s += arr[i]; // compute sum of all elements
    }
    vector<bool> dp(s+1, false); // initialize dp array with false values
    dp[0] = true; // a subset with sum 0 can always be formed
    for (int i = 0; i < n; i++) {
        for (int j = s; j >= arr[i]; j--) {
            if (dp[j-arr[i]]) { // if it's possible to form a subset with sum j-arr[i]
                dp[j] = true; // then it's also possible to form a subset with sum j
            }
        }
    }
    for (int i = 1; i <= s; i++) {
        if (!dp[i]) { // find the smallest positive integer that cannot be formed
            return i;
        }
    }
    return s+1; // if all integers can be formed, then the answer is s+1
}
 
int main() {
    vector<int> arr = {1, 3, 4, 5};
    cout << smallest_positive_integer(arr) << endl;
    arr = {1, 2, 6, 10, 11, 15};
    cout << smallest_positive_integer(arr) << endl;
    arr = {1, 1, 1, 1};
    cout << smallest_positive_integer(arr) << endl;
    arr = {1, 1, 3, 4};
    cout << smallest_positive_integer(arr) << endl;
    return 0;
}


Java




import java.util.ArrayList;
 
public class GFG {
    public static int smallestPositiveInteger(ArrayList<Integer> arr) {
        int n = arr.size();
        int s = 0;
        for (int i = 0; i < n; i++) {
            s += arr.get(i); // compute sum of all elements
        }
        boolean[] dp = new boolean[s + 1]; // initialize dp array with false values
        dp[0] = true; // a subset with sum 0 can always be formed
        for (int i = 0; i < n; i++) {
            for (int j = s; j >= arr.get(i); j--) {
                if (dp[j - arr.get(i)]) { // if it's possible to form a subset with sum j-arr[i]
                    dp[j] = true; // then it's also possible to form a subset with sum j
                }
            }
        }
        for (int i = 1; i <= s; i++) {
            if (!dp[i]) { // find the smallest positive integer that cannot be formed
                return i;
            }
        }
        return s + 1; // if all integers can be formed, then the answer is s+1
    }
 
    // Driver code
    public static void main(String[] args) {
        ArrayList<Integer> arr = new ArrayList<>();
        arr.add(1);
        arr.add(3);
        arr.add(4);
        arr.add(5);
        System.out.println(smallestPositiveInteger(arr));
 
        arr.clear();
        arr.add(1);
        arr.add(2);
        arr.add(6);
        arr.add(10);
        arr.add(11);
        arr.add(15);
        System.out.println(smallestPositiveInteger(arr));
 
        arr.clear();
        arr.add(1);
        arr.add(1);
        arr.add(1);
        arr.add(1);
        System.out.println(smallestPositiveInteger(arr));
 
        arr.clear();
        arr.add(1);
        arr.add(1);
        arr.add(3);
        arr.add(4);
        System.out.println(smallestPositiveInteger(arr));
    }
}


Python3




def smallest_positive_integer(arr):
    n = len(arr)
    s = sum(arr)
    dp = [False]*(s+1)
    dp[0] = True
    for i in range(n):
        for j in range(s, arr[i]-1, -1):
            if dp[j-arr[i]]:
                dp[j] = True
    for i in range(1, s+1):
        if not dp[i]:
            return i
    return s+1
 
arr=[1, 3, 4, 5]
print(smallest_positive_integer(arr))
arr=[1, 2, 6, 10, 11, 15]
print(smallest_positive_integer(arr))
arr=[1, 1, 1, 1]
print(smallest_positive_integer(arr))
arr=[1,1,3,4]
print(smallest_positive_integer(arr))


C#




using System;
using System.Collections.Generic;
 
class Program {
    static int SmallestPositiveInteger(List<int> arr)
    {
        int n = arr.Count;
        int s = 0;
        for (int i = 0; i < n; i++) {
              // compute sum of all elements
            s += arr[i];
        }
 
        bool[] dp = new bool[s + 1];
          // a subset with sum 0 can always be formed
        dp[0] = true;
 
        for (int i = 0; i < n; i++) {
            for (int j = s; j >= arr[i]; j--) {
                if (dp[j - arr[i]]) // if it's possible to
                                    // form a subset with
                                    // sum j-arr[i]
                {
                    dp[j] = true; // then it's also possible
                                  // to form a subset with
                                  // sum j
                }
            }
        }
 
        for (int i = 1; i <= s; i++) {
            if (!dp[i]) // find the smallest positive
                        // integer that cannot be formed
            {
                return i;
            }
        }
 
        return s + 1; // if all integers can be formed, then
                      // the answer is s+1
    }
 
    static void Main(string[] args)
    {
        List<int> arr = new List<int>{ 1, 3, 4, 5 };
        Console.WriteLine(SmallestPositiveInteger(arr));
 
        arr = new List<int>{ 1, 2, 6, 10, 11, 15 };
        Console.WriteLine(SmallestPositiveInteger(arr));
 
        arr = new List<int>{ 1, 1, 1, 1 };
        Console.WriteLine(SmallestPositiveInteger(arr));
 
        arr = new List<int>{ 1, 1, 3, 4 };
        Console.WriteLine(SmallestPositiveInteger(arr));
    }
}


Javascript




function smallestPositiveInteger(arr) {
    const n = arr.length;
    let s = 0;
    for (let i = 0; i < n; i++) {
        s += arr[i]; // compute sum of all elements
    }
    const dp = new Array(s + 1).fill(false); // initialize dp array with false values
    dp[0] = true; // a subset with sum 0 can always be formed
    for (let i = 0; i < n; i++) {
        for (let j = s; j >= arr[i]; j--) {
            if (dp[j - arr[i]]) { // if it's possible to form a subset with sum j-arr[i]
                dp[j] = true; // then it's also possible to form a subset with sum j
            }
        }
    }
    for (let i = 1; i <= s; i++) {
        if (!dp[i]) { // find the smallest positive integer that cannot be formed
            return i;
        }
    }
    return s + 1; // if all integers can be formed, then the answer is s+1
}
 
// Driver code
const arr1 = [1, 3, 4, 5];
console.log(smallestPositiveInteger(arr1));
 
const arr2 = [1, 2, 6, 10, 11, 15];
console.log(smallestPositiveInteger(arr2));
 
const arr3 = [1, 1, 1, 1];
console.log(smallestPositiveInteger(arr3));
 
const arr4 = [1, 1, 3, 4];
console.log(smallestPositiveInteger(arr4));


Output

2
4
5
10



Time Complexity: O(n*sum), where n is length of array
Auxiliary Space: O(sum)



Previous Article
Next Article

Similar Reads

Only integer with positive value in positive negative value in array
Given an array of N integers. In the given, for each positive element 'x' there exist a negative value '-x', except one integer whose negative value is not present. That integer may occur multiple number of time. The task is find that integer. Examples: Input : arr[] = { 1, 8, -6, -1, 6, 8, 8 } Output : 8 All positive elements have an equal negativ
8 min read
Find maximum subset sum formed by partitioning any subset of array into 2 partitions with equal sum
Given an array A containing N elements. Partition any subset of this array into two disjoint subsets such that both the subsets have an identical sum. Obtain the maximum sum that can be obtained after partitioning. Note: It is not necessary to partition the entire array, that is any element might not contribute to any of the partition. Examples: In
15+ min read
Maximize Array sum by replacing any K elements by its modulo with any positive integer
Given an array of positive integer arr[], and a number K. the task is to maximize the sum of the array by replacing any K elements of the array by taking modulus with any positive integer which is less than arr[i] i.e, (arr[i] = arr[i]%X where X â‰Ī arr[i]). Examples: Input: arr[] = {5, 7, 18, 12, 11, 3}, K = 4Output: 41Explanation: The replacement s
5 min read
Smallest positive integer that does not divide any elements of the given array
Given an array arr[] consisting of N positive integers, the task is to determine the smallest positive integer K such that none of the array elements is divisible by K. Examples: Input: arr[] = {3, 2, 6, 9, 2}Output: 4Explanation: None of the array elements is divisible by 4(the smallest positive). Input: arr[] = {3, 5, 1, 19, 11}Output: 2 Approach
6 min read
Reduce sum of any subset of an array to 1 by multiplying all its elements by any value
Given an array arr[] consisting of N positive integers, the task is to check if the sum of the elements of any subset of the given array can be reduced to 1 after multiplying all its elements by any integer. If it is not possible to do so, then print "No". Otherwise, print "Yes". Examples: Input: arr[] = {29, 6, 4, 10}Output: YesExplanation:Choose
7 min read
Find the smallest positive number which can not be represented by given digits
Given an array arr[] of size 10 where arr[i] represents the frequency of the digit i. The task is to find the smallest positive number which can not be represented by the given digits. Examples: Input: arr[] = {2, 1, 1, 4, 0, 6, 3, 2, 2, 2} Output: 4 Since the count of 4th digit is 0. So 4 can not be made. Input : arr[] = {0, 1, 1, 1, 1, 1, 1, 1, 1
8 min read
K-th smallest positive integer having sum with given number equal to bitwise OR with given number
Given two positive integers X and K, the task is to find the K-th smallest positive integer Y, such that X + Y = X | Y, where | denotes the bitwise OR operation. Example: Input: X = 5, K = 1Output: 2Explanation: The first number is 2 as (2 + 5 = 2 | 5 ) Input: X = 5, K = 5Output: 18Explanation: The list of correct values is 2, 8, 10, 16, 18. The 5t
5 min read
Find the last positive element remaining after repeated subtractions of smallest positive element from all Array elements
Given an array arr[] consisting of N positive integers, the task is to find the last positive array element remaining after repeated subtractions of the smallest positive array element from all array elements. Examples: Input: arr[] = {3, 5, 4, 7}Output: 2Explanation: Subtract the smallest positive element from the array, i.e. 3, the new array is a
6 min read
Largest possible Subset from an Array such that no element is K times any other element in the Subset
Given an array arr[] consisting of N distinct integers and an integer K, the task is to find the maximum size of a subset possible such that no element in the subset is K times any other element of the subset(i.e. no such pair {n, m} should be present in the subset such that either m = n * K or n = m * K). Examples: Input: arr[] = {2, 8, 6, 5, 3},
7 min read
Count numbers up to N that cannot be expressed as sum of at least two consecutive positive integers
Given a positive integer N, the task is to find the count of integers from the range [1, N] such that the integer cannot be expressed as sum of two or more consecutive positive integers. Examples: Input: N = 10Output: 4Explanation: The integers that cannot be expressed as sum of two or more consecutive integers are {1, 2, 4, 8}. Therefore, the coun
8 min read
Minimize operations to convert A to B by adding any odd integer or subtracting any even integer
Given two positive integers A and B. The task is to find the minimum number of operations required to convert number A into B. In a move, any one of the following operations can be applied on the number A: Select any odd integer x (x&gt;0) and add it to A i.e. (A+x);Or, select any even integer y (y&gt;0) and subtract it from A i.e. (A-y). Examples:
5 min read
Smallest positive integer that divides all array elements to generate quotients with sum not exceeding K
Given an array arr[] of size N and a positive integer K, the task is to find the smallest positive integer such that the sum of remaining array elements obtained by dividing all array elements by that smallest positive integer does not exceed K. Note: Dividing an array element by the smallest positive integer must be of Ceil type. Examples: Input:
8 min read
Find a non empty subset in an array of N integers such that sum of elements of subset is divisible by N
Given an array of N integers, the task is to find a non-empty subset such that the sum of elements of the subset is divisible by N. Output any such subset with its size and the indices(1-based indexing) of elements in the original array if it exists. Prerequisites: Pigeonhole PrincipleExamples: Input: arr[] = { 2, 3, 7, 1, 9 } Output: 2 1 2 The req
8 min read
Why the original value cannot be recovered from a given hash value?
A hash function is a mathematical function that takes input data (also known as the message or pre-image) and produces a fixed-length output called a hash value or digest. One of the main properties of a hash function is that it is designed to be a one-way function, meaning that it is computationally infeasible to recover the original input data fr
10 min read
Kth smallest positive integer Y such that its sum with X is same as its bitwise OR with X
Given two positive integers X and K, the task is to find the Kth smallest positive integer (Y) such that the sum of X and Y is equal to Bitwise OR of X and Y, i.e. (X + Y = X | Y) Examples: Input: X = 5, K = 1Output: 2Explanation:Consider the smallest number as 2. The sum of 2 and 5 is 2 + 5 = 7 and the Bitwise OR of 2 and 5 is 7. Input: X = 5, K =
6 min read
Sum of maximum and minimum of Kth subset ordered by increasing subset sum
Given an integer N and a set of all non-negative powers of N as S = {N0, N1, N2, N3, ... }, arrange all non-empty subsets of S in increasing order of subset-sum. The task is to find the sum of the greatest and smallest elements of the Kth subset from that ordering. Examples: Input: N = 4, K = 3Output: 5Explanation: S = {1, 4, 16, 64, ...}.Therefore
7 min read
Smallest positive integer X satisfying the given equation
Given two integers N and K, the task is to find the smallest positive integer X satisfying the equation: (X / K) * (X % K) = N Examples: Input: N = 6, K = 3 Output: 11 Explanation: For X = 11, (11 / 3) * (11 % 3) = 3 * 2 = 6 Therefore, the following equation satisfies. Input: N = 4, K = 6 Output: 10 Explanation: For X = 10, (10 / 6) * (10 % 6) = 1
7 min read
Generate an array with K positive numbers such that arr[i] is either -1 or 1 and sum of the array is positive
Given two positive integers, N and K ( 1 â‰Ī K â‰Ī N ), the task is to construct an array arr[](1-based indexing) such that each array element arr[i] is either i or -i and the array contains exactly K positive values such that sum of the array elements is positive. If more than one such sequence can be generated, print any of them. Otherwise, print "-1
7 min read
Count pairs in Array whose product is a Kth power of any positive integer
Given an array arr[] of length N and an integer K, the task is to count pairs in the array whose product is Kth power of a positive integer, i.e. A[i] * A[j] = ZK for any positive integer Z. Examples: Input: arr[] = {1, 3, 9, 8, 24, 1}, K = 3 Output: 5 Explanation: There are 5 such pairs, those can be represented as Z3 - A[0] * A[3] = 1 * 8 = 2^3 A
14 min read
Minimum replacements with any positive integer to make the array K-increasing
Given an array arr[] of N positive integers and an integer K, The task is to replace minimum number of elements with any positive integer to make the array K-increasing. An array is K-increasing if for every index i in range [K, N), arr[i] â‰Ĩ arr[i-K] Examples: Input: arr[] = {4, 1, 5, 2, 6, 2}, k = 2Output: 0Explanation: Here, for every index i whe
11 min read
Smallest positive integer K such that all array elements can be made equal by incrementing or decrementing by at most K
Given an array arr[] of size N, the task is to find the smallest positive integer K such that incrementing or decrementing each array element by K at most once makes all elements equal. If it is not possible to make all array elements equal, then print -1. Examples : Input: arr[] = { 5, 7, 9 }Output: 2Explanation: Incrementing the value of arr[0] b
14 min read
Split Array into K non-overlapping subset such that maximum among all subset sum is minimum
Given an array arr[] consisting of N integers and an integer K, the task is to split the given array into K non-overlapping subsets such that the maximum among the sum of all subsets is minimum. Examples: Input: arr[] = {1, 7, 9, 2, 12, 3, 3}, M = 3Output: 13Explanation:One possible way to split the array into 3 non-overlapping subsets is {arr[4],
7 min read
Convert given Array to 0 by reducing elements pairwise with any positive value
Given an array arr[] of size N, the task is to find the number of operations to convert array elements to zero by decrementing the value of array elements in pairs by any positive value. If the array elements can't be converted to 0, return -1. Input: arr[] = {3, 2}Output: -1Explanation: All the array elements can't be converted to 0Input: arr[] =
6 min read
Minimum positive integer value possible of X for given A and B in X = P*A + Q*B
Given values of A and B, find the minimum positive integer value of X that can be achieved in the equation X = P*A + P*B, Here P and Q can be zero or any positive or negative integer. Examples: Input: A = 3 B = 2 Output: 1 Input: A = 2 B = 4 Output: 2 Basically we need to find P and Q such that P*A &gt; P*B and P*A - P*B is minimum positive integer
3 min read
Number of ways in which N can be represented as the sum of two positive integers
Given a number N, the task is to find the number of unique ways in which N can be represented as a sum of two positive integers.Examples: Input: N = 7 Output: 3 (1 + 6), (2 + 5) and (3 + 4).Input: N = 200 Output: 100 Approach: The number of ways in which the number can be expressed as the sum of two positive integers are 1 + (N - 1), 2 + (N - 2), .
3 min read
Check if a number can be represented as sum of two positive perfect cubes
Given an integer N, the task is to check if N can be represented as the sum of two positive perfect cubes or not. Examples: Input: N = 28Output: YesExplanation: Since, 28 = 27 + 1 = 33 + 13.Therefore, the required answer is Yes Input: N = 34Output: No Approach: The idea is to store the perfect cubes of all numbers from 1 to cubic root of N in a Map
15+ min read
Check if N can be represented as sum of positive integers containing digit D at least once
Given a positive integer N and a digit D, the task is to check if N can be represented as a sum of positive integers containing the digit D at least once. If it is possible to represent N in such a format, then print "Yes". Otherwise, print "No". Examples: Input: N = 24, D = 7 Output: Yes Explanation: The value 24 can be represented as 17 + 7, both
10 min read
Check if a number can be represented as sum of two positive perfect biquadrates
Given a positive integer N, the task is to check if N can be written as the sum of two perfect biquadrates or not i.e., (N = X4 + Y4), where X and Y are non-negative integers. If it is possible, then print Yes. Otherwise, print No. Examples: Input: N = 97 Output: Yes Explanation: Summation of the biquadrates of 2 and 3 is 97, i.e. 24 + 34 = 16 + 81
11 min read
Check whether a number can be represented as sum of K distinct positive integers
Given two integers N and K, the task is to check whether N can be represented as sum of K distinct positive integers. Examples: Input: N = 12, K = 4 Output: Yes N = 1 + 2 + 4 + 5 = 12 (12 as sum of 4 distinct integers) Input: N = 8, K = 4 Output: No Recommended: Please try your approach on {IDE} first, before moving on to the solution.Approach: Con
10 min read
Check if a number can be represented as sum of K positive integers out of which at least K - 1 are nearly prime
Given two integers N and K, the task is to check if N can be represented as a sum of K positive integers, where at least K - 1 of them are nearly prime. Nearly Primes: Refers to those numbers which can be represented as a product of any pair of prime numbers. Examples: Input: N = 100, K = 6Output: YesExplanation: 100 can be represented as 4 + 6 + 9
15+ min read
Article Tags :
Practice Tags :
three90RightbarBannerImg