Source : https://www.hackerrank.com/challenges/grid-challenge
Given a square grid of characters in the range ascii[a-z], rearrange elements of each row alphabetically, ascending. Determine if the columns are also in ascending alphabetical order, top to bottom. Return YES
if they are or NO
if they are not.
For example, given:
a b c
a d e
e f g
The rows are already in alphabetical order. The columns a a e
, b d f
and c e g
are also in alphabetical order, so the answer would be YES
. Only elements within the same row can be rearranged. They cannot be moved to a different row.
Function Description
Complete the gridChallenge function in the editor below. It should return a string, either YES
or NO
.
gridChallenge has the following parameter(s):
- grid: an array of strings
Input Format
The first line contains , the number of testcases.
Each of the next sets of lines are described as follows:
- The first line contains , the number of rows and columns in the grid.
- The next lines contains a string of length
Constraints
Each string consists of lowercase letters in the range ascii[a-z]
Output Format
For each test case, on a separate line print YES
if it is possible to rearrange the grid alphabetically ascending in both its rows and columns, or NO
otherwise.
Sample Input
15ebacdfghijolmkntrpqsxywuv
Sample Output
YES
Explanation
The x grid in the test case can be reordered to
abcdefghijklmnopqrstuvwxy
This fulfills the condition since the rows 1, 2, ..., 5 and the columns 1, 2, ..., 5 are all lexicographically sorted.
Source : https://www.hackerrank.com/challenges/grid-challenge
Solution
// Karthikalapati.blogspot.com | |
import java.util.Scanner; | |
import java.util.Arrays; | |
public class Solution { | |
public static void main(String[] args) { | |
Scanner scan = new Scanner(System.in); | |
int T = scan.nextInt(); | |
while (T-- > 0) { | |
int N = scan.nextInt(); | |
char [][] grid = new char[N][N]; | |
for (int i = 0; i < N; i++) { | |
String str = scan.next(); | |
for (int j = 0; j < str.length(); j++) { | |
grid[i][j] = str.charAt(j); | |
} | |
} | |
System.out.println(canConvert(grid) ? "YES" : "NO"); | |
} | |
scan.close(); | |
} | |
/* Uses Greedy Approach */ | |
private static boolean canConvert(char [][] grid) { | |
/* Sort each row */ | |
int rows = grid.length; | |
int cols = grid[0].length; | |
for (int row = 0; row < rows; row++) { | |
Arrays.sort(grid[row]); | |
} | |
/* Check columns for lexicographic ordering */ | |
for (int row = 1; row < rows; row++) { | |
for (int col = 0; col < cols; col++) { | |
if (grid[row][col] < grid[row-1][col]) { | |
return false; | |
} | |
} | |
} | |
return true; | |
} | |
} | |
No comments:
Post a Comment