Saturday, January 29, 2022

Print Decreasing

 Input: 

5


Output:

5

4

3

2

1

package jan27;

public class PrintDecreasing {
public static void main(String[] args) {
int n = 5;
printDecreasing(n);
}

/**
* Prints numbers from n down to 1 using recursion.
* <p>
* Time Complexity: O(n)
* - Each recursive call processes one value of n and makes a single recursive call,
* resulting in n calls until the base case (n == 0) is reached.
* <p>
* Space Complexity: O(n)
* - The call stack holds n function calls (from n to 1) before unwinding,
* so space used is proportional to the depth of recursion.
*/
private static void printDecreasing(int n) {
if (n == 0) // base case
return;

System.out.println(n); // work
printDecreasing(n - 1); // recursive call (faith)
}
}

Time and Space Complexity Table

CaseTime ComplexitySpace ComplexityExplanation
BestO(n)O(n)Function calls from n down to 1; recursion depth = n
AverageO(n)O(n)All recursive calls executed once; linear stack usage
WorstO(n)O(n)In all cases, recursion proceeds to base case (n == 0)

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