Leetcode 880: Decoded String at Index

grid47
grid47
Exploring patterns and algorithms
Aug 11, 2024 6 min read

You are given an encoded string consisting of letters and digits. The string is decoded such that for each digit, the preceding segment of the decoded string is repeated (digit - 1) additional times. Your task is to return the kth character (1-indexed) in the decoded string, where k is a positive integer. The decoded string could be extremely large, so you are not expected to fully decode the string.
Problem
Approach
Steps
Complexity
Input: The input consists of an encoded string containing lowercase English letters and digits between 2 and 9. The string always starts with a letter.
Example: Input: s = 'abc3de2', k = 5
Constraints:
• 2 <= s.length <= 100
• s consists of lowercase English letters and digits 2 through 9.
• s starts with a letter.
• 1 <= k <= 10^9
• It is guaranteed that k is less than or equal to the length of the decoded string.
• The decoded string will have fewer than 2^63 letters.
Output: You should return a string representing the kth character in the decoded string.
Example: Output: 'd'
Constraints:
• The output is a single lowercase letter.
Goal: To efficiently determine the kth character without fully decoding the string.
Steps:
• First, calculate the total length of the decoded string by iterating over the encoded string.
• Identify the range in which the kth character lies by adjusting the index in reverse.
• When a digit is encountered, divide the total length by that digit to adjust the range, and continue until the correct position is found.
Goal: The problem has constraints that ensure that the decoded string is large enough that fully decoding it is impractical. The goal is to calculate the position of the kth character without decoding the entire string.
Steps:
• The number of characters to decode can grow very large, so a brute-force solution that fully decodes the string would be inefficient.
Assumptions:
• It is guaranteed that k is less than or equal to the length of the decoded string.
• The input string contains only lowercase letters and digits between 2 and 9.
Input: Input: s = 'abc3de2', k = 5
Explanation: The string 'abc3de2' decodes to 'abcdeabcde'. The 5th character is 'd'.

Input: Input: s = 'xy2z3', k = 6
Explanation: The string 'xy2z3' decodes to 'xyzxyzxyzxyz'. The 6th character is 'z'.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus