
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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 in 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
Advertisements