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 !!
similar solution
public static List getLongestNthString(List strings, int n) {
TreeMap<Integer, List> grouped = strings.stream().collect(
Collectors.groupingBy(
String::length,
TreeMap::new,
Collectors.toList()));
return grouped.get(grouped.descendingKeySet().toArray()[n – 1]);
}
Using stream
if i remove interview it will return yuri and list
I am not sure how you are testing the program. I removed Interview from the list and these are new outputs:
n = 0 => null
n = 1 => [Longest, Contain]
n = 2 => [Yuri, List]
n = 3 => [Ron]
it will always return elements from position n-1.
Hi Lokesh,
1 problem though. It will always return null. The if condition will always be true.
Indeed, if you do not change the value of n in main() function.