Skip to content
geeksforgeeks
  • 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
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • GfG 160: Daily DSA
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • 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:
String Guide for Competitive Programming
Next article icon

String Guide for Competitive Programming

Last Updated : 12 May, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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.

Table of Content

  • Common Operations on String
  • Competitive Programming Tips for Strings in C++
  • Competitive Programming Tips for Strings in Java
  • Competitive Programming Tips for Strings in Python
  • Important String Algorithms for 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 
    cout<<"Enter a word: ";
    cin >> word;
    cout<<endl;
    // Input a line (multiple words) 
    cin.ignore();
    cout<<"Enter a sentence: ";
    getline(cin, sentence);
    cout<<endl;
  
    cout << "word = " << word << "\n";
    cout << "sentence = " << sentence << "\n";
    
    return 0;
}
Java
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        // Prompt the user to enter a single word
        System.out.print("Enter a word: ");
        String word = scanner.next();

        // Prompt the user to enter a sentence
        System.out.print("Enter a sentence: ");
        scanner.nextLine(); // consume the newline character left after reading the word
        String sentence = scanner.nextLine();

        System.out.println("\nEntered word: " + word);
        System.out.println("Entered sentence: " + sentence);

        scanner.close();
    }
}
Python
# Python code to read a word and a sentence from the user

def main():
    # Prompt the user to enter a single word
    word = input("Enter a word: ")

    # Prompt the user to enter a sentence
    sentence = input("Enter a sentence: ")

    # Display the entered word and sentence
    print("\nEntered word:", word)
    print("Entered sentence:", sentence)

if __name__ == "__main__":
    main()
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}");
    }
}
JavaScript
let word, sentence;

// Input a single word
word = prompt("Enter a single word:");

// Input a sentence (multiple words)
sentence = prompt("Enter a sentence:");

// Display the input
console.log("word = " + word);
console.log("sentence = " + sentence);
//This code is contributed by Prachi.

Output
Enter a word: 
Enter a sentence: 
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);
    }
}
Python
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
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);
    }
}
Python
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);
    }
}
JavaScript
// Declare a string variable
let str = "Learn Competitive Programming with GFG!";

// Reverse the string by converting it to an array of characters, reversing the array, and joining it back into a string
let rev = str.split('').reverse().join('');

// Display the reversed string
console.log("Reverse = " + rev);

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
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);
    }
}
Python
str = "Learn Competitive Programming with "
str += "GFG!"
print("New String = " + str)
C#
using System;

class MainClass {
    public static void Main(string[] args) {
        string str = "Learn Competitive Programming with ";
        str += "GFG!";
        Console.WriteLine("New String = " + str);
    }
}
// this coe is contributed by utkarsh
JavaScript
// Initialize a string variable
let str = "Learn Competitive Programming with ";

// Concatenate another string to the existing one using the += operator
str += "GFG!";

// Display the updated string
console.log("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);
    }
}
Python
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);
    }
}
JavaScript
let str = "Learn Competitive Programming with GFG!";
let sortedStr = str.split('').sort().join('');
console.log("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
public class Main {
    public static void main(String[] args) {
        String str = "Learn Competitive Programming with GFG!";
        String sub = str.substring(6, 17); // Index 6 to 16
        System.out.println("Substring from index 6 to 16 = " + sub);
    }
}
Python
str = "Learn Competitive Programming with GFG!"
substring = str[6:17]  # Index 6 to 16
print("Substring from index 6 to 16 =", substring)
C#
using System;

class MainClass {
    public static void Main (string[] args) {
        // Initialize a string
        string str = "Learn Competitive Programming with GFG!";
        
        // Extract substring from index 6 to 16 (11 characters)
        string substring = str.Substring(6, 11);
        
        // Display the extracted substring
        Console.WriteLine("Substring from index 6 to 16 = " + substring);
    }
}
JavaScript
// Main function
function main() {
    // Define the string
    const str = "Learn Competitive Programming with GFG!";
    
    // Extract substring from index 6 to 16
    const substring = str.substring(6, 17);

    // Print the extracted substring
    console.log("Substring from index 6 to 16 =", substring);
}

// Call the main function to execute the program
main();

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;
}
Java
public class Main {
    // Pass by value
    public static int countSpaceSlow(String str, int idx) {
        if (idx == str.length())
            return 0;
        return countSpaceSlow(str, idx + 1)
                + (str.charAt(idx) == ' ' ? 1 : 0);
    }

