Given a binary string S of size N, the duty is to search 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) will be decreased to 1 size string by changing substrings “01” or “10” with “1” and “0” respectively.
Examples:
Enter: S = “0110”
Output: 4
Clarification: The 4 substrings are 01, 10, 110, 0110.Enter: S = “00000”
Output: 0
Strategy: The answer is predicated on the next mathematical concept:
We are able to remedy this primarily based on the exclusion precept. As a substitute of discovering attainable pairs discover the variety of unattainable circumstances and subtract that from all attainable substrings (i.e. N*(N+1)/2 ).
Methods to discover unattainable circumstances?
When s[i] and s[i-1] are identical, then after discount it should both grow to be “00” or “11”. In each circumstances, the substring can’t be decreased 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.
Comply with the under steps to unravel 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 method.
C++
|
Time Complexity: O(N)
Auxiliary House: O(1)