#880
Decoded String at Index
MediumStringStackString ManipulationDynamic Programming
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
Instead of fully decoding the string, we can calculate the length of the decoded string dynamically and find the k-th character without constructing the entire string. This is efficient and handles large inputs gracefully.
⚙️
Algorithm
5 steps- 1Step 1: Initialize a variable to keep track of the total length of the decoded string.
- 2Step 2: Iterate through the encoded string in reverse to find the effective length of the decoded string.
- 3Step 3: If the current character is a digit, divide the length by that digit to find the length of the previous segment.
- 4Step 4: If the current character is a letter and the current length is greater than or equal to k, check if this letter is the k-th character.
- 5Step 5: If found, return the letter; otherwise, continue until the beginning of the string.
solution.py15 lines
1def decodeAtIndex(s, k):
2 length = 0
3 for char in s:
4 if char.isdigit():
5 length *= int(char)
6 else:
7 length += 1
8 for char in reversed(s):
9 k %= length
10 if k == 0 and char.isalpha():
11 return char
12 if char.isdigit():
13 length //= int(char)
14 else:
15 length -= 1ℹ
Complexity note: The complexity is O(n) because we only traverse the string a couple of times, and we do not store the entire decoded string, making it efficient.
- 1The decoded string can grow exponentially, making full construction impractical.
- 2Using reverse traversal allows us to find the k-th character without full expansion.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.