LeetCode Entry

2109. Adding Spaces to a String

03.12.2024 medium 2024 kotlin rust

Insert spaces into string

2109. Adding Spaces to a String medium blog post substack youtube deep-dive 1.webp

Join me on Telegram

https://t.me/leetcode_daily_unstoppable/821

Problem TLDR

Insert spaces into string #medium

Intuition

Iterate over string and adjust second pointer for spaces or iterate over spaces and insert substrings.

Approach

  • Kotlin has a slice for strings
  • Rust strings can append &[..] slices

Complexity

  • Time complexity: \(O(n)\)

  • Space complexity: \(O(n)\)

Code


    fun addSpaces(s: String, spaces: IntArray) = buildString {
        for ((j, i) in spaces.withIndex())
              k
        append(s.drop(spaces.last()))
    }


    pub fn add_spaces(s: String, spaces: Vec<i32>) -> String {
        let mut r = String::new();
        for (i, &j) in spaces.iter().enumerate() {
            r += &s[r.len() - i..j as usize]; r += " "
        }; r += &s[*spaces.last().unwrap() as usize..]; r
    }


    string addSpaces(string s, vector<int>& spaces) {
        string r;
        for (int i = 0, j = 0; i < s.size(); ++i)
            j < spaces.size() && i == spaces[j]
                ? j++, r += " ", r += s[i] : r += s[i];
        return r;
    }