Display the Longest Name
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:
- 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++ code for the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to display longest names
// contained in the array
vector<string> solve(string* arr, int N)
{
// Edge Case
if (N == 0)
return {};
// Initialize Max
int Max = arr[0].size();
// Create an array res
vector<string> res;
// Insert first element in res
res.push_back(arr[0]);
// Traverse the array
for (int i = 1; i < N; i++) {
// If string with greater length
// is found
if (arr[i].size() > Max) {
Max = arr[i].size();
res.clear();
res.push_back(arr[i]);
}
// If string with current max length
else if (arr[i].size() == Max) {
res.push_back(arr[i]);
}
}
// Return the final answer
return res;
}
// Driver Code
int main()
{
string arr[] = { "GeeksforGeeks", "FreeCodeCamp",
"StackOverFlow", "MyCodeSchool" };
int N = sizeof(arr) / sizeof(arr[0]);
// Function call
vector<string> v = solve(arr, N);
// Printing the answer
for (auto i : v) {
cout << i << " ";
}
cout << endl;
return 0;
}
// Java code for the above approach
import java.io.*;
import java.util.*;
class GFG
{
// Function to display longest names
// contained in the array
public static ArrayList<String> solve(String arr[],
int N)
{
// Edge Case
if (N == 0) {
ArrayList<String> temp
= new ArrayList<String>();
return temp;
}
// Initialize Max
int Max = arr[0].length();
// Create an arraylist res
ArrayList<String> res = new ArrayList<String>();
// Insert first element in res
res.add(arr[0]);
// Traverse the array
for (int i = 1; i < N; i++) {
// If string with greater length
// is found
if (arr[i].length() > Max) {
Max = arr[i].length();
res.clear();
res.add(arr[i]);
}
// If string with current max length
else if (arr[i].length() == Max) {
res.add(arr[i]);
}
}
// Return the final answer
return res;
}
// Driver Code
public static void main(String[] args)
{
String arr[] = { "GeeksforGeeks", "FreeCodeCamp",
"StackOverFlow", "MyCodeSchool" };
int N = arr.length;
// Function call
ArrayList<String> v = solve(arr, N);
// Printing the answer
for (String i : v) {
System.out.print(i + " ");
}
System.out.println();
}
}
// This code is contributed by Rohit Pradhan
# Python code for the above approach
# Function to display longest names
# contained in the array
def solve(arr, N):
# Edge Case
if (N == 0):
return []
# Initialize Max
Max = len(arr[0])
# Create an array res
res = []
# Insert first element in res
res.append(arr[0])
# Traverse the array
for i in range(1,N):
# If string with greater length
# is found
if (len(arr[i]) > Max):
Max = len(arr[i])
res.clear()
res.append(arr[i]);
# If string with current max length
elif(len(arr[i]) == Max):
res.append(arr[i])
# Return the final answer
return res
# Driver Code
if __name__ == "__main__":
arr = ["GeeksforGeeks", "FreeCodeCamp", "StackOverFlow", "MyCodeSchool"]
# Value of N
N = len(arr)
# Function call
v = solve(arr, N)
# Printing the answer
for i in v:
print(i,end=" ")
# This code is contributed by Abhishek Thakur.
// C# code to implement the approach
using System;
using System.Collections.Generic;
class GFG
{
// Function to display longest names
// contained in the array
public static List<string> solve(string[] arr,
int N)
{
// Edge Case
if (N == 0) {
List<string> temp
= new List<string>();
return temp;
}
// Initialize Max
int Max = arr[0].Length;
// Create an List res
List<string> res = new List<string>();
// Insert first element in res
res.Add(arr[0]);
// Traverse the array
for (int i = 1; i < N; i++) {
// If string with greater length
// is found
if (arr[i].Length > Max) {
Max = arr[i].Length;
res.Clear();
res.Add(arr[i]);
}
// If string with current max length
else if (arr[i].Length == Max) {
res.Add(arr[i]);
}
}
// Return the final answer
return res;
}
// Driver Code
public static void Main()
{
string[] arr = { "GeeksforGeeks", "FreeCodeCamp",
"StackOverFlow", "MyCodeSchool" };
int N = arr.Length;
// Function call
List<string> v = solve(arr, N);
// Printing the answer
foreach (string i in v) {
Console.Write(i + " ");
}
Console.WriteLine();
}
}
// This code is contributed by code_hunt.
<script>
// JS code for the above approach
// Function to display longest names
// contained in the array
function solve(arr,N)
{
// Edge Case
if (N == 0)
return [];
// Initialize Max
let Max = arr[0].length;
// Create an array res
res = [];
// Insert first element in res
res.push(arr[0]);
// Traverse the array
for (let i = 1; i < N; i++) {
// If string with greater length
// is found
if (arr[i].length > Max) {
Max = arr[i].length;
res = [];
res.push(arr[i]);
}
// If string with current max length
else if (arr[i].length == Max) {
res.push(arr[i]);
}
}
// Return the final answer
return res;
}
// Driver Code
let arr = [ "GeeksforGeeks", "FreeCodeCamp",
"StackOverFlow", "MyCodeSchool" ];
let N = arr.length;
// Function call
let v = solve(arr, N);
// Printing the answer
console.log(v);
// This code is contributed by akashish__
</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:
#include <bits/stdc++.h>
using namespace std;
vector<string> findLongestNames(const vector<string>& arr) {
int maxLen = 0;
unordered_map<int, vector<string>> lengthMap; // Hash map to store names grouped by their lengths
// Iterate through each name in the array
for (const string& name : arr) {
int len = name.length(); // Calculate the length of the current name
// Update the hash map with the current name added to its corresponding length group
lengthMap[len].push_back(name);
// Update maxLen if the current length is greater
if (len > maxLen) {
maxLen = len;
}
}
// Retrieve all the names from the hash map for the length maxLen
return lengthMap[maxLen];
}
// Driver Code
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;
}
// This code is contributed by Veerendra_Singh_Rajpoot
// Java code to Display the Longest Name Using Hashing
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Main {
// Function to display longest names
public static List<String>
findLongestNames(List<String> arr)
{
int maxLen = 0;
Map<Integer, List<String> > lengthMap
= new HashMap<>(); // Hash map to store names
// grouped by their lengths
// Iterate through each name in the list
for (String it : arr) {
int len = it.length(); // Calculate the length
// of the current name
// Update the hash map with the current name
// added to its corresponding length group
List<String> namesList = lengthMap.getOrDefault(
len, new ArrayList<>());
namesList.add(it);
lengthMap.put(len, namesList);
// Update maxLen if the current length is
// greater
if (len > maxLen) {
maxLen = len;
}
}
// Retrieve all the names from the hash map for the
// length maxLen
return lengthMap.get(maxLen);
}
// Driver Code
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();
}
}
// This code is contributed by Veerendra_Singh_Rajpoot
def findLongestNames(arr):
# Hash map to store names grouped by their lengths
maxLen = 0
lengthMap = {}
# Iterate through each name in the array
for name in arr:
# Calculate the length of the current name
length = len(name)
# Update the hash map with the current name added to its corresponding length group
if length in lengthMap:
lengthMap[length].append(name)
else:
lengthMap[length] = [name]
# Update maxLen if the current length is greater
if length > maxLen:
maxLen = length
# Retrieve all the names from the hash map for the length maxLen
return lengthMap[maxLen]
# Test case
arr = ["GeeksforGeeks", "FreeCodeCamp", "StackOverFlow", "MyCodeSchool"]
longestNames = findLongestNames(arr)
for name in longestNames:
print(name, end=" ")
print()
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>>(); // Dictionary to store names grouped by their lengths
// Iterate through each name in the array
foreach (string name in arr) {
int len = name.Length; // Calculate the length of the current name
// Update the dictionary with the current name added to its corresponding length group
if (!lengthMap.ContainsKey(len)) {
lengthMap[len] = new List<string>();
}
lengthMap[len].Add(name);
// Update maxLen if the current length is greater
if (len > maxLen) {
maxLen = len;
}
}
// Retrieve all the names from the dictionary for the length maxLen
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();
}
}
function findLongestNames(arr) {
let maxLen = 0;
// Hash map to store names grouped by their lengths
let lengthMap = {};
// Iterate through each name in the array
for (let name of arr) {
// Calculate the length of the current name
let length = name.length;
// Update the hash map with the current name added to its corresponding length group
if (length in lengthMap) {
lengthMap[length].push(name);
} else {
lengthMap[length] = [name];
}
// Update maxLen if the current length is greater
if (length > maxLen) {
maxLen = length;
}
}
// Retrieve all the names from the hash map for the length maxLen
return lengthMap[maxLen];
}
// Test case
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:
#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) {
// Create a copy of the input array to avoid modifying the original
vector<string> sortedArr = arr;
// Sort the array in descending order of length
sort(sortedArr.begin(), sortedArr.end(), compareByLength);
// Find the length of the first (longest) name
int maxLength = sortedArr[0].length();
// Initialize a vector to store the longest names
vector<string> longestNames;
// Iterate through the sorted array and add names with the same length as the first name
for (const string& name : sortedArr) {
if (name.length() == maxLength) {
longestNames.push_back(name);
} else {
break; // Names are sorted by length, so we can stop when a shorter name is encountered
}
}
return longestNames;
}
//Driver code
int main() {
// Input array of names
vector<string> arr = {"GeeksforGeeks", "FreeCodeCamp", "StackOverFlow", "MyCodeSchool"};
// Call the function to find the longest names
vector<string> longestNames = findLongestNames(arr);
// Print the longest names
cout << "Longest Names: ";
for (const string& name : longestNames) {
cout << name << " ";
}
cout << endl;
return 0;
}
//This Code is contributed by Veerendra_Singh_Rajpoot
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class LongestNamesFinder {
public static void main(String[] args) {
// Input array of names
List<String> arr = List.of("GeeksforGeeks", "FreeCodeCamp", "StackOverFlow", "MyCodeSchool");
// Call the function to find the longest names
List<String> longestNames = findLongestNames(arr);
// Print the longest names
System.out.print("Longest Names: ");
for (String name : longestNames) {
System.out.print(name + " ");
}
System.out.println();
}
private static List<String> findLongestNames(List<String> arr) {
// Create a copy of the input list to avoid modifying the original
List<String> sortedArr = new ArrayList<>(arr);
// Sort the list in descending order of length
Collections.sort(sortedArr, (a, b) -> Integer.compare(b.length(), a.length()));
// Find the length of the first (longest) name
int maxLength = sortedArr.get(0).length();
// Initialize a list to store the longest names
List<String> longestNames = new ArrayList<>();
// Iterate through the sorted list and add names with the same length as the first name
for (String name : sortedArr) {
if (name.length() == maxLength) {
longestNames.add(name);
} else {
break; // Names are sorted by length, so we can stop when a shorter name is encountered
}
}
return longestNames;
}
}
//this code is contributed by utkarsh
def find_longest_names(arr):
# Sort the list in descending order of length
sorted_arr = sorted(arr, key=lambda x: len(x), reverse=True)
# Find the length of the first (longest) name
max_length = len(sorted_arr[0])
# Initialize a list to store the longest names
longest_names = []
# Iterate through the sorted list and add names with the same length as the first name
for name in sorted_arr:
if len(name) == max_length:
longest_names.append(name)
else:
break # Names are sorted by length, so we can stop when a shorter name is encountered
return longest_names
def main():
# Input list of names
arr = ["GeeksforGeeks", "FreeCodeCamp", "StackOverFlow", "MyCodeSchool"]
# Call the function to find the longest names
longest_names = find_longest_names(arr)
# Print the longest names
print("Longest Names:", *longest_names)
if __name__ == "__main__":
main()
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static List<string> FindLongestNames(List<string> names)
{
// Create a copy of the input list to avoid modifying the original
List<string> sortedNames = new List<string>(names);
// Sort the list in descending order of length
sortedNames.Sort((a, b) => b.Length.CompareTo(a.Length));
// Find the length of the first (longest) name
int maxLength = sortedNames[0].Length;
// Initialize a list to store the longest names
List<string> longestNames = new List<string>();
// Iterate through the sorted list and add names with the same length as the first name
foreach (string name in sortedNames)
{
if (name.Length == maxLength)
{
longestNames.Add(name);
}
else
{
break; // Names are sorted by length, so we can stop when a shorter name is encountered
}
}
return longestNames;
}
static void Main()
{
// Input list of names
List<string> names = new List<string> { "GeeksforGeeks", "FreeCodeCamp", "StackOverFlow", "MyCodeSchool" };
// Call the function to find the longest names
List<string> longestNames = FindLongestNames(names);
// Print the longest names
Console.Write("Longest Names: ");
Console.WriteLine(string.Join(" ", longestNames));
}
}
function compareByLength(a, b) {
return b.length - a.length;
}
function findLongestNames(arr) {
// Create a copy of the input array to avoid modifying the original
const sortedArr = [...arr];
// Sort the array in descending order of length
sortedArr.sort(compareByLength);
// Find the length of the first (longest) name
const maxLength = sortedArr[0].length;
// Initialize an array to store the longest names
const longestNames = [];
// Iterate through the sorted array and add names with the same length as the first name
for (const name of sortedArr) {
if (name.length === maxLength) {
longestNames.push(name);
} else {
break; // Names are sorted by length, so we can stop when a shorter name is encountered
}
}
return longestNames;
}
// Driver code
const arr = ["GeeksforGeeks", "FreeCodeCamp", "StackOverFlow", "MyCodeSchool"];
// Call the function to find the longest names
const longestNames = findLongestNames(arr);
// Print the longest names
console.log("Longest Names: " + longestNames.join(" "));
Output
Longest Names: GeeksforGeeks StackOverFlow
Time Complexity: O(N log N)
Space Complexity: O(1)