DEV Community

Discussion on: How to Compare Arrays in JavaScript Efficiently

Collapse
 
northerncaptain profile image
NorthernCaptain • Edited

Great article but I'm wondering why 3*n complexity is the best?
Why do you use 3 loops to get the results? It seems we can do this with two loops and 2*n complexity:

function squared(arr1, arr2) {
    if (arr1.length !== arr2.length) return false

    let frequencyCounter2 = {}

    // Create frequencyCounter2
    for (let num of arr2) {
        frequencyCounter2[num] = frequencyCounter2[num] + 1 || 1
    }

    // Count values from arr1 against frequency counter of arr2
    for (let val of arr1) {
        let square = val ** 2
        if (!(square in frequencyCounter2)) return false

        // Decrease frequency counter for our value
        let counter = frequencyCounter2[square] - 1
        if (counter < 0) return false
        frequencyCounter2[square] = counter
    }

    return true
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
doabledanny profile image
Danny Adams

Yeah, your solution looks good, best case complexity is 2n.

I could've used one loop to create both frequency counter objects to reduce it down to 2n, but used two loops as I felt it was easier to see what was going on for readers. In hindsight, perhaps I should've just used the one.

Thanks for reading!