Form Array by Concatenating Subarrays of Another Array - Problem

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

You are asked if you can choose 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 appears before the ith subarray in nums (i.e. the subarrays must be in the same order as groups).

Return true if you can do this task, and false otherwise.

Note: The subarrays are disjoint if and only if there is no index k such that nums[k] belongs to more than one subarray. A subarray is a contiguous sequence of elements within an array.

Input & Output

Example 1 — Basic Match
$ Input: groups = [[1,-1,-1],[3,-2,0]], nums = [1,-1,0,1,-1,-1,3,-2,0]
Output: true
💡 Note: Can choose subarrays [1,-1,-1] at indices 3-5 and [3,-2,0] at indices 6-8. Both groups found in order.
Example 2 — No Valid Arrangement
$ Input: groups = [[1,-1,-1],[3,-2,0]], nums = [1,-1,0,1,-1,-1,3,-2,0]
Output: false
💡 Note: Cannot find both groups as disjoint subarrays in the required order.
Example 3 — Single Group
$ Input: groups = [[1,2]], nums = [1,2,3,4]
Output: true
💡 Note: Single group [1,2] found at indices 0-1.

Constraints

  • 1 ≤ groups.length ≤ 1000
  • 1 ≤ groups[i].length ≤ 10
  • 1 ≤ nums.length ≤ 103
  • -107 ≤ nums[i], groups[i][j] ≤ 107

Visualization

Tap to expand
Form Array by Concatenating Subarrays: Check if Groups Can Be FoundGroups to find:[1,3][3,4]Target array:77133477Group [1,3]Group [3,4]Result: trueBoth groups found as disjoint subarrays in correct order
Understanding the Visualization
1
Input
Groups to find: [[1,3],[3,4]], Target array: [7,7,1,3,3,4,7,7]
2
Process
Find each group sequentially as contiguous subarrays
3
Output
Return true if all groups found in order
Key Takeaway
🎯 Key Insight: Use greedy sequential matching to find groups in order at first available positions
Asked in
Google 15 Microsoft 12 Facebook 8
32.4K Views
Medium Frequency
~25 min Avg. Time
856 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen