Program to generate array by concatenating subarrays of another array in Python

This problem involves checking if we can find all subarrays from a groups list within a nums array in sequential order. Each subarray in groups must appear as a contiguous sequence in nums, and they must appear in the same order as defined in groups.

Problem Understanding

Given a 2D array groups and a 1D array nums, we need to verify if we can select disjoint subarrays from nums such that:

  • The i-th subarray equals groups[i]

  • Each subarray appears after the previous one in nums

  • All subarrays are found without overlapping

Algorithm Steps

The solution follows these steps:

  • Initialize pointer i = 0 to track current position in nums

  • For each group in groups:

    • Search for the group starting from current position i

    • If found, update i to position after the found subarray

    • If not found, return False

  • Return True if all groups are found

Example

Let's implement the solution with a complete example:

def solve(groups, nums):
    i = 0
    for grp in groups:
        found = False
        for j in range(i, len(nums)):
            if nums[j:j+len(grp)] == grp:
                i = j + len(grp)
                found = True
                break
        if not found:
            return False
    return True

# Test case 1
groups = [[2,-2,-2],[4,-3,0]]
nums = [1,-1,0,2,-2,-2,4,-3,0]
print("Test 1:", solve(groups, nums))

# Test case 2 - groups not in order
groups2 = [[4,-3,0],[2,-2,-2]]
nums2 = [1,-1,0,2,-2,-2,4,-3,0]
print("Test 2:", solve(groups2, nums2))

# Test case 3 - missing group
groups3 = [[2,-2,-2],[5,6,7]]
nums3 = [1,-1,0,2,-2,-2,4,-3,0]
print("Test 3:", solve(groups3, nums3))
Test 1: True
Test 2: False
Test 3: False

How It Works

In the first test case:

  • Group [2,-2,-2] is found at indices 3-5 in nums

  • Group [4,-3,0] is found at indices 6-8 in nums

  • Both groups appear sequentially, so the result is True

The algorithm uses slice notation nums[j:j+len(grp)] to extract subarrays and compare them directly with each group. The pointer i ensures we only search forward, maintaining the sequential order requirement.

Conclusion

This solution efficiently checks if subarrays can be concatenated in order by using a greedy approach with forward-only searching. The time complexity is O(n*m) where n is the length of nums and m is the total length of all groups.

Updated on: 2026-03-26T14:06:20+05:30

302 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements