Open In App

Kth character after replacing each character of String by its frequency exactly X times

Last Updated : 16 Feb, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a string S consisting of N digits from [1, 9] and a positive integer K and X. Every day each character of the string is replaced by its frequency and value. The task is to find the Kth character of the string after X days.

Examples:

Input: S = “1214”, K = 10, X = 3
Output: 4
Explanation:
1st day = “12214444”
2nd day = “1222214444444444444444”
3rd day = “122222222444444444444444444444444444444444444444444444444” 
So, 10th character after 3rd day is 4.

Input: S =”123″, K = 6, X = 2 
Output: 3

Naive Approach: The simplest approach to solve the problem is to create the string by appending the digits in the string digitX times and finding the Kth character of the string.

C++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the Kth character
// after X days
char FindKthChar(string str, long long K, int X)
{
    string s = str;
 
    for (int i = 0; i < X; i++) {
        string res = "";
        for (int j = 0; j < s.size(); j++) {
            int count = s[j] - '0';
            while (count--) {
                res += s[j];
            }
        }
        s = res;
    }
 
    return s[K - 1];
}
 
// Driver Code
int main()
{
    // Given Input
    string str = "1214";
    long long K = 10;
    int X = 3;
 
    // Function Call
    char ans = FindKthChar(str, K, X);
    cout << ans << "\n";
    return 0;
}


Java




import java.util.*;
 
class Gfg {
    // Function to find the Kth character
    // after X days
    static char findKthChar(String str, long K, int X)
    {
        String s = str;
 
        for (int i = 0; i < X; i++) {
            String res = "";
            for (int j = 0; j < s.length(); j++) {
                int count = s.charAt(j) - '0';
                while (count-- > 0) {
                    res += s.charAt(j);
                }
            }
            s = res;
        }
 
        return s.charAt((int)(K - 1));
    }
 
    public static void main(String[] args)
    {
        // Given Input
        String str = "1214";
        long K = 10;
        int X = 3;
 
        // Function Call
        char ans = findKthChar(str, K, X);
        System.out.println(ans);
    }
}


Python3




    # Function to find the Kth character
    # after X days
    def FindKthChar(str, K, X):
    s = str
    for i in range(X):
        res = ""
        for j in range(len(s)):
            count = int(s[j])
            res += s[j] * count
        s = res
    return s[K - 1]
 
# Given Input
str = "1214"
K = 10
X = 3
 
# Function Call
ans = FindKthChar(str, K, X)
print(ans)
 
#This code is contributed by shivamsharma215


C#




using System;
 
class Gfg
{
 
  // Function to find the Kth character
  // after X days
  static char findKthChar(string str, long K, int X)
  {
    string s = str;
 
    for (int i = 0; i < X; i++) {
      string res = "";
      for (int j = 0; j < s.Length; j++) {
        int count = s[j] - '0';
        while (count-- > 0) {
          res += s[j];
        }
      }
      s = res;
    }
 
    return s[(int)(K - 1)];
  }
 
  public static void Main(string[] args)
  {
    // Given Input
    string str = "1214";
    long K = 10;
    int X = 3;
 
    // Function Call
    char ans = findKthChar(str, K, X);
    Console.WriteLine(ans);
  }
}
 
// This code is contributed by divya_p123.


Javascript




// JavaScript program for the above approach
// function to find the kth character
// after x days
function FindKthChar(str, K, X){
    let s = str;
    for(let i = 0; i<X; i++){
        let res = "";
        for(let j = 0; j<s.length; j++){
            let count = s[j] - '0';
            while(count--){
                res += s[j];
            }
        }
        s = res;
    }
    return s[K-1];
}
 
// driver code
let str = "1214";
let K = 10;
let X = 3;
 
// function call
let ans = FindKthChar(str, K, X);
console.log(ans);
 
// THIS CODE IS CONTRIBUTED BY YASH AGARWAL(YASHAGARWAL2852002)


Output

1

Time Complexity: O(?digit[i]X) for i in range [0, N-1]
Auxiliary Space: O(?digit[i]X) for i in range [0, N-1]

Efficient Approach: The above approach can be optimized further by instead of creating a string add digitX to the sum and check if sum > K. Follow the steps below to solve the problem:

  • Initialize a variable, say sum that stores the sum of the character of the string after X days.
  • Initialize a variable, say ans that stores the Kth characters after X days.
  • Iterate in the range [0, N-1] and perform the following steps:
    • Initialize a variable say range as (S[i] – ‘0’)X and add it to the variable sum.
    • If sum>=K, return S, modify ans as S[i], and terminate the loop.
  • Print the value of ans as the answer.