    // Pass by reference (Java doesn't have true pass-by-reference, but we can use mutable objects like StringBuilder)
    public static int countSpaceFast(StringBuilder str, int idx) {
        if (idx == str.length())
            return 0;
        return countSpaceSlow(str.toString(), idx + 1)
                + (str.charAt(idx) == ' ' ? 1 : 0);
    }

    public static void main(String[] args) {
        String str = "Learn Competitive programming with GFG!";
        System.out.println(countSpaceSlow(str, 0));
        System.out.println(countSpaceFast(new StringBuilder(str), 0));
    }
}
//This code is contributed by Monu.
Python
# Pass by value
def count_space_slow(string, idx):
    if idx == len(string):
        return 0
    return count_space_slow(string, idx + 1) + (string[idx] == ' ')

# Pass by reference (using a list)
def count_space_fast(string, idx):
    if idx == len(string):
        return 0
    return count_space_slow(string, idx + 1) + (string[idx] == ' ')

if __name__ == "__main__":
    string = list("Learn Competitive programming with GFG!")
    print(count_space_slow(string, 0))
    print(count_space_fast(string, 0))
JavaScript
// Pass by value
function countSpaceSlow(str, idx) {
    if (idx === str.length)
        return 0;
    return countSpaceSlow(str, idx + 1) + (str[idx] === ' ' ? 1 : 0);
}

// Pass by reference (not applicable in JavaScript)
// Just for the sake of consistency, we'll keep the function signature
function countSpaceFast(str, idx) {
    if (idx === str.length)
        return 0;
    return countSpaceSlow(str, idx + 1) + (str[idx] === ' ' ? 1 : 0);
}

let str = "Learn Competitive programming with GFG!";
console.log(countSpaceSlow(str, 0));
console.log(countSpaceFast(str, 0)); // No pass by reference in JavaScript, so same as countSpaceSlow

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;
}
Java
public class Main {

    // Slow because of concatenating strings using '+'
    public static String filterLowerCaseSlow(String str) {
        String res = "";
        for (int i = 0; i < str.length(); i++) {
            if (str.charAt(i) >= 'a' && str.charAt(i) <= 'z')
                res += str.charAt(i);
        }
        return res;
    }

    // Fast because of using StringBuilder's append() method
    public static String filterLowerCaseFast(String str) {
        StringBuilder res = new StringBuilder();
        for (int i = 0; i < str.length(); i++) {
            if (str.charAt(i) >= 'a' && str.charAt(i) <= 'z')
                res.append(str.charAt(i));
        }
        return res.toString();
    }

    public static void main(String[] args) {
        String str = "Learn Competitive programming with GFG!";
        System.out.println(filterLowerCaseSlow(str));
        System.out.println(filterLowerCaseFast(str));
    }
}
Python
class Main:
    @staticmethod
    # Slow because of concatenating strings using '+'
    def filter_lower_case_slow(string):
        res = ""
        for char in string:
            if 'a' <= char <= 'z':
                res += char
        return res

    @staticmethod
    # Fast because of using StringBuilder's append() method
    def filter_lower_case_fast(string):
        res = []
        for char in string:
            if 'a' <= char <= 'z':
                res.append(char)
        return ''.join(res)

    @staticmethod
    def main():
        string = "Learn Competitive programming with GFG!"
        print(Main.filter_lower_case_slow(string))
        print(Main.filter_lower_case_fast(string))


# Call the main function to execute the program
Main.main()
JavaScript
// Slow because of concatenating strings using '+'
function filterLowerCaseSlow(str) {
    let res = "";
    for (let i = 0; i < str.length; i++) {
        if (str.charAt(i) >= 'a' && str.charAt(i) <= 'z')
            res += str.charAt(i);
    }
    return res;
}

// Fast because of using StringBuilder's append() method
function filterLowerCaseFast(str) {
    let res = '';
    for (let i = 0; i < str.length; i++) {
        if (str.charAt(i) >= 'a' && str.charAt(i) <= 'z')
            res += str.charAt(i);
    }
    return res;
}

const str = "Learn Competitive programming with GFG!";
console.log(filterLowerCaseSlow(str));
console.log(filterLowerCaseFast(str));

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);
    }
}
Python
class GFG:
    def __init__(self):
        pass

    def main(self):
        # Slow Concatenation of Strings
        str1 = ""
        str1 += "Hello"
        str1 += " "
        str1 += "World"
        print(str1)

        # Fast Concatenation of Strings
        str2 = []
        str2.append("Hello")
        str2.append(" ")
        str2.append("World")
        print("".join(str2))

# Creating an instance of the class and calling the main method
gfg = GFG()
gfg.main()

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

Python
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.

Python
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



Next Article
String Guide for Competitive Programming

M

mrityuanjay8vae
Improve
Article Tags :
  • Strings
  • Competitive Programming
  • DSA
  • strings
Practice Tags :
  • Strings
  • Strings

Similar Reads

  • Competitive Programming - A Complete Guide
    Competitive Programming is a mental sport that enables you to code a given problem under provided constraints. The purpose of this article is to guide every individual possessing a desire to excel in this sport. This article provides a detailed syllabus for Competitive Programming designed by indust
    8 min read
  • Top Programming Languages For Competitive Programming
    Building an application, running a server, or even implementing a game needs a programming language as the foundation. There are more than 700 programming languages that are the most popular ones, and this number will increase day by day. But you don't need to learn all of them. Having a good comman
    12 min read
  • Queue for Competitive Programming
    In competitive programming, a queue is a data structure that is often used to solve problems that involve tasks that need to be completed in a specific order. This article explores the queue data structure and identifies its role as a critical tool for overcoming coding challenges in competitive pro
    8 min read
  • Segment Trees for Competitive Programming
    Segment Tree is one of the most important data structures used for solving problems based on range queries and updates. Problems based on Segment Trees are very common in Programming Contests. This article covers all the necessary concepts required to have a clear understanding of Segment Trees. Tab
    8 min read
  • Fast I/O for Competitive Programming
    In competitive programming, it is important to read input as fast as possible so we save valuable time. You must have seen various problem statements saying: " Warning: Large I/O data, be careful with certain languages (though most should be OK if the algorithm is well designed)" . The key for such
    4 min read
  • Python Input Methods for Competitive Programming
    Python is an amazingly user-friendly language with the only flaw of being slow. In comparison to C, C++, and Java, it is quite slower. In online coding platforms, if the C/C++ limit provided is x. Usually, in Java time provided is 2x, and in Python, it's 5x. To improve the speed of code execution fo
    6 min read
  • 5 Best Languages for Competitive Programming
    Needless to say, Competitive Programming is one of the most crucial and popular aspects of a programmer's journey. Though, all the programmers are strongly recommended to participate in such coding challenges to enhance their coding skills and to get various ravishing prizes, rewards, and other care
    5 min read
  • Suffix Arrays for Competitive Programming
    A suffix array is a sorted array of all suffixes of a given string. More formally if you are given a string 'S' then the suffix array for this string contains the indices 0 to n, such that the suffixes starting from these indices are sorted lexicographically. Example: Input: banana 0 banana 5 a1 ana
    5 min read
  • Arrays for Competitive Programming
    In this article, we will be discussing Arrays which is one of the most commonly used data structure. It also plays a major part in Competitive Programming. Moreover, we will see built-in methods used to write short codes for array operations that can save some crucial time during contests. Table of
    15+ min read
  • Competitive Programming vs General Programming
    Programming enthusiasts face a crossroads - Competitive Programming or General Programming? This article sheds light on the distinctions between Competitive Programming vs General Programming, offering a quick guide for those navigating the coding landscape. Whether you're aiming for speed and preci
    3 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.

