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++ 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 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 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# 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 |
<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> |
Yes
Time Complexity: O(N) where N is the length of the given array.
Auxiliary Space: O(N)