Grid Challenge Discussions | | HackerRank

Grid Challenge

  • + 0 comments

    There is no way to run out of O(n²) because of the column's checking, but follow a O(n) way to sort each row's string,

    function gridChallenge(grid) {
        for (let i = 0; i < grid.length; i++) {
            grid[i] = sortString(grid[i]);
        }
        let answer = 'YES';
        for (let idr = 1; idr < grid.length; idr++) {
            for (let idc = 0; idc < grid[0].length; idc++) {
                if (grid[idr][idc] < grid[idr-1][idc]) {
                    answer = 'NO';
                    break;
                }
            }
        }
        return answer;
    }
    
    function sortString(str) {
        const ALPHABET_SIZE = 26;
        const charCount = Array(ALPHABET_SIZE).fill(0);
        const asciiStartLowercase = "a".charCodeAt(0);
    
        for (const char of str) {
            charCount[char.charCodeAt(0) - asciiStartLowercase]++;
        }
    
        let sortedStr = "";
        for (let i = 0; i < charCount.length; i++) {
            if (charCount[i] > 0) {
                sortedStr += String.fromCharCode(i + asciiStartLowercase).repeat(charCount[i]);
            }
        }
        return sortedStr;
    }