Skip to content
Learn Netverks

Lesson

Step 9/36 25% through track

analyzing-loops

Analyzing loops

Last reviewed May 28, 2026 Content v20260528
Track mode
server_compiled
Means
Compiled runner
Reading
~1 min
Level
beginner

This lesson

This lesson teaches Analyzing loops: data structure and algorithm concepts with complexity analysis and interview-ready C++ examples.

Teams apply Analyzing loops in every serious DSA project—skipping it leaves blind spots in analysis and reviews.

You will apply Analyzing loops in contexts like: Interview loops, performance tuning, and foundational CS courses.

Compile and run C++17 snippets in the playground (`int main`, `std::cout`); after each run, state time and space complexity before moving on.

When you can explain the previous lesson's ideas in your own words.

Nested loops often drive complexity. Count how many times the inner body runs: independent loops add; nested loops multiply.

Patterns

  • Single loop 0..n-1 → O(n)
  • Two nested 0..n-1 → O(n²)
  • Outer n, inner halving j → O(n log n)
  • Loop i=0..n, inner j=0..i → still O(n²) (triangular)

Triangular inner loop

#include 

int main() {
    int n = 100;
    long long ops = 0;
    for (int i = 0; i < n; ++i)
        for (int j = 0; j < i; ++j)
            ++ops;
    std::cout << "ops ~ n(n-1)/2 = " << ops << "\n";
    return 0;
}

Halving pattern

While n > 0; n /= 2 runs O(log n) iterations—foundation for binary search and heap height analysis.

Important interview questions and answers

  1. Q: i and j both to n?
    A: O(n²)—classic interview trap.
  2. Q: j only to i?
    A: Still O(n²) because sum of 0..n-1 is n(n-1)/2.

Self-check

  1. What is complexity of double loop i,j from 0 to n-1?
  2. What is complexity of loop that halves n each iteration?

Pitfall: Inner loop to i still sums to O(n²)—triangular loops confuse many candidates.

Interview prep

Nested 0..n-1?

O(n²) multiplications.

Halving n loop?

O(log n) iterations.

Interview tip Lesson completion confidence

Can you explain this lesson in 30 seconds without reading notes?

Not saved yet.

Playground

Runs on the configured server runner (dev: npm run runner with LEARNING_RUNNER_ENABLED=true). Output appears below the editor.

Check yourself

Multiple choice — immediate feedback.

Discussion

Past discussion is visible to everyone. Only logged-in users can post comments and replies.

Starter discussion topics

  • Nested loops?
  • Halving loop?

Sign up or log in to post comments and sync lesson progress across devices.

No discussion yet. Be the first to ask a question.

Jump