Remove characters from the first string which are present in the second string
Last Updated :
13 Jul, 2023
Given two strings string1 and string2, remove those characters from the first string(string1) which are present in the second string(string2). Both strings are different and contain only lowercase characters.
NOTE: The size of the first string is always greater than the size of the second string( |string1| > |string2|).
Example:
Input:
string1 = "computer"
string2 = "cat"
Output: "ompuer"
Explanation: After removing characters(c, a, t)
from string1 we get "ompuer".
Input:
string1 = "occurrence"
string2 = "car"
Output: "ouene"
Explanation: After removing characters
(c, a, r) from string1 we get "ouene".
Algorithm: Let the first input string be a ”test string” and the string which has characters to be removed from the first string be a “mask”
- Initialize: res_ind = 0 /* index to keep track of the processing of each character in i/p string */
ip_ind = 0 /* index to keep track of the processing of each character in the resultant string */ - Construct count array from mask_str. The count array would be:
(We can use a Boolean array here instead of an int count array because we don’t need a count, we need to know only if the character is present in a mask string)
count['a'] = 1
count['k'] = 1
count['m'] = 1
count['s'] = 1 - Process each character in the input string and if the count of that character is 0, then only add the character to the resultant string.
str = “tet tringng” // ’s’ has been removed because ’s’ was present in mask_str, but we have got two extra characters “ng”
ip_ind = 11
res_ind = 9
Put a ‘\0' at the end of the string.
Implementations:
C++
// C++ program to remove duplicates, the order of
// characters is not maintained in this progress
#include <bits/stdc++.h>
#define NO_OF_CHAR 256
using namespace std;
int* getcountarray(string str2)
{
int* count = (int*)calloc(sizeof(int), NO_OF_CHAR);
for (int i = 0; i < str2.size(); i++)
{
count[str2[i]]++;
}
return count;
}
/* removeDirtyChars takes two
string as arguments: First
string (str1) is the one from
where function removes dirty
characters. Second string(str2)
is the string which contain
all dirty characters which need
to be removed from first
string */
string removeDirtyChars(string str1, string str2)
{
// str2 is the string
// which is to be removed
int* count = getcountarray(str2);
string res;
// ip_idx helps to keep
// track of the first string
int ip_idx = 0;
while (ip_idx < str1.size())
{
char temp = str1[ip_idx];
if (count[temp] == 0)
{
res.push_back(temp);
}
ip_idx++;
}
return res;
}
// Driver Code
int main()
{
string str1 = "geeksforgeeks";
string str2 = "mask";
// Function call
cout << removeDirtyChars(str1, str2) << endl;
}
C
#include <stdio.h>
#include <stdlib.h>
#define NO_OF_CHARS 256
/* Returns an array of size 256 containing count
of characters in the passed char array */
int* getCharCountArray(char* str)
{
int* count = (int*)calloc(sizeof(int), NO_OF_CHARS);
int i;
for (i = 0; *(str + i); i++)
count[*(str + i)]++;
return count;
}
/* removeDirtyChars takes two
string as arguments: First
string (str) is the one from
where function removes dirty
characters. Second string is
the string which contain all
dirty characters which need to
be removed from first string
*/
char* removeDirtyChars(char* str, char* mask_str)
{
int* count = getCharCountArray(mask_str);
int ip_ind = 0, res_ind = 0;
while (*(str + ip_ind))
{
char temp = *(str + ip_ind);
if (count[temp] == 0)
{
*(str + res_ind) = *(str + ip_ind);
res_ind++;
}
ip_ind++;
}
/* After above step string is ngring.
Removing extra "iittg" after string*/
*(str + res_ind) = '\0';
return str;
}
/* Driver code*/
int main()
{
char str[] = "geeksforgeeks";
char mask_str[] = "mask";
printf("%s", removeDirtyChars(str, mask_str));
return 0;
}
Java
// Java program to remove duplicates, the order of
// characters is not maintained in this program
public class GFG {
static final int NO_OF_CHARS = 256;
/* Returns an array of size 256 containing count
of characters in the passed char array */
static int[] getCharCountArray(String str)
{
int count[] = new int[NO_OF_CHARS];
for (int i = 0; i < str.length(); i++)
count[str.charAt(i)]++;
return count;
}
/* removeDirtyChars takes two
string as arguments: First
string (str) is the one from
where function removes
dirty characters. Second
string is the string which
contain all dirty characters
which need to be removed
from first string */
static String removeDirtyChars(String str,
String mask_str)
{
int count[] = getCharCountArray(mask_str);
int ip_ind = 0, res_ind = 0;
char arr[] = str.toCharArray();
while (ip_ind != arr.length)
{
char temp = arr[ip_ind];
if (count[temp] == 0) {
arr[res_ind] = arr[ip_ind];
res_ind++;
}
ip_ind++;
}
str = new String(arr);
/* After above step string is ngring.
Removing extra "iittg" after string*/
return str.substring(0, res_ind);
}
// Driver Code
public static void main(String[] args)
{
String str = "geeksforgeeks";
String mask_str = "mask";
System.out.println(removeDirtyChars(str, mask_str));
}
}
Python3
# Python program to remove characters
# from first string which
# are present in the second string
NO_OF_CHARS = 256
# Utility function to convert
# from string to list
def toList(string):
temp = []
for x in string:
temp.append(x)
return temp
# Utility function to
# convert from list to string
def toString(List):
return ''.join(List)
# Returns an array of size
# 256 containing count of characters
# in the passed char array
def getCharCountArray(string):
count = [0] * NO_OF_CHARS
for i in string:
count[ord(i)] += 1
return count
# removeDirtyChars takes two
# string as arguments: First
# string (str) is the one
# from where function removes dirty
# characters. Second string
# is the string which contain all
# dirty characters which need
# to be removed from first string
def removeDirtyChars(string, mask_string):
count = getCharCountArray(mask_string)
ip_ind = 0
res_ind = 0
temp = ''
str_list = toList(string)
while ip_ind != len(str_list):
temp = str_list[ip_ind]
if count[ord(temp)] == 0:
str_list[res_ind] = str_list[ip_ind]
res_ind += 1
ip_ind += 1
# After above step string is ngring.
# Removing extra "iittg" after string
return toString(str_list[0:res_ind])
# Driver code
mask_string = "mask"
string = "geeksforgeeks"
print(removeDirtyChars(string, mask_string))
# This code is contributed by Bhavya Jain
C#
// C# program to remove
// duplicates, the order
// of characters is not
// maintained in this program
using System;
class GFG {
static int NO_OF_CHARS = 256;
/* Returns an array of size
256 containing count of
characters in the passed
char array */
static int[] getCharCountArray(String str)
{
int[] count = new int[NO_OF_CHARS];
for (int i = 0; i < str.Length; i++)
count[str[i]]++;
return count;
}
/* removeDirtyChars takes two
string as arguments: First
string (str) is the one from
where function removes dirty
characters. Second string is
the string which contain all
dirty characters which need
to be removed from first string */
static String removeDirtyChars(String str,
String mask_str)
{
int[] count = getCharCountArray(mask_str);
int ip_ind = 0, res_ind = 0;
char[] arr = str.ToCharArray();
while (ip_ind != arr.Length)
{
char temp = arr[ip_ind];
if (count[temp] == 0) {
arr[res_ind] = arr[ip_ind];
res_ind++;
}
ip_ind++;
}
str = new String(arr);
/* After above step string
is ngring. Removing extra
"iittg" after string*/
return str.Substring(0, res_ind);
}
// Driver Code
public static void Main()
{
String str = "geeksforgeeks";
String mask_str = "mask";
Console.WriteLine(removeDirtyChars(str, mask_str));
}
}
// This code is contributed by mits
JavaScript
<script>
//Javascript Implementation
let NO_OF_CHARS = 256;
function getcountarray(str2)
{
var count = new Array(NO_OF_CHARS).fill(0);
for (var i = 0; i < str2.length; i++)
{
count[str2.charCodeAt(i)]++;
}
return count;
}
/* removeDirtyChars takes two
string as arguments: First
string (str1) is the one from
where function removes dirty
characters. Second string(str2)
is the string which contain
all dirty characters which need
to be removed from first
string */
function removeDirtyChars(str1, str2)
{
// str2 is the string
// which is to be removed
var count = getcountarray(str2);
var res ="";
// ip_idx helps to keep
// track of the first string
var ip_idx = 0;
while (ip_idx < str1.length)
{
var temp = str1[ip_idx];
if (count[temp.charCodeAt(0)] == 0)
{
res = res.concat(temp);
}
ip_idx++;
}
return res;
}
// Driver Code
var mask_string = "mask"
var string = "geeksforgeeks"
document.write(removeDirtyChars(string, mask_string));
// This code is contributed by shivani
</script>
Time Complexity: O(m+n) Where m is the length of the mask string and n is the length of the input string.
Auxiliary Space: O(m)
An efficient solution is we find every character of string2 in string1 if that character is present then we simply erase that character from string1.
C++
// C++ program to remove duplicates
#include <bits/stdc++.h>
using namespace std;
string removeChars(string string1, string string2) {
//we extract every character of string string 2
for(auto i:string2)
{
//we find char exit or not
while(find(string1.begin(),string1.end(),i)!=string1.end())
{
auto itr = find(string1.begin(),string1.end(),i);
//if char exit we simply remove that char
string1.erase(itr);
}
}
return string1;
}
// Driver Code
int main()
{
string string1,string2;
string1="geeksforgeeks";
string2="mask";
cout<< removeChars(string1,string2)<<endl;;
return 0;
}
C
#include <stdio.h>
#include <string.h>
char* removeChars(char string1[], char string2[]) {
int i, j, k;
int len1 = strlen(string1);
int len2 = strlen(string2);
for (i = 0; i < len2; i++) {
for (j = 0; j < len1; j++) {
if (string1[j] == string2[i]) {
for (k = j; k < len1; k++) {
string1[k] = string1[k + 1];
}
len1--;
j--;
}
}
}
return string1;
}
int main() {
char string1[] = "geeksforgeeks";
char string2[] = "mask";
printf("%s\n", removeChars(string1, string2));
return 0;
}
Java
/*package whatever //do not write package name here */
import java.io.*;
class GFG {
public static String removeChars(String string1,
String string2)
{
// we extract every character of string string 2
for (int index = 0; index < string2.length();
index++) {
char i = string2.charAt(index);
// we find char exit or not
while (string1.contains(i + "")) {
int itr = string1.indexOf(i);
// if char exit we simply remove that char
string1 = string1.replace((i + ""), "");
}
}
return string1;
}
// Driver Code
public static void main(String[] args)
{
String string1, string2;
string1 = "geeksforgeeks";
string2 = "mask";
System.out.println(removeChars(string1, string2));
}
}
//This code is contributed by KaaL-EL.
Python3
# Python 3 program to remove duplicates
def removeChars(string1, string2):
# we extract every character of string string 2
for i in string2:
# we find char exit or not
while i in string1:
itr = string1.find(i)
# if char exit we simply remove that char
string1 = string1.replace(i, '')
return string1
# Driver Code
if __name__ == "__main__":
string1 = "geeksforgeeks"
string2 = "mask"
print(removeChars(string1, string2))
# This code is contributed by ukasp.
C#
// Include namespace system
using System;
public class GFG
{
public static String removeChars(String string1, String string2)
{
// we extract every character of string string 2
for (int index = 0; index < string2.Length; index++)
{
var i = string2[index];
// we find char exit or not
while (string1.Contains(i.ToString() + ""))
{
// if char exit we simply remove that char
string1 = string1.Replace((i.ToString() + ""),"");
}
}
return string1;
}
// Driver Code
public static void Main(String[] args)
{
String string1;
String string2;
string1 = "geeksforgeeks";
string2 = "mask";
Console.WriteLine(GFG.removeChars(string1, string2));
}
}
// This code is contributed by aadityaburujwale.
JavaScript
// function to remove characters from string1 that are present in string2
function removeChars(string1, string2) {
let i, j, k;
let len1 = string1.length; // get length of string1
let len2 = string2.length; // get length of string2
// loop over characters in string2
for (i = 0; i < len2; i++) {
// loop over characters in string1
for (j = 0; j < len1; j++) {
// if character is found in both strings
if (string1.charAt(j) == string2.charAt(i)) {
// remove character from string1
string1 = string1.substring(0, j) + string1.substring(j + 1);
len1--; // decrease length of string1
j--; // decrement j to account for shifted indices
}
}
}
return string1;
}
let string1 = "geeksforgeeks";
let string2 = "mask";
console.log(removeChars(string1, string2));
Time Complexity: O(n*m), where n is the size of given string2 and m is the size of string1.
Auxiliary Space: O(1), as no extra space is used
Efficient Solution: An efficient solution is that we can mark the occurrence of all characters present in second string by -1 in frequency character array and then while traversing first string we can ignore the marked characters as shown in below program.
C++
// C++ program to remove duplicates
#include <bits/stdc++.h>
using namespace std;
char* removeChars(char* s1, int n1, char* s2, int n2)
{
int arr[26] = { 0 }; // an array of size 26 to count the frequency of characters
int curr = 0;
for (int i = 0; i < n2; i++) // assigned all the index of characters which are present
arr[s2[i] - 'a'] = -1; // in second string by -1 (just flagging)
for (int i = 0; i < n1; i++)
if (arr[s1[i] - 'a'] != -1) { // Checking if the index of characters don't have -1
s1[curr] = s1[i]; // i.e, that character was not present in second string
curr++; // and then storing that character in string
}
s1[curr] = '\0'; // marking last character as null to point the end of string
return s1;
}
// driver code
int main()
{
char string1[] = "geeksforgeeks";
char string2[] = "mask";
int n1 = sizeof(string1) / sizeof(string1[0]);
int n2 = sizeof(string2) / sizeof(string2[0]);
cout << removeChars(string1, n1, string2, n2) << endl;
return 0;
}
C
// C program to remove duplicates
#include <stdio.h>
#include <string.h>
char* removeChars(char* s1, int n1, char* s2, int n2)
{
int arr[26] = { 0 }; // an array of size 26 to count the
// frequency of characters
int curr = 0;
for (int i = 0; i < n2;
i++) // assigned all the index of characters which
// are present
arr[s2[i] - 'a']
= -1; // in second string by -1 (just flagging)
for (int i = 0; i < n1; i++)
if (arr[s1[i] - 'a']
!= -1) { // Checking if the index of characters
// don't have -1
s1[curr] = s1[i]; // i.e, that character was not
// present in second string
curr++; // and then storing that character in
// string
}
s1[curr] = '\0'; // marking last character as null to
// point the end of string
return s1;
}
// driver code
int main()
{
char string1[] = "geeksforgeeks";
char string2[] = "mask";
int n1 = strlen(string1);
int n2 = strlen(string2);
printf("%s\n", removeChars(string1, n1, string2, n2));
return 0;
}
//contributed by SATYAM NAYAK
Java
import java.util.*;
public class GFG {
static String removeChars(String s1, int n1, String s2,
int n2)
{
String s3 = "";
// an array of size 26 to count the frequency of
// characters
int[] arr = new int[26];
for (int i = 0; i < 26; i++) {
arr[i] = 0;
}
for (int i = 0; i < n2;
i++) // assigned all the index of characters
// which are present
arr[s2.charAt(i) - 'a']
= -1; // in second string by -1
// (just flagging)
for (int i = 0; i < n1; i++) {
if (arr[s1.charAt(i) - 'a'] != -1) {
// Checking if the index of
// characters don't have -1
s3 += s1.charAt(
i); // i.e, that character was not
// present in second string and
// then storing that character
// in string
}
}
s1 = s3;
return s1;
}
// driver code
public static void main(String args[])
{
String string1 = "geeksforgeeks";
String string2 = "mask";
int n1 = string1.length();
int n2 = string2.length();
System.out.println(
removeChars(string1, n1, string2, n2));
}
}
// This code is contributed by Samim Hossain
// Mondal.
Python3
# Python3 program to remove duplicates
def removeChars(s1, n1, s2, n2):
s3 = ""
# an array of size 26 to count the frequency of
# characters
arr = [0] * 26
for i in range(0, n2):
# assigned all the index of characters
# which are present
arr[ord(s2[i]) - ord('a')] = -1 # in second string by -1
# (just flagging)
for i in range(0, n1):
if (arr[ord(s1[i]) - ord('a')] != -1):
# Checking if the index of
# characters don't have -1
s3 += s1[i] # i.e, that character was not
# present in second string and
# then storing that character
# in string
s1 = s3
return s1
# driver code
string1 = "geeksforgeeks"
string2 = "mask"
n1 = len(string1)
n2 = len(string2)
print(removeChars(string1, n1, string2, n2))
# contributed by akashish__
C#
// C# program to remove duplicates
using System;
class GFG {
static string removeChars(string s1, int n1, string s2,
int n2)
{
string s3 = "";
// an array of size 26 to count the frequency of
// characters
int[] arr = new int[26];
for (int i = 0; i < 26; i++) {
arr[i] = 0;
}
for (int i = 0; i < n2;
i++) // assigned all the index of characters
// which are present
arr[s2[i] - 'a'] = -1; // in second string by -1
// (just flagging)
for (int i = 0; i < n1; i++) {
if (arr[s1[i] - 'a']
!= -1)
{
// Checking if the index of
// characters don't have -1
s3 += s1[i]; // i.e, that character was not
// present in second string and
// then storing that character
// in string
}
}
s1 = s3;
return s1;
}
// driver code
public static void Main()
{
string string1 = "geeksforgeeks";
string string2 = "mask";
int n1 = string1.Length;
int n2 = string2.Length;
Console.WriteLine(
removeChars(string1, n1, string2, n2));
}
}
// This code is contributed by Samim Hossain Mondal.
JavaScript
function removeChars(s1, n1, s2, n2) {
let arr = new Array(26).fill(0); // an array of size 26 to count the frequency of characters
let curr = 0;
for (let i = 0; i < n2; i++) { // assigned all the index of characters which are present in second string by -1 (just flagging)
arr[s2.charCodeAt(i) - 'a'.charCodeAt(0)] = -1;
}
let output = '';
for (let i = 0; i < n1; i++) {
if (arr[s1.charCodeAt(i) - 'a'.charCodeAt(0)] != -1) { // Checking if the index of characters don't have -1
output += s1.charAt(i); // i.e, that character was not present in second string
}
}
return output;
}
let string1 = "geeksforgeeks";
let string2 = "mask";
let n1 = string1.length;
let n2 = string2.length;
console.log(removeChars(string1, n1, string2, n2));
Time Complexity: O(|S1|), where |S1| is the size of given string 1.
Auxiliary Space: O(1), as only an array of constant size (26) is used.
Remove characters from the first string which are present in the second string
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem