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++
#include <bits/stdc++.h>
using namespace std;
bool check(vector< int >& arr,
vector<vector< int >>& pieces)
{
unordered_map< int , int > m;
for ( int i = 0; i < arr.size(); i++)
m[arr[i]] = i + 1;
for ( int i = 0; i < pieces.size(); i++)
{
if (pieces[i].size() == 1 &&
m[pieces[i][0]] != 0)
{
continue ;
}
else if (pieces[i].size() > 1 &&
m[pieces[i][0]] != 0)
{
int idx = m[pieces[i][0]] - 1;
idx++;
if (idx >= arr.size())
return false ;
for ( int j = 1; j < pieces[i].size(); j++)
{
if (arr[idx] == pieces[i][j])
{
idx++;
if (idx >= arr.size() &&
j < pieces[i].size() - 1)
return false ;
}
else
{
return false ;
}
}
}
else
{
return false ;
}
}
return true ;
}
int main()
{
vector< int > arr = { 1, 2, 4, 3 };
vector<vector< int > > pieces{ { 1 }, { 4, 3 }, { 2 } };
if (check(arr, pieces))
{
cout << "Yes" ;
}
else
{
cout << "No" ;
}
return 0;
}
|
Java
import java.util.*;
class GFG {
static boolean check(
List<Integer> arr,
ArrayList<List<Integer> > pieces)
{
Map<Integer, Integer> m
= new HashMap<>();
for ( int i = 0 ; i < arr.size(); i++)
m.put(arr.get(i), i);
for ( int i = 0 ;
i < pieces.size(); i++) {
if (pieces.get(i).size() == 1
&& m.containsKey(
pieces.get(i).get( 0 ))) {
continue ;
}
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 (idx >= arr.size())
return false ;
for ( int j = 1 ;
j < pieces.get(i).size();
j++) {
if (arr.get(idx).equals(
pieces.get(i).get(j))) {
idx++;
if (idx >= arr.size()
&& j < pieces.get(i).size() - 1 )
return false ;
}
else {
return false ;
}
}
}
else {
return false ;
}
}
return true ;
}
public static void main(String[] args)
{
List<Integer> arr
= Arrays.asList( 1 , 2 , 4 , 3 );
ArrayList<List<Integer> > pieces
= new ArrayList<>();
pieces.add(Arrays.asList( 1 ));
pieces.add(Arrays.asList( 4 , 3 ));
pieces.add(Arrays.asList( 2 ));
if (check(arr, pieces)) {
System.out.println( "Yes" );
}
else {
System.out.println( "No" );
}
}
}
|
Python3
from array import *
def check(arr, pieces):
m = {}
for i in range ( 0 , len (arr)):
m[arr[i]] = i + 1
for i in range ( 0 , len (pieces)):
if ( len (pieces[i]) = = 1 and
m[pieces[i][ 0 ]] ! = 0 ):
continue
elif ( len (pieces[i]) > 1 and
m[pieces[i][ 0 ]] ! = 0 ):
idx = m[pieces[i][ 0 ]] - 1
idx = idx + 1
if idx > = len (arr):
return False
for j in range ( 1 , len (pieces[i])):
if arr[idx] = = pieces[i][j]:
idx = idx + 1
if (idx > = len (arr) and
j < len (pieces[i]) - 1 ):
return False
else :
return False
else :
return False
return True
if __name__ = = "__main__" :
arr = [ 1 , 2 , 4 , 3 ]
pieces = [ [ 1 ], [ 4 , 3 ], [ 2 ] ]
if check(arr, pieces) = = True :
print ( "Yes" )
else :
print ( "No" )
|
C#
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
class GFG{
static bool check(List< int > arr,
List<List< int >> pieces)
{
Dictionary< int ,
int > m = new Dictionary< int ,
int >();
for ( int i = 0; i < arr.Count; i++)
m.Add(arr[i], i);
for ( int i = 0; i < pieces.Count; i++)
{
if (pieces[i].Count == 1 &&
m.ContainsKey(pieces[i][0]))
{
continue ;
}
else if (pieces[i].Count > 1 &&
m.ContainsKey(pieces[i][0]))
{
int idx = m[pieces[i][0]];
idx++;
if (idx >= arr.Count)
return false ;
for ( int j = 1; j < pieces[i].Count; j++)
{
if (arr[idx] == pieces[i][j])
{
idx++;
if (idx >= arr.Count &&
j < pieces[i].Count - 1)
return false ;
}
else
{
return false ;
}
}
}
else
{
return false ;
}
}
return true ;
}
static public void Main()
{
List< int > arr = new List< int >(){ 1, 2, 4, 3 };
List<List< int > > pieces = new List<List< int > >();
pieces.Add( new List< int >(){ 1 });
pieces.Add( new List< int >(){ 4, 3 });
pieces.Add( new List< int >(){ 2 });
if (check(arr, pieces))
{
Console.WriteLine( "Yes" );
}
else
{
Console.WriteLine( "No" );
}
}
}
|
Javascript
<script>
function check(arr, pieces)
{
var m = new Map();
for ( var i = 0; i < arr.length; i++)
m.set(arr[i], i+1)
for ( var i = 0; i < pieces.length; i++)
{
if (pieces[i].length == 1 &&
m.get(pieces[i][0]) != 0)
{
continue ;
}
else if (pieces[i].length > 1 &&
m.get(pieces[i][0]) != 0)
{
var idx = m.get(pieces[i][0]) - 1;
idx++;
if (idx >= arr.length)
return false ;
for ( var j = 1; j < pieces[i].length; j++)
{
if (arr[idx] == pieces[i][j])
{
idx++;
if (idx >= arr.length &&
j < pieces[i].length - 1)
return false ;
}
else
{
return false ;
}
}
}
else
{
return false ;
}
}
return true ;
}
var arr = [ 1, 2, 4, 3 ];
var pieces = [ [ 1 ], [ 4, 3 ], [ 2 ] ];
if (check(arr, pieces))
{
document.write( "Yes" );
}
else
{
document.write( "No" );
}
</script>
|
Time Complexity: O(N) where N is the length of the given array.
Auxiliary Space: O(N)