Divide a String Into Groups of Size k — Easy Problem & Solution

Split the string s into consecutive groups of exactly k characters, in order.

  • Difficulty: Easy
  • Topics: Strings, Simulation
  • Asked at: TCS, Capgemini, Cognizant
  • Time limit: 2 s
  • Memory limit: 256 MB
  • Languages: JavaScript, TypeScript, Python, Java, C++, C, C#, Go, Kotlin, Swift, Rust, PHP and Ruby

Problem statement

Split the string s into consecutive groups of exactly k characters, in order.

If the last group is short, pad it on the right with the character fill until it reaches length k. Return the groups.

Example 1

Input: s = "codekairo", k = 4, fill = "x"
Output: ["code","kair","oxxx"]
Explanation: The last group holds only o, so three x characters are appended.

Example 2

Input: s = "abcdefghi", k = 3, fill = "x"
Output: ["abc","def","ghi"]
Explanation: The length divides evenly, so no padding is needed.

Example 3

Input: s = "ab", k = 5, fill = "z"
Output: ["abzzz"]

Constraints

  • 1 <= s.length <= 100
  • 1 <= k <= 100
  • fill is a single lowercase letter
  • s consists of lowercase English letters.

How to solve Divide a String Into Groups of Size k

Cut the string at every multiple of k; at most the final piece is short, and padding it to length is a simple append loop.

Approach

  1. Loop i = 0, k, 2k, … while i < s.length.
  2. Take the slice starting at i of length up to k.
  3. While the slice is shorter than k, append fill.
  4. Collect the slices in order.

Why it works

Slices at multiples of k partition the string, and only the last can fall short because every earlier start has at least k characters remaining by construction.

Complexity

  • Time — O(n)
  • Space — O(n)

Pitfalls

  • Padding s to a multiple of k up front also works, but computing the pad length wrong adds a whole spurious group when the length already divides evenly.
  • Prepending the fill instead of appending reverses the padded group.

Reference solution

Python

from typing import List

def divideString(s: str, k: int, fill: str) -> List[str]:
    out = []
    for i in range(0, len(s), k):
        part = s[i:i + k]
        part += fill * (k - len(part))
        out.append(part)
    return out

JavaScript

var divideString = function(s, k, fill) {
    var out = [];
    for (var i = 0; i < s.length; i += k) {
        var part = s.substr(i, k);
        while (part.length < k) part += fill;
        out.push(part);
    }
    return out;
};

Also on the editorial tab: C, C#, C++, Go, Java, Kotlin, PHP, Ruby, Rust, Swift, TypeScript.

All 282 strings problems · the whole catalogue