Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • DSA
  • Practice Mathematical Algorithm
  • Mathematical Algorithms
  • Pythagorean Triplet
  • Fibonacci Number
  • Euclidean Algorithm
  • LCM of Array
  • GCD of Array
  • Binomial Coefficient
  • Catalan Numbers
  • Sieve of Eratosthenes
  • Euler Totient Function
  • Modular Exponentiation
  • Modular Multiplicative Inverse
  • Stein's Algorithm
  • Juggler Sequence
  • Chinese Remainder Theorem
  • Quiz on Fibonacci Numbers
Open In App
Next Article:
License Key Formatting
Next article icon

License Key Formatting

Last Updated : 24 Mar, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

Given a string S that consists of only alphanumeric characters and dashes. The string is separated into n+1 groups by n dashes. We are also given a number K, the task is to reformat the string S, such that each group contains exactly K characters, except for the first group, which could be shorter than K but still must contain at least one character. Furthermore, a dash must be inserted between two groups, and you should convert all lowercase letters to uppercase. Return the reformatted string.

Examples:

Input: S = "5F3Z-2e-9-w", K = 4
Output: "5F3Z-2E9W"
Explanation: The string S has been split into two parts, each part has 4 characters.Note that two extra dashes are not needed and can be removed.

Input: S = "2-5g-3-J", K = 2
Output: "2-5G-3J"
Explanation: The string s has been split into three parts, each part has 2 characters except the first part as it could be shorter as mentioned above

Table of Content

  • [Naive Approach] Using Extra String - O(n) Time and O(n) Space
  • [Expected Approach] Using One variable - O(n) Time and O(1) Space

[Naive Approach] Using Extra String - O(n) Time and O(n) Space

The idea is to use Greedy approach where we fill the result (from end) with k characters and the end fill the remaining characters at the beginning.

Follow the steps to solve the problem:

  • Create an empty string temp and push only the characters (in upper-case) that are different than '-'.
  • Now reverse the string obtained. Also, create a string 'ans' to store the final string.
  • Iterate over the string and whenever 'K' characters are pushed in 'ans' push a dash "-" into the string.
  • Return 'ans' as the result.
