Skip to the code
cf.
+10 XP

#1 Count the Loop Steps

easy

A performance panel in your dev tools shows how many times the busiest line of a code snippet runs. Each snippet starts with let steps = 0 and is one of these:

  • "constant": steps++ once.
  • "linear": for (let i = 0; i < n; i++) steps++;
  • "pairs": for (let i = 0; i < n; i++) for (let j = i + 1; j < n; j++) steps++;
  • "halving": let m = n; while (m > 1) { m = Math.floor(m / 2); steps++; }
  • "loop-halving": the "halving" snippet run once for every i from 0 to n - 1.

Write countSteps(kind, n) that returns the final value of steps for that snippet. Use a formula or a quick loop, but don't run the "pairs" loops for big n.

Example 1

Input: kind = "linear", n = 5
Output: 5

The loop body runs once for each of the 5 values of i.

Example 2

Input: kind = "pairs", n = 5
Output: 10

There are 4 + 3 + 2 + 1 = 10 pairs with i < j.

Constraints

  • kind is one of "constant", "linear", "pairs", "halving", "loop-halving".
  • 0 <= n <= 100000
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).