#1640

Check Array Formation Through Concatenation

Easy
ArrayHash TableHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal approach uses a HashMap to store the pieces for quick look-up, allowing us to efficiently check if the current segment of `arr` matches any piece.

⚙️

Algorithm

5 steps
  1. 1Step 1: Create a HashMap to store the pieces with their first element as the key.
  2. 2Step 2: Initialize a pointer for the target array `arr`.
  3. 3Step 3: While the pointer is within bounds, check if the current element exists in the HashMap.
  4. 4Step 4: If it exists, retrieve the corresponding piece and check if it matches the next elements in `arr`. Move the pointer accordingly.
  5. 5Step 5: If any piece does not match, return false. If the pointer reaches the end of `arr`, return true.
solution.py11 lines
1def canFormArray(arr, pieces):
2    piece_map = {piece[0]: piece for piece in pieces}
3    i = 0
4    while i < len(arr):
5        if arr[i] not in piece_map:
6            return False
7        piece = piece_map[arr[i]]
8        if arr[i:i + len(piece)] != piece:
9            return False
10        i += len(piece)
11    return True

Complexity note: The time complexity is O(n) since we only traverse `arr` once and use a HashMap for constant time lookups. The space complexity is O(n) due to the storage of pieces in the HashMap.

  • 1Using a HashMap allows for efficient lookups, reducing the need for nested loops.
  • 2The problem emphasizes the importance of maintaining the order of elements within each piece.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.