Created
February 17, 2025 03:44
-
-
Save SuryaPratapK/622f3e8bf1dc4f116bd54007d52b2d49 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
string smallestNumber(string pattern) { | |
int n=pattern.size(); | |
stack<int> st; | |
string res=""; | |
for(int i=1;i<=n+1;++i){ | |
st.push(i); | |
char c = pattern[i-1]; | |
//If increasing then reverse and save | |
if(i==n+1 or c=='I'){ | |
while(!st.empty()){ | |
res.push_back(char('0'+st.top())); | |
st.pop(); | |
} | |
} | |
} | |
return res; | |
} | |
}; | |
/* | |
//JAVA | |
import java.util.Stack; | |
class Solution { | |
public String smallestNumber(String pattern) { | |
int n = pattern.length(); | |
Stack<Integer> st = new Stack<>(); | |
StringBuilder res = new StringBuilder(); | |
for (int i = 1; i <= n + 1; ++i) { | |
st.push(i); | |
if (i == n + 1 || pattern.charAt(i - 1) == 'I') { | |
while (!st.isEmpty()) { | |
res.append(st.pop()); | |
} | |
} | |
} | |
return res.toString(); | |
} | |
} | |
#Python | |
class Solution: | |
def smallestNumber(self, pattern: str) -> str: | |
n = len(pattern) | |
st = [] | |
res = [] | |
for i in range(1, n + 2): | |
st.append(i) | |
if i == n + 1 or pattern[i - 1] == 'I': | |
while st: | |
res.append(str(st.pop())) | |
return ''.join(res) | |
*/ |
What is the complexity.?
O(N)
for both TC and SC
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
What is the complexity.?