FastPrepSplit Text into Fixed-Length Chunks

Split Text into Fixed-Length Chunks

WhatNot logoWhatNot● EasyINTERNPHONE SCREEN
Learn

Problem statement

Given a string text and a positive integer k, split the string from left to right into consecutive chunks.

  • Every chunk except possibly the last must contain exactly k characters.
  • If fewer than k characters remain, return them as the last chunk without padding.
  • Keep every character exactly once and in order. Spaces and punctuation count toward the length; do not split by words or trim whitespace.
  • Return an empty array when text is empty. Do not add an empty trailing chunk when the length is divisible by k.

Function

splitFixedLength(text: String, k: int) → String[]

Examples

Example 1

text = "abcdefg"k = 3return = ["abc","def","g"]

Two full chunks contain three characters each. The remaining character forms the last chunk.

Example 2

text = "ab cd! "k = 3return = ["ab ","cd!"," "]

Spaces and punctuation count as characters and are preserved, including the trailing space.

Example 3

text = ""k = 4return = []

There are no characters, so the result contains no chunks.

Constraints

  • 0 <= text.length <= 2000.
  • 1 <= k <= 2000.
  • Every character is printable ASCII, with character code from 32 to 126.

More WhatNot problems

See WhatNot hiring insights
public String[] splitFixedLength(String text, int k) {
    // write your code here
}
text"abcdefg"
k3
expected["abc", "def", "g"]
Checking account…