The Wayback Machine - https://web.archive.org/web/20241108085741/https://www.geeksforgeeks.org/find-sum-unique-sub-array-sum-given-array/
Open In App

Find Sum of all unique sub-array sum for a given array.

Last Updated : 17 Aug, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given an array of n-positive elements. The sub-array sum is defined as the sum of all elements of a particular sub-array, the task is to find the sum of all unique sub-array sum. 

Note: Unique Sub-array sum means no other sub-array will have the same sum value. 

Examples:

Input : arr[] = {3, 4, 5} 
Output : 40 
Explanation: All possible unique sub-array with their sum are as: 
(3), (4), (5), (3+4), (4+5), (3+4+5). Here all are unique so required sum = 40

Input : arr[] = {2, 4, 2} 
Output : 12 
Explanation: All possible unique sub-array with their sum are as: 
(2), (4), (2), (2+4), (4+2), (2+4+2). Here only (4) and (2+4+2) are unique.

Method 1 (Sorting Based):

  1. Calculate the cumulative sum of an array. 
  2. Store all sub-array sum in vector. 
  3. Sort the vector. 
  4. Mark all duplicate sub-array sum to zero 
  5. Calculate and return totalSum.

Implementation:

C++




// C++ for finding sum of all unique
// subarray sum
#include <bits/stdc++.h>
using namespace std;
 
// function for finding grandSum
long long int findSubarraySum(int arr[], int n)
{
    int i, j;
 
    // calculate cumulative sum of array
    // cArray[0] will store sum of zero elements
    long long int cArray[n + 1] = { 0 };
    for (i = 0; i < n; i++)
        cArray[i + 1] = cArray[i] + arr[i];
 
    vector<long long int> subArrSum;
 
    // store all subarray sum in vector
    for (i = 1; i <= n; i++)
        for (j = i; j <= n; j++)
            subArrSum.push_back(cArray[j] -
                                cArray[i - 1]);
 
    // sort the vector
    sort(subArrSum.begin(), subArrSum.end());
 
    // mark all duplicate sub-array
    // sum to zero
    long long totalSum = 0;
    for (i = 0; i < subArrSum.size() - 1; i++)
    {
        if (subArrSum[i] == subArrSum[i + 1])
        {
            j = i + 1;
            while (subArrSum[j] == subArrSum[i] &&
                                   j < subArrSum.size())
            {
                subArrSum[j] = 0;
                j++;
            }
            subArrSum[i] = 0;
        }
    }
 
    // calculate total sum
    for (i = 0; i < subArrSum.size(); i++)
        totalSum += subArrSum[i];
 
    // return totalSum
    return totalSum;
}
 
// Driver Code
int main()
{
    int arr[] = { 3, 2, 3, 1, 4 };
    int n = sizeof(arr) / sizeof(arr[0]);
    cout << findSubarraySum(arr, n);
    return 0;
}


Java




// Java for finding sum of all unique
// subarray sum
import java.util.*;
 
class GFG{
 
// Function for finding grandSum
static int findSubarraySum(int arr[], int n)
{
    int i, j;
 
    // Calculate cumulative sum of array
    // cArray[0] will store sum of zero elements
    int cArray[] = new int[n + 1];
    for(i = 0; i < n; i++)
        cArray[i + 1] = cArray[i] + arr[i];
 
    Vector<Integer> subArrSum = new Vector<Integer>();
 
    // Store all subarray sum in vector
    for(i = 1; i <= n; i++)
        for(j = i; j <= n; j++)
            subArrSum.add(cArray[j] -
                          cArray[i - 1]);
 
    // Sort the vector
    Collections.sort(subArrSum);
 
    // Mark all duplicate sub-array
    // sum to zero
    int totalSum = 0;
    for(i = 0; i < subArrSum.size() - 1; i++)
    {
        if (subArrSum.get(i) ==
            subArrSum.get(i + 1))
        {
            j = i + 1;
            while (subArrSum.get(j) ==
                   subArrSum.get(i) &&
               j < subArrSum.size())
            {
                subArrSum.set(j, 0);
                j++;
            }
            subArrSum.set(i, 0);
        }
    }
 
    // Calculate total sum
    for(i = 0; i < subArrSum.size(); i++)
        totalSum += subArrSum.get(i);
 
    // Return totalSum
    return totalSum;
}
 
// Driver Code
public static void main(String[] args)
{
    int arr[] = { 3, 2, 3, 1, 4 };
    int n = arr.length;
     
    System.out.print(findSubarraySum(arr, n));
}
}
 
