Problem · Array

Classify a Number Series and Return the Next Term

Learn this problem
EasyInMobi logoInMobiFULLTIMEOA

Problem 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

  1. First test for an arithmetic progression: every consecutive difference must be equal.
  2. If that test fails, test for a geometric progression: there must be one integer multiplier r such that sequence[i] = sequence[i - 1] * r for every valid i.
  3. If both earlier tests fail, test for a Fibonacci-style progression: sequence[i] = sequence[i - 1] + sequence[i - 2] for every i >= 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[]) → long

Examples

Example 1

sequence = [2,5,8,11]return = 14

The 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 = 48

Each term is the previous term multiplied by 2, so the next term is 48.

Example 3

sequence = [8,9,17,26]return = 43

Each 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 = -999

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

More InMobi problems

drafts saved locally
public long nextSeriesNumber(long[] sequence) {
    // write your code here
}
sequence[2,5,8,11]
expected14
checking account