Program to find Smallest and Largest Word in a String
Last Updated :
03 Mar, 2025
Given a string, find the minimum and the maximum length words in it.
Examples:
Input : "This is a test string"
Output : Minimum length word: a
Maximum length word: string
Input : "GeeksforGeeks A computer Science portal for Geeks"
Output : Minimum length word: A
Maximum length word: GeeksforGeeks
Method 1:
The idea is to keep a starting index si and an ending index ei.
- si points to the starting of a new word and we traverse the string using ei.
- Whenever a space or ‘\0’ character is encountered,we compute the length of the current word using (ei - si) and compare it with the minimum and the maximum length so far.
- If it is less, update the min_length and the min_start_index( which points to the starting of the minimum length word).
- If it is greater, update the max_length and the max_start_index( which points to the starting of the maximum length word).
- Finally, update minWord and maxWord which are output strings that have been sent by reference with the substrings starting at min_start_index and max_start_index of length min_length and max_length respectively.
Below is the implementation of the above approach:
C++
// CPP Program to find Smallest and
// Largest Word in a String
#include<iostream>
#include<cstring>
using namespace std;
void minMaxLengthWords(string input, string &minWord, string &maxWord)
{
// minWord and maxWord are received by reference
// and not by value
// will be used to store and return output
int len = input.length();
int si = 0, ei = 0;
int min_length = len, min_start_index = 0, max_length = 0, max_start_index = 0;
// Loop while input string is not empty
while (ei <= len)
{
if (ei < len && input[ei] != ' ')
ei++;
else
{
// end of a word
// find curr word length
int curr_length = ei - si;
if (curr_length < min_length)
{
min_length = curr_length;
min_start_index = si;
}
if (curr_length > max_length)
{
max_length = curr_length;
max_start_index = si;
}
ei++;
si = ei;
}
}
// store minimum and maximum length words
minWord = input.substr(min_start_index, min_length);
maxWord = input.substr(max_start_index, max_length);
}
// Driver code
int main()
{
string a = "GeeksforGeeks A Computer Science portal for Geeks";
string minWord, maxWord;
minMaxLengthWords(a, minWord, maxWord);
// to take input in string use getline(cin, a);
cout << "Minimum length word: "
<< minWord << endl
<< "Maximum length word: "
<< maxWord << endl;
}
Java
// Java Program to find Smallest and
// Largest Word in a String
import java.io.*;
class GFG
{
static String minWord = "", maxWord = "";
static void minMaxLengthWords(String input)
{
input=input.trim();//Triming any space before the String else space at start would be consider as smallest word
// minWord and maxWord are received by reference
// and not by value
// will be used to store and return output
int len = input.length();
int si = 0, ei = 0;
int min_length = len, min_start_index = 0,
max_length = 0, max_start_index = 0;
// Loop while input string is not empty
while (ei <= len)
{
if (ei < len && input.charAt(ei) != ' ')
{
ei++;
}
else
{
// end of a word
// find curr word length
int curr_length = ei - si;
if (curr_length < min_length)
{
min_length = curr_length;
min_start_index = si;
}
if (curr_length > max_length)
{
max_length = curr_length;
max_start_index = si;
}
ei++;
si = ei;
}
}
// store minimum and maximum length words
minWord = input.substring(min_start_index, min_start_index + min_length);
maxWord = input.substring(max_start_index, max_start_index+max_length);//Earlier code was not working if the largests word is inbetween String
}
// Driver code
public static void main(String[] args)
{
String a = "GeeksforGeeks A Computer Science portal for Geeks";
minMaxLengthWords(a);
// to take input in string use getline(cin, a);
System.out.print("Minimum length word: "
+ minWord
+ "\nMaximum length word: "
+ maxWord);
}
}
// This code contributed by Rajput-Ji
Python
# Python3 program to find Smallest and
# Largest Word in a String
# defining the method to find the longest
# word and the shortest word
def minMaxLengthWords(inp):
length = len(inp)
si = ei = 0
min_length = length
min_start_index = max_length = max_start_index = 0
# loop to find the length and stating index
# of both longest and shortest words
while ei <= length:
if (ei < length) and (inp[ei] != " "):
ei += 1
else:
curr_length = ei - si
# condition checking for the shortest word
if curr_length < min_length:
min_length = curr_length
min_start_index = si
# condition for the longest word
if curr_length > max_length:
max_length = curr_length
max_start_index = si
ei += 1
si = ei
# extracting the shortest word using
# it's starting index and length
minWord = inp[min_start_index :
min_start_index + min_length]
# extracting the longest word using
# it's starting index and length
maxWord = inp[max_start_index : max_length]
# printing the final result
print("Minimum length word: ", minWord)
print ("Maximum length word: ", maxWord)
# Driver Code
# Using this string to test our code
a = "GeeksforGeeks A Computer Science portal for Geeks"
minMaxLengthWords(a)
# This code is contributed by Animesh_Gupta
C#
// C# Program to find Smallest and
// Largest Word in a String
using System;
class GFG
{
static String minWord = "", maxWord = "";
static void minMaxLengthWords(String input)
{
// minWord and maxWord are received by reference
// and not by value
// will be used to store and return output
int len = input.Length;
int si = 0, ei = 0;
int min_length = len, min_start_index = 0,
max_length = 0, max_start_index = 0;
// Loop while input string is not empty
while (ei <= len)
{
if (ei < len && input[ei] != ' ')
{
ei++;
}
else
{
// end of a word
// find curr word length
int curr_length = ei - si;
if (curr_length < min_length)
{
min_length = curr_length;
min_start_index = si;
}
if (curr_length > max_length)
{
max_length = curr_length;
max_start_index = si;
}
ei++;
si = ei;
}
}
// store minimum and maximum length words
minWord = input.Substring(min_start_index, min_length);
maxWord = input.Substring(max_start_index, max_length);
}
// Driver code
public static void Main(String[] args)
{
String a = "GeeksforGeeks A Computer Science portal for Geeks";
minMaxLengthWords(a);
// to take input in string use getline(cin, a);
Console.Write("Minimum length word: "
+ minWord
+ "\nMaximum length word: "
+ maxWord);
}
}
// This code has been contributed by 29AjayKumar
JavaScript
// JavaScript Program to find Smallest and
// Largest Word in a String
let minWord = "";
let maxWord = "";
function minMaxLengthWords(input)
{
// minWord and maxWord are received by reference
// and not by value
// will be used to store and return output
let len = input.length;
let si = 0, ei = 0;
let min_length = len;
let min_start_index = 0;
let max_length = 0;
let max_start_index = 0;
// Loop while input string is not empty
while (ei <= len)
{
if (ei < len && input[ei] != ' ')
{
ei++;
}
else
{
// end of a word
// find curr word length
let curr_length = ei - si;
if (curr_length < min_length)
{
min_length = curr_length;
min_start_index = si;
}
if (curr_length > max_length)
{
max_length = curr_length;
max_start_index = si;
}
ei++;
si = ei;
}
}
// store minimum and maximum length words
minWord =
input.substring(min_start_index,min_start_index + min_length);
maxWord =
input.substring(max_start_index, max_length);
}
// Driver code
let a = "GeeksforGeeks A Computer Science portal for Geeks";
minMaxLengthWords(a);
// to take input in string use getline(cin, a);
console.log("Minimum length word: "
+ minWord+"<br>"
+ "Maximum length word: "
+ maxWord);
OutputMinimum length word: A
Maximum length word: GeeksforGeeks
Time Complexity: O(n), where n is the length of string.
Auxiliary Space: O(n), where n is the length of string. This is because when string is passed in the function it creates a copy of itself in stack.
Method 2: By Using Regular Expressions
In this approach we uses regular expressions to find words in a given input string and iterates through them. It keeps track of the smallest and largest words based on their lengths and prints them.
- First, Define a regular expression pattern to match words.
- Then, Create iterators to search for words within the input string.
- Initialize variables to store the smallest and largest words.
- Iterate through the words in the string.
- Check if the current word is smaller than the smallest word.
- Check if the current word is larger than the largest word .
- At the end ,print the smallest and largest words.
C++
#include <iostream>
#include <string>
#include <regex>
#include <iterator>
// Function to find the smallest and largest words in a string using regular expressions
void findSmallestLargestWordsRegex(const std::string& input) {
// Define a regular expression pattern to match words
std::regex wordRegex("\\b\\w+\\b");
// Create iterators to search for words within the input string
std::sregex_iterator wordsBegin(input.begin(), input.end(), wordRegex);
std::sregex_iterator wordsEnd;
// Initialize variables to store the smallest and largest words
std::string smallestWord, largestWord;
// Iterate through the words in the string
for (std::sregex_iterator it = wordsBegin; it != wordsEnd; ++it) {
std::smatch match = *it;
std::string word = match.str();
// Check if the current word is smaller than the smallest word found so far
if (word.length() < smallestWord.length() || smallestWord.empty()) {
smallestWord = word;
}
// Check if the current word is larger than the largest word found so far
if (word.length() > largestWord.length()) {
largestWord = word;
}
}
// Print the smallest and largest words
std::cout << "Minimum length word: " << smallestWord << std::endl;
std::cout << "Maximum length word: " << largestWord << std::endl;
}
int main() {
// Input string
std::string input = "This is a test string";
// Call the function to find and display the smallest and largest words
findSmallestLargestWordsRegex(input);
return 0;
}
// Siddhesh
Java
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class SmallestLargestWords {
// Function to find the smallest and largest words in a string using regular expressions
public static void findSmallestLargestWordsRegex(String input) {
// Define a regular expression pattern to match words
String wordRegex = "\\b\\w+\\b";
Pattern pattern = Pattern.compile(wordRegex);
Matcher matcher = pattern.matcher(input);
// Initialize variables to store the smallest and largest words
String smallestWord = "";
String largestWord = "";
// Iterate through the words in the string
while (matcher.find()) {
String word = matcher.group();
// Check if the current word is smaller than the smallest word found so far
if (word.length() < smallestWord.length() || smallestWord.isEmpty()) {
smallestWord = word;
}
// Check if the current word is larger than the largest word found so far
if (word.length() > largestWord.length()) {
largestWord = word;
}
}
// Print the smallest and largest words
System.out.println("Minimum length word: " + smallestWord);
System.out.println("Maximum length word: " + largestWord);
}
public static void main(String[] args) {
// Input string
String input = "This is a test string";
// Call the function to find and display the smallest and largest words
findSmallestLargestWordsRegex(input);
}
}
// Siddhesh
Python
import re
# Function to find the smallest and largest words in a string using regular expressions
def find_smallest_largest_words_regex(input_str):
# Define a regular expression pattern to match words
word_regex = r'\b\w+\b'
words = re.findall(word_regex, input_str)
# Initialize variables to store the smallest and largest words
smallest_word = ""
largest_word = ""
# Iterate through the words in the string
for word in words:
# Check if the current word is smaller than the smallest word found so far
if len(word) < len(smallest_word) or not smallest_word:
smallest_word = word
# Check if the current word is larger than the largest word found so far
if len(word) > len(largest_word):
largest_word = word
# Print the smallest and largest words
print("Minimum length word:", smallest_word)
print("Maximum length word:", largest_word)
# Input string
input_str = "This is a test string"
# Call the function to find and display the smallest and largest words
find_smallest_largest_words_regex(input_str)
# Siddhesh
C#
using System;
using System.Text.RegularExpressions;
class Program
{
// Function to find the smallest and largest words in a string using regular expressions
static void FindSmallestLargestWordsRegex(string input)
{
// Define a regular expression pattern to match words
string wordPattern = @"\b\w+\b";
// Use Regex.Matches to get a collection of words
MatchCollection words = Regex.Matches(input, wordPattern);
// Initialize variables to store the smallest and largest words
string smallestWord = null, largestWord = null;
// Iterate through the words in the collection
foreach (Match match in words)
{
string word = match.Value;
// Check if the current word is smaller than the smallest word found so far
if (string.IsNullOrEmpty(smallestWord) || word.Length < smallestWord.Length)
{
smallestWord = word;
}
// Check if the current word is larger than the largest word found so far
if (string.IsNullOrEmpty(largestWord) || word.Length > largestWord.Length)
{
largestWord = word;
}
}
// Print the smallest and largest words
Console.WriteLine("Minimum length word: " + smallestWord);
Console.WriteLine("Maximum length word: " + largestWord);
}
static void Main()
{
// Input string
string input = "This is a test string";
// Call the function to find and display the smallest and largest words
FindSmallestLargestWordsRegex(input);
}
}
// This code is contributed by shivamgupta310570
JavaScript
// Function to find the smallest and largest words in a string using regular expressions
function findSmallestLargestWordsRegex(input) {
// Define a regular expression pattern to match words
const wordRegex = /\b\w+\b/g;
// Create an array of words by matching the regular expression
const words = input.match(wordRegex) || [];
// Initialize variables to store the smallest and largest words
let smallestWord = '', largestWord = '';
// Iterate through the words in the array
for (const word of words) {
// Check if the current word is smaller than the smallest word found so far
if (word.length < smallestWord.length || smallestWord.length === 0) {
smallestWord = word;
}
// Check if the current word is larger than the largest word found so far
if (word.length > largestWord.length) {
largestWord = word;
}
}
// Print the smallest and largest words
console.log("Minimum length word:", smallestWord);
console.log("Maximum length word:", largestWord);
}
// Input string
const input = "This is a test string";
// Call the function to find and display the smallest and largest words
findSmallestLargestWordsRegex(input);
// This code is contributed by shivamgupta0987654321
OutputMinimum length word: a
Maximum length word: string
Time complexity: O(n), n is length of string
Space complexity: O(m), m is the length of the longest word.
Method 3: Using Stack
In this approach, we will push all the words one by one into a char stack and check for the max as well as min length for every word on the basis of that we will print the Minimum length word and Maximum length word.
Below is the implementation of the above approach:
C++
// CPP program to find Smallest and Largest Word in a String
// using stack
#include <bits/stdc++.h>
using namespace std;
pair<string, string> smallestAndLargestWord(string& str)
{
// Pair to store the smallest and largest words
pair<string, string> stringPair;
// Stack to temporarily store characters of a word
stack<char> stk;
int n = str.size();
// Variables to store the smallest and largest words
string minWord = "";
string maxWord = "";
// Temporary variable to store each word
string temp = "";
// Loop through the characters of the string
for (int i = 0; i < n; i++) {
if (str[i] != ' ') {
// Push characters onto the stack until a space
// is encountered
stk.push(str[i]);
}
else {
// When a space is encountered, extract the word
// from the stack
while (!stk.empty()) {
temp += stk.top();
stk.pop();
}
// Compare the length of the current word with
// the smallest and largest words found so far
if (minWord == ""
|| temp.size() < minWord.size()) {
minWord = temp;
}
if (maxWord == ""
|| temp.size() > maxWord.size()) {
maxWord = temp;
}
// Reset the temporary variable for the next
// word
temp = "";
}
}
// Extract the last word from the stack
while (!stk.empty()) {
temp += stk.top();
stk.pop();
}
// Compare the length of the last word with the smallest
// and largest words found so far
if (minWord == "" || temp.size() < minWord.size()) {
minWord = temp;
}
if (maxWord == "" || temp.size() > maxWord.size()) {
maxWord = temp;
}
// Reverse both the strings as stack reverses them
// already
reverse(minWord.begin(), minWord.end());
reverse(maxWord.begin(), maxWord.end());
// Store the smallest and largest words in the pair
stringPair.first = minWord;
stringPair.second = maxWord;
return stringPair;
}
int main()
{
string str = "GeeksforGeeks A computer Science portal "
"for Geeks";
// Call the function to find the smallest and largest
// words
pair<string, string> stringPair
= smallestAndLargestWord(str);
// Print the results
cout << "Minimum length word: " << stringPair.first
<< endl;
cout << "Maximum length word: " << stringPair.second
<< endl;
return 0;
}
Java
public class SmallestLargestWord {
// Function to find the smallest and largest word in a string
public static String[] smallestAndLargestWord(String str) {
// Array to store the smallest and largest words
String[] result = new String[2];
// Variables to store the smallest and largest words
String minWord = "";
String maxWord = "";
// Temporary variable to store each word
String temp = "";
// Loop through the characters of the string
int i = 0;
while (i < str.length()) {
if (str.charAt(i) != ' ') {
// Add characters to temp until a space is encountered
temp += str.charAt(i);
} else {
// When a space is encountered, compare the length of the current word
// with the smallest and largest words found so far
if (minWord.isEmpty() || temp.length() < minWord.length()) {
minWord = temp;
}
if (maxWord.isEmpty() || temp.length() > maxWord.length()) {
maxWord = temp;
}
// Reset the temporary variable for the next word
temp = "";
}
i++;
}
// Compare the length of the last word with the smallest and largest words found so far
if (minWord.isEmpty() || temp.length() < minWord.length()) {
minWord = temp;
}
if (maxWord.isEmpty() || temp.length() > maxWord.length()) {
maxWord = temp;
}
// Store the smallest and largest words in the result array
result[0] = minWord;
result[1] = maxWord;
return result;
}
public static void main(String[] args) {
String str = "GeeksforGeeks A computer Science portal for Geeks";
// Call the function to find the smallest and largest words
String[] result = smallestAndLargestWord(str);
// Print the results
System.out.println("Minimum length word: " + result[0]);
System.out.println("Maximum length word: " + result[1]);
}
}
Python
def smallest_and_largest_word(string):
# Variables to store the smallest and largest words
min_word = ""
max_word = ""
# Temporary variable to store each word
temp = ""
# Loop through the characters of the string
i = 0
while i < len(string):
if string[i] != ' ':
# Push characters onto the stack until a space is encountered
temp += string[i]
else:
# When a space is encountered, compare the length of the current word
# with the smallest and largest words found so far
if min_word == "" or len(temp) < len(min_word):
min_word = temp
if max_word == "" or len(temp) > len(max_word):
max_word = temp
# Reset the temporary variable for the next word
temp = ""
i += 1
# Compare the length of the last word with the smallest and largest words found so far
if min_word == "" or len(temp) < len(min_word):
min_word = temp
if max_word == "" or len(temp) > len(max_word):
max_word = temp
# Store the smallest and largest words
return min_word, max_word
# Main function
def main():
string = "GeeksforGeeks A computer Science portal for Geeks"
# Call the function to find the smallest and largest words
min_word, max_word = smallest_and_largest_word(string)
# Print the results
print("Minimum length word:", min_word)
print("Maximum length word:", max_word)
if __name__ == "__main__":
main()
JavaScript
class Pair {
constructor(first, second) {
this.first = first;
this.second = second;
}
}
function smallestAndLargestWord(str) {
const words = str.split(" ");
let minWord = "";
let maxWord = "";
for (const word of words) {
if (!minWord || word.length < minWord.length) {
minWord = word;
}
if (!maxWord || word.length > maxWord.length) {
maxWord = word;
}
}
return new Pair(minWord, maxWord);
}
function main() {
const str = "GeeksforGeeks A computer Science portal for Geeks";
const stringPair = smallestAndLargestWord(str);
console.log("Minimum length word: " + stringPair.first);
console.log("Maximum length word: " + stringPair.second);
}
main();
OutputMinimum length word: A
Maximum length word: GeeksforGeeks
Time complexity: O(n), n is length of string.
Auxiliary Space: O(m), m is the length of the longest word.
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem