Quick way to check if all the characters of a string are same

20 Jun, 2022
Given a string, check if all the characters of the string are the same or not.
Examples: 
Input : s = "geeks"
Output : No

Input : s = "gggg" 
Output : Yes
Simple Way
To find whether a string has all the same characters. Traverse the whole string from index 1 and check whether that character matches the first character of the string or not. If yes, then match until string size. If no, then break the loop. 
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find whether the string// has all same characters or not.#include <iostream>using namespace std; bool allCharactersSame(string s){    int n = s.length();    for (int i = 1; i < n; i++)        if (s[i] != s[0])            return false;     return true;} // Driver codeint main(){    string s = "aaa";    if (allCharactersSame(s))        cout << "Yes";    else        cout << "No";     return 0;}
// Java program to find whether the String// has all same characters or not.import java.io.*; public class GFG{ static boolean allCharactersSame(String s){    int n = s.length();    for (int i = 1; i < n; i++)        if (s.charAt(i) != s.charAt(0))            return false;             return true;} // Driver code    static public void main (String[] args){        String s = "aaa";    if (allCharactersSame(s))        System.out.println("Yes");    else        System.out.println("No");             }} // This Code is contributed by vt_m.
# Python3 program to find whether the string# has all same characters or not. # Function to check the string has# all same characters or not .def allCharactersSame(s) :    n = len(s)    for i in range(1, n) :        if s[i] != s[0] :            return False     return True # Driver codeif __name__ == "__main__" :         s = "aaa"    if allCharactersSame(s) :        print("Yes")    else :        print("No") # This code is contributed by ANKITRAI1
// C# program to find whether the string// has all same characters or not.using System; public class GFG{ static bool allCharactersSame(string s){    int n = s.Length;    for (int i = 1; i < n; i++)        if (s[i] != s[0])            return false;     return true;} // Driver code    static public void Main (String []args){        string s = "aaa";    if (allCharactersSame(s))        Console.WriteLine("Yes");    else        Console.WriteLine("No");             }} // This code is contributed by vt_m.
<?php// PHP program to find whether// the string has all same// characters or not.function allCharactersSame($s){    $n = strlen($s);    for ($i = 1; $i < $n; $i++)        if ($s[$i] != $s[0])            return false;     return true;} // Driver code$s = "aaa";if (allCharactersSame($s))echo "Yes";elseecho "No"; // This code is contributed// by ChitraNayal?>
<script>    // Javascript program to find whether the string    // has all same characters or not.         function allCharactersSame(s)    {        let n = s.length;        for (let i = 1; i < n; i++)            if (s[i] != s[0])                return false;         return true;    }         let s = "aaa";    if (allCharactersSame(s))        document.write("Yes");    else        document.write("No");                 // This code is contributed by suresh07.</script>
Yes
Time Complexity: O(n)
Here n is the length of the string.
Auxiliary Space: O(1)
As constant extra space is used.
Quick Way (Not time complexity wise, but in terms of number of lines of code)
The idea is to use find_first_not_of() in C++ STL. find_first_not_of() finds and returns the position of the first character that does not match a specified character (or any of the specified characters in case of a string). 
C++
// A quick C++ program to find whether the// string has all same characters or not.#include <iostream>using namespace std; bool allCharactersSame(string s){    return (s.find_first_not_of(s[0]) == string::npos);} // Driver codeint main(){    string s = "aaa";    if (allCharactersSame(s))        cout << "Yes";    else        cout << "No";     return 0;}
Yes
One other way is using a SET
The idea is to add all the characters of a string to a set. After adding, if the size of the set is greater than 1, it means different characters are present, if the size is exactly 1, it means there is only one unique character.
Below is the implementation of the above logic.
C++
Java
Python3
C#
Javascript
// C++ program for above approach#include <bits/stdc++.h>using namespace std; // Function to check is all the// characters in string are or notvoid allCharactersSame(string s){    set <char> s1;       // Insert characters in the set    for ( int i=0 ; i < s.length() ; i++)        s1.insert(s[i]);         // If all characters are same    // Size of set will always be 1    if ( s1.size() == 1 )        cout << "YES";    else        cout << "NO";} // Driver codeint main(){    string str = "nnnn";    allCharactersSame(str);      return 0;}
// Java program for above approachimport java.io.*;import java.util.*; class GFG{     // Function to check is all the// characters in string are or notpublic static void allCharactersSame(String s){    Set<Character> s1 = new HashSet<Character>();         // Insert characters in the set    for(int i = 0; i < s.length(); i++)        s1.add(s.charAt(i));          // If all characters are same    // Size of set will always be 1    if (s1.size() == 1)        System.out.println("YES");    else        System.out.println("NO");} // Driver Codepublic static void main(String[] args){    String str = "nnnn";         allCharactersSame(str);}} // This code is contributed by divyeshrabadiya07
# Python3 program for# the above approach # Function to check is# all the characters in# string are or notdef allCharactersSame(s):       s1 = []     # Insert characters in    # the set    for i in range(len(s)):        s1.append(s[i])     # If all characters are same    # Size of set will always be 1    s1 = list(set(s1))    if(len(s1) == 1):        print("YES")    else:        print("NO") # Driver codeStr = "nnnn"allCharactersSame(Str) # This code is contributed by avanitrachhadiya2155
// C# program for above approachusing System;using System.Collections.Generic; class GFG{     // Function to check is all the// characters in string are or notstatic void allCharactersSame(string s){    HashSet<char> s1 = new HashSet<char>();          // Insert characters in the set    for(int i = 0; i < s.Length; i++)        s1.Add(s[i]);           // If all characters are same    // Size of set will always be 1    if (s1.Count == 1)        Console.WriteLine("YES");    else        Console.WriteLine("NO");} // Driver code static void Main(){    string str = "nnnn";         allCharactersSame(str);}} // This code is contributed by divyesh072019
<script>// Javascript program for above approach     // Function to check is all the    // characters in string are or not    function allCharactersSame(s)    {        let s1 = new Set();        // Insert characters in the set    for(let i = 0; i < s.length; i++)    {           s1.add(s[i]);     }          // If all characters are same    // Size of set will always be 1    if (s1.size == 1)        document.write("YES");    else        document.write("NO");    }         // Driver Code    let str = "nnnn";    allCharactersSame(str);         //This code is contributed by rag2127     </script>
YES
Time Complexity: O(nLogn)
As insertion in a set takes Logn time and we are inserting n elements.
Auxiliary Space: O(n)
Extra space is used to store the elements in the set.
 This article is contributed by Jatin Goyal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
 
vt_m
ankthon
ukasp
OrdinaryMoron
nikhilmohite3
avanitrachhadiya2155
divyeshrabadiya07
divyesh072019
suresh07
rag2127
abhijeet19403
STL
C++
Strings
Strings
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Vector in C++ STL
Map in C++ Standard Template Library (STL)
std::sort() in C++ STL
Initialize a vector in C++ (7 different ways)
Bitwise Operators in C/C++
Write a program to reverse an array or string
Reverse a string in Java
Write a program to print all permutations of a given string
C++ Data Types
Check for Balanced Brackets in an expression (well-formedness) using Stack