Skip to main content
Back to problems
#984
Medium Algorithms

String without aaa or bbb

String Greedy
45.0% acceptance
Feb 25, 2026
872
377
Given two integers a and b, return any string s such that: s has length a + b and contains exactly a 'a' letters, and exactly b 'b' letters, The substring 'aaa' does not occur in s, and The substring 'bbb' does not occur in s.

Solution

Rust
Time O(n²)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn str_without3a3b(a: i32, b: i32) -> String {
    let mut res = String::new();
    let (mut a, mut b) = (a, b);
    while a > 0 || b > 0 {
      if a >= b {
        let take_a = if a > b { 2.min(a) } else { 1 };
        for _ in 0..take_a { res.push('a'); a -= 1; }
        if b > 0 { res.push('b'); b -= 1; }
      } else {
        let take_b = 2.min(b);
        for _ in 0..take_b { res.push('b'); b -= 1; }
        if a > 0 { res.push('a'); a -= 1; }
      }
    }
    res
  }
}