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++
// 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
// 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
Python3
# 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#
// 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.
JavaScript
<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>
OutputGeeksforGeeks 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; // 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
// 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
Python3
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()
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>>(); // 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();
}
}
JavaScript
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");
OutputGeeksforGeeks 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) {
// 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
Java
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
Python3
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()
C#
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));
}
}
JavaScript
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(" "));
OutputLongest Names: GeeksforGeeks StackOverFlow
Time Complexity: O(N log N)
Space Complexity: O(1)
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem