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

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

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

    Reply
  2. Using stream

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

      Reply

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.