Solution of Grid Challenge in Hackerrank
Hi Everyone!!! In this article I will discuss the challenges in Hackerrank, namely the Grid Challenge. The questions for the Grid Challenge are as follows:
From the challenge there is an input array of strings. from the array of strings we are instructed to sort each row alphabetically, but not the columns. After that we are instructed to check whether the order from top to bottom is in alphabetic order or not, YES
if it is in order and No
if it is not.
Explanation:
Suppose there is an input as follows:
a b d
f k c
g e r
We sort each row alphabetically, so it looks like this:
a b d // alredy alphabetic
c f k
e g r
The first row does not change because it is already sorted alphabetically.
Because the rows are sorted, we only need to check whether the grid is also sorted when checked from top to bottom.
// from Top
a b d
c f k
e g r
// to Bottom
a
, c
, e
are alphabetic. b
, f
, g
are alphabetic. d
, k
, r
are alphabetic. So the answer to the above input is YES
.
The answer to the above challenge is as follows:
- We need to sort each string from the array alphabetically.
- After sorting, we need to loop each array and string so that we get the order from top to bottom.
- After that we check whether the letter of the looped one is now larger or smaller than the letter below it. If it is bigger then it means it is out of order so we return “
NO
”.
More or less for the logic of the function as above, here is the code using the Go language:
func isColumnOrderedAlphabetic(grid []string) bool{
for i := 0 ; i < len(grid[0]); i++ {
for j := 0; j < len(grid); j++ {
if j < len(grid) - 1 && rune(grid[j][i]) > rune(grid[j+1][i]) {
return false
}
}
}
return true
}
func gridChallenge(grid []string) string {
// Write your code here
// Sorting
for i := 0; i< len(grid); i++{
wordRune := []rune(grid[i])
sort.Slice(wordRune, func(i, j int) bool {
return wordRune[i] < wordRune[j]
})
grid[i] = string(wordRune)
}
// End Sorting
if isColumnOrderedAlphabetic(grid) {
return "YES"
}
return "NO"
}
I think that’s all I can share about the solution to the Grid Challenge from Hackerrank, I hope this article can be useful for you and for myself. Thank you for reading this article and see you again in my next article.
Let’s connect: Linkedin