Find Largest and Smallest word in a given String

Objective: Given a String, write a program to find largest and smallest word in it.

Example:

Input String: test
Smallest Word: test
Largest Word: test
------------------
Input String: This problem is solved at Algorithms tutorial horizon
Smallest Word: is
Largest Word: Algorithms

Approach:

Do a single traversal and keep track of longest ad smallest words using word lengths.

See the code for more understanding, it is self explanatory.

Code:

Output:

Input String: test
Smallest Word: test
Largest Word: test
------------------
Input String: This problem is solved at Algorithms tutorial horizon
Smallest Word: is
Largest Word: Algorithms

__________________________________________________
Top Companies Interview Questions..-

Google Microsoft Amazon Facebook more..

If you find anything incorrect or you feel that there is any better approach to solve the above problem, please write comment.
__________________________________________________

You may also like...

1 Response

  1. Archit says:

    A rather Short solution
    Tme complexity : O(nLogn)


    static void findLongestAndShortest(String[] words) {
    Arrays.sort(words,Comparator.comparing(String::length));
    System.out.println("smallest word : " + words[0]);
    System.out.println("longest word:" + words[words.length-1]);
    }

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: