FastPrepVan Eck Sequence Term

Van Eck Sequence Term

Bloomberg LP logoBloomberg LP● MediumNEW GRADONSITE INTERVIEW
Learn

Problem statement

Given a positive integer n, define a zero-indexed sequence a as follows:

  • a[0] = 0.
  • For every i >= 1, let x = a[i - 1]. If x appeared in a[0..i-2], let j be its greatest previous index and set a[i] = (i - 1) - j. Otherwise, set a[i] = 0.

Return a[n - 1].

Function

vanEckTerm(n: int) → int

Examples

Example 1

n = 1return = 0

The requested term is the initial value a[0].

Example 2

n = 4return = 0

The first four terms are [0, 0, 1, 0], so a[3] = 0.

Example 3

n = 10return = 6

The 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.

More Bloomberg LP problems

See Bloomberg LP hiring insights
public int vanEckTerm(int n) {
    // Write your code here.
}
n1
expected0
Checking account…