Friday, May 2, 2025

Wave Printing a two Dimensional Array

Input:
  • 1 2 3
  • 4 5 6

Output:

  • 1 4 5 2 3 6 


package jan22;  // Package name

import java.util.Scanner; // Importing Scanner for user input

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

// Declare a 2D array with 2 rows and 3 columns
// SC: O(m * n), where m = 2, n = 3
int[][] arr = new int[2][3];

Scanner scanner = new Scanner(System.in); // Create Scanner object

// Input loop to fill the 2D array
// TC: O(m * n), each element is read once
for (int i = 0; i < arr.length; i++) { // O(m) loop over rows
for (int j = 0; j < arr[0].length; j++) { // O(n) loop over columns
arr[i][j] = scanner.nextInt(); // O(1) input per element
}
}

// Call wave traversal
wave(arr); // TC: O(m * n)
}

public static void wave(int[][] arr) {
int column = 0; // Start from the first column

// Traverse each column
// Outer loop: TC = O(n) where n is number of columns
while (column < arr[0].length) {

if (column % 2 == 0) {
// Even column: top to bottom traversal
// Inner loop: TC = O(m)
for (int row = 0; row < arr.length; row++) {
System.out.print(arr[row][column] + " ");
}
} else {
// Odd column: bottom to top traversal
// Inner loop: TC = O(m)
for (int row = arr.length - 1; row >= 0; row--) {
System.out.print(arr[row][column] + " ");
}
}

column++; // Move to next column
}
}
}


/*
Total Time Complexity: O(m * n)
- Input reading: O(m * n)
- Wave printing: O(m * n)

Total Space Complexity: O(m * n)
- 2D array of m rows and n columns
- No additional data structures used
*/


ComplexityBest CaseAverage CaseWorst CaseExplanation
TCO(m × n)O(m × n)O(m × n)                Each element is read and printed once
SCO(m × n)O(m × n)O(m × n)                Space for storing all elements in the array


private static void method2(int[][] arr) {

int noe = arr.length * arr[0].length;

int col = 0;
while (noe > 0) {

for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i][col] + " ");
noe--;
}

col++;
for (int i = arr.length - 1; i >= 0; i--) {
System.out.print(arr[i][col] + " ");
noe--;
}

col++;


}
}

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