1. Problem
Given a list of strings, return all the strings with the nth longest length in that list.
For example, in the following list, n=1 shall return [Interview], and n=2 shall return [Longest, Contain].
list = [Yuri, Ron, Interview, Longest, List, Contain]
9 Chars - Interview
7 Chars - Longest, Contain
4 Chars - Yuri, List
3 Chars - Ron
Though the 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?
2. Solution
I have written a simple Java program that finds“all Nth longest elements” from a list of strings. It uses a TreeMap to store the length of words as Map key, and all similar length strings in a List as Map value.
import java.util.ArrayList;
import java.util.List;
import java.util.TreeMap;
public class NthLongestStringAlgorithm {
public static void main(String[] args) {
List<String> list = List.of("Yuri", "Ron", "Interview", "Longest", "List", "Contain");
for(int i=1; i<=4; i++){
System.out.println("Words with " + i + "th length: " + findNthLongestElement(list, i));
}
}
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]);
}
}
The program output:
Words with 1th length: [Interview]
Words with 2th length: [Longest, Contain]
Words with 3th length: [Yuri, List]
Words with 4th length: [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
return input.stream() .sorted((s1, s2) -> s2.length() - s1.length()) .limit(n) .collect(Collectors.toList());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 => nulln = 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.