Infer Numeric Pattern and Identify Corrupted Element
Math & Bit ManipulationModel answerLast 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:
-
Constant-step progression: Each term increases by the same amount
d. Formula:a[i] = a[0] + i*d -
Alternating-step progression: The difference between consecutive terms alternates between two values
d1andd2. For odd positions the difference isd1, for even positions it'sd2. -
Multiplicative progression: Each term is multiplied by the same integer ratio
r ≥ 2(all terms positive). Formula:a[i] = a[0] * r^i -
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] + cfori ≥ 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 patternparameters: dict with pattern-specific values (e.g.,{"d": 5}for constant-step)anomaly_index_or_None: integer index of corrupted element, orNonenext_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.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core strategy is to test each pattern type in priority order, checking whether the sequence fits that pattern with at most one corrupted value.
Pattern Validation Strategy
For each pattern type:
- Assume no corruption: Calculate pattern parameters from the first few elements and verify all remaining elements match
- If validation fails: Try assuming each position is corrupted, derive parameters from the remaining elements, and check if exactly one position causes all violations
Pattern-Specific Detection
Constant-step progression:
- Compute difference
d = a[1] - a[0] - Check if
a[i] == a[0] + i*dfor all positions - If multiple violations exist, try each position as the anomaly and re-derive
dfrom other elements - With one anomaly removed, use majority voting: compute all pairwise differences and pick the most common
Alternating-step progression:
- Derive
d1from odd-position differences,d2from even-position differences - Validate the pattern holds throughout
- If violations occur, try assuming each position is corrupt and re-validate
Multiplicative progression:
- Check all terms are positive
- Compute ratio
r = a[1] / a[0](must be an integer ≥ 2) - Verify
a[i] == a[0] * r^i - Handle potential corruption by testing if removing one element yields a valid geometric sequence
Fibonacci-like with offset:
- For positions
i ≥ 2, derivec = a[i] - a[i-1] - a[i-2] - All derived
cvalues should be identical - If not, identify which position might be wrong by checking consistency when each candidate is removed
Complexity Analysis
- Time: O(n) - single pass to test each pattern, testing 4 patterns still O(n)
- Space: O(1) - only store pattern parameters and counters
Implementation Strategy
def next_value(seq):
n = len(seq)
# Test constant-step
result = test_arithmetic(seq)
if result:
return result
# Test alternating-step
result = test_alternating(seq)
if result:
return result
# Test multiplicative
result = test_geometric(seq)
if result:
return result
# Test Fibonacci-like
result = test_fibonacci(seq)
if result:
return result
def test_arithmetic(seq):
n = len(seq)
# Try with no anomaly
d = seq[1] - seq[0]
violations = []
for i in range(n):
if seq[i] != seq[0] + i * d:
violations.append(i)
if len(violations) == 0:
return ("arithmetic", {"d": d}, None, seq[-1] + d)
if len(violations) == 1:
# One violation - it's the anomaly
idx = violations[0]
return ("arithmetic", {"d": d}, idx, seq[-1] + d if idx != n-1 else seq[-2] + d)
# Multiple violations - try removing each position
for skip in range(n):
# Derive d from remaining elements
if skip == 0:
d_test = seq[2] - seq[1]
else:
d_test = seq[1] - seq[0]
valid = True
a0 = seq[0] if skip != 0 else seq[1] - d_test
for i in range(n):
if i == skip:
continue
expected = a0 + i * d_test
if seq[i] != expected:
valid = False
break
if valid:
next_term = seq[-1] + d_test if skip != n-1 else seq[-2] + d_test
return ("arithmetic", {"d": d_test}, skip, next_term)
return None
def test_geometric(seq):
# All must be positive
if any(x <= 0 for x in seq):
return None
# Similar validation logic with ratio r
# Check r is integer >= 2
# ...
def test_fibonacci(seq):
n = len(seq)
if n < 3:
return None
# Derive c from positions >= 2
c_values = []
for i in range(2, n):
c_values.append(seq[i] - seq[i-1] - seq[i-2])
# Check if all c values are the same (allowing one anomaly)
# ...
Common Mistakes
- Overflow handling: Large integers can cause overflow in geometric progressions with powers
- Division precision: Geometric ratio must be computed carefully to ensure it's an exact integer
- Edge case n=3: Minimal length requires special handling since removing one element leaves only 2
- Tie-breaking: Must test patterns in strict priority order, not best-fit
- Next term with anomaly at end: If the last element is corrupted, compute next term from the pattern, not from the corrupted value
Time Complexity: O(n)
Space Complexity: O(1)
The solution systematically tests each pattern in order, using single-pass validation with anomaly detection, ensuring we identify the simplest pattern that explains the sequence with at most one error.