Integer Sequence Rule Inference and Next-Term Prediction
Math & Bit ManipulationModel answerLast updated
Design a systematic program that detects the governing rule of an integer sequence and predicts the next k terms, ranked by plausibility.
Integer Sequence Rule Inference and Next-Term Prediction
You receive an integer sequence of between 2 and 50 terms. The sequence may have been generated by any of the following mechanisms:
- A polynomial rule (including constant, arithmetic, and higher-degree progressions)
- A linear recurrence, possibly with a constant offset (e.g. geometric progressions, Fibonacci-like rules, affine maps)
- A digit-level transform applied repeatedly (e.g. each term equals the previous term plus its own digit sum)
- An interleaving of two or more independent subsequences (e.g. odd-indexed and even-indexed terms each follow their own rule)
- A combination or nesting of the above
Your task is to describe a complete, systematic strategy for inferring the rule and predicting the next k terms (1 ≤ k ≤ 5). Then implement that strategy as a program.
What your answer should cover
- Heuristic pipeline — which rule families you check, in what order, and why that order makes sense
- Model selection — how you score competing explanations and choose among them when more than one fits the observed terms
- Insufficient evidence and ambiguity — how you detect and report cases where the sequence is too short to confirm any rule, or where two rules with different predictions are equally plausible
- Implementation — working code that accepts the sequence and
k, and outputs candidate rules with their predicted next terms and plausibility scores - Complexity analysis — time and space cost of each stage
- Edge cases — n = 2, constant sequences, non-integer intermediate values, negative terms, very fast growth
Input / output
Input: a list of integers s (2 ≤ len(s) ≤ 50)
an integer k (1 ≤ k ≤ 5)
Output: for each distinct prediction of the next k terms,
the best-scoring rule that produces it and its score;
or a message indicating insufficient evidence / ambiguity
Example
s = [2, 5, 8, 11, 14], k = 3
Expected output: arithmetic (d=3), next terms: [17, 20, 23], score: 3.5
s = [1, 2, 4, 8, 16], k = 2
Expected output: geometric (r=2), next terms: [32, 64], score: 3.5
(flag: degree-4 polynomial predicts [31, 57] with score ≤ 0 — ambiguity note)
s = [1, 2], k = 1
Expected output: insufficient evidence
Hints
Hint 1
Start with finite differences: repeatedly subtract consecutive terms. If any row becomes constant, you have a polynomial of that degree. This check is O(n²) and catches arithmetic, quadratic, and higher-degree rules before you try anything more expensive.
Hint 2
Model selection is cleaner when you separate fitting from verification. Fit a rule's parameters on the smallest prefix needed (e.g. d+1 terms for a degree-d polynomial), then count how many of the remaining terms it predicts exactly. That count is your evidence; penalize it by the number of free parameters to get a score.
Hint 3
Interleaving patterns are easy to miss. Before giving up, split the sequence into even-indexed and odd-indexed subsequences and run your full pipeline on each part independently. This handles alternating rules like +3, ×2, +3, ×2 without any special-case logic.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core insight is to treat this as model selection, not open-ended guessing. Build a library of rule families, fit each one on a minimal prefix of the sequence, then verify it against every remaining term. Rank survivors by how much evidence they have relative to their complexity — a lightweight Occam's razor.
Score formula: score = confirmations − 0.5 × complexity
- Confirmations = terms correctly predicted that were not used to fit the rule's parameters
- Complexity = number of free parameters, plus a small structural cost for interleaving
A degree-1 polynomial (arithmetic) has 2 parameters; if it fits 10 terms it scores 8 − 0.5×2 = 7.0. A degree-4 polynomial has 5 parameters; even if it fits 5 terms it has 0 confirmations and scores 0 − 2.5 = −2.5, so it is rejected.
Heuristic pipeline (cheapest to most exotic)
Stage 1 — Finite differences (polynomial check)
Repeatedly subtract consecutive terms. If a difference row ever becomes constant, the sequence is polynomial of that degree. Degree 0 is constant, degree 1 is arithmetic. A degree-d polynomial requires at least d+2 terms before it earns even one confirmation.
Stage 2 — Linear recurrences with optional constant
Fit a[i] = c1·a[i−1] + … + cr·a[i−r] + c0 via Gaussian elimination over exact rationals. Orders 1 through 4 cover geometric sequences, affine maps (2x+1), and Fibonacci-like rules. Exact arithmetic (Python's Fraction) is essential here — float arithmetic produces false positives.
Stage 3 — Digit-level transforms
Check whether a[i+1] = a[i] + digitsum(a[i]), or similar digit-based maps. These have zero numeric parameters, so every term after the first counts as a confirmation. Skip for sequences containing negative terms.
Stage 4 — Interleaving
Split into even-indexed and odd-indexed subsequences (and, if n ≥ 12, into thirds). Run stages 1–3 on each part independently. This captures patterns like +3, ×2, +3, ×2 without special-casing, because each parity class obeys its own rule.
After all stages, group surviving candidates by the next-k terms they predict. Keep the best-scoring rule per group.
Insufficient evidence and ambiguity
- Insufficient: best rule has fewer than 2 confirmations. Report this when n = 2 — arithmetic, geometric, and dozens of other rules all fit with zero confirmations.
- Ambiguous: two candidates with different predictions are within 1.0 score of each other. Report both predictions. Classic example:
[1, 2, 4, 8, 16]— powers of 2 (score 3.5) and the unique degree-4 polynomial through those 5 points (score −2.5) disagree on the 6th term (32 vs 31). The scoring correctly prefers powers of 2, but a good implementation surfaces the alternative.
Complexity
| Stage | Time | Space |
|---|---|---|
| Finite differences | O(n²) | O(n²) |
| Recurrence of order r | O(r³) solve + O(nr) verify | O(r²) |
| All recurrences r ≤ R | O(R⁴ + nR²) | O(R²) |
| Digit maps | O(n · D), D = digit length | O(1) |
| Interleaving (×2 split) | constant factor on the above | — |
For n ≤ 50 and R ≤ 4 the total runtime is well under a millisecond.
Python implementation
from fractions import Fraction as F
from itertools import islice
def _to_int(x):
return int(x) if isinstance(x, F) and x.denominator == 1 else x
def fit_polynomial(s, k):
"""Return next k terms if s is polynomial, else None."""
rows = [[F(x) for x in s]]
while len(rows[-1]) > 1 and len(set(rows[-1])) != 1:
prev = rows[-1]
rows.append([b - a for a, b in zip(prev, prev[1:])])
if len(rows) > len(s): # no constant row found
return None
if len(set(rows[-1])) != 1:
return None
# count confirmations: fit used d+1 terms, rest confirm
degree = len(rows) - 1
confirmations = len(s) - (degree + 1)
if confirmations < 0:
return None
# extend by k terms
for _ in range(k):
rows[-1].append(rows[-1][-1]) # constant row extends trivially
for row in reversed(rows[:-1]):
row.append(row[-1] + rows[rows.index(row) + 1][-1])
preds = [_to_int(rows[0][-(k - i)]) for i in range(k - 1, -1, -1)]
score = confirmations - 0.5 * (degree + 1)
return {"rule": f"polynomial degree {degree}", "preds": preds,
"score": score, "confirmations": confirmations}
def fit_recurrence(s, order, k):
"""Fit a[i] = c1*a[i-1]+...+cr*a[i-r]+c0 of given order over rationals."""
r = order
if len(s) < 2 * r + 1:
return None
# build system: r+1 equations in r+1 unknowns [c0, c1, ..., cr]
mat = []
for i in range(r, 2 * r + 1):
row = [F(1)] + [F(s[i - j]) for j in range(1, r + 1)] + [F(s[i])]
mat.append(row)
# Gaussian elimination
n_eq = r + 1
for col in range(n_eq):
pivot = next((i for i in range(col, n_eq) if mat[i][col] != 0), None)
if pivot is None:
return None # singular — skip
mat[col], mat[pivot] = mat[pivot], mat[col]
for i in range(n_eq):
if i != col and mat[i][col] != 0:
factor = mat[i][col] / mat[col][col]
mat[i] = [mat[i][j] - factor * mat[col][j] for j in range(n_eq + 1)]
coeffs = [mat[i][-1] / mat[i][i] for i in range(n_eq)] # [c0, c1, ..., cr]
# verify against all terms
seq = [F(x) for x in s]
for i in range(r, len(seq)):
predicted = coeffs[0] + sum(coeffs[j] * seq[i - j] for j in range(1, r + 1))
if predicted != seq[i]:
return None
confirmations = len(s) - (2 * r + 1)
if confirmations < 0:
return None
# predict next k terms
for _ in range(k):
nxt = coeffs[0] + sum(coeffs[j] * seq[-(j)] for j in range(1, r + 1))
seq.append(nxt)
preds = [_to_int(x) for x in seq[-k:]]
score = confirmations - 0.5 * (r + 1)
return {"rule": f"recurrence order {r}", "preds": preds,
"score": score, "confirmations": confirmations}
def fit_digit_sum(s, k):
"""Check a[i+1] == a[i] + digit_sum(a[i]) for all i."""
if any(x < 0 for x in s):
return None
def dsum(n): return sum(int(d) for d in str(n))
for i in range(len(s) - 1):
if s[i] + dsum(s[i]) != s[i + 1]:
return None
confirmations = len(s) - 1
seq = list(s)
for _ in range(k):
seq.append(seq[-1] + dsum(seq[-1]))
score = confirmations - 0.5 * 0 # 0 free numeric parameters
return {"rule": "digit-sum map", "preds": seq[-k:],
"score": score, "confirmations": confirmations}
def detect_sequence(s, k):
candidates = []
# Stages 1 and 2: polynomial and recurrences on the full sequence
r = fit_polynomial(s, k)
if r: candidates.append(r)
for order in range(1, 5):
r = fit_recurrence(s, order, k)
if r: candidates.append(r)
# Stage 3: digit-level map
r = fit_digit_sum(s, k)
if r: candidates.append(r)
# Stage 4: interleaving — split into even/odd subsequences
for stride in (2, 3):
parts = [s[start::stride] for start in range(stride)]
if all(len(p) >= 3 for p in parts):
part_preds = []
part_scores = []
valid = True
for p in parts:
best = None
for cand_fn in [
lambda p=p: fit_polynomial(p, k),
*(lambda p=p, o=o: fit_recurrence(p, o, k) for o in range(1, 3)),
]:
res = cand_fn()
if res and (best is None or res["score"] > best["score"]):
best = res
if best is None:
valid = False
break
part_preds.append(best["preds"])
part_scores.append(best["score"])
if valid:
# interleave the per-part predictions
merged = []
iters = [iter(pp) for pp in part_preds]
for i in range(k):
merged.append(next(iters[i % stride]))
score = sum(part_scores) - 0.5 * stride # structural cost
candidates.append({"rule": f"interleaved (stride {stride})",
"preds": merged[:k], "score": score,
"confirmations": min(
c["confirmations"] for c in
[{"confirmations": s} for s in part_scores])})
if not candidates:
return {"status": "no rule found"}
# Deduplicate by prediction, keep best score per group
best_by_pred = {}
for c in candidates:
key = tuple(c["preds"])
if key not in best_by_pred or c["score"] > best_by_pred[key]["score"]:
best_by_pred[key] = c
ranked = sorted(best_by_pred.values(), key=lambda x: -x["score"])
best = ranked[0]
if best["confirmations"] < 2:
return {"status": "insufficient evidence", "candidates": ranked}
if len(ranked) > 1 and ranked[0]["score"] - ranked[1]["score"] < 1.0:
return {"status": "ambiguous", "candidates": ranked[:2]}
return {"status": "ok", "best": best}
Common mistakes
- Using floats for recurrence coefficients:
1/3in exact arithmetic is fine; as a float it introduces rounding errors that break verification. - Confirming on the same terms used for fitting: this inflates the score and lets degree-4 polynomials beat arithmetic. Always split fit prefix from verification suffix.
- Ignoring interleaving: sequences like
2, 10, 5, 20, 8, 40look random until you separate even- and odd-indexed terms. - Reporting ambiguity too aggressively: two rules that make the same prediction are not ambiguous even if they are structurally different — deduplicate by prediction first.