Skip to content
Related Articles

Related Articles

Improve Article

Find character at Kth index by appending S1 (M) times and S2 (M+1) times

  • Difficulty Level : Hard
  • Last Updated : 16 Sep, 2021

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 Initially
  • Append S1 one times
  • Append S2 two times
  • Append S1 three times
  • Append S2 four times
  • Append S1 five times
  • Append S2 six times
  • You can keep building this string until it reaches K

The task is to find the character at the kth position in the new string str.

Input: S1 = “a”,  S2 = “bc”, k = 4
Output: b
Explanation: s3 = “a” + “bcbc” +”aaa” + “bcbcbcbc” ==>  abcbcaaabcbcbcbc. so the character on the 4th index is ‘b’

Input: S1 = “Geeks”, S2 = “for”, k = 3
Output: e
Explanation: s3 = “Geeks” + “for” + “GeeksGeeks” ==> GeeksforGeeksGeeks. so the character at 3rd position is ‘e’.

 

Approach: The simple solution would be to keep appending strings in the string str, until the index reaches k. Then, return the character to the index k.



Below is the implementation of the above approach.

C++




// C++ program to solve the above approach
#include<bits/stdc++.h>
using namespace std;
 
char KthCharacter(string s, string t, long k)
{
 
  // initializing first and second variable
  // as to store how many string 's'
  // and string 't' will be appended
  long f = 1;
  long ss = 2;
  string tmp = "";
 
  // storing tmp length
  int len = tmp.length();
 
  // if length of string tmp is greater than k, then
  // we have reached our destination string now we can
  // return character at index k
  while (len < k) {
 
    long tf = f;
    long ts = ss;
 
    // appending s to tmp, f times
    while (tf-- != 0) {
      tmp += s;
    }
 
    // appending t to tmp, s times
    while (ts-- != 0) {
      tmp += t;
    }
    f += 2;
    ss += 2;
    len = tmp.length();
  }
 
  // extracting output character
  char output = tmp[k - 1];
  return output;
}
 
// Driver code
int main()
{
  string S1 = "a", S2 = "bc";
  int k = 4;
  char ans = KthCharacter(S1, S2, k);
  cout<<ans;
}
 
// This code is contributed by ipg2016107.

Java




// Java program to solve the above approach
 
import java.io.*;
 
class GFG {
    static char KthCharacter(String s, String t, long k)
    {
        // initializing first and second variable
        // as to store how many string 's'
        // and string 't' will be appended
        long f = 1;
        long ss = 2;
        String tmp = "";
 
        // storing tmp length
        int len = tmp.length();
 
        // if length of string tmp is greater than k, then
        // we have reached our destination string now we can
        // return character at index k
        while (len < k) {
 
            long tf = f;
            long ts = ss;
 
            // appending s to tmp, f times
            while (tf-- != 0) {
                tmp += s;
            }
 
            // appending t to tmp, s times
            while (ts-- != 0) {
                tmp += t;
            }
            f += 2;
            ss += 2;
            len = tmp.length();
        }
 
        // extracting output character
        char output = tmp.charAt((int)k - 1);
        return output;
    }
 
    // Driver code
    public static void main(String[] args)
    {
 
        String S1 = "a", S2 = "bc";
        int k = 4;
        char ans = KthCharacter(S1, S2, k);
        System.out.println(ans);
    }
}

Python3




# Python program to solve the above approach
def KthCharacter(s, t, k):
   
    # initializing first and second variable
    # as to store how many string 's'
    # and string 't' will be appended
    f = 1
    ss = 2
    tmp = ""
     
    # storing tmp length
    lenn = len(tmp)
     
    # if length of string tmp is greater than k, then
    # we have reached our destination string now we can
    # return character at index k
    while (lenn < k):
        tf = f
        ts = ss
         
        # appending s to tmp, f times
        while (tf != 0):
            tf -=1
            tmp += s
        # appending t to tmp, s times
        while (ts != 0) :
            ts -=1
            tmp += t
         
        f += 2
        ss += 2
        lenn = len(tmp)
     
    # extracting output character
    output = tmp[k - 1]
    return output
     
# Driver code
S1 = "a"
S2 = "bc"
k = 4
ans = KthCharacter(S1, S2, k)
print(ans)
 
# This code is contributed by shivanisinghss2110

C#




// C# program to solve the above approach
using System;
 
class GFG {
    static char KthCharacter(string s, string t, long k)
    {
        // initializing first and second variable
        // as to store how many string 's'
        // and string 't' will be appended
        long f = 1;
        long ss = 2;
        string tmp = "";
 
        // storing tmp length
        int len = tmp.Length;
 
        // if length of string tmp is greater than k, then
        // we have reached our destination string now we can
        // return character at index k
        while (len < k) {
 
            long tf = f;
            long ts = ss;
 
            // appending s to tmp, f times
            while (tf-- != 0) {
                tmp += s;
            }
 
            // appending t to tmp, s times
            while (ts-- != 0) {
                tmp += t;
            }
            f += 2;
            ss += 2;
            len = tmp.Length;
        }
 
        // extracting output character
        char output = tmp[(int)k - 1];
        return output;
    }
 
