Sign in to devexcode.com with google.com

To continue, google.com will share your name, email address, and profile picture with this site. See this site's privacy policy.

1764. Form Array by Concatenating Subarrays of Another Array

Explanation:

To solve this problem, we need to check if it is possible to choose n disjoint subarrays from the nums array such that they match the groups array and are in the same order as specified by groups.

We can iterate through the groups array and for each group, try to match it with a subarray in nums. We need to ensure that the subarrays are disjoint and appear in the same order as in groups.

Algorithmic Idea:

  1. Initialize a pointer j to keep track of the current position in the nums array.
  2. Iterate over each group in groups: a. Find the subarray in nums that matches the current group. b. If found, update the pointer j to the next position after the matched subarray. c. If not found, return false.
  3. Return true if all groups are successfully matched.

Time Complexity:

The time complexity of this algorithm is O(n * m), where n is the number of groups and m is the maximum length of any group.

Space Complexity:

The space complexity of this algorithm is O(1) as we are using constant extra space.

:

class Solution {
    public boolean canChoose(int[][] groups, int[] nums) {
        int j = 0;
        for (int[] group : groups) {
            int i = j;
            while (i < nums.length && !matchGroup(group, nums, i)) {
                i++;
            }
            if (i >= nums.length) {
                return false;
            }
            j = i + group.length;
        }
        return true;
    }
    
    private boolean matchGroup(int[] group, int[] nums, int start) {
        for (int i = 0; i < group.length; i++) {
            if (start + i >= nums.length || group[i] != nums[start + i]) {
                return false;
            }
        }
        return true;
    }
}

Code Editor (Testing phase)

Improve Your Solution

Use the editor below to refine the provided solution. Select a programming language and try the following:

  • Add import statement if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.