Decoded String at Index in Python

The Decoded String at Index problem involves finding a character at a specific position in a decoded string without actually creating the full decoded string. This approach saves memory when dealing with very long decoded strings.

Problem Understanding

Given an encoded string, we decode it using these rules ?

  • If the character is a letter, write it to the tape.
  • If the character is a digit, repeat the entire current tape digit − 1 more times.

For example, "hello2World3" becomes "hellohelloWorldhellohelloWorldhellohelloWorld".

Algorithm Overview

Instead of creating the full decoded string, we use a two-pass approach ?

  1. Forward pass: Calculate the total length of the decoded string
  2. Backward pass: Find the character at position k by working backwards

Implementation

def decode_at_index(s, k):
    # Step 1: Calculate total size of decoded string
    size = 0
    for char in s:
        if char.isdigit():
            size *= int(char)
        else:
            size += 1
    
    # Step 2: Work backwards to find the character
    for i in range(len(s) - 1, -1, -1):
        k %= size
        
        # If we found our target position and it's a letter
        if s[i].isalpha() and k == 0:
            return s[i]
        
        # Update size based on current character
        if s[i].isalpha():
            size -= 1
        else:
            size //= int(s[i])  # Use integer division
    
    return ""

# Test the function
result = decode_at_index("hello2World3", 10)
print(f"Character at position 10: {result}")

# Test with another example
result2 = decode_at_index("leet2code3", 10)
print(f"Character at position 10 in 'leet2code3': {result2}")
Character at position 10: o
Character at position 10 in 'leet2code3': o

How It Works

Let's trace through "hello2World3" with k=10 ?

Forward Pass (Calculate Size): "hello" ? size = 5 "2" ? size = 5 × 2 = 10 "World" ? size = 10 + 5 = 15 "3" ? size = 15 × 3 = 45 Backward Pass (Find Character): k=10, size=45 ? k%45=10 At "3": size=45/3=15 At "d": k%15=10, size=14 Continue until we find position 10...

Key Points

  • Time complexity: O(n) where n is the length of the encoded string
  • Space complexity: O(1) - no need to store the decoded string
  • The modulo operation helps us find the equivalent position in smaller repeated sections
  • We use integer division (//) in Python 3 for proper integer results

Alternative Class-Based Solution

class Solution:
    def decodeAtIndex(self, s, k):
        # Calculate total size
        size = 0
        for char in s:
            if char.isdigit():
                size *= int(char)
            else:
                size += 1
        
        # Find character by working backwards
        for i in range(len(s) - 1, -1, -1):
            k %= size
            if s[i].isalpha() and k == 0:
                return s[i]
            if s[i].isalpha():
                size -= 1
            else:
                size //= int(s[i])
        
        return ""

# Test the class solution
solution = Solution()
result = solution.decodeAtIndex("hello2World3", 10)
print(f"Result: {result}")
Result: o

Conclusion

The decoded string at index algorithm efficiently finds characters in decoded strings without creating the full decoded string. This approach uses two passes and modulo arithmetic to achieve O(n) time complexity with O(1) space complexity.

Updated on: 2026-03-25T08:29:20+05:30

257 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements