Form Array by Concatenating Subarrays of Another Array — LeetCode 1764 Python Solution

MediumGreedyArrayTwo PointersString Matching
Problem
#1764
Reading time
2 min

The problem

You are given a 2D integer array groups of length n. You are also given an integer array nums.

Example

Input
groups = [[1,-1,-1],[3,-2,0]], nums = [1,-1,0,1,-1,-1,3,-2,0]
Output
true
Explanation
You can choose the 0th subarray as [1,-1,0,1,-1,-1,3,-2,0] and the 1st one as [1,-1,0,1,-1,-1,3,-2,0].

Python solution

Python
class Solution:
    def canChoose(self, groups: List[List[int]], nums: List[int]) -> bool:
        n, m = len(groups), len(nums)
        i = j = 0
        while i < n and j < m:
            g = groups[i]
            if g == nums[j : j + len(g)]:
                j += len(g)
                i += 1
            else:
                j += 1
        return i == n

Complexity

MeasureComplexity
TimeO(n) (after optional sort O(n log n))
SpaceO(1) auxiliary

Pattern: Two Pointers

Use the order already in the input to discard half the search space at every step. LeetCode 1764. Form Array by Concatenating Subarrays of Another Array is filed here because LeetCode tags it Two Pointers, which is the vocabulary this hub collects.

The two pointers guide has the Python template for the pattern and the 201 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1764. Form Array by Concatenating Subarrays of Another Array?
LeetCode 1764. Form Array by Concatenating Subarrays of Another Array is rated Medium on LeetCode.
What is the time complexity of LeetCode 1764. Form Array by Concatenating Subarrays of Another Array?
The Python solution on this page runs in O(n) (after optional sort O(n log n)).
What is the space complexity of LeetCode 1764. Form Array by Concatenating Subarrays of Another Array?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 1764. Form Array by Concatenating Subarrays of Another Array cover?
LeetCode 1764. Form Array by Concatenating Subarrays of Another Array is tagged Greedy, Array, Two Pointers and String Matching on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview