📝 Beginner-Friendly Guide “Divide a String Into Groups of Size k” – LeetCode 2138 (C++ | Python | JavaScript)

LeetCode 2138 | Easy | String Manipulation

🧠 Problem Summary

You are given:

  • A string s consisting of lowercase English letters
  • An integer k representing the desired group size
  • A character fill to be used if the final group is incomplete

Your task is to:

  • Divide the string into groups of size k
  • If the last group has fewer than k characters, pad it with the fill character

Return a list of all groups.

🤩 Intuition

This is a simple string-slicing problem where we need to:

  1. Iterate through the string in steps of size k
  2. For each step, extract a substring of size k
  3. If fewer than k characters remain at the end, append the required number of fill characters

This ensures all groups are of uniform length.

📊 C++ Code

class Solution {
 public:
  vector<string> divideString(string s, int k, char fill) {
    vector<string> ans;

    for (int i = 0; i < s.length(); i += k)
      ans.push_back(i + k > s.length()
                        ? s.substr(i) + string(i + k - s.length(), fill)
                        : s.substr(i, k));

    return ans;
  }
};

📝 Key Notes:

  • We check if the remaining characters are fewer than k
  • If yes, we pad using string(length, fill)
  • Time Complexity: O(n) where n = length of string

💻 JavaScript Code

var divideString = function(s, k, fill) {
    const result = [];

    for (let i = 0; i < s.length; i += k) {
        let chunk = s.slice(i, i + k);
        if (chunk.length < k) {
            chunk += fill.repeat(k - chunk.length);
        }
        result.push(chunk);
    }

    return result;
};

🔍 Explanation:

  • Use .slice() to grab groups
  • Pad using .repeat() if needed

🐍 Python Code

class Solution:
    def divideString(self, s: str, k: int, fill: str) -> List[str]:
        result = []
        for i in range(0, len(s), k):
            chunk = s[i:i+k]
            if len(chunk) < k:
                chunk += fill * (k - len(chunk))
            result.append(chunk)
        return result

✅ Final Thoughts

This problem tests your understanding of string slicing and basic iteration:

  • Slice by k
  • Handle edge cases with padding

It’s a clean, practical problem to get comfortable with loops and substring operations.

Drop a ❤️ if this helped, and follow along for more clean breakdowns and real-world examples!

Happy coding! 🚀

Leave a Reply