Monday, May 19, 2025

Zig Zag

 

1. Here are a few sets of inputs and outputs for your reference

Input1 -> 1

Output1 -> 111


Input2 -> 2

Output2 -> 211121112


Input2 -> 3

Output3 -> 3 21112111232111211123


2. Figure out the pattern and complete the recursive function pzz to achieve the above for any positive

number n.

Input Format

A number n

Output Format

As discussed in point 1 of description



package jan27;

public class ZigZag {
public static void main(String[] args) {

int n = 2;

pzz(n); // EXPECTATION
}

/**
* Prints numbers in a zig-zag recursive pattern:
* - Prints n three times: pre-order, in-order, and post-order
* - Calls itself twice with n-1
*
* Time Complexity: O(2^n)
* - Each call makes 2 recursive calls, doubling calls at each level
* - Total calls grow exponentially with n
*
* Space Complexity: O(n)
* - Maximum recursion depth is n
*/
private static void pzz(int n) {
if (n == 0) return;

// WORK: pre-order
System.out.print(n + " ");

// FAITH
pzz(n - 1);

// WORK: in-order
System.out.print(n + " ");

// FAITH
pzz(n - 1);

// WORK: post-order
System.out.print(n + " ");
}
}

CaseTime ComplexitySpace ComplexityExplanation
Best CaseO(2^n)O(n)Recursive calls always happen twice, recursion depth is n
Average CaseO(2^n)O(n)Same as best case, recursion structure doesn’t change
Worst CaseO(2^n)O(n)Same as best case, all calls are made


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