// This code is contributed by Amit Katiyar


Python3




# Python3 for finding sum of all
# unique subarray sum
 
# function for finding grandSum
def findSubarraySum(arr, n):
     
    # calculate cumulative sum of array
    # cArray[0] will store sum of zero elements
    cArray = [0 for i in range(n + 1)]
    for i in range(0, n, 1):
        cArray[i + 1] = cArray[i] + arr[i]
 
    subArrSum = []
 
    # store all subarray sum in vector
    for i in range(1, n + 1, 1):
        for j in range(i, n + 1, 1):
            subArrSum.append(cArray[j] -
                             cArray[i - 1])
 
    # sort the vector
    subArrSum.sort(reverse = False)
 
    # mark all duplicate sub-array
    # sum to zero
    totalSum = 0
    for i in range(0, len(subArrSum) - 1, 1):
        if (subArrSum[i] == subArrSum[i + 1]):
            j = i + 1
            while (subArrSum[j] == subArrSum[i] and
                           j < len(subArrSum)):
                subArrSum[j] = 0
                j += 1
            subArrSum[i] = 0
 
    # calculate total sum
    for i in range(0, len(subArrSum), 1):
        totalSum += subArrSum[i]
 
    # return totalSum
    return totalSum
 
# Drivers code
if __name__ == '__main__':
    arr = [3, 2, 3, 1, 4]
    n = len(arr)
    print(findSubarraySum(arr, n))
     
# This code is contributed by
# Sahil_Shelangia


C#




// C# for finding sum of all unique
// subarray sum
using System;
using System.Collections.Generic;
class GFG{
 
// Function for finding grandSum
static int findSubarraySum(int []arr,
                           int n)
{
  int i, j;
 
  // Calculate cumulative sum
  // of array cArray[0] will
  // store sum of zero elements
  int []cArray = new int[n + 1];
   
  for(i = 0; i < n; i++)
    cArray[i + 1] = cArray[i] + arr[i];
 
  List<int> subArrSum = new List<int>();
 
  // Store all subarray sum in vector
  for(i = 1; i <= n; i++)
    for(j = i; j <= n; j++)
      subArrSum.Add(cArray[j] -
                    cArray[i - 1]);
 
  // Sort the vector
  subArrSum.Sort();
 
  // Mark all duplicate
  // sub-array sum to zero
  int totalSum = 0;
  for(i = 0; i < subArrSum.Count - 1; i++)
  {
    if (subArrSum[i] ==
        subArrSum[i + 1])
    {
      j = i + 1;
      while (subArrSum[j] ==
             subArrSum[i] &&
             j < subArrSum.Count)
      {
        subArrSum[j] = 0;
        j++;
      }
      subArrSum[i] = 0;
    }
  }
 
  // Calculate total sum
  for(i = 0; i < subArrSum.Count; i++)
    totalSum += subArrSum[i];
 
  // Return totalSum
  return totalSum;
}
 
// Driver Code
public static void Main(String[] args)
{
    int []arr = {3, 2, 3, 1, 4};
    int n = arr.Length;   
    Console.Write(findSubarraySum(arr, n));
}
}
 
// This code is contributed by Rajput-Ji


Javascript




