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

233
Vistas
How to figure out time complexity for a while loop nested in a for loop?

So I have this code here and I am just trying to understand the time and space complexity.

for time complexity I think its O(n^2) because it is going through at most n - 1 loops in the while loop and it will go through n times in the for loop so it will be O(n(n-1)) which is O(n^2) and space complexity I think its O(n) because it is linear space.

I don't know if I'm right but if I am wrong can someone correct my thinking? Thanks in advance.

    // Write your code here
    let visited = new Array(s.length).fill(false);
    let count = 0;
    for (let i = 0; i < s.length; i++) {
        let j = i + 1;
        visited[i] = true;
        while (j < s.length && s[j] === s[i] && !visited[j]) {
            visited[j] = true;
            count++;
            j++;
        }
    }
    return count; 
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

This is O(n) in time complexity, because:

while (j < s.length && s[j] === s[i] && !visited[j]) {

For this condition to be fulfilled, visited[j] needs to be false, and when it does get fulfilled, you then do

visited[j] = true;

So, that above line can only run as many times as there are items in the visited array. If the while loop runs to the end the first outer iteration (when i is 0), then it'll never run in any of the other outer iterations. If the while loop runs halfway through visited the first iteration, and through the other half the second iteration, it'll never run for the rest of the outer iterations. So, this part of the code:

    while (j < s.length && s[j] === s[i] && !visited[j]) {
        visited[j] = true;
        count++;
        j++;
    }

will never run more than visited.length times total.

The outer loop is, of course, O(n). So, you get

outer loop: O(n)
+ inner loop: O(n) when summed over all iterations of the outer loop
= O(n)
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