VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-the-duplicate-characters-in-a-string-in-o1-space/

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


  • Courses
  • Tutorials
  • Interview Prep

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

Last Updated : 23 Jul, 2025

Given a stringstr, 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:


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.

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.

Comment
Article Tags: