Skip to content

Commit 0f7bd1a

Browse files
committed
solve(backtracking): Problem 2375 - Construct smallest number from di string
1 parent 1d52ea8 commit 0f7bd1a

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
# https://leetcode.com/problems/construct-smallest-number-from-di-string
2+
3+
class Solution:
4+
def smallestNumber(self, pattern: str) -> str:
5+
"""
6+
You are given a 0-indexed string pattern of length n consisting of the characters 'I' meaning increasing and 'D' meaning decreasing.
7+
8+
A 0-indexed string num of length n + 1 is created using the following conditions:
9+
10+
- num consists of the digits '1' to '9', where each digit is used at most once.
11+
- If pattern[i] == 'I', then num[i] < num[i + 1].
12+
- If pattern[i] == 'D', then num[i] > num[i + 1].
13+
14+
Return the lexicographically smallest possible string num that meets the conditions.
15+
"""
16+
def buildSequence(curr_idx, curr_count):
17+
if curr_idx != len(pattern):
18+
if pattern[curr_idx] == 'I':
19+
buildSequence(curr_idx + 1, curr_idx + 1)
20+
21+
else:
22+
curr_count = buildSequence(curr_idx + 1, curr_count)
23+
24+
25+
self.result.append(str(curr_count + 1))
26+
27+
return curr_count + 1
28+
29+
30+
self.result = []
31+
buildSequence(0, 0)
32+
33+
return "".join(self.result[::-1])
34+

0 commit comments

Comments
 (0)