703206. Display longest name

Basic

Display Longest Name

Summary

Given an array of names, find and display the longest name. The problem requires understanding arrays and strings.

Detailed Explanation

The approach to this problem is straightforward: iterate through the array of names, compare the length of each name, and store the longest one. Here's a step-by-step breakdown:

  1. Initialize a variable longest_name to store the longest name found so far.
  2. Iterate through the array of names using a for loop or any other suitable iteration method.
  3. For each name in the array:
    • Calculate its length using the length() function (in languages that support it) or by manually counting characters.
    • Compare the length of the current name with the length of the longest name found so far (longest_name).
    • If the current name is longer, update longest_name to be the current name.
  4. After iterating through all names, display the longest name found.

Time and Space Complexity

The time complexity of this algorithm is O(n), where n is the number of names in the array, since we need to iterate through each name once. The space complexity is O(1) because we only use a constant amount of space to store the longest name found.

Optimized Solutions

Java

View on GeeksforGeeks
public class DisplayLongestName {
    public static void main(String[] args) {
        String[] names = {"John", "Jane", "Jim", "Jessica"};
        String longest_name = "";
        for (String name : names) {
            if (name.length() > longest_name.length()) {
                longest_name = name;
            }
        }
        System.out.println("The longest name is: " + longest_name);
    }
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.