Fundamentals 9 min read

Can You Reconstruct an Array from Pieces? LeetCode 1640 Solution Explained

The article reflects on the challenges of choosing college majors and then provides a comprehensive solution to LeetCode problem 1640, detailing the problem statement, examples, and multiple language implementations using sorting, binary search, and hash‑table techniques.

IT Services Circle
IT Services Circle
IT Services Circle
Can You Reconstruct an Array from Pieces? LeetCode 1640 Solution Explained

Volunteer Reflections

Every year during the college entrance exam volunteer period, many "regret posts" appear. Older netizens, before the era of "Zhang Xuefeng", often chose schools or majors based on reputation or parental experience, lacking personal insight. A 985 graduate shared on XHS how a poor understanding of the volunteer process led to selecting an unwanted major, resulting in a vague university experience, difficult internships, and a stressful job search, ultimately ending up in an over‑working job with health issues.

The post resonated widely, highlighting how the nature of competition has shifted from information gaps to career planning, especially with AI development and the rise of consulting agencies.

Problem Description

Platform: LeetCode

Problem 1640: Given an integer array arr with distinct elements and an array pieces of integer arrays (also with distinct elements), determine if you can concatenate the arrays in pieces in any order to form arr. You cannot reorder the integers within each pieces[i]. Return true if possible, otherwise false.

Example 1:

Input: arr = [15,88], pieces = [[88],[15]]
Output: true
Explanation: Concatenate [15] and [88] in order.

Example 2:

Input: arr = [49,18,16], pieces = [[16,18,49]]
Output: false
Explanation: Even though the numbers match, you cannot reorder pieces[0].

Example 3:

Input: arr = [91,4,64,78], pieces = [[78],[4,64],[91]]
Output: true
Explanation: Concatenate [91], [4,64] and [78] in order.

Constraints: The sum of lengths of pieces[i] equals arr.length; all integers in arr are distinct; all integers in pieces are distinct when flattened.

Sorting + Binary Search Approach

This method sorts pieces by their first element, then for each element in arr uses binary search to locate the matching piece and checks consecutive elements. If any mismatch occurs, it returns false; otherwise it proceeds.

class Solution {
    public boolean canFormArray(int[] arr, int[][] pieces) {
        int n = arr.length, m = pieces.length;
        Arrays.sort(pieces, (a,b)->a[0]-b[0]);
        for (int i = 0; i < n; ) {
            int l = 0, r = m - 1;
            while (l < r) {
                int mid = l + r + 1 >> 1;
                if (pieces[mid][0] <= arr[i]) l = mid; else r = mid - 1;
            }
            int len = pieces[r].length, idx = 0;
            while (idx < len && pieces[r][idx] == arr[i + idx]) idx++;
            if (idx == len) i += len; else return false;
        }
        return true;
    }
}

Time complexity: sorting plus binary search; space complexity: O(1) extra.

Hash Table Approach

Because all elements are distinct, we can build a hash map from the first element of each piece to its index, then iterate through arr and directly compare with the corresponding piece.

class Solution {
    public boolean canFormArray(int[] arr, int[][] pieces) {
        int n = arr.length, m = pieces.length;
        int[] hash = new int[110];
        for (int i = 0; i < m; i++) hash[pieces[i][0]] = i;
        for (int i = 0; i < n; ) {
            int[] cur = pieces[hash[arr[i]]];
            int len = cur.length, idx = 0;
            while (idx < len && cur[idx] == arr[i + idx]) idx++;
            if (idx == len) i += len; else return false;
        }
        return true;
    }
}

Similar implementations are provided in C++, Python, and TypeScript, following the same logic.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

algorithmLeetCodeBinary Searchhash tableSortingarray reconstruction
IT Services Circle
Written by

IT Services Circle

Delivering cutting-edge internet insights and practical learning resources. We're a passionate and principled IT media platform.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.