Java Puzzle – Return All Strings with the Nth Longest Length

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

Sourcecode on Github


Notify of
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode