Open In App

Count of strings that does not contain Arc intersection

Last Updated : 14 Sep, 2022
Improve
Improve
Like Article
Like
Save
Share
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:
  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.



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 character of str Input: arr[] = {"apple", "banana", "p
8 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", "001", "010", "100", ""011", "110", "101", "111"}
17 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 uppercase and the lowercase character for alphabet 'a'.
11 min read
Largest number not exceeding N that does not contain any of the digits of S
Given a numberic string N (1 ≤ |N| ≤ 105) and another numeric string S (1 ≤ |S| ≤ 105), the task is to find the maximum number ≤ N such that it doesn't contain digits of string S. Remove leading zeros, if required. Note: The string S doesn't contain '0'. Examples: Input: N = "2004", S = "2" Output: 1999 Explanation: 2004 has digit 2 which is in the
14 min read
Count of Numbers in Range where the number does not contain more than K non zero digits
Given a range represented by two positive integers L and R and a positive integer K. Find the count of numbers in the range where the number does not contain more than K non zero digits.Examples: Input : L = 1, R = 1000, K = 3 Output : 1000 Explanation : All the numbers from 1 to 1000 are 3 digit numbers which obviously cannot contain more than 3 n
11 min read
Count numbers that does not contain digit N in given range
Given integers, N, L, and R, the task is to find the number of integers in the range L to R that does not contain the digit N. print the answer modulo 109 + 7. ( L ? R ? 101000000) Examples: Input: N = 5, L = 1, R = 10Output: 9Explanation: excluding all 5 others from 1 to 10 will be included in the answer. Input: N = 5, L = 1, R = 100Output: 81Expl
14 min read
Count the nodes of a tree whose weighted string does not contain any duplicate characters
Given a tree, and the weights (in the form of strings) of all the nodes, the task is to count the nodes whose weights do not contain any duplicate character.Examples: Input: Output: 2 Only the strings of the node 1 and 4 contains unique strings. Approach: Perform dfs on the tree and for every node, check if its string contains duplicate char or not
5 min read
Count of numbers in a range that does not contain the digit M and which is divisible by M.
Given three integers, the lower range L, the upper range U, and a digit M. The task is to count all the numbers between L and U such that the number is divisible by M and, also, it does not contain the digit M. Examples: Input: M = 9 ,L = 16 , U = 26 Output: 1 Explanation: Within this given range ,the number that follows the above two given conditi
5 min read
Queries to count numbers from a range which does not contain digit K in their decimal or octal representation
Given an integer K and an array Q[][] consisting of N queries of type {L, R}, the task for each query is to print the count of numbers from the range [L, R] that doesn't contain the digit K in their decimal representation or octal representation. Examples: Input: K = 7, Q[][] = {{1, 15}}Output: 13Explanation:Only number 7 and 15 contains digit K in
9 min read
Count of subarray that does not contain any subarray with sum 0
Given an array arr, the task is to find the total number of subarrays of the given array which do not contain any subarray whose sum of elements is equal to zero. All the array elements may not be distinct.Examples: Input: arr = {2, 4, -6} Output: 5 Explanation: There are 5 subarrays which do not contain any subarray whose elements sum is equal to
11 min read
Article Tags :
Practice Tags :