703441. Roll the characters of a String

Medium

Roll the characters of a String

Slug: roll-the-characters-of-a-string2127

Difficulty: Medium

Id: 703441

Topic Tags: Arrays, Strings, Data Structures

Company Tags: Airtel

Summary

The problem involves rolling the characters of a given string in a specific order. The goal is to take a string as input and roll its characters into a single string by concatenating them according to certain rules. This process can be seen as taking a character from each set of n consecutive characters, where n is the number of sets, and then repeating this process until all characters have been processed.

Detailed Explanation

To solve this problem, we will implement an algorithm that iterates through the input string and constructs a new string based on the given rules. We can start by initializing an empty result string and a counter to keep track of the number of sets processed so far.

Here's a step-by-step breakdown of the solution:

  1. Initialize an empty result string res and a counter count set to 0.
  2. Iterate through each character in the input string:
    • If count is equal to the desired number of sets (e.g., 3), increment count and add the current character to the result string.
    • Otherwise, simply add the current character to the result string.
  3. Repeat step 2 until all characters have been processed.

Time Complexity Analysis:

  • The algorithm iterates through each character in the input string once, resulting in a time complexity of O(n), where n is the length of the input string.

Space Complexity Analysis:

  • The algorithm requires additional space to store the result string and the counter variable. In the worst-case scenario, when all characters are added to the result string without any sets being processed, the space complexity would be O(n). However, since we're processing sets of characters, the average case would have a space complexity closer to O(1) or constant.

Optimized Solutions

Java

View on GeeksforGeeks
public String rollCharacters(String str) {
    StringBuilder res = new StringBuilder();
    int count = 0;
    for (char c : str.toCharArray()) {
        if (count == 3) {
            res.append(c);
            count = 0;
        } else {
            res.append(c);
            count++;
        }
    }
    return res.toString();
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.