Sign in to devexcode.com with google.com

To continue, google.com will share your name, email address, and profile picture with this site. See this site's privacy policy.

2468. Split Message Based on Limit

Explanation

To solve this problem, we can iterate through the message while keeping track of the current part. We need to split the message into parts of length limit or less, and each part should have a suffix indicating its index and the total number of parts. We can achieve this by determining the number of parts needed, then dividing the message into equal parts (except the last one) and adjusting the length of the last part if necessary. Finally, we construct the parts with the appropriate suffixes.

  • Calculate the number of parts needed: numParts = ceiling(message.length() / limit).
  • Iterate over the message, splitting it into parts of length limit (except the last part).
  • Append the parts with the correct suffixes to the result array.

Time complexity: O(n) where n is the length of the message
Space complexity: O(n) for the result array

class Solution {
    public String[] splitMessage(String message, int limit) {
        int numParts = (int) Math.ceil((double) message.length() / limit);
        String[] result = new String[numParts];
        
        int index = 0;
        for (int i = 0; i < numParts - 1; i++) {
            result[i] = message.substring(index, index + limit) + "<" + (i + 1) + "/" + numParts + ">";
            index += limit;
        }
        
        result[numParts - 1] = message.substring(index) + "<" + numParts + "/" + numParts + ">";
        
        return result;
    }
}

Code Editor (Testing phase)

Improve Your Solution

Use the editor below to refine the provided solution. Select a programming language and try the following:

  • Add import statement if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.