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 Stack
  • Practice Stack
  • MCQs on Stack
  • Stack Tutorial
  • Stack Operations
  • Stack Implementations
  • Monotonic Stack
  • Infix to Postfix
  • Prefix to Postfix
  • Prefix to Infix
  • Advantages & Disadvantages
Open In App
Next Article:
Count of sub-strings that do not consist of the given character
Next article icon

Count of strings that does not contain Arc intersection

Last Updated : 14 Sep, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

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 illustration of the same.

Examples:

Input: arr[] = {“0101”, “0011”, “0110”}
Output: 2
Explanation: The string "0101" have Arc Intersection. Therefore, the count of strings that doesn't have any Arc Intersection is 2.

Input: arr[] = {“0011”, “0110”, “00011000”}
Output: 3
Explanation: All the given strings doesn't have any Arc Intersection. Therefore, the count is 3.

Naive Approach: The simplest approach is to traverse the array and check for each string, if similar characters are grouped together at consecutive indices or not. If found to be true, keep incrementing count of such strings. Finally, print the value of count obtained. 

Time Complexity: O(N*M2), where M is the maximum length of string in the given array.
Auxiliary Space: O(1)

Efficient Approach: To optimize the above approach, the idea is to use Stack. Follow the steps below to solve the problem:

  1. Initialize count, to store the count of strings that doesn't contain any arc intersection.
  2. Initialize a stack to store every character of the string into it.
  3. Iterate the given string and perform the following operations:
    • Push the current character into the stack.
    • If the stack size is greater than 2, then check if the two elements at the top of the stack are same or not. If found to be true, then pop both the characters as to remove the nearest arc intersection.
  4. After completing the above steps, if stack is empty, then it doesn't contain any arc intersection.
  5. Follow the Step 2 to Step 4 for each string in the array to check whether string contains arc intersection or not. If it doesn't contain then count this string.

Below is the implementation of the above approach:

C++
// C++ program for the above approach  #include <bits/stdc++.h> using namespace std;  // Function to check if there is arc // intersection or not int arcIntersection(string S, int len) {     stack<char> stk;      // Traverse the string S     for (int i = 0; i < len; i++) {          // Insert all the elements in         // the stack one by one         stk.push(S[i]);          if (stk.size() >= 2) {              // Extract the top element             char temp = stk.top();              // Pop out the top element             stk.pop();              // Check if the top element             // is same as the popped element             if (stk.top() == temp) {                 stk.pop();             }              // Otherwise             else {                 stk.push(temp);             }         }     }      // If the stack is empty     if (stk.empty())         return 1;     return 0; }  // Function to check if there is arc // intersection or not for the given // array of strings void countString(string arr[], int N) {     // Stores count of string not     // having arc intersection     int count = 0;      // Iterate through array     for (int i = 0; i < N; i++) {          // Length of every string         int len = arr[i].length();          // Function Call         count += arcIntersection(             arr[i], len);     }      // Print the desired count     cout << count << endl; }  // Driver Code int main() {     string arr[] = { "0101", "0011", "0110" };     int N = sizeof(arr) / sizeof(arr[0]);      // Function Call     countString(arr, N);      return 0; } 
Java
// Java program for the above approach import java.util.*;  class GFG {  // Function to check if there is arc // intersection or not static int arcIntersection(String S, int len) {     Stack<Character> stk  = new Stack<>();      // Traverse the String S     for (int i = 0; i < len; i++)      {          // Insert all the elements in         // the stack one by one         stk.push(S.charAt(i));          if (stk.size() >= 2)         {              // Extract the top element             char temp = stk.peek();              // Pop out the top element             stk.pop();              // Check if the top element             // is same as the popped element             if (stk.peek() == temp)              {                 stk.pop();             }              // Otherwise             else              {                 stk.add(temp);             }         }     }      // If the stack is empty     if (stk.isEmpty())         return 1;     return 0; }  // Function to check if there is arc // intersection or not for the given // array of Strings static void countString(String arr[], int N) {        // Stores count of String not     // having arc intersection     int count = 0;      // Iterate through array     for (int i = 0; i < N; i++)      {          // Length of every String         int len = arr[i].length();          // Function Call         count += arcIntersection(             arr[i], len);     }      // Print the desired count     System.out.print(count +"\n"); }  // Driver Code public static void main(String[] args) {     String arr[] = { "0101", "0011", "0110" };     int N = arr.length;      // Function Call     countString(arr, N); } }  // This code is contributed by 29AjayKumar 
Python3
# Python3 program for the above approach  # Function to check if there is arc # intersection or not def arcIntersection(S, lenn):          stk = []          # Traverse the string S     for i in range(lenn):                  # Insert all the elements in         # the stack one by one         stk.append(S[i])          if (len(stk) >= 2):                          # Extract the top element             temp = stk[-1]              # Pop out the top element             del stk[-1]              # Check if the top element             # is same as the popped element             if (stk[-1] == temp):                 del stk[-1]                              # Otherwise             else:                 stk.append(temp)                      # If the stack is empty     if (len(stk) == 0):         return 1              return 0      # Function to check if there is arc # intersection or not for the given # array of strings def countString(arr, N):          # Stores count of string not     # having arc intersection     count = 0      # Iterate through array     for i in range(N):          # Length of every string         lenn = len(arr[i])          # Function Call         count += arcIntersection(arr[i], lenn)      # Print the desired count     print(count)  # Driver Code if __name__ == '__main__':          arr = [ "0101", "0011", "0110" ]     N = len(arr)          # Function Call     countString(arr, N)      # This code is contributed by mohit kumar 29 
C#
// C# program for  // the above approach using System;  using System.Collections.Generic;   class GFG {  // Function to check if there is arc // intersection or not static int arcIntersection(String S, int len) {     Stack<char> stk  = new Stack<char>();      // Traverse the String S     for (int i = 0; i < len; i++)      {          // Insert all the elements in         // the stack one by one         stk.Push(S[i]);          if (stk.Count >= 2)         {              // Extract the top element             char temp = stk.Peek();              // Pop out the top element             stk.Pop();              // Check if the top element             // is same as the popped element             if (stk.Peek() == temp)              {                 stk.Pop();             }              // Otherwise             else              {                 stk.Push(temp);             }         }     }      // If the stack is empty     if (stk.Count == 0)         return 1;     return 0; }  // Function to check if there is arc // intersection or not for the given // array of Strings static void countString(String []arr, int N) {        // Stores count of String not     // having arc intersection     int count = 0;      // Iterate through array     for (int i = 0; i < N; i++)      {          // Length of every String         int len = arr[i].Length;          // Function Call         count += arcIntersection(             arr[i], len);     }      // Print the desired count     Console.Write(count +"\n"); }  // Driver Code public static void Main(String[] args) {     String [] arr = { "0101", "0011", "0110" };     int N = arr.Length;      // Function Call     countString(arr, N); } }  // This code is contributed by jana_sayantan. 
JavaScript
<script>  // JavaScript program for the above approach  // Function to check if there is arc // intersection or not function arcIntersection(S, len) {     var stk = [];      // Traverse the string S     for (var i = 0; i < len; i++) {          // Insert all the elements in         // the stack one by one         stk.push(S[i]);          if (stk.length >= 2) {              // Extract the top element             var temp = stk[stk.length-1];              // Pop out the top element             stk.pop();              // Check if the top element             // is same as the popped element             if (stk[stk.length-1] == temp) {                 stk.pop();             }              // Otherwise             else {                 stk.push(temp);             }         }     }      // If the stack is empty     if (stk.length==0)         return 1;     return 0; }  // Function to check if there is arc // intersection or not for the given // array of strings function countString(arr, N) {     // Stores count of string not     // having arc intersection     var count = 0;      // Iterate through array     for (var i = 0; i < N; i++) {          // Length of every string         var len = arr[i].length;          // Function Call         count += arcIntersection(             arr[i], len);     }      // Print the desired count     document.write( count + "<br>"); }  // Driver Code  var arr = ["0101", "0011", "0110" ]; var N = arr.length;  // Function Call countString(arr, N);   </script> 

