Compressed String decoding for Kth character
Last Updated :
13 Dec, 2023
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>
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' ;
std::string repeated(expandedStr);
for ( int i = 1; i < repeat; i++) {
expandedStr += repeated;
}
curStrLen *= repeat;
} else {
expandedStr += c;
curStrLen++;
}
if (curStrLen >= k) {
return expandedStr[k - 1];
}
}
return '\0' ;
}
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 {
public static char getKthCharacter(String compressedStr, int k) {
int curStrLen = 0 ;
StringBuilder expandedStr = new StringBuilder();
for ( char c : compressedStr.toCharArray()) {
if (Character.isDigit(c)) {
int repeat = Character.getNumericValue(c);
expandedStr = new StringBuilder(expandedStr.toString().repeat(repeat));
curStrLen *= repeat;
} else {
expandedStr.append(c);
curStrLen++;
}
if (curStrLen > k - 1 ) {
return expandedStr.charAt(k - 1 );
}
}
return '\0' ;
}
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
def getKthCharacter(compressed_str, k):
cur_str_len = 0
expanded_str = ""
for char in compressed_str:
if char.isdigit():
repeat = int (char)
expanded_str = expanded_str * repeat
cur_str_len = cur_str_len * repeat
else :
expanded_str + = char
cur_str_len + = 1
if cur_str_len > k - 1 :
return expanded_str[k - 1 ]
return - 1
S = "ab2c3"
K = 10
print (getKthCharacter(S, K))
|
C#
using System;
class GFG
{
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' ;
string repeated = expandedStr;
for ( int i = 1; i < repeat; i++)
{
expandedStr += repeated;
}
curStrLen *= repeat;
}
else
{
expandedStr += c;
curStrLen++;
}
if (curStrLen >= k)
{
return expandedStr[k - 1];
}
}
return '\0' ;
}
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
function getKthCharacter(compressed_str, k) {
let cur_str_len = 0;
let expanded_str = "" ;
for (let char of compressed_str) {
if (!isNaN(char)) {
let repeat = parseInt(char);
expanded_str = expanded_str.repeat(repeat);
cur_str_len = cur_str_len * repeat;
} else {
expanded_str += char;
cur_str_len += 1;
}
if (cur_str_len > k - 1) {
return expanded_str[k - 1];
}
}
return -1;
}
let S = "ab2c3" ;
let K = 10;
console.log(getKthCharacter(S, K));
|
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++
#include <iostream>
using namespace std;
char getKthCharacterWithoutExpansion(string compressed_str,
int k)
{
int count = 0;
for ( char ch : compressed_str) {
if ( isdigit (ch)) {
int repeat = ch - '0' ;
int new_count = count * repeat;
if (new_count >= k) {
return getKthCharacterWithoutExpansion(
compressed_str, (k - 1) % count + 1);
}
count = new_count;
}
else {
count += 1;
}
if (count >= k) {
return ch;
}
}
return 0;
}
int main()
{
string S = "ab2c3";
int K = 15;
char result = getKthCharacterWithoutExpansion(S, K);
(result == 0) ? cout << -1 : cout << result << endl;
return 0;
}
|
Java
public class GFG {
public static char getKthCharacterWithoutExpansion(String compressed_str, int k) {
int count = 0 ;
for ( char ch : compressed_str.toCharArray()) {
if (Character.isDigit(ch)) {
int repeat = ch - '0' ;
int new_count = count * repeat;
if (new_count >= k) {
return getKthCharacterWithoutExpansion(compressed_str,
(k - 1 ) % count + 1 );
}
count = new_count;
} else {
count += 1 ;
}
if (count >= k) {
return ch;
}
}
return '\0' ;
}
public static void main(String[] args) {
String S = "ab2c3" ;
int K = 15 ;
char result = getKthCharacterWithoutExpansion(S, K);
if (result == '\0' ) {
System.out.println(- 1 );
} else {
System.out.println(result);
}
}
}
|
Python3
def getKthCharacterWithoutExpansion(compressed_str, k):
count = 0
for char in compressed_str:
if char.isdigit():
repeat = int (char)
new_count = count * repeat
if new_count > = k:
return getKthCharacterWithoutExpansion(compressed_str, (k - 1 ) % count + 1 )
count = new_count
else :
count + = 1
if count > = k:
return char
return - 1
S = "ab2c3"
K = 15
print (getKthCharacterWithoutExpansion(S, K))
|
C#
using System;
class Program
{
static void Main()
{
string S = "ab2c3" ;
int K = 15;
Console.WriteLine(GetKthCharacterWithoutExpansion(S, K));
}
static char GetKthCharacterWithoutExpansion( string compressedStr, int k)
{
int count = 0;
foreach ( char c in compressedStr)
{
if ( char .IsDigit(c))
{
int repeat = int .Parse(c.ToString());
int newCount = count * repeat;
if (newCount >= k)
{
return GetKthCharacterWithoutExpansion(compressedStr, (k - 1) % count + 1);
}
count = newCount;
}
else
{
count++;
}
if (count >= k)
{
return c;
}
}
return '\0' ;
}
}
|
Javascript
function main() {
const S = "ab2c3" ;
const K = 15;
console.log(GetKthCharacterWithoutExpansion(S, K));
}
function GetKthCharacterWithoutExpansion(compressedStr, k) {
let count = 0;
for (let i = 0; i < compressedStr.length; i++) {
const c = compressedStr.charAt(i);
if (!isNaN(parseInt(c))) {
const repeat = parseInt(c);
const newCount = count * repeat;
if (newCount >= k) {
return GetKthCharacterWithoutExpansion(compressedStr, (k - 1) % count + 1);
}
count = newCount;
} else {
count++;
}
if (count >= k) {
return c;
}
}
return '\0' ;
}
main();
|
Time Complexity: O(N), where N is the length of the string.
Auxiliary Space: O(1).
Share your thoughts in the comments
Please Login to comment...