<script>
      // JavaScript for finding sum of all unique
      // subarray sum
      // Function for finding grandSum
      function findSubarraySum(arr, n) {
        var i, j;
 
        // Calculate cumulative sum
        // of array cArray[0] will
        // store sum of zero elements
        var cArray = new Array(n + 1).fill(0);
 
        for (i = 0; i < n; i++)
        cArray[i + 1] = cArray[i] + arr[i];
 
        var subArrSum = [];
 
        // Store all subarray sum in vector
        for (i = 1; i <= n; i++)
          for (j = i; j <= n; j++) subArrSum.push(cArray[j] - cArray[i - 1]);
 
        // Sort the vector
        subArrSum.sort();
 
        // Mark all duplicate
        // sub-array sum to zero
        var totalSum = 0;
        for (i = 0; i < subArrSum.length - 1; i++) {
          if (subArrSum[i] == subArrSum[i + 1]) {
            j = i + 1;
            while (subArrSum[j] == subArrSum[i] && j < subArrSum.length) {
              subArrSum[j] = 0;
              j++;
            }
            subArrSum[i] = 0;
          }
        }
 
        // Calculate total sum
        for (i = 0; i < subArrSum.length; i++) totalSum += subArrSum[i];
 
        // Return totalSum
        return totalSum;
      }
 
      // Driver Code
      var arr = [3, 2, 3, 1, 4];
      var n = arr.length;
      document.write(findSubarraySum(arr, n));
       
      // This code is contributed by rdtank.
    </script>


Output

41

Complexity Analysis:

  • Time Complexity: O(N^2 + N * logN)
  • Auxiliary Space: O(N)

Method 2 (Hashing Based): 

The idea is to make an empty hash table. We generate all subarrays. For every subarray, we compute its sum and increment count of the sum in the hash table. Finally, we add all those sums whose count is 1.

Implementation:

C++




// C++ for finding sum of all unique subarray sum
#include <bits/stdc++.h>
using namespace std;
 
// function for finding grandSum
long long int findSubarraySum(int arr[], int n)
{
    int res = 0;
 
    // Go through all subarrays, compute sums
    // and count occurrences of sums.
    unordered_map<int, int> m;
    for (int i = 0; i < n; i++) {
        int sum = 0;
        for (int j = i; j < n; j++) {
            sum += arr[j];
            m[sum]++;
        }
    }
 
    // Print all those sums that appear
    // once.
    for (auto x : m)
        if (x.second == 1)
            res += x.first;
 
    return res;
}
 
// Driver code
int main()
{
    int arr[] = { 3, 2, 3, 1, 4 };
    int n = sizeof(arr) / sizeof(arr[0]);
    cout << findSubarraySum(arr, n);
    return 0;
}


Java




// Java for finding sum of all
// unique subarray sum
import java.util.*;
 
class GFG
{
 
// function for finding grandSum
static int findSubarraySum(int []arr, int n)
{
    int res = 0;
 
    // Go through all subarrays, compute sums
    // and count occurrences of sums.
    HashMap<Integer,
            Integer> m = new HashMap<Integer,
                                     Integer>();
    for (int i = 0; i < n; i++)
    {
        int sum = 0;
        for (int j = i; j < n; j++)
        {
            sum += arr[j];
            if (m.containsKey(sum))
            {
                m.put(sum, m.get(sum) + 1);
            }
            else
            {
                m.put(sum, 1);
            }
        }
    }
 
    // Print all those sums that appear
    // once.
    for (Map.Entry<Integer,
                   Integer> x : m.entrySet())
        if (x.getValue() == 1)
            res += x.getKey();
 
    return res;
}
 
// Driver code
public static void main(String[] args)
{
    int arr[] = { 3, 2, 3, 1, 4 };
    int n = arr.length;
    System.out.println(findSubarraySum(arr, n));
}
}
 
// This code is contributed by PrinciRaj1992


Python3




# Python3 for finding sum of all
# unique subarray sum
 
# function for finding grandSum
def findSubarraySum(arr, n):
 
    res = 0
 
    # Go through all subarrays, compute sums
    # and count occurrences of sums.
    m = dict()
    for i in range(n):
        Sum = 0
        for j in range(i, n):
            Sum += arr[j]
            m[Sum] = m.get(Sum, 0) + 1
         
    # Print all those Sums that appear
    # once.
    for x in m:
        if m[x] == 1:
            res += x
 
    return res
 
