Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

126
Vistas
What is the Big-O of this Anagram checker

This is a piece of code I wrote to check if two strings are anagrams. This is not homework, I am learning DS&A by myself.

It seems to me that the big-O should be O(N) because there are 2 separate for-loops, but the second for-loop worries me, specifically the Object.entries() call. Is the final time complexity O(N) or O(N^2) here?

function isAnagram(origStr, checkStr) {

    if (origStr.length !== checkStr.length) {
        return false;
    }

    const origFreqCounter = {};
    const checkFreqCounter = {};

    let countFreq = (str, counter) => {
        for (const c of str) {
            counter[c] = counter[c] + 1 || 1;
        }    
    };

    countFreq(origStr, origFreqCounter);
    countFreq(checkStr, checkFreqCounter);

    // Is this O(N) or O(N^2)?
    for (const [key, value] of Object.entries(origFreqCounter)) {
        if (checkFreqCounter[key] !== value) return false;
    }
    
    return true;
}

console.log(isAnagram('', '')) // true
console.log(isAnagram('aaz', 'zza')) // false
console.log(isAnagram('anagram', 'nagaram')) // true
console.log(isAnagram("rat","car")) // false)
console.log(isAnagram('awesome', 'awesom')) // false
console.log(isAnagram('amanaplanacanalpanama', 'acanalmanplanpamana')) // false
console.log(isAnagram('qwerty', 'qeywrt')) // true
console.log(isAnagram('texttwisttime', 'timetwisttext')) // true
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Yes, it's O(n).

This function iterates over the string's length, no nested loops:

let countFreq = (str, counter) => {
    for (const c of str) {
        counter[c] = counter[c] + 1 || 1;
    }    
};

That function is called twice, and not in a loop, so that's O(n).

Then the Object.entries iterates over the entries of the origFreqCounter object. The origFreqCounter object will not have more entries than the number of characters in the origStr string, so that's also O(n).

O(n) + O(n) + O(n) = O(n).

Or, to be pedantic - the algorithm depends on the size of both origStr and checkStr, which are not necessarily the same, so it'd be more proper to call it O(n + m).

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda