AlgoViz

Arithmetic sequences

easy 13 min

An arithmetic sequence adds the same difference d at every step, like stairs of equal height.

See it run

Climb a staircase to any term in one step, count a nested loop's triangle of iterations, pair numbers like Gauss, and watch n(n-1)/2 grow like n².

Operations

Find the nth term

Find the 10th term of 2, 5, 8, 11, ... without listing the terms in between, using a_n = a_1 + (n - 1)d.

Step 1 of 6

Find term #10 of 2, 5, 8, 11, ...

  1. 20a1
  2. 51
  3. 82
  4. 113
  5. ?4
  6. ?5
  7. ?6
  8. ?7
  9. ?8
  10. ?9a10
a1 = 2d = 3n = 10

The sequence starts at a_1 = 2 and every term is 3 more than the one before, so d = 3. We know the first few terms and want a_{10} without listing all ten.

Step 1: Find term #10 of 2, 5, 8, 11, ...

def nth_term(a1, d, n):    return a1 + (n - 1) * d      # n - 1 jumps of size ddef nth_term_slow(a1, d, n):    term = a1    for _ in range(n - 1):       # one jump at a time: O(n)        term += d    return termprint(nth_term(2, 3, 10))        # 29
Time
O(1)
Space
O(1)
walking term by term
O(n): 9 additions here
1,000,000th term
still one formula

Say it as stairs: to reach landing n you climb n - 1 steps of height d. Writing n × d instead of (n - 1) × d is the most common slip.

Common mistakes

The bugs interviewers watch for, with the fix beside each.

  • Counting n jumps instead of n - 1

    critical

    Term 1 needs zero jumps, so term n needs n - 1. Using n × d gives a value one whole step too far.

    Wrong
    def nth_term(a1, d, n):    return a1 + n * d        # nth_term(2, 3, 10) gives 32
    Right
    def nth_term(a1, d, n):    return a1 + (n - 1) * d  # nth_term(2, 3, 10) gives 29
  • Using / and getting a float

    major

    In Python 3, / always returns a float. For large n the float loses precision, and the result prints as 5050.0. Use // because n(n + 1) is always even.

    Wrong
    total = n * (n + 1) / 2     # 5050.0, inexact for huge n
    Right
    total = n * (n + 1) // 2    # 5050, exact integer
  • Looping when a formula exists

    major

    Summing 1 to n in a loop is O(n). Inside another loop, or for n near 10^9, that is too slow. The closed form is O(1).

    Wrong
    total = 0for k in range(1, n + 1):   # O(n)    total += k
    Right
    total = n * (n + 1) // 2    # O(1)
  • Calling a dependent nested loop O(n)

    critical

    The inner loop being shorter on most passes does not make the whole thing linear. Its counts form 0, 1, ..., n - 1, which sum to n(n - 1)/2, still O(n²).

    Wrong
    # "inner loop is short, so this is O(n)"for i in range(n):    for j in range(i):        work(i, j)
    Right
    # 0 + 1 + ... + (n - 1) = n(n - 1)/2 calls: O(n^2)for i in range(n):    for j in range(i):        work(i, j)
  • Checking for an AP without sorting first

    major

    If the question asks whether the values can be rearranged into an arithmetic sequence, the input order is irrelevant. Comparing neighbours of the unsorted list rejects valid inputs like [3, 5, 1].

    Wrong
    def can_make_ap(nums):    d = nums[1] - nums[0]    return all(nums[i] - nums[i - 1] == d for i in range(2, len(nums)))
    Right
    def can_make_ap(nums):    nums = sorted(nums)    d = nums[1] - nums[0]    return all(nums[i] - nums[i - 1] == d for i in range(2, len(nums)))
  • Overflow in fixed-width languages

    minor

    In Java or C++, n * (n + 1) overflows a 32-bit int once n passes about 46,340. Python integers never overflow, but say how you would guard it in an interview.

    Wrong
    // Javaint total = n * (n + 1) / 2;          // overflows for n > 46340
    Right
    // Javalong total = (long) n * (n + 1) / 2;  // widen before multiplying

Interview tips

  • How to explain it

    • An arithmetic sequence adds the same difference d each step: a_n = a_1 + (n - 1)d.
    • Its sum is the number of terms times the average of the first and last: n(a_1 + a_n)/2.
    • 1 + 2 + ... + n = n(n + 1)/2, which is why a loop over pairs costs O(n²).
  • Spot it in code

    • `for j in range(i)` or `for j in range(i + 1, n)` inside `for i in range(n)`: about n²/2 iterations.
    • Comparing every pair of items once: n(n - 1)/2 pairs.
    • Bubble sort and selection sort passes shrink by one each time: an arithmetic sum.
    • A total you can write as first + ... + last with a fixed step: replace the loop with the formula.
  • Memory tricks

    • ADD: Arithmetic means ADDing the same Difference.
    • Stairs: n landings, n - 1 steps between them.
    • Gauss: pair first with last, 1 + 100 = 2 + 99 = 101, and 50 pairs make 5050.
  • Watch out

    • n - 1 jumps, not n.
    • Sum 1 to n is n(n + 1)/2; sum 0 to n - 1 is n(n - 1)/2. Know which one your loop makes.
    • Use // in Python and a 64-bit type in Java or C++.