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 Codeint 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 approachimport 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 approachfrom 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 Codeif __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 approachusing 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 Codestatic 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 |
Yes
Time Complexity: O(N*log N) where N is the length of the given array.
Auxiliary Space: O(N)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
Recommended Posts:
- Count permutations of given array that generates the same Binary Search Tree (BST)
- Minimum length of substring whose rotation generates a palindromic substring
- Check if any permutation of N equals any power of K
- Check if any permutation of a number without any leading zeros is a power of 2 or not
- Longest palindromic String formed using concatenation of given strings in any order
- Check if K can be obtained by performing arithmetic operations on any permutation of an Array
- Check if any permutation of array contains sum of every adjacent pair not divisible by 3
- Check if there exists a permutation of given string which doesn't contain any monotonous substring
- Minimum number of given operations required to convert a permutation into an identity permutation
- Minimum number of adjacent swaps required to convert a permutation to another permutation by given condition
- Check if any permutation of a large number is divisible by 8
- Maximize minimum distance between repetitions from any permutation of the given Array
- Maximize modulus by replacing adjacent pairs with their modulus for any permutation of given Array
- Maximize Bitwise AND of first element with complement of remaining elements for any permutation of given Array
- Check if given string is a substring of string formed by repeated concatenation of z to a
- Check if a string is concatenation of another given string
- Count array elements that can be maximized by adding any permutation of first N natural numbers
- Minimum cost to generate any permutation of the given string
- Check if a Sequence is a concatenation of two permutations
- Check if the concatenation of first N natural numbers is divisible by 3
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.
Improved By : akhilsaini

