Physics I / Complexity and efficiency basics
Practice question · Multiple choice

Two nested loops each running nn times give O(n2)O(n^{2}). Why does the analysis not simply add the two loops?

Hints
  1. Count the total iterations for n=3n = 3 by hand.
  2. Nesting and sequencing are different structures.
Show the answer

A. Because the inner loop runs in full for EACH outer iteration

Why

Nesting multiplies, sequencing adds. Two sequential nn-loops are O(n)O(n); two nested ones are O(n2)O(n^{2}), and the code looks almost identical.

Read the lesson: Complexity and efficiency basics →

Practise Complexity and efficiency basics

The app has 8 more questions on this lesson, and keeps your place in the course. Physics I is free to start.

More questions on Complexity and efficiency basics