Problem Statement :
Write a function called matchSquare, which accept two arrays (arr1, arr2)
Write a function called matchSquare, which accept two arrays (arr1, arr2)
Criteria:
- The function should return true, if every value in the arr1, has its corresponding values squared in the second array arr2
- The frequency of the values must be the same.
Ex:
matchSquare([1,2,3], [4,1,9]) //true matchSquare([1,2,3], [1,9]) //false, frequency and length issue matchSquare([1,2,1], [4,4,1]) //false (Must have the same frequency), //because in the arry2, there is 2 4's, which does not have a matching another 2 in the arr1,
Criteria My solution (brute force):
- The function should return true, if every value in the arr1, has its corresponding values squared in the second array arr2
- The Frequency of the values must be the same.
Ex:
matchSquare([1,2,3], [4,1,9]) //true
matchSquare([1,2,3], [1,9]) //false, frequency and length issue
matchSquare([1,2,1], [4,4,1]) //false (Must have the same frequency),
//because in the arry2, there is 2 4's, which does not have a matching another 2 in the arr1,
My Solution (Brute force):
function matchSquare(arr1, arr2){
if(arr1.length !== arr2.length){
return false;
}
for(let i = 0; i < arr1.length; i++){ // This is O(n)
let correctIndex = arr2.indexOf(arr1[i] ** 2) // This is O(n)
if(correctIndex === -1) {
return false;
}
arr2.splice(correctIndex,1) //Here again after splice, the re-index of the arr2,O(n)
}
return true;
}
Together it is O(n^2),
Can we get any better approach here, and also Please help me with a?
An explanation if possible would be helpful.