Editorial
Solution walkthrough
Review the explanation, then compare the reference implementation.
Video explanation
Solution
Intuition
The grouping boundaries are fixed every k characters. Every group except possibly the last is already full, so only the final group can require padding.
Approach
Slice the nonempty string at starting positions zero, k, 2k, and so on, appending each slice of at most k characters to the result. Append exactly k - lastGroupLength copies of fill to the final group, then return the groups. When the length is already divisible by k, this appends zero characters and does not create an extra group. When the whole string is shorter than k, its only group is padded.
class Solution:
def divideString(self, s: str, k: int, fill: str) -> List[str]:
n = len(s)
res = []
for i in range(0, n, k):
res.append(s[i : i + k])
res[-1] += fill * (k - len(res[-1]))
return resComplexity analysis
Let n = s.length. Time is O(n + k) including last-group padding. The returned groups contain O(n + k) characters, and constructing the padding plus the replacement final immutable string uses O(k) transient auxiliary space.
