VOOZH about

URL: https://www.geeksforgeeks.org/dsa/alphanumeric-abbreviations-of-a-string/

⇱ Alphanumeric Abbreviations of a String - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Alphanumeric Abbreviations of a String

Last Updated : 10 Apr, 2025

Given a string of characters of length less than 10. We need to print all the alpha-numeric abbreviation of the string. The alpha-numeric abbreviation is in the form of characters mixed with the digits which is equal to the number of skipped characters of a selected substring. 

So, whenever a substring of characters is skipped, you have to replace it with the digit denoting the number of characters in the substring. There may be any number of skipped substrings of a string. No two substrings should be adjacent to each other. Hence, no two digits are adjacent in the result. For a clearer idea, see the example. 

Examples:

Input: ANKS 
Output:
ANKS (nothing is replaced)
ANK1 (S is replaced) 
AN1S (K is replaced)
AN2  (KS is replaced)
A1KS (N is replaced)
A1K1 (N and S are replaced)
A2S (NK is replaced)
A3 (NKS is replaced)
1NKS (A is replaced)
1NK1 (A and S are replaced)
1N1S (A and N is replaced)
1N2 (A and KS are replaced)
2KS (AN is replaced)
2K1 (AN and S is replaced)
3S (ANK is replaced)
4 (ANKS is replaced)

Input: ABC
Output:
ABC
AB1 
A1C 
A2 
1BC 
1B1 
2C 
3
Note: 11C is not valid because no two digits should be adjacent, 
2C is the correct one because AB is a substring, not A and B individually

The idea is to start with an empty string. At every step, we have two choices.

  1. Consider character as it is.
  2. Add character to count. If there is no count, then use 1.



👁 COULD NOT LOAD IMAGE

You can see how each character can either add up to the result as a character or as a digit. This further gives rise to 2^n abbreviations at the end where n is the length of string. 

Implementation:


Output
GFG
GF1
G1G
G2
1FG
1F1
2G
3

Time Complexity: O(2^N), Where N is the length of the input string. 
Auxiliary Space: O(2^N)

We can generate all these Abbreviations Iteratively too

Algorithm : 1. Let string of length n = 3 , str = "ABC" binary value between 0 to 7 will helps in deciding which character to be used or which character will be replaced If for let say n = 6 , binary = 110 consider each binary bit position as index bit = 1 means it will be replaced and 0 means we are not changing that index character and 0 means it remain as it is

Implementation:


Output
ANKS
1NKS
A1KS
2KS
AN1S
1N1S
A2S
3S
ANK1
1NK1
A1K1
2K1
AN2
1N2
A3
4

Time Complexity: O(2^N), Where N is the length of the input string. 
Auxiliary Space: O(N), for storing strings in a temporary string.

Comment
Article Tags: