Last Updated: 8 Sep, 2025

Smart Tweet Splitter

Ninja
Asked in company
Wednesday Solutions

Problem statement

You are given a long string of text and a maximum character length for a tweet. Your task is to write a function that splits the text into one or more tweets.

The splitting must adhere to the following rules:

  • Each tweet string must have a length less than or equal to maxLength.

  • Splitting must only occur at word boundaries (i.e., on spaces). A word must not be broken in the middle.

  • If the text is split into multiple tweets, a numbering suffix like (1/3), (2/3), (3/3) must be appended to each tweet.

  • The length of this numbering suffix must be included when calculating the total character count of a tweet.

  • Your function should return a list or array of the resulting tweet strings.


    Input Format:
    The first line of input contains the string text.
    The second line of input contains an integer maxLength.
    


    Output Format:
    Print the resulting tweet strings, one per line.
    If the text is empty or contains only spaces, print nothing.
    If any single word in the text is too long to fit in a tweet even by itself (after accounting for the suffix), the task is impossible. In this case, print a single line with the string Error: Word too long.
    


    Note:
    The core challenge is that you don't know the total number of tweets (T in (i/T)) until you've already split the text. But the length of T (e.g., whether it's a 1-digit or 2-digit number) affects the available space in each tweet, which in turn affects the splitting.
    The optimal solution involves an iterative approach: first, try to split the text assuming there will be 1 total tweet. If that fails, try to split it assuming there will be 2 total tweets, and so on, until a valid split is found. The first valid split will be the one with the minimum possible number of tweets.