# Minimum sum of two elements from two arrays such that indexes are not same

Last Updated : 12 Oct, 2023

Given two arrays a[] and b[] of same size. Task is to find minimum sum of two elements such that they belong to different arrays and are not at same index in their arrays.

Examples:

`Input : a[] = {5, 4, 13, 2, 1}        b[] = {2, 3, 4, 6, 5}Output : 3We take 1 from a[] and 2 from b[]Sum is 1 + 2 = 3.Input : a[] = {5, 4, 13, 1}        b[] = {3, 2, 6, 1}Output : 3We take 1 from a[] and 2 from b[].Note that we can't take 1 from b[]as the elements can not be at sameindex. `

A simple solution is to consider every element of a[], form its pair with all elements of b[] at indexes different from its index and compute sums. Finally return the minimum sum. Time complexity of this solution is O(n2)

An efficient solution works in O(n) time. Below are steps.

1. Find minimum elements from a[] and b[]. Let these elements be minA and minB respectively.
2. If indexes of minA and minB are not same, return minA + minB.
3. Else find second minimum elements from two arrays. Let these elements be minA2 and minB2. Return min(minA + minB2, minA2 + minB)

Below is the implementation of above idea:

## C++

 `// C++ program to find minimum sum of two` `// elements chosen from two arrays such that` `// they are not at same index.` `#include ` `using` `namespace` `std;`   `// Function which returns minimum sum of two` `// array elements such that their indexes are` `// not same` `int` `minSum(``int` `a[], ``int` `b[], ``int` `n)` `{` `    ``// Finding minimum element in array A and` `    ``// also/ storing its index value.` `    ``int` `minA = a[0], indexA;` `    ``for` `(``int` `i=1; i

## Java

 `// Java program to find minimum sum of two` `// elements chosen from two arrays such that` `// they are not at same index.`   `class` `Minimum{`   `    ``// Function which returns minimum sum of two` `    ``// array elements such that their indexes are` `    ``// not same` `    ``public` `static` `int` `minSum(``int` `a[], ``int` `b[], ``int` `n)` `        ``{` `           ``// Finding minimum element in array A and` `           ``// also/ storing its index value.` `           ``int` `minA = a[``0``], indexA = ``0``;` `           ``for` `(``int` `i=``1``; i

## Python3

 `# Python3 code to find minimum sum of ` `# two elements chosen from two arrays` `# such that they are not at same index.` `import` `sys`   `# Function which returns minimum sum ` `# of two array elements such that their` `# indexes arenot same` `def` `minSum(a, b, n):` `    `  `    ``# Finding minimum element in array A ` `    ``# and also storing its index value.` `    ``minA ``=` `a[``0``]` `    ``indexA ``=` `0` `    ``for` `i ``in` `range``(``1``,n):` `        ``if` `a[i] < minA:` `            ``minA ``=` `a[i]` `            ``indexA ``=` `i` `            `  `    ``# Finding minimum element in array B` `    ``# and also storing its index value` `    ``minB ``=` `b[``0``]` `    ``indexB ``=` `0` `    ``for` `i ``in` `range``(``1``, n):` `        ``if` `b[i] < minB:` `            ``minB ``=` `b[i]` `            ``indexB ``=` `i` `            `  `    ``# If indexes of minimum elements ` `    ``# are not same, return their sum.` `    ``if` `indexA !``=` `indexB:` `        ``return` `(minA ``+` `minB)` `    `  `    ``# When index of A is not same as ` `    ``# previous and value is also less ` `    ``# than other minimum. Store new ` `    ``# minimum and store its index` `    ``minA2 ``=` `sys.maxsize` `    ``indexA2``=``0` `    ``for` `i ``in` `range``(n):` `        ``if` `i !``=` `indexA ``and` `a[i] < minA2:` `            ``minA2 ``=` `a[i]` `            ``indexA2 ``=` `i` `            `  `    ``# When index of B is not same as ` `    ``# previous and value is also less ` `    ``# than other minimum. Store new ` `    ``# minimum and store its index` `    ``minB2 ``=` `sys.maxsize` `    ``indexB2 ``=` `0` `    ``for` `i ``in` `range``(n):` `        ``if` `i !``=` `indexB ``and` `b[i] < minB2:` `            ``minB2 ``=` `b[i]` `            ``indexB2 ``=` `i` `    `  `    ``# Taking sum of previous minimum of ` `    ``# a[] with new minimum of b[]` `    ``# and also sum of previous minimum ` `    ``# of b[] with new minimum of a[] ` `    ``# and return whichever is minimum.` `    ``return` `min``(minB ``+` `minA2, minA ``+` `minB2)` `    `  `# Driver code` `a ``=` `[``5``, ``4``, ``3``, ``8``, ``1``]` `b ``=` `[``2``, ``3``, ``4``, ``2``, ``1``]` `n ``=` `len``(a)` `print``(minSum(a, b, n))`   `# This code is contributed by "Sharad_Bhardwaj".`

## C#

 `// C# program to find minimum sum of` `// two elements chosen from two arrays` `// such that they are not at same index.` `using` `System;` `        `  `public` `class` `GFG {` `    `  `    ``// Function which returns minimum` `    ``// sum of two array elements such ` `    ``// that their indexes are not same` `    ``static` `int` `minSum(``int` `[]a, ``int` `[]b,` `                                  ``int` `n)` `    ``{` `        `  `        ``// Finding minimum element in` `        ``// array A and also/ storing its` `        ``// index value.` `        ``int` `minA = a[0], indexA = 0;` `        `  `        ``for` `(``int` `i = 1; i < n; i++)` `        ``{` `            ``if` `(a[i] < minA)` `            ``{` `                ``minA = a[i];` `                ``indexA = i;` `            ``}` `        ``}`   `        ``// Finding minimum element in ` `        ``// array B and also storing its` `        ``// index value` `        ``int` `minB = b[0], indexB = 0;` `        `  `        ``for` `(``int` `i = 1; i < n; i++)` `        ``{` `            ``if` `(b[i] < minB)` `            ``{` `                ``minB = b[i];` `                ``indexB = i;` `            ``}` `        ``}`   `        ``// If indexes of minimum elements` `        ``// are not same, return their sum.` `        ``if` `(indexA != indexB)` `            ``return` `(minA + minB);` `            `  `        ``// When index of A is not same as` `        ``// previous and value is also less` `        ``// than other minimum Store new` `        ``// minimum and store its index` `        ``int` `minA2 = ``int``.MaxValue;` `        `  `        ``for` `(``int` `i=0; i

## Javascript

 ``

## PHP

 ``

Output

```3

```

Time Complexity : O(n)
Auxiliary Space : O(1)

New approach:- Here , Another approach to solve this problem is by using sorting. We can sort both arrays in non-decreasing order and then find the minimum sum by taking the sum of the first two elements of the sorted arrays.

Algorithm:

1. Define a function minSum which takes input arrays a, b and their length n as arguments.
2. Sort both arrays a and b in non-decreasing order using the Arrays.sort method.
3. Initialize a variable minSum to Integer.MAX_VALUE.
4. Initialize two variables i and j to 0.
5. Use a while loop to iterate over the arrays a and b until either i or j is less than n.
6. Check if the indexes of the current elements being compared are not the same, calculate their sum and if it is less than the current minSum, update the minSum.
7. If the element in a at index i is less than the element in b at index j, increment i by 1. Otherwise, increment j by 1.
8. Return the minimum sum calculated in step 3.
9. In the main method, define two arrays a and b, set their values and their length n.
10. Call the minSum function with arrays a, b and n as arguments and print the result.

Here is the implementation of this approach:-

## C++

 `#include ` `#include ` `#include ` `using` `namespace` `std;`   `int` `minSum(vector<``int``>& a, vector<``int``>& b, ``int` `n) {` `    ``// Sort both arrays in non-decreasing order` `    ``sort(a.begin(), a.end());` `    ``sort(b.begin(), b.end());`   `    ``// Initialize the minimum sum` `    ``int` `minSum = INT_MAX;`   `    ``// Iterate over the arrays and find the minimum sum` `    ``int` `i = 0, j = 0;` `    ``while` `(i < n && j < n) {` `        ``if` `(i != j) {` `            ``int` `sum = a[i] + b[j];` `            ``if` `(sum < minSum) {` `                ``minSum = sum;` `            ``}` `        ``}` `        ``if` `(a[i] < b[j]) {` `            ``i++;` `        ``} ``else` `{` `            ``j++;` `        ``}` `    ``}`   `    ``// Return the minimum sum` `    ``return` `minSum;` `}`   `int` `main() {` `    ``vector<``int``> a = {5, 4, 3, 8, 1};` `    ``vector<``int``> b = {2, 3, 4, 2, 1};` `    ``int` `n = 5;` `    ``cout << minSum(a, b, n) << endl;` `    ``return` `0;` `}`

