Check if an array element is concatenation of two elements from another array
Last Updated :
31 May, 2021
Given two arrays arr[] and brr[] consisting of N and M positive integers respectively, the task is to find all the elements from the array brr[] which are equal to the concatenation of any two elements from the array arr[]. If no such element exists, then print "-1".
Examples:
Input: arr[] = {2, 34, 4, 5}, brr[] = {26, 24, 345, 4, 22}
Output: 24 345 22
Explanation:
The elements from the array brr[] which are concatenation of any two elements from the array arr[] are:
- 24 is concatenation of 2 and 4.
- 345 is concatenation of 34 and 5.
- 22 is concatenation of 2 and 2.
Input: arr[] = {1, 2, 3}, brr[] = {1, 23}
Output: 23
Naive Approach: The simplest approach to solve the problem is to generate all possible pairs from the given array and check if the concatenation of pairs of elements from the array arr[] is present in the array brr[] or not. If found to be true, then print the concatenated number formed.
Time Complexity: O(M * N2)
Auxiliary Space: O(N2)
Efficient Approach: The above approach can be optimized by checking for each element in the array brr[], whether brr[i] can be divided into 2 parts left and right such that both the parts exists in the array arr[].
Consider a number, b[i] = 2365
All possible combinations of left and right are:
Left Right
2 365
23 65
236 5
Follow the steps below to solve the problem:
- Initialize a HashMap M and store all elements present in the array arr[].
- Traverse the array brr[] and perform the following steps:
- Generate all possible combinations of left and right parts, such that their concatenation results to brr[i].
- If both the left and the right parts are present in Map M in one of the above combinations, then print the value of brr[i]. Otherwise, continue to the next iteration.
Below is the implementation of the above approach:
C++
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to find elements present in
// the array b[] which are concatenation
// of any pair of elements in the array a[]
void findConcatenatedNumbers(vector<int> a,
vector<int> b)
{
// Stores if there doesn't any such
// element in the array brr[]
bool ans = true;
// Stored the size of both the arrays
int n1 = a.size();
int n2 = b.size();
// Store the presence of an element
// of array a[]
unordered_map<int, int> cnt;
// Traverse the array a[]
for (int i = 0; i < n1; i++) {
cnt[a[i]] = 1;
}
// Traverse the array b[]
for (int i = 0; i < n2; i++) {
int left = b[i];
int right = 0;
int mul = 1;
// Traverse over all possible
// concatenations of b[i]
while (left > 9) {
// Update right and left parts
right += (left % 10) * mul;
left /= 10;
mul *= 10;
// Check if both left and right
// parts are present in a[]
if (cnt[left] == 1
&& cnt[right] == 1) {
ans = false;
cout << b[i] << " ";
}
}
}
if (ans)
cout << "-1";
}
// Driver Code
int main()
{
vector<int> a = { 2, 34, 4, 5 };
vector<int> b = { 26, 24, 345, 4, 22 };
findConcatenatedNumbers(a, b);
return 0;
}
Java
// Java program for the above approach
import java.io.*;
import java.util.*;
class GFG
{
// Function to find elements present in
// the array b[] which are concatenation
// of any pair of elements in the array a[]
static void findConcatenatedNumbers(int[] a,
int[] b)
{
// Stores if there doesn't any such
// element in the array brr[]
boolean ans = true;
// Stored the size of both the arrays
int n1 = a.length;
int n2 = b.length;
// Store the presence of an element
// of array a[]
int cnt[] = new int[100000];
// Traverse the array
for (int i = 0; i < n1; i++)
{
cnt[a[i]] = 1;
}
// Traverse the array b[]
for (int i = 0; i < n2; i++) {
int left = b[i];
int right = 0;
int mul = 1;
// Traverse over all possible
// concatenations of b[i]
while (left > 9) {
// Update right and left parts
right += (left % 10) * mul;
left /= 10;
mul *= 10;
// Check if both left and right
// parts are present in a[]
if (cnt[left] == 1
&& cnt[right] == 1) {
ans = false;
System.out.print(b[i] + " ");
}
}
}
if (ans)
System.out.print("-1");
}
// Driver code
public static void main(String[] args)
{
int[] a = { 2, 34, 4, 5 };
int[] b = { 26, 24, 345, 4, 22 };
findConcatenatedNumbers(a, b);
}
}
// This code is contributed by sanjoy_62.
Python3
# Python3 program for the above approach
from collections import defaultdict
# Function to find elements present in
# the array b[] which are concatenation
# of any pair of elements in the array a[]
def findConcatenatedNumbers(a, b):
# Stores if there doesn't any such
# element in the array brr[]
ans = True
# Stored the size of both the arrays
n1 = len(a)
n2 = len(b)
# Store the presence of an element
# of array a[]
cnt = defaultdict(int)
# Traverse the array a[]
for i in range(n1):
cnt[a[i]] = 1
# Traverse the array b[]
for i in range(n2):
left = b[i]
right = 0
mul = 1
# Traverse over all possible
# concatenations of b[i]
while (left > 9):
# Update right and left parts
right += (left % 10) * mul
left //= 10
mul *= 10
# Check if both left and right
# parts are present in a[]
if (cnt[left] == 1 and cnt[right] == 1):
ans = False
print(b[i], end = " ")
if (ans):
print("-1")
# Driver Code
if __name__ == "__main__":
a = [ 2, 34, 4, 5 ]
b = [ 26, 24, 345, 4, 22 ]
findConcatenatedNumbers(a, b)
# This code is contributed by chitranayal
C#
// C# program for the above approach
using System;
class GFG
{
// Function to find elements present in
// the array b[] which are concatenation
// of any pair of elements in the array a[]
static void findConcatenatedNumbers(int[] a,
int[] b)
{
// Stores if there doesn't any such
// element in the array brr[]
bool ans = true;
// Stored the size of both the arrays
int n1 = a.Length;
int n2 = b.Length;
// Store the presence of an element
// of array a[]
int []cnt = new int[100000];
// Traverse the array
for (int i = 0; i < n1; i++)
{
cnt[a[i]] = 1;
}
// Traverse the array b[]
for (int i = 0; i < n2; i++) {
int left = b[i];
int right = 0;
int mul = 1;
// Traverse over all possible
// concatenations of b[i]
while (left > 9) {
// Update right and left parts
right += (left % 10) * mul;
left /= 10;
mul *= 10;
// Check if both left and right
// parts are present in a[]
if (cnt[left] == 1
&& cnt[right] == 1) {
ans = false;
Console.Write(b[i] + " ");
}
}
}
if (ans)
Console.Write("-1");
}
// Driver code
public static void Main(String[] args)
{
int[] a = { 2, 34, 4, 5 };
int[] b = { 26, 24, 345, 4, 22 };
findConcatenatedNumbers(a, b);
}
}
// This code is contributed by shivani
JavaScript
<script>
// JavaScript program for the above approach
// Function to find elements present in
// the array b[] which are concatenation
// of any pair of elements in the array a[]
function findConcatenatedNumbers(a, b)
{
// Stores if there doesn't any such
// element in the array brr[]
var ans = true;
// Stored the size of both the arrays
var n1 = a.length;
var n2 = b.length;
// Store the presence of an element
// of array a[]
var cnt = new Map();
// Traverse the array a[]
for (var i = 0; i < n1; i++) {
cnt.set(a[i], 1);
}
// Traverse the array b[]
for (var i = 0; i < n2; i++) {
var left = b[i];
var right = 0;
var mul = 1;
// Traverse over all possible
// concatenations of b[i]
while (left > 9) {
// Update right and left parts
right += (left % 10) * mul;
left = parseInt(left/10);
mul *= 10;
// Check if both left and right
// parts are present in a[]
if (cnt.has(left)
&& cnt.has(right)) {
ans = false;
document.write( b[i] + " ");
}
}
}
if (ans)
document.write( "-1");
}
// Driver Code
var a = [2, 34, 4, 5 ];
var b = [26, 24, 345, 4, 22 ];
findConcatenatedNumbers(a, b);
</script>
Time Complexity: O(M*log(X)), where X is the largest element in the array brr[].
Auxiliary Space: O(N)
Similar Reads
Check if each element of an Array is the Sum of any two elements of another Array Given two arrays A[] and B[] consisting of N integers, the task is to check if each element of array B[] can be formed by adding any two elements of array A[]. If it is possible, then print âYesâ. Otherwise, print âNoâ. Examples: Input: A[] = {3, 5, 1, 4, 2}, B[] = {3, 4, 5, 6, 7} Output: Yes Explan
6 min read
Check if an array can be converted to another given array by swapping pairs of unequal elements Given two arrays arr1[] and arr2[] of size N, consisting of binary integers, the task is to check if arr1[] can be converted to arr2[] by swapping any pair of array elements (arr1[i], arr1[j]) such that i < j and arr1[i] is 1 and arr1[j] is 0 (any number of times). If it is possible to do so, the
11 min read
Check if concatenation of any permutation of given list of arrays generates the given array Given an array arr[] of N distinct integers and a list of arrays pieces[] of distinct integers, the task is to check if the given list of arrays can be concatenated in any order to obtain the given array. If it is possible, then print "Yes". Otherwise, print "No". Examples: Input: arr[] = {1, 2, 4,
9 min read
Check if an array is subset of another array Given two arrays a[] and b[] of size m and n respectively, the task is to determine whether b[] is a subset of a[]. Both arrays are not sorted, and elements are distinct.Examples: Input: a[] = [11, 1, 13, 21, 3, 7], b[] = [11, 3, 7, 1] Output: trueInput: a[]= [1, 2, 3, 4, 5, 6], b = [1, 2, 4] Output
13 min read
Check if a string is concatenation of another given string Given two strings str1 and str2 of length N and M respectively, the task is to check if the string str1 can be formed by concatenating the string str2 repetitively or not. Examples: Input: str1 = âabcabcabcâ, str2 = âabcâOutput: YesExplanation: Concatenating the string str2 thrice generates the stri
7 min read
For each element in 1st array count elements less than or equal to it in 2nd array | Set 2 Given two unsorted arrays arr1[] and arr2[]. They may contain duplicates. For each element in arr1[] count elements less than or equal to it in array arr2[]. Examples: Input : arr1[] = [1, 2, 3, 4, 7, 9] arr2[] = [0, 1, 2, 1, 1, 4] Output : [4, 5, 5, 6, 6, 6] Explanation: There are 4 elements less t
13 min read
Merging elements of two different arrays alternatively in third array Given two arrays arr1[] and arr2[], we need to combine two arrays in such a way that the combined array has alternate elements of both. If one array has extra element, then these elements are appended at the end of the combined array. Input : arr1[] = {1, 2, 3, 4, 5, 6} arr2[] = {11, 22, 33, 44}Outp
7 min read
Find all concatenations of words in Array Given an array of strings arr[] (1 <= |arr[i]| <= 20) of size N (1 <= N <= 104), the task is to find all strings from the given array that are formed by the concatenation of strings in the same given array. Examples: Input: arr[]= { "geek", "geeks", "for", "geeksforgeeks", "g", "f", "g",
9 min read
Check if a Sequence is a concatenation of two permutations Given an array arr containing positive integers, the task is to check if the given array arr is a concatenation of two permutations or not. A sequence of M integers is called a permutation if it contains all integers from 1 to M exactly once. Examples: Input: arr[] = {1, 2, 5, 3, 4, 1, 1} Output: No
8 min read
Check if two unsorted arrays (with duplicates allowed) have same elements Given two unsorted arrays, check whether both arrays have the same set of elements or not. Examples: Input : A = {2, 5, 6, 8, 10, 2, 2} B = {2, 5, 5, 6, 8, 5, 6} Output : No Input : A = {2, 5, 6, 8, 2, 10, 2} B = {2, 5, 6, 8, 2, 10, 2} Output : Yes Input : A = {2, 5, 8, 6, 10, 2, 2} B = {2, 5, 6, 8,
13 min read