Open In App

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

Last Updated : 23 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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

Recommended Practice

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

// 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 code
int main()
{
    string s = "aaa";
    if (allCharactersSame(s))
        cout << "Yes";
    else
        cout << "No";
 
    return 0;
}

                    

Java

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

# 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 code
if __name__ == "__main__" :
     
    s = "aaa"
    if allCharactersSame(s) :
        print("Yes")
    else :
        print("No")
 
# This code is contributed by ANKITRAI1

                    

C#

// 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
// 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";
else
echo "No";
 
// This code is contributed
// by ChitraNayal
?>

                    

Javascript

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

                    

Output
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 code
int main()
{
    string s = "aaa";
    if (allCharactersSame(s))
        cout << "Yes";
    else
        cout << "No";
 
    return 0;
}

                    

Java

// A quick java program to find whether the
// string has all same characters or not.
 
import java.util.*;
 
public class Main {
    static boolean allCharactersSame(String s) {
        for (int i = 1; i < s.length(); i++) {
            if (s.charAt(i) != s.charAt(0)) {
                return false;
            }
        }
        return true;
    }
     
  // Driver code
    public static void main(String[] args) {
        String s = "aaa";
        if (allCharactersSame(s))
            System.out.println("Yes");
        else
            System.out.println("No");
    }
}
 
// This code is contributed by prince

                    

Python3

# Python program for the above approach
 
def allCharactersSame(s):
    return all(c == s[0] for c in s)
 
# Driver code
s = "aaa"
if allCharactersSame(s):
    print("Yes")
else:
    print("No")
 
# This code is contributed by adityashatmfh

                    

C#

// A quick C# program to find whether the
// string has all same characters or not.
using System;
 
public class GFG {
    static bool allCharactersSame(string s)
    {
        return (s.TrimStart(s[0]) == "");
    }
    // Driver code
    static public void Main()
    {
        string s = "aaa";
        if (allCharactersSame(s))
            Console.WriteLine("Yes");
        else
            Console.WriteLine("No");
    }
}

                    

Javascript

// Javascript program for the above approach
 
function allCharactersSame(s) {
  return s.split('').every(c => c === s[0]);
}
 
// Driver code
const s = "aaa";
if (allCharactersSame(s)) {
  console.log("Yes");
} else {
  console.log("No");
}
 
 
// This code is contributed princekumaras

                    

Output
Yes

Time Complexity: O(N)
Auxiliary Space: O(1)

Quick Way (Not time complexity wise, but in terms of number of lines of code)

The idea is to use built-in all()           function in Python.
The all()           function returns True if all items in an iterable object are same with comparing character, otherwise it returns False. For empty iterable object, the all()           function also returns True.

Python3

s = "aaa"
 
all_same = all(ch == s[0] for ch in s)
print(all_same)
 
# This code is contributed by Susobhan Akhuli

                    


Time Complexity: O(N) [For iteration]
Auxiliary Space: O(1)


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

// C++ program for above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to check is all the
// characters in string are or not
void 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 code
int main()
{
    string str = "nnnn";
    allCharactersSame(str);
      return 0;
}

                    

Java

// Java program for above approach
import java.io.*;
import java.util.*;
 
class GFG{
     
// Function to check is all the
// characters in string are or not
public 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 Code
public static void main(String[] args)
{
    String str = "nnnn";
     
    allCharactersSame(str);
}
}
 
// This code is contributed by divyeshrabadiya07

                    

Python3

# Python3 program for
# the above approach
 
# Function to check is
# all the characters in
# string are or not
def 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 code
Str = "nnnn"
allCharactersSame(Str)
 
# This code is contributed by avanitrachhadiya2155

                    

C#

// C# program for above approach
using System;
using System.Collections.Generic;
 
class GFG{
     
// Function to check is all the
// characters in string are or not
static 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

                    

Javascript

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

                    

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


 



Similar Reads

Minimum characters to be replaced in given String to make all characters same
Given a string str of size N consisting of lowercase English characters, the task is to find the minimum characters to be replaced to make all characters of string str same. Any character can be replaced by any other character. Example: Input: str="geeksforgeeks"Output: 9Explanation: Replace all the characters except 'e' of the string with 'e'. Inp
7 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 : 010101100011Output : 4Method 1 (Change in value
8 min read
Make all characters of a string same by minimum number of increments or decrements of ASCII values of characters
Given a string S of length N, the task is to make all characters of the string the same by incrementing/decrementing the ASCII value of any character by 1 any number of times. Note: All characters must be changed to a character of the original string. Examples: Input: S = "geeks"Output: 20Explanation:The minimum number of operations can be attained
6 min read
Modify characters of a string by adding integer values of same-indexed characters from another given string
Given two strings S and N of the same length, consisting of alphabetical and numeric characters respectively, the task is to generate a new string obtained by adding the integer value of each character of string N with the ASCII value of the same indexed character of string S. Finally, print the resultant string.Note: If the sum exceeds 122, then s
6 min read
Check whether two strings contain same characters in same order
Given two strings s1 and s2, the task is to find whether the two strings contain the same characters that occur in the same order. For example string "Geeks" and string "Geks" contain the same characters in same order. Examples: Input: s1 = "Geeks", s2 = "Geks" Output: Yes Input: s1 = "Arnab", s2 = "Andrew" Output: No Approach: We have two strings
9 min read
Check if given strings can be made same by swapping two characters of same or different strings
Given an array of equal-length strings, arr[] of size N, the task is to check if all the strings can be made equal by repeatedly swapping any pair of characters of same or different strings from the given array. If found to be true, then print "YES". Otherwise, print "NO". Examples: Input: arr[] = { "acbdd", "abcee" } Output: YES Explanation: Swapp
11 min read
Minimum characters to be replaced to make frequency of all characters same
Given a string S consisting of alphabets ['A' - 'Z'], the task is to find the minimum number of operations required to make frequency of every character equal. In one operation any character of the string can be chosen and replaced with another valid character.Examples: Input: S = "ABCB" Output: 1 Explanation: In the given string character 'C' can
6 min read
Minimize swaps of pairs of characters required such that no two adjacent characters in the string are same
Given a string S consisting of N characters, the task is to find the minimum number of pairs of characters that are required to be swapped such that no two adjacent characters are the same. If it is not possible to do so, then print "-1". Examples: Input: S = "ABAACD"Output: 1Explanation: Swapping S[3] and S[4] modifies the given string S to "ABACA
9 min read
Rearrange characters in a sorted string such that no pair of adjacent characters are the same
Given a sorted string S consisting of N lowercase characters, the task is to rearrange characters in the given string such that no two adjacent characters are the same. If it is not possible to rearrange as per the given criteria, then print "-1". Examples: Input: S = "aaabc"Output: abaca Input: S = "aa"Output: -1 Approach: The given problem can be
20 min read
String with k distinct characters and no same characters adjacent
Given n and k, print a string that has n characters. The string should have exactly k distinct characters and no adjacent positions. Examples: Input : n = 5, k = 3 Output : abcab Explanation: 3 distinct character a, b, c and n length string. Input: 3 2 Output: aba Explanation: 2 distinct character 'a' and 'b' and n length string. Consider the first
6 min read
Article Tags :
Practice Tags :