- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 soureArr. 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.
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; for (let i = 0; i < sourceArr.length; ++i) { indexes[sourceArr[i][0]] = i; } while (arrIndex < arr.length) { index = indexes[arr[arrIndex]]; if (index === undefined) return false; for (let j = 0; j < sourceArr[index].length; ++j) { if (arr[arrIndex] !== sourceArr[index][j]) return false; ++arrIndex; } } return true; }; console.log(validFormation(arr1, sourceArr)); console.log(validFormation(arr2, sourceArr));
Output
This will produce the following output −
false true
- Related Articles
- Can array form consecutive sequence - JavaScript
- Find possible numbers in array that can sum to a target value JavaScript
- Java Program to copy an array from the specified source array
- All Paths From Source to Target in C++
- Accumulating array elements to form new array in JavaScript
- Searching for target string in a strangely sorted array in JavaScript
- JavaScript Array from() Method
- Program to check we can form array from pieces or not in Python
- Build tree array from flat array in JavaScript
- Split array entries to form object in JavaScript
- How can I remove a specific item from an array JavaScript?
- Remove element from array referencing spreaded array in JavaScript
- Program to find minimum number of increments on subarrays to form a target array in Python
- JavaScript Remove random item from array and then remove it from array until array is empty
- Rearrange an array in maximum minimum form by JavaScript

Advertisements