Check if concatenation of any permutation of given list of arrays generates the given array
Last Updated :
14 Feb, 2023
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, 3}, pieces[][] = {{1}, {4, 3}, {2}}
Output: Yes
Explanation:
Rearrange the list to {{1}, {2}, {4, 3}}.
Now, concatenating the all the arrays from the list generates the sequence {1, 2, 4, 3} which is same as the given array.
Input: arr[] = {1, 2, 4, 3}, pieces = {{1}, {2}, {3, 4}}
Output: No
Explanation:
There is no possible permutation of given list such that after concatenating the generated sequence becomes equal to the given array.
Naive Approach: The simplest approach is to traverse the given array arr[] and for each element, arr[i], check if there exists any array present in the list such that it starts from arr[i] or not. If found to be true then increment i while elements present in the array found to be equal to arr[i]. If they are not equal, print No. Repeat the above steps until i < N. After traversing the elements of the given array, print Yes.
Time Complexity: O(N2)
Auxiliary Space: O(N)
Efficient Approach: The idea is to use the concept of Hashing by storing the indices of the elements present in the given array arr[] using Map data structure. Follow the steps below to solve the problem:
- Create a Map to store the indices of the elements of the given array arr[].
- Iterate over each of the arrays present in the list and for each array, follow the steps below:
- Find the index of its first element in the array arr[] from the Map.
- Check if the obtained array is a subarray of the array arr[] or not starting from the index found before.
- If the subarray is not equal to the array found, print No.
- Otherwise, after traversing the given array, print Yes.
Below is the implementation of the above approach:
C++
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to check if it is possible
// to obtain array by concatenating
// the arrays in list pieces[]
bool check(vector<int>& arr,
vector<vector<int>>& pieces)
{
// Stores the index of element in
// the given array arr[]
unordered_map<int, int> m;
for(int i = 0; i < arr.size(); i++)
m[arr[i]] = i + 1;
// Traverse over the list pieces
for(int i = 0; i < pieces.size(); i++)
{
// If item size is 1 and
// exists in map
if (pieces[i].size() == 1 &&
m[pieces[i][0]] != 0)
{
continue;
}
// If item contains > 1 element
// then check order of element
else if (pieces[i].size() > 1 &&
m[pieces[i][0]] != 0)
{
int idx = m[pieces[i][0]] - 1;
idx++;
// If end of the array
if (idx >= arr.size())
return false;
// Check the order of elements
for(int j = 1; j < pieces[i].size(); j++)
{
// If order is same as
// the array elements
if (arr[idx] == pieces[i][j])
{
// Increment idx
idx++;
// If order breaks
if (idx >= arr.size() &&
j < pieces[i].size() - 1)
return false;
}
// Otherwise
else
{
return false;
}
}
}
// Return false if the first
// element doesn't exist in m
else
{
return false;
}
}
// Return true
return true;
}
// Driver Code
int main()
{
// Given target list
vector<int> arr = { 1, 2, 4, 3 };
// Given array of list
vector<vector<int> > pieces{ { 1 }, { 4, 3 }, { 2 } };
// Function call
if (check(arr, pieces))
{
cout << "Yes";
}
else
{
cout << "No";
}
return 0;
}
// This code is contributed by akhilsaini
Java
// Java program for the above approach
import java.util.*;
class GFG {
// Function to check if it is possible
// to obtain array by concatenating
// the arrays in list pieces[]
static boolean check(
List<Integer> arr,
ArrayList<List<Integer> > pieces)
{
// Stores the index of element in
// the given array arr[]
Map<Integer, Integer> m
= new HashMap<>();
for (int i = 0; i < arr.size(); i++)
m.put(arr.get(i), i);
// Traverse over the list pieces
for (int i = 0;
i < pieces.size(); i++) {
// If item size is 1 and
// exists in map
if (pieces.get(i).size() == 1
&& m.containsKey(
pieces.get(i).get(0))) {
continue;
}
// If item contains > 1 element
// then check order of element
else if (pieces.get(i).size() > 1
&& m.containsKey(
pieces.get(i).get(0))) {
int idx = m.get(
pieces.get(i).get(0));
idx++;
// If end of the array
if (idx >= arr.size())
return false;
// Check the order of elements
for (int j = 1;
j < pieces.get(i).size();
j++) {
// If order is same as
// the array elements
if (arr.get(idx).equals(
pieces.get(i).get(j))) {
// Increment idx
idx++;
// If order breaks
if (idx >= arr.size()
&& j < pieces.get(i).size() - 1)
return false;
}
// Otherwise
else {
return false;
}
}
}
// Return false if the first
// element doesn't exist in m
else {
return false;
}
}
// Return true
return true;
}
// Driver Code
public static void main(String[] args)
{
// Given target list
List<Integer> arr
= Arrays.asList(1, 2, 4, 3);
ArrayList<List<Integer> > pieces
= new ArrayList<>();
// Given array of list
pieces.add(Arrays.asList(1));
pieces.add(Arrays.asList(4, 3));
pieces.add(Arrays.asList(2));
// Function Call
if (check(arr, pieces)) {
System.out.println("Yes");
}
else {
System.out.println("No");
}
}
}
Python3
# Python3 program for the above approach
from array import *
# Function to check if it is possible
# to obtain array by concatenating
# the arrays in list pieces[]
def check(arr, pieces):
# Stores the index of element in
# the given array arr[]
m = {}
for i in range(0, len(arr)):
m[arr[i]] = i + 1
# Traverse over the list pieces
for i in range(0, len(pieces)):
# If item size is 1 and
# exists in map
if (len(pieces[i]) == 1 and
m[pieces[i][0]] != 0):
continue
# If item contains > 1 element
# then check order of element
elif (len(pieces[i]) > 1 and
m[pieces[i][0]] != 0):
idx = m[pieces[i][0]] - 1
idx = idx+1
# If end of the array
if idx >= len(arr):
return False
# Check the order of elements
for j in range(1, len(pieces[i])):
# If order is same as
# the array elements
if arr[idx] == pieces[i][j]:
# Increment idx
idx = idx+1
# If order breaks
if (idx >= len(arr) and
j < len(pieces[i]) - 1):
return False
# Otherwise
else:
return False
# Return false if the first
# element doesn't exist in m
else:
return False
# Return true
return True
# Driver Code
if __name__ == "__main__":
arr = [ 1, 2, 4, 3 ]
# Given array of list
pieces = [ [ 1 ], [ 4, 3 ], [ 2 ] ]
# Function call
if check(arr, pieces) == True:
print("Yes")
else:
print("No")
# This code is contributed by akhilsaini
C#
// C# program for the above approach
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
class GFG{
// Function to check if it is possible
// to obtain array by concatenating
// the arrays in list pieces[]
static bool check(List<int> arr,
List<List<int>> pieces)
{
// Stores the index of element in
// the given array arr[]
Dictionary<int,
int> m = new Dictionary<int,
int>();
for(int i = 0; i < arr.Count; i++)
m.Add(arr[i], i);
// Traverse over the list pieces
for(int i = 0; i < pieces.Count; i++)
{
// If item size is 1 and
// exists in map
if (pieces[i].Count == 1 &&
m.ContainsKey(pieces[i][0]))
{
continue;
}
// If item contains > 1 element
// then check order of element
else if (pieces[i].Count > 1 &&
m.ContainsKey(pieces[i][0]))
{
int idx = m[pieces[i][0]];
idx++;
// If end of the array
if (idx >= arr.Count)
return false;
// Check the order of elements
for(int j = 1; j < pieces[i].Count; j++)
{
// If order is same as
// the array elements
if (arr[idx] == pieces[i][j])
{
// Increment idx
idx++;
// If order breaks
if (idx >= arr.Count &&
j < pieces[i].Count - 1)
return false;
}
// Otherwise
else
{
return false;
}
}
}
// Return false if the first
// element doesn't exist in m
else
{
return false;
}
}
// Return true
return true;
}
// Driver Code
static public void Main()
{
// Given target list
List<int> arr = new List<int>(){ 1, 2, 4, 3 };
List<List<int> > pieces = new List<List<int> >();
// Given array of list
pieces.Add(new List<int>(){ 1 });
pieces.Add(new List<int>(){ 4, 3 });
pieces.Add(new List<int>(){ 2 });
// Function call
if (check(arr, pieces))
{
Console.WriteLine("Yes");
}
else
{
Console.WriteLine("No");
}
}
}
// This code is contributed by akhilsaini
JavaScript
<script>
// Javascript program for the above approach
// Function to check if it is possible
// to obtain array by concatenating
// the arrays in list pieces[]
function check(arr, pieces)
{
// Stores the index of element in
// the given array arr[]
var m = new Map();
for(var i = 0; i < arr.length; i++)
m.set(arr[i], i+1)
// Traverse over the list pieces
for(var i = 0; i < pieces.length; i++)
{
// If item size is 1 and
// exists in map
if (pieces[i].length == 1 &&
m.get(pieces[i][0]) != 0)
{
continue;
}
// If item contains > 1 element
// then check order of element
else if (pieces[i].length > 1 &&
m.get(pieces[i][0]) != 0)
{
var idx = m.get(pieces[i][0]) - 1;
idx++;
// If end of the array
if (idx >= arr.length)
return false;
// Check the order of elements
for(var j = 1; j < pieces[i].length; j++)
{
// If order is same as
// the array elements
if (arr[idx] == pieces[i][j])
{
// Increment idx
idx++;
// If order breaks
if (idx >= arr.length &&
j < pieces[i].length - 1)
return false;
}
// Otherwise
else
{
return false;
}
}
}
// Return false if the first
// element doesn't exist in m
else
{
return false;
}
}
// Return true
return true;
}
// Driver Code
// Given target list
var arr = [ 1, 2, 4, 3 ];
// Given array of list
var pieces = [ [ 1 ], [ 4, 3 ], [ 2 ] ];
// Function call
if (check(arr, pieces))
{
document.write( "Yes");
}
else
{
document.write( "No");
}
// This code is contributed by itsok.
</script>
Time Complexity: O(N) where N is the length of the given array.
Auxiliary Space: O(N)
Similar Reads
Check if an array element is concatenation of two elements from another array
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,
8 min read
Count of permutations of an Array having maximum MEXs sum of prefix arrays
Given an array arr of size N, the task is to find the number of its permutations such that the sum of MEXs of its prefix arrays is maximum. Note: MEX of a set of integers is defined as the smallest non-negative integer that does not belong to this set. Example: Input: arr[] = {1, 0, 1}Output: 2Expla
10 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 Array elements of given range form a permutation
Given an array arr[] consisting of N distinct integers and an array Q[][2] consisting of M queries of the form [L, R], the task for each query is to check if array elements over the range [L, R] forms a permutation or not. Note: A permutation is a sequence of length N containing each number from 1 t
13 min read
Check if Array elements in given range form Permutation by performing given updates
Given an array arr[] consisting of N distinct integers and a 2d array Q[][3] consisting of M queries of the 2 types whose operations are as follows: [1, P, X] update position P with X. [2, L, R] check if array elements over the range [L, R] forms a permutation or not. For each query of the second ty
15+ min read
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
Generate an Array of length N having K subarrays as permutations of their own length
Given integers N and K, the task is to generate an array of length N which contains exactly K subarrays as a permutation of 1 to X where X is the subarray length. There may exist multiple answers you may print any one of them. If no array is possible to construct then print -1. Note: A Permutation o
7 min read
Check if given permutation of 1 to N is feasible using given operations
Given an array arr[] of size N, the task to check if this array is built under following constraints: The array can only contain numbers from 1 to N.We have to build the array sequentially. It means at first we place 1 then 2 and so on upto N.If the array is empty then we can place a number at any p
9 min read
Check if the given array is same as its inverse permutation
Given an array arr[] consisting of integers in the range [1, N], the task is to determine whether the Inverse Permutation of the given array is same as the given array. An inverse permutation is a permutation obtained by inserting the position of all elements at the position equal to the respective
8 min read
Find any permutation of Binary String of given size not present in Array
Given an array arr[] of N distinct binary strings each having N characters, the task is to find any binary string having N characters such that it doesn't occur in the given array arr[]. Example: Input: arr[] = {"10", "01"}Output: 00Explanation: String "00" does not appear in array arr[]. Another va
5 min read