LeetCode Daily Challenge-2138. Divide a String Into Groups of Size k

2 min read

Algorithm walkthrough
Input and output
The divideString method takes three parameters:
s
: The input string to be dividedk
: The size of each groupfill
: The character used to pad the last group if needed And we need to return the grouped strings in groups of size k
1. Initialize variables:
- res = []: An empty list to store the resulting groups
- n = len(s): The length of the input string
2. Iterate through the string in steps of k:
This loop starts at index 0 and jumps by k positions each iteration (0, k, 2k, 3k, etc.)
for i in range(0, n, k):
3. For each iteration, check if a complete group of size k exists:
if (i+k-1) < n
: checks if we can extract a full group of k characters- If yes:
res.append(s[i:i+k])
extracts exactly k characters starting from index i
4. Handle the last group (if incomplete):
else
: branch executes when we can't get a full group of k characterss[i:n]
gets the remaining characters.ljust(k, fill)
pads the string on the right with the fill character to make it exactly k characters long
Full solution
class Solution:
def divideString(self, s: str, k: int, fill: str) -> List[str]:
# TC: O(n)
# SC: O(n)
res = []
n = len(s)
for i in range(0,n,k):
if (i+k-1)<n:
res.append(s[i:i+k])
else:
res.append(s[i:n].ljust(k, fill)) # fill the right with fill character
return res
0
Subscribe to my newsletter
Read articles from Anni Huang directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Anni Huang
Anni Huang
I am Anni HUANG, a software engineer with 3 years of experience in IDE development and Chatbot.