Print the longest String in an Array

 Print the longest String in an Array.

Example 1:

N = 5
names[] = { "code", "codes", "codemummy",
  "coding", "coder" }

Output:
codemummy



method 1:

1) initializes two variables: "largest" and "index". "largest" is used to keep track of the length of the longest string seen so far, while "index" is used to keep track of the index of the longest string in the "names" array.

2)loop through each string in the "names" array using a for loop.

3)For each string, check if its length is greater than the current value of "largest". If so, update the values of "largest" and "index" to reflect the new longest string found.

4)Once all strings in the array have been checked, the method returns the string at the index stored in the "index" variable.






Java implementation:

class codemummy {
    String longest(String names[], int n) {
        int largest=0;
        int index =0;
        for(int i=0;i<n;i++){
            if(names[i].length()>largest){
                largest=names[i].length();
                index=i;
            }
        }
        return names[index];
    }
}

 Time Complexity: O(n)
Auxiliary Space: O(1).



c++ implementation:

    string longest(string names[], int n) {
        int largest = 0;
        int index = 0;
        for(int i = 0; i < n; i++) {
            if(names[i].length() > largest) {
                largest = names[i].length();
                index = i;
            }
        }
        return names[index];
    }

 Time Complexity: O(n)
Auxiliary Space: O(1).




python implementation:

    def longest(self, names, n):
        largest = 0
        index = 0
        for i in range(n):
            if len(names[i]) > largest:
                largest = len(names[i])
                index = i
        return names[index]

 Time Complexity: O(n)
Auxiliary Space: O(1).




















No comments

darkmode