C++
#include <bits/stdc++.h> using namespace std; string ReFormatString(string S, int K){     string temp;     int n = S.length();     for (int i = 0; i < n; i++) {         if (S[i] != '-') {             temp.push_back(toupper(S[i]));         }     }     int len = temp.length();     string ans;     int val = K;      // Iterate over the string from right     // to left and start pushing     // characters at an interval of K     for (int i = len - 1; i >= 0; i--) {         if (val == 0) {             val = K;             ans.push_back('-');         }         ans.push_back(temp[i]);         val--;     }      // Reverse the final string and     // return it.     reverse(ans.begin(), ans.end());     return ans; } int main(){     string s = "5F3Z-2e-9-w";     int K = 4;     cout << ReFormatString(s, K);     return 0; } 
C
#include <ctype.h> #include <stdio.h> #include <string.h>   char* ReFormatString(char* S, int K) {     /     char temp[100];     int n = strlen(S);     int len = 0;     for (int i = 0; i < n; i++) {         if (S[i] != '-') {             temp[len++] = toupper(S[i]);         }     }         char* ans         = (char*)malloc(sizeof(char) * (len + len / K + 1));     int val = K;     int j = 0;      // Iterate over the string from right     // to left and start pushing     // characters at an interval of K     for (int i = len - 1; i >= 0; i--) {         if (val == 0) {             val = K;             ans[j++] = '-';         }         ans[j++] = temp[i];         val--;     }      // Reverse the final string and     // return it.     ans[j] = '\0';     int i = 0, k = j - 1;     while (i < k) {         char t = ans[i];         ans[i++] = ans[k];         ans[k--] = t;     }     return ans; }  int main() {     char s[] = "5F3Z-2e-9-w";     int K = 4;     printf("%s", ReFormatString(s, K));     return 0; } 
Java
class GFG {   public static String ReFormatString(String S, int K)    {     String temp = "";     int n = S.length();     for (int i = 0; i < n; i++) {       if (S.charAt(i) != '-') {         temp += (Character.toUpperCase(S.charAt(i)));       }     }     int len = temp.length();        String ans = "";     int val = K;      // Iterate over the String from right     // to left and start pushing     // characters at an interval of K     for (int i = len - 1; i >= 0; i--) {       if (val == 0) {         val = K;         ans += '-';       }       ans += temp.charAt(i);       val--;     }      // Reverse the final String and return it     char[] charArray = ans.toCharArray();     reverse(charArray, charArray.length);     String res = new String(charArray);     return res;   }     static void reverse(char a[], int n)   {     char t;     for (int i = 0; i < n / 2; i++) {       t = a[i];       a[i] = a[n - i - 1];       a[n - i - 1] = t;     }   }    public static void main(String args[]) {     String s = "5F3Z-2e-9-w";     int K = 4;     System.out.println(ReFormatString(s, K));    } } 
Python
def ReFormatStrings(s,k):      temp = ""     n = len(s)     for i in range(0,n):         if(s[i] != '-'):             temp += s[i].upper()     length = len(temp)          ans = ""     val = k          # Iterate over the string from right to left      # and start pushing characters at an interval of K     for i in range(length - 1,-1,-1):         if(val == 0):             val = k             ans += '-'         ans += temp[i]         val -= 1      # Reverse the final string and return it.     ans = ans[::-1]     return ans  # Driver code if __name__ == "__main__":     s = "5F3Z-2e-9-w"     k = 4     print(ReFormatStrings(s,k)) 
C#
using System;  public class GFG{       public static string ReFormatString(string S, int K)   {         string temp="";     int n = S.Length;     for (int i = 0; i < n; i++) {       if (S[i] != '-') {         temp+=(char.ToUpper(S[i]));       }     }     int len = temp.Length;           string ans="";     int val = K;      // Iterate over the string from right     // to left and start pushing     // characters at an interval of K     for (int i = len - 1; i >= 0; i--) {       if (val == 0) {         val = K;         ans+='-';       }       ans+=temp[i];       val--;     }      // Reverse the final string and     // return it.     char[] charArray = ans.ToCharArray();     Array.Reverse( charArray );     string res = new string(charArray);       return res;   }    static public void Main (){     string s = "5F3Z-2e-9-w";     int K = 4;     Console.WriteLine(ReFormatString(s, K));    } } 
JavaScript
function reverse(s) {     let splitString = s.split("");     let reverseArray = splitString.reverse();     let joinArray = reverseArray.join("");     return joinArray; }  function ReFormatString(S,K) {     let temp = "";     let n = S.length;     for (let i = 0; i < n; i++) {         if (S[i] != '-') {             temp+=S[i].toUpperCase();         }     }     let len = temp.length;         let ans = "";     let val = K;      // Iterate over the let from right     // to left and start pushing     // characters at an interval of K     for (let i = len - 1; i >= 0; i--) {         if (val == 0) {             val = K;             ans += '-';         }         ans += temp[i];         val--;     }      // Reverse the final let and     // return it.     ans = reverse(ans);     return ans; }  let s = "5F3Z-2e-9-w"; let K = 4; console.log(ReFormatString(s, K)); 

Output
5F3Z-2E9W

[Expected Approach] Using One variable - O(n) Time and O(1) Space

This is mainly an optimization over the above Greedy Approach.

  • Without creating any other string, we move all the dashes to the front and remove them then.
  • We make use of the below mathematical formula to calculate the number of dashes.
    Number of Dashes = (Total alphanumeric elements)/(number of elements in every group)
    Formula: Number of Dashes at any step = (Total alphanumeric elements to the right of the current index) / (number of elements in every group).

Follow the steps to solve the problem:

  • Iterate from the back of the string and move all the alphanumeric characters to the back of the string.
  • Delete all the dashes from the beginning.
  • Calculate the number of dashes(rounded-up) that would be present in the final string and append free it to the original string.
  • Iterate from the front and depending on the number of dashes that would be present up to that character, move the character by that amount in the left direction. 
  • Delete all the extra dashes that would have accumulated in the front of the string
  • Return the string after all the modifications as the answer.
C++
#include <bits/stdc++.h> using namespace std;   string ReFormatString(string S, int K){     int len = S.length();     int cnt = 0;     int x = 0;      // Move the characters to the     // back of the string.     for (int i = len - 1; i >= 0; i--) {         if (S[i] == '-') {             x++;         }         else {             S[i + x] = toupper(S[i]);         }     }      // Calculate total number of     // alphanumeric characters so     // as to get the number of dashes     // in the final string.     int slen = len - x;     int step = slen / K;      // Remove x characters from the     // start of the string      reverse(S.begin(), S.end());     int val = x;     while (val--) {         S.pop_back();     }      // Push the empty spaces in     // the string (slen+step) to get     // the final string length      int temp = step;     while (temp--)         S.push_back(' ');     reverse(S.begin(), S.end());      len = S.length();      // Using simple mathematics     // to push the elements     // in the string at the correct place.      int i = slen, j = step, f = 0;     while (j < len) {          // At every step calculate the         // number of dashes that would be         // present before the character         step = i / K;         if (f == 1)             step--;         int rem = i % K;          // If the remainder is zero it         // implies that the character is a dash.          if (rem == 0 and f == 0) {             S[j - step] = '-';             f = 1;             continue;         }         S[j - step] = S[j];         i--;         j++;         f = 0;     }     // Remove all the dashes that would have     // accumulated in the beginning of the string.      len = S.length();     reverse(S.begin(), S.end());     for (int i = len - 1; i >= 0; i--) {         if (S[i] != '-') {             break;         }         if (S[i] == '-')             S.pop_back();     }     reverse(S.begin(), S.end());      return S; } int main() {     string s = "5F3Z-2e-9-w";     int K = 4;     cout << ReFormatString(s, K);     return 0; } 
Java
/*package whatever //do not write package name here */  import java.io.*; import java.util.*;  class GFG {    public static String reverseS(String str){     String nstr = "";     for (int i = 0; i < str.length(); i++) {       char ch         = str.charAt(i);        nstr         = ch + nstr;      }     return nstr;   }    public static String ReFormatString(String S, int K)   {     int len = S.length();     int cnt = 0;     int x = 0;      // Move the characters to the     // back of the string.     for (int i = len - 1; i >= 0; i--) {       if (S.charAt(i) == '-') {         x++;       }       else {         S = S.substring(0, i + x)           + Character.toUpperCase(S.charAt(i))           + S.substring(i + x + 1);       }     }      // Calculate total number of     // alphanumeric characters so     // as to get the number of dashes     // in the final string.     int slen = len - x;     int step = (int)(slen / K);      // Remove x characters from the     // start of the string      S = reverseS(S);     int val = x;     while (val > 0) {       S = S.substring(0, S.length() - 1);       val--;     }      // Push the empty spaces in     // the string (slen+step) to get     // the final string length      int temp = step;     while (temp > 0) {       S += " ";       temp--;     }     S = reverseS(S);      len = S.length();      // Using simple mathematics     // to push the elements     // in the string at the correct place.      int i = slen, j = step, f = 0;     while (j < len) {        // At every step calculate the       // number of dashes that would be       // present before the character       step = (int)(i / K);       if (f == 1)         step--;       int rem = i % K;        // If the remainder is zero it       // implies that the character is a dash.        if (rem == 0 && f == 0) {         S = S.substring(0, j - step) + "-"           + S.substring(j - step + 1);         f = 1;         continue;       }       S = S.substring(0, j - step) + S.charAt(j)         + S.substring(j - step + 1);       i--;       j++;       f = 0;     }     // Remove all the dashes that would have     // accumulated in the beginning of the string.      len = S.length();     S = reverseS(S);     for (int m = len - 1; m >= 0; m--) {       if (S.charAt(m) != '-') {         break;       }       if (S.charAt(m) == '-')         S = S.substring(0, S.length() - 1);     }     S = reverseS(S);      return S;   }    public static void main(String[] args)   {     String s = "5F3Z-2e-9-w";     int K = 4;     System.out.println(ReFormatString(s, K));   } } 
Python
def reverse(string):     string = string[::-1]     return string  def ReFormatString( S, K):     length = len(S)     cnt = 0     x = 0      for i in range(length-1,-1,-1):         if (S[i] == '-'):             x+=1         else:             S = S[:i+x] + S[i].upper() + S[i+x+1:]      # Calculate total number of     # alphanumeric characters so     # as to get the number of dashes     # in the final string.     slen = length - x     step = slen / K      # Remove x characterclss from the     # start of the string      S = reverse(S)     val = x     while (val>0):         S = S[:len(S)-1]         val-=1      # Push the empty spaces in     # the string (slen+step) to get     # the final string length      temp = step     while (temp>0):         S+=' '         temp-=1     S = reverse(S)           length = len(S)      # Using simple mathematics     # to push the elements     # in the string at the correct place.      i = slen     j = step     f = 0     while (j < length):          # At every step calculate the         # number of dashes that would be         # present before the character         step = int(i / K)         if (f == 1):             step-=1         rem = i % K          # If the remainder is zero it         # implies that the character is a dash.         if (rem == 0 and f == 0):             step = int(step)             j = int(j)             S = S[:int(j-step)] + '-' + S[int(j-step)+1:]             f = 1             continue         S = S[:int(j-step)] + S[int(j)] + S[int(j-step)+1:]         i -= 1         j += 1         f = 0     # Remove all the dashes that would have     # accumulated in the beginning of the string.     length = len(S)     S = reverse(S)     for char in reversed(S):         if (char != '-'):             break         if (char == '-'):             S = S[:len(S)-1]     S = reverse(S)      return S   s = "5F3Z-2e-9-w" K = 4 print(ReFormatString(s, K)) 
C#
using System; using System.Collections.Generic;  public class GFG {    public static String reverseS(String str)   {     String nstr = "";     for (int i = 0; i < str.Length; i++) {       char ch = str[i];        nstr = ch + nstr;      }     return nstr;   }      public static String ReFormatString(String S, int K)   {     int len = S.Length;     int x = 0;     int i;      // Move the characters to the     // back of the string.     for (i = len - 1; i >= 0; i--) {       if (S[i] == '-') {         x++;       }       else {         S = S.Substring(0, i + x)           + Char.ToUpper(S[i])           + S.Substring(i + x + 1);       }     }      // Calculate total number of     // alphanumeric characters so     // as to get the number of dashes     // in the final string.     int slen = len - x;     int step = (int)(slen / K);      // Remove x characters from the     // start of the string      S = reverseS(S);     int val = x;     while (val > 0) {       S = S.Substring(0, S.Length - 1);       val--;     }      // Push the empty spaces in     // the string (slen+step) to get     // the final string length      int temp = step;     while (temp > 0) {       S += " ";       temp--;     }     S = reverseS(S);      len = S.Length;      // Using simple mathematics     // to push the elements     // in the string at the correct place.      i = slen;     int j = step, f = 0;     while (j < len) {        // At every step calculate the       // number of dashes that would be       // present before the character       step = (int)(i / K);       if (f == 1)         step--;       int rem = i % K;        // If the remainder is zero it       // implies that the character is a dash.        if (rem == 0 && f == 0) {         S = S.Substring(0, j - step) + "-"           + S.Substring(j - step + 1);         f = 1;         continue;       }       S = S.Substring(0, j - step) + S[j]         + S.Substring(j - step + 1);       i--;       j++;       f = 0;     }     // Remove all the dashes that would have     // accumulated in the beginning of the string.      len = S.Length;     S = reverseS(S);     for (int m = len - 1; m >= 0; m--) {       if (S[m] != '-') {         break;       }       if (S[m] == '-')         S = S.Substring(0, S.Length - 1);     }     S = reverseS(S);      return S;   }     static public void Main()   {      string s = "5F3Z-2e-9-w";     int K = 4;     Console.WriteLine(ReFormatString(s, K));   } } 
JavaScript
function ReFormatString(S, K) {     let len = S.length;     let cnt = 0;     let x = 0;      // Move the characters to the     // back of the string.     for (let i = len - 1; i >= 0; i--) {         if (S[i] == '-') {             x++;         }         else {             let c = (S[i].toUpperCase());             let arr1 = S.split('');             arr1[i + x] = c;             S = arr1.join("");         }     }      // Calculate total number of     // alphanumeric characters so     // as to get the number of dashes     // in the final string.     let slen = len - x;     let step = slen / K;      // Remove x characters from the     // start of the string      S = S.split('').reverse().join('');      let val = x;     while (val--) {         S = S.substring(0, S.length - 1);     }      // Push the empty spaces in     // the string (slen+step) to get     // the final string length      let temp = step;     while (temp--)         S += ' ';     S = S.split('').reverse().join('');      len = S.length;      // Using simple mathematics     // to push the elements     // in the string at the correct place.      let i = slen, j = step, f = 0;     while (j < len) {          // At every step calculate the         // number of dashes that would be         // present before the character         step = Math.floor(i / K);         if (f == 1)             step--;         let rem = i % K;          // If the remainder is zero it         // implies that the character is a dash.          if (rem == 0 && f == 0) {             let arr2 = S.split('');             arr2[j - step] = '-';             S = arr2.join("");             f = 1;             continue;         }         let arr3 = S.split('');         arr3[j - step] = S[j];         S = arr3.join("");         i--;         j++;         f = 0;     }     // Remove all the dashes that would have     // accumulated in the beginning of the string.      len = S.length;     S = S.split('').reverse().join('');      for (let i = len - 1; i >= 0; i--) {         if (S[i] != '-') {             break;         }         if (S[i] == '-')             S = S.substring(0, S.length - 1);      }     S = S.split('').reverse().join('');     return S; }  let s = "5F3Z-2e-9-w"; let K = 4; console.log(ReFormatString(s, K)); 

Output
5F3Z-2E9W

Next Article
License Key Formatting

K

kishanpandeyrkt
Improve
Article Tags :
  • Strings
  • Greedy
  • Mathematical
  • DSA
Practice Tags :
  • Greedy
  • Mathematical
  • Strings

Similar Reads

    Formats in Perl
    Formats are the writing templates used in Perl to output the reports. Perl has a mechanism which helps in generating simple reports and charts. Instead of executing, Formats are declared, so they may occur at any point in the program. Formats have their own namespace apart from the other types in Pe
    5 min read
    Data Formatting in Excel
    Data formatting in Excel is the key to transforming raw numbers into clear, professional, and actionable insights. From customizing dates and currencies to applying conditional formatting for quick analysis, mastering these techniques saves time and enhances your spreadsheets’ impact. This guide wil
    3 min read
    What is the Formatting Toolbar?
    The Formatting Toolbar is a standard component of many WPS and text editors that allows users to format the text quickly. Using this toolbar allows the user to improve the appearance and legibility of the textual content in a rather short period of time. In this article, I want to shed some light on
    6 min read
    Less.js String % format() Function
    Less.js is a simple CSS pre-processor that facilitates the creation of manageable, customizable, and reusable style sheets for websites. Since CSS is a dynamic style sheet language, it is preferred. Because LESS is adaptable, it can be used by a variety of browsers. Only CSS that has been created an
    4 min read
    Java String format() Method
    In Java, the String.format() method allows us to create a formatted string using a specified format string and arguments. We can concatenate the strings using this method, and at the same time, we can format the output with options such as width, alignment, decimal places, and more.Example: In the e
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences