Count Operations

Easy~10 min

Given an integer n and a string pattern describing a loop structure, return the total number of iterations that pattern would execute.

The patterns are:

  • "single" — A single for loop from 0 to n-1: n iterations
  • "nested" — Two nested for loops, each from 0 to n-1: n² iterations
  • "half" — A loop that starts at n and halves each step until reaching 0: the number of times you can halve n before it reaches 0 (i.e., floor(log₂(n)) + 1 for n > 0, or 0 if n = 0)

This problem tests your understanding of how loop structures map to Big O complexity.

Examples

Example 1
Input: n = 5, pattern = "single"
Output: 5
Explanation: A single loop from 0 to 4 runs 5 times.
Example 2
Input: n = 4, pattern = "nested"
Output: 16
Explanation: Two nested loops: 4 * 4 = 16 iterations.
Example 3
Input: n = 8, pattern = "half"
Output: 4
Explanation: Halving: 8 → 4 → 2 → 1 = 4 steps (floor(log₂(8)) + 1 = 3 + 1 = 4).

Constraints

  • 0 <= n <= 10^9
  • pattern is one of "single", "nested", or "half"
Code
Ctrl+EnterRun|Ctrl+⇧+EnterSubmit
Output

Run your code to see results

Use Cmd+Enter to run