3307. Find the K-th Character in String Game II #1886
-
Topics: Alice and Bob are playing a game. Initially, Alice has a string You are given a positive integer Now Bob will ask Alice to perform all operations in sequence:
Return the value of the Note that the character Example 1:
Example 2:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to determine the k-th character in a string after performing a series of operations. The string starts as "a", and each operation either appends a copy of the current string to itself (operation 0) or appends a transformed version of the string where each character is incremented by 1 in the alphabet (operation 1, with 'z' wrapping around to 'a'). Given that k can be as large as 1014 and the number of operations can be up to 100, we need an efficient approach that avoids explicitly constructing the string. Approach
Let's implement this solution in PHP: 3307. Find the K-th Character in String Game II <?php
/**
* @param Integer $k
* @param Integer[] $operations
* @return String
*/
function kthCharacter($k, $operations) {
$n = count($operations);
$total_shift = 0;
$exp = $n; // Exponent representing current string length = 2^$exp
for ($i = $n - 1; $i >= 0; $i--) {
if ($exp - 1 < 48) {
$half = 1 << ($exp - 1);
if ($k > $half) {
$k -= $half;
if ($operations[$i] == 1) {
$total_shift++;
}
}
}
$exp--;
}
$total_shift %= 26;
return chr(ord('a') + $total_shift);
}
// Test cases
// Example 1
$k = 5;
$operations = [0, 0, 0];
echo kthCharacter($k, $operations) . "\n"; // Output: a
// Example 2
$k = 10;
$operations = [0, 1, 0, 1];
echo kthCharacter($k, $operations) . "\n"; // Output: b
?> Explanation:
This approach efficiently narrows down the position k through backward simulation, avoiding the need to handle the exponentially large string directly, and leverages modular arithmetic to handle character transformations. The complexity is O(n), where n is the number of operations, making it suitable for large k. |
Beta Was this translation helpful? Give feedback.
We need to determine the k-th character in a string after performing a series of operations. The string starts as "a", and each operation either appends a copy of the current string to itself (operation 0) or appends a transformed version of the string where each character is incremented by 1 in the alphabet (operation 1, with 'z' wrapping around to 'a'). Given that k can be as large as 1014 and the number of operations can be up to 100, we need an efficient approach that avoids explicitly constructing the string.
Approach
Problem Analysis: The key observation is that each operation doubles the length of the string. For operation 0, the second half is an exact copy of the first half. Fo…