## Java

 `import` `java.util.Arrays;`   `class` `Minimum {` `    `  `    ``public` `static` `int` `minSum(``int` `a[], ``int` `b[], ``int` `n) {` `        ``// Sort both arrays in non-decreasing order` `        ``Arrays.sort(a);` `        ``Arrays.sort(b);` `        `  `        ``// Initialize the minimum sum` `        ``int` `minSum = Integer.MAX_VALUE;` `        `  `        ``// Iterate over the arrays and find the minimum sum` `        ``int` `i = ``0``, j = ``0``;` `        ``while` `(i < n && j < n) {` `            ``if` `(i != j) {` `                ``int` `sum = a[i] + b[j];` `                ``if` `(sum < minSum) {` `                    ``minSum = sum;` `                ``}` `            ``}` `            ``if` `(a[i] < b[j]) {` `                ``i++;` `            ``} ``else` `{` `                ``j++;` `            ``}` `        ``}` `        `  `        ``// Return the minimum sum` `        ``return` `minSum;` `    ``}` `    `  `    ``public` `static` `void` `main(String[] args) {` `        ``int` `a[] = {``5``, ``4``, ``3``, ``8``, ``1``};` `        ``int` `b[] = {``2``, ``3``, ``4``, ``2``, ``1``};` `        ``int` `n = ``5``;` `        ``System.out.print(minSum(a, b, n));` `    ``}` `}`

## Python

 `def` `minSum(a, b, n):` `    ``# Sort both arrays in non-decreasing order` `    ``a.sort()` `    ``b.sort()`   `    ``# Initialize the minimum sum` `    ``minSum ``=` `float``(``'inf'``)`   `    ``# Iterate over the arrays and find the minimum sum` `    ``i, j ``=` `0``, ``0` `    ``while` `i < n ``and` `j < n:` `        ``if` `i !``=` `j:` `            ``sum_val ``=` `a[i] ``+` `b[j]` `            ``if` `sum_val < minSum:` `                ``minSum ``=` `sum_val` `        ``if` `a[i] < b[j]:` `            ``i ``+``=` `1` `        ``else``:` `            ``j ``+``=` `1`   `    ``# Return the minimum sum` `    ``return` `minSum`     `a ``=` `[``5``, ``4``, ``3``, ``8``, ``1``]` `b ``=` `[``2``, ``3``, ``4``, ``2``, ``1``]` `n ``=` `5` `print``(minSum(a, b, n))`

## C#

 `using` `System;` `using` `System.Collections.Generic;` `using` `System.Linq;`   `class` `Program {` `    ``// Function to find the minimum sum of elements from two` `    ``// sorted arrays` `    ``static` `int` `MinSum(List<``int``> a, List<``int``> b, ``int` `n)` `    ``{` `        ``// Sort both arrays in non-decreasing order` `        ``a.Sort();` `        ``b.Sort();`   `        ``// Initialize the minimum sum` `        ``int` `minSum = ``int``.MaxValue;`   `        ``// Iterate over the arrays and find the minimum sum` `        ``int` `i = 0, j = 0;` `        ``while` `(i < n && j < n) {` `            ``if` `(i != j) {` `                ``int` `sum = a[i] + b[j];` `                ``if` `(sum < minSum) {` `                    ``minSum = sum;` `                ``}` `            ``}` `            ``if` `(a[i] < b[j]) {` `                ``i++;` `            ``}` `            ``else` `{` `                ``j++;` `            ``}` `        ``}`   `        ``// Return the minimum sum` `        ``return` `minSum;` `    ``}`   `    ``static` `void` `Main(``string``[] args)` `    ``{` `        ``List<``int``> a = ``new` `List<``int``>{ 5, 4, 3, 8, 1 };` `        ``List<``int``> b = ``new` `List<``int``>{ 2, 3, 4, 2, 1 };` `        ``int` `n = 5;` `        ``Console.WriteLine(MinSum(a, b, n));` `    ``}` `}`

## Javascript

 `function` `minSum(a, b, n) {` `    ``// Sort both arrays in non-decreasing order` `    ``a.sort((x, y) => x - y);` `    ``b.sort((x, y) => x - y);`   `    ``// Initialize the minimum sum` `    ``let minSum = Number.MAX_SAFE_INTEGER;`   `    ``// Iterate over the arrays and find the minimum sum` `    ``let i = 0, j = 0;` `    ``while` `(i < n && j < n) {` `        ``if` `(i !== j) {` `            ``const sum = a[i] + b[j];` `            ``if` `(sum < minSum) {` `                ``minSum = sum;` `            ``}` `        ``}` `        ``if` `(a[i] < b[j]) {` `            ``i++;` `        ``} ``else` `{` `            ``j++;` `        ``}` `    ``}`   `    ``// Return the minimum sum` `    ``return` `minSum;` `}`   `// Driver code` `const a = [5, 4, 3, 8, 1];` `const b = [2, 3, 4, 2, 1];` `const n = 5;` `console.log(minSum(a, b, n));`

Output:-

`3`

Time Complexity:- The time complexity of this approach is O(n log n), dominated by the sorting of the arrays using Arrays.sort() which takes O(n log n) time complexity. The while loop then iterates over both arrays once, which takes O(n) time complexity. Therefore, the overall time complexity is O(n log n).

Auxiliary space:- The auxiliary space complexity is O(1) as we are not using any additional data structures to solve the problem, only some variables to store the minimum sum and the current indices of the arrays.

Previous
Next