Grid Challenge Discussions | Algorithms | HackerRank

Grid Challenge

  • + 0 comments

    My Java solution with o(r * c log c) time complexity and o(r) space:

    public static String gridChallenge(List<String> grid) {
            if(grid.size() == 1) return "YES"; //no cols to check
            
            // 1. sort rows alphabetically ascending
            List<String> sortedGrid = new ArrayList<>();
            for(String row : grid){
                char[] chars = row.toCharArray();
                Arrays.sort(chars);
                sortedGrid.add(new String(chars));
            }
            
            // 2. check cols for alphabetically ascending order from top to bottom
            for(int col = 0; col < grid.get(0).length(); col++){
                for(int row = 1; row < grid.size(); row++){
                    String currRow = sortedGrid.get(row);
                    String prevRow = sortedGrid.get(row - 1);
                    //check if col is in order
                    if(currRow.charAt(col) < prevRow.charAt(col)) return "NO";
                }
            }
            return "YES";
        }