Display the Longest Name
Last Updated :
27 Dec, 2023
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:
C++
#include <bits/stdc++.h>
using namespace std;
vector<string> solve(string* arr, int N)
{
if (N == 0)
return {};
int Max = arr[0].size();
vector<string> res;
res.push_back(arr[0]);
for ( int i = 1; i < N; i++) {
if (arr[i].size() > Max) {
Max = arr[i].size();
res.clear();
res.push_back(arr[i]);
}
else if (arr[i].size() == Max) {
res.push_back(arr[i]);
}
}
return res;
}
int main()
{
string arr[] = { "GeeksforGeeks" , "FreeCodeCamp" ,
"StackOverFlow" , "MyCodeSchool" };
int N = sizeof (arr) / sizeof (arr[0]);
vector<string> v = solve(arr, N);
for ( auto i : v) {
cout << i << " " ;
}
cout << endl;
return 0;
}
|
Java
import java.io.*;
import java.util.*;
class GFG
{
public static ArrayList<String> solve(String arr[],
int N)
{
if (N == 0 ) {
ArrayList<String> temp
= new ArrayList<String>();
return temp;
}
int Max = arr[ 0 ].length();
ArrayList<String> res = new ArrayList<String>();
res.add(arr[ 0 ]);
for ( int i = 1 ; i < N; i++) {
if (arr[i].length() > Max) {
Max = arr[i].length();
res.clear();
res.add(arr[i]);
}
else if (arr[i].length() == Max) {
res.add(arr[i]);
}
}
return res;
}
public static void main(String[] args)
{
String arr[] = { "GeeksforGeeks" , "FreeCodeCamp" ,
"StackOverFlow" , "MyCodeSchool" };
int N = arr.length;
ArrayList<String> v = solve(arr, N);
for (String i : v) {
System.out.print(i + " " );
}
System.out.println();
}
}
|
Python3
def solve(arr, N):
if (N = = 0 ):
return []
Max = len (arr[ 0 ])
res = []
res.append(arr[ 0 ])
for i in range ( 1 ,N):
if ( len (arr[i]) > Max ):
Max = len (arr[i])
res.clear()
res.append(arr[i]);
elif ( len (arr[i]) = = Max ):
res.append(arr[i])
return res
if __name__ = = "__main__" :
arr = [ "GeeksforGeeks" , "FreeCodeCamp" , "StackOverFlow" , "MyCodeSchool" ]
N = len (arr)
v = solve(arr, N)
for i in v:
print (i,end = " " )
|
C#
using System;
using System.Collections.Generic;
class GFG
{
public static List< string > solve( string [] arr,
int N)
{
if (N == 0) {
List< string > temp
= new List< string >();
return temp;
}
int Max = arr[0].Length;
List< string > res = new List< string >();
res.Add(arr[0]);
for ( int i = 1; i < N; i++) {
if (arr[i].Length > Max) {
Max = arr[i].Length;
res.Clear();
res.Add(arr[i]);
}
else if (arr[i].Length == Max) {
res.Add(arr[i]);
}
}
return res;
}
public static void Main()
{
string [] arr = { "GeeksforGeeks" , "FreeCodeCamp" ,
"StackOverFlow" , "MyCodeSchool" };
int N = arr.Length;
List< string > v = solve(arr, N);
foreach ( string i in v) {
Console.Write(i + " " );
}
Console.WriteLine();
}
}
|
Javascript
<script>
function solve(arr,N)
{
if (N == 0)
return [];
let Max = arr[0].length;
res = [];
res.push(arr[0]);
for (let i = 1; i < N; i++) {
if (arr[i].length > Max) {
Max = arr[i].length;
res = [];
res.push(arr[i]);
}
else if (arr[i].length == Max) {
res.push(arr[i]);
}
}
return res;
}
let arr = [ "GeeksforGeeks" , "FreeCodeCamp" ,
"StackOverFlow" , "MyCodeSchool" ];
let N = arr.length;
let v = solve(arr, N);
console.log(v);
</script>
|
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:
- Create a hash map to store names grouped by their lengths, and a variable maxLen to store the length of longest string.
- Iterate through each name in the input array.
- Calculate the length of the current name.
- Update the hash map with the current name added to its corresponding length group.
- Update maxLen if the current length is greater.
- Retrieve all the names from the hash map for the length maxLen.
Below is the implementation:
C++
#include <bits/stdc++.h>
using namespace std;
vector<string> findLongestNames( const vector<string>& arr) {
int maxLen = 0;
unordered_map< int , vector<string>> lengthMap;
for ( const string& name : arr) {
int len = name.length();
lengthMap[len].push_back(name);
if (len > maxLen) {
maxLen = len;
}
}
return lengthMap[maxLen];
}
int main() {
vector<string> arr = { "GeeksforGeeks" , "FreeCodeCamp" , "StackOverFlow" , "MyCodeSchool" };
vector<string> longestNames = findLongestNames(arr);
for ( const string& name : longestNames) {
cout << name << " " ;
}
cout << endl;
return 0;
}
|
Java
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Main {
public static List<String>
findLongestNames(List<String> arr)
{
int maxLen = 0 ;
Map<Integer, List<String> > lengthMap
= new HashMap<>();
for (String it : arr) {
int len = it.length();
List<String> namesList = lengthMap.getOrDefault(
len, new ArrayList<>());
namesList.add(it);
lengthMap.put(len, namesList);
if (len > maxLen) {
maxLen = len;
}
}
return lengthMap.get(maxLen);
}
public static void main(String[] args)
{
List<String> arr
= List.of( "GeeksforGeeks" , "FreeCodeCamp" ,
"StackOverFlow" , "MyCodeSchool" );
List<String> longestNames = findLongestNames(arr);
for (String name : longestNames) {
System.out.print(name + " " );
}
System.out.println();
}
}
|
Python3
def findLongestNames(arr):
maxLen = 0
lengthMap = {}
for name in arr:
length = len (name)
if length in lengthMap:
lengthMap[length].append(name)
else :
lengthMap[length] = [name]
if length > maxLen:
maxLen = length
return lengthMap[maxLen]
arr = [ "GeeksforGeeks" , "FreeCodeCamp" , "StackOverFlow" , "MyCodeSchool" ]
longestNames = findLongestNames(arr)
for name in longestNames:
print (name, end = " " )
print ()
|
C#
using System;
using System.Collections.Generic;
class Gfg {
static List< string > findLongestNames(List< string > arr) {
int maxLen = 0;
Dictionary< int , List< string >> lengthMap = new Dictionary< int , List< string >>();
foreach ( string name in arr) {
int len = name.Length;
if (!lengthMap.ContainsKey(len)) {
lengthMap[len] = new List< string >();
}
lengthMap[len].Add(name);
if (len > maxLen) {
maxLen = len;
}
}
return lengthMap[maxLen];
}
static void Main( string [] args) {
List< string > arr = new List< string > { "GeeksforGeeks" , "FreeCodeCamp" , "StackOverFlow" , "MyCodeSchool" };
List< string > longestNames = findLongestNames(arr);
foreach ( string name in longestNames) {
Console.Write(name + " " );
}
Console.WriteLine();
}
}
|
Javascript
function findLongestNames(arr) {
let maxLen = 0;
let lengthMap = {};
for (let name of arr) {
let length = name.length;
if (length in lengthMap) {
lengthMap[length].push(name);
} else {
lengthMap[length] = [name];
}
if (length > maxLen) {
maxLen = length;
}
}
return lengthMap[maxLen];
}
let arr = [ "GeeksforGeeks" , "FreeCodeCamp" , "StackOverFlow" , "MyCodeSchool" ];
let longestNames = findLongestNames(arr);
for (let name of longestNames) {
console.log(name + " " );
}
console.log( "\n" );
|
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:
C++
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
bool compareByLength( const string& a, const string& b) {
return a.length() > b.length();
}
vector<string> findLongestNames( const vector<string>& arr) {
vector<string> sortedArr = arr;
sort(sortedArr.begin(), sortedArr.end(), compareByLength);
int maxLength = sortedArr[0].length();
vector<string> longestNames;
for ( const string& name : sortedArr) {
if (name.length() == maxLength) {
longestNames.push_back(name);
} else {
break ;
}
}
return longestNames;
}
int main() {
vector<string> arr = { "GeeksforGeeks" , "FreeCodeCamp" , "StackOverFlow" , "MyCodeSchool" };
vector<string> longestNames = findLongestNames(arr);
cout << "Longest Names: " ;
for ( const string& name : longestNames) {
cout << name << " " ;
}
cout << endl;
return 0;
}
|
Java
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class LongestNamesFinder {
public static void main(String[] args) {
List<String> arr = List.of( "GeeksforGeeks" , "FreeCodeCamp" , "StackOverFlow" , "MyCodeSchool" );
List<String> longestNames = findLongestNames(arr);
System.out.print( "Longest Names: " );
for (String name : longestNames) {
System.out.print(name + " " );
}
System.out.println();
}
private static List<String> findLongestNames(List<String> arr) {
List<String> sortedArr = new ArrayList<>(arr);
Collections.sort(sortedArr, (a, b) -> Integer.compare(b.length(), a.length()));
int maxLength = sortedArr.get( 0 ).length();
List<String> longestNames = new ArrayList<>();
for (String name : sortedArr) {
if (name.length() == maxLength) {
longestNames.add(name);
} else {
break ;
}
}
return longestNames;
}
}
|
Python3
def find_longest_names(arr):
sorted_arr = sorted (arr, key = lambda x: len (x), reverse = True )
max_length = len (sorted_arr[ 0 ])
longest_names = []
for name in sorted_arr:
if len (name) = = max_length:
longest_names.append(name)
else :
break
return longest_names
def main():
arr = [ "GeeksforGeeks" , "FreeCodeCamp" , "StackOverFlow" , "MyCodeSchool" ]
longest_names = find_longest_names(arr)
print ( "Longest Names:" , * longest_names)
if __name__ = = "__main__" :
main()
|
C#
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static List< string > FindLongestNames(List< string > names)
{
List< string > sortedNames = new List< string >(names);
sortedNames.Sort((a, b) => b.Length.CompareTo(a.Length));
int maxLength = sortedNames[0].Length;
List< string > longestNames = new List< string >();
foreach ( string name in sortedNames)
{
if (name.Length == maxLength)
{
longestNames.Add(name);
}
else
{
break ;
}
}
return longestNames;
}
static void Main()
{
List< string > names = new List< string > { "GeeksforGeeks" , "FreeCodeCamp" , "StackOverFlow" , "MyCodeSchool" };
List< string > longestNames = FindLongestNames(names);
Console.Write( "Longest Names: " );
Console.WriteLine( string .Join( " " , longestNames));
}
}
|
Javascript
function compareByLength(a, b) {
return b.length - a.length;
}
function findLongestNames(arr) {
const sortedArr = [...arr];
sortedArr.sort(compareByLength);
const maxLength = sortedArr[0].length;
const longestNames = [];
for (const name of sortedArr) {
if (name.length === maxLength) {
longestNames.push(name);
} else {
break ;
}
}
return longestNames;
}
const arr = [ "GeeksforGeeks" , "FreeCodeCamp" , "StackOverFlow" , "MyCodeSchool" ];
const longestNames = findLongestNames(arr);
console.log( "Longest Names: " + longestNames.join( " " ));
|
Output
Longest Names: GeeksforGeeks StackOverFlow
Time Complexity: O(N log N)
Space Complexity: O(1)
Share your thoughts in the comments
Please Login to comment...