'); // $('.spinner-loading-overlay').show(); let script = document.createElement('script'); script.src = 'https://assets.geeksforgeeks.org/v2/editor-prod/static/js/bundle.min.js'; script.defer = true document.head.appendChild(script); script.onload = function() { suggestionModalEditor() //to add editor in suggestion modal if(loginData && loginData.premiumConsent){ personalNoteEditor() //to load editor in personal note } } script.onerror = function() { if($('.editorError').length){ $('.editorError').remove(); } var messageDiv = $('
').text('Editor not loaded due to some issues'); $('#suggestion-section-textarea').append(messageDiv); $('.suggest-bottom-btn').hide(); $('.suggestion-section').hide(); editorLoaded = false; } }); //suggestion modal editor function suggestionModalEditor(){ // editor params const params = { data: undefined, plugins: ["BOLD", "ITALIC", "UNDERLINE", "PREBLOCK"], } // loading editor try { suggestEditorInstance = new GFGEditorWrapper("suggestion-section-textarea", params, { appNode: true }) suggestEditorInstance._createEditor("") $('.spinner-loading-overlay:eq(0)').remove(); editorLoaded = true; } catch (error) { $('.spinner-loading-overlay:eq(0)').remove(); editorLoaded = false; } } //personal note editor function personalNoteEditor(){ // editor params const params = { data: undefined, plugins: ["UNDO", "REDO", "BOLD", "ITALIC", "NUMBERED_LIST", "BULLET_LIST", "TEXTALIGNMENTDROPDOWN"], placeholderText: "Description to be......", } // loading editor try { let notesEditorInstance = new GFGEditorWrapper("pn-editor", params, { appNode: true }) notesEditorInstance._createEditor(loginData&&loginData.user_personal_note?loginData.user_personal_note:"") $('.spinner-loading-overlay:eq(0)').remove(); editorLoaded = true; } catch (error) { $('.spinner-loading-overlay:eq(0)').remove(); editorLoaded = false; } } var lockedCasesHtml = `You can suggest the changes for now and it will be under 'My Suggestions' Tab on Write.

You will be notified via email once the article is available for improvement. Thank you for your valuable feedback!`; var badgesRequiredHtml = `It seems that you do not meet the eligibility criteria to create improvements for this article, as only users who have earned specific badges are permitted to do so.

