Write a Python script that takes a string like '3a1b4j' and outputs 'aaabbjjj' by sorting the string and counting consecutive characters based on the numeric values.
1Times asked
Aug 2026Last seen
Aug 2026First seen
💡 Model Answer
The input format is a sequence of digit–letter pairs. We can parse the string, sort the pairs by letter, and then expand each letter according to its count:
python
import re
def expand(encoded: str) -> str:
# Find all digit-letter pairs
pairs = re.findall(r'(\d+)([a-zA-Z])', encoded)
# Convert to list of (letter, count)
items = [(letter, int(count)) for count, letter in pairs]
# Sort by letter
items.sort(key=lambda x: x[0])
# Build result
return ''.join(letter * count for letter, count in items)
print(expand('3a1b4j')) # aaabbjjjThe regular expression captures each number and the following letter. After sorting alphabetically, we multiply each letter by its numeric count to produce the expanded string. This solution runs in O(n log n) time due to the sort, where n is the number of distinct letters.
This answer was generated by AI for study purposes. Use it as a starting point — personalize it with your own experience.
🎤 Get questions like this answered in real-time
Assisting AI listens to your interview, captures questions live, and gives you instant AI-powered answers on a discreet on-screen overlay.
Get Assisting AI — Starts at ₹500