Skip to content

Instantly share code, notes, and snippets.

@anil477
Created May 17, 2017 15:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anil477/d7410c21e61cdf7fc7479d6a09493bac to your computer and use it in GitHub Desktop.
Save anil477/d7410c21e61cdf7fc7479d6a09493bac to your computer and use it in GitHub Desktop.
Write a function fib() that a takes an integer n, and returns the nth fibonacci number.
// N time and O(1)O(1) space
import java.util.Map;
import java.util.HashMap;
class Fibber {
Map<Integer, Integer> memo = new HashMap<Integer, Integer>();
public int fib(int n) {
// edge case: negative index
if (n < 0) {
throw new IllegalArgumentException("Index was negative. No such thing as a negative index in a series.");
}
// base case: 0 or 1
else if (n == 0 || n == 1) {
return n;
}
// see if we've already calculated this
if (memo.containsKey(n)) {
return memo.get(n);
}
int result = fib(n-1) + fib(n-2);
// memoize
memo.put(n, result);
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment