#1764
Form Array by Concatenating Subarrays of Another Array
MediumArrayTwo PointersGreedyString MatchingTwo PointersArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
We can use a single pass through `nums` while checking for each group. By using a pointer to track our position in `nums`, we can efficiently find and validate each group without unnecessary checks.
⚙️
Algorithm
6 steps- 1Step 1: Initialize a pointer `i` to 0 to track the current position in `nums`.
- 2Step 2: Iterate through each group in `groups`.
- 3Step 3: For each group, check if the subarray in `nums` starting from `i` matches the group.
- 4Step 4: If it matches, increment `i` by the length of the group to move the pointer forward.
- 5Step 5: If a match is not found, return false immediately.
- 6Step 6: If all groups are matched successfully, return true.
solution.py8 lines
1def canFormArray(groups, nums):
2 i = 0
3 for group in groups:
4 group_len = len(group)
5 if nums[i:i + group_len] != group:
6 return False
7 i += group_len
8 return Trueℹ
Complexity note: The time complexity is O(n) because we only make a single pass through `nums`, checking each group in constant time relative to its size.
- 1The order of groups matters, so we must ensure each group is checked sequentially.
- 2Disjoint subarrays mean that once we use elements from `nums`, they cannot be reused for subsequent groups.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.