Divide a String Into Groups of Size k (LeetCode 2138): Solution and Explanation

Easy
String
Simulation

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

  1. Start with an empty list groups.
  2. For i = 0, k, 2k, ... while i < n, take group = s[i : i + k].
  3. If the slice is shorter than k, append k - len(group) copies of fill.
  4. Append the group to the answer and return the list at the end.

Step-by-step example

s = "abcdefghij", k = 3, fill = "x"
  1. Ten characters with k = 3 means four groups.
  2. i = 0 cuts "abc", i = 3 cuts "def", i = 6 cuts "ghi". All three are full.
  3. i = 9 cuts "j", which is two characters short, so append "xx" to get "jxx".
  4. 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 groups
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n + k)

Every character of s is copied once, plus at most k - 1 padding characters.

Space

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.