Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on Hash
  • Practice Hash
  • MCQs on Hash
  • Hashing Tutorial
  • Hash Function
  • Index Mapping
  • Collision Resolution
  • Open Addressing
  • Separate Chaining
  • Quadratic probing
  • Double Hashing
  • Load Factor and Rehashing
  • Advantage & Disadvantage
Open In App
Next Article:
Count of strings that does not contain Arc intersection
Next article icon

Count of strings that does not contain any character of a given string

Last Updated : 22 Aug, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array arr containing N strings and a string str, the task is to find the number of strings that do not contain any character of string str.

Examples:

Input: arr[] = {“abcd”, “hijk”, “xyz”, “ayt”}, str=”apple”
Output: 2
Explanation: “hijk” and “xyz” are the strings that do not contain any character of str

Input: arr[] = {“apple”, “banana”, “pear”}, str=”nil”
Output: 1

Recommended: Please try your approach on {IDE} first, before moving on to the solution.

Approach: Follow the below steps to solve this problem:

  1. Create a set st and store each character of string str in this set.
  2. Create a variable ans to store the number of all the required strings.
  3. Now, start traversing on the array and for each string, check if any of its character is present in the set st or not. If it is, then this is not a required string.
  4. If it doesn’t contain any character from the set, increase answer by 1.
  5. Return ans after the loop ends, as the answer to this problem.

Below is the implementation of the above approach:

C++




// C++ code for the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to count the number of strings
// that does not contain any character of string str
int allowedStrings(vector<string>& arr, string str)
{
    int ans = 0;
    unordered_set<char> st;
    for (auto x : str) {
        st.insert(x);
    }
 
    for (auto x : arr) {
        bool allowed = 1;
        for (auto y : x) {
 
            // If the character is present in st
            if (st.find(y) != st.end()) {
                allowed = 0;
                break;
            }
        }
 
        // If the string doesn't
        // have any character of st
        if (allowed) {
            ans += 1;
        }
    }
 
    return ans;
}
 
// Driver Code
int main()
{
    vector<string> arr
        = { "abcd", "hijk", "xyz", "ayt" };
    string str = "apple";
    cout << allowedStrings(arr, str);
}
 
 

Java




/*package whatever //do not write package name here */
import java.io.*;
import java.util.*;
 
class GFG {
 
  // Function to count the number of strings
  // that does not contain any character of string str
  public static int allowedStrings(List<String> arr,
                                   String str)
  {
    int ans = 0;
    Set<Character> st = new HashSet<Character>();
 
    char[] chararray = str.toCharArray();
    for (Character x : chararray) {
      st.add(x);
    }
 
    for (int i = 0; i < arr.size(); i++) {
      String x = arr.get(i);
      boolean allowed = true;
      char[] chararray2 = x.toCharArray();
      for (Character y : chararray2) {
 
        // If the character is present in st
        if (st.contains(y)) {
          allowed = false;
          break;
        }
      }
 
      // If the string doesn't
      // have any character of st
      if (allowed) {
        ans += 1;
      }
    }
 
    return ans;
  }
 
  public static void main(String[] args)
  {
    List<String> arr = new ArrayList<String>();
    arr.add("abcd");
    arr.add("hijk");
    arr.add("xyz");
    arr.add("ayt");
    String str = "apple";
    System.out.println(allowedStrings(arr, str));
  }
}
 
// This code is contributed by akashish__
 
 

Python3




# Python 3 code for the above approach
 
# Function to count the number of strings
# that does not contain any character of string str
def allowedStrings(arr, st):
    ans = 0
    st1 = set([])
    for x in st:
        st1.add(x)
 
    for x in arr:
        allowed = 1
        for y in x:
 
            # If the character is present in st1
            if (y in st1):
                allowed = 0
                break
 
        # If the string doesn't
        # have any character of st
        if (allowed):
            ans += 1
 
    return ans
 
# Driver Code
if __name__ == "__main__":
 
    arr = ["abcd", "hijk", "xyz", "ayt"]
    st = "apple"
    print(allowedStrings(arr, st))
 
    # This code is contributed by ukasp.
 
 

C#




using System;
using System.Collections.Generic;
 
public class GFG{
 
  // Function to count the number of strings
  // that does not contain any character of string str
  public static int allowedStrings(List<String> arr,
                                   String str)
  {
    int ans = 0;
    HashSet<char> st = new HashSet<char>();
 
    for(int i=0;i<str.Length;i++)
    {
      st.Add(str[i]);
    }
 
    for (int i = 0; i < arr.Count; i++) {
      String x = arr[i];
      bool allowed = true;
      for (int j=0;j<x.Length;j++) {
 
        // If the character is present in st
        if (st.Contains(x[j])) {
          allowed = false;
          break;
        }
      }
 
      // If the string doesn't
      // have any character of st
      if (allowed==true) {
        ans += 1;
      }
    }
 
    return ans;
  }
 
  static public void Main (){
 
    List<String> arr = new List<String>();
    arr.Add("abcd");
    arr.Add("hijk");
    arr.Add("xyz");
    arr.Add("ayt");
    String str = "apple";
    Console.WriteLine(allowedStrings(arr, str)); 
 
  }
}
// This code is contributed by akashish__
 
 

Javascript




<script>
// Javascript code for the above approach
 
// Function to count the number of strings
// that does not contain any character of string str
function allowedStrings(arr, str)
{
    let ans = 0;
    let st = new Set();
    for (x of str) {
        st.add(x);
    }
 
    for (x of arr) {
        let allowed = 1;
        for (y of x) {
 
            // If the character is present in st
            if (st.has(y)) {
                allowed = 0;
                break;
            }
        }
 
        // If the string doesn't
        // have any character of st
        if (allowed) {
            ans += 1;
        }
    }
 
    return ans;
}
 
// Driver Code
 
let arr = ["abcd", "hijk", "xyz", "ayt"];
let str = "apple";
document.write(allowedStrings(arr, str));
 
// This code is contributed by gfgking.
</script>
 
 
Output
2    

 
 Time Complexity: O(N*M), where N is the size of the array and M is the size of the longest string.
Auxiliary Space: O(N)

Approach:

To solve this problem is to iterate through each string in the given array and for each string, iterate through each character in the given string str. If a character in str is found in the current string, then we break the loop and move to the next string in the array. If none of the characters in str are found in the current string, then we increment a counter variable that keeps track of the number of strings that do not contain any character of str.

Implementation of the above approach:

C++




// C++ code for the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to count the number of strings
// that does not contain any character of string str
int allowedStrings(vector<string>& arr, string str)
{
    int count = 0;
    for (string s : arr) {
        bool flag = true;
        for (char c : str) {
            if (s.find(c) != string::npos) {
                flag = false;
                break;
            }
        }
        if (flag) {
            count++;
        }
    }
    return count;
}
 
// Driver Code
int main()
{
    vector<string> arr
        = { "abcd", "hijk", "xyz", "ayt" };
    string str = "apple";
    cout << allowedStrings(arr, str);
}
 
 

Java




import java.util.*;
 
public class Main {
    // Function to count the number of strings
    // that does not contain any character of string str
    public static int allowedStrings(List<String> arr, String str) {
        int count = 0;
        for (String s : arr) {
            boolean flag = true;
            for (char c : str.toCharArray()) {
                if (s.indexOf(c) != -1) {
                    flag = false;
                    break;
                }
            }
            if (flag) {
                count++;
            }
        }
        return count;
    }
 
    // Driver Code
    public static void main(String[] args) {
        List<String> arr = Arrays.asList("abcd", "hijk", "xyz", "ayt");
        String str = "apple";
        System.out.println(allowedStrings(arr, str));
    }
}
 
 

Python




# javascript code for the above approach
 
# Function to count the number of strings
# that does not contain any character of string str
def allowed_strings(arr, str):
    count = 0
    for s in arr:
        flag = True
        for c in str:
            if c in s:
                flag = False
                break
        if flag:
            count += 1
    return count
 
 
# Driver Code
if __name__ == "__main__":
    arr = ["abcd", "hijk", "xyz", "ayt"]
    str = "apple"
    print(allowed_strings(arr, str))
 
 

C#




using System;
using System.Collections.Generic;
 
public class MainClass
{
    // Function to count the number of strings
    // that does not contain any character of string str
    public static int allowedStrings(List<string> arr, string str)
    {
        int count = 0;
        foreach (string s in arr)
        {
            bool flag = true;
            foreach (char c in str)
            {
                if (s.Contains(c))
                {
                    flag = false;
                    break;
                }
            }
            if (flag)
            {
                count++;
            }
        }
        return count;
    }
 
    // Driver Code
    public static void Main()
    {
        List<string> arr = new List<string> { "abcd", "hijk", "xyz", "ayt" };
        string str = "apple";
        Console.WriteLine(allowedStrings(arr, str));
    }
}
 
 

Javascript




// Function to count the number of strings
// that do not contain any character of string str
function allowedStrings(arr, str) {
    let count = 0; // Initialize a variable to store the count of allowed strings
    for (let s of arr) { // Loop through each string in the array arr
        let flag = true; // Initialize a flag to true, assuming the current string is allowed
 
        // Loop through each character in the string str
        for (let c of str) {
            // Check if the current character c exists in the current string s
            // If it does, set the flag to false, indicating the string is not allowed
            if (s.indexOf(c) !== -1) {
                flag = false;
                break;
            }
        }
 
        // If the flag is still true after checking all characters in str,
        // it means the current string s does not contain any character from str,
        // so we increment the count of allowed strings.
        if (flag) {
            count++;
        }
    }
 
    return count; // Return the final count of allowed strings.
}
 
// Driver Code
    const arr = ["abcd", "hijk", "xyz", "ayt"]; // Input array of strings
    const str = "apple"; // Input string
    console.log(allowedStrings(arr, str)); // Call the function and log the result to the console.
 
 
Output
2    

Time Complexity: O(N*M)

Space Complexity: O(1)
 



Next Article
Count of strings that does not contain Arc intersection

C

code_r
Improve
Article Tags :
  • Arrays
  • DSA
  • Hash
  • Strings
  • frequency-counting
Practice Tags :
  • Arrays
  • Hash
  • Strings

Similar Reads

  • Count of sub-strings that do not consist of the given character
    Given a string str and a character c. The task is to find the number of sub-strings that do not consist of the character c. Examples: Input: str = "baa", c = 'b' Output: 3 The sub-strings are "a", "a" and "aa" Input: str = "ababaa", C = 'b' Output: 5 Approach: Initially take a counter that counts th
    13 min read
  • Count binary Strings that does not contain given String as Subsequence
    Given a number N and string S, count the number of ways to create a binary string (containing only '0' and '1') of size N such that it does not contain S as a subsequence. Examples: Input: N = 3, S = "10".Output: 4Explanation: There are 8 strings possible to fill 3 positions with 0's or 1's. {"000",
    15+ min read
  • Count of substrings from given Ternary strings containing characters at least once
    Given string str of size N consisting of only 0, 1, and 2, the task is to find the number of substrings that consists of characters 0, 1, and 2 at least once. Examples: Input: str = "0122"Output: 2Explanation:There exists 2 substrings such that the substrings has characters 0, 1, 2 at least once is
    6 min read
  • Count of substrings containing only the given character
    Given a string S and a character C, the task is to count the number of substrings of S that contains only the character C.Examples: Input: S = "0110111", C = '1' Output: 9 Explanation: The substrings containing only '1' are: "1" — 5 times "11" — 3 times "111" — 1 time Hence, the count is 9. Input: S
    6 min read
  • Count of strings that does not contain Arc intersection
    Given an array arr[] consisting of N binary strings, the task is to count the number of strings that does not contain any Arc Intersection. Connecting consecutive pairs of identical letters using Arcs, if there is an intersection obtained, then it is known as Arc Intersection. Below is the illustrat
    8 min read
  • Count of substrings which contains a given character K times
    Given a string consisting of numerical alphabets, a character C and an integer K, the task is to find the number of possible substrings which contains the character C exactly K times. Examples: Input : str = "212", c = '2', k = 1 Output : 4 Possible substrings are {"2", "21", "12", "2"} that contain
    9 min read
  • Count of substrings of a given Binary string with all characters same
    Given binary string str containing only 0 and 1, the task is to find the number of sub-strings containing only 1s and 0s respectively, i.e all characters same. Examples: Input: str = “011”Output: 4Explanation: Three sub-strings are "1", "1", "11" which have only 1 in them, and one substring is there
    10 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 o
    8 min read
  • Total length of string from given Array of strings composed using given characters
    Given a list of characters and an array of strings, find the total length of all strings in the array of strings that can be composed using the given characters.Examples: Input: string = ["mouse", "me", "bat", "lion"], chars = "eusamotb" Output: 10 Explanation: The strings that can be formed using t
    6 min read
  • Count of Substrings that can be formed without using the given list of Characters
    Given a string str and a list of characters L, the task is to count the total numbers of substrings of the string str without using characters given in the list L. Examples: Input: str = "abcd", L[] = {'a', 'b', 't', 'q'} Output: 3 Explanation: On ignoring the characters 'a' and 'b' from the given s
    7 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences