0
function gridChallenge(grid) {
    let sortedRows = [];
    for(let i = 0; i < grid.length; i++){
        let sortedRow = grid[i].split('').sort().join('')
        sortedRows.push(sortedRow)

    }

    let columns = []
    let sortedColumns = columns.sort()
    for(let z = 0; z < sortedRows.length; z++){
        let column = sortedRows[z].split('')[0]
        columns.push(column)
    }

    if(columns === sortedColumns){
        console.log("YES")
    } else {
        console.log("NO")
    }
}

The code is working completely fine in the IDE and showing the expected output but when I tried to run the same code in HackerRank it is showing that the code is giving undefined as output. And I've also tried with other problems it is giving the same result.

Link of the problem: https://www.hackerrank.com/challenges/one-week-preparation-kit-grid-challenge/problem?isFullScreen=true&h_l=interview&playlist_slugs%5B%5D=preparation-kits&playlist_slugs%5B%5D=one-week-preparation-kit&playlist_slugs%5B%5D=one-week-day-four

tasin000
  • 3
  • 3
  • 4
    Your *function* returns `undefined` because you haven't included any logic to return anything out of it. Assuming [this](https://www.hackerrank.com/challenges/grid-challenge/problem) is the problem you're trying to solve, the prompt explicitly mentions an expectation that the function will return a string `YES` or `NO` - simply logging that string will not suffice. – esqew Apr 27 '23 at 16:59

1 Answers1

0

HackerRank does not work on console output... technically it does, but in a different way than what you're thinking. HackerRank will have code that it executes. That code will call your gridChallenge function. Next, it will print the result of your function. That is what HackerRank accepts as the "solution."

In JavaScript, like any other programming language, you have a return keyword to pass a value from the function to the caller of the function. You made the common mistake of printing the solution rather than returning the value of the solution.

This might seem misleading because the problem clearly states that you must print YES or NO on separate lines... that must have been a mistake on their part because in the code editor, it provides a doc-comment clearly stating the contrary:

/*
 * Complete the 'gridChallenge' function below.
 *
 * The function is expected to return a STRING.
 * The function accepts STRING_ARRAY grid as parameter.
 */

function gridChallenge(grid) {
    // Write your code here

}
Viraj Shah
  • 754
  • 5
  • 19