FastPrepCollatz Conjecture with Shared Memoization

Collatz Conjecture with Shared Memoization

Bloomberg LP logoBloomberg LP● MediumNEW GRADPHONE SCREENONSITE INTERVIEW
Learn

Problem statement

For each value in queries, return its Collatz step count as a decimal string.

For a positive value n, repeatedly apply:

  • If n is even, replace it with n / 2.
  • If n is odd, replace it with 3n + 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.

More Bloomberg LP problems

See Bloomberg LP hiring insights
public String[] collatzSteps(long[] queries) {
  // Write your code here.
}
queries[5,8,4,-3]
expected["5", "3", "2", "null"]
Checking account…