Interview 150
Fibonacci Number
- Problem
- LC 509
- File
- interview150_LC509FibonacciNumber.java
- Path
- pkg5leetcode/interview150/interview150_LC509FibonacciNumber.java
- Package
- pkg5leetcode.interview150
- Command
- java pkg5leetcode/interview150/interview150_LC509FibonacciNumber.java
- Approach
- Iterative DP with two previous values.
- Complexity
- Time O(n), Space O(1)
There is no in-browser runner. This is the file from the curriculum, unchanged.
1package pkg5leetcode.interview150;2 3/*4 * Fibonacci Number | LC 5095 * APPROACH: Iterative DP with two previous values.6 * COMPLEXITY: Time O(n), Space O(1)7 */8public class interview150_LC509FibonacciNumber {9 static int fib(int n) {10 if (n <= 1) return n;11 int a = 0, b = 1;12 for (int i = 2; i <= n; i++) {13 int c = a + b;14 a = b;15 b = c;16 }17 return b;18 }19 20 public static void main(String[] args) {21 check(fib(2) == 1, "case1");22 check(fib(3) == 2, "case2");23 check(fib(4) == 3, "case3");24 System.out.println("all tests passed");25 }26 27 static void check(boolean cond, String name) {28 if (!cond) throw new AssertionError("FAILED: " + name);29 System.out.println(" PASS " + name);30 }31}