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
Frequency of character ‘k’ = 2
Frequency of character ‘s’ = 2
Therefore, the required output is e g k s.
Input: str = “apple”
Output: p
Explanation:
Frequency of character ‘p’ = 2.
Therefore, the required output is p.
Approach: Follow the steps below to solve the problem:
- Initialize a variable, say first, where ith bit of first check if the character (i + ‘a’) present in the string at least once or not.
- Initialize a variable, say second, where ith bit of second check if the character (i + ‘a’) present in the string at least twice or not.
- Iterate over the characters of the string. For every ith character, check if str[i] has already occurred in the string or not. If found to be true, then set the (str[i] – ‘a’)th bit of second.
- Otherwise, set (str[i] – ‘a’)th bit of first.
- Finally, iterate over the range [0, 25] and check if ith bit of both first and second is set or not. If found to be true, then print (i + ‘a’).
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void findDuplicate(string str, int N)
{
int first = 0;
int second = 0;
for ( int i = 0; i < N; i++) {
if (first & (1 << (str[i] - 'a' ))) {
second
= second | (1 << (str[i] - 'a' ));
}
else {
first
= first | (1 << (str[i] - 'a' ));
}
}
for ( int i = 0; i < 26; i++) {
if ((first & (1 << i))
&& (second & (1 << i))) {
cout << char (i + 'a' ) << " " ;
}
}
}
int main()
{
string str = "geeksforgeeks" ;
int N = str.length();
findDuplicate(str, N);
}
|
Java
public class GFG
{
static void findDuplicate(String str, int N)
{
int first = 0 ;
int second = 0 ;
for ( int i = 0 ; i < N; i++)
{
if ((first & ( 1 << (str.charAt(i) - 'a' ))) != 0 )
{
second
= second | ( 1 << (str.charAt(i) - 'a' ));
}
else
{
first
= first | ( 1 << (str.charAt(i) - 'a' ));
}
}
for ( int i = 0 ; i < 26 ; i++)
{
if (((first & ( 1 << i))
& (second & ( 1 << i))) != 0 ) {
System.out.print(( char )(i + 'a' ) + " " );
}
}
}
static public void main(String args[])
{
String str = "geeksforgeeks" ;
int N = str.length();
findDuplicate(str, N);
}
}
|
Python3
def findDuplicate(str1, N):
first = 0
second = 0
for i in range (N):
if (first & ( 1 << ( ord (str1[i]) - 97 ))):
second = second | ( 1 << ( ord (str1[i]) - 97 ))
else :
first = first | ( 1 << ( ord (str1[i]) - 97 ))
for i in range ( 26 ):
if ((first & ( 1 << i)) and (second & ( 1 << i))):
print ( chr (i + 97 ), end = " " )
if __name__ = = '__main__' :
str1 = "geeksforgeeks"
N = len (str1)
findDuplicate(str1, N)
|
C#
using System;
class GFG
{
static void findDuplicate( string str, int N)
{
int first = 0;
int second = 0;
for ( int i = 0; i < N; i++) {
if ((first & (1 << (str[i] - 'a' ))) != 0)
{
second
= second | (1 << (str[i] - 'a' ));
}
else
{
first
= first | (1 << (str[i] - 'a' ));
}
}
for ( int i = 0; i < 26; i++)
{
if (((first & (1 << i))
& (second & (1 << i))) != 0) {
Console.Write(( char )(i + 'a' ) + " " );
}
}
}
static public void Main()
{
string str = "geeksforgeeks" ;
int N = str.Length;
findDuplicate(str, N);
}
}
|
Javascript
<script>
function findDuplicate(str, N)
{
let first = 0;
let second = 0;
for (let i = 0; i < N; i++)
{
if ((first & (1 << (str[i].charCodeAt() -
'a' .charCodeAt()))) != 0)
{
second = second | (1 << (str[i].charCodeAt() -
'a' .charCodeAt()));
}
else
{
first = first | (1 << (str[i].charCodeAt() -
'a' .charCodeAt()));
}
}
for (let i = 0; i < 26; i++)
{
if (((first & (1 << i)) &
(second & (1 << i))) != 0)
{
document.write(String.fromCharCode(
i + 'a' .charCodeAt()) + " " );
}
}
}
let str = "geeksforgeeks" ;
let N = str.length;
findDuplicate(str, N);
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(1)
Approach: Using Sorting
Steps:
- First, sort the string.
- Then compare adjacent characters to find duplicates.
- Last return the result.
C++
#include <algorithm>
#include <iostream>
#include <string>
using namespace std;
string findDuplicateChars(string str)
{
sort(str.begin(), str.end());
string result = "" ;
for ( int i = 1; i < str.length(); i++) {
if (str[i] == str[i - 1]
&& result.find(str[i]) == string::npos) {
if (result.length() > 0) {
result += " " ;
}
result += str[i];
}
}
return result;
}
int main()
{
string str = "geeksforgeeks" ;
string duplicates = findDuplicateChars(str);
cout << duplicates << endl;
return 0;
}
|
Java
import java.util.Arrays;
public class GFG {
static String findDuplicateChars(String str)
{
char [] charArray = str.toCharArray();
Arrays.sort(charArray);
StringBuilder result = new StringBuilder();
for ( int i = 1 ; i < charArray.length; i++) {
if (charArray[i] == charArray[i - 1 ]
&& result.indexOf(
String.valueOf(charArray[i]))
== - 1 ) {
if (result.length() > 0 ) {
result.append( " " );
}
result.append(charArray[i]);
}
}
return result.toString();
}
public static void main(String[] args)
{
String str = "geeksforgeeks" ;
String duplicates = findDuplicateChars(str);
System.out.println(duplicates);
}
}
|
Python3
def findDuplicateChars(string):
string = ''.join( sorted (string))
result = ""
for i in range ( 1 , len (string)):
if string[i] = = string[i - 1 ] and string[i] not in result:
if len (result) > 0 :
result + = " "
result + = string[i]
return result
if __name__ = = "__main__" :
string = "geeksforgeeks"
duplicates = findDuplicateChars(string)
print (duplicates)
|
C#
using System;
using System.Linq;
class Program
{
static string FindDuplicateChars( string str)
{
char [] charArray = str.ToCharArray();
Array.Sort(charArray);
string sortedStr = new string (charArray);
string result = "" ;
for ( int i = 1; i < sortedStr.Length; i++)
{
if (sortedStr[i] == sortedStr[i - 1] && result.IndexOf(sortedStr[i]) == -1)
{
if (! string .IsNullOrEmpty(result))
{
result += " " ;
}
result += sortedStr[i].ToString();
}
}
return result;
}
static void Main()
{
string str = "geeksforgeeks" ;
string duplicates = FindDuplicateChars(str);
Console.WriteLine(duplicates);
}
}
|
Javascript
function findDuplicateChars(str) {
let charArray = str.split( '' );
charArray.sort();
let result = '' ;
for (let i = 1; i < charArray.length; i++) {
if (charArray[i] === charArray[i - 1] && result.indexOf(charArray[i]) === -1) {
if (result.length > 0) {
result += ' ' ;
}
result += charArray[i];
}
}
return result;
}
let str = 'geeksforgeeks' ;
let duplicates = findDuplicateChars(str);
console.log(duplicates);
|
Time Complexity: O(nlog(n)), where n is the length of the input string .
Auxiliary Space: O(n), where n is the length of the input string.
Last Updated :
04 Dec, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...