LeetCode 2109: Adding Spaces to a String Solution

Master LeetCode problem 2109 (Adding Spaces to a String), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

2109. Adding Spaces to a String

Problem Explanation

Explanation:

To solve this problem, we can iterate through the given string and the spaces array simultaneously. We keep track of the current position in the original string and compare it with the positions where spaces need to be added. If the current position matches one of the space positions, we insert a space before that character.

Time Complexity:

The time complexity of this solution is O(n), where n is the length of the input string.

Space Complexity:

The space complexity of this solution is O(n), where n is the length of the input string.

Solution Code

class Solution {
    public String addSpacesToString(String s, int[] spaces) {
        StringBuilder sb = new StringBuilder();
        int spaceIdx = 0;
        for (int i = 0; i < s.length(); i++) {
            if (spaceIdx < spaces.length && i == spaces[spaceIdx]) {
                sb.append(" ");
                spaceIdx++;
            }
            sb.append(s.charAt(i));
        }
        return sb.toString();
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 2109 (Adding Spaces to a String)?

This page provides optimized solutions for LeetCode problem 2109 (Adding Spaces to a String) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 2109 (Adding Spaces to a String)?

The time complexity for LeetCode 2109 (Adding Spaces to a String) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 2109 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2109 in Java, C++, or Python.

Back to LeetCode Solutions