Count Loop Executions
For each query, you are given a loop pattern type and an integer limit n. Your task is to mathematically determine exactly how many times the tick() function would execute for the specified loop pattern, without actually running the loops.
The cost of an operation for a given input size n is defined by its loop pattern type:
- Type 'A': for i=1 through n, tick()
- Type 'B': for i=1 through n, for j=1 through i, tick()
- Type 'C': start i=1; while i<=n, tick() then set i=2i
- Type 'D': for i=1 through n, start j=1; while j<=n, tick() then set j=2j
All loop bounds are inclusive.
Return a list of integers representing the execution counts for each query.
Note:
- The input is given as two arrays. The ith query you need to process is represented by the loop pattern types[i] and its corresponding maximum limit n_values[i]. Your output should be an array where the ith element is the answer to the ith query.
- You must compute the counts mathematically or logically. A naive loop simulation will result in a Time Limit Exceeded error.
Example 1:
Input:
types = ['A', 'B', 'C', 'D'] n_values = [3, 3, 3, 3]
Output:
[3, 6, 2, 6]
Explanation:
- Query 1 (Type A, n=3): The loop runs for i=1, 2, 3. The count is 3.
- Query 2 (Type B, n=3): The inner loop runs 1 time for i=1, 2 times for i=2, and 3 times for i=3. Total count = 1 + 2 + 3 = 6.
- Query 3 (Type C, n=3): i starts at 1. tick() executes, i becomes 2. tick() executes, i becomes 4. The loop terminates since 4 > 3. The count is 2.
- Query 4 (Type D, n=3): The outer loop runs 3 times. For each iteration, the inner loop mimics Type C and executes 2 times. Total count = 3 * 2 = 6.
Example 2:
Input:
types = ['B', 'D'] n_values = [0, 0]
Output:
[0, 0]
Explanation:
- For n=0, none of the loops meet the initial condition to execute even once. All pattern types output 0.
Now Your Turn!
Pick the correct output for the given inputInput:
types = ['B', 'A', 'C', 'D'] n_values = [4, 10, 7, 5]
Still unsure what the problem is asking ?
Let’s go through a few more examples, step by step, to make it clearer.
Constraints:
- 1 <= Q <= 100000
- 0 <= n <= 109
- Allowed types: 'A', 'B', 'C', 'D'
- Answers are guaranteed to fit in signed 64-bit integers.