package jan22;
import java.util.Scanner;
public class SpiralDisplay {
public static void main(String[] args) {
// Declare a 2D array with 3 rows and 4 columns
// Space Complexity: O(m * n), where m = 3, n = 4
int[][] arr = new int[3][4];
Scanner scanner = new Scanner(System.in); // Constant space (O(1)) for Scanner object
// Input loop to fill the 2D array
// Time Complexity: O(m * n), every element is read once
for (int i = 0; i < arr.length; i++) { // Loop over m rows
for (int j = 0; j < arr[0].length; j++) { // Loop over n columns
arr[i][j] = scanner.nextInt(); // Input each element (O(1))
}
}
spiralDisplay(arr); // Call method to print in diagonal wave order
}
private static void spiralDisplay(int[][] arr) {
int column = 0;
// First phase: traverse from top row diagonally down-right
// Total iterations: m diagonals from first column
for (int row = 0; row < arr.length; row++) {
int tempRow = row, tempCol = column;
while (tempRow >= 0 && tempCol < arr[0].length) { // Stay within bounds
System.out.print(arr[tempRow--][tempCol++] + " "); // Diagonal up-left
}
}
int row = arr.length - 1;
// Second phase: traverse from top row's second column to end, diagonally
for (int col = 1; col < arr[0].length; col++) {
int tempRow = row, tempCol = col;
while (tempCol < arr[0].length && tempRow >= 0) { // Stay within bounds
System.out.print(arr[tempRow--][tempCol++] + " "); // Diagonal up-left
}
}
}
}
Complexity Best Case Average Case Worst Case Explanation TC O(m × n) O(m × n) O(m × n) Each element is printed exactly once diagonally SC O(m × n) O(m × n) O(m × n) For storing input array; no extra space used
Saturday, May 3, 2025
Spiral Display of 2D Array
Subscribe to:
Post Comments (Atom)
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:...
-
I/P: 24 10 20 50 -1 60 -1 -1 30 70 -1 80 110 -1 120 -1 -1 90 -1 -1 40 100 -1 -1 -1 O/P: 10 20 30 40 50 60 70 80 90 100 110 120 import ja...
-
https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/description/ Given the sorted rotated array nums of unique elements, retu...
-
O(1) < O(log n) < O(n) < O(n log n) < O(n ^ 2) ..... < O(2 ^ n) < O(n!) Try to keep TC till O(n ^ 2) ====================...
No comments:
Post a Comment