VOOZH about

URL: https://www.geeksforgeeks.org/dsa/display-the-longest-name/

⇱ Display the Longest Name - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Display the Longest Name

Last Updated : 23 Jul, 2025

Given a list of names in an array arr[] of size N, display the longest name contained in it. If there are multiple longest names print all of that.

Examples:

Input: arr[] = {"GeeksforGeeks", "FreeCodeCamp", "StackOverFlow",  "MyCodeSchool"}
Output: GeeksforGeeks StackOverFlow
Explanation: size of arr[0] and arr[2] i.e., 13 > size of arr[1]  and arr[3] i.e., 12

Input:  arr[] = {"Akash", "Adr"}
Output: Akash

Approach: Follow the given idea to solve the problem:

Traverse the given array and store the names with the maximum length, if a name with greater length is found update max length and add that name to the final answer.

Follow the steps to solve this problem:

  • If N = 0 then simply return.
  • Create an array res to store the answer.
  • Else, Initialize Max = size of arr[0]  and insert arr[0] in the res.
  • Now, Traverse the array and check
    • If size of arr[i] = Max, then push back arr[i] in vector res.
    • Else If size of arr[i] > Max, then
      • Set, Max = size of arr[i]
      • Empty the array res 
      • Insert arr[i] in res
  • Return res as the final answer

Below is the implementation of the above approach:


Output
GeeksforGeeks StackOverFlow 

Time Complexity: O(N), where N is the size of the given array.
Auxiliary Space: O(N), for storing the names in the res array.

Another Approach: Hashing

We can make a hash-map of key-value pair where key will be length of string and value will be the string themself. This allows us to quickly access the longest names by retrieving the group with the maximum length.

Follow the steps to implement the above idea:

  1. Create a hash map to store names grouped by their lengths, and a variable maxLen to store the length of longest string.
  2. Iterate through each name in the input array.
  3. Calculate the length of the current name.
  4. Update the hash map with the current name added to its corresponding length group.
  5. Update maxLen if the current length is greater.
  6. Retrieve all the names from the hash map for the length maxLen.

Below is the implementation:


Output
GeeksforGeeks StackOverFlow 

Time Complexity: O(N), where N is the size of the given array.
Auxiliary Space: O(N), for hash map

Sorting Approach:

Sort the array of names in descending order of length. Then, iterate through the sorted array and print all names with the same length as the first name in the sorted array (which will be the longest).

Below is the implementation:


Output
Longest Names: GeeksforGeeks StackOverFlow 

Time Complexity: O(N log N)

Space Complexity: O(1)

Comment
Article Tags:
Article Tags: