The problem asks to reconstruct the lexicographically smallest permutation from a string s
consisting of 'I' and 'D' characters. 'I' indicates an increasing sequence, and 'D' indicates a decreasing sequence in the permutation. The solution leverages a greedy approach and array manipulation.
The core idea is to process the string s
iteratively. We maintain an array ans
initialized with numbers from 1 to n+1 (where n is the length of s). When we encounter a sequence of 'D's, we reverse the corresponding portion of the ans
array. This ensures that we get the smallest lexicographical permutation.
Initialization: Create an array ans
containing integers from 1 to n+1
.
Iteration: Traverse the input string s
.
'D' Sequence: If we encounter a 'D', we find the end of the consecutive 'D's. Then, we reverse the portion of the ans
array corresponding to this 'D' sequence. Reversing ensures we obtain the smallest possible numbers in decreasing order for this segment.
'I' Sequence: If we encounter an 'I', we move to the next character; no reversal is needed as the order is already increasing.
Result: After processing the entire string, the ans
array contains the lexicographically smallest permutation.
Time Complexity: O(n), where n is the length of the input string s
. This is because we iterate through the string once, and the reversal operation within each iteration takes linear time proportional to the length of the reversed subarray. In the worst case, we reverse the entire array once, but the overall time complexity remains linear.
Space Complexity: O(n). This is due to the space used to store the ans
array of size n+1. The space used by other variables is constant.
The Python code efficiently implements this approach:
class Solution:
def findPermutation(self, s: str) -> List[int]:
n = len(s)
ans = list(range(1, n + 2)) # Initialize array with 1 to n+1
i = 0
while i < n:
j = i
while j < n and s[j] == 'D': # Find end of 'D' sequence
j += 1
ans[i : j + 1] = ans[i : j + 1][::-1] # Reverse the subarray
i = max(i + 1, j) # Move to the next position
return ans
The code in other languages (Java, C++, Go) follows the same logic, differing primarily in syntax and data structure handling. They all maintain the linear time and space complexity.