Skip to content
Related Articles
Open in App
Not now

Related Articles

Display the Longest Name

Improve Article
Save Article
  • Last Updated : 20 Sep, 2022
Improve Article
Save Article

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>
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.


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!