Find Kth Character in Expanded String

You are given a string s consisting of one or more words separated by a single space.

Each word contains only lowercase English letters.

We construct a new string t from s using the following process:

For every word in s,

  • repeat its first character once,
  • repeat its second character twice,
  • repeat its third character three times,
  • and so on.

Words remain separated by a single space in t.

You are also given an integer k, representing a valid 0-based index in the expanded string t.

Return the character at index k in t.

Example 1:

Input: s = "abc", k = 3

Output: "c"

Explanation:

Expanded string: t = "abbccc"

Indexing:

  • t[0] = 'a'
  • t[1] = 'b'
  • t[2] = 'b'
  • t[3] = 'c'

So, the answer is "c".

Example 2:

Input: s = "cat dog", k = 5

Output: "t"

Explanation:

  • For "cat" → "caattt"
  • For "dog" → "dooggg"

Expanded string: t = "caattt dooggg"

At index 5, the character is 't'.

Now Your Turn!

Pick the correct output for the given input

Input: s = "code", k = 6

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • 1 ≤ s.length ≤ 105
  • s contains lowercase English letters ('a' to 'z') and single spaces ' '
  • There are no leading or trailing spaces in s.
  • All words in s are separated by exactly one space.
  • 0 ≤ k < t.length
  • k is guaranteed to be a valid index in the expanded string t.

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

0
class Solution {
public:
char kthCharacter(string s, long long k) {
// Your code goes here
}
};
Test Case

Input:

K
S