Skip to content

Commit ad8a05b

Browse files
committed
1137. N-th Tribonacci Number (Iterative)
1 parent 48fc241 commit ad8a05b

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
package com.cheehwatang.leetcode;
2+
3+
// Time Complexity : O(n),
4+
// where 'n' is the input 'n'.
5+
// We traverse from 3 to 'n' to calculate the n-th tribonacci number.
6+
//
7+
// Space Complexity : O(1),
8+
// as the auxiliary space used is independent of the input.
9+
10+
public class NthTribonacciNumber_Iterative {
11+
12+
// Approach:
13+
// We use the iterative method, using the variable 'first', 'second' and 'third' to keep track.
14+
15+
public int tribonacci(int n) {
16+
if (n == 0 || n == 1) return n;
17+
if (n == 2) return 1;
18+
19+
// As we need both 'n - 1', 'n - 2' and 'n - 3' to start, record 'first', 'second' and 'third', respectively.
20+
// For each iteration until n, sum all three numbers and replace the numbers.
21+
int first = 1;
22+
int second = 1;
23+
int third = 0;
24+
int result = 0;
25+
for (int i = 3; i <= n; i++) {
26+
result = first + second + third;
27+
third = second;
28+
second = first;
29+
first = result;
30+
}
31+
return result;
32+
}
33+
}

0 commit comments

Comments
 (0)