Display longest name

Display longest name

Difficulty: BasicAccuracy: 66.29%Submissions: 78K+Points: 1Average Time: 15m

Given an array arr[] containing strings of names. Your task is to return the longest string. If there are multiple names of the longest size, return the first occurring name.

Examples :

Input: arr[] = ["Geek", "Geeks", "Geeksfor", "GeeksforGeek", "GeeksforGeeks"]
Output: "GeeksforGeeks"
Explanation: name "GeeksforGeeks" has maximum length among all names. 
        
Input: arr[] = ["Apple", "Mango", "Orange", "Banana"]
Output: "Orange"
Explanation: names "Orange" and "Banana" both have maximum length among all names but Orange comes first so answer will be "Orange".         

Constraints:

1 <= arr.size()<= 1000

1 <= arr[i] <= 1000

arr[i] has only lowercase and uppercase letters


Here, we first iterate over each item of the array and calculate length of each string - and, log these length for each with the item in a dictionary. Later, we will find the max and return the item.

    def longest(self, arr):
        # code here
        
        size = {}
        
        for item in arr:
            size[item] = len(item)        
        item = max(size, key = size.get)
        
        return item        


To view or add a comment, sign in

More articles by Kumar Preeti Lata

Explore content categories