![]() |
VOOZH | about |
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., 12Input: 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:
Below is the implementation of the above approach:
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.
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:
Below is the implementation:
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:
Longest Names: GeeksforGeeks StackOverFlow
Time Complexity: O(N log N)
Space Complexity: O(1)