Quick way to check if all the characters of a string are same
Last Updated :
23 Mar, 2023
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++
// 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>
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
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>
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
Program to check if first and the last characters of string are equal We are given a string, we need to check whether the first and last characters of the string str are equal or not. Case sensitivity is to be considered. Examples : Input : university Output : Not Equal Explanation: In the string "university", the first character is 'u' and the last character is 'y',
4 min read
Check if a given string is made up of two alternating characters Given a string str, the task is to check whether the given string is made up of only two alternating characters.Examples: Input: str = "ABABABAB" Output: YesInput: str = "XYZ" Output: No Recommended: Please try your approach on {IDE} first, before moving on to the solution.Approach: In order for the
11 min read
Check if a string is made up of K alternating characters Given a string str and an integer K, the task is to check if it is made up of K alternating characters. Examples: Input: str = "acdeac", K = 4 Output: Yes Input: str = "abcdcab", K = 2 Output: No Approach: In order for the string to be made up of K alternating characters, it must satisfy the followi
5 min read
Check if both halves of the string have same set of characters Given a string of lowercase characters only, the task is to check if it is possible to split a string from the middle which will give two halves having the same characters and same frequency of each character. If the length of the given string is ODD then ignore the middle element and check for the
12 min read
Check if there is any common character in two given strings Given two strings. The task is to check that is there any common character in between two strings. Examples: Input: s1 = "geeksforgeeks", s2 = "geeks" Output: Yes Input: s1 = "geeks", s2 = "for" Output: No Approach: Traverse the 1st string and map the characters of the string with its frequency, in
8 min read
Print all the duplicate characters in a string Given a string s, the task is to identify all characters that appear more than once and print each as a list containing the character and its count. Examples:Input: s = "geeksforgeeks"Output: ['e', 4], ['g', 2], ['k', 2], ['s', 2]Explanation: Characters e, g, k, and s appear more than once. Their co
8 min read
Python program to check if a string contains all unique characters To implement an algorithm to determine if a string contains all unique characters. Examples: Input : s = "abcd" Output: True "abcd" doesn't contain any duplicates. Hence the output is True. Input : s = "abbd" Output: False "abbd" contains duplicates. Hence the output is False. One solution is to cre
3 min read
Find the duplicate characters in a string in O(1) space Given a string str, the task is to find all the duplicate characters present in a given string in lexicographical order without using any additional data structure. Examples: Input: str = "geeksforgeeks" Output: e g k s Explanation: Frequency of character 'g' = 2 Frequency of character 'e' = 4 Frequ
10 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
Check if String formed by first and last X characters of a String is a Palindrome Given a string str and an integer X. The task is to find whether the first X characters of both string str and reversed string str are same or not. If it is equal then print true, otherwise print false. Examples: Input: str = abcdefba, X = 2Output: trueExplanation: First 2 characters of both string
5 min read