Quick revision
The short answer
Printing the first n Fibonacci numbers is a recurrence problem from math and bits, solved like the smallest dynamic programming problem. Each number is the sum of the two before it, so we keep only the last two, prev and curr, starting at 0 and 1, print prev, and slide the pair along with next = prev + curr. It takes O(n) time and O(1) extra space besides the output, while the naive recursion takes exponential time.
The solution
What it costs
| Approach | Time | Extra space | Note |
|---|---|---|---|
Recursive fib(i) for every i | exponential, about 1.6^n | O(n) call stack | recomputes the same values |
| Recursion with a memo array | O(n) | O(n) | each value computed once |
| Loop with an array of all values | O(n) | O(n) | bottom up |
| Loop with prev and curr | O(n) | O(1) | keeps only the last two |
What to remember
We printed the first n Fibonacci numbers by walking forward with two variables, printing prev and sliding the pair along with next = prev + curr, in O(n) time and O(1) extra space, with BigInteger for n above 93. The clue to remember is a value defined from the few values just before it, wanted in order: compute from the smallest upwards and keep only as many earlier answers as the rule looks back, like a hand that leaves only the last two lines of the notebook showing.
1What the Fibonacci sequence is, and what we must print
Imagine keeping a column of numbers in a notebook with one simple habit. You write 0 on the first line and 1 on the second. From then on, each new line is the two lines just above it added together. To write the next line you never need to look further up the page; you could cover every older line with your hand and still carry on. That column is the Fibonacci sequence, and that hand covering the old lines is the idea this whole article is built on.
Let us write the first few lines together. 0 and 1 are given. 0 + 1 is 1, then 1 + 1 is 2, 1 + 2 is 3, 2 + 3 is 5, and on to 8, 13, 21 and 34. The line at position i is called F(i), read as F of i, counting from zero, so F(0) = 0, F(1) = 1 and F(2) = 1. Our habit is written F(i) = F(i - 1) + F(i - 2), which only says each line is the sum of the two above it. There is no formula to memorise beyond that.
We will keep one example all through the article, n = 10. The first ten numbers are F(0) up to F(9), so the answer is 0, 1, 1, 2, 3, 5, 8, 13, 21, 34. Notice that the last number printed is F(9), not F(10). Starting the count at zero means the first n numbers end at position n - 1, and keeping that straight now will save a confused moment later.
The index above each box is i, and the box holds F(i). For n = 10 we print these ten boxes, from F(0) to F(9).
- n
- 10
- F(0), F(1)
- 0 and 1, given
- F(9)
- 34, the last one printed
1For n = 10 the answer is 0, 1, 1, 2, 3, 5, 8, 13, 21, 34. Each box from index 2 on is the sum of the two boxes just to its left.
What to assume
- Does the sequence start 0, 1 or 1, 1?
- We say aloud that we start at 0, 1, the more common choice. n = 1 gives [0], n = 0 gives an empty list, and a negative n makes no sense, so we reject it.
- How large can n be?
- Fibonacci numbers grow about 1.6 times at every step, and the largest one that fits in a Java long is F(92), so a list of longs holds at most the first 93 numbers. Beyond that we need
BigInteger, Java's class for whole numbers of any size.
A careful candidate asks a few questions first. Does the sequence start 0, 1 or 1, 1? We say aloud that we start at 0, 1, the more common choice. n = 1 gives [0], n = 0 gives an empty list, and a negative n makes no sense, so we reject it. The last question catches people out. How large can n be? Fibonacci numbers grow about 1.6 times at every step, and the largest one that fits in a Java long is F(92), so a list of longs holds at most the first 93 numbers. Beyond that we need BigInteger, Java's class for whole numbers of any size.
Your turn
Solve it before you read on. Above is one example with the result expected for it. Under What to assume are the points this solution takes as given. Say your approach aloud or type it below, and write the code in your own editor. Then take one hint at a time and compare.
2How to recognise a sequence built from its own earlier values
When most of us read this question, our eyes go straight to the formula F(i) = F(i - 1) + F(i - 2), and we think of writing it in Java exactly as it stands, as a method that calls itself. That is natural, because the formula reads like a recipe. Before following it, let us read the question slowly, one clue at a time.
The first clue is that each value is defined from the values just before it. A definition like this is called a recurrence, from recur, to come back again, because the same rule comes back at every step. A recurrence is a warning as well as a recipe. Translated into a method that calls itself twice, it asks for the same smaller answers again and again, as we will soon see.
The second clue is the word first. We are asked for all the numbers in order from the start, not one far away value. So by the time we need F(i), we have just produced the two numbers it depends on. The order of the output matches the order of the dependencies, a lucky and useful fact.
Put together, these clues point to the pattern called math and bits, and inside it to the smallest case of dynamic programming. That grand name only means working out the small answers first, keeping them, and building each bigger answer from them instead of recomputing. The rule to carry to new problems is this. When an answer is defined from a few earlier answers, compute in order from the smallest, and keep only as many earlier answers as the rule looks back. Fibonacci looks back two steps, so we keep two numbers, the two lines our hand left uncovered.
Some ideas look related but do not fit. Bit tricks, the other half of this family, help when we want one huge F(n) very fast, but printing n numbers needs n steps whatever we do. A closed formula with powers of 1.618 exists, but it uses floating point numbers, which lose accuracy after about F(70). The keep-the-last-two shape, though, also solves climbing stairs and the house robber problem, so this small exercise pays off later.
3The honest first attempt, translating the definition into recursion
The brute force, the first attempt almost everyone makes, is to copy the definition straight into Java, and that is a good instinct. A method that calls itself is called recursive. Our fib returns n itself when n is 0 or 1, and fib(n - 1) + fib(n - 2) otherwise, and we call it for every i from 0 to n - 1. It matches the definition word for word and gives correct answers.
Each circle is one call of fib. A call on F(n) for n of 2 or more makes two smaller calls below it. Nine calls in all, to find five different values.
- calls
- 9
- values
- 5 different, F(0) to F(4)
1
fib(4)asks forfib(3)andfib(2),fib(3)asks forfib(2)andfib(1), and so on down to F(1) and F(0), which answer at once.- F(2) computed
- 2 times
- calls
- 9
2F(2) is worked out twice, once under F(4) and once under F(3). The second time does exactly the same additions and gets the same 1.
- F(1) asked
- 3 times
- F(0) asked
- 2 times
- fib(10) calls
- 177
- fib(30) calls
- 2692537
3F(1) is asked for three times and F(0) twice. Every repeated circle is work the computer has already done once.
Now let us count the work by hand, because this is where the surprise is. Take fib(4). It calls fib(3) and fib(2). fib(3) calls fib(2) and fib(1). Each fib(2) calls fib(1) and fib(0). If we draw every call as a circle, as in the picture below, we count nine circles. But there are only five different values involved, F(0) to F(4). So four of the nine calls were repeats of work already done.
Why is that so bad? Because the repeats themselves repeat. fib(5) takes 15 calls, fib(10) takes 177, and fib(30) takes 2,692,537 calls to produce one number. Each step up in n multiplies the count by about 1.6, so the time grows exponentially, multiplying by a fixed amount for every extra step. firstNSlow pays that price again for every entry. The space is milder, a chain of waiting calls as deep as n, which is O(n), read as order n, meaning it grows in step with n.
So where exactly is the waste? The picture makes it plain. F(2) is worked out twice, F(1) three times, F(0) twice, and each time the answer is the same. A Fibonacci number never changes once we know it, so working it out a second time teaches the computer nothing new. That repeated, identical work is what we must get rid of.
4Getting to the two-variable loop, one observation at a time
The first observation is the simplest repair. If the same value is asked for many times, we can write it down the first time and look it up afterwards. This is called memoization, which just means keeping a memo. fib(i) first checks memo[i] and computes only if that box is empty, so every value is computed once and the time drops to O(n). It still needs an array of n numbers, but it is a good middle step to mention in an interview.
The second observation comes from the notebook. When we wrote the column by hand, we never went back to look at old lines. We worked forward, from the top, and each new line needed only the two lines just above it. So instead of starting from F(n) and asking for smaller values, as recursion does, we can start from F(0) and F(1) and walk forward. Working from the smallest answer upwards like this is called bottom up.
The third observation gives the final solution. If each new number needs only the last two, we only ever need to keep two numbers, prev and curr. prev holds the number we are about to print and curr the one after it. They start as 0 and 1. In each pass we print prev, compute the next number as prev + curr, and slide the pair one step to the right, like our hand uncovering one new line in the notebook and covering one old one.
Now comes the question every beginner asks. Why do we need a third variable called next? Could we not write prev = curr and then curr = prev + curr? Let us try it with prev = 1 and curr = 2. The first line sets prev to 2. The second computes prev + curr, but prev is now 2, so it gives 4, while the right answer was 1 + 2 = 3. We overwrote the old prev before using it. Saving the sum in next first keeps both old values for as long as we need them. This is the mistake beginners make most often here.
Why is the loop correct, and not just plausible? At the top of pass i, prev holds F(i) and curr holds F(i + 1). That is true before the first pass. During the pass we print prev, which is F(i). Then next = F(i) + F(i + 1), which is F(i + 2) by the definition, and the slide makes prev = F(i + 1) and curr = F(i + 2), so the statement is true again for pass i + 1. A statement that stays true at the top of every pass is called a loop invariant, and it is how we know the loop prints F(0) to F(n - 1) in order.
5Watching the pair slide along for n = 10
The picture runs firstN(10) one pass at a time. The boxes are the Fibonacci numbers as we would write them on paper, from F(0) to F(11), and a question mark is a number the program has not worked out yet. The two labels under the boxes show which numbers prev and curr hold, and the panel beside shows i, next, the pair, and out, the list we are building.
Watch two things. First, the pair always sits side by side and moves exactly one box to the right in each pass. Second, out always grows by the number prev held at the start of the pass, so the printed boxes trail one step behind prev.
The boxes are F(0) to F(11) as we would write them on paper; a question mark is a number not worked out yet. Marked boxes are already in out. Only prev and curr are kept in variables.
- i
- not started
- prev
- 0
- curr
- 1
- out
- []
1Before the loop, prev holds F(0) = 0 and curr holds F(1) = 1. Nothing is printed yet, and every later box is still unknown.
- i
- 0
- next
- 1
- prev
- 1
- curr
- 1
- out
- [0]
2i = 0: we add prev, 0, to out. next = 0 + 1 = 1, then prev moves to 1 and curr to 1, which is F(2).
- i
- 1
- next
- 2
- prev
- 1
- curr
- 2
- out
- [0, 1]
3i = 1: we add prev, 1, to out. next = 1 + 1 = 2, so the pair becomes prev = 1 and curr = 2.
- i
- 2
- next
- 3
- prev
- 2
- curr
- 3
- out
- [0, 1, 1]
4i = 2: we add 1 to out. next = 1 + 2 = 3, and the pair slides on to prev = 2, curr = 3.
- i
- 3
- next
- 5
- prev
- 3
- curr
- 5
- out
- [0, 1, 1, 2]
5i = 3: we add 2. next = 2 + 3 = 5, and the pair is now prev = 3, curr = 5. Only two numbers are ever held.
- i
- 4
- next
- 8
- prev
- 5
- curr
- 8
- out
- [0, 1, 1, 2, 3]
6i = 4: we add 3. next = 3 + 5 = 8. The pair moves to prev = 5, curr = 8, exactly one box to the right.
- i
- 5
- next
- 13
- prev
- 8
- curr
- 13
- out
- [0, 1, 1, 2, 3, 5]
7i = 5: we add 5. next = 5 + 8 = 13, so prev = 8 and curr = 13. The same three lines run every time.
- i
- 6
- next
- 21
- prev
- 13
- curr
- 21
- out
- [0, 1, 1, 2, 3, 5, 8]
8i = 6: we add 8. next = 8 + 13 = 21, so prev = 13 and curr = 21.
- i
- 7
- next
- 34
- prev
- 21
- curr
- 34
- out
- [0, 1, 1, 2, 3, 5, 8, 13]
9i = 7: we add 13. next = 13 + 21 = 34, so prev = 21 and curr = 34.
- i
- 8
- next
- 55
- prev
- 34
- curr
- 55
- out
- [0, 1, 1, 2, 3, 5, 8, 13, 21]
10i = 8: we add 21. next = 21 + 34 = 55, so prev = 34 and curr = 55. Notice curr is now ahead of what we print.
- i
- 9
- next
- 89
- prev
- 55
- curr
- 89
- out
- [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
11i = 9, the last pass: we add 34, so out holds ten numbers. The pair still moves on, to prev = 55 and curr = 89.
- i
- 10, loop ends
- prev
- 55, not printed
- curr
- 89, not printed
- out
- [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
12Now i becomes 10, the test i < n fails, and the loop ends. We return out. 55 and 89 were computed but never printed, which is harmless.
Let us read a few frames back. In the first frame nothing is printed; prev and curr hold the two given numbers. In the frame for i = 0, out receives 0, next becomes 1, and the pair slides to 1 and 1. In the frame for i = 3, out receives 2 and the pair is 3 and 5. However many boxes are filled on paper, the program holds only two numbers and the list.
The last two frames sometimes worry beginners. In the pass for i = 9 we add 34, the tenth number, and the pair still moves on to 55 and 89, numbers that are never printed. Then the test i < 10 fails and the loop ends. That extra addition is harmless, but it matters for overflow, because the unprinted curr is the first number to grow too big for a long.
6The complete Java program
Here is the whole class. firstN uses long and refuses n above 93, because the 94th number would not fit. firstNBig runs exactly the same loop with BigInteger for any n. main prints our example, the two smallest cases, the largest Fibonacci number a long can hold, and F(100) from the BigInteger version, and each comment shows what that line prints.
Let us read firstN in the order it runs. The two checks at the top come first. A negative n is meaningless, so we throw an IllegalArgumentException with a plain message. An n above 93 would need F(93), which is larger than the biggest long, so we refuse it and point the caller to firstNBig. Without it, a long that grows too big silently wraps round to a negative number, which is far worse than a clear exception.
Next we create out and set prev = 0 and curr = 1. The loop runs n times. out.add(prev) records the number this pass is responsible for, long next = prev + curr works out the following number while both old values are intact, and prev = curr and curr = next slide the pair along. When the loop ends we return out.
Why does firstN(93) work if F(93) does not fit? In the pass for i = 91 the loop computes F(93) into curr, and that value has already wrapped round. But it is never printed. The last pass, i = 92, prints prev, F(92) = 7540113804746346429, so the overflow touches only numbers that never reach out, as the comment on that line says.
firstNBig is the same loop with BigInteger.ZERO and BigInteger.ONE as the starting pair and prev.add(curr) in place of the plus sign, because Java's + does not work on objects. BigInteger grows as large as it needs, so main can print F(100), a number with 21 digits.
7How much it costs, and the cases at the edges
Let us count on the example first. For n = 10 the loop ran ten times, and each pass did one add to the list, one addition and two assignments, a handful of steps. For n numbers that is n passes of constant work, a fixed amount that does not depend on n, so the time is O(n). We cannot do better, since n numbers must be printed.
The space has two parts. The output list holds n numbers, but the question asks for those, so we do not count them against our method. Apart from it we keep prev, curr, next and i, four variables whether n is 10 or 90, so the extra space is O(1), read as constant.
| Approach | Time | Extra space | Note |
|---|---|---|---|
Recursive fib(i) for every i | exponential, about 1.6^n | O(n) call stack | recomputes the same values |
| Recursion with a memo array | O(n) | O(n) | each value computed once |
| Loop with an array of all values | O(n) | O(n) | bottom up |
| Loop with prev and curr | O(n) | O(1) | keeps only the last two |
One honest footnote concerns BigInteger. Its numbers gain about one digit every five steps, and adding two numbers of d digits takes time in proportion to d, so the BigInteger version is really about O(n squared) digit operations. For n in the thousands it is still very fast.
The edge cases need very little code. For n = 0 the loop never runs and we return []. For n = 1 it runs once and returns [0]. A negative n throws an exception, because a negative count has no meaning, and n above 93 throws and points the caller to firstNBig. The bug beginners actually hit is the one we met earlier, updating prev before computing the sum, which quietly doubles curr.
8Follow-up questions
How would you compute only F(n), for a very large n, quickly?
If we need one far away value rather than the whole list, we can use fast doubling. It relies on two identities, F(2k) = F(k) times (2 F(k + 1) - F(k)) and F(2k + 1) = F(k) squared plus F(k + 1) squared, which jump from position k to position 2k. We reach n by reading its binary digits from the top, so it takes about log n steps instead of n, which is where the bits in math and bits come in. For printing the first n numbers it does not help, because the list itself has n entries.
Can you write it recursively without the exponential cost?
Yes, in two ways. The first is memoization, keeping an array memo where memo[i] is filled the first time fib(i) is computed, so later calls read the box instead of recursing. The second is to pass the pair along, as in fib(n, prev, curr), which returns prev when n is 0 and otherwise calls fib(n - 1, curr, prev + curr). That makes one call per step, so it is O(n) time. Both still use O(n) call stack, because Java does not remove finished calls early, so for large n the loop is still the safer choice.
9Conclusion
We printed the first n Fibonacci numbers by walking forward with two variables, printing prev and sliding the pair along with next = prev + curr, in O(n) time and O(1) extra space, with BigInteger for n above 93. The clue to remember is a value defined from the few values just before it, wanted in order: compute from the smallest upwards and keep only as many earlier answers as the rule looks back, like a hand that leaves only the last two lines of the notebook showing.
Open with
Let me confirm the details first. I will start at 0 and 1, so n = 10 prints 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, n = 0 prints nothing, and a negative n is rejected.
Then, if they want more
The direct recursion, fib(n - 1) + fib(n - 2), is correct but recomputes the same values again and again, so its cost grows about 1.6 times per step; fib(30) alone makes over two and a half million calls. Memoizing it gives O(n) time with an O(n) array.
Better, since each number needs only the two before it and I produce them in order, I keep two variables, prev and curr, starting at 0 and 1. In each of n passes I add prev to the output, compute next as prev plus curr before changing anything, then set prev to curr and curr to next.
The invariant is that prev holds F(i) at the top of pass i. That is O(n) time and O(1) extra space besides the output. A long holds Fibonacci numbers only up to F(92), so I refuse n above 93 and use BigInteger with the same loop beyond that.
About this answer
- Last updated
- 15 November 2026
- Written for
- Java 21, using only java.util
- Checked
- The Java solution was compiled and run, and each printed result matches the comment beside it. The pictures are checked against the format when the site is built. The explanation around the code is a study note: confirm anything critical against the documentation below. What the checks cover
- Where the question comes from
- Public interview write-ups, reworded by Scrivio; counted 32 times in that collection. How it is counted
- Official documentation
- ArrayList (Java 21), java.util, package documentation
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Print the first n numbers of the Fibonacci sequence.": https://scrivio-interview-library.netlify.app/data-structures/solutions/print-the-first-n-numbers-of-the-fibonacci-sequence-dbded1/