Open In App

Generate two output strings depending upon occurrence of character in input string.

Last Updated : 16 Jul, 2024
Comments
Improve
Suggest changes
30 Likes
Like
Report

Given an input string str[], generate two output strings. One of which consists of those character which occurs only once in input string and second which consists of multi-time occurring characters. Output strings must be sorted.
Examples: 
 

Input : str[] = "geeksforgeeks"
Output : String with characters occurring once:
for
String with characters occurring multiple times:
egks

Input : str[] = "geekspractice"
Output : String with characters occurring once:
agikprst
String with characters occurring multiple times:
ce


 


Approach : We follow total two steps to generate the both output strings. 
Step 1: Create a count array and count occurrences of characters in the given input string. 
Step 2: Check count array for each position 'i' which leads to three possible conditions : 
a) If count value is 1, append character in first output string. 
b) If count value is greater than 1, append character in second output string. 
c) If count value is 0 do nothing.
Time Complexity for above approach is O(n). 
Auxiliary Space required is O(1). 
 

C++
Java Python C# Javascript

Output: 
 

String with characters occurring once:
cdltv
String with characters occurring multiple times:
eo

Time complexity : O(n) 
Auxiliary Space : O(1)


Approach : Using Sets

Follwo the below steps:

  • Create a set to store characters occurring only once.
  • Create another set to store characters occurring multiple times.
  • Iterate through the input string and populate the sets accordingly.
  • Convert sets to sorted strings and return them.

Below is the implementation of the above approach :


Output
String with characters occurring once: for
String with characters occurring multiple times: egks
String with characters occurring once: agikprst
String with characters occurring multiple times: ce

Time complexity: O(n + k * log(k)), where n is the length of the input string & k is the number of unique characters

Auxiliary space : O(c), where c is the number of unique characters.
 


Next Article
Article Tags :
Practice Tags :

Similar Reads