Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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.
Algorithm
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
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))
True
How It Works
The algorithm checks if each piece can be found as a contiguous subsequence in the original array. For each piece:
It finds the starting position of the first element
Verifies that the entire piece matches the corresponding slice in nums
Adds valid pieces to a temporary list
Finally, it checks if all elements from nums are covered by comparing the lengths of nums and temp.
Alternative Solution Using Dictionary
We can optimize the solution by using a dictionary to map starting elements to their pieces ?
def solve_optimized(nums, pieces):
# Create a dictionary mapping first element to piece
piece_map = {}
for piece in pieces:
piece_map[piece[0]] = piece
result = []
i = 0
while i < len(nums):
if nums[i] in piece_map:
piece = piece_map[nums[i]]
# Check if the piece matches at current position
if nums[i:i+len(piece)] == piece:
result.extend(piece)
i += len(piece)
else:
return False
else:
return False
return len(result) == len(nums)
nums = [5,1,12,36,2,47,6]
pieces = [[2,47,6],[12,36],[1],[5]]
print(solve_optimized(nums, pieces))
True
Conclusion
Both solutions check if pieces can be concatenated to form the original array by verifying contiguous subsequences. The dictionary approach offers better lookup performance for the starting elements of each piece.
