Algorithm: given a list of strings, return all the strings with the nth longest length in that list for example: list – Yuri, Ron, Interview, Longest, List, Contain
and nth = 1 will return just “Interview” whereas nth = 2 will return both “Longest” and “Contain”.
Though solution to “How to find the kth largest element in an unsorted array of length n in O(n)?” can be applied to string length, how to translate back to print all the strings with n length?
Solution
I have written a simple java program which is able to find “all Nth longest elements” from a list of strings. Program is as below:
package com.howtodoinjava.examples; import java.util.ArrayList; import java.util.List; import java.util.TreeMap; public class NthLogestStringAlgorithm { public static void main(String[] args) { int n = 0; List<String> list = new ArrayList<String>(); list.add("Yuri"); list.add("Ron"); list.add("Interview"); list.add("Longest"); list.add("List"); list.add("Contain"); System.out.println( findNthLongestElement(list, n) ); } private static List<String> findNthLongestElement(List<String> list, int n) { if(n < 1) { return null; //Handle invalid case } TreeMap<Integer, List<String>> map = new TreeMap<>(); for(String str : list) { Integer length = str.length(); List<String> tempList = map.get(length) != null ? map.get(length) : new ArrayList<String>(); tempList.add(str); map.put(length, tempList); } return map.get( map.descendingKeySet().toArray()[n-1] ); } }
========Output of program======= n = 0 => null n = 1 => [Interview] n = 2 => [Longest, Contain] n = 3 => [Yuri, List] n = 4 => [Ron]
Happy Learning !!
Leave a Reply