    // Driver code
    public static void Main(string[] args)
    {
 
        string S1 = "a", S2 = "bc";
        int k = 4;
        char ans = KthCharacter(S1, S2, k);
        Console.Write(ans);
    }
}
 
// This code is contributed by ukasp.

Javascript




<script>
 
// JavaScript program to solve the above approach
 
function KthCharacter(s, t, k) {
  // initializing first and second variable
  // as to store how many string 's'
  // and string 't' will be appended
  let f = 1;
  let ss = 2;
  let tmp = "";
 
  // storing tmp length
  let len = tmp.length;
 
  // if length of string tmp is greater than k, then
  // we have reached our destination string now we can
  // return character at index k
  while (len < k) {
    let tf = f;
    let ts = ss;
 
    // appending s to tmp, f times
    while (tf-- != 0) {
      tmp += s;
    }
 
    // appending t to tmp, s times
    while (ts-- != 0) {
      tmp += t;
    }
    f += 2;
    ss += 2;
    len = tmp.length;
  }
 
  // extracting output character
  let output = tmp[k - 1];
  return output;
}
 
// Driver code
 
let S1 = "a",
  S2 = "bc";
let k = 4;
let ans = KthCharacter(S1, S2, k);
document.write(ans);
 
</script>
Output
b

Time Complexity: O(K)
Auxiliary Space: O(K)

Efficient Approach: Since K is a long type, and the size of a string can only get up to the max possible value of int, this code cannot be used and won’t pass in every case.  Rather than appending the string s and t to temp, subtract the length of s and length of t from K, so that the range is always within int type. Follow the steps below to solve the problem:

  • Initialize two variables n and m as the lengths of the respective strings s and t.
  • Initialize two variables, first and second as 1 and 2 to keep the count of time strings s and t have to be appended.
  • Initialize the variable output to store the character at kth position in the new string.
  • Iterate in a while loop till k is greater than 0:
    • If k is greater than first*n, then, subtract that from k and increase the value of first by 2.
    • If k is greater than second*m, then, subtract that from k and increase the value of second by 2.
    • Else(k is less than second*m), then the character from the second string t will be the answer as the string t will be appended second times and k will be in this range of positions.
    • Initialize the variable ind as the modulus of k%m and the character at ind position in the string t will be the answer. Store the character in the variable output.
    • Else(k is less than first*n), then the character from the second string s will be the answer as the string s will be appended first times and k will be in this range of positions.
    • Initialize the variable ind as the modulus of k%n and the character at ind position in the string s will be the answer. Store the character in the variable output.
  • After performing the above steps, return the value of output as the answer.

Below is the implementation of the above approach.

Java




// Java program to solve the above approach
 
import java.io.*;
 
class GFG {
    static char KthCharacter(String s, String t, long k)
    {
        // storing length
        long n = s.length();
        long m = t.length();
 
        // variables for temporary strings of s and t
        long first = 1;
        long second = 2;
 
        // final output variable
        char output = '?';
        while (k > 0) {
 
            // if k is greater than even after adding string
            // 's' 'first' times  (let's call it x) we'll
            // subtract x from k
            if (k > first * n) {
 
                long x = first * n;
                k = k - x;
 
                // incrementing first by 2, as said in
                // problem statement
                first = first + 2;
 
                // if k is greater than even after adding
                // string 't' 'second' times  (let's call it
                // y) we'll subtract y from k
                if (k > second * m) {
 
                    long y = second * m;
                    k = k - y;
 
                    // incrementing second by two as said in
                    // problem statement
                    second = second + 2;
                }
 
                // if k is smaller than y, then the
                // character
                // will be at position k%m.
                else {
 
                    // returning character at k index
                    long ind = k % m;
                    ind--;
                    if (ind < 0)
                        ind = m - 1;
                    output = t.charAt((int)ind);
                    break;
                }
            }
 
            // if k is smaller than x, then the character
            // is at position k%n
            else {
 
                // returning character at k index
                long ind = k % n;
                ind--;
                if (ind < 0)
                    ind = n - 1;
                output = s.charAt((int)ind);
                break;
            }
        }
        return output;
    }
 
    // Driver code
    public static void main(String[] args)
    {
 
        String S1 = "a", S2 = "bc";
        int k = 4;
        char ans = KthCharacter(S1, S2, k);
        System.out.println(ans);
    }
}

Python3




