Compute the Nth Recency Value
Company: Bloomberg
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: hard
Interview Round: Onsite
Quick Answer: This question evaluates understanding of recurrence-based sequence generation, index-based historical state tracking, and the design of time- and space-efficient algorithms. It is commonly asked in the Coding & Algorithms domain to assess algorithmic analysis and performance reasoning, emphasizing practical implementation-level competency rather than purely theoretical concepts.
Constraints
- 1 <= n <= 1000000
- An O(n^2) simulation that scans backward every step will be too slow for large n.
Examples
Input: 1
Expected Output: 0
Explanation: The sequence starts with a[0] = 0, so the first value is 0.
Input: 2
Expected Output: 0
Explanation: a[1] = 0 because the previous value 0 had not appeared before index 0.
Input: 4
Expected Output: 0
Explanation: The sequence is [0, 0, 1, 0], so a[3] = 0.
Input: 7
Expected Output: 2
Explanation: The sequence through index 6 is [0, 0, 1, 0, 2, 0, 2], so a[6] = 2.
Input: 10
Expected Output: 6
Explanation: The sequence through index 9 is [0, 0, 1, 0, 2, 0, 2, 2, 1, 6], so a[9] = 6.
Input: 20
Expected Output: 3
Explanation: Continuing the sequence efficiently gives a[19] = 3.
Hints
- You only need to remember the most recent previous index of each value, not every occurrence.
- While generating the sequence, update the last seen position of the previous value before moving to the next value.