Given a string s
and an integer k
, you need to divide the string into groups of size k
. If the length of s
is not a multiple of k
, the final group should be filled with lowercase 'x'
characters to make its length equal to k
.
Return the list of groups formed.
s
?k
be greater than the length of s
?s
(e.g. can it contain spaces, punctuation, numbers)?s
is empty, should the result be an empty list?Without further constraints, I’ll assume that:
s
can be any non-empty string containing any characters.k
is a positive integer.s
in increments of k
.k
characters, append 'x'
characters until the group’s length is k
.Here’s the implementation of the described strategy:
def divideString(s: str, k: int, fill: str = 'x') -> list:
result = []
n = len(s)
# Traverse the string in steps of k
for i in range(0, n, k):
group = s[i:i + k]
# If the group is shorter than k, fill it with 'x'
if len(group) < k:
group += fill * (k - len(group))
result.append(group)
return result
# Example usage:
# s = "abcdefghi"
# k = 3
# Expected output: ["abc", "def", "ghi"]
print(divideString("abcdefghi", 3))
# s = "abcdefghij"
# k = 3
# Expected output: ["abc", "def", "ghi", "jxx"]
print(divideString("abcdefghij", 3))
n
is the length of the input string s
. We traverse the string in chunks of size k
and perform O(1) operations for handling the last group.This solution ensures that the string is divided into groups of size k
, with the last group padded if necessary. The approach is efficient and handles edge cases effectively.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?