Premium Only Content

2109. Adding Spaces to a String
You are given a 0-indexed string s and a 0-indexed integer array spaces that describes the indices in the original string where spaces will be added. Each space should be inserted before the character at the given index.
For example, given s = "EnjoyYourCoffee" and spaces = [5, 9], we place spaces before 'Y' and 'C', which are at indices 5 and 9 respectively. Thus, we obtain "Enjoy Your Coffee".
Return the modified string after the spaces have been added.
Example 1:
Input: s = "LeetcodeHelpsMeLearn", spaces = [8,13,15]
Output: "Leetcode Helps Me Learn"
Explanation:
The indices 8, 13, and 15 correspond to the underlined characters in "LeetcodeHelpsMeLearn".
We then place spaces before those characters.
Example 2:
Input: s = "icodeinpython", spaces = [1,5,7,9]
Output: "i code in py thon"
Explanation:
The indices 1, 5, 7, and 9 correspond to the underlined characters in "icodeinpython".
We then place spaces before those characters.
Example 3:
Input: s = "spacing", spaces = [0,1,2,3,4,5,6]
Output: " s p a c i n g"
Explanation:
We are also able to place spaces before the first character of the string.
Constraints:
1 <= s.length <= 3 * 105
s consists only of lowercase and uppercase English letters.
1 <= spaces.length <= 3 * 105
0 <= spaces[i] <= s.length - 1
All the values of spaces are strictly increasing.
class Solution {
public:
string addSpaces(string s, vector<int>& spaces) {
int n = s.size();
int m = spaces.size();
int j=0;
string str="";
sort(spaces.begin(), spaces.end());
for(int i=0; i<n; i++){
if(j < m && spaces[j] == i){
str += " ";
j++;
}
str += s[i];
}
return str;
}
};
-
1:02:50
Flyover Conservatives
9 hours agoEric Trump: America’s Most Subpoenaed Man SPEAKS OUT! | FOC Show
20.8K5 -
LIVE
PandaSub2000
1 day agoLIVE 10/3 @10pm ET | SUPER MARIO GALAXY 1 & 2 on SWITCH 2
235 watching -
1:26:04
Glenn Greenwald
8 hours agoJournalist Ken Klippenstein on Trump's New Domestic Terrorism Memo; Glenn Takes Your Questions on Bari Weiss's CBS Role, His Interview with Nick Fuentes, and More | SYSTEM UPDATE #526
75.8K56 -
SynthTrax & DJ Cheezus Livestreams
2 days agoFriday Night Synthwave 80s 90s Electronica and more DJ MIX Livestream GOTH NIGHT Special Edition
27.1K2 -
2:20:47
Mally_Mouse
5 days agoFriend Friday!! 🎉 - Let's Play! - Lockdown Protocol
29.5K1 -
LIVE
MissesMaam
4 hours ago*Spicy* Friend Friday LOCKDOWN Protocol!!! :: SpookTober 💚✨
201 watching -
41:36
MattMorseTV
5 hours ago $0.80 earned🔴Portland just made a BIG MISTAKE.🔴
43.6K74 -
13:10:23
LFA TV
1 day agoLIVE & BREAKING NEWS! | FRIDAY 10/3/25
165K46 -
4:07:27
Nerdrotic
9 hours ago $0.33 earnedHollywood is TARIFFied, James Gunn Attacks Fans, Bill Burqa, RoP is Doomed | Friday Night Tights 374
76.1K12 -
LIVE
Eternal_Spartan
13 hours ago🟢 Eternal Spartan Plays Destiny 2 | The Best PVP/PVE Action!| USMC Veteran
38 watching