Files
test-glm47/ai_coder_2/subtasks/Decomp/001-02.md
T
2026-02-04 16:54:36 +10:00

2.3 KiB

Subtask: Base62 Encoding/Decoding

Parent Task: Decomp/001 Subtask ID: Decomp/001-02 Dependencies: None (can be implemented in parallel with 001-01)

Description

Implement Base62 encoding/decoding for converting numeric IDs to short codes. This is a pure algorithm component with no external dependencies.

Requirements

  • Convert integer ID to Base62 string (0-9, a-z, A-Z)
  • Convert Base62 string back to integer ID
  • Support IDs up to 10^12 (10M URLs with buffer)
  • Handle leading zeros correctly
  • No external dependencies for core logic

Technical Specifications

Algorithm

ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
BASE = 62

def encode(num: int) -> str:
    """Convert integer to Base62 string."""
    if num == 0:
        return ALPHABET[0]
    result = []
    while num > 0:
        num, remainder = divmod(num, BASE)
        result.append(ALPHABET[remainder])
    return ''.join(reversed(result))

def decode(short_code: str) -> int:
    """Convert Base62 string to integer."""
    result = 0
    for char in short_code:
        result = result * BASE + ALPHABET.index(char)
    return result

Complexity Analysis

  • Time: O(log₆₂(n)) for both operations
  • Space: O(log₆₂(n)) for output string

Code Length Constraints

  • Target: <50 lines (Simplicity First principle)
  • Single file module: base62.py

Acceptance Criteria

  • encode(0) returns "0"
  • encode(12345) returns correct Base62 string
  • decode(encode(12345)) == 12345 for all test values
  • Handles edge cases: 0, negative numbers (raise error), max value
  • Unit tests with 100% coverage
  • No external dependencies (stdlib only)
  • <50 lines of code

Notes

  • Why Base62: URL-safe, compact (~62^8 = 218 trillion combinations with 8 chars)
  • Case sensitivity: URLs are case-sensitive, which is standard
  • Alternative considered: Base57 (excluding ambiguous chars like 0/O/l/1) - rejected for simplicity

Edge Cases

  • Empty string input → raise ValueError
  • Invalid characters in input → raise ValueError
  • Negative numbers → raise ValueError
  • Overflow for very large numbers → Python handles big ints natively

Performance

  • Encoding/decoding should be <1μs per operation
  • No memory allocations in tight loops (use list comprehension)