🧠 Can You Form the Array? Use This Simple Map Trick to Solve It Instantly!
IntuitionWe want to check if we can form arr by concatenating subarrays from pieces in any order, while preserving the internal order of elements in each piece.


### Intuition
![image.png](https://assets.leetcode.com/users/images/024b8700-2bf1-4525-8a9f-b0b68c0ff55c_1743581534.9804287.png)

We want to check if we can form `arr` by concatenating subarrays from `pieces` in any order, while preserving the **internal order** of elements in each piece.

---

### Approach
![image.png](https://assets.leetcode.com/users/images/cb4b8cef-bfcf-420d-971d-ffce77c8a068_1743581539.8903265.png)

1. Build a hash map where the key is the first number of each piece, and the value is the piece itself.
2. Traverse through `arr`, and at each index:
   - Check if `arr[i]` is the start of any piece.
   - If yes, match the full piece against the next elements in `arr`.
   - If any mismatch happens — return `false`.
3. If everything matches perfectly — return `true`.

This greedy matching uses constant-time lookup for pieces.

---

### Complexity

**Time Complexity:**  
- ( O(n) ) — one pass through `arr`, each `piece` used once

**Space Complexity:**  
- ( O(p) ) — `p = number of pieces` stored in hash map

---

### Code

```python []
class Solution(object):
    def canFormArray(self, arr, pieces):
        m = {p[0]: p for p in pieces}
        i = 0
        while i < len(arr):
            if arr[i] not in m:
                return False
            p = m[arr[i]]
            for num in p:
                if i >= len(arr) or arr[i] != num:
                    return False
                i += 1
        return True
```

```javascript []
function canFormArray(arr, pieces) {
  const m = new Map();
  for (const p of pieces) m.set(p[0], p);
  for (let i = 0; i < arr.length;) {
    const p = m.get(arr[i]);
    if (!p) return false;
    for (let j = 0; j < p.length; j++) {
      if (arr[i + j] !== p[j]) return false;
    }
    i += p.length;
  }
  return true;
}
```

<img src="https://assets.leetcode.com/users/images/b91de711-43d7-4838-aabe-07852c019a4d_1743313174.0180438.webp" width="270"/>

['Array', 'Hash Table', 'Python', 'JavaScript']