# Driver code
arr = [3, 2, 3, 1, 4]
n = len(arr)
print(findSubarraySum(arr, n))
 
# This code is contributed by mohit kumar


C#




// C# for finding sum of all
// unique subarray sum
using System;
using System.Collections.Generic;
     
class GFG
{
 
// function for finding grandSum
static int findSubarraySum(int []arr, int n)
{
    int res = 0;
 
    // Go through all subarrays, compute sums
    // and count occurrences of sums.
    Dictionary<int,
               int> m = new Dictionary<int,
                                       int>();
    for (int i = 0; i < n; i++)
    {
        int sum = 0;
        for (int j = i; j < n; j++)
        {
            sum += arr[j];
            if (m.ContainsKey(sum))
            {
                m[sum] = m[sum] + 1;
            }
            else
            {
                m.Add(sum, 1);
            }
        }
    }
 
    // Print all those sums that appear
    // once.
    foreach(KeyValuePair<int, int> x in m)
        if (x.Value == 1)
            res += x.Key;
 
    return res;
}
 
// Driver code
public static void Main(String[] args)
{
    int []arr = { 3, 2, 3, 1, 4 };
    int n = arr.Length;
    Console.WriteLine(findSubarraySum(arr, n));
}
}
 
// This code is contributed by Rajput-Ji


Javascript




<script>
 
// Javascript for finding sum of all
// unique subarray sum
 
// Function for finding grandSum
function findSubarraySum(arr, n)
{
    let res = 0;
     
    // Go through all subarrays, compute sums
    // and count occurrences of sums.
    let m = new Map();
    for(let i = 0; i < n; i++)
    {
        let sum = 0;
        for(let j = i; j < n; j++)
        {
            sum += arr[j];
            if (m.has(sum))
            {
                m.set(sum, m.get(sum) + 1);
            }
            else
            {
                m.set(sum, 1);
            }
        }
    }
     
    // Print all those sums that appear
    // once.
    for(let x of m)
        if (x[1] == 1)
            res += x[0];
     
    return res;
}
 
// Driver code
let arr = [ 3, 2, 3, 1, 4 ];
let n = arr.length;
 
document.write(findSubarraySum(arr, n));
 
// This code is contributed by gfgking
 
</script>


Output

41

Complexity Analysis:

  • Time Complexity: O(N^2)
  • Auxiliary Space: O(N)


Previous Article
Next Article

Similar Reads

