Build a Repeated, Joined String
Practice building a string incrementally (StringBuilder/append) instead of repeated concatenation.
Given a string word, an integer count, and a separator string sep, build and return a single string that repeats word exactly count times, with sep inserted between each repetition (but not before the first or after the last). If count is 0, return an empty string.
This is a basics exercise for building strings incrementally — StringBuilder in Java, StringBuilder in C#, and their equivalents elsewhere — rather than repeatedly concatenating with +.
Example 1
Input: word = "ab", count = 3, sep = "-"
Output: "ab-ab-ab"
Example 2
Input: word = "x", count = 1, sep = ","
Output: "x"
Explanation: With only one repetition, no separator is needed.
Example 3
Input: word = "hi", count = 0, sep = ","
Output: ""
Constraints
- 1 <= word.length <= 20
- 0 <= count <= 1000
- 0 <= sep.length <= 5
Follow-up
How would this change if word could be megabytes long and count could be in the millions?
Hints
Companies
No companies reported yet.
Discussion
Sign in to join the discussion.
Loading discussion...
Test results
No test cases yet.