

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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 Questions & Answers
- Can array form consecutive sequence - JavaScript
- All Paths From Source to Target in C++
- Java Program to copy an array from the specified source array
- Accumulating array elements to form new array in JavaScript
- Find possible numbers in array that can sum to a target value JavaScript
- Program to check we can form array from pieces or not in Python
- JavaScript Array from() Method
- HTML DOM Form target property
- Split array entries to form object in JavaScript
- Build tree array from flat array in JavaScript
- Searching for target string in a strangely sorted array in JavaScript
- HTML <form> target Attribute
- Rearrange an array in maximum minimum form by JavaScript
- Trim and split string to form array in JavaScript
- Form a sequence out of an array in JavaScript
Advertisements