Character at Position in Infinite String
JavaView on GFG
Problem Overview
The infinite string is built by repeated expansion: from the current string S, step t produces S, then t dollar signs, then the reverse of S.
Intuition
The infinite string is built by repeated expansion: from the current string S, step t produces S, then t dollar signs, then the reverse of S. Length therefore follows len = 2 * len + t and grows exponentially, so only a logarithmic number of expansions reach any given position. First grow until the length covers pos, then unwind those expansions. A hit inside the dollar block is immediate; a hit in the reversed half mirrors onto the front half; otherwise the position stays in the front half.
Algorithm
- 1Start with len equal to s.length, target equal to pos, and step equal to 0.
- 2While len is less than target, increment step and set len to 2 * len + step.
- 3While target is still past the original string length, let prevLen be (len - step) / 2.
- 4If target sits in the open dollar interval after prevLen, return dollar.
- 5If target sits in the reversed half, replace target with len - target + 1.
- 6Set len to prevLen, decrement step, and continue.
- 7Return s.charAt(target - 1).
Example Walkthrough
Input: s = "ab", pos = 5
- 1. One expansion makes ab$ba with length 5, which already covers position 5.
- 2. Position 5 lies in the reversed half, so it mirrors to position 1.
- 3. That maps to the first character of the original string, which is a.
Output: a
Common Pitfalls
- • Positions are one based. Convert with charAt(target - 1) only after the walk finishes.
- • Use 64 bit lengths while expanding. Intermediate lengths can exceed a 32 bit int even when pos fits in one.
- • Mirror with len - target + 1 for the reversed half. Off by one here picks the wrong original character.
- • Do not materialize the expanded string. Building it explicitly is linear in the huge length and will time out.
Character at Position in Infinite String.java
Java
// Approach: Each expansion doubles the string and inserts step dollar signs
// in the middle: S -> S + "$"*step + reverse(S). Grow the length until it
// covers pos, then walk the expansions backward. If pos lands in the dollar
// block return '$'; if it lands in the reversed half mirror it into the
// front half; otherwise stay in the front half.
// Complexity: O(log pos) time, O(1) extra space.
class Solution {
public char posInfinite(String s, int pos) {
long len = s.length();
long target = pos;
long step = 0;
while (len < target) {
step++;
len = 2 * len + step;
}
while (target > s.length()) {
long prevLen = (len - step) / 2;
if (target > prevLen && target <= prevLen + step)
return '$';
if (target > prevLen + step)
target = len - target + 1;
len = prevLen;
step--;
}
return s.charAt((int) target - 1);
}
}Was this solution helpful?