
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Program to generate array by concatenating subarrays of another array in Python
Suppose we have one 2D array called groups, and another array nums. We have to check whether we can select n disjoint subarrays from the array nums such that the ith subarray is equal to groups[i] (0-indexed), and if i > 0, the (i-1)th subarray will appear before the ith subarray in nums.
So, if the input is like groups = [[2,-2,-2],[4,-3,0]] nums = [1,-1,0,2,-2,-2,4,-3,0], then the output will be true because array group[0] is present from index 3 to 5 of nums and group[1] is from index 6 to 8 in nums.
To solve this, we will follow these steps −
i := 0
for each grp in groups, do
for j in range i to size of nums - 1, do
if subarray of nums[from index j to j+ size of grp] is same as grp, then
i := j + size of grp
come out from the loop
otherwise,
return False
return True
Example
Let us see the following implementation to get better understanding −
def solve(groups, nums): i = 0 for grp in groups: for j in range(i, len(nums)): if nums[j:j+len(grp)] == grp: i = j + len(grp) break else: return False return True groups = [[2,-2,-2],[4,-3,0]] nums = [1,-1,0,2,-2,-2,4,-3,0] print(solve(groups, nums))
Input
[[2,-2,-2],[4,-3,0]], [1,-1,0,2,-2,-2,4,-3,0]
Output
True
- Related Articles
- Program to find expected sum of subarrays of a given array by performing some operations in Python
- Python program to copy all elements of one array into another array
- Program to find number of ways to split array into three subarrays in Python
- Convert array into array of subarrays - JavaScript
- Program to find minimum number of increments on subarrays to form a target array in Python
- Program to find modulus of a number by concatenating n times in Python
- Golang Program To Push An Array Into Another Array
- C++ Program to push an array into another array
- Maximum number by concatenating every element in a rotation of an array in C++
- Swift Program to Copy All the Elements of One Array to Another Array
- Golang Program To Copy All The Elements Of One Array To Another Array
- C++ Program to Copy All the Elements of One Array to Another Array
- Program to sort array by increasing frequency of elements in Python
- Sort an array according to the order defined by another array in C++
- 8086 program to determine modulus of first array elements corresponding to another array elements\n