However, you can still create improvements through the Pick for Improvement section.`; jQuery('.improve-header-sec-child').on('click', function(){ jQuery('.improve-modal--overlay').hide(); $('.improve-modal--suggestion').hide(); jQuery('#suggestion-modal-alert').hide(); }); $('.suggest-change_wrapper, .locked-status--impove-modal .improve-bottom-btn').on('click',function(){ // when suggest changes option is clicked $('.ContentEditable__root').text(""); $('.suggest-bottom-btn').html("Suggest changes"); $('.thank-you-message').css("display","none"); $('.improve-modal--improvement').hide(); $('.improve-modal--suggestion').show(); $('#suggestion-section-textarea').show(); jQuery('#suggestion-modal-alert').hide(); if(suggestEditorInstance !== null){ suggestEditorInstance.setEditorValue(""); } $('.suggestion-section').css('display', 'block'); jQuery('.suggest-bottom-btn').css("display","block"); }); $('.create-improvement_wrapper').on('click',function(){ // when create improvement option clicked then improvement reason will be shown if(loginData && loginData.isLoggedIn) { $('body').append('
'); $('.spinner-loading-overlay').show(); jQuery.ajax({ url: writeApiUrl + 'create-improvement-post/?v=1', type: "POST", contentType: 'application/json; charset=utf-8', dataType: 'json', xhrFields: { withCredentials: true }, data: JSON.stringify({ gfg_id: post_id }), success:function(result) { $('.spinner-loading-overlay:eq(0)').remove(); $('.improve-modal--overlay').hide(); $('.unlocked-status--improve-modal-content').css("display","none"); $('.create-improvement-redirection-to-write').attr('href',writeUrl + 'improve-post/' + `${result.id}` + '/', '_blank'); $('.create-improvement-redirection-to-write')[0].click(); }, error:function(e) { showErrorMessage(e.responseJSON,e.status) }, }); } else { if(loginData && !loginData.isLoggedIn) { $('.improve-modal--overlay').hide(); if ($('.header-main__wrapper').find('.header-main__signup.login-modal-btn').length) { $('.header-main__wrapper').find('.header-main__signup.login-modal-btn').click(); } return; } } }); $('.left-arrow-icon_wrapper').on('click',function(){ if($('.improve-modal--suggestion').is(":visible")) $('.improve-modal--suggestion').hide(); else{ } $('.improve-modal--improvement').show(); }); const showErrorMessage = (result,statusCode) => { if(!result) return; $('.spinner-loading-overlay:eq(0)').remove(); if(statusCode == 403) { $('.improve-modal--improve-content.error-message').html(result.message); jQuery('.improve-modal--overlay').show(); jQuery('.improve-modal--improvement').show(); $('.locked-status--impove-modal').css("display","block"); $('.unlocked-status--improve-modal-content').css("display","none"); $('.improve-modal--improvement').attr("status","locked"); return; } } function suggestionCall() { var editorValue = suggestEditorInstance.getValue(); var suggest_val = $(".ContentEditable__root").find("[data-lexical-text='true']").map(function() { return $(this).text().trim(); }).get().join(' '); suggest_val = suggest_val.replace(/\s+/g, ' ').trim(); var array_String= suggest_val.split(" ") //array of words var gCaptchaToken = $("#g-recaptcha-response-suggestion-form").val(); var error_msg = false; if(suggest_val != "" && array_String.length >=4){ if(editorValue.length { jQuery('.ContentEditable__root').focus(); jQuery('#suggestion-modal-alert').hide(); }, 3000); } } document.querySelector('.suggest-bottom-btn').addEventListener('click', function(){ jQuery('body').append('
'); jQuery('.spinner-loading-overlay').show(); if(loginData && loginData.isLoggedIn) { suggestionCall(); return; } // script for grecaptcha loaded in loginmodal.html and call function to set the token setGoogleRecaptcha(); }); $('.improvement-bottom-btn.create-improvement-btn').click(function() { //create improvement button is clicked $('body').append('
'); $('.spinner-loading-overlay').show(); // send this option via create-improvement-post api jQuery.ajax({ url: writeApiUrl + 'create-improvement-post/?v=1', type: "POST", contentType: 'application/json; charset=utf-8', dataType: 'json', xhrFields: { withCredentials: true }, data: JSON.stringify({ gfg_id: post_id }), success:function(result) { $('.spinner-loading-overlay:eq(0)').remove(); $('.improve-modal--overlay').hide(); $('.create-improvement-redirection-to-write').attr('href',writeUrl + 'improve-post/' + `${result.id}` + '/', '_blank'); $('.create-improvement-redirection-to-write')[0].click(); }, error:function(e) { showErrorMessage(e.responseJSON,e.status); }, }); });
"For an ad-free experience and exclusive features, subscribe to our Premium Plan!"
Continue without supporting
`; $('body').append(adBlockerModal); $('body').addClass('body-for-ad-blocker'); const modal = document.getElementById("adBlockerModal"); modal.style.display = "block"; } function handleAdBlockerClick(type){ if(type == 'disabled'){ window.location.reload(); } else if(type == 'info'){ document.getElementById("ad-blocker-div").style.display = "none"; document.getElementById("ad-blocker-info-div").style.display = "flex"; handleAdBlockerIconClick(0); } } var lastSelected= null; //Mapping of name and video URL with the index. const adBlockerVideoMap = [ ['Ad Block Plus','https://media.geeksforgeeks.org/auth-dashboard-uploads/abp-blocker-min.mp4'], ['Ad Block','https://media.geeksforgeeks.org/auth-dashboard-uploads/Ad-block-min.mp4'], ['uBlock Origin','https://media.geeksforgeeks.org/auth-dashboard-uploads/ub-blocke-min.mp4'], ['uBlock','https://media.geeksforgeeks.org/auth-dashboard-uploads/U-blocker-min.mp4'], ] function handleAdBlockerIconClick(currSelected){ const videocontainer = document.getElementById('ad-blocker-info-div-gif'); const videosource = document.getElementById('ad-blocker-info-div-gif-src'); if(lastSelected != null){ document.getElementById("ad-blocker-info-div-icons-"+lastSelected).style.backgroundColor = "white"; document.getElementById("ad-blocker-info-div-icons-"+lastSelected).style.borderColor = "#D6D6D6"; } document.getElementById("ad-blocker-info-div-icons-"+currSelected).style.backgroundColor = "#D9D9D9"; document.getElementById("ad-blocker-info-div-icons-"+currSelected).style.borderColor = "#848484"; document.getElementById('ad-blocker-info-div-name-span').innerHTML = adBlockerVideoMap[currSelected][0] videocontainer.pause(); videosource.setAttribute('src', adBlockerVideoMap[currSelected][1]); videocontainer.load(); videocontainer.play(); lastSelected = currSelected; }

What kind of Experience do you want to share?

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