DSA Factory
Free Complexity lessonsComplexity · Stage 1 · Growth in practice · Step 1

Add or multiply?

Loops one after another add their work; loops inside each other multiply it. About 6 minutes.

One after the other

Say you first tidy your desk (a tasks), and then, separately, tidy your room (b tasks). The total is a + b. The second job starts only when the first one is finished.

Loops work the same way: a loop that runs a times, followed by another loop that runs b times, does a + b steps in total.

Side by side: add the two counts.
a = 3, b = 4, layout "inside": one ✓ per run of the inner body
1234
pass 1
pass 2
pass 3
then
7

If the loops ran one after the other, it'd be 3 steps then 4 steps: 3 + 4 = 7. Now put the 4-loop inside the 3-loop.

Move 1 of 4

One inside the other

If the b-loop sits inside the a-loop, the whole b-loop runs again on every pass of the a-loop. It's like repeating a full room cleaning once for each guest: a times b.

This is where slow code usually hides, so when you read code, look first for loops sitting inside loops.

Nested: multiply the two counts.
In code
if layout == "then":
    return a + b
return a * b
Quick check

A loop over 1,000 items sits inside a loop over 1,000 items. How many times does the inner body run?

  1. A1,000,000
  2. B2,000
  3. C1,000
Show the answer

1,000,000. Nested loops multiply: 1,000 × 1,000.

Your problem

Add or multiply?

One loop runs a times and another runs b times. If layout is "then", the second loop comes after the first. If layout is "inside", the second loop sits inside the first. Return how many times the loop bodies run in total (for "inside", count the inner body).

Example
a = 3, b = 4, layout = "inside" → 12

0 ≤ a, b ≤ 1,000,000 · layout is "then" or "inside" · return a long

Solve it in your browserFree account, no card. Python, C++, Java or JavaScript, with hints if you get stuck, and your progress is saved.
Sign up free to solve