Divide a String Into Groups of Size k

Easy
663.

Divide a String Into Groups of Size k

Divide a String Into Groups of Size k is an easy coding problem on strings and simulation, asked in TCS, Capgemini and Cognizant interviews.

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.
Write your solution here. Running it against the tests needs a free account — what you type comes with you.Sign in to run
/**
 * @param {string} s
 * @param {number} k
 * @param {string} fill
 * @return {string[]}
 */
var divideString = function(s, k, fill) {
    // Write your code here
    
};

Sign in to run your own test cases

Sign in

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

Divide a String Into Groups of Size k solution explained: step-by-step approach, complexity and code in Python, Java, C++ and JavaScript. An easy problem.

Divide a String Into Groups of Size k is an easy coding problem on strings and simulation, asked in TCS, Capgemini and Cognizant interviews.

  • 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.

Hints for Divide a String Into Groups of Size k

  1. Hint 1

    Step through s in strides of k and slice.

  2. Hint 2

    The last slice may be short — pad it after cutting, not before.

  3. Hint 3

    Only the final group can ever need padding.

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

Java

public static String[] divideString(String s, int k, String fill) {
    List<String> out = new ArrayList<>();
    for (int i = 0; i < s.length(); i += k) {
        StringBuilder part = new StringBuilder(s.substring(i, Math.min(i + k, s.length())));
        while (part.length() < k) part.append(fill);
        out.add(part.toString());
    }
    return out.toArray(new String[0]);
}

C++

vector<string> divideString(string s, int k, string fill) {
    vector<string> out;
    for (int i = 0; i < (int) s.size(); i += k) {
        string part = s.substr(i, k);
        while ((int) part.size() < k) part += fill;
        out.push_back(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#, Go, Kotlin, PHP, Ruby, Rust, Swift, TypeScript.

All 515 strings problems · the whole catalogue

Learn the technique: Strings