Grid Challenge Discussions | | HackerRank

Grid Challenge

  • + 0 comments

    Java 15 using streams, some utils and early return for NO result:

    class Cache<K, V> {
        protected final HashMap<K, V> storage = new HashMap<>();
        
        public Function<K, V> memoize(Function<K, V> func) {
            return k -> storage.computeIfAbsent(k, func);
        }
    }
    
    class StreamUtils {
        public static <T> Stream<ArrayList<T>> sliding(Stream<T> stream, int n) {
            // Use LinkedList to store the sliding window
            var window = new LinkedList<T>();
    
            // Use flatMap to emit the window after each element
            return stream.flatMap(curr -> {
                window.add(curr); // Add current element to window
                if (window.size() > n) {
                    window.removeFirst(); // Remove oldest element
                }
                if (window.size() == n) {
                    return Stream.of(new ArrayList<>(window)); // Emit window
                }
                return Stream.empty(); // Skip until window is full
            });
        }
    
        public static <T> boolean isSorted(Stream<T> stream, Comparator<? super T> comparator) {
            return StreamUtils.sliding(stream, 2).allMatch(window -> {
                return comparator.compare(window.get(0), window.get(1)) <= 0;
            });
        }
    }
    
    class Result {
    
        public static String gridChallenge(List<String> grid) {
            var nRows = grid.size();
            assert 1 <= nRows && nRows <= 100;
            // the question lies about input being square - nRows != nCols in third test case;
            // we need to find nCols separately
            var nCols = grid.get(0).length();
            
            var getSortedRow = new Cache<Integer, String>().memoize(i -> {
                var row = grid.get(i);
                var sorted = row.chars().sorted().collect(
                    StringBuilder::new,
                    StringBuilder::appendCodePoint,
                    StringBuilder::append
                ).toString();
                return sorted;
            });
            
            var cols = IntStream.range(0, nCols).mapToObj(j ->
                IntStream.range(0, nRows).map(i -> getSortedRow.apply(i).charAt(j))
            );
            var allColsSorted = cols.allMatch(col ->
                StreamUtils.isSorted(col.boxed(), Comparator.naturalOrder())
            );
                
            return allColsSorted ? "YES" : "NO";
        }
    }