tinycodinglm / cp2 /cp-0026.jsonl
winapiadmin's picture
Upload folder using huggingface_hub (part 15)
b27bfb3 verified
|
Raw History Blame Contribute Delete
7.59 kB
cp-practice-sim trace
System You are a competitive-programming assistant. Deliver correct, complete, runnable solutions that read standard input and write standard output. Give only a concise rationale: approach, correctness idea, and time/space com...

You are a competitive-programming assistant. Deliver correct, complete, runnable solutions that read standard input and write standard output. Give only a concise rationale: approach, correctness idea, and time/space complexity.

User 2026-11-07T23:20:03.537Z

Unrolled Banner Letter

Topic: String manipulation and parsing | Difficulty: medium

Problem

A banner is written in a compressed form. A compressed string is a concatenation of items; an item is either a lowercase letter or k[X], where k is a positive integer and X is a non-empty compressed string, meaning X repeated k times. For example 2[ab3[c]]d expands to abcccabcccd. The expanded banner can be astronomically long, so it must not be built. Given the compressed string and a position p, print the p-th letter (1-indexed) of the expanded banner.

Input

The first line contains the compressed string. The second line contains the integer p.

Output

Print the single letter at position p of the expansion.

Constraints

  • 1 <= length of the compressed string <= 2*10^5
  • every repeat count k satisfies 1 <= k <= 10^9
  • the expansion has length at least p, and 1 <= p <= 10^18
  • the compressed string is valid, with every bracket pair containing at least one letter

Examples

Example 1

Input:

markdown
2[ab3[c]]d
7

Output:

markdown
b

Note: The expansion is abcccabcccd and its 7th letter is b.

Example 2

Input:

markdown
1000000000[1000000000[z]]y
1000000000000000001

Output:

markdown
y

Note: The expansion has 10^18 letters z followed by y.

Example 3

Input:

markdown
ab
2

Output:

markdown
b

Solve this in JavaScript (Node.js), Ruby, C#, one complete program per language. Include a concise rationale (approach, correctness idea, time/space complexity).

Assistant 2026-11-07T23:20:05.511Z

Approach. Parse iteratively with a stack into a tree of items and compute each subtree's expanded length, saturating at 2*10^18. Then descend from the root: skip items whose total length is at most p, and inside a repeated block reduce p modulo the block's single-copy length.

Correctness. Positions inside k copies of X map to position (p mod |X|) of X, and saturation is harmless because p is below the cap so any capped length still exceeds p. The descent visits each item at most once, so it also runs in linear time.

Complexity. Time: O(n). Space: O(n).

JavaScript (Node.js)

javascript
const lines = require('fs').readFileSync(0, 'utf8').split('\n').map(x => x.trim());
const s = lines[0];
let p = BigInt(lines[1]) - 1n;
const CAP = 2000000000000000000n;
const mk = (k) => ({ segs: [], len: 0n, k });
const root = mk(1n);
const stack = [root];
let num = 0n;
for (const ch of s) {
  if (ch >= '0' && ch <= '9') {
    num = num * 10n + BigInt(ch.charCodeAt(0) - 48);
  } else if (ch === '[') {
    stack.push(mk(num));
    num = 0n;
  } else if (ch === ']') {
    const f = stack.pop();
    const par = stack[stack.length - 1];
    let total = f.len * f.k;
    if (total > CAP) total = CAP;
    par.segs.push({ child: f, total });
    par.len = par.len + total > CAP ? CAP : par.len + total;
  } else {
    const par = stack[stack.length - 1];
    par.segs.push({ ch, total: 1n });
    par.len = par.len + 1n > CAP ? CAP : par.len + 1n;
  }
}
let node = root;
outer: while (true) {
  for (const sg of node.segs) {
    if (p < sg.total) {
      if (sg.ch !== undefined) {
        console.log(sg.ch);
        break outer;
      }
      p = p % sg.child.len;
      node = sg.child;
      continue outer;
    }
    p -= sg.total;
  }
}

Ruby

ruby
s = gets.strip
p = gets.strip.to_i - 1
cap = 2 * 10**18
Frame = Struct.new(:segs, :len, :k)
root = Frame.new([], 0, 1)
stack = [root]
num = 0
s.each_char do |ch|
  if ch >= '0' && ch <= '9'
    num = num * 10 + ch.ord - 48
  elsif ch == '['
    stack << Frame.new([], 0, num)
    num = 0
  elsif ch == ']'
    f = stack.pop
    par = stack[-1]
    total = [f.len * f.k, cap].min
    par.segs << [f, total]
    par.len = [par.len + total, cap].min
  else
    par = stack[-1]
    par.segs << [ch, 1]
    par.len = [par.len + 1, cap].min
  end
end
node = root
loop do
  moved = false
  node.segs.each do |sg, total|
    if p < total
      if sg.is_a?(String)
        puts sg
        exit
      end
      p %= sg.len
      node = sg
      moved = true
      break
    end
    p -= total
  end
  break unless moved
end

C#

csharp
using System;
using System.Collections.Generic;

class Frame
{
    public List<Seg> Segs = new List<Seg>();
    public long Len = 0;
    public long K;
    public Frame(long k) { K = k; }
}

class Seg
{
    public char Ch;
    public Frame Child;
    public long Total;
}

class Program
{
    const long CAP = 2000000000000000000L;

    static long Add(long a, long b) { return Math.Min(CAP, a + b); }

    static long Mul(long a, long b)
    {
        if (a == 0 || b == 0) return 0;
        if (a > CAP / b) return CAP;
        return Math.Min(CAP, a * b);
    }

    static void Main()
    {
        string s = Console.ReadLine().Trim();
        long p = long.Parse(Console.ReadLine().Trim()) - 1;
        var root = new Frame(1);
        var stack = new List<Frame> { root };
        long num = 0;
        foreach (char ch in s)
        {
            if (ch >= '0' && ch <= '9') num = num * 10 + (ch - '0');
            else if (ch == '[')
            {
                stack.Add(new Frame(num));
                num = 0;
            }
            else if (ch == ']')
            {
                Frame f = stack[stack.Count - 1];
                stack.RemoveAt(stack.Count - 1);
                Frame par = stack[stack.Count - 1];
                long total = Mul(f.Len, f.K);
                par.Segs.Add(new Seg { Child = f, Total = total });
                par.Len = Add(par.Len, total);
            }
            else
            {
                Frame par = stack[stack.Count - 1];
                par.Segs.Add(new Seg { Ch = ch, Total = 1 });
                par.Len = Add(par.Len, 1);
            }
        }
        Frame node = root;
        while (true)
        {
            bool moved = false;
            foreach (Seg sg in node.Segs)
            {
                if (p < sg.Total)
                {
                    if (sg.Child == null)
                    {
                        Console.WriteLine(sg.Ch);
                        return;
                    }
                    p %= sg.Child.Len;
                    node = sg.Child;
                    moved = true;
                    break;
                }
                p -= sg.Total;
            }
            if (!moved) break;
        }
    }
}