We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
Java 15 using streams, some utils and early return for NO result:
classCache<K,V>{protectedfinalHashMap<K,V>storage=newHashMap<>();publicFunction<K,V>memoize(Function<K,V>func){returnk->storage.computeIfAbsent(k,func);}}classStreamUtils{publicstatic<T>Stream<ArrayList<T>>sliding(Stream<T>stream,intn){// Use LinkedList to store the sliding windowvarwindow=newLinkedList<T>();// Use flatMap to emit the window after each elementreturnstream.flatMap(curr->{window.add(curr);// Add current element to windowif(window.size()>n){window.removeFirst();// Remove oldest element}if(window.size()==n){returnStream.of(newArrayList<>(window));// Emit window}returnStream.empty();// Skip until window is full});}publicstatic<T>booleanisSorted(Stream<T>stream,Comparator<?superT>comparator){returnStreamUtils.sliding(stream,2).allMatch(window->{returncomparator.compare(window.get(0),window.get(1))<=0;});}}classResult{publicstaticStringgridChallenge(List<String>grid){varnRows=grid.size();assert1<=nRows&&nRows<=100;// the question lies about input being square - nRows != nCols in third test case;// we need to find nCols separatelyvarnCols=grid.get(0).length();vargetSortedRow=newCache<Integer,String>().memoize(i->{varrow=grid.get(i);varsorted=row.chars().sorted().collect(StringBuilder::new,StringBuilder::appendCodePoint,StringBuilder::append).toString();returnsorted;});varcols=IntStream.range(0,nCols).mapToObj(j->IntStream.range(0,nRows).map(i->getSortedRow.apply(i).charAt(j)));varallColsSorted=cols.allMatch(col->StreamUtils.isSorted(col.boxed(),Comparator.naturalOrder()));returnallColsSorted?"YES":"NO";}}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Grid Challenge
You are viewing a single comment's thread. Return to all comments →
Java 15 using streams, some utils and early return for NO result: