Sponsored
Sponsored
This approach involves using prefix sums to count the number of 'b's seen until each index and adjusting to track the potential number of deletions to ensure a balanced string.
Time Complexity: O(n), where n is the length of the string.
Space Complexity: O(1), since we're using constant space.
1function minDeletionsToMakeBalanced(s) {
2 let totalB = 0;
3 for (let char of s) {
4 if (char === 'b') totalB++;
5 }
6
7 let minDeletions = totalB;
8 let currentA = 0;
9 let currentB = 0;
10
11 for (let char of s) {
12 if (char === 'a') {
13 currentA++;
14 } else if (char === 'b') {
15 currentB++;
16 minDeletions = Math.min(minDeletions, currentA + (totalB - currentB));
17 }
18 }
19
20 return minDeletions;
21}
22
23console.log(minDeletionsToMakeBalanced('aababbab')); // Output: 2
This JavaScript solution uses a modern for...of iteration to count 'b's and then re-adjust as we iterate again to assess the minimal deletions needed in a similar manner as other language implementations.