Sunday, January 12, 2025
Google search engine
HomeData Modelling & AIString Guide for Competitive Programming

String Guide for Competitive Programming

Strings are a sequence of characters, and are one of the most fundamental data structures in Competitive Programming. String problems are very common in competitive programming contests, and can range from simple to very challenging. In this article we are going to discuss about most frequent string tips and tricks that will help a programmer during Competitive Programming.

Common Operations on String:

1. Taking Strings as Input:

C++




#include <iostream>
using namespace std;
 
int main() {
 
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
 
    string word, sentence;
    // Input a single word
    cin >> word;
    // Input a line (multiple words)
    cin.ignore();
    getline(cin, sentence);
    cout << "word = " << word << "\n";
    cout << "sentence = " << sentence << "\n";
     
    return 0;
}


Java




// Working program with FastReader
import java.io.*;
import java.util.*;
 
public class Main {
    static class FastReader {
        BufferedReader br;
        StringTokenizer st;
 
        public FastReader()
        {
            br = new BufferedReader(
                new InputStreamReader(System.in));
        }
 
        String next()
        {
            while (st == null || !st.hasMoreElements()) {
                try {
                    st = new StringTokenizer(br.readLine());
                }
                catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return st.nextToken();
        }
 
        int nextInt() { return Integer.parseInt(next()); }
 
        long nextLong() { return Long.parseLong(next()); }
 
        double nextDouble()
        {
            return Double.parseDouble(next());
        }
 
        String nextLine()
        {
            String str = "";
            try {
                if(st.hasMoreTokens()){
                    str = st.nextToken("\n");
                }
                else{
                    str = br.readLine();
                }
            }
            catch (IOException e) {
                e.printStackTrace();
            }
            return str;
        }
    }
 
    public static void main(String[] args)
    {
        FastReader s = new FastReader();
        String word = s.next();
        String sentence = s.nextLine();
        System.out.println("Word = " + word);
        System.out.println("Sentence = " + sentence);
    }
}


Python3




import io
import os
import sys
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
s = input().decode()
sys.stdout.write(s + "\n")


C#




using System;
 
class Program
{
    static void Main()
    {
        string word, sentence;
 
        // Input a single word
        word = Console.ReadLine();
 
        // Input a line (multiple words)
        sentence = Console.ReadLine();
 
        Console.WriteLine($"word = {word}");
        Console.WriteLine($"sentence = {sentence}");
    }
}


Output

word = 
sentence = 

2. Find the First and Last Occurrence of a Character in the String:

C++




#include <bits/stdc++.h>
using namespace std;
 
int main()
{
 
    string str = "Learn Competitive Programming with GFG!";
    size_t first = str.find('m'),
        last = str.find_last_of('m');
    if (first != string::npos)
        cout << "First occurrence of m is at index = "
            << first << "\n";
    if (last != string::npos)
        cout << "Last Occurrence of m is at index = "
            << last << "\n";
    return 0;
}


Java




import java.io.*;
 
class GFG {
    public static void main(String[] args)
    {
        String str
            = "Learn Competitive Programming with GFG!";
        int first = str.indexOf('m'),
            last = str.lastIndexOf('m');
        if (first != -1)
            System.out.println(
                "First Occurrence of m is at index = "
                + first);
        if (last != -1)
            System.out.println(
                "Last Occurrence of m is at index = "
                + last);
    }
}


Python3




str = "Learn Competitive Programming with GFG!"
first = str.find('m')
last = str.rfind('m')
if first != -1:
    print(f"First Occurrence of m is at index = {first}")
if last != -1:
    print(f"Last Occurrence of m is at index = {last}")


C#




using System;
 
class Program
{
    static void Main()
    {
        string str = "Learn Competitive Programming with GFG!";
 
        int first = str.IndexOf('m');
        int last = str.LastIndexOf('m');
 
        if (first != -1)
            Console.WriteLine($"First occurrence of 'm' is at index = {first}");
         
        if (last != -1)
            Console.WriteLine($"Last occurrence of 'm' is at index = {last}");
 
        
        
    }
}


Javascript




let str = "Learn Competitive Programming with GFG!";
let first = str.indexOf('m');
let last = str.lastIndexOf('m');
 
if (first !== -1) {
    console.log(`First Occurrence of m is at index = ${first}`);
}
 
if (last !== -1) {
    console.log(`Last Occurrence of m is at index = ${last}`);
}


Output

First occurrence of m is at index = 8
Last Occurrence of m is at index = 25

3. Reverse a String:

C++




#include <bits/stdc++.h>
using namespace std;
 
int main()
{
    string str = "Learn Competitive Programming with GFG!";
    string rev(str.rbegin(), str.rend());
    cout << "Reverse = " << rev << "\n";
    return 0;
}


Java




/*package whatever //do not write package name here */
 
import java.io.*;
 
class GFG {
    public static void main(String[] args)
    {
        String str
            = "Learn Competitive Programming with GFG!";
        StringBuilder rev = new StringBuilder();
        rev.append(str);
        rev.reverse();
        System.out.println("Reverse = " + rev);
    }
}


Python3




str = "Learn Competitive Programming with GFG!"
print(f"Reverse = {str[::-1]}")


C#




using System;
using System.Text;
 
class Program
{
    static void Main()
    {
        string str = "Learn Competitive Programming with GFG!";
        string reversed = ReverseString(str);
         
        Console.WriteLine("Reverse = " + reversed);
    }
 