Below is the implementation of the above approach:

C++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the Kth character
// after X days
char FindKthChar(string str, long long K, int X)
{
 
    // Variable to store the KthChar
    char ans;
    int sum = 0;
 
    // Traverse the string
    for (int i = 0; i < str.length(); i++) {
 
        // Convert char into int
        int digit = str[i] - '0';
 
        // Calculate characters
        int range = pow(digit, X);
        sum += range;
 
        // If K is less than sum
        // than ans = str[i]
        if (K <= sum) {
            ans = str[i];
            break;
        }
    }
    // Return answer
    return ans;
}
 
// Driver Code
int main()
{
    // Given Input
    string str = "123";
    long long K = 9;
    int X = 3;
 
    // Function Call
    char ans = FindKthChar(str, K, X);
    cout << ans << "\n";
    return 0;
}


Java




// Java program for the above approach
class GFG{
 
// Function to find the Kth character
// after X days
static char FindKthChar(String str, int K, int X)
{
     
    // Variable to store the KthChar
    char ans = ' ';
    int sum = 0;
 
    // Traverse the string
    for(int i = 0; i < str.length(); i++)
    {
         
        // Convert char into int
        int digit = (int)str.charAt(i) - 48;
 
        // Calculate characters
        int range = (int)Math.pow(digit, X);
        sum += range;
 
        // If K is less than sum
        // than ans = str[i]
        if (K <= sum)
        {
            ans = str.charAt(i);
            break;
        }
    }
 
    // Return answer
    return ans;
}
 
// Driver code
public static void main(String[] args)
{
     
    // Given Input
    String str = "123";
    int K = 9;
    int X = 3;
 
    // Function Call
    char ans = FindKthChar(str, K, X);
    System.out.println(ans);
}
}
 
// This code is contributed by abhinavjain194


Python3




# Python3 program for the above approach
import math
 
# Function to find the Kth character
# after X days
def FindKthChar(Str, K, X):
      
    # Variable to store the KthChar
    ans = ' '
    Sum = 0
  
    # Traverse the string
    for i in range(len(Str)):
       
        # Convert char into int
        digit = ord(Str[i]) - 48
  
        # Calculate characters
        Range = int(math.pow(digit, X))
        Sum += Range
  
        # If K is less than sum
        # than ans = str[i]
        if (K <= Sum):
            ans = Str[i]
            break
      
    # Return answer
    return ans
 
# Given Input
Str = "123"
K = 9
X = 3
 
# Function Call
ans = FindKthChar(Str, K, X)
print(ans)
 
# This code is contributed by divyeshrabadiya07.


C#




// C# program for the above approach
using System;
using System.Collections.Generic;
 
class GFG{
 
// Function to find the Kth character
// after X days
static char FindKthChar(string str, int K, int X)
{
     
    // Variable to store the KthChar
    char ans = ' ';
    int sum = 0;
 
    // Traverse the string
    for(int i = 0; i < str.Length; i++)
    {
         
        // Convert char into int
        int digit = (int)str[i] - 48;
 
        // Calculate characters
        int range = (int)Math.Pow(digit, X);
        sum += range;
 
        // If K is less than sum
        // than ans = str[i]
        if (K <= sum)
        {
            ans = str[i];
            break;
        }
    }
     
    // Return answer
    return ans;
}
 
// Driver Code
public static void Main()
{
     
    // Given Input
    string str = "123";
    int K = 9;
    int X = 3;
 
    // Function Call
    char ans = FindKthChar(str, K, X);
    Console.Write(ans);
}
}
 
// This code is contributed by SURENDRA_GANGWAR


Javascript




<script>
// javascript program for the above approach   
// Function to find the Kth character
    // after X days
     function FindKthChar( str , K , X) {
 
        // Variable to store the KthChar
        var ans = "";
        var sum = 0;
 
        // Traverse the string
        for (i = 0; i < str.length; i++) {
 
            // Convert char into int
            var digit = parseInt( str[i]);
 
            // Calculate characters
            var range = parseInt( Math.pow(digit, X));
            sum += range;
 
            // If K is less than sum
            // than ans = str[i]
            if (K <= sum) {
                ans = str[i];
                break;
            }
        }
 
        // Return answer
        return ans;
    }
 
    // Driver code
     
 
        // Given Input
        var str = "123";
        var K = 9;
        var X = 3;
 
        // Function Call
        var ans = FindKthChar(str, K, X);
        document.write(ans);
 
