Skip to main content
Back to problems
#1640
Easy Algorithms

Check array formation through concatenation

Array Hash Table
57.3% acceptance
Feb 25, 2026
940
143
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. 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.

Solution

Rust
Time O(n)
Space O(1)
LeetCode
solution.rs
use std::collections::HashMap;

impl Solution {
  pub fn can_form_array(arr: Vec<i32>, pieces: Vec<Vec<i32>>) -> bool {
    let map: HashMap<i32, &Vec<i32>> = pieces.iter().map(|p| (p[0], p)).collect();
    let mut i = 0;
    while i < arr.len() {
      if let Some(piece) = map.get(&arr[i]) {
        if arr[i..i+piece.len()] == piece[..] {
          i += piece.len();
        } else {
          return false;
        }
      } else {
        return false;
      }
    }
    true
  }
}