LeetCode 1640: Check Array Formation Through Concatenation

ArrayHash Table

LeetCode 1640 Solution 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.

LeetCode 1640 Solutions in Java, C++, Python

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);
    }
}

Interactive Code Editor for LeetCode 1640

Improve Your LeetCode 1640 Solution

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

  • Add import statements 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.

Loading editor...

Related LeetCode Problems