Anti Diagonals - The Coding Shala

Home >> Interview Questions >> Anti Diagonals

Anti Diagonals Java Solution

Give an N*N square matrix, return an array of its anti-diagonals. Look at the example for more details.
Example:
``````
Input:
1 2 3

7 8 9
4 5 6

Return the following :
[
[1],
[2, 4],  [3, 5, 7],
[6, 8],
[9]

]
``````
```
Input :
```1 2
3 4

Return the following  :
[
[1],
[2, 3],
[4]

]
``````

Anti Diagonals Java Solution

 ``` 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31``` ```public class Solution { public ArrayList> diagonal(ArrayList> A) { ArrayList> ans = new ArrayList>(); int N = A.size(); int i = N - 1; while(i>=0){ ArrayList tmp = new ArrayList(); int row = 0, col = N-i-1; for(int j=0;j=0){ int row = N-i-1, col = N-1; ArrayList tmp = new ArrayList(); for(int j=0;j<=i;j++){ tmp.add(A.get(row).get(col)); row++; col--; } ans.add(tmp); i--; } return ans; } } ```

Other Posts You May Like

1. how can i solve this using array and not using collection framework classes

1. Change ArrayList to Array and all logic and process will be same, since return type is ArrayList so before returning you have to copy Array into ArrayList again that will be additional changes.

2. how can we change ArrayList to array having variable columns?

1. public class Solution {
public int[][] diagonal(int[][] a) {
int n = a.length-1;
ArrayList> otp = new ArrayList<>();

for(int i=0; i temp = new ArrayList<>();
int row = 0, col = i;
while(col >= 0) {
row++;
col--;
}
}

for(int i=1; i temp = new ArrayList<>();
int row = i, col = n-1;
while(row < n) {
row++;
col--;
}
}
int[][] otpArray = new int[n+n-1][n+n-1];
for(int i=0; i<otp.size(); i++)
for(int j=0; j<otp.get(i).size(); j++)
otpArray[i][j] = otp.get(i).get(j);

return otpArray;
}
}

2. Its giving :
[1 0 0 ] [2 4 0 ] [5 0 0 ]

But it should:
[1 ] [2 4 ] [3 5 7 ] [6 8 ] [9 ]