Input: 5
Output: 5 4 3 2 1 1 2 3 4 5
package jan27;
public class DecreasingIncreasing {
public static void main(String[] args) {
int n = 5;
decreasingIncreasing(n); // Output: 5 4 3 2 1 1 2 3 4 5
}
/**
* Prints numbers in decreasing then increasing order using recursion.
*
* Time Complexity: O(n)
* - One recursive call for each n down to 1, and two print operations per level.
* - But still linear because print is constant time.
*
* Space Complexity: O(n)
* - Due to recursive call stack growing to depth n before unwinding.
*/
private static void decreasingIncreasing(int n) {
if (n == 0) // BASE CASE
return;
System.out.println(n); // WORK (before recursive call)
decreasingIncreasing(n - 1); // FAITH
System.out.println(n); // WORK (after recursive call)
}
}
Expectation is f(5) => f(4) will print 4 3 2 1 1 2 3 4Then Work is sout(5) before and after f(4).
| Case | Time Complexity | Space Complexity | Explanation |
|---|---|---|---|
| All Cases | O(n) | O(n) | One recursive call per level; prints twice per call but stack grows to n |
No comments:
Post a Comment