Divide a String Into Groups of Size k - Problem

A string s can be partitioned into groups of size k using the following procedure:

  • The first group consists of the first k characters of the string, the second group consists of the next k characters of the string, and so on. Each character can be a part of exactly one group.
  • For the last group, if the string does not have k characters remaining, a character fill is used to complete the group.

Note that the partition is done so that after removing the fill character from the last group (if it exists) and concatenating all the groups in order, the resultant string should be s.

Given the string s, the size of each group k and the character fill, return a string array denoting the composition of every group s has been divided into, using the above procedure.

Input & Output

Example 1 — Basic Case
$ Input: s = "abcdefghi", k = 3, fill = "x"
Output: ["abc","def","ghi"]
💡 Note: The string has exactly 9 characters, which divides evenly into 3 groups of size 3: "abc", "def", "ghi". No padding needed.
Example 2 — Padding Required
$ Input: s = "abcdefg", k = 3, fill = "x"
Output: ["abc","def","gxx"]
💡 Note: The string has 7 characters. First two groups are complete: "abc", "def". Last group "g" needs padding with "x" to become "gxx".
Example 3 — Single Character Group
$ Input: s = "a", k = 3, fill = "b"
Output: ["abb"]
💡 Note: Single character "a" forms one group, padded with "b" twice to reach size 3: "abb".

Constraints

  • 1 ≤ s.length ≤ 100
  • s consists of lowercase English letters only
  • 1 ≤ k ≤ 100
  • fill is a lowercase English letter

Visualization

Tap to expand
Divide a String Into Groups of Size k INPUT String s = "abcdefghi" a b c d e f g h i 0 1 2 3 4 5 6 7 8 Parameters k = 3 fill = "x" Length = 9 Groups needed: 9/3 = 3 ALGORITHM STEPS 1 Calculate Groups groups = ceil(9/3) = 3 2 Slice i=0 s[0:3] --> "abc" 3 Slice i=1 s[3:6] --> "def" 4 Slice i=2 s[6:9] --> "ghi" Direct String Slicing abc def ghi No padding needed (9 % 3 == 0) FINAL RESULT Output Array: "abc" index 0 "def" index 1 "ghi" index 2 Output ["abc","def","ghi"] OK - Valid partition! Verification: "abc"+"def"+"ghi" = s Key Insight: Direct string slicing avoids character-by-character iteration. For each group i, extract s[i*k : (i+1)*k]. If the last group is shorter than k, pad with 'fill' character until length k. Time: O(n) | Space: O(n) where n = length of string s TutorialsPoint - Divide a String Into Groups of Size k | Optimized - Direct String Slicing
Asked in
Amazon 15 Microsoft 12
23.4K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen