Skip to content

Commit a7a8e0d

Browse files
committed
finds kth smallest element in sorted 2d array
1 parent 0cf0903 commit a7a8e0d

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
package DailyChallenges.JulyChallenges;
2+
3+
import java.util.Arrays;
4+
5+
public class KthSmallestElementInSortedMatrix {
6+
7+
public static int kthSmallest(int[][] matrix, int k) {
8+
9+
int rows = matrix.length, cols = matrix[0].length;
10+
11+
if (rows == cols && k == 1)
12+
return matrix[0][0];
13+
14+
int[] allData = new int[rows * cols];
15+
int idx = 0;
16+
17+
for (int ro = 0; ro < rows; ro++) {
18+
19+
for (int col = 0; col < cols; col++) {
20+
allData[idx] = matrix[ro][col];
21+
idx++;
22+
}
23+
}
24+
25+
Arrays.sort(allData);
26+
27+
return allData[k - 1];
28+
}
29+
30+
public static void main(String[] args) {
31+
int[][] matrix = { { 1, 5, 9 }, { 10, 11, 13 }, { 12, 13, 15 } };
32+
int k = 8;
33+
System.out.println(kthSmallest(matrix, k));
34+
35+
int[][] matrix2 = { { -5 } };
36+
37+
System.out.println(kthSmallest(matrix2, 1));
38+
}
39+
}

0 commit comments

Comments
Β (0)