Count Iterations of Consecutive Loops
Solve this ProblemEasy5 min
Topics
BasicsComplexity
Companies
TCSInfosysWipro
A function runs three loops one after another: one over
n, one over m, and another over n. Given n and m, return the total number of loop passes.
When loops are sequentialSequential CodeStatements or loops that run one after another, not inside each other., their work adds up: n + m + n = 2n + m, which is O(n + m). Contrast this with nested loops, where counts multiply. Telling "one after another" from "one inside another" is most of the skill in reading complexity from code.
Test Case 1:
Input:n = 3, m = 5
Output:11
Explanation:The first loop runs 3 times, the second 5, the third 3 again: 3 + 5 + 3.
Test Case 2:
Input:n = 0, m = 4
Output:4
Explanation:The loops over n never run; only the m loop does.
Constraints
- ◆
0 ≤ n, m ≤ 1000000
Try the Dry Run
Approach & Solutions
Run All Three LoopsGood
Run the three loops one after another — n passes, then m passes, then n passes again — and count every pass. Because each loop finishes before the next starts, their counts add up: 2n + m.
Time
O(n + m)Space
O(1)Java
class Solution {
public int consecutiveLoopsCount(int n, int m) {
int count = 0;
for (int i = 0; i < n; i++) {
count++;
}
for (int j = 0; j < m; j++) {
count++;
}
for (int i = 0; i < n; i++) {
count++;
}
return count;
}
}Add the CountsOptimal
Each loop's count is known without running it: n, m and n. Add them: 2n + m. In Big-O terms the constant 2 disappears and the code is O(n + m) — both inputs matter, because either one could be the big one.
Time
O(1)Space
O(1)Java
class Solution {
public int consecutiveLoopsCount(int n, int m) {
return 2 * n + m;
}
}