Output: 
2

 

Time Complexity: O(N*M), where M is the maximum length of string in the given array.
Auxiliary Space: O(M), where M is the maximum length of string in the given array.


Next Article
Count of sub-strings that do not consist of the given character

C

chahattekwani71
Improve
Article Tags :
  • Misc
  • Strings
  • Stack
  • DSA
  • Arrays
  • binary-string
Practice Tags :
  • Arrays
  • Misc
  • Stack
  • Strings

Similar Reads

  • Count of strings that does not contain any character of a given string
    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: 2Explanation: "hijk" and "xyz" are the strings that do not contain any char
    8 min read
  • 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 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 Strings that does not contain any alphabet's both uppercase and lowercase
    Given an array of strings arr[], containing N strings, the task is to count the number of strings that do not contain both the uppercase and the lowercase character of an alphabet. Example: Input: arr[]={ "abcdA", "abcd", "abcdB", "abc" }Output: 2Explanation: The first string contains both the upper
    11 min read
  • Count of K length substring containing at most X distinct vowels
    Given string str of size N containing both uppercase and lowercase letters, and two integers K and X. The task is to find the count of substrings of size K containing at most X distinct vowels. Examples: Input: str = "TrueGoik", K = 3, X = 2Output: 6Explanation: The five such substrings are "Tru", "
    9 min read
  • Count of substrings containing exactly K distinct vowels
    Given string str of size N containing both uppercase and lowercase letters, and an integer K. The task is to find the count of substrings containing exactly K distinct vowels. Examples: Input: str = "aeiou", K = 2Output: 4Explanation: The substrings having two distinct vowels are "ae", "ei", "io" an
    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 substrings consisting of equal number of a, b, c and d
    Given a string str, the task is to count non-empty substrings with equal number of ‘a’, ‘b’, ‘c’, and ‘d’. Examples: Input: str = “abcdef” Output: 6 Explanation: Substring consisting of equal number of ‘a’, ‘b’, ‘c’, and ‘d’ are { “abcd”, “abcde”, “abcdf”, “abcdef”, “e”, “f” }. Therefore, the requir
    14 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
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