
You are given a string 'S' which can contain numbers or characters, and an integer 'N'.
Split the string 'S' into substrings of length 'N'. The last substring might be shorter than 'N'.
Let 'S' = "HelloWorld", N = 3.
The output should be "Hel", "loW ,"orl", "d".
The first line contains the string 'S'.
The second line contains the integer 'N'.
Output Format :
Return an array of strings, where each string is a segment of the original string 'S' of length 'N', except possibly the last one.
Note :
You don’t need to print anything. Just implement the given function.
1 <= length of 'S' <= 10^5
1 <= 'N' <= length of 'S'
'S' can contain numbers as well as letters
Time Limit: 1 sec
ABCDEFG
2
AB, CD, EF, G
The input string is "ABCDEFG" and 'N' is 2.
Splitting the string every 2 characters results in the substrings: "AB", "CD", "EF", and the remaining "G".
Thus, the answer is "AB", "CD", "EF", "G".
1234567890
3
123, 456, 789, 0
Iterate through the string with a step of 'N'.
Approach:
Algorithm:
O(L), where 'L' is the length of the string 'S'.
We iterate through the string 'S' once. The substring operation takes at most O(L) in some implementations, but when considered together across the loop, each character is processed a constant number of times. Thus, the overall time complexity is of the order O(L).
O(K), where 'K' is the number of substrings generated, which is at most 'L'.
We are creating a list to store the substrings. In the worst case, if 'N' is 1, the number of substrings will be equal to the length of 'S'. Thus, the overall space complexity is of the order O(L) in the worst case, but can be less if 'N' is larger. So, we represent it as O(K) where K is the number of output substrings.