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: 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 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 INPUT groups (2D array): groups[0]: 1 -1 -1 groups[1]: 3 -2 0 nums array: 1 -1 0 1 -1 -1 3 -2 0 idx: 0 1 2 3 4 5 6 7 8 ALGORITHM STEPS 1 Initialize Start at nums index 0 Process groups in order 2 Find groups[0] Search [1,-1,-1] in nums Found at index 3! 1 -1 -1 OK 3 Find groups[1] Continue from index 6 Search [3,-2,0] 3 -2 0 OK 4 All Groups Found Disjoint and in order Return true FINAL RESULT nums with matches highlighted: 1 -1 0 1 -1 -1 3 -2 0 0 1 2 3 4 5 6 7 8 groups[0] match groups[1] match Unused elements Output: true Both groups found as disjoint subarrays in order Key Insight: Greedy approach works because we need subarrays in order. Once we find a match for groups[i], we continue searching for groups[i+1] from the next position. This ensures subarrays are disjoint and maintains the required ordering. Time: O(n * m * k) where m = groups length, k = avg group size. TutorialsPoint - Form Array by Concatenating Subarrays of Another Array | Greedy Sequential Matching
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