Open In App

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

Improve
Improve
Like Article
Like
Save
Share
Report

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:
Explanation: 
Frequency of character ‘p’ = 2. 
Therefore, the required output is p.

Approach: Follow the steps below to solve the problem:

Below is the implementation of the above approach:

C++




// 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 structure
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'))) {
 
            // 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 Code
int main()
{
    string str = "geeksforgeeks";
    int N = str.length();
 
    findDuplicate(str, N);
}


Java




// Java program for the above approach
public 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.


Python3




# Python 3 code added. program to implement
# the above approach
 
# Function to find duplicate characters
# in string without using any additional
# data structure
def 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 Code
if __name__ == '__main__':
    str1 = "geeksforgeeks"
    N = len(str1)
    findDuplicate(str1, N)
 
    # This code is contributed by SURENDRA_GANGWAR.


C#




// C# program for the above approach
using 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.


Javascript




<script>
 
// Javascript program for the above approach
 
// Function to find duplicate characters
// in string without using any additional
// data structure
function 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 code
let str = "geeksforgeeks";
let N = str.length;
 
findDuplicate(str, N);
 
// This code is contributed by divyesh072019
 
</script>


Output

e g k s







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




// C++ program to implement
// the above approach
 
#include <algorithm>
#include <iostream>
#include <string>
 
using namespace std;
 
string findDuplicateChars(string str)
{
    // sort the string in lexicographical order
    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) {
                // add a space before adding the duplicate
                // character
                result += " ";
            }
            // add the duplicate character to the result
            // string
            result += str[i];
        }
    }
    return result;
}
 
// Driver Code
int main()
{
    string str = "geeksforgeeks";
    string duplicates = findDuplicateChars(str);
    cout << duplicates << endl;
    return 0;
}


Java




import java.util.Arrays;
 
public class GFG {
    // Function to find and return duplicate characters in a
    // string
    static String findDuplicateChars(String str)
    {
        // Convert the string to a character array
        char[] charArray = str.toCharArray();
 
        // Sort the character array in lexicographical order
        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) {
                    // add a space before adding the
                    // duplicate character
                    result.append(" ");
                }
                // add the duplicate character to the result
                // string
                result.append(charArray[i]);
            }
        }
        return result.toString();
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        String str = "geeksforgeeks";
        String duplicates = findDuplicateChars(str);
        System.out.println(duplicates);
    }
}


Python3




def findDuplicateChars(string):
    # Sort the string in lexicographical order
    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:
                # Add a space before adding the duplicate character
                result += " "
            # Add the duplicate character to the result string
            result += string[i]
    return result
 
# Driver Code
if __name__ == "__main__":
    string = "geeksforgeeks"
    duplicates = findDuplicateChars(string)
    print(duplicates)


C#




using System;
using System.Linq;
 
class Program
{
    static string FindDuplicateChars(string str)
    {
        // Sort the string in lexicographical order
        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))
                {
                    // Add a space before adding the duplicate character
                    result += " ";
                }
 
                // Add the duplicate character to the result string
                result += sortedStr[i].ToString();
            }
        }
 
        return result;
    }
 
    static void Main()
    {
        string str = "geeksforgeeks";
        string duplicates = FindDuplicateChars(str);
        Console.WriteLine(duplicates);
    }
}


Javascript




function findDuplicateChars(str) {
    // Convert the string to an array of characters
    let charArray = str.split('');
 
    // Sort the character array in lexicographical order
    charArray.sort();
 
    // Initialize a StringBuilder equivalent in JavaScript
    let result = '';
 
    for (let i = 1; i < charArray.length; i++) {
        // Check if the current character is the same as the previous one
        if (charArray[i] === charArray[i - 1] && result.indexOf(charArray[i]) === -1) {
            // Add a space before adding the duplicate character, if needed
            if (result.length > 0) {
                result += ' ';
            }
            // Add the duplicate character to the result string
            result += charArray[i];
        }
    }
 
    return result;
}
 
// Driver Code
let str = 'geeksforgeeks';
let duplicates = findDuplicateChars(str);
console.log(duplicates);


Output

e g k s








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
Previous
Next
Share your thoughts in the comments
Similar Reads