Add elements of given arrays with given constraints
Last Updated :
20 Mar, 2023
Given two integer arrays, add their elements into third array by satisfying following constraints -
- Addition should be done starting from 0th index of both arrays.
- Split the sum if it is a not a single digit number and store the digits in adjacent locations in output array.
- Output array should accommodate any remaining digits of larger input array.
Examples:
Input:
a = [9, 2, 3, 7, 9, 6]
b = [3, 1, 4, 7, 8, 7, 6, 9]
Output:
[1, 2, 3, 7, 1, 4, 1, 7, 1, 3, 6, 9]
Input:
a = [9343, 2, 3, 7, 9, 6]
b = [34, 11, 4, 7, 8, 7, 6, 99]
Output:
[9, 3, 7, 7, 1, 3, 7, 1, 4, 1, 7, 1, 3, 6, 9, 9]
Input:
a = []
b = [11, 2, 3 ]
Output:
[1, 1, 2, 3 ]
Input:
a = [9, 8, 7, 6, 5, 4, 3, 2, 1]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9]
Output:
[1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0]
Difficulty Level: Rookie
The idea is very simple. We maintain an output array and run a loop from the 0th index of both arrays. For each iteration of loop, we consider next elements in both arrays and add them. If the sum is greater than 9, we push the individual digits of the sum to output array else we push the sum itself. Finally we push the remaining elements of larger input array to output array.
Below is the implementation of above idea:
C++
// C++ program to add two arrays following given
// constraints
#include<bits/stdc++.h>
using namespace std;
// Function to push individual digits of a number
// to output vector from left to right
void split(int num, vector<int> &out)
{
vector<int> arr;
while (num)
{
arr.push_back(num%10);
num = num/10;
}
// reverse the vector arr and append it to output vector
out.insert(out.end(), arr.rbegin(), arr.rend());
}
// Function to add two arrays keeping given
// constraints
void addArrays(int arr1[], int arr2[], int m, int n)
{
// create a vector to store output
vector<int> out;
// maintain a variable to store current index in
// both arrays
int i = 0;
// loop till arr1 or arr2 runs out
while (i < m && i < n)
{
// read next elements from both arrays and
// add them
int sum = arr1[i] + arr2[i];
// if sum is single digit number
if (sum < 10)
out.push_back(sum);
else
{
// if sum is not a single digit number, push
// individual digits to output vector
split(sum, out);
}
// increment to next index
i++;
}
// push remaining elements of first input array
// (if any) to output vector
while (i < m)
split(arr1[i++], out);
// push remaining elements of second input array
// (if any) to output vector
while (i < n)
split(arr2[i++], out);
// print the output vector
for (int x : out)
cout << x << " ";
}
// Driver code
int main()
{
int arr1[] = {9343, 2, 3, 7, 9, 6};
int arr2[] = {34, 11, 4, 7, 8, 7, 6, 99};
int m = sizeof(arr1) / sizeof(arr1[0]);
int n = sizeof(arr2) / sizeof(arr2[0]);
addArrays(arr1, arr2, m, n);
return 0;
}
Java
// Java program to add two arrays following given
// constraints
import java.util.Vector;
class GFG
{
// Function to push individual digits of a number
// to output vector from left to right
static void split(int num, Vector<Integer> out)
{
Vector<Integer> arr = new Vector<>();
while (num > 0)
{
arr.add(num % 10);
num /= 10;
}
// reverse the vector arr and
// append it to output vector
for (int i = arr.size() - 1; i >= 0; i--)
out.add(arr.elementAt(i));
}
// Function to add two arrays keeping given
// constraints
static void addArrays(int[] arr1, int[] arr2,
int m, int n)
{
// create a vector to store output
Vector<Integer> out = new Vector<>();
// maintain a variable to store
// current index in both arrays
int i = 0;
// loop till arr1 or arr2 runs out
while (i < m && i < n)
{
// read next elements from both arrays
// and add them
int sum = arr1[i] + arr2[i];
// if sum is single digit number
if (sum < 10)
out.add(sum);
else
// if sum is not a single digit number,
// push individual digits to output vector
split(sum, out);
// increment to next index
i++;
}
// push remaining elements of first input array
// (if any) to output vector
while (i < m)
split(arr1[i++], out);
// push remaining elements of second input array
// (if any) to output vector
while (i < n)
split(arr2[i++], out);
// print the output vector
for (int x : out)
System.out.print(x + " ");
}
// Driver Code
public static void main(String[] args)
{
int[] arr1 = { 9343, 2, 3, 7, 9, 6 };
int[] arr2 = { 34, 11, 4, 7, 8, 7, 6, 99 };
int m = arr1.length;
int n = arr2.length;
addArrays(arr1, arr2, m, n);
}
}
// This code is contributed by
// sanjeev2552
Python3
# Python program to add two arrays
# following given constraints
# Function to push individual digits
# of a number to output list from
# left to right
def split(num, out):
arr = []
while num:
arr.append(num % 10)
num = num // 10
for i in range(len(arr) - 1, -1, -1):
out.append(arr[i])
# Function to add two arrays keeping given
# constraints
def add_arrays(arr1, arr2, m, n):
# Create a list to store output
out = []
# Maintain a variable to store
# current index in both arrays
i = 0
# Loop till arr1 or arr2 runs out
while i < m and i < n:
# Read next elements from both
# arrays and add them
sum = arr1[i] + arr2[i]
# If sum is single digit number
if sum < 10:
out.append(sum)
else:
# If sum is not a single digit
# number, push individual digits
# to output list
split(sum, out)
# Increment to next index
i += 1
# Push remaining elements of first
# input array (if any) to output list
while i < m:
split(arr1[i], out)
i += 1
# Push remaining elements of second
# input array (if any) to output list
while i < n:
split(arr2[i], out)
i += 1
# Print the output list
for x in out:
print(x, end = " ")
# Driver code
arr1 = [9343, 2, 3, 7, 9, 6]
arr2 = [34, 11, 4, 7, 8, 7, 6, 99]
m = len(arr1)
n = len(arr2)
add_arrays(arr1, arr2, m, n)
# This code is contributed by akashish__
C#
// C# program to add two arrays following given
// constraints
using System;
using System.Collections.Generic;
class GFG
{
// Function to push individual digits of a number
// to output vector from left to right
static void split(int num, List<int> outs)
{
List<int> arr = new List<int>();
while (num > 0)
{
arr.Add(num % 10);
num /= 10;
}
// reverse the vector arr and
// append it to output vector
for (int i = arr.Count - 1; i >= 0; i--)
outs.Add(arr[i]);
}
// Function to add two arrays keeping given
// constraints
static void addArrays(int[] arr1, int[] arr2,
int m, int n)
{
// create a vector to store output
List<int> outs = new List<int>();
// maintain a variable to store
// current index in both arrays
int i = 0;
// loop till arr1 or arr2 runs out
while (i < m && i < n)
{
// read next elements from both arrays
// and add them
int sum = arr1[i] + arr2[i];
// if sum is single digit number
if (sum < 10)
outs.Add(sum);
else
// if sum is not a single digit number,
// push individual digits to output vector
split(sum, outs);
// increment to next index
i++;
}
// push remaining elements of first input array
// (if any) to output vector
while (i < m)
split(arr1[i++], outs);
// push remaining elements of second input array
// (if any) to output vector
while (i < n)
split(arr2[i++], outs);
// print the output vector
foreach (int x in outs)
Console.Write(x + " ");
}
// Driver Code
public static void Main(String[] args)
{
int[] arr1 = { 9343, 2, 3, 7, 9, 6 };
int[] arr2 = { 34, 11, 4, 7, 8, 7, 6, 99 };
int m = arr1.Length;
int n = arr2.Length;
addArrays(arr1, arr2, m, n);
}
}
// This code is contributed by PrinciRaj1992
JavaScript
<script>
// Javascript program to add two arrays
// following given constraints
// Function to push individual digits
// of a number to output vector from
// left to right
function split(num, out)
{
let arr = [];
while (num)
{
arr.push(num % 10);
num = Math.floor(num / 10);
}
for(let i = arr.length - 1; i >= 0; i--)
out.push(arr[i]);
}
// Function to add two arrays keeping given
// constraints
function addArrays(arr1, arr2, m, n)
{
// Create a vector to store output
let out = [];
// Maintain a variable to store
// current index in both arrays
let i = 0;
// Loop till arr1 or arr2 runs out
while (i < m && i < n)
{
// Read next elements from both
// arrays and add them
let sum = arr1[i] + arr2[i];
// If sum is single digit number
if (sum < 10)
out.push(sum);
else
{
// If sum is not a single digit
// number, push individual digits
// to output vector
split(sum, out);
}
// Increment to next index
i++;
}
// Push remaining elements of first
// input array (if any) to output vector
while (i < m)
split(arr1[i++], out);
// Push remaining elements of second
// input array (if any) to output vector
while (i < n)
split(arr2[i++], out);
// Print the output vector
for(let x of out)
document.write(x + " ");
}
// Driver code
let arr1 = [ 9343, 2, 3, 7, 9, 6 ];
let arr2 = [ 34, 11, 4, 7, 8, 7, 6, 99 ];
let m = arr1.length;
let n = arr2.length;
addArrays(arr1, arr2, m, n);
// This code is contributed by _saurabh_jaiswal
</script>
Output9 3 7 7 1 3 7 1 4 1 7 1 3 6 9 9
Time complexity of above solution is O(m + n) as we traverses both arrays exactly once.
Method 2(using String and STL):
in this approach we will take one string named "ans". as we add the element of both arrays the resultant sum will be converted to string and this string will be appended with main string "ans".
After doing this for all elements we will take one vector and transfer the whole string to that vector and finally will print that vector.
Below is implementation of above approach:
C++
// C++ program to add two arrays
// following given constrains
#include <bits/stdc++.h>
using namespace std;
// function to add two arrays
// following given constrains
void creat_new(int arr1[], int arr2[], int n, int m)
{
string ans;
int i = 0;
while (i < min(n, m)) {
// adding the elements
int sum = arr1[i] + arr2[i];
// converting the integer to string
string s = to_string(sum);
// appending the string
ans += s;
i++;
}
// entering remaining element(if any) of
// first array
for (int j = i; j < n; j++) {
string s = to_string(arr1[j]);
ans += s;
}
// entering remaining element (if any) of
// second array
for (int j = i; j < m; j++) {
string s = to_string(arr2[j]);
ans += s;
}
// taking vector
vector<int> k;
// assigning the elements of string
// to vector
for (int i = 0; i < ans.length(); i++) {
k.push_back(ans[i] - '0');
}
// printing the elements of vector
for (int i = 0; i < k.size(); i++) {
cout << k[i] << " ";
}
}
// driver code
int main()
{
int arr1[] = { 9, 2, 3, 7, 9, 6 };
int arr2[] = { 3, 1, 4, 7, 8, 7, 6, 9 };
int n = sizeof(arr1) / sizeof(arr1[0]);
int m = sizeof(arr2) / sizeof(arr2[0]);
// function call
creat_new(arr1, arr2, n, m);
return 0;
}
// this code is contributed by Machhaliya Muhammad
Java
/*package whatever //do not write package name here */
import java.util.*;
class GFG {
// function to add two arrays
// following given constrains
static void creat_new(int arr1[], int arr2[], int n,
int m)
{
String ans = "";
int i = 0;
while (i < Math.min(n, m))
{
// adding the elements
int sum = arr1[i] + arr2[i];
// converting the integer to string
String s = sum + "";
// appending the string
ans += s;
i++;
}
// entering remaining element(if any) of
// first array
for (int j = i; j < n; j++) {
String s = arr1[j] + "";
ans += s;
}
// entering remaining element (if any) of
// second array
for (int j = i; j < m; j++) {
String s = arr2[j] + "";
ans += s;
}
// taking vector
ArrayList<Integer> k = new ArrayList<>();
// assigning the elements of string
// to vector
for (int j = 0; j < ans.length(); j++) {
k.add(ans.charAt(j) - '0');
}
// printing the elements of vector
for (int j = 0; j < k.size(); j++) {
System.out.print(k.get(j) + " ");
}
}
public static void main(String[] args)
{
int arr1[] = { 9, 2, 3, 7, 9, 6 };
int arr2[] = { 3, 1, 4, 7, 8, 7, 6, 9 };
int n = arr1.length;
int m = arr2.length;
// function call
creat_new(arr1, arr2, n, m);
}
}
// This code is contributed by aadityaburujwale.
Python3
import math
class GFG :
# function to add two arrays
# following given constrains
@staticmethod
def creat_new( arr1, arr2, n, m) :
ans = ""
i = 0
while (i < min(n,m)) :
# adding the elements
sum = arr1[i] + arr2[i]
# converting the integer to string
s = str(sum) + ""
# appending the string
ans += s
i += 1
# entering remaining element(if any) of
# first array
j = i
while (j < n) :
s = str(arr1[j]) + ""
ans += s
j += 1
# entering remaining element (if any) of
# second array
j = i
while (j < m) :
s = str(arr2[j]) + ""
ans += s
j += 1
# taking vector
k = []
# assigning the elements of string
# to vector
j = 0
while (j < len(ans)) :
k.append(ord(ans[j]) - ord('0'))
j += 1
# printing the elements of vector
j = 0
while (j < len(k)) :
print(k[j],end=' ')
j += 1
@staticmethod
def main( args) :
arr1 = [9, 2, 3, 7, 9, 6]
arr2 = [3, 1, 4, 7, 8, 7, 6, 9]
n = len(arr1)
m = len(arr2)
# function call
GFG.creat_new(arr1, arr2, n, m)
if __name__=="__main__":
GFG.main([])
# This code is contributed by aadityaburujwale.
C#
// Include namespace system
using System;
using System.Collections.Generic;
public class GFG
{
// function to add two arrays
// following given constrains
public static void creat_new(int[] arr1, int[] arr2, int n, int m)
{
var ans = "";
var i = 0;
while (i < Math.Min(n,m))
{
// adding the elements
var sum = arr1[i] + arr2[i];
// converting the integer to string
var s = sum.ToString() + "";
// appending the string
ans += s;
i++;
}
// entering remaining element(if any) of
// first array
for (int j = i; j < n; j++)
{
var s = arr1[j].ToString() + "";
ans += s;
}
// entering remaining element (if any) of
// second array
for (int j = i; j < m; j++)
{
var s = arr2[j].ToString() + "";
ans += s;
}
// taking vector
var k = new List<int>();
// assigning the elements of string
// to vector
for (int j = 0; j < ans.Length; j++)
{
k.Add((int)(ans[j]) - (int)('0'));
}
// printing the elements of vector
for (int j = 0; j < k.Count; j++)
{
Console.Write(k[j] + " ");
}
}
public static void Main(String[] args)
{
int[] arr1 = {9, 2, 3, 7, 9, 6};
int[] arr2 = {3, 1, 4, 7, 8, 7, 6, 9};
var n = arr1.Length;
var m = arr2.Length;
// function call
GFG.creat_new(arr1, arr2, n, m);
}
}
// This code is contributed by aadityaburujwale.
JavaScript
// JavaScript Code
// function to add two arrays
// following given constrains
const creat_new = (arr1, arr2, n, m) => {
let ans = "";
let i = 0;
while (i < Math.min(n, m))
{
// adding the elements
let sum = arr1[i] + arr2[i];
// converting the integer to string
let s = sum.toString();
// appending the string
ans += s;
i++;
}
// entering remaining element(if any) of
// first array
for (let j = i; j < n; j++) {
let s = arr1[j].toString();
ans += s;
}
// entering remaining element (if any) of
// second array
for (let j = i; j < m; j++) {
let s = arr2[j].toString();
ans += s;
}
// taking vector
let k = [];
// assigning the elements of string
// to vector
for (let i = 0; i < ans.length; i++) {
k.push(parseInt(ans[i]));
}
// printing the elements of vector
console.log(k);
}
// Driver code
let arr1 = [9, 2, 3, 7, 9, 6];
let arr2 = [3, 1, 4, 7, 8, 7, 6, 9];
let n = arr1.length;
let m = arr2.length;
// function call
creat_new(arr1, arr2, n, m);
// This code is contributed by akashish__
Output1 2 3 7 1 4 1 7 1 3 6 9
Time Complexity: O(max(m,n))
Auxiliary Space:O(m+n), since vector k(of size m+n in worst case) is being created.
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