Van Eck Sequence Term
Problem statement
Given a positive integer n, define a zero-indexed sequence a as follows:
a[0] = 0.- For every
i >= 1, letx = a[i - 1]. Ifxappeared ina[0..i-2], letjbe its greatest previous index and seta[i] = (i - 1) - j. Otherwise, seta[i] = 0.
Return a[n - 1].
Function
vanEckTerm(n: int) → intExamples
Example 1
n = 1return = 0The requested term is the initial value a[0].
Example 2
n = 4return = 0The first four terms are [0, 0, 1, 0], so a[3] = 0.
Example 3
n = 10return = 6The prefix is [0, 0, 1, 0, 2, 0, 2, 2, 1, 6]. Before index 9, the previous value 1 last appeared at index 2, so a[9] = 8 - 2 = 6.
Constraints
1 <= n <= 1000000.