Divide a String Into Groups of Size k (LeetCode 2138): Solution and Explanation
Split a string into consecutive chunks of length k, padding the final chunk with a fill character when it comes up short.
Intuition
The cut points are fixed in advance: group g always starts at index g * k. So there is nothing to decide, only to slice.
Every slice is full length except possibly the last one, which runs out of characters. That last slice is topped up with copies of fill until it reaches length k.
Approach: Slice in steps of k, pad the tail
- Start with an empty list
groups. - For i = 0, k, 2k, ... while i < n, take
group = s[i : i + k]. - If the slice is shorter than k, append
k - len(group)copies offill. - Append the group to the answer and return the list at the end.
Step-by-step example
s = "abcdefghij", k = 3, fill = "x"
- Ten characters with k = 3 means four groups.
- i = 0 cuts "abc", i = 3 cuts "def", i = 6 cuts "ghi". All three are full.
- i = 9 cuts "j", which is two characters short, so append "xx" to get "jxx".
- The answer is ["abc", "def", "ghi", "jxx"].
Code: Python, Java, C++
1class Solution:
2 def divideString(self, s: str, k: int, fill: str) -> List[str]:
3 groups = []
4 for i in range(0, len(s), k):
5 group = s[i:i + k]
6 if len(group) < k:
7 group += fill * (k - len(group))
8 groups.append(group)
9 return groups1class Solution {
2 public String[] divideString(String s, int k, char fill) {
3 int n = s.length();
4 String[] groups = new String[(n + k - 1) / k];
5 for (int i = 0; i < n; i += k) {
6 StringBuilder group = new StringBuilder(s.substring(i, Math.min(n, i + k)));
7 while (group.length() < k) {
8 group.append(fill);
9 }
10 groups[i / k] = group.toString();
11 }
12 return groups;
13 }
14}1class Solution {
2public:
3 vector<string> divideString(string s, int k, char fill) {
4 vector<string> groups;
5 for (int i = 0; i < (int)s.size(); i += k) {
6 string group = s.substr(i, k);
7 if ((int)group.size() < k) {
8 group += string(k - group.size(), fill);
9 }
10 groups.push_back(group);
11 }
12 return groups;
13 }
14};Time and space complexity
O(n + k)
Every character of s is copied once, plus at most k - 1 padding characters.
O(n + k)
The output holds all of s plus the padding; no other storage is needed.
Other approaches
Pad first, then slice (time O(n + k), space O(n + k))
Append fill characters until the length is a multiple of k, then cut every k characters with no special case for the last group.
Build character by character (time O(n + k), space O(n + k))
For each group index g and offset j, take s[g * k + j] if it exists, otherwise fill. Useful in languages without convenient slicing.
Common mistakes
- Padding every group instead of only the last one. Full groups must stay untouched.
- Computing the group count as n / k with integer division, which drops the short last group. Use (n + k - 1) / k.
- Slicing past the end of the string in languages that throw on out-of-range substrings, such as Java and C#.
Frequently asked questions
What if k is larger than the string?
There is exactly one group: the whole string padded with fill up to length k.
Can more than one group need padding?
No. Every group before the last is full because there are always at least k characters left when it is cut.
How many groups are there?
The ceiling of n / k, which is (n + k - 1) / k with integer division.