# Python program to solve the above approach
def KthCharacter(s, t, k):
     
        # storing length
        n = len(s)
        m = len(t)
 
        # variables for temporary strings of s and t
        first = 1
        second = 2
 
        # final output variable
        output = '?'
        while (k > 0):
 
            # if k is greater than even after adding string
            # 's' 'first' times  (let's call it x) we'll
            # subtract x from k
            if (k > first * n):
                x = first * n
                k = k - x
 
                # incrementing first by 2, as said in
                # problem statement
                first = first + 2
 
                # if k is greater than even after adding
                # string 't' 'second' times  (let's call it
                # y) we'll subtract y from k
                if (k > second * m):
 
                    y = second * m
                    k = k - y
 
                    # incrementing second by two as said in
                    # problem statement
                    second = second + 2
                 
                # if k is smaller than y, then the
                # character
                # will be at position k%m.
                else:
 
                    # returning character at k index
                    ind = k % m
                    ind-=1
                    if (ind < 0):
                        ind = m - 1
                    output = t[ind]
                    break
                 
            # if k is smaller than x, then the character
            # is at position k%n
            else:
 
                # returning character at k index
                ind = k % n
                ind-=1
                if (ind < 0):
                    ind = n - 1
                output = s[ind]
                break
             
        return output
     
# Driver code
S1 = "a"
S2 = "bc"
k = 4
ans = KthCharacter(S1, S2, k)
print(ans)
     
# This code is contributed by shivanisinghss2110

C#




// C# program to solve the above approach
using System;
 
public class GFG {
    static char Kthchar(String s, String t, long k)
    {
       
        // storing length
        long n = s.Length;
        long m = t.Length;
 
        // variables for temporary strings of s and t
        long first = 1;
        long second = 2;
 
        // readonly output variable
        char output = '?';
        while (k > 0) {
 
            // if k is greater than even after adding string
            // 's' 'first' times  (let's call it x) we'll
            // subtract x from k
            if (k > first * n) {
 
                long x = first * n;
                k = k - x;
 
                // incrementing first by 2, as said in
                // problem statement
                first = first + 2;
 
                // if k is greater than even after adding
                // string 't' 'second' times  (let's call it
                // y) we'll subtract y from k
                if (k > second * m) {
 
                    long y = second * m;
                    k = k - y;
 
                    // incrementing second by two as said in
                    // problem statement
                    second = second + 2;
                }
 
                // if k is smaller than y, then the
                // character
                // will be at position k%m.
                else {
 
                    // returning character at k index
                    long ind = k % m;
                    ind--;
                    if (ind < 0)
                        ind = m - 1;
                    output = t[(int)(ind)];
                    break;
                }
            }
 
            // if k is smaller than x, then the character
            // is at position k%n
            else {
 
                // returning character at k index
                long ind = k % n;
                ind--;
                if (ind < 0)
                    ind = n - 1;
                output = s[(int)(ind)];
                break;
            }
        }
        return output;
    }
 
    // Driver code
    public static void Main(String[] args)
    {
 
        String S1 = "a", S2 = "bc";
        int k = 4;
        char ans = Kthchar(S1, S2, k);
        Console.WriteLine(ans);
    }
}
 
// This code is contributed by Amit Katiyar

Javascript




<script>
 
// javascript program to solve the above approach
 
   function KthCharacter(s, t , k)
    {
        // storing length
        var n = s.length;
        var m = t.length;
 
        // variables for temporary strings of s and t
        var first = 1;
        var second = 2;
 
        // final output variable
        var output = '?';
        while (k > 0) {
 
            // if k is greater than even after adding string
            // 's' 'first' times  (let's call it x) we'll
            // subtract x from k
            if (k > first * n) {
 
                var x = first * n;
                k = k - x;
 
                // incrementing first by 2, as said in
                // problem statement
                first = first + 2;
 
                // if k is greater than even after adding
                // string 't' 'second' times  (let's call it
                // y) we'll subtract y from k
                if (k > second * m) {
 
                    var y = second * m;
                    k = k - y;
 
                    // incrementing second by two as said in
                    // problem statement
                    second = second + 2;
                }
 
                // if k is smaller than y, then the
                // character
                // will be at position k%m.
                else {
 
                    // returning character at k index
                    var ind = k % m;
                    ind--;
                    if (ind < 0)
                        ind = m - 1;
                    output = t.charAt(parseInt(ind));
                    break;
                }
            }
 
            // if k is smaller than x, then the character
            // is at position k%n
            else {
 
                // returning character at k index
                var ind = k % n;
                ind--;
                if (ind < 0)
                    ind = n - 1;
                output = s.charAt(parseInt(ind));
                break;
            }
        }
        return output;
    }
 
    // Driver code
     
 
    var S1 = "a", S2 = "bc";
    var k = 4;
    var ans = KthCharacter(S1, S2, k);
    document.write(ans);
 
// This code contributed by Princi Singh
</script>
Output
b

Time Complexity: O(K)
Auxiliary Space: O(1)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.




My Personal Notes arrow_drop_up
Recommended Articles
Page :