To solve this problem efficiently, we can use a two-pass approach:
-
First Pass (Left to Right):
- Compute a prefix sum that counts the number of 'B's encountered up to each position. This represents how many 'B's we need to delete if we decide to split the string at that position, keeping all 'A's to the left.
-
Second Pass (Right to Left):
- Compute a suffix sum that counts the number of 'A's from each position to the end of the string. This represents how many 'A's we need to delete if we decide to keep all 'B's to the right.
-
Combine Results:
- For each possible split point, the total number of deletions needed is the sum of the 'B's to the left and 'A's to the right. The minimum of these sums across all possible split points gives the answer.
Here is the Java implementation of this approach:
public class Solution {
public static int solution(String S) {
int N = S.length();
// prefixB[i] will store the number of 'B's up to index i-1
int[] prefixB = new int[N + 1];
prefixB[0] = 0;
for (int i = 0; i < N; i++) {
prefixB[i + 1] = prefixB[i] + (S.charAt(i) == 'B' ? 1 : 0);
}
// suffixA[i] will store the number of 'A's from index i to end
int[] suffixA = new int[N + 1];
suffixA[N] = 0;
for (int i = N - 1; i >= 0; i--) {
suffixA[i] = suffixA[i + 1] + (S.charAt(i) == 'A' ? 1 : 0);
}
// Now find the minimum prefixB[i] + suffixA[i] over all i
int minDeletions = Integer.MAX_VALUE;
for (int i = 0; i <= N; i++) {
int deletions = prefixB[i] + suffixA[i];
if (deletions < minDeletions) {
minDeletions = deletions;
}
}
return minDeletions;
}
// Example usage and simple test cases
public static void main(String[] args) {
System.out.println(solution("BAAABAB")); // Output: 2
System.out.println(solution("AAAA")); // Output: 0
System.out.println(solution("BBBB")); // Output: 0
System.out.println(solution("ABABAB")); // Output: 3
System.out.println(solution("BABA")); // Output: 2
}
}
Explanation:
Test Cases:
"BAAABAB" returns 2.
"AAAA" returns 0 (already all 'A's).
"BBBB" returns 0 (already all 'B's).
"ABABAB" returns 3.
"BABA" returns 2.
This approach ensures an efficient solution with a time complexity of O(N) and space complexity of O(N), where N is the length of the string S.