Check Array Formation Through Concatenation — LeetCode 1640 Python Solution

EasyArrayHash Table
Problem
#1640
Pattern
Hash Map
Reading time
2 min

The 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.

Example

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

Python solution

Python
class Solution:
    def canFormArray(self, arr: List[int], pieces: List[List[int]]) -> bool:
        i = 0
        while i < len(arr):
            k = 0
            while k < len(pieces) and pieces[k][0] != arr[i]:
                k += 1
            if k == len(pieces):
                return False
            j = 0
            while j < len(pieces[k]) and arr[i] == pieces[k][j]:
                i, j = i + 1, j + 1
        return True

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Hash Map

Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 1640. Check Array Formation Through Concatenation is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Hash Table.

The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1640. Check Array Formation Through Concatenation?
LeetCode 1640. Check Array Formation Through Concatenation is rated Easy on LeetCode.
What is the time complexity of LeetCode 1640. Check Array Formation Through Concatenation?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 1640. Check Array Formation Through Concatenation?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 1640. Check Array Formation Through Concatenation cover?
LeetCode 1640. Check Array Formation Through Concatenation is tagged Array and Hash Table on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview