Input: 5
Output: 1 2 3 4 5 5 4 3 2 1
package jan27;
public class IncreasingDecreasing {
public static void main(String[] args) {
int n = 5;
increasingDecreasing(1, n); // EXPECTATION: 1 2 3 4 5 5 4 3 2 1
}
/**
* Prints numbers in increasing and then decreasing order using recursion.
*
* Time Complexity: O(n)
* - Each number from 1 to n is printed twice (before and after recursion).
* - But overall complexity is still O(n) since print is O(1).
*
* Space Complexity: O(n)
* - Due to recursive call stack that grows from 1 to n.
*/
private static void increasingDecreasing(int val, int n) {
if (val > n) return; // BASE CASE
System.out.println(val); // WORK (increasing part)
increasingDecreasing(val + 1, n); // FAITH
System.out.println(val); // WORK (decreasing part)
}
}
Expectataion of f(1,n) => FAITH f(2, n) it will print 2 3 4 5 5 4 3 2
Then before and after f(2, n) we'll print '1' as WORK
📊 Summary Table:
Case Time Complexity Space Complexity Explanation All Cases O(n) O(n) One recursive call per lev
No comments:
Post a Comment