Generate two output strings depending upon occurrence of character in input string.
Last Updated :
16 Jul, 2024
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++
// CPP program to print two strings
// made of character occurring once
// and multiple times
#include <bits/stdc++.h>
using namespace std;
const int MAX_CHAR = 256;
// function to print two strings
// generated from single string one
// with characters occurring once
// other with character occurring
// multiple of times
void printDuo(string &str)
{
// initialize hashtable with zero
// entry
int countChar[MAX_CHAR] = { 0 };
// perform hashing for input string
int n = str.length();
for (int i = 0; i < n; i++)
countChar[str[i] - 'a']++;
// generate string (str1) consisting
// char occurring once and string
// (str2) consisting char occurring
// multiple times
string str1 = "", str2 = "";
for (int i = 0; i < MAX_CHAR; i++) {
if (countChar[i] > 1)
str2 = str2 + (char)(i + 'a');
else if (countChar[i] == 1)
str1 = str1 + (char)(i + 'a');
}
// print both strings
cout << "String with characters occurring "
<< "once:\n";
cout << str1 << "\n";
cout << "String with characters occurring "
<< "multiple times:\n";
cout << str2 << "\n";
}
// driver program
int main()
{
string str = "lovetocode";
printDuo(str);
return 0;
}
Java
// Java program to print two strings
// made of character occurring once
// and multiple times
class GFG {
final static int MAX_CHAR = 256;
// function to print two strings
// generated from single string one
// with characters occurring once
// other with character occurring
// multiple of times
static void printDuo(String str) {
// initialize hashtable with zero
// entry
int countChar[] = new int[MAX_CHAR];
// perform hashing for input string
int n = str.length();
for (int i = 0; i < n; i++) {
countChar[str.charAt(i) - 'a']++;
}
// generate string (str1) consisting
// char occurring once and string
// (str2) consisting char occurring
// multiple times
String str1 = "", str2 = "";
for (int i = 0; i < MAX_CHAR; i++) {
if (countChar[i] > 1) {
str2 = str2 + (char) (i + 'a');
} else if (countChar[i] == 1) {
str1 = str1 + (char) (i + 'a');
}
}
// print both strings
System.out.print("String with characters occurring "
+ "once:\n");
System.out.print(str1 + "\n");
System.out.print("String with characters occurring "
+ "multiple times:\n");
System.out.print(str2 + "\n");
System.out.print("");
}
// driver program
public static void main(String[] args) {
String str = "lovetocode";
printDuo(str);
}
}
//this code contributed by 29AJayKumar
Python
# Python3 program to print two strings
# made of character occurring once
# and multiple times
MAX_CHAR = 256
# function to print two strings
# generated from single string one
# with characters occurring once
# other with character occurring
# multiple of times
def printDuo(string):
# initialize hashtable with zero
# entry
countChar = [0 for i in range(MAX_CHAR)]
# perform hashing for input string
n = len(string)
for i in range(n):
countChar[ord(string[i]) - ord('a')] += 1
# generate string (str1) consisting
# char occurring once and string
# (str2) consisting char occurring
# multiple times
str1 = ""
str2 = ""
for i in range(MAX_CHAR):
if (countChar[i] > 1):
str2 = str2 + chr(i + ord('a'))
elif (countChar[i] == 1):
str1 = str1 + chr(i + ord('a'))
# print both strings
print("String with characters occurring once:",
"\n", str1)
print("String with characters occurring",
"multiple times:", "\n", str2)
# Driver Code
string = "lovetocode"
printDuo(string)
# This code is contributed by
# Mohit kumar 29
C#
// C# program to print two strings
// made of character occurring once
// and multiple times
using System;
class GFG
{
static int MAX_CHAR = 256;
// function to print two strings
// generated from single string one
// with characters occurring once
// other with character occurring
// multiple of times
static void printDuo(string str)
{
// initialize hashtable with zero
// entry
int[] countChar = new int[MAX_CHAR];
// perform hashing for input string
int n = str.Length;
for (int i = 0; i < n; i++)
{
countChar[str[i] - 'a']++;
}
// generate string (str1) consisting
// char occurring once and string
// (str2) consisting char occurring
// multiple times
string str1 = "", str2 = "";
for (int i = 0; i < MAX_CHAR; i++)
{
if (countChar[i] > 1)
{
str2 = str2 + (char) (i + 'a');
}
else if (countChar[i] == 1)
{
str1 = str1 + (char) (i + 'a');
}
}
// print both strings
Console.Write("String with characters "+
"occurring once:\n");
Console.Write(str1 + "\n");
Console.Write("String with characters occurring " +
"multiple times:\n");
Console.Write(str2 + "\n");
Console.Write("");
}
// Driver Code
public static void Main()
{
string str = "lovetocode";
printDuo(str);
}
}
// This code is contributed by ita_c
Javascript
<script>
// javascript program to print two strings
// made of character occurring once
// and multiple times
var MAX_CHAR = 256;
// function to print two strings
// generated from single string one
// with characters occurring once
// other with character occurring
// multiple of times
function printDuo(str)
{
// initialize hashtable with zero
// entry
var countChar = Array(MAX_CHAR).fill(0);
// perform hashing for input string
var n = str.length;
for (var i = 0; i < n; i++)
countChar[str[i].charCodeAt(0) - 'a'.charCodeAt(0)]++;
// generate string (str1) consisting
// char occurring once and string
// (str2) consisting char occurring
// multiple times
var str1 = "", str2 = "";
for (var i = 0; i < MAX_CHAR; i++) {
if (countChar[i] > 1)
str2 = str2 + String.fromCharCode(i + 'a'.charCodeAt(0));
else if (countChar[i] == 1)
str1 = str1 + String.fromCharCode(i + 'a'.charCodeAt(0));
}
// print both strings
document.write( "String with characters occurring "
+ "once:<br>");
document.write( str1 + "<br>");
document.write( "String with characters occurring "
+ "multiple times:<br>");
document.write( str2 + "<br>");
}
// driver program
var str = "lovetocode";
printDuo(str);
</script>
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 :
Python
def separate_characters(input_str):
# Initialize sets to store characters occurring only once and multiple times
singles_set = set()
multiples_set = set()
# Iterate through the input string and populate the sets accordingly
char_count = {}
for char in input_str:
if char in char_count:
char_count[char] += 1
else:
char_count[char] = 1
for char, count in char_count.items():
if count == 1:
singles_set.add(char)
else:
multiples_set.add(char)
# Convert sets to sorted strings
singles = ''.join(sorted(singles_set))
multiples = ''.join(sorted(multiples_set))
return singles, multiples
# Example usage:
input_str1 = "geeksforgeeks"
singles1, multiples1 = separate_characters(input_str1)
print("String with characters occurring once:", singles1)
print("String with characters occurring multiple times:", multiples1)
input_str2 = "geekspractice"
singles2, multiples2 = separate_characters(input_str2)
print("String with characters occurring once:", singles2)
print("String with characters occurring multiple times:", multiples2)
OutputString 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.
Similar Reads
Generate Two Output Strings Depending upon Occurrence of Character in Input String - Python
The task of generating two output strings based on the occurrence of characters in an input string in Python involves classifying characters based on their frequency. We need to create one string that contains characters that appear only once in the input string and another string for characters tha
4 min read
Find the Nth occurrence of a character in the given String
Given string str, a character ch, and a value N, the task is to find the index of the Nth occurrence of the given character in the given string. Print -1 if no such occurrence exists. Examples: Input: str = "Geeks", ch = 'e', N = 2 Output: 2 Input: str = "GFG", ch = 'e', N = 2 Output: -1 Recommended
7 min read
Find the number of occurrences of a character upto preceding position
Given a string S of length N and an integer P(1?P?N) denoting the position of a character in the string. The task is to find the number of occurrences of the character present at position P up to P-1 index. Examples: Input : S = "ababababab", P = 9 Output : 4 Character at P is 'a'. Number of occurre
7 min read
Python - Replacing Nth occurrence of multiple characters in a String with the given character
Replacing the Nth occurrence of multiple characters in a string with a given character involves identifying and counting specific character occurrences.Using a Loop and find()Using a loop and find() method allows us to search for the first occurrence of a substring within each list element. This app
2 min read
Generate string by incrementing character of given string by number present at corresponding index of second string
Given two strings S[] and N[] of the same size, the task is to update string S[] by adding the digit of string N[] of respective indices. Examples: Input: S = "sun", N = "966"Output: bat Input: S = "apple", N = "12580"Output: brute Approach: The idea is to traverse the string S[] from left to right.
4 min read
Print characters having even frequencies in order of occurrence
Given a string str containing only lowercase characters. The task is to print the characters having an even frequency in the order of their occurrence.Note: Repeated elements with even frequency are printed as many times they occur in order of their occurrences.Examples: Input: str = "geeksforgeeks"
5 min read
Check if String can be generated by concatenating character or String itself
Given a target string S consisting of lowercase alphabets, the task is to make this string by performing some operation on an empty string such that: The first operation is to append a lower case alphabet to string S and The second operation is to append a copy of S to itself. Note: The first operat
6 min read
Print the string by ignoring alternate occurrences of any character
Given a string of both uppercase and lowercase alphabets, the task is to print the string with alternate occurrences of any character dropped(including space and consider upper and lowercase as same). Examples: Input : It is a long day Dear. Output : It sa longdy ear. Print first I and then ignore n
4 min read
Print characters having odd frequencies in order of occurrence
Given a string str containing only lowercase characters. The task is to print the characters having an odd frequency in the order of their occurrence.Note: Repeated elements with odd frequency are printed as many times they occur in order of their occurrences.Examples: Input: str = "geeksforgeeks" O
7 min read
Number of substrings with each character occurring even times
Given a string S consisting of N lowercase alphabets, the task is to count the number of substrings whose frequency of each character is even. Examples: Input: S = "abbaa"Output: 4Explanation:The substrings having frequency of each character is even are {"abba", "aa", "bb", "bbaa"}.Therefore, the co
14 min read