Find Kth Character in Expanded String Problem
#3744
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3744.
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 k^th character of the string t.
Example 1:
Input: s = "hello world", k = 0
Output: "h"
Explanation:
t = "heelllllllooooo woorrrllllddddd". Therefore, the answer is t[0] = "h".
Example 2:
Input: s = "hello world", k = 15
Output: " "
Explanation:
t = "heelllllllooooo woorrrllllddddd". Therefore, the answer is t[15] = " ".
Constraints:
1 <= s.length <= 10^5scontains only lowercase English letters and spaces' '.sdoes not contain any leading or trailing spaces.- All the words in
sare separated by a single space. 0 <= k < t.length. That is,kis a valid index oft.
Solution
Approach: Skip whole words, then scan one word
Split s into words. A word of length L expands to 1 + 2 + ... + L = L * (L + 1) / 2 characters, call it m, followed by one space.
For each word:
- If
k == m, indexkis the space after this word, so return' '. - If
k > m, the answer lies in a later word: subtractm + 1fromkand move on. - Otherwise
k < mand the character is inside this word. Walk through its letters, addingi + 1(the repeat count of thei-th letter) to a running totalcur; the first letter wherek < curis the answer.
k can reach about 5 * 10^9, so it needs a 64-bit integer.
Complexity: time O(n), space O(n) for the split words.
class Solution:
def kthCharacter(self, s: str, k: int) -> str:
for w in s.split():
m = (1 + len(w)) * len(w) // 2
if k == m:
return " "
if k > m:
k -= m + 1
else:
cur = 0
for i in range(len(w)):
cur += i + 1
if k < cur:
return w[i]