Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

231
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!