Check Array Formation Through Concatenation

You are given an array of distinct integers arr and an array of integer arrays pieces, where the integers in 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.

Example 1:

Input: arr = [15,88], pieces = [[88],[15]]
Output: true
Explanation: Concatenate [15] then [88]

Approach

Java


public class ArrayFormationThroughConcatenation {
    public static void main(String[] args) {
        int[] arr = { 1588 };
        int[][] pieces = { { 88 }, { 15 } };
        System.out.println(canFormArray(arr, pieces));
    }

    static boolean canFormArray(int[] arrint[][] pieces) {
        for (int i = 0; i < arr.length;) {
            int k = -1;
            for (int j = 0; j < pieces.length; j++) {
                if (pieces[j][0] == arr[i]) {
                    k = j;
                    break;
                }
            }
            if (k == -1)
                return false;
            else {
                int flag = 0;
                for (int l = 0; l < pieces[k].length; l++) {
                    if (pieces[k][l] == arr[i])
                        i++;
                    else {
                        flag = 1;
                        break;
                    }
                }
                if (flag == 1)
                    return false;
            }
        }
        return true;
    }

}

C++

#include <bits/stdc++.h>
using namespace std;

bool canFormArray(vector<int&arrvector<vector<int>> &pieces)
{
    for (int i = 0i < arr.size();)
    {
        int k = -1;
        for (int j = 0j < pieces.size(); j++)
        {
            if (pieces[j][0] == arr[i])
            {
                k = j;
                break;
            }
        }
        if (k == -1)
            return false;
        else
        {
            int flag = 0;
            for (int l = 0l < pieces[k].size(); l++)
            {
                if (pieces[k][l] == arr[i])
                    i++;
                else
                {
                    flag = 1;
                    break;
                }
            }
            if (flag == 1)
                return false;
        }
    }
    return true;
}

int main()
{
    vector<intarr = {1588};
    vector<vector<int>> pieces = {{88}, {15}};
    if (canFormArray(arrpieces))
        cout << "true";
    else
        cout << "false";
    return 0;
}


No comments:

Post a Comment