Count the number of sub-arrays such that the average of elements present in the sub-array is greater than that not present in the sub-array
Given an array of integers arr[], the task is to count the number of sub-arrays such that the average of elements present in the sub-array is greater than the average of elements that are not present in the sub-array.Examples: Input: arr[] = {6, 3, 5} Output: 3 The sub-arrays are {6}, {5} and {6, 3, 5} because their averages are greater than {3, 5}
8 min read
Given a string and an integer k, find the kth sub-string when all the sub-strings are sorted according to the given condition
Given a string str, its sub-strings are formed in such a way that all the sub-strings starting with the first character of the string will occur first in the sorted order of their lengths followed by all the sub-strings starting with the second character of the string in the sorted order of their lengths and so on. For example for the string abc, i
9 min read
Find all unique pairs of maximum and second maximum elements over all sub-arrays in O(NlogN)
Let [Tex](a, b) [/Tex]represent the ordered pair of the second maximum and the maximum element of an array respectively. We need to find all such unique pairs overall contiguous sub-arrays of a given array. Examples: Input: Arr = [ 1, 2, 3, 4, 5 ] Output: (1, 2) (2, 3) (3, 4) (4, 5) Input: Arr = [ 1, 1, 2 ] Output: (1, 1) (1, 2) Input: Arr = [ 1, 2
13 min read
Maximum sub-array sum after dividing array into sub-arrays based on the given queries
Given an array arr[] and an integer k, we can cut this array at k different positions where k[] stores the positions of all the cuts required. The task is to print maximum sum among all the cuts after every cut made. Every cut is of the form of an integer x where x denotes a cut between arr[x] and arr[x + 1]. Examples: Input: arr[] = {4, 5, 6, 7, 8
9 min read
Find minimum length sub-array which has given sub-sequence in it
Given an array arr[] of N elements, the task is to find the length of the smallest sub-array which has the sequence {0, 1, 2, 3, 4} as a sub-sequence in it. Examples: Input: arr[] = {0, 1, 2, 3, 4, 2, 0, 3, 4} Output: 5 The required Subarray is {0, 1, 2, 3, 4} with minimum length. The entire array also includes the sequence but it is not minimum in
10 min read
Find the maximum element in the array other than Ai
Given an array arr[] of size N. The task is to find maximum element among N - 1 elements other than arr[i] for each i from 1 to N.Examples: Input: arr[] = {2, 5, 6, 1, 3} Output: 6 6 5 6 6 Input: arr[] = {1, 2, 3} Output: 3 3 2 Approach: An efficient approach is to make prefix and suffix array of maximum elements and find maximum element among N -
6 min read
Maximum number of Unique integers in Sub-Array of given size
Given an array of N integers and a number M. The task is to find out the maximum number of unique integers among all possible contiguous subarrays of size M. Examples: Input : arr[] = {5, 3, 5, 2, 3, 2}, M = 3 Output : 3 Explanation: In the sample test case, there are 4 subarrays of size 3. s1 = (5, 3, 5)- Has 2 unique numbers. s2 = (3, 5, 2)- Has
12 min read
Ways to divide a binary array into sub-arrays such that each sub-array contains exactly one 1
Give an integer array arr[] consisting of elements from the set {0, 1}. The task is to print the number of ways the array can be divided into sub-arrays such that each sub-array contains exactly one 1. Examples: Input: arr[] = {1, 0, 1, 0, 1} Output: 4 Below are the possible ways: {1, 0}, {1, 0}, {1}{1}, {0, 1, 0}, {1}{1, 0}, {1}, {0, 1}{1}, {0, 1}
6 min read
Divide the array into minimum number of sub-arrays having unique elements
Given an array arr. The task is to divide the array into the minimum number of subarrays containing unique elements and return the count of such subarrays. Note: An array element cannot be present in more than one subarray.Examples : Input : arr[] = {1, 2, 1, 1, 2, 3}Output : 3Explanation : The subarrays having unique elements are { 1, 2 }, { 1 },
8 min read
Given an n x n square matrix, find sum of all sub-squares of size k x k
Given an n x n square matrix, find sum of all sub-squares of size k x k where k is smaller than or equal to n. Examples : Input: n = 5, k = 3 arr[][] = { {1, 1, 1, 1, 1}, {2, 2, 2, 2, 2}, {3, 3, 3, 3, 3}, {4, 4, 4, 4, 4}, {5, 5, 5, 5, 5}, }; Output: 18 18 18 27 27 27 36 36 36 Input: n = 3, k = 2 arr[][] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9}, }; Outpu
15+ min read
Subsequence pair from given Array having all unique and all same elements respectively
Given an array arr[] of N integers, the task is to choose the two subsequences of equal lengths such that the first subsequence must have all the unique elements and the second subsequence must have all the same elements. Print the maximum length of the subsequence pair. Examples: Input: arr[] = {1, 2, 3, 1, 2, 3, 3, 3} Output: 3 Explanation: The f
6 min read
Find sum of sum of all sub-sequences
Given an array of n integers. The task is to find the sum of each sub-sequence of the array. Examples : Input : arr[] = { 6, 8, 5 } Output : 76 All subsequence sum are: { 6 }, sum = 6 { 8 }, sum = 8 { 5 }, sum = 5 { 6, 8 }, sum = 14 { 6, 5 }, sum = 11 { 8, 5 }, sum = 13 { 6, 8, 5 }, sum = 19 Total sum = 76. Input : arr[] = {1, 2} Output : 6 Method
4 min read
Find all possible unique indices after reducing the array based on given conditions
Given an array arr of N integers, and an array of keys, such that key for each element in arr is equal to its index in arr initially. Given that one can perform certain moves where in one move, choose two indices (i, j), remove corresponding elements from the array, and add a new element equal to sum of the removed elements (arr[i] + arr[j]), with
9 min read
Find sum of all unique elements in the array for K queries
Given an arrays arr[] in which initially all elements are 0 and another array Q[][] containing K queries where every query represents a range [L, R], the task is to add 1 to each subarrays where each subarray is defined by the range [L, R], and return sum of all unique elements.Note: One-based indexing is used in the Q[][] array to signify the rang
8 min read
Find all distinct palindromic sub-strings of a given string
Given a string of lowercase ASCII characters, find all distinct continuous palindromic sub-strings of it. Examples: Input: str = "abaaa"Output: Below are 5 palindrome sub-stringsaaaaaaababInput: str = "geek"Output: Below are 4 palindrome sub-stringseeegk Brute Force SolutionIntuition: We declare a boolean 2-D array and fill it diagonally.We check f
15+ min read
Find all unique subsets of a given set using C++ STL
Given an array arr[] of integers of size N that might contain duplicates, the task is to find all possible unique subsets, using C++ STL. Note: Each subset should be sorted. Examples: Input: N = 3, arr[] = {2, 1, 2}Output:(), (1), (1 2), (1 2 2), (2), (2 2)Explanation: All possible subsets = (), (2), (1), (1, 2), (2), (2 2), (2 1), (2, 1, 2)After S
3 min read
Find all Unique Subsets of a given Set
Given an array A[] of positive integers, print all the unique non-empty subsets of the array  Note: The set can not contain duplicate elements, so any repeated subset should be considered only once in the output. Examples:  Input: A[] = {1, 5, 6}Output: {{1}, {1, 5}, {1, 6}, {5}, {5, 6}, {6}, {1, 5, 6}}Explanation: The number of all the non-empty p
15+ min read
For all Array elements find Product of Sum of all smaller and Sum of all greater elements
Given an array arr[] of integers of length N, the task is to find the product of the sum of all the numbers larger than that number with the sum of all the numbers less than that number for each number in the array. Examples: Input: arr[] = {8, 4, 9, 3}, N = 4Output:- 63, 51, 0, 0Explanation:For first number 8: Sum of elements smaller than this is
15 min read
Count all square sub-matrix with sum greater than the given number S
Given a matrix mat[][] and two integers K and S, the task is to count all K x K sub-matrix such that the sum of all the elements in the sub-matrix is greater than or equal to S. Examples: Input: K = 2, S = 15 mat[][] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}} Output: 3 Explanation: In the given matrix there are 3 sub-matrix Sub-Matrix 1: (0, 1) to (1, 2)
15 min read
Count number of square sub matrices of given matrix whose sum of all cells is equal to S | Set 2
Given a matrix, arr[][] of dimensions M*N, and an integer S, the task is to print the count of the number of subsquares of the matrix, whose sum is equal to S. Examples: Input: M = 4, N = 5, S = 10, arr[][]={{2, 4, 3, 2, 10}, {3, 1, 1, 1, 5}, {1, 1, 2, 1, 4}, {2, 1, 1, 1, 3}} Output: 3 Explanation: Sub-squares {10}, {{2, 4}, {3, 1}} and {{1, 1, 1},
12 min read
Print all unique digits present in concatenation of all array elements in the order of their occurrence
Given an array arr[] consisting of N integers, the task is to print all unique digits of the number formed by concatenating all array elements in the order of their occurrence after excluding leading zeroes. Examples: Input: arr[] = {122, 474, 612, 932}Output: 7 6 9 3Explanation:The number formed by concatenating array elements is “122474612932”.Un
10 min read
Find unique lexicographically increasing quadruplets with sum as B and GCD of absolute values of all elements is 1
Given an array A of size N and an integer B, the task is to find all unique quadruplets arranged in the lexicographically increasing order such that the sum of the elements of each quadrupled is B and the gcd of the absolute values of all elements of a quadrupled is 1. Example: Input: A = {1, 0, -1, 0, -2, 2 }, B = 0Output:-2 -1 1 2-1 0 0 1Explanat
11 min read
Find sub-matrix with the given sum
Given an N x N matrix and two integers S and K, the task is to find whether there exists a K x K sub-matrix with sum equal to S. Examples: Input: K = 2, S = 14, mat[][] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 }} Output: Yes 1 2 5 6 is the required 2 x 2 sub-matrix with element sum = 14 Input: K = 1, S = 5, mat[][] =
9 min read
Find sub-arrays from given two arrays such that they have equal sum
Given two arrays A[] and B[] of equal sizes i.e. N containing integers from 1 to N. The task is to find sub-arrays from the given arrays such that they have equal sum. Print the indices of such sub-arrays. If no such sub-arrays are possible then print -1.Examples: Input: A[] = {1, 2, 3, 4, 5}, B[] = {6, 2, 1, 5, 4} Output: Indices in array 1 : 0, 1
15+ min read
All unique combinations whose sum equals to K (Combination Sum II)
Given an array arr[] of size N and an integer K. The task is to find all the unique combinations from the given array such that sum of the elements in each combination is equal to K. Examples: Input: arr[] = {1, 2, 3}, K = 3 Output: {1, 2} {3} Explanation:These are the combinations whose sum equals to 3. Input: arr[] = {2, 2, 2}, K = 4 Output: {2,
7 min read
Find the GCD of LCM of all unique pairs in an Array
Given an integer array arr[] of size N, the task is to find the GCD of LCM of all unique pair (i, j) of the array, such that i < j.Examples: Input: arr[] = {10, 24, 40, 80} Output: 40 Explanation: LCM of all unique pairs following given conditions are: LCM(10, 24) = 120 LCM(10, 40) = 40 LCM(10, 80) = 80 LCM(24, 40) = 120 LCM(24, 80) = 240 LCM(40
9 min read
Print all Unique Strings present in a given Array
Given an array of strings arr[], the task is to print all unique strings that are present in the given array. Examples: Input: arr[] = { "geeks", "geek", "ab", "geek" "code", "karega" } Output: geeks ab code karega Explanation: The frequency of the string "geeks" is 1. The frequency of the string "geek" is 2. The frequency of the string "ab" is 1.
15+ min read
Smallest string containing all unique characters from given array of strings
Given an array of strings arr[], the task is to find the smallest string which contains all the characters of the given array of strings. Examples: Input: arr[] = {"your", "you", "or", "yo"}Output: ruyoExplanation: The string "ruyo" is the smallest string which contains all the characters that are used across all the strings of the given array. Inp
9 min read
Print all Distinct (Unique) Elements in given Array
Given an integer array arr[], print all distinct elements from this array. The given array may contain duplicates and the output should contain every element only once. Examples: Input: arr[] = {12, 10, 9, 45, 2, 10, 10, 45}Output: {12, 10, 9, 45, 2} Input: arr[] = {1, 2, 3, 4, 5}Output: {1, 2, 3, 4, 5} Input: arr[] = {1, 1, 1, 1, 1}Output: {1} Tab
11 min read
Sum of minimum element of all sub-sequences of a sorted array
Given a sorted array A of n integers. The task is to find the sum of the minimum of all possible subsequences of A.Note: Considering there will be no overflow of numbers. Examples: Input: A = [1, 2, 4, 5] Output: 29 Subsequences are [1], [2], [4], [5], [1, 2], [1, 4], [1, 5], [2, 4], [2, 5], [4, 5] [1, 2, 4], [1, 2, 5], [1, 4, 5], [2, 4, 5], [1, 2,
4 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg