# Puzzle – Return all the strings with the Nth longest length

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>();

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>();
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 !!

### 7 thoughts on “Puzzle – Return all the strings with the Nth longest length”

1. 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]);
}

2. Using stream

```return input.stream()
.sorted((s1, s2) -> s2.length() - s1.length())
.limit(n)
.collect(Collectors.toList());
```
3. 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]`

4. it will always return elements from position n-1.

5. Hi Lokesh,

1 problem though. It will always return null. The if condition will always be true.