Minimum sum of two elements from two arrays such that indexes are not same
Last Updated :
23 Jul, 2025
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 : 3
We 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 : 3
We take 1 from a[] and 2 from b[].
Note that we can't take 1 from b[]
as the elements can not be at same
index.
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.
- Find minimum elements from a[] and b[]. Let these elements be minA and minB respectively.
- If indexes of minA and minB are not same, return minA + minB.
- 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 <bits/stdc++.h>
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<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;
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_MAX, indexA2;
for (int i=0; i<n; i++)
{
if (i != indexA && 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
int minB2 = INT_MAX, indexB2;
for (int i=0; i<n; i++)
{
if (i != indexB && 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
int main()
{
int a[] = {5, 4, 3, 8, 1};
int b[] = {2, 3, 4, 2, 1};
int n = sizeof(a)/sizeof(a[0]);
cout << minSum(a, b, n);
return 0;
}
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<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 = Integer.MAX_VALUE, indexA2 = 0;
for (int i=0; i<n; i++)
{
if (i != indexA && 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
int minB2 = Integer.MAX_VALUE, indexB2 = 0;
for (int i=0; i<n; i++)
{
if (i != indexB && 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 Math.min(minB + minA2, minA + minB2);
}
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));
}
}
// This code is contributed by rishabh_jain
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<n; i++)
{
if (i != indexA && a[i] < minA2)
{
minA2 = a[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
int minB2 = int.MaxValue;
for (int i=0; i<n; i++)
if (i != indexB && b[i] < minB2)
minB2 = b[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 Math.Min(minB + minA2,
minA + minB2);
}
public static void Main()
{
int []a = {5, 4, 3, 8, 1};
int []b = {2, 3, 4, 2, 1};
int n = 5;
Console.Write(minSum(a, b, n));
}
}
// This code is contributed by Sam007.
JavaScript
<script>
// JavaScript program to find minimum sum of two
// elements chosen from two arrays such that
// they are not at same index.
// Function which returns minimum sum of two
// array elements such that their indexes are
// not same
function minSum(a, b, n)
{
// Finding minimum element in array A and
// also/ storing its index value.
let minA = a[0], indexA;
for (let 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
let minB = b[0], indexB;
for (let 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
let minA2 = Number.MAX_SAFE_INTEGER, indexA2;
for (let i=0; i<n; i++)
{
if (i != indexA && 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
let minB2 = Number.MAX_SAFE_INTEGER, indexB2;
for (let i=0; i<n; i++)
{
if (i != indexB && 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 Math.min(minB + minA2, minA + minB2);
}
// Driver code
let a = [5, 4, 3, 8, 1];
let b = [2, 3, 4, 2, 1];
let n = a.length;
document.write(minSum(a, b, n));
// This code is contributed by Surbhi Tyagi.
</script>
PHP
<?php
// PHP program to find minimum
// sum of two elements chosen
// from two arrays such that
// they are not at same index.
// Function which returns
// minimum sum of two array
// elements such that their
// indexes are not same
function minSum($a, $b, $n)
{
// Finding minimum element
// in array A and also
// storing its index value.
$minA = $a[0];
for ($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
$minB = $b[0];
for ($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
$minA2 = 9999999;
$indexA2 = 0;
for ($i = 0; $i < $n; $i++)
{
if ($i != $indexA &&
$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 = 999999;
$indexB2 = 0;
for ($i = 0; $i < $n; $i++)
{
if ($i != $indexB &&
$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 = array(5, 4, 3, 8, 1);
$b = array(2, 3, 4, 2, 1);
$n = count($a);
echo minSum($a, $b, $n);
// This code is contributed
// by Sam007
?>
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:
- Define a function minSum which takes input arrays a, b and their length n as arguments.
- Sort both arrays a and b in non-decreasing order using the Arrays.sort method.
- Initialize a variable minSum to Integer.MAX_VALUE.
- Initialize two variables i and j to 0.
- Use a while loop to iterate over the arrays a and b until either i or j is less than n.
- 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.
- 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.
- Return the minimum sum calculated in step 3.
- In the main method, define two arrays a and b, set their values and their length n.
- 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 <bits/stdc++.h>
#include <algorithm>
#include <vector>
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.
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem