Saturday, January 29, 2022

Print Decreasing Increasing

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 4
Then Work is sout(5) before and after f(4).


CaseTime ComplexitySpace ComplexityExplanation
All CasesO(n)O(n)One recursive call per level; prints twice per call but stack grows to n

No comments:

Post a Comment

Diagonal Traversal

 eg.  1       2       3       4 5      6       7       8 9    10    11     12 13  14   15    16 Output: 1 6 11 16 2 7 12 3 8 4  Approach:...