Space Out the Characters of a String
Solve this ProblemEasy5 min
Topics
BasicsStrings
Companies
TCSInfosysWipro
Given a string
text with no spaces, return its characters separated by single spaces — for example "h e l l o".
This is the "print every character" exercise, done so the output can be checked: each character is visited in order with an indexString IndexThe position of a character in a string, starting from 0., just like an array. The small catch is the separatorSeparatorText placed between items, such as a comma or a space — but not before the first or after the last.: a space belongs between characters, not after the last one.
Test Case 1:
Input:text = "hello"
Output:"h e l l o"
Explanation:A single space between neighbouring characters, none at the ends.
Test Case 2:
Input:text = "A"
Output:"A"
Explanation:One character needs no separator.
Constraints
- ◆
1 ≤ text.length ≤ 100 - ◆
text contains printable ASCII characters and no spaces
Try the Dry Run
Approach & Solutions
Separator Before Every Character but the FirstGood
Visit the characters by index. Before adding character i, add a space — except for i = 0. That rule places exactly one space between neighbours and none at the ends. This is how you would print each character of a string on one line.
Time
O(n)Space
O(n)Java
class Solution {
public String spaceOut(String text) {
StringBuilder result = new StringBuilder();
for (int i = 0; i < text.length(); i++) {
if (i > 0) {
result.append(' ');
}
result.append(text.charAt(i));
}
return result.toString();
}
}Join with a SeparatorOptimal
Most languages can join a sequence of pieces with a separator: String.join in Java, " ".join in Python and split("").join(" ") in JavaScript put the space only between items. C++ uses a separator variable that is empty for the first character; C keeps the loop.
Time
O(n)Space
O(n)Java
class Solution {
public String spaceOut(String text) {
return String.join(" ", text.split(""));
}
}