3307. Find the K-th Character in String Game II
UnknownView on LeetCode
Time: O(log k)
Space: O(log k)
Problem Overview
Find the K-th Character in String Game II (Unknown) asks you to solve a structured algorithmic task. This is a common Math / Bit Manipulation pattern in coding interviews. Find highest set bit of k; trace back through operations to determine character.
A full step-by-step explanation is being added. See the study guide for pattern-based practice.
Approach
Find highest set bit of k; trace back through operations to determine character.
Related patterns: Math, Bit Manipulation, Recursion
3307.cs
C#
// Approach: Find highest set bit of k; trace back through operations to determine character.
// Time: O(log k) Space: O(log k)
public class Solution
{
public char KthCharacter(long k, int[] operations)
{
int operationsCount = (int)Math.Ceiling(Math.Log(k) / Math.Log(2));
int increases = 0;
for (int i = operationsCount - 1; i >= 0; --i)
{
long halfSize = 1L << i;
if (k > halfSize)
{
k -= halfSize; // Move k from the right half to the left half.
increases += operations[i];
}
}
return (char)('a' + increases % 26);
}
}Was this solution helpful?
Related Problems
- 12. Integer to Roman(Medium)
- 13. Roman to Integer(Easy)
- 25. Reverse Nodes in k-Group(Hard)
- 29. Divide Two Integers(Medium)
- 66. Plus One(Easy)
- 67. Add Binary(Easy)