Split a string into consecutive groups of size k, padding the last group if needed.
Divide String Into Groups of Size K
gfgGiven a string s, divide it into consecutive groups where each group has exactly k characters.
If the last group has fewer than k characters, pad it on the right with a specified fill character until it reaches length k.
Return the resulting groups in order as an array of strings.
Input Format
Input
- A string
s - An integer
k - A character
fillused to pad the last group when needed
Notes
- Groups are formed from left to right.
- Each output group must have length exactly
k.
Output Format
Output
- Return an array of strings where each string has length
k.
Constraints
1 <= k <= len(s)is not guaranteed in this rephrased version; the last group may be shorter thank.scontains printable characters.fillis a single character.- Time complexity should be linear in the length of
s.
Example 1
Input
s = "abcdefghi", k = 3, fill = "x"
Output
["abc", "def", "ghi"]
Explanation
The string length is already a multiple of 3, so no padding is needed.
Example 2
Input
s = "abcdefgh", k = 3, fill = "x"
Output
["abc", "def", "ghx"]
Explanation
The last group contains only gh, so it is padded with one x to reach length 3.
Premium problem context
Unlock deeper context for this problem
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.