BestAverage |
See |
ClosingPrices
Tests
data-syntaxhighlighter-params="brush: java; gutter: false; theme: Confluence" data-theme=Confluence>public class ClosingPrices/*> We need to process a feed. Each line in the feed is either a ticker or a price.For each ticker, we need to report the last (i.e. closing price)> For example:> "007000AA\n" +> "15.47\n" +> "15.48\n" + > "15.49\n" +> "008000BB\n" +> "45.13\n" + > "45.14\n" +> "009000CC\n" +> "89.10\n";> */private MapString, Double closingPrices = new HashMap();private enum EntryType {CUSIP, PRICE, ERROR};>public ClosingPrices(BufferedReader reader) throws IOException> {readInput(reader);}> > private void readInput(BufferedReader reader) throws IOException> {>String line;String lastCusip = "";while((line = reader.readLine()) != null){> line.trim();> if(StringUtils.isBlank(line))> { > continue;> } >EntryType entryType = entryType(line);> if(entryType == EntryType.CUSIP) > { > if(!line.equals(lastCusip))> {> lastCusip = line; > closingPrices.put(line, null);> }> }> else if(entryType == EntryType.PRICE)> {> closingPrices.put(lastCusip, Double.parseDouble(line));> }> }> }> return closingPrices.get(ticker); > }double getClosingPrice(String ticker)> {> {> return EntryType.CUSIP;> }private EntryType entryType(String line){> if(line.matches("[a-zA-Z0-9]{8}"))else if(line.matches("\\d+\\.?\\d+"))> {> return EntryType.PRICE; > }else{> return EntryType.ERROR;> }> }} data-syntaxhighlighter-params="brush: java; gutter: false; theme: Confluence" data-theme=Confluence>static boolean testsPass() throws IOExceptionString input = "007000AA\n" +> "15.47\n" + > "15.48\n" +> "15.49\n" +> "008000BB\n" + > "45.13\n" +> "45.14\n" + > "009000CC\n" +> "89.10\n";> BufferedReader reader = new BufferedReader(new StringReader(input));> ClosingPrices closingPrices = new ClosingPrices(reader);boolean check = closingPrices.getClosingPrice("007000AA") == 15.49 &&pre data-role="codeBlock" data-info="js" class="language-javascript"> closingPrices.getClosingPrice("008000BB") == 45.14;> if(!check)> {> return false;> }return true;}
ConstructItinerary
Tests
data-syntaxhighlighter-params="brush: java; gutter: false; theme: Confluence" data-theme=Confluence>static MapString,String itinerary(MapString,String trips)>/*Consider tripsFrom: To: Itinerary--------- ---------B - C A - B> D - E B - C> A - B C - D> C - D D - E>*/> // Reverse input map > MapString,String reveredMap = trips.entrySet().stream().collect(> Collectors.toMap(Map.Entry::getValue, Map.Entry::getKey));// Starting point will be the key not found in reversed mapSetString startPoint = new HashSet(trips.keySet());> startPoint.removeAll(reveredMap.keySet());> if(startPoint.size() != 1)> {return null;}> String start = startPoint.iterator().next();String end;> MapString,String result = new HashMap();> while((end = trips.get(start)) != null)> {> result.put(start, end); > start = end;> }return result;} data-syntaxhighlighter-params="brush: java; gutter: false; theme: Confluence" data-theme=Confluence>static boolean testsPass()MapString,String trips = new HashMapString,String() {{> put("B", "C");> put("D", "E");> put("A", "B"); > put("C", "D");> }};MapString, String result = itinerary(trips);> boolean check = result.get("A").equals("B") && pre data-role="codeBlock" data-info="js" class="language-javascript"> result.get("B").equals("C") && pre data-role="codeBlock" data-info="js" class="language-javascript"> result.get("C").equals("D") && pre data-role="codeBlock" data-info="js" class="language-javascript"> result.get("D").equals("E");> if(!check) > {> return false;> }return true;}
ConversionsWithStreams
Tests
data-syntaxhighlighter-params="brush: java; gutter: false; theme: Confluence" data-theme=Confluence>staticT MapT, T reverseKeysValues(MapT, T map)> return map.entrySet().stream().collect( > Collectors.toMap(Map.Entry::getValue, Map.Entry::getKey));>} data-syntaxhighlighter-params="brush: java; gutter: false; theme: Confluence" data-theme=Confluence>static boolean testsPass()MapString,String result = reverseKeysValues(new HashMapString,String() {{pre data-role="codeBlock" data-info="js" class="language-javascript"> put("one", "1");> put("two", "2");> put("three", "3");> }});> boolean check = result.get("1").equals("one") &&> result.get("2").equals("two") &&> result.get("3").equals("three");> if(!check)> {> return false; > }return true;}
DictionaryWordCount
Tests
data-syntaxhighlighter-params="brush: java; gutter: false; theme: Confluence" data-theme=Confluence>static MapString,Integer wordCountWithMerge(String dictionary)> String[] words = dictionary.split("\\s+");> return Arrays.stream(words).collect(> HashMap::new, > (m, i) - m.merge(i, 1, Integer::sum),> HashMap::putAll);>}> >static ListString mostFrequentWord(String dictionary)> MapString,Integer map = wordCountWithMerge(dictionary); > int mostUsedCount = map.values().stream().mapToInt(x -x).max().getAsInt();> return map.entrySet().stream()> .filter(e - e.getValue() == mostUsedCount)> .map(Map.Entry::getKey)> .collect(Collectors.toList());>}data-syntaxhighlighter-params="brush: java; gutter: false; theme: Confluence" data-theme=Confluence>static MapString,Long wordCountWithCounting(String dictionary)> String[] words = dictionary.split("\\s+");> return Arrays.stream(words).collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));>} data-syntaxhighlighter-params="brush: java; gutter: false; theme: Confluence" data-theme=Confluence>static boolean testsPass()MapString,Long result1 = wordCountWithCounting("one two one three two one one");> boolean check = result1.get("one") == 4 && result1.get("two") == 2 && result1.get("three") == > if(!check)pre data-role="codeBlock" data-info="js" class="language-javascript"> {> return false;> }MapString,Integer result2 = wordCountWithMerge("one two one three two one one");> check = result2.get("one") == 4 && result2.get("two") == 2 && result2.get("three") == 1;> if(!check) > {> return false;> }check = mostFrequentWord("one two one three two one one").get(0).equals("one");> if(!check) > {> return false;> }return true;}
FractionToDecimal
Tests
data-syntaxhighlighter-params="brush: java; gutter: false; theme: Confluence" data-theme=Confluence>static String fractionToDecimal(int n, int d)// Numerator = 1, Denominator = 2 - "0.5"> // Numerator = 2, Denominator = 1 - "2"> // Numerator = 2, Denominator = 3 - "0.(6)">/* >Consider: 2/3> map >rem result key value>20 0. 20 2>*/if(n == 0){> return "0";> }if(d == 0){> return "";> }String result = "";if((n 0) ^ (d 0)){> result += "-";> }> n = Math.abs(n);> d = Math.abs(d); > result += n / d;> // Remainder> int rem = n % d * 10;> if(rem == 0)> {return result;}> result += ".";> MapInteger, Integer map = new HashMap();while(rem != 0){> if(map.containsKey(rem))> {> int beg = map.get(rem); > String part1 = result.substring(0, beg);> String part2 = result.substring(beg); > result = part1 + "(" + part2 + ")";return result;}> map.put(rem, result.length());> result += rem / d;> rem = rem % d * 10;> }return result;} data-syntaxhighlighter-params="brush: java; gutter: false; theme: Confluence" data-theme=Confluence>static boolean testsPass()boolean check = fractionToDecimal(1, 2).equals("0.5");> if(!check){return false;> }> check = fractionToDecimal(2, 1).equals("2");> if(!check)> {return false;}> check = fractionToDecimal(2, 3).equals("0.(6)");if(!check){> return false;> }return true;}
LengthOfCycle
Tests
data-syntaxhighlighter-params="brush: java; gutter: false; theme: Confluence" data-theme=Confluence>static int lengthOfCycle(int[] a, int startIndex)// You are given an integer array of size N.// Every element of the array is greater than or equal to 0.>// Starting from arr[startIndex], follow each element to the index it points to.>// Continue to do this until you find a cycle.// Return the length of the cycle. If no cycle is found return -1//>// Examples:>// countLengthOfCycle([1, 0], 0) == 2>// countLengthOfCycle([1, 2, 0], 0) == 3> MapInteger, Integer visitedMap = new HashMap();> int count = 1;> int index = startIndex;> while(!visitedMap.containsKey(index)) > {if(a[index] a.length){> return -1;> }> visitedMap.put(index, count++);> index = a[index];> }return count - visitedMap.get(index);} data-syntaxhighlighter-params="brush: java; gutter: false; theme: Confluence" data-theme=Confluence>static boolean testsPass()boolean check = lengthOfCycle(new int[] {1, 2, 0}, 0) == 3;> if(!check){return false;> }> return true;}
LongestString
Tests
data-syntaxhighlighter-params="brush: java; gutter: false; theme: Confluence" data-theme=Confluence>static int lengthLongestSubstringLengthWithNUnique(String s, int n)> // "abcbbbbcccbdddadacb", 2 - "bcbbbbcccb"> int max = 0, start = 0;> MapCharacter,Integer map = new HashMap();for(int i = 0; i s.length(); ++i){> char c = s.charAt(i);> map.merge(c, 1, Integer::sum);> if(map.size() n)> {> max = Math.max(max, i - start);> while(map.size() n)> {> c = s.charAt(start); > int count = map.get(c);> if(count 1)> { > map.put(c, count - 1);> }> else> { > map.remove(c);> }> start++;> }}}> return Math.max(max, s.length() - start);>}data-syntaxhighlighter-params="brush: java; gutter: false; theme: Confluence" data-theme=Confluence>static String longestSubstringLengthWithNUnique(String s, int n)> // "abcbbbbcccbdddadacb", 2 - "bcbbbbcccb"> int max = 0, start = 0;> String maxStr = "";> MapCharacter,Integer map = new HashMap();for(int i = 0; i s.length(); ++i){> char c = s.charAt(i);> map.merge(c, 1, Integer::sum);> if(map.size() n)> {> if(i - start max) > {> max = i - start;> maxStr = s.substring(start, i); > }> max = Math.max(max, i - start); > while(map.size() n)> {> c = s.charAt(start); > int count = map.get(c);> if(count 1)> { > map.put(c, count - 1);> }> else> { > map.remove(c);> }> start++;> } > }}if(s.length() - start max)> {> max = s.length() - start; > maxStr = s.substring(start, start + max);> }> return maxStr;>} data-syntaxhighlighter-params="brush: java; gutter: false; theme: Confluence" data-theme=Confluence>static boolean testsPass()boolean check = lengthLongestSubstringLengthWithNUnique("abcbbbbcccbdddadacb", 2) == 10;> if(!check) > {> return false;> }check = longestSubstringLengthWithNUnique("abcbbbbcccbdddadacb", 2).equals("bcbbbbcccb");> if(!check)> {> return false;> }return true;}
SortLogFile
Tests
data-syntaxhighlighter-params="brush: java; gutter: false; theme: Confluence" data-theme=Confluence>static ListString sortMessages(String[] messages)>/*Message is preceded by ID.Messages containing text should come before messages containing all numbers> If two messages are same, they should be ordered by their ID> Unsorted Sorted> -------- ------> "A3 one two three"; "A2 hello world";"A2 hello world"; "A4 hello world";> "B2 3 5 8 12"; "A1 one two three";> "A1 one two three"; "A3 one two three";"B1 5 2 19"; "B2 3 5 8 12";> "A4 hello world"; "B1 5 2 19";>*/> MapString, SortedSetString stringMessageMap = new TreeMap();MapString, SortedSetString numberMessageMap = new TreeMap();> for(String s : messages) > {String[] a = s.split("\\s+");> String id = a[0];> String message = s.substring(id.length()).trim();> if(message.matches("^[\\d ]*$"))> { > numberMessageMap.computeIfAbsent(message, x - new TreeSet()).add(id);}> else> {> stringMessageMap.computeIfAbsent(message, x - new TreeSet()).add(id);}> }> ListString result = new ArrayList();> for(String message : stringMessageMap.keySet())> {> SortedSetString ids = stringMessageMap.get(message);> for(String id : ids)> {> result.add(id + " " + message);> }> }for(String message : numberMessageMap.keySet())> {SortedSetString ids = numberMessageMap.get(message);> for(String id : ids) > { > result.add(id + " " + message);> }> }return result;} data-syntaxhighlighter-params="brush: java; gutter: false; theme: Confluence" data-theme=Confluence>static boolean testsPass()String [] data = new String[] {"A3 one two three","A2 hello world","B2 3 5 8 12","A1 one two three","B1 5 2 19","A4 hello world"};> ListString sorted = sortMessages(data);boolean check = sorted.get(0).equals("A2 hello world") &&> sorted.get(1).equals("A4 hello world") &&> sorted.get(2).equals("A1 one two three") && > sorted.get(3).equals("A3 one two three") && > sorted.get(4).equals("B2 3 5 8 12") && > sorted.get(5).equals("B1 5 2 19");> if(!check) > {> return false;> }return true;}