Sponsored
Sponsored
This approach constructs the string by always choosing the majority character until we need to switch to prevent three consecutive characters.
Steps:
Time Complexity: O(a + b) because each character is processed once.
Space Complexity: O(a + b) for the result string.
1function strWithout3a3b(a, b) {
2 let res = [];
3 while (a > 0 || b > 0) {
4 let writeA = false;
5 let n = res.length;
6 if (n >= 2 && res[n - 1] === res[n - 2]) {
7 if (res[n - 1] === 'b') writeA = true;
8 } else {
9 if (a >= b) writeA = true;
10 }
11
12 if (writeA) {
13 res.push('a');
14 a--;
15 } else {
16 res.push('b');
17 b--;
18 }
19 }
20 return res.join('');
21}
22
23console.log(strWithout3a3b(4, 1));
This JavaScript solution creates a result list where characters are pushed based on the criteria of avoiding 'aaa' or 'bbb', and balances the number of 'a's and 'b's through an iterative approach.
This approach leverages an interleaving strategy to distribute characters evenly and avoid consecutive identical sequences.
Steps:
Time Complexity: O(a + b) due to iteration through characters.
Space Complexity: O(a + b) used for the output string.
This Python solution constructs the required string using a consistent interleaving pattern that ensures no 'aaa' or 'bbb' occurs by alternating the placement of 'a's and 'b's controlled by their counts.