#3744
Medium Algorithms Find kth character in expanded string
String
57.1% acceptance
Mar 31, 2026
5
3
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.
Solution
Rust
Time O(n)
Space O(1)
impl Solution {
pub fn kth_character(s: String, k: i64) -> char {
let bytes = s.as_bytes();
let mut pos: i64 = 0;
let mut word_pos = 0i64;
for &b in bytes {
if b == b' ' {
if pos + 1 > k {
return ' ';
}
pos += 1;
word_pos = 0;
} else {
word_pos += 1;
if pos + word_pos > k {
return b as char;
}
pos += word_pos;
}
}
unreachable!()
}
}