Compressed String decoding for Kth character
Last Updated :
23 Jul, 2025
Given a compressed string composed of lowercase characters and numbers, the task is to decode the compressed string and to find out the character located at the Kth position in the uncompressed string, You can transform the string by following the rule that when you encounter a numeric value "n", repeat the preceding substring starting from index 0 'n' times
Examples:
Input: S = "ab2c3" K = 10
Output: "c"
Explanation:
- When traversing the string we got the first numeric value 2,
- here the preceding Substring =" ab "
- So "ab" is repeated twice, Now the string Will be "ababc3".
- The second numeric value we got is 3,
- Now, our preceding String is "ababc"
- So it will be repeated 3 times.
- Now the expanded string will be "ababc" + "ababc" + "ababc" = "ababcababcababc"
- 10th character is "c", so the output is "c".
Input: S = "z3a2s1" K = 12
Output: -1
Explanation: Expanded string will be "zzzazzzas" and have a length of 9, so output -1 (as the Kth index does not exist)
Naive Approach: The basic way to solve the problem is as follows:
The idea is to generate the expanded string and then find the Kth value of that string. To do so we will use a string "decoded" and insert the compressed string when encounter a string and if we encounter a digit then we will multiply the string the digit times and store it in "decoded" string .
Below is the implementation of the above idea:
C++
#include <iostream>
#include <string>
// Function to find the k-th character in a compressed string
char getKthCharacter(std::string compressedStr, int k) {
std::string expandedStr;
int curStrLen = 0;
for (char c : compressedStr) {
if (std::isdigit(c)) {
int repeat = c - '0'; // Extract the digit (repetition count)
// Repeat the current expanded string based on the repetition count
std::string repeated(expandedStr);
for (int i = 1; i < repeat; i++) {
expandedStr += repeated;
}
// Update the length based on repetition
curStrLen *= repeat;
} else {
// If the character is not a digit, simply append it to the expanded string
expandedStr += c;
// Increment the length
curStrLen++;
}
if (curStrLen >= k) {
return expandedStr[k - 1]; // If we have reached the desired position,
// return the k-th character
}
}
return '\0'; // If the position is out of bounds, return a default value
}
int main() {
std::string S = "ab2c3";
int K = 10;
char result = getKthCharacter(S, K);
if (result == '\0') {
std::cout << "Position is out of bounds." << std::endl;
} else {
std::cout << "The K-th character is: " << result << std::endl;
}
return 0;
}
Java
public class KthCharacterInCompressedString {
// Function to find the k-th character in a compressed string
public static char getKthCharacter(String compressedStr, int k) {
int curStrLen = 0; // To keep track of the length of the current expanded string
StringBuilder expandedStr = new StringBuilder(); // To store the expanded string
for (char c : compressedStr.toCharArray()) {
if (Character.isDigit(c)) {
int repeat = Character.getNumericValue(c); // Extract the digit (repetition count)
// Repeat the current expanded string based on the repetition count
expandedStr = new StringBuilder(expandedStr.toString().repeat(repeat));
// Update the length based on repetition
curStrLen *= repeat;
} else {
// If the character is not a digit, simply append it to the expanded string
expandedStr.append(c);
// Increment the length
curStrLen++;
}
if (curStrLen > k - 1) {
return expandedStr.charAt(k - 1); // If we have reached the desired
// position, return the k-th character
}
}
return '\0'; // If the position is out of bounds, return a
// default value (you can change this to -1 if needed).
}
public static void main(String[] args) {
String S = "ab2c3";
int K = 10;
char result = getKthCharacter(S, K);
if (result == '\0') {
System.out.println("Position is out of bounds.");
} else {
System.out.println("The K-th character is: " + result);
}
}
}
Python3
# Python3 implementation
# of above approach
def getKthCharacter(compressed_str, k):
# To keep track of the length of
# the current expanded string
cur_str_len = 0
# To store the expanded string
expanded_str = ""
for char in compressed_str:
# If the character is a digit
if char.isdigit():
repeat = int(char)
# Repeat the current
# expanded string
expanded_str = expanded_str * repeat
# Update the length
# based on repetition
cur_str_len = cur_str_len * repeat
else:
# If the character is not a digit,
# append it to the expanded string
expanded_str += char
# Increment the length
cur_str_len += 1
# If we have reached the
# desired position
if cur_str_len > k - 1:
# Return the k-th character
# from the expanded string
return expanded_str[k - 1]
# If the position is out of
# bounds, return -1
return -1
# Driver Code
S = "ab2c3"
K = 10
# Call the getKthCharacter function
# and print the result
print(getKthCharacter(S, K))
# This code is contributed by the Author
C#
using System;
class GFG
{
// Function to find the k-th character in a compressed string
static char GetKthCharacter(string compressedStr, int k)
{
string expandedStr = "";
int curStrLen = 0;
foreach (char c in compressedStr)
{
if (char.IsDigit(c))
{
int repeat = c - '0'; // Extract the digit (repetition count)
// Repeat the current expanded string based on the repetition count
string repeated = expandedStr;
for (int i = 1; i < repeat; i++)
{
expandedStr += repeated;
}
// Update the length based on repetition
curStrLen *= repeat;
}
else
{
// If the character is not a digit, simply append it to the expanded string
expandedStr += c;
// Increment the length
curStrLen++;
}
if (curStrLen >= k)
{
return expandedStr[k - 1]; // If we have reached the desired position,
// return the k-th character
}
}
return '\0'; // If the position is out of bounds, return a default value
}
static void Main()
{
string S = "ab2c3";
int K = 10;
char result = GetKthCharacter(S, K);
if (result == '\0')
{
Console.WriteLine("Position is out of bounds.");
}
else
{
Console.WriteLine($"The K-th character is: {result}");
}
}
}
JavaScript
// JavaScript implementation
// of above approach
function getKthCharacter(compressed_str, k) {
// To keep track of the length of
// the current expanded string
let cur_str_len = 0;
// To store the expanded string
let expanded_str = "";
for (let char of compressed_str) {
// If the character is a digit
if (!isNaN(char)) {
let repeat = parseInt(char);
// Repeat the current
// expanded string
expanded_str = expanded_str.repeat(repeat);
// Update the length
// based on repetition
cur_str_len = cur_str_len * repeat;
} else {
// If the character is not a digit,
// append it to the expanded string
expanded_str += char;
// Increment the length
cur_str_len += 1;
}
// If we have reached the
// desired position
if (cur_str_len > k - 1) {
// Return the k-th character
// from the expanded string
return expanded_str[k - 1];
}
}
// If the position is out of
// bounds, return -1
return -1;
}
// Driver Code
let S = "ab2c3";
let K = 10;
// Call the getKthCharacter function
// and print the result
console.log(getKthCharacter(S, K));
// This code is contributed by Tapesh(tapeshdua420)
Time Complexity: O(N),
Auxiliary Space: O(N), where N is the length of the expanded string.
Efficient Approach: To solve the problem without expanding the string using Recursion :
- Initialize a counter to keep track of the current position in the uncompressed string.
- Iterate through the compressed string's characters:
- If a character is a digit, calculate the potential new position in the uncompressed string without expanding the string.
- If the new position is greater than or equal to K, the Kth character lies within the repeated portion. Recurse on that portion with an adjusted K value.
- If the character is not a digit, increment the counter.
- If the counter reaches or exceeds k, return the current character as the k-th character.
- If the loop completes without finding the k-th character, return -1 to indicate an out-of-bounds position.
Below is the implementation of the above idea:
C++
// C++ code for the above approach:
#include <iostream>
using namespace std;
char getKthCharacterWithoutExpansion(string compressed_str,
int k)
{
// To keep track of the position
// in the uncompressed string
int count = 0;
for (char ch : compressed_str) {
if (isdigit(ch)) {
int repeat = ch - '0';
// Calculate the new position
int new_count = count * repeat;
// If new position exceeds k
if (new_count >= k) {
return getKthCharacterWithoutExpansion(
compressed_str, (k - 1) % count + 1);
}
count = new_count;
}
else {
count += 1;
}
// If we have reached the
// desired position
if (count >= k) {
// Return the current character
return ch;
}
}
// If the position is
// out of bounds
return 0;
}
// Driver code
int main()
{
// Input S and K
string S = "ab2c3";
int K = 15;
// Call the decoding function
// and print the result
char result = getKthCharacterWithoutExpansion(S, K);
(result == 0) ? cout << -1 : cout << result << endl;
return 0;
}
Java
//Java code for the above approach
public class GFG {
public static char getKthCharacterWithoutExpansion(String compressed_str, int k) {
// To keep track of the position in the uncompressed string
int count = 0;
for (char ch : compressed_str.toCharArray()) {
if (Character.isDigit(ch)) {
int repeat = ch - '0';
// Calculate the new position
int new_count = count * repeat;
// If new position exceeds k
if (new_count >= k) {
return getKthCharacterWithoutExpansion(compressed_str,
(k - 1) % count + 1);
}
count = new_count;
} else {
count += 1;
}
// If we have reached the desired position
if (count >= k) {
// Return the current character
return ch;
}
}
// If the position is out of bounds
return '\0';
}
public static void main(String[] args) {
// Input S and K
String S = "ab2c3";
int K = 15;
// Call the decoding function and print the result
char result = getKthCharacterWithoutExpansion(S, K);
if (result == '\0') {
System.out.println(-1);
} else {
System.out.println(result);
}
}
}
Python3
# Python3 implementation
# of above approach
def getKthCharacterWithoutExpansion(compressed_str, k):
# To keep track of the position
# in the uncompressed string
count = 0
for char in compressed_str:
if char.isdigit():
repeat = int(char)
# Calculate the new position
new_count = count * repeat
# If new position exceeds k
if new_count >= k:
return getKthCharacterWithoutExpansion(compressed_str, (k - 1) % count + 1)
count = new_count
else:
count += 1
# If we have reached the desired position
if count >= k:
# Return the current character
return char
return -1
# Driver Code
S = "ab2c3"
K = 15
# Call the getKthCharacter
# WithoutExpansion function
# And print the result
print(getKthCharacterWithoutExpansion(S, K))
# This code is contributed by the Author
C#
using System;
class Program
{
static void Main()
{
string S = "ab2c3";
int K = 15;
// Call the GetKthCharacterWithoutExpansion function
// And print the result
Console.WriteLine(GetKthCharacterWithoutExpansion(S, K));
}
static char GetKthCharacterWithoutExpansion(string compressedStr, int k)
{
// To keep track of the position
// in the uncompressed string
int count = 0;
foreach (char c in compressedStr)
{
if (char.IsDigit(c))
{
int repeat = int.Parse(c.ToString());
// Calculate the new position
int newCount = count * repeat;
// If new position exceeds k
if (newCount >= k)
{
return GetKthCharacterWithoutExpansion(compressedStr, (k - 1) % count + 1);
}
count = newCount;
}
else
{
count++;
}
// If we have reached the desired position
if (count >= k)
{
// Return the current character
return c;
}
}
return '\0';
}
}
JavaScript
function main() {
const S = "ab2c3";
const K = 15;
// Call the GetKthCharacterWithoutExpansion function
// And print the result
console.log(GetKthCharacterWithoutExpansion(S, K));
}
function GetKthCharacterWithoutExpansion(compressedStr, k) {
// To keep track of the position in the uncompressed string
let count = 0;
for (let i = 0; i < compressedStr.length; i++) {
const c = compressedStr.charAt(i);
if (!isNaN(parseInt(c))) {
const repeat = parseInt(c);
// Calculate the new position
const newCount = count * repeat;
// If new position exceeds k
if (newCount >= k) {
return GetKthCharacterWithoutExpansion(compressedStr, (k - 1) % count + 1);
}
count = newCount;
} else {
count++;
}
// If we have reached the desired position
if (count >= k) {
// Return the current character
return c;
}
}
return '\0';
}
main(); // Call the main function
Time Complexity: O(N), where N is the length of the string.
Auxiliary Space: O(1).
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem