π§ Solving LeetCode Until I Become Top 1% β Day 27
πΉ Problem: 2138 Divide a String Into Groups of Size k
Difficulty: #Easy
Tags: #String, #Greedy
π Problem Summary
Given a string
s
, divide it into groups of sizek
. If the final group is smaller thank
, fill it with the givenfill
character until it reaches lengthk
.
Return a list of strings, each representing a group of size k
.
π§ My Thought Process
-
Brute Force Idea:
- Start taking substrings of length
k
in a loop and append them to a result list. - If the final group is smaller than
k
, pad it manually.
- Start taking substrings of length
-
Optimized Strategy:
- First, check if
s
is divisible byk
. If not, append the appropriate number offill
characters to make its length divisible byk
. - Then, iterate over the updated string with a step of size
k
and slice out chunks.
- First, check if
βοΈ Code Implementation (Python)
class Solution:
def divideString(self, s: str, k: int, fill: str) -> List[str]:
res = []
n = len(s)
s = s + (fill*(k-n%k) if n%k else '')
start = 0
while start < len(s):
res.append(s[start:start+k])
start += k
return res
β±οΈ Time & Space Complexity
- Time: O(N) Traverses the string once to pad (if needed), and once to slice.
- Space: O(N) Output list stores all the k-sized chunks.
π§© Key Takeaways
- β Learned how to chunk a string cleanly using modulo logic and list comprehensions.
- π‘ Edge cases like "what if the string isn't divisible by k?" must be handled before chunking.
- π This pattern is helpful for problems involving grouping, formatting, or padding strings to meet constraints.
π Reflection (Self-Check)
- [x] Could I solve this without help?
- [x] Did I write code from scratch?
- [x] Did I understand why it works?
- [x] Will I be able to recall this in a week?
π Related Problems
- [[68 Text Justification]]
π Progress Tracker
Metric | Value |
---|---|
Day | 27 |
Total Problems Solved | 360 |
Confidence Today | π |
Top comments (0)