Given a binary string S of size N, the duty is to seek out the variety of pairs of integers [L, R] 1 ≤ L < R ≤ N such that S[L . . . R] (the substring of S from L to R) might be diminished to 1 size string by changing substrings “01” or “10” with “1” and “0” respectively.
Enter: S = “0110”
Rationalization: The 4 substrings are 01, 10, 110, 0110.
Enter: S = “00000”
Method: The answer is predicated on the next mathematical thought:
We will remedy this based mostly on the exclusion precept. As an alternative of discovering doable pairs discover the variety of unattainable circumstances and subtract that from all doable substrings (i.e. N*(N+1)/2 ).
discover unattainable circumstances?
When s[i] and s[i-1] are identical, then after discount it would both change into “00” or “11”. In each circumstances, the substring can’t be diminished to size 1. So substring from 0 to i, from 1 to i, . . . can’t be made to have size 1. That depend of substrings is i.
Observe the beneath steps to resolve the issue:
- Initialize reply ans = N * (N + 1) / 2
- Run a loop from i = 1 to N – 1
- If S[i] is the same as S[i – 1], then subtract i from ans.
- Return ans – N (as a result of there are N substrings having size 1).
Beneath is the implementation of the above strategy.
Time Complexity: O(N)
Auxiliary House: O(1)