Find the duplicate characters in a string in O(1) space - GeeksforGeeks

29 Jan, 2022
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++
Java
Python3
C#
Javascript
// C++ program to implement// the above approach#include <bits/stdc++.h>using namespace std; // Function to find duplicate characters// in string without using any additional// data structurevoid findDuplicate(string str, int N){     // Check if (i + 'a') is present    // in str at least once or not.    int first = 0;     // Check if (i + 'a') is present    // in str at least twice or not.    int second = 0;     // Iterate over the characters    // of the string str    for (int i = 0; i < N; i++) {         // If str[i] has already occurred in str        if (first & (1 << (str[i] - 'a'))) {             // Set (str[i] - 'a')-th bit of second            second                = second | (1 << (str[i] - 'a'));        }        else {             // Set (str[i] - 'a')-th bit of second            first                = first | (1 << (str[i] - 'a'));        }    }     // Iterate over the range [0, 25]    for (int i = 0; i < 26; i++) {         // If i-th bit of both first        // and second is Set        if ((first & (1 << i))            && (second & (1 << i))) {             cout << char(i + 'a') << " ";        }    }} // Driver Codeint main(){    string str = "geeksforgeeks";    int N = str.length();     findDuplicate(str, N);}
// Java program for the above approachpublic class GFG{   // Function to find duplicate characters  // in string without using any additional  // data structure  static void findDuplicate(String str, int N)  {     // Check if (i + 'a') is present    // in str at least once or not.    int first = 0;     // Check if (i + 'a') is present    // in str at least twice or not.    int second = 0;     // Iterate over the characters    // of the string str    for (int i = 0; i < N; i++)    {       // If str[i] has already occurred in str      if ((first & (1 << (str.charAt(i) - 'a'))) != 0)      {         // Set (str[i] - 'a')-th bit of second        second          = second | (1 << (str.charAt(i) - 'a'));      }      else      {         // Set (str[i] - 'a')-th bit of second        first          = first | (1 << (str.charAt(i) - 'a'));      }    }     // Iterate over the range [0, 25]    for (int i = 0; i < 26; i++)    {       // If i-th bit of both first      // and second is Set      if (((first & (1 << i))           & (second & (1 << i))) != 0) {         System.out.print((char)(i + 'a') + " ");      }    }  }   // Driver Code  static public void main(String args[])  {    String str = "geeksforgeeks";    int N = str.length();     findDuplicate(str, N);  }} // This code is contributed by AnkThon.
# Python 3 code added. program to implement# the above approach # Function to find duplicate characters# in string without using any additional# data structuredef findDuplicate(str1, N):       # Check if (i + 'a') is present    # in str1 at least once or not.    first = 0     # Check if (i + 'a') is present    # in str1 at least twice or not.    second = 0     # Iterate over the characters    # of the string str1    for i in range(N):               # If str1[i] has already occurred in str1        if (first & (1 << (ord(str1[i]) - 97))):                       # Set (str1[i] - 'a')-th bit of second            second = second | (1 << (ord(str1[i]) - 97))        else:            # Set (str1[i] - 'a')-th bit of second            first = first | (1 << (ord(str1[i]) - 97))     # Iterate over the range [0, 25]    for i in range(26):               # If i-th bit of both first        # and second is Set        if ((first & (1 << i)) and (second & (1 << i))):            print(chr(i + 97), end = " ") # Driver Codeif __name__ == '__main__':    str1 = "geeksforgeeks"    N = len(str1)    findDuplicate(str1, N)     # This code is contributed by SURENDRA_GANGWAR.
// C# program for the above approachusing System;class GFG{   // Function to find duplicate characters  // in string without using any additional  // data structure  static void findDuplicate(string str, int N)  {     // Check if (i + 'a') is present    // in str at least once or not.    int first = 0;     // Check if (i + 'a') is present    // in str at least twice or not.    int second = 0;     // Iterate over the characters    // of the string str    for (int i = 0; i < N; i++) {       // If str[i] has already occurred in str      if ((first & (1 << (str[i] - 'a'))) != 0)      {         // Set (str[i] - 'a')-th bit of second        second          = second | (1 << (str[i] - 'a'));      }      else      {         // Set (str[i] - 'a')-th bit of second        first          = first | (1 << (str[i] - 'a'));      }    }     // Iterate over the range [0, 25]    for (int i = 0; i < 26; i++)    {       // If i-th bit of both first      // and second is Set      if (((first & (1 << i))           & (second & (1 << i))) != 0) {         Console.Write((char)(i + 'a') + " ");      }    }  }   // Driver Code  static public void Main()  {    string str = "geeksforgeeks";    int N = str.Length;     findDuplicate(str, N);  }} // This code is contributed by susmitakundugoaldanga.
<script> // Javascript program for the above approach // Function to find duplicate characters// in string without using any additional// data structurefunction findDuplicate(str, N){     // Check if (i + 'a') is present    // in str at least once or not.    let first = 0;         // Check if (i + 'a') is present    // in str at least twice or not.    let second = 0;         // Iterate over the characters    // of the string str    for(let i = 0; i < N; i++)    {                 // If str[i] has already occurred in str        if ((first & (1 << (str[i].charCodeAt() -                               'a'.charCodeAt()))) != 0)        {                     // Set (str[i] - 'a')-th bit of second            second = second | (1 << (str[i].charCodeAt() -                                        'a'.charCodeAt()));        }        else        {                         // Set (str[i] - 'a')-th bit of second            first = first | (1 << (str[i].charCodeAt() -                                      'a'.charCodeAt()));        }    }         // Iterate over the range [0, 25]    for(let i = 0; i < 26; i++)    {                 // If i-th bit of both first        // and second is Set        if (((first & (1 << i)) &            (second & (1 << i))) != 0)        {            document.write(String.fromCharCode(                i + 'a'.charCodeAt()) + " ");        }    }} // Driver codelet str = "geeksforgeeks";let N = str.length; findDuplicate(str, N); // This code is contributed by divyesh072019 </script>
e g k s
 
Time Complexity: O(N)Auxiliary Space: O(1)
SURENDRA_GANGWAR
susmitakundugoaldanga
ankthon
divyesh072019
simmytarika5
surinderdawra388
frequency-counting
Searching
Strings
Searching
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Search an element in a sorted and rotated array
Program to find largest element in an array
Given an array of size n and a number k, find all elements that appear more than n/k times
k largest(or smallest) elements in an array
Median of two sorted arrays of different sizes
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
Longest Common Subsequence | DP-4