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:...
-
https://leetcode.com/problems/reverse-integer/description/ Integer.MAX_VALUE = 2,147,483,647 = 2 31 - 1 Integer.MIN_VALUE = -2,147,483,64...
-
https://leetcode.com/problems/two-sum/description/ Given the constraints: 2 <= nums.length <= 10⁴ -10⁹ <= nums[i] <= 10⁹ -10...
-
For this particular question, we only have the In - region. So, the code looks like : package pep.Day7 ; public class TowerOfHanoi { p...
No comments:
Post a Comment