Greedy Approach! || Beats 100%|| C++|| Easy to understand Approach
About the questionThis is a fundamental yet frequently asked problem in FAANG-style interviews. The problem statement indirectly relates to Theory of Computatio
![Desktop.png](https://assets.leetcode.com/users/images/5d92fd62-9812-45d7-9fcd-af9d73565d63_1742123855.1856046.png)

# About the question
This is a fundamental yet frequently asked problem in FAANG-style interviews. The problem statement indirectly relates to Theory of Computation (TOC) concepts, so anyone familiar with finite automata and state transitions will have a much clearer visualization of how we are solving it.

# Intuition
At first glance, the problem seems straightforward: avoid $$aaa$$ and $$bbb$$ from appearing in the final string—which is exactly our goal! 😆
However, the real challenge is tracking the counts of $$a$$ and $$b$$ to ensure we don’t exceed the required number of each.
# Approach
We'll maintain a string $$result$$, where we gradually add characters while ensuring no $$aaa$$ or $$bbb$$ forms.
For the approach, we'll be focusing on a greedy approach, which will make a decision based on two things for every iteration we perform to append a particular character
1️⃣ What are the last two characters in the result?
2️⃣ Which character has the higher remaining count?

Every time, we check if the last two characters are same or not. So if they are same, then the next letter we append into the result will be the other character, so as to avoid 3 consecutive same letters ($$aaa$$ or $$bbb$$).

We'll also keep a track of how many $$a's$$ and $$b's$$ are remaining to be appended till now in the string, so that whoever's count is higher, will be added first, when the last two characters are different while checking the condition. This way, the Output string will be having no 3 consecutive $$a's$$ or $$b's$$
 
# Complexity
- Time complexity:
Since it runs a while loop with a+b iterations, the time complexity is $$O(a+b)$$



- Space complexity:
We're constructing a string of length a+b as output, so the space complexity will be $$O(a+b)$$

# Code
```cpp []
class Solution {
public:
    string strWithout3a3b(int a, int b) {
        string result;
        
        while (a > 0 || b > 0) {
            if (result.size() >= 2 && result.back() == result[result.size() - 2]) {
               
                if (result.back() == 'a') {
                    result += 'b';
                    b--;
                } else {
                    result += 'a';
                    a--;
                }
            } else {
                if (a >= b) {
                    result += 'a';
                    a--;
                } else {
                    result += 'b';
                    b--;
                }
            }
        }
        
        return result;
    }
};

```
# Thanks Y'all :)
# Hope this explanation helped! If you found it useful, consider upvoting. Happy coding!🚀
['String', 'Greedy', 'C++']