Skip to main content
Back to problems
Leetcode
Medium
Strings
Arrays
Divide a String Into Groups of Size K

Split a string into consecutive groups of size k, padding the last group if needed.

Acceptance 100%
Also Available On
Other platform versions and source mappings for the same problem.

Divide String Into Groups of Size K

gfg
Problem Statement

Given 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 fill used 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 than k.
  • s contains printable characters.
  • fill is a single character.
  • Time complexity should be linear in the length of s.
Examples
Sample cases returned by the problem API.

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.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.