[LeetCode] Find Kth Character in Expanded String

3744. Find Kth Character in Expanded String

You are given a string s consisting of one or more words separated by single spaces. Each word in s consists of lowercase English letters.

We obtain the expanded string t from s as follows:

  • For each word in s, repeat its first character once, then its second character twice, and so on.

For example, if s = "hello world", then t = "heelllllllooooo woorrrllllddddd".

You are also given an integer k, representing a valid index of the string t.

Return the kth character of the string t.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public:
char kthCharacter(string s, long long k) {
int len = 0;
k++;
for(auto& ch : s) {
if(isalpha(ch)) len++;
else len = 0;
k -= max(len, 1);
if(k <= 0) return ch;
}
return '#';
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2025/11/23/PS/LeetCode/find-kth-character-in-expanded-string/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.