Find the n-th term of a series where each term is the sum of the previous four

Quick Overview

Compute the n-th term of a sequence that starts 1, 2, 3, 4 and where every later term is the sum of the previous four. It tests basic dynamic programming with a rolling window, careful loop bounds, constant-space iteration and awareness of integer overflow.

Find the n-th term of a series where each term is the sum of the previous four

Company: HSBC

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: easy

Interview Round: Other

Given a positive integer `n`, return the n-th term of the following sequence. The first four terms are $N_1 = 1$, $N_2 = 2$, $N_3 = 3$ and $N_4 = 4$. Every later term is the sum of the previous four terms: $$ N_k = N_{k-1} + N_{k-2} + N_{k-3} + N_{k-4} \quad \text{for } k > 4 $$ ### Function Signature ```python def nth_term(n: int) -> int: ``` ### Rules - Terms are numbered from 1, so `n = 1` asks for $N_1$. - Return the exact integer value of $N_n$. ### Constraints - `1 <= n <= 50` ### Examples ```text Input: n = 5 Output: 10 ``` The fifth term is the first computed one: $N_5 = N_1 + N_2 + N_3 + N_4 = 1 + 2 + 3 + 4 = 10$. ```text Input: n = 8 Output: 69 ``` The sequence begins 1, 2, 3, 4, 10, 19, 36, 69, so the eighth term is 4 + 10 + 19 + 36 = 69. ```text Input: n = 3 Output: 3 ``` For `n` from 1 to 4 the answer is one of the given starting terms, here $N_3 = 3$.

Overview: Compute the n-th term of a sequence that starts 1, 2, 3, 4 and where every later term is the sum of the previous four. It tests basic dynamic programming with a rolling window, careful loop bounds, constant-space iteration and awareness of integer overflow.

HSBC logo
HSBC
Nov 25, 2026
easySoftware EngineerOtherCoding & Algorithms
0
0

Given a positive integer n, return the n-th term of the following sequence.

The first four terms are N1=1N_1 = 1, N2=2N_2 = 2, N3=3N_3 = 3 and N4=4N_4 = 4. Every later term is the sum of the previous four terms:

Nk=Nk−1+Nk−2+Nk−3+Nk−4for k>4N_k = N_{k-1} + N_{k-2} + N_{k-3} + N_{k-4} \quad \text{for } k > 4

Function Signature

def nth_term(n: int) -> int:

Rules

  • Terms are numbered from 1, so n = 1 asks for N1N_1 .
  • Return the exact integer value of NnN_n .

Constraints

  • 1 <= n <= 50

Examples

Input: n = 5
Output: 10

The fifth term is the first computed one: N5=N1+N2+N3+N4=1+2+3+4=10N_5 = N_1 + N_2 + N_3 + N_4 = 1 + 2 + 3 + 4 = 10.

Input: n = 8
Output: 69

The sequence begins 1, 2, 3, 4, 10, 19, 36, 69, so the eighth term is 4 + 10 + 19 + 36 = 69.

Input: n = 3
Output: 3

For n from 1 to 4 the answer is one of the given starting terms, here N3=3N_3 = 3.