// This code contributed by gauravrajput1
</script>


Output

2

Time Complexity: O(N), since there is only one loop to carry out the operations the overall complexity turns out to be O(N)
Auxiliary Space: O(1), since there is no extra array or data structure used, it takes constant space.



Similar Reads

Modify string by replacing characters by alphabets whose distance from that character is equal to its frequency
Given a string S consisting of N lowercase alphabets, the task is to modify the string S by replacing each character with the alphabet whose circular distance from the character is equal to the frequency of the character in S. Examples: Input: S = "geeks"Output: hggltExplanation: The following modifications are done on the string S: The frequency o
7 min read
Check if frequency of character in one string is a factor or multiple of frequency of same character in other string
Given two strings, the task is to check whether the frequencies of a character(for each character) in one string are multiple or a factor in another string. If it is, then output "YES", otherwise output "NO". Examples: Input: s1 = "aabccd", s2 = "bbbaaaacc" Output: YES Frequency of 'a' in s1 and s2 are 2 and 4 respectively, and 2 is a factor of 4 F
6 min read
Printing frequency of each character just after its consecutive occurrences
Given a string in such a way that every character occurs in a repeated manner. Your task is to print the string by inserting the frequency of each unique character after it and also eliminating all repeated characters. Examples: Input: GeeeEEKKKssOutput: G1e3E2K3s2 Input: ccccOddEEEOutput: c4O1d2E3 Recommended PracticeEasy stringTry It!One approach
3 min read
Length of String formed by repeating each character in range [L, R] of given string its lexicographic value times
Given a string S of length N, and a range [L, R] (1 &lt;= L, R &lt;= N). The task is to find the length of string formed by repeating each character in the range [L, R], to its lexicographical value times. Examples: Input: s = "cbbde", l = 2, r = 5Output: 13Explanation: Resultant String is formed after repeating each character in range [2, 5] as sh
9 min read
Find character at Kth index by appending S1 (M) times and S2 (M+1) times
Given two strings, S1 and S2 and an integer K.A string str can be made by performing the following operations: Take an Empty String InitiallyAppend S1 one timesAppend S2 two timesAppend S1 three timesAppend S2 four timesAppend S1 five timesAppend S2 six timesYou can keep building this string until it reaches K The task is to find the character at t
15 min read
Generate a number such that the frequency of each digit is digit times the frequency in given number
Given a number N containing digits from 1 to 9 only. The task is to generate a new number using the number N such that the frequency of each digit in the new number is equal to the frequency of that digit in N multiplied by the digit itself.Note: The digits in the new number must be in increasing order.Examples: Input : N = 312 Output : 122333 Expl
8 min read
Lexicographically Kth-smallest string having 'a' X times and 'b' Y times
Given three non-negative integers, X, Y, and K, the task is to find the Kth smallest lexicographical string having X occurrences of character 'a' and Y occurrences of character 'b'. Examples: Input: X = 2, Y = 3, K = 3Output: abbabExplanation: First lexicographical smallest string = "aabbb".Second lexicographical smallest string = "ababb".Third lex
20 min read
Count distinct strings possible by replacing each character by its Morse code
Given an array of strings arr[], the task is to count the number of distinct strings that can be generated from the given array by replacing each character of the strings by its Morse code. Below is the Morse code of all the lowercase alphabets: Examples: Input: arr[] = {"gig", "zeg", "gin", "msn"}Output: 2Explanation: Replacing each character of t
10 min read
Make the string lexicographically smallest and non palindromic by replacing exactly one character
Given a palindromic string str containing only lowercase letters, the task is to print the lexicographically smallest string, by replacing exactly one character, such the string is not a palindrome. Examples: Input: str = "abccba" Output: "aaccba" Explanation: Lexicographically smallest non-palindromic string possible is "aaccba", here we have repl
5 min read
Maximum length prefix such that frequency of each character is atmost number of characters with minimum frequency
Given a string S, the task is to find the prefix of string S with the maximum possible length such that frequency of each character in the prefix is at most the number of characters in S with minimum frequency. Examples: Input: S = 'aabcdaab' Output: aabcd Explanation: Frequency of characters in the given string - {a: 4, b: 2, c: 1, d: 1} Minimum f
8 min read
Practice Tags :