Simplify complexity

27 views Asked by At

I came across this questions which asks to create a function which will return true/false based on the passed array containing all the letters to make up the passed word. Each letter from array can only be used once.

Here's my attempt:

const checkArray = (word, arr) => {
    let good = true
    word.split('').forEach(letter => {
        const letterIdx = arr.findIndex(arrLetter => arrLetter === letter)
        if (letterIdx === -1) good = false

        arr.splice(letterIdx, 1)
    })

    return good
}

const word = 'goal'
const arr1 = ['g', 'o','a','l','x','a','d'] // true
const arr1 = ['g', 'r','a','l','x','a','d'] // false

With my approach, a loop inside a loop is used. Whats a better (less complexity) way of solving this issue?

0

There are 0 answers