- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Program to check we can form array from pieces or not in Python
Suppose we have an array nums where all elements are unique and have another array with different smaller arrays called pieces. We have to check whether we can get the main array nums by concatenating the arrays in pieces in any order or not. But we are not allowed to reorder the elements present in each array pieces[i].
So, if the input is like nums = [5,1,12,36,2,47,6] pieces = [[2,47,6],[12,36],[1],[5]], then the output will be True because we can concatenate them in this order [[5], [1], [12,36], [2,47,6]] to get the main array.
To solve this, we will follow these steps −
temp := a new list
for each p in pieces, do
if p[0] not present in nums, then
return False
l := size of p
indx := index(p[0]) in nums
if subarray of nums from index indx to indx+l-1 is not same as p, then
return False
otherwise,
append p after temp
if size of nums is same as size of temp, then
return True
otherwise,
return False
Example (Python)
Let us see the following implementation to get better understanding −
def solve(nums, pieces): temp = [] for p in pieces: if p[0] not in nums: return False l = len(p) indx = nums.index(p[0]) if nums[indx:indx+l] != p: return False else: temp.extend(p) if len(nums) == len(temp): return True else: return False nums = [5,1,12,36,2,47,6] pieces = [[2,47,6],[12,36],[1],[5]] print(solve(nums, pieces))
Input
[5,1,12,36,2,47,6], [[2,47,6],[12,36],[1],[5]]
Output
True