Last Updated: 27 May, 2025

Split String

Easy
Asked in company
Impledge Technologies

Problem statement

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'.


For Example :
Let 'S' = "HelloWorld", N = 3.
The output should be "Hel", "loW ,"orl", "d".
Input Format :
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.
Constraints :
1 <= length of 'S' <= 10^5
1 <= 'N' <= length of 'S'
'S' can contain numbers as well as letters

Time Limit: 1 sec

Approaches

01 Approach

Approach:

  • Initialize an empty list to store the resulting substrings.
  • Iterate through the input string 'S' from the beginning to the end with a step size of 'N'.
  • In each iteration, extract a substring of length 'N' starting from the current index.
  • If the remaining part of the string is less than 'N', extract the remaining part as the last substring.
  • Add each extracted substring to the list.
  • Return the list of substrings.

Algorithm:

  • Initialize an empty list 'result'.
  • Initialize a variable 'L' to the length of the string 'S'.
  • Iterate using 'i' from 0 to 'L - 1' with a step of 'N':
    • If ( 'i' + 'N' <= 'L' ):
      • Add the substring of 'S' from index 'i' to 'i' + 'N' (exclusive) to 'result'.
    • Else:
      • Add the substring of 'S' from index 'i' to the end of 'S' to 'result'.
  • Return 'result'.