Input: 5
Output: 1,2,3,4,5
package jan27;
public class PrintIncreasing {
public static void main(String[] args) {
int n = 5;
printIncreasing(n); // Expectation
}
/**
* Prints numbers from 1 to n using recursion.
*
* Time Complexity: O(n)
* - One recursive call per number from n to 1 before reaching the base case.
*
* Space Complexity: O(n)
* - Due to recursive calls, the call stack grows to depth n before starting to unwind.
*/
private static void printIncreasing(int n) {
if (n == 0) // Base Case
return;
printIncreasing(n - 1); // Faith
System.out.println(n); // Work
// Pehle FAITH call hoga, then WORK hoga
// f(4) apna kaam kr kr laega, then hum 'n' print kr denge
// Hence, FAITH and WORK should be dependent on n
}
}
| Case | Time Complexity | Space Complexity | Explanation |
|---|---|---|---|
| All Cases | O(n) | O(n) | One call per level until base case; stack grows to n |
No comments:
Post a Comment