Find the Second Shortest Word in a Sentence in Java
Finding the second shortest word in a sentence means identifying the word whose length is greater than the shortest word but smaller than all other words.
This problem improves understanding of string traversal, comparisons, and edge case handling without relying on built-in string utilities.
Understanding the Problem
Given a sentence, we must:
- Extract words manually from the sentence.
- Track the shortest and second shortest words.
- Compare word lengths dynamically.
Example 1
Input: Java is very easy to learn
Output: is
Example 2
Input: Find the second shortest word
Output: the
Logic Explanation
- Traverse the sentence character by character.
- Build each word until a space is found.
- Compare word length with shortest and second shortest.
- Update values accordingly.
- Check the last word after the loop.
Java Program to Find the Second Shortest Word
import java.util.Scanner;
public class SecondShortestWord {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a sentence: ");
String str = sc.nextLine();
String word = "";
String shortest = "";
String secondShortest = "";
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if (ch != ' ') {
word = word + ch;
} else {
if (shortest.equals("") || word.length() < shortest.length()) {
secondShortest = shortest;
shortest = word;
} else if (!word.equals(shortest) &&
(secondShortest.equals("") || word.length() < secondShortest.length())) {
secondShortest = word;
}
word = "";
}
}
// Check last word
if (shortest.equals("") || word.length() < shortest.length()) {
secondShortest = shortest;
shortest = word;
} else if (!word.equals(shortest) &&
(secondShortest.equals("") || word.length() < secondShortest.length())) {
secondShortest = word;
}
System.out.println("Second shortest word: " + secondShortest);
}
}
Sample Output
Enter a sentence: Java is very easy to learn
Second shortest word: is
Important Notes
- If multiple words have the same length, the first valid one is considered.
- The sentence must contain at least two words of different lengths.
- No use of
split()method.
Practice Challenges
- Modify the program to ignore punctuation marks.
- Find the third shortest word in a sentence.
- Print both shortest and second shortest words together.
This problem strengthens string comparison logic and is frequently asked in Java interviews and coding tests.