Collatz Conjecture with Shared Memoization
Problem statement
For each value in queries, return its Collatz step count as a decimal string.
For a positive value n, repeatedly apply:
- If
nis even, replace it withn / 2. - If
nis odd, replace it with3n + 1.
The step count is the number of replacements required to reach 1. For a nonpositive query, return "null". Process queries in order and share memoized results, including intermediate values, across the batch.
Function
collatzSteps(queries: long[]) → String[]Examples
Example 1
queries = [5,8,4,-3]return = ["5","3","2","null"]5 -> 16 -> 8 -> 4 -> 2 -> 1 takes five steps. Later queries reuse cached suffix counts. The negative query returns null.
Example 2
queries = [1,2,3]return = ["0","1","7"]One is already complete; two takes one step; three follows 3,10,5,16,8,4,2,1.
Constraints
1 <= queries.length <= 10^4.-10^6 <= queries[i] <= 10^6.- For the positive range above, every intermediate value fits in a signed 64-bit integer.