Problem · Array
Classify a Number Series and Return the Next Term
Learn this problemProblem statement
Given an integer array sequence, determine whether it follows an arithmetic progression, an integer-ratio geometric progression, or a Fibonacci-style progression. Return the next term. If it follows none of them, return -999.
Classification Rules
- First test for an arithmetic progression: every consecutive difference must be equal.
- If that test fails, test for a geometric progression: there must be one integer multiplier
rsuch thatsequence[i] = sequence[i - 1] * rfor every validi. - If both earlier tests fail, test for a Fibonacci-style progression:
sequence[i] = sequence[i - 1] + sequence[i - 2]for everyi >= 2. The first two terms may be any integers.
The tests are performed in the order above. This makes the result deterministic when a sequence satisfies more than one rule.
Function
nextSeriesNumber(sequence: long[]) → longExamples
Example 1
sequence = [2,5,8,11]return = 14The consecutive difference is always 3, so this is an arithmetic progression and the next term is 11 + 3 = 14.
Example 2
sequence = [3,6,12,24]return = 48Each term is the previous term multiplied by 2, so the next term is 48.
Example 3
sequence = [8,9,17,26]return = 43Each term from the third onward is the sum of the previous two, so the next term is 17 + 26 = 43.
Example 4
sequence = [1,2,4,7]return = -999The sequence satisfies none of the three progression rules, so the sentinel -999 is returned.
Constraints
3 <= sequence.length <= 1000-10^9 <= sequence[i] <= 10^9- Every multiplication, addition, difference, and valid next term fits in a signed
long.