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 thefill
character
Return a list of all groups.
π€© Intuition
This is a simple string-slicing problem where we need to:
- Iterate through the string in steps of size
k
- For each step, extract a substring of size
k
- If fewer than
k
characters remain at the end, append the required number offill
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! π
Top comments (6)
Good intution
thanks anna
Pretty cool seeing the same trick in all three languages - makes it look simple.
Thanks Nevo!
Hi, great guide thanks for sharing
Thanks Saile!