    static string ReverseString(string input)
    {
        char[] charArray = input.ToCharArray();
        Array.Reverse(charArray);
        return new string(charArray);
    }
}


Output

Reverse = !GFG htiw gnimmargorP evititepmoC nraeL


4. Append a character/string at the end of the String:

C++




#include <bits/stdc++.h>
using namespace std;
 
int main() {
      string str = "Learn Competitive Programming with ";
      str.append("GFG!");
      cout << "New String = " << str << "\n";
    return 0;
}


Java




/*package whatever //do not write package name here */
 
import java.io.*;
 
class GFG {
    public static void main (String[] args) {
        StringBuilder str = new StringBuilder("Learn Competitive Programming with ");
          str.append("GFG!");
          System.out.println("New String = " + str);
    }
}


Python3




str = "Learn Competitive Programming with "
str = "".join([str, "GFG!"])
print(f"New String = {str}")


Output

New String = Learn Competitive Programming with GFG!








5. Sorting a string:

C++




#include <bits/stdc++.h>
using namespace std;
 
int main()
{
    string str = "Learn Competitive Programming with GFG!";
    sort(str.begin(), str.end());
    cout << "Sorted String = " << str << "\n";
 
    return 0;
}


Java




/*package whatever //do not write package name here */
 
import java.util.*;
 
class GFG {
    public static void main(String[] args)
    {
        String str
            = "Learn Competitive Programming with GFG!";
        char array[] = str.toCharArray();
        Arrays.sort(array);
        str = new String(array);
        System.out.println("Sorted String = " + str);
    }
}


Python3




str = "Learn Competitive Programming with GFG!"
str = "".join(sorted(str))
print(f"Sorted string = {str}")


C#




using System;
 
class MainClass
{
    public static void Main(string[] args)
    {
        string str = "Learn Competitive Programming with GFG!";
         
        // Convert the string to a char array, sort, and then convert back to string
        char[] charArray = str.ToCharArray();
        Array.Sort(charArray);
        string sortedStr = new string(charArray);
 
        Console.WriteLine("Sorted String = " + sortedStr);
 
        // Alternatively, using LINQ
        //string sortedStr = new string(str.OrderBy(c => c).ToArray());
        //Console.WriteLine("Sorted String = " + sortedStr);
    }
}


Output

Sorted String =     !CFGGLPaaeeegghiiiimmmnnooprrrtttvw








6. Substring extraction:

C++




#include <bits/stdc++.h>
using namespace std;
 
int main()
{
    string str = "Learn Competitive Programming with GFG!";
    cout << "Substring from index 6 to 16 = "
         << str.substr(6, 11) << "\n";
    return 0;
}


Java




import java.io.*;
 
class GFG {
    public static void main(String[] args)
    {
        String str
            = "Learn Competitive Programming with GFG!";
        System.out.println("Substring from index 6 to 16 = "
                           + str.substring(6, 17));
    }
}


Python3




Str = "Learn Competitive Programming with GFG!"
print(f"Substring from index 6 to 16 = {Str[6:17]}")


Output

Substring from index 6 to 16 = Competitive








Competitive Programming Tips for Strings in C++:

1. Pass by reference:

We should always pass the reference of strings to avoid making copies of the original string which is quite inefficient.

C++




#include <iostream>
using namespace std;
 
// Pass by value
int countSpaceSlow(string str, int idx)
{
    if (idx == str.length())
        return 0;
    return countSpaceSlow(str, idx + 1)
           + (str[idx] == ' ' ? 1 : 0);
}
 
// Pass by reference
int countSpaceFast(string& str, int idx)
{
    if (idx == str.length())
        return 0;
    return countSpaceSlow(str, idx + 1)
           + (str[idx] == ' ' ? 1 : 0);
}
 
int main()
{
    string str = "Learn Competitive programming with GFG!";
    cout << countSpaceSlow(str, 0) << "\n";
    cout << countSpaceFast(str, 0) << "\n";
    return 0;
}


Output

4
4








2. push_back() vs + operator:

We should always use push_back() function instead of + operator, to add a character at the end of the string. This is because the time complexity of + operator depends on the length of the string O(N) whereas push_back() simply pushes the character at the end in O(1) time complexity. So, if we need to append characters in a loop, push_back() will have much better performance as compared to + operator.

C++




#include <iostream>
using namespace std;
 
// Slow because of + operator
string filterLowerCaseSlow(string str)
{
    string res = "";
    for (int i = 0; i < str.length(); i++) {
        if (str[i] >= 'a' && str[i] <= 'z')
            res += str[i];
    }
    return res;
}
 
// Fast because of push_back()
string filterLowerCaseFast(string& str)
{
    string res = "";
    for (int i = 0; i < str.length(); i++) {
        if (str[i] >= 'a' && str[i] <= 'z')
            res.push_back(str[i]);
    }
    return res;
}
 
int main()
{
    string str = "Learn Competitive programming with GFG!";
    cout << filterLowerCaseSlow(str) << "\n";
    cout << filterLowerCaseFast(str) << "\n";
    return 0;
}


Output

earnompetitiveprogrammingwith
earnompetitiveprogrammingwith








Competitive Programming Tips for Strings in Java:

1. StringBuilder vs + operator:

Avoid using the + operator repeatedly when concatenating multiple strings. This can create unnecessary string objects, leading to poor performance. Instead, use StringBuilder (or StringBuffer for thread safety) to efficiently concatenate strings.

Java




import java.io.*;
 
class GFG {
    public static void main(String[] args)
    {
        // Slow Concatenation of Strings
        String str1 = "";
        str1 = str1 + "Hello";
        str1 = str1 + " ";
        str1 = str1 + "World";
        System.out.println(str1);
 
        // Fast Concatenation of Strings
        StringBuilder str2 = new StringBuilder();
        str2.append("Hello");
        str2.append(" ");
        str2.append("World");
        System.out.println(str2);
    }
}


Output

Hello World
Hello World








2. Use the equals() Method for String Comparison:

When comparing string content, use the equals() method or its variants (equalsIgnoreCase(), startsWith(), endsWith(), etc.) instead of the “==” operator, which compares object references.

Java




/*package whatever //do not write package name here */
 
import java.io.*;
 
class GFG {
    public static void main(String[] args)
    {
        String s1 = "GFG", s2 = "GFG";
        // Incorrect implementation
        System.out.println(s1 == s2);
        System.out.println(new String("GFG")
                           == new String("GFG"));
 
        // Correct Implementation
        System.out.println(s1.equals(s2));
        System.out.println(
            new String("GFG").equals(new String("GFG")));
    }
}


Output

true
false
true
true








Competitive Programming Tips for Strings in Python:

1. Use String Slicing and Concatenation Effectively.

String slicing is a powerful way to extract substrings from a string. You can use slicing to get individual characters, substrings of any length, or even reversed strings. String concatenation is used to join two or more strings together. There are two ways to concatenate strings in Python: using the + operator or the join() method. The + operator is more efficient for concatenating a small number of strings, while the join() method is more efficient for concatenating a large number of strings.

Python3




Str = "Learn Competitive Programming "
print(f"First five characters = {Str[0:5]}")
print(f"Reverse = {Str[::-1]}")
 
Str += "with "
Str = "".join([Str, "GFG!"])
 
print(Str)


Output

First five characters = Learn
Reverse =  gnimmargorP evititepmoC nraeL
Learn Competitive Programming with GFG!








2. Use Regular Expressions for Pattern Matching:

Regular expressions are a powerful tool for matching patterns in strings. Python has a built-in re module that provides regular expression support.

Python3




import re
 
# Method to find the number of words using Regex
def count_words(text):
    words = re.findall(r"\w+", text)
    return len(words)
 
 
print(count_words("Learn Competitive Programming with GFG!"))


Output

5








Important String Algorithms for Competitive Programming:

Here are some important string algorithms for competitive programming:

String Algorithms

String hashing using Polynomial rolling hash function

Rabin-Karp Algorithm for Pattern Searching

KMP Algorithm for Pattern Searching

Z algorithm (Linear time pattern searching Algorithm)

Suffix Array Pattern Searching

Aho-Corasick Algorithm for Pattern Searching

Finite Automata algorithm for Pattern Searching

Boyer Moore Algorithm for Pattern Searching

Manacher’s Algorithm – Linear Time Longest Palindromic Substring

Learn to code easily with our course Coding for Everyone. This course is accessible and designed for everyone, even if you’re new to coding. Start today and join millions on a journey to improve your skills!Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

Commit to GfG’s Three-90 Challenge! Purchase a course, complete 90% in 90 days, and save 90% cost click here to explore.

Last Updated :
18 Jan, 2024
Like Article

Save Article


Previous

<!–

8 Min Read | Java

–>


Next


<!–

8 Min Read | Java

–>

Share your thoughts in the comments

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments