Find numbers of balancing positions in string

Given a string, the task is to find the number of such balancing positions in the string from where the left and the right part of that string contains same characters. The frequency of characters doesn’t matters.

Examples:

Input : str[] = abaaba
Output : Number of balancing positions : 3
Explanations : All 3 balancing positions are as :
ab|aaba, aba|aba, abaa|ba

Input : str[] = noon
Output : Number of balancing positions : 1
Explanations : Balancing position is :
no|on

Naive Approach : If we try to solve this problem by the naive approach, we have to process for all n positions of string and at each position, we must check whether the left and right parts of our string from that position have same characters or not.
The process of finding whether the position is balancing or not (frequency of both parts need not be same) can be done in O(n^2) time for a single position( where we should check if each element in left part is present in right and vice-versa). This whole process will lead an algorithm of time complexity O(n^3).

Efficient Approach: Idea of efficient algorithm came from this article. The main difference is that we should not care about equal frequency, and using traversing the string.
We first fill right[] with counts of all characters. Then we traverse the string from left to right. For every character, we increment its count in left[] and decrement count in right[]. For any point being traversed, if all characters that have non-zero value in left also have non-zero value in right, and vice versa is also true, then we increment result.

C++

// C++ program to find number of balancing
// points in string
#include<bits/stdc++.h>
using namespace std;
const int MAX_CHAR = 256;

// function to return number of balancing points
int countBalance(char *str)
{
    int n = strlen(str); // string length

    // hash array for storing hash of string
    // intialized by 0 being global
    int leftVisited[MAX_CHAR] = {0};
    int rightVisited[MAX_CHAR] = {0};

    // process string initially for rightVisited
    for (int i=0; i<n; i++)
        rightVisited[str[i]]++;

    // check for balancing points
    int res = 0;
    for (int i=0; i<n; i++)
    {
        // for every position inc left hash
        // & dec rightVisited
        leftVisited[str[i]]++;
        rightVisited[str[i]]--;

        // check whether  both hash have same
        // character or not
        int j;
        for (j=0; j<MAX_CHAR; j++)
        {
            // Either both leftVisited[j] and
            // rightVisited[j] should have none
            // zero value or both should have
            // zero value
            if ( (leftVisited[j] == 0 &&
                   rightVisited[j] != 0) ||
                 (leftVisited[j] != 0 &&
                  rightVisited[j] == 0)
               )
                break;
        }

        // if both have same character increment
        // count
        if (j == MAX_CHAR)
            res++;
    }
    return res;
}

//driver program
int main()
{
    char str[] = "abaababa";
    cout << countBalance(str);
    return 0;
}

Java

// Java program to find number of balancing
// points in string

class GFG
{
    static final int MAX_CHAR = 256;
    
    // method to return number of balancing points
    static int countBalance(String s)
    {
    	char[] str=s.toCharArray();
    	int n = str.length; // string length
    	
    
    	// hash array for storing hash of string
    	// intialized by 0 being global
    	int[] rightVisited = new int[MAX_CHAR];
    	int[] leftVisited = new int[MAX_CHAR];
    
    	// process string initially for rightVisited
    	for (int i=0; i<n; i++)
    		rightVisited[str[i]]++;
    
    	// check for balancing points
    	int res = 0;
    	for (int i=0; i<n; i++)
    	{
    		// for every position inc left hash
    		// & dec rightVisited
    		leftVisited[str[i]]++;
    		rightVisited[str[i]]--;
    
    		// check whether both hash have same
    		// character or not
    		int j;
    		for (j=0; j<MAX_CHAR; j++)
    		{
    			// Either both leftVisited[j] and
    			// rightVisited[j] should have none
    			// zero value or both should have
    			// zero value
    			if ( (leftVisited[j] == 0 &&
    				rightVisited[j] != 0) ||
    				(leftVisited[j] != 0 &&
    				rightVisited[j] == 0)
    			)
    				break;
    		}
    
    		// if both have same character increment
    		// count
    		if (j == MAX_CHAR)
    			res++;
    	}
    	return res;
    }
    
	// Driver Method
	public static void main(String[] args)
	{
		String str = "abaababa";
		System.out.println(countBalance(str));
	}
}
/* This code is contributed by Mr. Somesh Awasthi */


Output:

5

This article is contributed by Shivam Pradhan (anuj_charm). If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

GATE CS Corner    Company Wise Coding Practice

Recommended Posts:







Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.