Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • DSA
  • Interview Problems on String
  • Practice String
  • MCQs on String
  • Tutorial on String
  • String Operations
  • Sort String
  • Substring & Subsequence
  • Iterate String
  • Reverse String
  • Rotate String
  • String Concatenation
  • Compare Strings
  • KMP Algorithm
  • Boyer-Moore Algorithm
  • Rabin-Karp Algorithm
  • Z Algorithm
  • String Guide for CP
Open In App
Next Article:
Program to find Smallest and Largest Word in a String
Next article icon

Program to find Smallest and Largest Word in a String

Last Updated : 03 Mar, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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); 

Output
Minimum 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 

Output
Minimum 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(); 

Output
Minimum 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.


Next Article
Program to find Smallest and Largest Word in a String

K

kartik
Improve
Article Tags :
  • DSA
  • Strings
Practice Tags :
  • Strings

Similar Reads

    String in Data Structure
    A 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
    3 min read
    Introduction to Strings - Data Structure and Algorithm Tutorials
    Strings are sequences of characters. The differences between a character array and a string are, a string is terminated with a special character ‘\0’ and strings are typically immutable in most of the programming languages like Java, Python and JavaScript. Below are some examples of strings:"geeks"
    7 min read
    Applications, Advantages and Disadvantages of String
    The String data structure is the backbone of programming languages and the building blocks of communication. String data structures are one of the most fundamental and widely used tools in computer science and programming. They allow for the representation and manipulation of text and character sequ
    6 min read
    Subsequence and Substring
    What is a Substring? A substring is a contiguous part of a string, i.e., a string inside another string. In general, for an string of size n, there are n*(n+1)/2 non-empty substrings. For example, Consider the string "geeks", There are 15 non-empty substrings. The subarrays are: g, ge, gee, geek, ge
    6 min read
    Storage for Strings in C
    In C, a string can be referred to either using a character pointer or as a character array. Strings as character arrays C char str[4] = "GfG"; /*One extra for string terminator*/ /* OR */ char str[4] = {‘G’, ‘f’, ‘G’, '\0'}; /* '\0' is string terminator */ When strings are declared as character arra
    5 min read

    Strings in different language

    Strings in C
    A String in C programming is a sequence of characters terminated with a null character '\0'. The C String is work as an array of characters. The difference between a character array and a C string is that the string in C is terminated with a unique character '\0'.DeclarationDeclaring a string in C i
    5 min read
    std::string class in C++
    C++ has in its definition a way to represent a sequence of characters as an object of the class. This class is called std:: string. The string class stores the characters as a sequence of bytes with the functionality of allowing access to the single-byte character.String vs Character ArrayStringChar
    8 min read
    String Class in Java
    A string is a sequence of characters. In Java, objects of the String class are immutable, which means they cannot be changed once created. In this article, we are going to learn about the String class in Java.Example of String Class in Java:Java// Java Program to Create a String import java.io.*; cl
    7 min read
    Python String
    A string is a sequence of characters. Python treats anything inside quotes as a string. This includes letters, numbers, and symbols. Python has no character data type so single character is a string of length 1.Pythons = "GfG" print(s[1]) # access 2nd char s1 = s + s[0] # update print(s1) # printOut
    6 min read
    C# Strings
    In C#, a string is a sequence of Unicode characters or an array of characters. The range of Unicode characters will be U+0000 to U+FFFF. The array of characters is also termed as the text. So the string is the representation of the text. A string is an important concept, and sometimes people get con
    7 min read
    JavaScript String Methods
    JavaScript strings are the sequence of characters. They are treated as Primitive data types. In JavaScript, strings are automatically converted to string objects when using string methods on them. This process is called auto-boxing. The following are methods that we can call on strings.slice() extra
    11 min read
    PHP Strings
    In PHP, strings are one of the most commonly used data types. A string is a sequence of characters used to represent text, such as words and sentences. Strings are enclosed in either single quotes (' ') or double quotes (" "). You can create a string using single quotes (' ') or double quotes (" ").
    4 min read

    Basic operations on String

    Searching For Characters and Substring in a String in Java
    Efficient String manipulation is very important in Java programming especially when working with text-based data. In this article, we will explore essential methods like indexOf(), contains(), and startsWith() to search characters and substrings within strings in Java.Searching for a Character in a
    5 min read
    Reverse a String – Complete Tutorial
    Given a string s, the task is to reverse the string. Reversing a string means rearranging the characters such that the first character becomes the last, the second character becomes second last and so on.Examples:Input: s = "GeeksforGeeks"Output: "skeeGrofskeeG"Explanation : The first character G mo
    13 min read
    Left Rotation of a String
    Given a string s and an integer d, the task is to left rotate the string by d positions.Examples:Input: s = "GeeksforGeeks", d = 2Output: "eksforGeeksGe" Explanation: After the first rotation, string s becomes "eeksforGeeksG" and after the second rotation, it becomes "eksforGeeksGe".Input: s = "qwer
    15+ min read
    Sort string of characters
    Given a string of lowercase characters from 'a' - 'z'. We need to write a program to print the characters of this string in sorted order.Examples: Input : "dcab" Output : "abcd"Input : "geeksforgeeks"Output : "eeeefggkkorss"Naive Approach - O(n Log n) TimeA simple approach is to use sorting algorith
    5 min read
    Frequency of Characters in Alphabetical Order
    Given a string s, the task is to print the frequency of each of the characters of s in alphabetical order.Example: Input: s = "aabccccddd" Output: a2b1c4d3 Since it is already in alphabetical order, the frequency of the characters is returned for each character. Input: s = "geeksforgeeks" Output: e4
    9 min read
    Swap characters in a String
    Given a String S of length N, two integers B and C, the task is to traverse characters starting from the beginning, swapping a character with the character after C places from it, i.e. swap characters at position i and (i + C)%N. Repeat this process B times, advancing one position at a time. Your ta
    14 min read
    C Program to Find the Length of a String
    The length of a string is the number of characters in it without including the null character (‘\0’). In this article, we will learn how to find the length of a string in C.The easiest way to find the string length is by using strlen() function from the C strings library. Let's take a look at an exa
    2 min read
    How to insert characters in a string at a certain position?
    Given a string str and an array of indices chars[] that describes the indices in the original string where the characters will be added. For this post, let the character to be inserted in star (*). Each star should be inserted before the character at the given index. Return the modified string after
    7 min read
    Check if two strings are same or not
    Given two strings, the task is to check if these two strings are identical(same) or not. Consider case sensitivity.Examples:Input: s1 = "abc", s2 = "abc" Output: Yes Input: s1 = "", s2 = "" Output: Yes Input: s1 = "GeeksforGeeks", s2 = "Geeks" Output: No Approach - By Using (==) in C++/Python/C#, eq
    7 min read
    Concatenating Two Strings in C
    Concatenating two strings means appending one string at the end of another string. In this article, we will learn how to concatenate two strings in C.The most straightforward method to concatenate two strings is by using strcat() function. Let's take a look at an example:C#include <stdio.h> #i
    2 min read
    Remove all occurrences of a character in a string
    Given a string and a character, remove all the occurrences of the character in the string.Examples: Input : s = "geeksforgeeks" c = 'e'Output : s = "gksforgks"Input : s = "geeksforgeeks" c = 'g'Output : s = "eeksforeeks"Input : s = "geeksforgeeks" c = 'k'Output : s = "geesforgees"Using Built-In Meth
    2 min read

    Binary String

    Check if all bits can be made same by single flip
    Given a binary string, find if it is possible to make all its digits equal (either all 0's or all 1's) by flipping exactly one bit. Input: 101Output: YeExplanation: In 101, the 0 can be flipped to make it all 1Input: 11Output: NoExplanation: No matter whichever digit you flip, you will not get the d
    5 min read
    Number of flips to make binary string alternate | Set 1
    Given a binary string, that is it contains only 0s and 1s. We need to make this string a sequence of alternate characters by flipping some of the bits, our goal is to minimize the number of bits to be flipped. Examples : Input : str = “001” Output : 1 Minimum number of flips required = 1 We can flip
    8 min read
    Binary representation of next number
    Given a binary string that represents binary representation of positive number n, the task is to find the binary representation of n+1. The binary input may or may not fit in an integer, so we need to return a string.Examples: Input: s = "10011"Output: "10100"Explanation: Here n = (19)10 = (10011)2n
    6 min read
    Min flips of continuous characters to make all characters same in a string
    Given a string consisting only of 1's and 0's. In one flip we can change any continuous sequence of this string. Find this minimum number of flips so the string consist of same characters only.Examples: Input : 00011110001110Output : 2We need to convert 1's sequenceso string consist of all 0's.Input
    8 min read
    Generate all binary strings without consecutive 1's
    Given an integer n, the task is to generate all binary strings of size n without consecutive 1's.Examples: Input : n = 4Output : 0000 0001 0010 0100 0101 1000 1001 1010Input : n = 3Output : 000 001 010 100 101Approach:The idea is to generate all binary strings of length n without consecutive 1's usi
    6 min read
    K'th bit in a binary representation with n iterations
    Given a decimal number m. Consider its binary representation string and apply n iterations. In each iteration, replace the character 0 with the string 01, and 1 with 10. Find the kth (1-based indexing) character in the string after the nth iterationExamples: Input: m = 5, n = 2, k = 5Output: 0Explan
    15+ min read

    Substring and Subsequence

    All substrings of a given String
    Given a string s, containing lowercase alphabetical characters. The task is to print all non-empty substrings of the given string.Examples : Input : s = "abc"Output : "a", "ab", "abc", "b", "bc", "c"Input : s = "ab"Output : "a", "ab", "b"Input : s = "a"Output : "a"[Expected Approach] - Using Iterati
    8 min read
    Print all subsequences of a string
    Given a string, we have to find out all its subsequences of it. A String is said to be a subsequence of another String, if it can be obtained by deleting 0 or more character without changing its order.Examples: Input : abOutput : "", "a", "b", "ab"Input : abcOutput : "", "a", "b", "c", "ab", "ac", "
    12 min read
    Count Distinct Subsequences
    Given a string str of length n, your task is to find the count of distinct subsequences of it.Examples: Input: str = "gfg"Output: 7Explanation: The seven distinct subsequences are "", "g", "f", "gf", "fg", "gg" and "gfg" Input: str = "ggg"Output: 4Explanation: The four distinct subsequences are "",
    13 min read
    Count distinct occurrences as a subsequence
    Given two strings pat and txt, where pat is always shorter than txt, count the distinct occurrences of pat as a subsequence in txt.Examples: Input: txt = abba, pat = abaOutput: 2Explanation: pat appears in txt as below three subsequences.[abba], [abba]Input: txt = banana, pat = banOutput: 3Explanati
    15+ min read
    Longest Common Subsequence (LCS)
    Given two strings, s1 and s2, the task is to find the length of the Longest Common Subsequence. If there is no common subsequence, return 0. A subsequence is a string generated from the original string by deleting 0 or more characters, without changing the relative order of the remaining characters.
    15+ min read
    Shortest Superstring Problem
    Given a set of n strings arr[], find the smallest string that contains each string in the given set as substring. We may assume that no string in arr[] is substring of another string.Examples: Input: arr[] = {"geeks", "quiz", "for"}Output: geeksquizforExplanation: "geeksquizfor" contains all the thr
    15+ min read
    Printing Shortest Common Supersequence
    Given two strings s1 and s2, find the shortest string which has both s1 and s2 as its sub-sequences. If multiple shortest super-sequence exists, print any one of them.Examples:Input: s1 = "geek", s2 = "eke"Output: geekeExplanation: String "geeke" has both string "geek" and "eke" as subsequences.Inpu
    9 min read
    Shortest Common Supersequence
    Given two strings s1 and s2, the task is to find the length of the shortest string that has both s1 and s2 as subsequences.Examples: Input: s1 = "geek", s2 = "eke"Output: 5Explanation: String "geeke" has both string "geek" and "eke" as subsequences.Input: s1 = "AGGTAB", s2 = "GXTXAYB"Output: 9Explan
    15+ min read
    Longest Repeating Subsequence
    Given a string s, the task is to find the length of the longest repeating subsequence, such that the two subsequences don't have the same string character at the same position, i.e. any ith character in the two subsequences shouldn't have the same index in the original string. Examples:Input: s= "ab
    15+ min read
    Longest Palindromic Subsequence (LPS)
    Given a string s, find the length of the Longest Palindromic Subsequence in it. Note: The Longest Palindromic Subsequence (LPS) is the maximum-length subsequence of a given string that is also a Palindrome. Longest Palindromic SubsequenceExamples:Input: s = "bbabcbcab"Output: 7Explanation: Subsequen
    15+ min read
    Longest Palindromic Substring
    Given a string s, the task is to find the longest substring which is a palindrome. If there are multiple answers, then return the first appearing substring.Examples:Input: s = "forgeeksskeegfor" Output: "geeksskeeg"Explanation: There are several possible palindromic substrings like "kssk", "ss", "ee
    12 min read

    Palindrome

    C Program to Check for Palindrome String
    A string is said to be palindrome if the reverse of the string is the same as the string. In this article, we will learn how to check whether the given string is palindrome or not using C program.The simplest method to check for palindrome string is to reverse the given string and store it in a temp
    4 min read
    Check if a given string is a rotation of a palindrome
    Given a string, check if it is a rotation of a palindrome. For example your function should return true for "aab" as it is a rotation of "aba". Examples: Input: str = "aaaad" Output: 1 // "aaaad" is a rotation of a palindrome "aadaa" Input: str = "abcd" Output: 0 // "abcd" is not a rotation of any p
    15+ min read
    Check if characters of a given string can be rearranged to form a palindrome
    Given a string, Check if the characters of the given string can be rearranged to form a palindrome. For example characters of "geeksogeeks" can be rearranged to form a palindrome "geeksoskeeg", but characters of "geeksforgeeks" cannot be rearranged to form a palindrome. Recommended PracticeAnagram P
    14 min read
    Online algorithm for checking palindrome in a stream
    Given a stream of characters (characters are received one by one), write a function that prints 'Yes' if a character makes the complete string palindrome, else prints 'No'. Examples:Input: str[] = "abcba"Output: a Yes // "a" is palindrome b No // "ab" is not palindrome c No // "abc" is not palindrom
    15+ min read
    Print all Palindromic Partitions of a String using Bit Manipulation
    Given a string, find all possible palindromic partitions of a given string. Note that this problem is different from Palindrome Partitioning Problem, there the task was to find the partitioning with minimum cuts in input string. Here we need to print all possible partitions. Example: Input: nitinOut
    10 min read
    Minimum Characters to Add at Front for Palindrome
    Given a string s, the task is to find the minimum number of characters to be added to the front of s to make it palindrome. A palindrome string is a sequence of characters that reads the same forward and backward. Examples: Input: s = "abc"Output: 2Explanation: We can make above string palindrome as
    12 min read
    Make largest palindrome by changing at most K-digits
    You are given a string s consisting of digits (0-9) and an integer k. Convert the string into a palindrome by changing at most k digits. If multiple palindromes are possible, return the lexicographically largest one. If it's impossible to form a palindrome with k changes, return "Not Possible".Examp
    14 min read
    Minimum Deletions to Make a String Palindrome
    Given a string s of length n, the task is to remove or delete the minimum number of characters from the string so that the resultant string is a palindrome. Note: The order of characters should be maintained. Examples : Input : s = "aebcbda"Output : 2Explanation: Remove characters 'e' and 'd'. Resul
    15+ min read
    Minimum insertions to form a palindrome with permutations allowed
    Given a string of lowercase letters. Find minimum characters to be inserted in the string so that it can become palindrome. We can change the positions of characters in the string.Examples: Input: geeksforgeeksOutput: 2Explanation: geeksforgeeks can be changed as: geeksroforskeeg or geeksorfroskeeg
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences