LeetCode 1640: Check Array Formation Through Concatenation Solution

Master LeetCode problem 1640 (Check Array Formation Through Concatenation), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

1640. Check Array Formation Through Concatenation

Problem Explanation

Explanation

To solve this problem, we need to check if it is possible to form the array arr by concatenating the arrays in pieces without reordering the integers within each array in pieces. We can achieve this by mapping each integer in arr to its corresponding piece in pieces and checking if the concatenation of these mapped pieces matches the original arr.

We can create a mapping of the first integer of each piece to the entire piece. Then, we iterate through arr, check if the integer is in our mapping, and concatenate the corresponding piece. If at any point we encounter an integer that is not in the mapping or the final concatenated array does not match arr, we return false.

Solution Code

class Solution {
    public boolean canFormArray(int[] arr, int[][] pieces) {
        Map<Integer, int[]> map = new HashMap<>();
        for (int[] piece : pieces) {
            map.put(piece[0], piece);
        }
        
        int[] result = new int[arr.length];
        int idx = 0;
        for (int num : arr) {
            if (map.containsKey(num)) {
                int[] piece = map.get(num);
                for (int i = 0; i < piece.length; i++) {
                    result[idx++] = piece[i];
                }
            } else {
                return false;
            }
        }
        
        return Arrays.equals(arr, result);
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 1640 (Check Array Formation Through Concatenation)?

This page provides optimized solutions for LeetCode problem 1640 (Check Array Formation Through Concatenation) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 1640 (Check Array Formation Through Concatenation)?

The time complexity for LeetCode 1640 (Check Array Formation Through Concatenation) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 1640 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1640 in Java, C++, or Python.

Back to LeetCode Solutions