Jerry's Blog

Recording what I learned everyday

View on GitHub


1 January 2021

LeetCode(1640) -- Check Array Formation Through Concatenation

by Jerry Zhang

Problem

You are given an array of distinct integers arr and an array of integer arrays pieces, where the integers in pieces are distinct. Your goal is to form arr by concatenating the arrays in pieces in any order. However, you are not allowed to reorder the integers in each array pieces[i].

Return true if it is possible to form the array arr from pieces. Otherwise, return false.

My Solution

class Solution {
    public boolean canFormArray(int[] arr, int[][] pieces) {
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < pieces.length; i++) {
            map.put(pieces[i][0], i);
        }
        for (int i = 0; i < arr.length; i++) {
            if (!map.containsKey(arr[i])) {
                return false;
            }
            int[] piece = pieces[map.get(arr[i])];
            i++;
            for (int j = 1; j < piece.length; j++) {
                if (arr[i] != piece[j]) {
                    return false;
                }
                i++;
            }
            i--;
        }
        return true;
    }
}

The Solution

class Solution {
public:
    bool canFormArray(vector<int>& arr, vector<vector<int>>& pieces) {
        unordered_map<int, vector<int>> map;
        for (int i = 0; i < pieces.size(); i++) {
            map[pieces[i][0]] = pieces[i];
        }
        int i = 0;
        while (i < arr.size()) {
            if (map[arr[i]].size() == 0) {
                return false;
            } else {
                vector<int> vec = map[arr[i]];
                for (int j = 0; j < vec.size(); j++) {
                    if (arr[i] == vec[j]) {
                        i++;
                    } else {
                        return false;
                    }
                }
            }
        }
        return true;
    }
};
tags: LeetCode