KatInterview

Infer Numeric Pattern and Identify Corrupted Element

Math & Bit ManipulationModel answer
MediumModel answerMath & Bit Manipulationsequencespattern-recognitionedge-cases

Last updated

Determine which mathematical pattern a sequence follows, detect if one value is wrong, and predict the next term.

You're given a list of integers representing a sequence that follows one of four mathematical patterns. Your task is to identify the pattern, detect whether exactly one element might be incorrect, and predict what comes next.

Write a function next_value(seq: list[int]) that returns a tuple (model_name, parameters, anomaly_index_or_None, next_term).

The sequence follows exactly one of these patterns:

  1. Constant-step progression: Each term increases by the same amount d. Formula: a[i] = a[0] + i*d

  2. Alternating-step progression: The difference between consecutive terms alternates between two values d1 and d2. For odd positions the difference is d1, for even positions it's d2.

  3. Multiplicative progression: Each term is multiplied by the same integer ratio r ≥ 2 (all terms positive). Formula: a[i] = a[0] * r^i

  4. Fibonacci-like with offset: Each term equals the sum of the previous two terms plus a constant c. Formula: a[i] = a[i-1] + a[i-2] + c for i ≥ 2

Requirements:

  • At most one element in the sequence may be corrupted (replaced with a wrong value)
  • If corruption exists, return its zero-based index; otherwise return None
  • Compute the next term based on the identified pattern
  • Your solution must run in O(n) time with O(1) extra space
  • When multiple patterns could fit equally well, prefer them in this order: constant-step → alternating-step → multiplicative → Fibonacci-like

Return format:

  • model_name: string identifying the pattern
  • parameters: dict with pattern-specific values (e.g., {"d": 5} for constant-step)
  • anomaly_index_or_None: integer index of corrupted element, or None
  • next_term: integer value that should follow the sequence

Handle edge cases including short sequences (minimum length 3), large integers, and ambiguous cases where detection requires careful analysis.

Hints

Hint 1

Try validating each pattern by checking if removing any single element makes the rest consistent.

Hint 2

For each pattern type, derive what the parameters should be from uncorrupted elements, then check if at most one element violates those parameters.

Hint 3

The tie-breaking rule means you should test patterns in order and accept the first one that fits with at most one anomaly.