HackerRank Grid Challenge Problem Solution
In this post, we will solve HackerRank Grid Challenge Problem Solution.
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.
Example
grid = [abc, ade, efg]
The grid is illustrated below.
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.
gridChallenge has the following parameter(s):
- string grid[n]: an array of strings
Returns
- string: either
YES
orNO
Input Format
The first line contains t, the number of testcases.
Each of the next t sets of lines are described as follows:
– The first line contains n, the number of rows and columns in the grid.
– The next n lines contains a string of length n
utput 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
STDIN Function ----- -------- 1 t = 1 5 n = 5 ebacd grid = ['ebacd', 'fghij', 'olmkn', 'trpqs', 'xywuv'] fghij olmkn trpqs xywuv
Sample Output
YES
Explanation
The 5×5 grid in the 1 test case can be reordered to
abcde
fghij
klmno
pqrst
uvwxy
This fulfills the condition since the rows 1, 2, …, 5 and the columns 1, 2, …, 5 are all alphabetically sorted.
Grid Challenge C Solution
#include<stdio.h>
#include<string.h>
int main()
{
char a[1000][1000],t;
int i,j=0,k,N,u=0,v,T;
scanf("%d",&T);
for(v=0;v<T;v++)
{
scanf("%d",&N);
for(i=0;i<N;i++)
{
scanf("%s",&a[i]);
}
for(i=0;i<N;i++)
{
for(k=0;k<N;k++)
{
for(j=0;j<N-1;j++)
{
if(a[i][j]>a[i][j+1])
{
t=a[i][j];a[i][j]=a[i][j+1];a[i][j+1]=t;
}
}
}
}
for(i=0;i<N;i++)
{
for(k=0;k<N;k++)
{
for(j=0;j<N-1;j++)
{
if(a[i][j]>a[i][j+1])
{
t=a[i][j];a[i][j]=a[i][j+1];a[i][j+1]=t;
}
}
}
}
for(j=0;j<N;j++)
{
for(k=0;k<N;k++)
{
for(i=0,u=0;i<N-1;i++)
{
if(a[i][j]>a[i+1][j])
{ u++;
printf("NO\n");
break;
}
}
if(u!=0) break;
}
if(u!=0) break;
}
if(u==0)printf("YES\n");
}
return 0;
}
Grid Challenge C++ Solution
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
bool Solve(vector<vector<char>>& matrix) {
int n = matrix.size();
for (int i = 0; i < n; i++) {
auto& row = matrix[i];
sort(row.begin(), row.end());
}
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n; j++) {
if (matrix[i][j] > matrix[i+1][j])
return false;
}
}
return true;
}
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
int cases;
cin >> cases;
for (int t = 0; t < cases; t++) {
int n;
cin >> n;
vector<vector<char>> matrix;
for (int i = 0; i < n; i++) {
vector<char> row(n);
for (int j = 0; j < n; j++) {
char c;
cin >> c;
// cin.get(c);
row[j] = c;
}
matrix.push_back(row);
}
bool result = Solve(matrix);
if (result) {
cout << "YES";
} else {
cout << "NO";
}
cout << endl;
}
return 0;
}
Grid Challenge C Sharp Solution
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
class Solution {
static void Main(String[] args) {
int Cases = Int32.Parse(Console.ReadLine());
for (int i = 0; i < Cases; i++) {
int Size = Int32.Parse(Console.ReadLine());
char[][] Input = populateArray(Size);
char[][] Rows = sortRows(Input.Select(x => x.ToArray()).ToArray(), Size);
if (goCompare(Rows, Size))
Console.WriteLine("YES");
else
Console.WriteLine("NO");
}
}
private static char[][] populateArray(int Size) {
char[][] Input = new char[Size][];
for (int i = 0; i < Size; i++)
Input[i] = Console.ReadLine().ToCharArray();
return Input;
}
private static char[][] sortRows(char[][] input, int Size) {
for (int i = 0; i < Size; i++)
Array.Sort(input[i]);
return input;
}
private static Boolean goCompare(char[][] Rows, int Size) {
for (int i = 0; i < Size; i++)
for (int x = 1; x < Size; x++)
if (Rows[x][i] < Rows[x - 1][i])
return false;
return true;
}
}
Grid Challenge Java Solution
import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.*;
import java.util.regex.*;
import java.util.stream.*;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;
class Result {
public static String gridChallenge(List<String> grid) {
char[][] arr = new char[grid.size()][grid.get(0).length()];
for(int i=0;i<grid.size(); i++){
char[] word = grid.get(i).toCharArray();
Arrays.sort(word);
for(int j=0; j<word.length; j++){
arr[i][j] = word[j];
}
}
for(int col=0; col<arr[0].length; col++){
for(int row=0; row<grid.size()-1; row++){
if(arr[row][col] > arr[row+1][col]){
return "NO";
}
}
}
return "YES";
}
}
public class Solution {
public static void main(String[] args) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));
int t = Integer.parseInt(bufferedReader.readLine().trim());
IntStream.range(0, t).forEach(tItr -> {
try {
int n = Integer.parseInt(bufferedReader.readLine().trim());
List<String> grid = IntStream.range(0, n).mapToObj(i -> {
try {
return bufferedReader.readLine();
} catch (IOException ex) {
throw new RuntimeException(ex);
}
})
.collect(toList());
String result = Result.gridChallenge(grid);
bufferedWriter.write(result);
bufferedWriter.newLine();
} catch (IOException ex) {
throw new RuntimeException(ex);
}
});
bufferedReader.close();
bufferedWriter.close();
}
}
Grid Challenge JavaScript Solution
function processData(input) {
const lines = input.split('\n');
const tests = Number(lines[0]);
var curLine = 1;
for (var q = 0; q < tests; q++) {
var n = Number(lines[curLine]);
var arr = [];
for (var i = 0; i < n; i++) {
var cur = lines[curLine + i + 1].split('').sort();
arr.push(cur);
}
var failed = false;
for (var i = 0; i < n - 1 && !failed; i++) {
for (var j = 0; j < n && !failed; j++) {
if (arr[i][j] > arr[i+1][j]) failed = true;
}
}
if (failed) console.log("NO");
else console.log("YES");
curLine += n + 1;
}
}
process.stdin.resume();
process.stdin.setEncoding("ascii");
_input = "";
process.stdin.on("data", function (input) {
_input += input;
});
process.stdin.on("end", function () {
processData(_input);
});
Grid Challenge Python Solution
w=int(input())
sa=0
while sa!=w:
x=int(input())
i=0
k=""
s=[]
while i!=x:
t=[]
k=input("")
for l in k:
t.append(l)
t.sort()
s.append(t)
i+=1
i=0
r=0
while i!=x-1:
if r==1:
break
for k in range(x):
if s[i][k]>s[i+1][k]:
r=1
i+=1
if r==1:
print("NO")
elif r==0:
print("YES")
sa=sa+1