Last Updated: 3 Sep, 2021

String Reformat

Easy
Asked in company
Google inc

Problem statement

You are given a string ‘S’ consisting of alphanumeric characters, the string divided into groups by a ‘-’. Your task is to reformat the string that all the groups contain exactly ‘K’ characters. All the lowercase characters should be converted to uppercase.

Note:
The first group may have fewer characters than ‘K’.
For example:
You are given ‘S’ =’A1-ijklmno-pqr’ and k = ‘3’, then the string contains 3 parts, [“A1”, “ijklmno”, “pqr”], then you can form the string in groups ["A1I”, “JKL”, “MNO”, “PQR"] of uppercase characters. Hence the answer is "A1I-JKL-MNO-PQR"
Input Format:
 The first line of input contains the integer ‘T’ representing the number of test cases.

The first line of each test case contains one integer ‘K’, representing the size of the group the string is to be divided.

The second line of each test case contains the string ‘S’ representing the given string.
Output Format:
For each test case, print a single string consisting of alphanumeric characters divided into groups of size ‘K’ separated by ‘-’.

Print a separate line for each test case.
Constraints:
1 <= T <= 10
1 <= K <= 10^8
1 <= |S| <= 10^8

All characters in ‘S’ are alphanumeric and ‘-’.

Time Limit: 1 sec
Note:
You do not need to print anything. It has already been taken care of. Just implement the function.

Approaches

01 Approach

In this approach, we will remove the separator ‘-’,  Then we will move from the end towards the starting of the string and add a  ‘-’ after each k character of the string.

 

Algorithm:

  • Initialise an empty string ansStr
  • Iterate i from length of s  - 1 to 0
    • If s[i] is equal to ‘-’
      • Continue the loop
    • If the size ansStr mod with k + 1 equals to k
      • Add ‘-’ to ansStr
    • Add upper case character at s[i] to ansStr
  • Reverse the string ansStr
  • Finally, return the string ansStr