Generate the first n terms of the Fibonacci sequence as a list

Quick Overview

Write a Python function that returns the first n Fibonacci numbers as a list, starting from 0 and 1. It tests base cases for zero, one and two terms, building each term from the previous two, and the time and space cost of the result.

Generate the first n terms of the Fibonacci sequence as a list

Company: Oracle

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: easy

Interview Round: Other

Write a Python function that generates the Fibonacci sequence up to a given number of terms. The Fibonacci sequence is a series of numbers in which each number is the sum of the two preceding ones, starting from 0 and 1: `0, 1, 1, 2, 3, 5, 8, 13, 21, ...`. The function should return a list containing the first `n` terms of the sequence. ### Function Signature ```python def fibonacci_sequence(n: int) -> list[int]: ``` ### Rules - `n` is a number of terms, not a largest value. - If `n = 0`, return an empty list `[]`. - If `n = 1`, return `[0]`. - If `n = 2`, return `[0, 1]`. ### Constraints - `0 <= n <= 125` ### Examples ```text Input: n = 5 Output: [0, 1, 1, 2, 3] ``` After 0 and 1, each term is the sum of the two before it: 0 + 1 = 1, 1 + 1 = 2, 1 + 2 = 3. That makes five terms. ```text Input: n = 8 Output: [0, 1, 1, 2, 3, 5, 8, 13] ``` The sequence continues with 2 + 3 = 5, 3 + 5 = 8 and 5 + 8 = 13, for eight terms in total. ```text Input: n = 0 Output: [] ``` Zero terms were requested, so the list is empty.

Overview: Write a Python function that returns the first n Fibonacci numbers as a list, starting from 0 and 1. It tests base cases for zero, one and two terms, building each term from the previous two, and the time and space cost of the result.

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

Write a Python function that generates the Fibonacci sequence up to a given number of terms. The Fibonacci sequence is a series of numbers in which each number is the sum of the two preceding ones, starting from 0 and 1: 0, 1, 1, 2, 3, 5, 8, 13, 21, .... The function should return a list containing the first n terms of the sequence.

Function Signature

def fibonacci_sequence(n: int) -> list[int]:

Rules

  • n is a number of terms, not a largest value.
  • If n = 0 , return an empty list [] .
  • If n = 1 , return [0] .
  • If n = 2 , return [0, 1] .

Constraints

  • 0 <= n <= 125

Examples

Input: n = 5
Output: [0, 1, 1, 2, 3]

After 0 and 1, each term is the sum of the two before it: 0 + 1 = 1, 1 + 1 = 2, 1 + 2 = 3. That makes five terms.

Input: n = 8
Output: [0, 1, 1, 2, 3, 5, 8, 13]

The sequence continues with 2 + 3 = 5, 3 + 5 = 8 and 5 + 8 = 13, for eight terms in total.

Input: n = 0
Output: []

Zero terms were requested, so the list is empty.