Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Can form target array from source array JavaScript
We are given an array of distinct integers, let's say arr, and another array of integer arrays, let say sourceArr.
In the sourceArr array, the integers are distinct. We should write a function that forms arr by concatenating the arrays in sourceArr in any order.
However, we cannot reorder the integers inside of any subarray in the sourceArr. We should return true if it is possible to form the array arr from sourceArr, false otherwise.
For example:
const arr = [23, 67, 789]; const sourceArr = [[23], [789, 67]];
The function should return false because we cannot reorder the elements inside a subarray and without which we cannot achieve the target arr.
Algorithm Approach
The solution uses an index mapping strategy:
- Create a map where each subarray's first element points to its index in sourceArr
- Iterate through the target array and match consecutive elements with subarrays
- If any mismatch occurs or a starting element isn't found, return false
Example
const arr1 = [23, 67, 789];
const arr2 = [23, 789, 67];
const sourceArr = [[23], [789, 67]];
const validFormation = (arr, sourceArr) => {
const indexes = new Array(100);
let arrIndex = 0;
let index;
// Map first element of each subarray to its index
for (let i = 0; i
Output
false
true
How It Works
For arr1 = [23, 67, 789]:
- Finds subarray starting with 23: [23]
- Matches successfully, moves to index 1
- Looks for subarray starting with 67: not found
- Returns false
For arr2 = [23, 789, 67]:
- Finds subarray starting with 23: [23]
- Matches successfully, moves to index 1
- Finds subarray starting with 789: [789, 67]
- Both 789 and 67 match consecutively
- Returns true
Conclusion
This algorithm efficiently determines if a target array can be formed by concatenating subarrays without reordering their internal elements. The key insight is mapping subarray starting elements to their positions for quick lookup.
