Saturday, January 29, 2022

Print Increasing Decreasing

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:

CaseTime ComplexitySpace ComplexityExplanation
All CasesO(n)O(n)One recursive call per lev

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:...