The Wayback Machine - https://web.archive.org/web/20241127052201/https://www.geeksforgeeks.org/remove-characters-from-the-first-string-which-are-present-in-the-second-string/
Open In App

Remove characters from the first string which are present in the second string

Last Updated : 13 Jul, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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”.

We strongly recommend that you click here and practise it, before moving on to the solution.

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”

  1. 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 */
  2. 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
  3. 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>


Output

geeforgee

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));


Output

geeforgee

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));


Output

geeforgee

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. 



Previous Article
Next Article

Similar Reads

Most frequent word in first String which is not present in second String
Given two string 'S1' and 'S2', the task is to return the most frequent (which is used the maximum number of times) word from 'S1' that is not present in 'S2'. If more than one word is possible then print lexicographically smallest among them. Examples: Input: S1 = "geeks for geeks is best place to learn", S2 = "bad place" Output: geeks "geeks" is
7 min read
Find elements which are present in first array and not in second
Given two arrays, the task is that we find numbers which are present in first array, but not present in the second array. Examples : Input : a[] = {1, 2, 3, 4, 5, 10}; b[] = {2, 3, 1, 0, 5};Output : 4 10 4 and 10 are present in first array, butnot in second array.Input : a[] = {4, 3, 5, 9, 11}; b[] = {4, 9, 3, 11, 10};Output : 5 Recommended Practic
14 min read
Count of elements in Array which are present K times & their double isn't present
Given an array arr[] of N integers, the task is to find the count of elements in the array that are present K times and their double are not present in the array. Examples: Input: arr[] = {10, 6, 12, 8, 10, 8}, K = 2Output: 2Explanation: 10 is a valid number since it appears exactly two times and 20 does not appear in array.8 is a valid number sinc
9 min read
Count elements present in first array but not in second
Given two arrays (which may or may not be sorted) of sizes M and N respectively. Their arrays are such that they might have some common elements in them. You need to count the number of elements whose occurrences are more in the first array than second. Examples: Input : arr1[] = {41, 43, 45, 50}, M = 4, arr2[] = {55, 67, 65, 61, 62}, N = 5 Output
6 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. Get the ASCII value of string N[] and add it to t
4 min read
Find all Characters in given String which are not present in other String
Given two strings str1 and str2, which are of lengths N and M. The second string contains all the characters of the first string, but there are some extra characters as well. The task is to find all the extra characters present in the second string. Examples: Input: str1 = "abcd", str2 = "dabcdehi"Output: d, e, h, iExplanation: [d, e, h, i] are the
10 min read
Check whether second string can be formed from characters of first string
Given two strings str1 and str2, check if str2 can be formed from str1 Example : Input : str1 = geekforgeeks, str2 = geeksOutput : YesHere, string2 can be formed from string1. Input : str1 = geekforgeeks, str2 = andOutput : NoHere string2 cannot be formed from string1. Input : str1 = geekforgeeks, str2 = geeeekOutput : YesHere string2 can be formed
5 min read
Count of times second string can be formed from the characters of first string
Given two strings str and patt, the task is to find the count of times patt can be formed using the characters of str. Examples: Input: str = "geeksforgeeks", patt = "geeks" Output: 2 "geeks" can be made at most twice from the characters of "geeksforgeeks". Input: str = "abcbca", patt = "aabc" Output: 1 Approach: Count the frequency of all the char
6 min read
Count subsequences in first string which are anagrams of the second string
Given two strings str1 and str2 of length n1 and n2 respectively. The problem is to count all the subsequences of str1 which are anagrams of str2. Examples: Input : str1 = "abacd", str2 = "abc" Output : 2 Index of characters in the 2 subsequences are: {0, 1, 3} = {a, b, c} = abc and {1, 2, 3} = {b, a, c} = bac The above two subsequences of str1 are
13 min read
Modify array by removing characters from their Hexadecimal representations which are present in a given string
Given an array arr[] of size N and a string S, the task is to modify given array by removing all characters from their hexadecimal representations that are present in S and then replacing the equivalent decimal element back into the array. Examples: Input: arr[] = {74, 91, 31, 122}, S = "1AB"Output: {4, 5, 15, 7}Explanation: 74 -> (4A)16 -> (
10 min read
Find characters which when increased by K are present in String
Given a string s of lowercase English alphabets and integer K. the task is to check if each character after increasing their ASCII by K is present in the string or not. Return only unique characters and the first index where they are present. Examples: Input: s = "dszepvaxuo", k = 3Output: {{1, 's'}, {6, 'a'}, {8, 'u'}}Explanation: Moving each char
8 min read
Count of strings in the first array which are smaller than every string in the second array
Given two arrays A[] and B[] which consists of N and M strings respectively. A string S1 is said to be smaller than string S2 if the frequency of the smallest character in the S1 is smaller than the frequency of the smallest character in S2. The task is to count the number of strings in A[] which are smaller than B[i] for every i. Examples: Input:
15+ min read
Convert characters of string1 to characters present in string2 by incrementing or decrementing lexicographically
Given two strings A and B having lower case English alphabets, the task is to find the number of operations required to convert string A such that it only contains letters that are also in the string B where at each operation, the current character can be changed to either the next character or the previous character. Also, the next character after
8 min read
Find the sum of the ascii values of characters which are present at prime positions
Given string str of size N, the task is to find the sum of all ASCII values of the characters that are present at prime positions. Examples: Input: str = "abcdef" Output: 298 'b', 'c' and 'e' are the only characters which are at prime positions i.e. 2, 3 and 5 respectively. And sum of their ASCII values is 298.Input: str = "geeksforgeeks" Output: 6
8 min read
Number of hours after which the second person moves ahead of the first person if they travel at a given speed
Given three integers A, B and K. Initially, the first person was ahead of the second person by K kms. In every hour, the first person moves ahead by A kms and the second person moves ahead by B kms. The task is to print the number of hours after which the second person crosses the first. If it is impossible to do so then print -1. Examples: Input:
4 min read
Find numbers which are multiples of first array and factors of second array
Given two arrays A[] and B[], the task is to find the integers which are divisible by all the elements of array A[] and divide all the elements of array B[]. Examples: Input: A[] = {1, 2, 2, 4}, B[] = {16, 32, 64} Output: 4 8 16 4, 8 and 16 are the only numbers that are multiples of all the elements of array A[] and divide all the elements of array
7 min read
Count number of rotated strings which have more number of vowels in the first half than second half
Given string str of even size N consisting of lowercase English alphabets. The task is to find the number of rotated strings of str which have more vowels in the first half than the second half. Examples: Input: str = "abcd" Output: 2 Explanation:All rotated string are "abcd", "dabc", "cdab", "bcda". The first two rotated strings have more vowels i
15+ min read
Count the number of sub-arrays such that the average of elements present in the sub-array is greater than that not present in the sub-array
Given an array of integers arr[], the task is to count the number of sub-arrays such that the average of elements present in the sub-array is greater than the average of elements that are not present in the sub-array.Examples: Input: arr[] = {6, 3, 5} Output: 3 The sub-arrays are {6}, {5} and {6, 3, 5} because their averages are greater than {3, 5}
8 min read
Minimum cost to remove the spaces between characters of a String by rearranging the characters
Given a string str that consists of characters and spaces, the task is to find the minimum cost to reduce the number of spaces between characters of the string. Cost of moving a character for index i to index j is defined as: | i - j | Examples: Input: str = " @ $" Output: 4 Explanation: As the characters are at indices [2, 7] (only two), either mo
7 min read
Sum of frequencies of characters of a string present in another string
Given two strings S1 and S2 of lengths M and N respectively, the task is to calculate the sum of the frequencies of the characters of string S1 in the string S2. Examples: Input: S1 = "pPKf", S2 = "KKKttsdppfP"Output: 7Explanation:The character 'p' occurs twice in the string S2.The character 'P' occurs once in the string S2.The character 'K' occurs
5 min read
Find the longest sub-string which is prefix, suffix and also present inside the string
Given string str. The task is to find the longest sub-string which is a prefix, a suffix, and a sub-string of the given string, str. If no such string exists then print -1.Examples: Input: str = "fixprefixsuffix" Output: fix "fix" is a prefix, suffix and present inside in the string too.Input: str = "aaaa" "aa" is a prefix, suffix and present insid
10 min read
Find the longest sub-string which is prefix, suffix and also present inside the string | Set 2
Given string str. The task is to find the longest sub-string which is a prefix, a suffix and a sub-string of the given string, str. If no such string exists then print -1.Examples: Input: str = "geeksisforgeeksinplatformgeeks" Output: geeksInput: str = “fixprefixsuffix” Output: fix Note: The Set-1 of this article is attached here.Approach: The impl
9 min read
Minimum changes required to make first string substring of second string
Given two strings S1 and S2 ( size of S1 <= Size of S2 ). The task is to find the minimum number of characters to be replaced in the string S2, such that the string S1 is a substring of S2. Examples: Input : S1 = cdef, S2 = abbdef Output : 1 Input : S1 = gfg, S2 = fgg Output : 2 Approach: Traverse the string S2 From every index in S2, check the
8 min read
Program to print characters present at prime indexes in a given string
Given a string, our task is to print the characters present at prime index. Examples : Input : I love programming Output : lv gan Explanation : prime index characters in a string are : lv gan Input : Happy coding everyone Output : apycn ro Approach : Use two loops to divide the numbers upto the value of length of string.Increment variable result wh
5 min read
Count of camel case characters present in a given string
Given a string S, the task is to count the number of camel case characters present in the given string. The camel case character is defined as the number of uppercase characters in the given string. Examples: Input: S = "ckjkUUYII"Output: 5Explanation: Camel case characters present are U, U, Y, I and I. Input: S = "abcd"Output: 0 Recommended: Pleas
7 min read
Number of Positions to partition the string such that atleast m characters with same frequency are present in each substring
Given a string str of lowercase English alphabets and an integer m. The task is to count how many positions are there in the string such that if you partition the string into two non-empty sub-strings, there are at least m characters with the same frequency in both sub-strings. The characters need to be present in the string str.Examples: Input: st
15+ min read
Find repeated character present first in a string
Given a string, find the repeated character present first in the string.(Not the first repeated character, found here.) Examples: Input : geeksforgeeks Output : g (mind that it will be g, not e.) Asked in: Goldman Sachs internship Simple Solution using O(N^2) complexity: The solution is to loop through the string for each character and search for t
15 min read
Count characters of a string which when removed individually makes the string equal to another string
Given two strings A and B of size N and M respectively, the task is to count characters of the string A, which when removed individually makes both the strings equal. If there exists several such characters, then print their respective positions. Otherwise, print "-1". Examples: Input: A = "abaac", B = "abac"Output: 2 3 4Explanation: Following remo
8 min read
Count the sum of count of distinct characters present in all Substrings
Given a string S consisting of lowercase English letters of size N where (1 <= N <= 105), the task is to print the sum of the count of distinct characters N where (1 <= N <= 105)in all the substrings. Examples: Input: str = "abbca"Output: 28Explanation: The following are the substrings of "abbca":=> Sum of distinct characters in Subs
8 min read
Find the lexicographically smallest sequence which can be formed by re-arranging elements of second array
Given two arrays A and B of N integers. Reorder the elements of B in itself in such a way that the sequence formed by (A[i] + B[i]) % N after re-ordering is the smallest lexicographically. The task is to print the lexicographically smallest sequence possible. Note: The array elements are in range [0, n).Examples: Input: a[] = {0, 1, 2, 1}, b[] = {3
11 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg