Input:
- 1 2 3 4
- 5 6 7 8
- 9 10 11 12
- 13 14 15 16
Output:
- 1 5 9 13 14 15 16 12 8 4 3 2 6 10 11 7
package jan22;
import java.util.Scanner;
public class SpriralTraversal {
public static void main(String[] args) {
// Initialize a 4x4 2D array (matrix)
// SC: O(m * n), where m = 4 and n = 4
int[][] arr = new int[4][4];
Scanner scanner = new Scanner(System.in); // SC: O(1) for Scanner
// Input loop to fill the 2D array
// TC: O(m * n) because we read each element once
for (int i = 0; i < arr.length; i++) { // O(m)
for (int j = 0; j < arr[0].length; j++) { // O(n)
arr[i][j] = scanner.nextInt(); // O(1)
}
}
ringRotate1(arr); // TC: O(m * n), SC: O(1) extra
}
private static void ringRotate1(int[][] arr) {
int r = arr.length;
int c = arr[0].length;
// Total elements to be processed
int totalNumberElements = r * c; // O(1)
// Initialize boundary pointers
int minRow = 0, maxRow = arr.length - 1;
int minCol = 0, maxCol = arr[0].length - 1;
// TC: O(m * n) - each element is printed exactly once
// SC: O(1) - no extra space used other than variables
while (totalNumberElements > 0) {
// Traverse from top to bottom in left column
for (int i = minRow; i <= maxRow && totalNumberElements > 0; i++) {
System.out.print(arr[i][minCol] + " ");
totalNumberElements--;
}
minCol++;
// Traverse from left to right in bottom row
for (int i = minCol; i <= maxCol && totalNumberElements > 0; i++) {
System.out.print(arr[maxRow][i] + " ");
totalNumberElements--;
}
maxRow--;
// Traverse from bottom to top in right column
for (int i = maxRow; i >= minRow && totalNumberElements > 0; i--) {
System.out.print(arr[i][maxCol] + " ");
totalNumberElements--;
}
maxCol--;
// Traverse from right to left in top row
for (int i = maxCol; i >= minCol && totalNumberElements > 0; i--) {
System.out.print(arr[minRow][i] + " ");
totalNumberElements--;
}
minRow++;
}
}
}
📊 Time & Space Complexity Summary
| Complexity Type | Value | Notes |
|---|
| Time Complexity | O(m × n) | Every element in the matrix is printed exactly once |
| Space Complexity | O(m × n) | For input matrix size (4×4 here), no extra space used |
| Extra Space Used | O(1) | Only loop counters and boundary variables |
| Case | Time Complexity | Reason |
|---|
| Best Case | O(m × n) | You always need to traverse all elements at least once. |
| Average Case | O(m × n) | The spiral pattern does not skip or reduce processing of elements. |
| Worst Case | O(m × n) | Even if the values are all the same or follow any pattern, traversal remains same. |
No comments:
Post a Comment