question_slug
stringlengths 3
77
| title
stringlengths 1
183
| slug
stringlengths 12
45
| summary
stringlengths 1
160
⌀ | author
stringlengths 2
30
| certification
stringclasses 2
values | created_at
stringdate 2013-10-25 17:32:12
2025-04-12 09:38:24
| updated_at
stringdate 2013-10-25 17:32:12
2025-04-12 09:38:24
| hit_count
int64 0
10.6M
| has_video
bool 2
classes | content
stringlengths 4
576k
| upvotes
int64 0
11.5k
| downvotes
int64 0
358
| tags
stringlengths 2
193
| comments
int64 0
2.56k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
reverse-prefix-of-word | C++ BEST SOLUTION | c-best-solution-by-poxyprabal-9bps | \n\n# Code\n\nclass Solution {\npublic:\n string reversePrefix(string word, char ch) {\n int l = 0;\n for (int r = 0; r < word.size(); r++) {\n | poxyprabal | NORMAL | 2024-05-01T16:18:34.467264+00:00 | 2024-05-01T16:18:34.467285+00:00 | 385 | false | \n\n# Code\n```\nclass Solution {\npublic:\n string reversePrefix(string word, char ch) {\n int l = 0;\n for (int r = 0; r < word.size(); r++) {\n if (word[r] == ch) {\n while (l <= r) {\n swap(word[r], word[l]);\n l++;\n r--;\n }\n return word;\n }\n }\n return word;\n }\n};\n``` | 4 | 0 | ['C++'] | 0 |
reverse-prefix-of-word | Simple easy to understand solution in 0ms. | simple-easy-to-understand-solution-in-0m-gkeu | Intuition\nMy intition was to count the index of character and then reverse it to that index using a reverse function.\n\n# Approach\nfind the index of characte | ayushsachan7 | NORMAL | 2024-05-01T10:02:09.668166+00:00 | 2024-05-01T10:02:09.668194+00:00 | 309 | false | # Intuition\nMy intition was to count the index of character and then reverse it to that index using a reverse function.\n\n# Approach\nfind the index of character using for loop and reverse upto that index using swap function.\n\n# Complexity\n- Time complexity: O(N)\n\n- Space complexity: O(1)\n\n# Code\n```\nclass Solution {\npublic:\n string reverse(string word,int k)\n {\n int i=0;\n while(i<k)\n {\n swap(word[i],word[k]);\n i++;\n k--;\n\n }\n return word;\n }\n string reversePrefix(string word, char ch) {\n int j=0;\n for(int i=0;i<word.length();i++)\n {\n if(ch==word[i]){\n j=i;\n break;}\n }\n if(j==0)\n return word;\n return reverse(word,j);\n \n }\n};\n``` | 4 | 0 | ['Two Pointers', 'String', 'C++'] | 4 |
reverse-prefix-of-word | EXPLAINED SOLUTION | explained-solution-by-nurliaidin-ys5p | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n1. Prepare to Store Pre | Nurliaidin | NORMAL | 2024-05-01T09:54:25.042058+00:00 | 2024-05-01T09:54:25.042078+00:00 | 532 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. **Prepare to Store Prefix and Suffix:**\n - Initialize `pre` to store characters before `ch`.\n - Set up `suf` to store any characters after `ch`.\n\n2. **Search for the Specified Character:**\n - Iterate through each character.\n - If `ch` is found, proceed.\n\n3. **Handle Character Found:**\n - Store remaining characters in `suf`.\n - Exit the loop.\n\n4. **Handle Character Not Found:**\n - Clear `pre` if `ch` is not found.\n\n5. **Reverse Prefix:**\n - Reverse the order of characters in `pre`.\n\n6. **Combine Prefix and Suffix:**\n - Concatenate reversed `pre` with `suf`.\n\n7. **Return the Result:**\n - If `pre` is empty, return the original word.\n - Otherwise, return the word with reversed prefix and suffix.\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n **`o(n)`**\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n **`o(n)`**\n# Code\n``` javascript []\n/**\n * @param {string} word\n * @param {character} ch\n * @return {string}\n */\nvar reversePrefix = function(word, ch) {\n let n = word.length;\n\n //create a list to store the characters before the CHARACTER(ch)\n let pre = [];\n // suf will store the remaining suffix if there is any \n let suf = "";\n for(let i=0; i<n; i++) {\n pre.push(word[i]);\n\n // check if the current character is the character wanted\n if(word[i] == ch) {\n // if so then put the remaining character to suf and break the loop\n suf = word.substr(i+1, n-1);\n break;\n }\n // if the wanted character is not found, then just leave the pre empty in case it is easy to check\n if(i+1 == n) pre = [];\n }\n //return `word` itself if pre is empty which means the wanted character is not found or return the result in which prefix is reversed and suffix is added\n return pre.length == 0 ? word : pre.reverse().join(\'\') + suf;\n};\n```\n``` cpp []\nclass Solution {\npublic:\n string reversePrefix(string word, char ch) {\n int n = word.size();\n\n //create a list to store the characters before the CHARACTER(ch)\n vector<char> pre;\n\n // suf will store the remaining suffix if there is any \n string suf = ""; \n \n for(int i=0; i<n; i++) {\n pre.push_back(word[i]);\n\n // check if the current character is the character wanted\n if(word[i] == ch) {\n // if so then put the remaining character to suf and break the loop\n suf = word.substr(i+1, n-1);\n break; \n }\n // if the wanted character is not found, then just leave the pre empty in case it is easy to check\n if(i+1 == n) pre.clear(); \n }\n reverse(pre.begin(), pre.end()); //reverse the pre\n string res(pre.begin(), pre.end()); //convert the pre to string res\n res+=suf; //add the remaining suf if there is any\n return pre.size() == 0 ? word : res; //return `word` itself if pre is empty which means the wanted character is not found or return `res`\n }\n};\n``` | 4 | 0 | ['C++', 'JavaScript'] | 3 |
reverse-prefix-of-word | String find/reverse solution | string-findreverse-solution-by-drgavriko-0q8p | Approach\n Describe your approach to solving the problem. \n\nFirst, we find the position of the first occurrence of the character \'ch\' in the string \'word\' | drgavrikov | NORMAL | 2024-05-01T07:10:31.463305+00:00 | 2024-05-01T07:11:00.476863+00:00 | 10 | false | # Approach\n<!-- Describe your approach to solving the problem. -->\n\nFirst, we find the position of the first occurrence of the character \'ch\' in the string \'word\' using the \'find\' function.\n\nIf the character is found (i.e., its index is not equal to std::string::npos), we use the \'std::reverse\' function from the standard library to reverse the order of characters in the substring from the beginning of the string to the found character, inclusive.\n\n\n# Complexity\n- Time complexity: $O(n)$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $O(1)$ additional memory\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n string reversePrefix(string word, char ch) {\n size_t charIndex = word.find(ch);\n if (charIndex != std::string::npos) {\n std::reverse(word.begin(), word.begin() + charIndex + 1);\n }\n return word;\n }\n};\n``` | 4 | 0 | ['C++'] | 0 |
reverse-prefix-of-word | Easy solution and iterative solution | easy-solution-and-iterative-solution-by-3iwig | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \nIterative approach\nYou | Rishabhdwivedii | NORMAL | 2024-05-01T04:49:08.416858+00:00 | 2024-05-01T04:49:08.416879+00:00 | 541 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nIterative approach\nYou define a function reversePrefix that takes a string word and a character ch as input parameters and returns a string.\nYou initialize an empty string reverse to store the reversed prefix.\nYou iterate over the indices of the word using a for loop.\nInside the loop, if the character at index i matches the given character ch, you extract the prefix up to and including ch, reverse it, and assign it to the reverse variable.\nYou break out of the loop once the prefix is reversed to avoid unnecessary iterations.\nFinally, you return the concatenation of the reversed prefix (reverse) and the remaining part of the word (word[len(reverse):]), effectively reversing the prefix and leaving the rest of the word unchanged.\n\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(N)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(1)\n\n# Code\n```\nclass Solution:\n def reversePrefix(self, word: str, ch: str) -> str:\n reverse=\'\'\n for i in range (len(word)):\n if(word[i]==ch):\n prefix=word[:i+1]\n reverse=prefix[::-1]\n break\n return reverse+word[len(reverse):]\n\n\n \n``` | 4 | 0 | ['Python3'] | 4 |
reverse-prefix-of-word | easiest approach cpp | | easiest-approach-cpp-by-ankitlodhi-3y6i | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | ankitlodhi | NORMAL | 2024-05-01T04:14:16.693785+00:00 | 2024-05-01T04:14:16.693819+00:00 | 342 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n string reversePrefix(string word, char ch) {\n int i = word.find(ch);\n if (i != -1) {\n reverse(word.begin(), word.begin() + i + 1);\n }\n return word;\n }\n};\n``` | 4 | 0 | ['C++'] | 0 |
reverse-prefix-of-word | The solution really easy to got it | the-solution-really-easy-to-got-it-by-ja-sayw | Code\n\nfunc reversePrefix(word string, ch byte) string {\n var natija string\n for i := 0; i < len(word); i++ {\n if word[i] == ch { \n | Javohir_hasanov | NORMAL | 2024-05-01T03:59:40.744903+00:00 | 2024-05-01T03:59:40.744933+00:00 | 218 | false | # Code\n```\nfunc reversePrefix(word string, ch byte) string {\n var natija string\n for i := 0; i < len(word); i++ {\n if word[i] == ch { \n ch_index := i\n for i >= 0 {\n natija += string(word[i])\n i--\n } \n return natija + word[ch_index + 1 : ]\n }\n } \n return word\n}\n\n\n``` | 4 | 0 | ['Go'] | 2 |
reverse-prefix-of-word | 💯Two Pointers🎯✅ | 98.63%🔥| 4 Easy Steps : 🎯| Simple (5 line) to understand💯Explained | two-pointers-9863-4-easy-steps-simple-5-4rrkd | Intuition\nsimply we are using 2\uFE0F\u20E3 pointers\uD83D\uDC96\uD83D\uDC96 left and right to traverse pointer in opposite direction and concurrently swaping | Prathamesh18X | NORMAL | 2024-05-01T03:34:04.908921+00:00 | 2024-05-01T03:34:04.908946+00:00 | 1,005 | false | # Intuition\nsimply we are using **2\uFE0F\u20E3 pointers**\uD83D\uDC96\uD83D\uDC96 `left` and `right` to traverse pointer in opposite direction and concurrently swaping each other to reverse the string till `left` is less than `right`...\uD83D\uDCAF\n\n# Dont forget to vote...\u2B06\uFE0F **me**\uD83E\uDD73\n### *and*\n# world\'s Largest Democratic Election 2k24\n\n\n# Code\uD83C\uDFAF\n```javascript []\nvar reversePrefix = function (word, ch) {\n var left = 0;\n var right = word.indexOf(ch)\n const arr = word.split(\'\')\n\n if(r === -1) return word\n \n while(l < r) {\n const temp = arr[left];\n arr[left] = arr[right];\n arr[right] = temp;\n left++\n right--\n }\n return arr.join(\'\');\n};\n```\n```python []\ndef reverse_prefix(word, ch):\n left = 0\n right = word.find(ch)\n if right == -1:\n return word\n \n arr = list(word)\n \n while left < right:\n arr[left], arr[right] = arr[right], arr[left]\n left += 1\n right -= 1\n \n return \'\'.join(arr)\n```\n```java []\n public static String reversePrefix(String word, char ch) {\n int left = 0;\n int right = word.indexOf(ch);\n if (right == -1) {\n return word;\n }\n char[] arr = word.toCharArray();\n \n while (left < right) {\n char temp = arr[left];\n arr[left] = arr[right];\n arr[right] = temp;\n left++;\n right--;\n }\n \n return new String(arr);\n }\n\n\n```\n```cpp []\nstring reversePrefix(const std::string& word, char ch) {\n int left = 0;\n int right = word.find(ch);\n if (right == std::string::npos) {\n return word;\n }\n string arr = word;\n \n while (left < right) {\n swap(arr[left], arr[right]);\n left++;\n right--;\n }\n \n return arr;\n}\n```\n```ruby []\ndef reverse_prefix(word, ch)\n left = 0\n right = word.index(ch)\n return word if right.nil?\n \n arr = word.chars\n \n while left < right\n arr[left], arr[right] = arr[right], arr[left]\n left += 1\n right -= 1\n end\n \n arr.join\nend\n```\n``` kotlin []\nfun reversePrefix(word: String, ch: Char): String {\n var left = 0\n val right = word.indexOf(ch)\n if (right == -1) {\n return word\n }\n val arr = word.toCharArray()\n \n while (left < right) {\n // Swap characters at left and right\n val temp = arr[left]\n arr[left] = arr[right]\n arr[right] = temp\n left++\n right--\n }\n \n // Convert CharArray back to String and return\n return String(arr)\n}\n```\n\n\n### Approach\uD83D\uDD25\uD83D\uDE43\n\n1. **Find the First Occurrence of `ch`:**\n - Use `indexOf` method on `word` to find the index of the first occurrence of `ch`.\n - If `ch` is not found (`indexOf` returns -1), return the original string.\n\n2. **Convert String to an Array:**\n - Convert `word` to an array of characters using `split(\'\')` for easier manipulation.\n\n3. **Reverse the Prefix:**\n - Define two pointers: `left` starting at index 0, and `right` starting at the index of `ch`.\n - Swap characters at `left` and `right` pointers.\n - Move `left` one step forward and `right` one step backward.\n - Continue until `left` and `right` pointers meet or cross.\n\n4. **Convert the Array Back to a String:**\n - Join the array of characters using `join(\'\')` to convert it back to a string.\n\n5. **Return the Result:**\n - Return the modified string.\n\n\n# Complexity\n- Time complexity: `O(1)`\n\n | 4 | 0 | ['Two Pointers', 'String', 'C', 'Python', 'C++', 'Java', 'Python3', 'Ruby', 'Kotlin', 'JavaScript'] | 3 |
reverse-prefix-of-word | ✅Beats 91%🔥 2 Solutions🔥🔥🔥Simple character matching solution. With no additional space | beats-91-2-solutionssimple-character-mat-cly4 | image.png\n\n\n# Intuition\nIf we can find the given charater ch in given string word, we have to reverse string till first ch including it. To do this, we can | Saketh3011 | NORMAL | 2024-05-01T01:31:10.330068+00:00 | 2024-05-01T07:01:33.198804+00:00 | 632 | false | image.png\n\n\n# Intuition\nIf we can find the given charater `ch` in given string `word`, we have to reverse string till first `ch` including it. To do this, we can find first `ch` index in `word` and then return concatenation of reversed substring till `ch`and rest of the substring.\n\n# Approach\n- First we iterate through each character in the input string `word`.\n- Then use enumerate to get both the character and its index in the string.\n- When the character `ch` is found:\n - Use slicing to reverse the prefix of `word` up to the index of `ch`.\n - Concatenate the reversed prefix with the suffix of `word` starting from the next character after `ch`.\n- If `ch` is not found, return the original `word` unchanged.\n\n# Complexity\n- Time complexity: $$O(n)$$\n\n- Space complexity: $$O(n)$$. Extra space only for returned string\n\n# Code\n**Method 1**\n``` python []\nclass Solution:\n def reversePrefix(self, word: str, ch: str) -> str:\n for i,c in enumerate(word):\n if c == ch:\n return word[i::-1] + word[i+1::]\n return word\n```\n``` java []\nclass Solution {\n public String reversePrefix(String word, char ch) {\n for (int i = 0; i < word.length(); i++) {\n if (word.charAt(i) == ch) {\n return new StringBuilder(word.substring(0, i + 1)).reverse().toString() + word.substring(i + 1);\n }\n }\n return word;\n }\n}\n```\n``` cpp []\nclass Solution {\npublic:\n string reversePrefix(string word, char ch) {\n for (int i = 0; i < word.size(); i++) {\n if (word[i] == ch) {\n reverse(word.begin(), word.begin() + i + 1);\n break;\n }\n }\n return word;\n }\n};\n```\n\n**Method 2:**\n``` python []\nclass Solution:\n def reversePrefix(self, word: str, ch: str) -> str:\n first_occurrence = word.find(ch)\n if first_occurrence == -1:\n return word\n \n prefix = word[:first_occurrence + 1]\n reversed_prefix = prefix[::-1]\n return reversed_prefix + word[first_occurrence + 1:]\n```\n``` java []\nclass Solution {\n public String reversePrefix(String word, char ch) {\n int firstOccurence = word.indexOf(ch);\n if(firstOccurence == -1){\n return word;\n }\n \n StringBuilder prefix = new StringBuilder(word.substring(0, firstOccurence+1));\n return prefix.reverse().toString() + word.substring(firstOccurence+1);\n }\n}\n```\n``` cpp []\nclass Solution {\npublic:\n string reversePrefix(string word, char ch) {\n int first_occurrence = word.find(ch);\n if (first_occurrence == string::npos) {\n return word;\n }\n \n string prefix = word.substr(0, first_occurrence + 1);\n reverse(prefix.begin(), prefix.end());\n return prefix + word.substr(first_occurrence + 1);\n }\n};\n```\n.\n\n# Method 3:\nOnly for C++\n# Intuition\nIn Python and Java string are immutable so we return new string. \nBut in C++ string are mutable so we can reverse `word` inplace with two pointer.\n# Complexity\n- Time complexity: $$O(n)$$\n- Space complexity: $$O(1)$$.\n\n``` cpp []\nclass Solution {\npublic:\n string reversePrefix(string word, char ch) {\n int first_occurrence = word.find(ch);\n if (first_occurrence == string::npos) {\n return word;\n }\n \n int i = 0, j = first_occurrence;\n while(i<=j) {\n swap(word[i++], word[j--]);\n }\n return word;\n }\n};\n``` | 4 | 0 | ['Two Pointers', 'String', 'C', 'Python', 'C++', 'Java', 'Python3'] | 1 |
reverse-prefix-of-word | Java || 100% beats | java-100-beats-by-saurabh_kumar1-h12l | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | saurabh_kumar1 | NORMAL | 2023-08-16T11:06:03.444839+00:00 | 2023-08-16T11:06:03.444864+00:00 | 80 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:0(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:0(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public String reversePrefix(String word, char ch) {\n int index = 0;\n StringBuilder str = new StringBuilder();\n for(int i=0; i<word.length(); i++ ){\n if(word.charAt(i)==(ch)) {\n index = i; break;\n }\n }\n str.append(word.substring(0,index+1));\n str.reverse();\n str.append(word.substring(index+1,word.length()));\n return str.toString();\n }\n}\n``` | 4 | 0 | ['Java'] | 1 |
reverse-prefix-of-word | [ Go Solution ]Great explanation and Full Description | go-solution-great-explanation-and-full-d-8zrr | Intuition\nThe problem asks to reverse the prefix of a string up to the first occurrence of a specified character. If the character does not exist in the string | sansaian | NORMAL | 2023-06-21T14:34:16.549695+00:00 | 2023-06-21T14:34:16.549721+00:00 | 454 | false | # Intuition\nThe problem asks to reverse the prefix of a string up to the first occurrence of a specified character. If the character does not exist in the string, we should return the original string. The problem can be solved by iterating through the string and once we find the specified character, we reverse the prefix and append the remaining part of the string.\n\n# Approach\nWe first initialize an empty slice `result` with capacity equal to the length of the input string `word` to store the resulting string. We also initialize a counter `r` to `0` to keep track of the index of the specified character in the string.\n\nWe then iterate over the string, and if we encounter the specified character, we break out of the loop.\n\nNext, we check if `r` equals the length of the string. If it does, it means the specified character does not exist in the string, and we return the original string.\n\nIf `r` does not equal the length of the string, it means we have found the specified character. We iterate from `r` to `0` in reverse order, append each character at index `j` to `result`, and finally append the remaining part of the string starting from index `r+1` to `result`.\n\nFinally, we return the string representation of `result`.\n\n# Complexity\n- Time complexity: The time complexity for this algorithm is O(n), where `n` is the length of the `word`. This is because we perform a single pass over the `word`.\n\n- Space complexity: The space complexity is also O(n), as we create a new string of the same size as the input `word`.\n\n# Code\n```\nfunc reversePrefix(word string, ch byte) string {\n\n\tr := 0\n\tfor i := range word {\n\t\tif word[i] == ch {\n\t\t\tbreak\n\t\t}\n\t\tr++\n\t}\n\tif r == len(word) {\n\t\treturn word\n\t}\n result := make([]byte, 0, len(word))\n\tfor j := r; j >= 0; j-- {\n\t\tresult = append(result, word[j])\n\t}\n\tresult = append(result, word[r+1:]...)\n\treturn string(result)\n}\n``` | 4 | 0 | ['Two Pointers', 'Go'] | 0 |
reverse-prefix-of-word | reverse prefix python3 | reverse-prefix-python3-by-timsmyrnov-cy41 | Complexity\n- Time complexity:\nO(N)\n\n- Space complexity:\nO(N)\n\n# Code\n\nclass Solution:\n def reversePrefix(self, word: str, ch: str) -> str:\n | timsmyrnov | NORMAL | 2023-05-01T07:40:58.023315+00:00 | 2023-05-01T07:40:58.023348+00:00 | 717 | false | # Complexity\n- Time complexity:\nO(N)\n\n- Space complexity:\nO(N)\n\n# Code\n```\nclass Solution:\n def reversePrefix(self, word: str, ch: str) -> str:\n prefix = \'\'\n for i, c in enumerate(word):\n if c == ch:\n return (prefix + c)[::-1] + word[i+1:]\n prefix += c\n return prefix\n``` | 4 | 0 | ['Python3'] | 2 |
reverse-prefix-of-word | Sol: Reverse Prefix of Word [JAVA] | sol-reverse-prefix-of-word-java-by-subha-glbe | Code\n\nclass Solution {\n public String reversePrefix(String word, char ch) {\n String subString = word.substring(0, word.indexOf(ch)+1);\n\t\tString | subhajitbhattacharjee007 | NORMAL | 2022-12-28T12:18:56.394869+00:00 | 2022-12-28T12:19:13.747449+00:00 | 371 | false | # Code\n```\nclass Solution {\n public String reversePrefix(String word, char ch) {\n String subString = word.substring(0, word.indexOf(ch)+1);\n\t\tString remainingString = word.substring( word.indexOf(ch)+1, word.length());\n\t\tString s = "";\n\t\tfor( int i=subString.length()-1; i>=0; i--) {\n\t\t\ts=s+subString.charAt(i);\n\t\t}\n\t\treturn s+remainingString;\n }\n}\n``` | 4 | 0 | ['Java'] | 2 |
reverse-prefix-of-word | C++ | Find and Reverse | Easy | c-find-and-reverse-easy-by-shreyanshxyz-kvb3 | \nclass Solution {\npublic:\n string reversePrefix(string word, char ch) {\n if(word.length() == 1) return word;\n \n for(int i = 0; i < | shreyanshxyz | NORMAL | 2022-08-10T13:50:38.788842+00:00 | 2022-08-10T13:50:38.788883+00:00 | 239 | false | ```\nclass Solution {\npublic:\n string reversePrefix(string word, char ch) {\n if(word.length() == 1) return word;\n \n for(int i = 0; i < word.size(); i++){\n if(word[i] == ch){\n reverse(word.begin(), word.begin() + i + 1);\n break;\n }\n }\n return word;\n }\n};\n``` | 4 | 0 | ['C'] | 0 |
reverse-prefix-of-word | C++ solution || 2 approaches || Solved using Stack(3ms) || using reverse function(0ms) | c-solution-2-approaches-solved-using-sta-ttv8 | \t\t\t\t\t\t\t\t\t----Approach 1(Stack)----\n\n\tclass Solution {\n\tpublic:\n\t\tstring reversePrefix(string word, char ch) {\n\n stack s;\n int | ap00rv_13 | NORMAL | 2022-07-08T04:00:56.179367+00:00 | 2022-07-08T04:00:56.179398+00:00 | 254 | false | \t\t\t\t\t\t\t\t\t----Approach 1(Stack)----\n\n\tclass Solution {\n\tpublic:\n\t\tstring reversePrefix(string word, char ch) {\n\n stack<char> s;\n int i=0, count = 0;\n int size = word.size();\n\n while(word[i] != ch){\n count++;\n if(count == size) return word;\n else{ \n s.push(word[i]);\n i++;\n }\n }\n s.push(word[i]); \n \n string s1 = "";\n \n while(!s.empty()){ \n s1 += s.top();\n s.pop();\n }\n \n string s2 = "";\n for(int j = i+1 ;j<word.size(); j++){\n s2 += word[j];\n }\n\t\t\n string str = s1 + s2; \n return str;\n }\n};\n\n\n\t\t\t\t\t\t\t\t\t----Approach 2 (Reverse Function)----\n\n\n\tclass Solution {\n\tpublic:\n\t\tstring reversePrefix(string word, char ch) {\n\t\t reverse(word.begin() , word.begin() + word.find(ch)+1);\n\t\t\t\treturn word;\n\t\t}\n\t};\n\n// plzz upvote if you like this solution :) | 4 | 0 | ['Stack', 'C', 'C++'] | 1 |
reverse-prefix-of-word | c++ simple one line code | c-simple-one-line-code-by-sailakshmi1-0x70 | ```\nclass Solution {\npublic:\n string reversePrefix(string word, char ch) {\n int j=0;\n for(int i=0;i<word.size();i++){\n if(word[i]= | sailakshmi1 | NORMAL | 2022-06-18T08:41:16.997662+00:00 | 2022-06-18T08:41:16.997703+00:00 | 251 | false | ```\nclass Solution {\npublic:\n string reversePrefix(string word, char ch) {\n int j=0;\n for(int i=0;i<word.size();i++){\n if(word[i]==ch){\n reverse(word.begin(),word.begin()+i+1);\n break;\n }\n }\n return word;\n }\n}; | 4 | 0 | ['C'] | 1 |
reverse-prefix-of-word | Python 3 (25ms) | One Line Solution | Faster than 95% | Easy to Understand | python-3-25ms-one-line-solution-faster-t-6sla | \nclass Solution:\n def reversePrefix(self, word: str, ch: str) -> str:\n if ch not in word:\n return word\n return (\'\'.join(rever | MrShobhit | NORMAL | 2022-01-25T17:24:59.420287+00:00 | 2022-01-25T17:24:59.420331+00:00 | 545 | false | ```\nclass Solution:\n def reversePrefix(self, word: str, ch: str) -> str:\n if ch not in word:\n return word\n return (\'\'.join(reversed(word[:(word.index(ch)+1)]))+word[(word.index(ch))+1:])\n``` | 4 | 0 | ['String', 'Python', 'Python3'] | 4 |
reverse-prefix-of-word | [JavaScript] one line solution (86%,35%) | javascript-one-line-solution-8635-by-053-xz0d | Runtime: 76 ms, faster than 86.18% of JavaScript online submissions for Reverse Prefix of Word.\nMemory Usage: 38.9 MB, less than 35.53% of JavaScript online su | 0533806 | NORMAL | 2021-09-15T02:25:40.756831+00:00 | 2021-09-15T02:25:40.756869+00:00 | 641 | false | Runtime: 76 ms, faster than 86.18% of JavaScript online submissions for Reverse Prefix of Word.\nMemory Usage: 38.9 MB, less than 35.53% of JavaScript online submissions for Reverse Prefix of Word.\n```\nvar reversePrefix = function(word, ch) {\n return word.indexOf(ch) !== -1 ? word.split("").slice(0, word.indexOf(ch) + 1).reverse().join("") + word.slice(word.indexOf(ch) + 1) : word;\n};\n``` | 4 | 0 | ['JavaScript'] | 2 |
reverse-prefix-of-word | C++ Simple and Easy 2-Line Solution, 0ms Faster than 100% | c-simple-and-easy-2-line-solution-0ms-fa-q8ym | We find the index of the first accurance of the char in word, then we use built-in function reverse which accepts a range to reverse.\n\nclass Solution {\npubli | yehudisk | NORMAL | 2021-09-13T14:34:55.396312+00:00 | 2021-09-13T14:34:55.396354+00:00 | 192 | false | We find the index of the first accurance of the char in word, then we use built-in function `reverse` which accepts a range to reverse.\n```\nclass Solution {\npublic:\n string reversePrefix(string word, char ch) {\n reverse(word.begin(), word.begin() + word.find(ch) + 1);\n return word;\n }\n};\n```\n**Like it? please upvote!** | 4 | 0 | ['C'] | 0 |
reverse-prefix-of-word | Python 3, straightforward | python-3-straightforward-by-silvia42-pwo9 | We are iterating over the string word until character ch is found.\nWe return reversed slice plus leftover from the string word.\n\nclass Solution:\n def rev | silvia42 | NORMAL | 2021-09-12T04:05:37.842968+00:00 | 2021-09-12T05:37:15.328076+00:00 | 357 | false | We are iterating over the string ```word``` until character ```ch``` is found.\nWe return reversed slice plus leftover from the string ```word```.\n```\nclass Solution:\n def reversePrefix(self, word: str, ch: str) -> str:\n for i in range(len(word)):\n if word[i]==ch:\n return word[:i+1][::-1]+word[i+1:]\n return word\n```\nOne Liner:\n```\nclass Solution:\n def reversePrefix(self, word: str, ch: str) -> str:\n return word[:word.find(ch)+1][::-1] + word[word.find(ch)+1:]\n```\n | 4 | 1 | [] | 2 |
reverse-prefix-of-word | beats 100% simple solution | beats-100-simple-solution-by-harshjat-x8uy | IntuitionThe problem requires reversing the prefix of the given string word up to the first occurrence of the character ch. A natural approach is to iterate thr | harshjat | NORMAL | 2025-03-03T09:46:42.869870+00:00 | 2025-03-03T09:46:42.869870+00:00 | 49 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
The problem requires reversing the prefix of the given string word up to the first occurrence of the character ch. A natural approach is to iterate through the string, identify the first occurrence of ch, and reverse the substring from the beginning to that position. Using a stack is one way to achieve this.
# Approach
<!-- Describe your approach to solving the problem. -->
Use a Stack for Reversing the Prefix
Iterate through word, pushing characters onto a stack until we find ch.
Store the remaining part of the string separately.
Reconstruct the Result
Pop elements from the stack to form the reversed prefix.
Append the rest of the string to this reversed prefix.
Edge Cases Considered
If ch is not found, return word as it is.
If ch is the first character, the result is the same as word.
If ch is at the end of the string, the whole string gets reversed.
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
o(n)
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
o(n)

# Code
```cpp []
class Solution {
public:
string reversePrefix(string word, char ch) {
string s="",t="";
stack<char> st;
bool found = false;
for(char cah: word){
if(found){
s = s+cah;
}
else{
if(cah==ch){
found =true;
st.push(cah);
}
else{
st.push(cah);
}
}
}
while(!st.empty()){
t = t+st.top();
st.pop();
}
if(!found){
return word;
}
return t+s;
}
};
``` | 3 | 0 | ['C++'] | 0 |
reverse-prefix-of-word | Real Solution using stack | real-solution-using-stack-by-piero24-r8h8 | Complexity\n- Time complexity: O(n)\n\n- Space complexity: O(n)\n\n# Code\npython3 []\nclass Solution:\n def reversePrefix(self, word: str, ch: str) -> str:\ | Piero24 | NORMAL | 2024-09-27T13:48:54.903768+00:00 | 2024-09-27T13:48:54.903788+00:00 | 142 | false | # Complexity\n- Time complexity: $$O(n)$$\n\n- Space complexity: $$O(n)$$\n\n# Code\n```python3 []\nclass Solution:\n def reversePrefix(self, word: str, ch: str) -> str:\n head, stack = "", []\n for i, e in enumerate(word):\n if e == ch:\n head = e\n word = word[i+1:]\n break\n stack.append(e)\n\n if head == "": return word\n while stack: head = head + stack.pop()\n return head + word\n```\n\n```java []\nclass Solution {\n public String reversePrefix(String word, char ch) {\n StringBuilder head = new StringBuilder();\n StringBuilder stack = new StringBuilder();\n \n for (int i = 0; i < word.length(); i++) {\n char e = word.charAt(i);\n if (e == ch) {\n head.append(e);\n word = word.substring(i + 1);\n break;\n }\n stack.append(e);\n }\n\n // If the character was not found, return the original word\n if (head.length() == 0) return word;\n\n // Reverse the stack and append it to the head\n return head.append(stack.reverse()).append(word).toString();\n }\n}\n```\n\n```cpp []\n#include <string>\n#include <stack>\n\nclass Solution {\npublic:\n std::string reversePrefix(std::string word, char ch) {\n std::string head = "";\n std::stack<char> stack;\n\n for (int i = 0; i < word.size(); i++) {\n char e = word[i];\n if (e == ch) {\n head += e;\n word = word.substr(i + 1);\n break;\n }\n stack.push(e);\n }\n\n // If the character was not found, return the original word\n if (head.empty()) return word;\n\n // Reverse the stack and append it to the head\n while (!stack.empty()) {\n head += stack.top();\n stack.pop();\n }\n \n return head + word;\n }\n};\n``` | 3 | 0 | ['Stack', 'C++', 'Java', 'Python3'] | 0 |
reverse-prefix-of-word | Beats 100.00% of users with C++ || Step By Step Explain || Easy To Understand || | beats-10000-of-users-with-c-step-by-step-8e05 | Abhiraj Pratap Singh\n\n---\n\n# if you like the solution please UPVOTE it....\n\n\n---\n\n# Intuition\n- The problem seems to involve reversing a substring of | abhirajpratapsingh | NORMAL | 2024-05-02T16:59:15.122512+00:00 | 2024-05-02T16:59:15.122546+00:00 | 13 | false | # Abhiraj Pratap Singh\n\n---\n\n# if you like the solution please UPVOTE it....\n\n\n---\n\n# Intuition\n- The problem seems to involve reversing a substring of a given string starting from the beginning up to the occurrence of a specified character.\n\n---\n\n\n\n---\n\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- Define a function reverse to reverse a substring of a given string up to a specified index.\n- Iterate through the string and find the index of the specified character.\n- If the character is found, call the reverse function to reverse the substring up to that index.\nReturn the modified string.\n\n\n---\n\n# Complexity\n- **Time complexity :**\n - Finding the index of the specified character takes O(n) time in the worst case, where n is the length of the string.\n - Reversing the substring takes O(n/2) time.\n - Overall, the time complexity is O(n).\n\n--- \n- **Space complexity :**\n - We use O(1) extra space.\n - Overall, the space complexity is O(1).\n\n---\n\n\n# Code\n```\nclass Solution {\npublic:\n string reverse ( string word , int last )\n {\n int start = 0 ; \n while ( start < last )\n {\n swap ( word[start] , word[last] ) ;\n start++ ;\n last-- ;\n }\n return word ;\n }\n string reversePrefix(string word, char ch)\n {\n for ( int i = 0 ; i < word.length() ; i++ )\n {\n if ( word[i] == ch )\n return reverse ( word , i ) ;\n }\n return word ;\n }\n};\n```\n\n---\n\n# if you like the solution please UPVOTE it....\n\n\n---\n\n\n\n\n\n\n\n\n----\n\n----\n | 3 | 0 | ['Two Pointers', 'String', 'C++'] | 0 |
reverse-prefix-of-word | Reverse prefix of word cpp soltuion 0ms run time | reverse-prefix-of-word-cpp-soltuion-0ms-qv7bh | \n\n\n\n# Intuition\nThis problem involves reversing a substring of a given string up to a specified character. The intuition here is to iterate through the str | Pratham_2521 | NORMAL | 2024-05-01T08:10:08.842448+00:00 | 2024-05-01T08:10:08.842480+00:00 | 30 | false | \n[](https://leetcode.com/problems/reverse-prefix-of-word/submissions/1246206292/)\n\n\n# Intuition\nThis problem involves reversing a substring of a given string up to a specified character. The intuition here is to iterate through the string until we find the target character. Once we encounter the target character for the first time, we reverse the substring from the beginning of the string up to that character.\n\n---\n\n\n# Approach\n\n- Initialize an empty string ans to store the result.\n- Iterate through the characters of the input string word.\n- If the current character matches the target character ch and it\'s the first occurrence (one is true), append it to the result string ans.\n- If the target character is found, reverse the substring in ans up to that point.\n- Return the modified string ans.\n\n---\n\n\n# Complexity\n- **Time** **complexity**: O(n), where n is the length of the input string word. This is because we traverse the string only once to find the target character and perform constant-time operations within the loop.\n\n- **Space** ****complexity****: O(n), where n is the length of the input string word. The space complexity is dominated by the space used to store the result string ans, which can grow up to the size of the input string.\n# Code\n```\nclass Solution {\npublic:\n string reversePrefix(string word, char ch) {\n string ans="";\n int i = 0;\n int n = word.length();\n bool one = true;\n while(i<n)\n {\n if(word[i] == ch && one)\n {\n ans +=ch;\n int len = ans.length();\n int s = 0 , e = len-1;\n while(s<e)\n {\n swap(ans[s],ans[e]);\n s++;\n e--;\n }\n one = false;\n }\n else{\n ans += word[i];\n }\n i++;\n }\n return ans;\n }\n};\n\n``` | 3 | 0 | ['C++'] | 2 |
reverse-prefix-of-word | ✅Simple Solution || Multiple Approach || Easy Explanation || Beginner Friendly🔥🔥🔥 | simple-solution-multiple-approach-easy-e-h0gv | Intuition\nThe intuition behind this solution is to reverse the prefix of the given string word up to the first occurrence of the character ch. If the character | Sayan98 | NORMAL | 2024-05-01T06:52:06.467123+00:00 | 2024-05-02T05:44:56.251013+00:00 | 246 | false | # Intuition\nThe intuition behind this solution is to reverse the prefix of the given string word up to the first occurrence of the character ch. If the character ch is not present in the string, the entire string is returned unchanged.\n\n# Approach\n- Find the **index** of the first occurrence of the character ch in the string word using the IndexOf method. Store the **index** in the variable **index**.\n- If **index** is -1 (meaning ch is not present in word), return the original string **word**.\n- Convert the string **word** to a character array **wordArr** using the ToCharArray method.\n- Reverse the prefix of **wordArr** up to the index index (inclusive) using the Array.Reverse method.\n- Convert the modified character array **wordArr** back to a string using the **new string(char[])** constructor.\n- Return the modified **string**.\n\n# Complexity\n- Time complexity: **O(n)**\nThe time complexity of the Contains, ToCharArray, Array.Reverse, new string(char[]) method is O(n), where n is the length of the character array wordArr.\n\n- Space complexity: **O(n)**\nWhere n is the length of the input string word.\n\n# Code\n```\npublic class Solution {\n public string ReversePrefix(string word, char ch) {\n var index = word.IndexOf(ch); \n if(index == -1) return word;\n var wordArr = word.ToCharArray();\n Array.Reverse(wordArr, 0, index + 1);\n return new string(wordArr);\n }\n}\n```\n\n# Using StringBuilder\n```\npublic class Solution {\n public string ReversePrefix(string word, char ch) {\n var index = word.IndexOf(ch);\n if(index == -1) return word;\n var builder = new StringBuilder(word);\n var l = 0;\n var r = index;\n\n while(l < r) {\n\n (builder[l], builder[r]) = (builder[r], builder[l]);\n l++; r--;\n }\n return builder.ToString();\n }\n}\n```\n\n\n | 3 | 0 | ['Two Pointers', 'String', 'C#'] | 1 |
reverse-prefix-of-word | Beats 100% C++ solution | with explanantion | beats-100-c-solution-with-explanantion-b-okxg | Approach\n- Iterate over input string till we find required character.\n- Store and reverse string till current index\n- Return by adding it with remaining stri | anupsingh556 | NORMAL | 2024-05-01T06:51:12.135148+00:00 | 2024-05-01T06:51:39.546433+00:00 | 5 | false | # Approach\n- Iterate over input string till we find required character.\n- Store and reverse string till current index\n- Return by adding it with remaining string\n- If no occurence is found we can simply return original string\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(n)\n# Code\n```\nclass Solution {\npublic:\n string reversePrefix(string a, char ch) {\n for(int i=0;i<a.size();i++) {\n if(a[i]==ch) {\n string temp = a.substr(0, i+1);\n reverse(temp.begin(), temp.end());\n return temp + a.substr(i+1);\n }\n }\n return a;\n }\n};\n``` | 3 | 0 | ['C++'] | 0 |
reverse-prefix-of-word | Python | Easy | python-easy-by-khosiyat-f9pt | see the Successfully Accepted Submission\n\n# Code\n\nclass Solution:\n def reversePrefix(self, word: str, ch: str) -> str:\n index = word.find(ch) # | Khosiyat | NORMAL | 2024-05-01T06:48:40.875554+00:00 | 2024-05-01T06:48:40.875591+00:00 | 362 | false | [see the Successfully Accepted Submission](https://leetcode.com/problems/reverse-prefix-of-word/submissions/1246310040/?source=submission-ac)\n\n# Code\n```\nclass Solution:\n def reversePrefix(self, word: str, ch: str) -> str:\n index = word.find(ch) # Find the index of the first occurrence of ch\n if index != -1: # If ch is found\n # Reverse the substring from index 0 to the index of ch\n return word[:index+1][::-1] + word[index+1:]\n else: # If ch is not found\n return word # Return the original word\n \n```\n | 3 | 0 | ['Python3'] | 1 |
reverse-prefix-of-word | Best Solution || Beats 100% || Simplified Approach || O(n) || C++ || | best-solution-beats-100-simplified-appro-gbhd | # Intuition \n\n\n# Approach\n\n\n\nThe approach of the provided code is to reverse the prefix of a given string up to the first occurrence of a specific char | atharvviit | NORMAL | 2024-05-01T06:34:50.696515+00:00 | 2024-05-01T06:34:50.696546+00:00 | 116 | false | <!-- # Intuition -->\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n\nThe approach of the provided code is to reverse the prefix of a given string up to the first occurrence of a specific character. Here\'s a step-by-step breakdown of the approach:\n\n1. **Search for the Character**: The code starts by iterating through the input string `word` to find the index of the first occurrence of the character `ch`. This is done using a loop that goes through each character of the string until it finds `ch`. If `ch` is found, the index is stored in the variable `en`. If `ch` is not found, `en` remains -1.\n\n2. **Reverse the Prefix**: After finding the index `en` of the character `ch`, the code calls the `rev` function to reverse the prefix part of the string from index 0 to `en`, inclusive. This is achieved by passing the substring starting from index 0 to `en` (inclusive) to the `rev` function.\n\n3. **Reverse Function (`rev`)**: The `rev` function takes the starting and ending indices of a substring along with the string itself. It then iterates through the substring and swaps characters from the beginning with characters from the end until it reaches the middle, effectively reversing the substring.\n\n4. **Return Result**: Finally, the modified string with the reversed prefix is returned.\n\nThis approach efficiently reverses the prefix of the string up to the specified character without needing to reverse the entire string.\n\n\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n\nC++ Code :\n```\nclass Solution {\npublic:\n void rev(int st,int en,string &str)\n {\n for(int i=st;i<(en/2);i++)\n {\n swap(str[i],str[en-1-i]);\n }\n return;\n }\n string reversePrefix(string word, char ch) {\n int en=-1;\n int n=word.size();\n for(int i=0;i<n;i++)\n {\n if(word[i]==ch)\n {\n en=i; \n break;\n }\n }\n cout<<en;\n en+=1;\n rev(0,en,word);\n return word;\n }\n};\n```\n\nJAVA Code :\n\n```\nclass Solution {\n public String reversePrefix(String word, char ch) {\n int end = word.indexOf(ch); // Find the index of the first occurrence of \'ch\'\n \n if (end == -1) // If \'ch\' is not found in the word\n return word; // Return the original word\n \n // Convert the string to a char array to make it mutable\n char[] chars = word.toCharArray();\n \n // Reverse the prefix of the string up to the index \'end\'\n int start = 0;\n while (start < end) {\n char temp = chars[start];\n chars[start] = chars[end];\n chars[end] = temp;\n start++;\n end--;\n }\n \n // Convert the char array back to string and return\n return new String(chars);\n }\n}\n\n``` | 3 | 0 | ['Two Pointers', 'String', 'C++', 'Java'] | 0 |
reverse-prefix-of-word | Easy to understand solution CPP, Java and Python | easy-to-understand-solution-cpp-java-and-sk7k | Intuition\n Describe your first thoughts on how to solve this problem. \nApply brute force i.e, do as you are asked to do \n\n# Approach\n Describe your approac | Harshit_PSIT | NORMAL | 2024-05-01T05:14:15.187369+00:00 | 2024-05-01T05:14:15.187401+00:00 | 687 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nApply brute force i.e, do as you are asked to do \n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nAlgrithm to be performed-:\n- Find the index of the given character in the word string\n- Generate a substring from 0 - index +1\n- Generate anoher substring from that index+1 to length of the word\n- reverse the first substring \n- return the concatenated reverse substring and 2nd substring\n\n# Complexity\n- Time complexity: O(n + k + m), where n is the length of the input string word, k is the length of the prefix before ch, and m is the length of the suffix after ch.\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(n), where n is the length of the input string word\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n\n```C++ []\n#include <string>\nusing namespace std;\n\nclass Solution {\npublic:\n string reverse(string s) {\n int i = 0;\n int j = s.length() - 1;\n while (i < j) {\n char temp = s[i];\n s[i] = s[j];\n s[j] = temp;\n i++;\n j--;\n }\n return s;\n }\n \n string reversePrefix(string word, char ch) {\n int i = word.find(ch);\n string s = word.substr(0, i + 1);\n string temp = "";\n if (i + 1 < word.length()) {\n temp = word.substr(i + 1);\n }\n s = reverse(s);\n return s + temp;\n }\n};\n\n```\n```Java []\nclass Solution {\n public String reverse(String s){\n char ch[]=s.toCharArray();\n int i=0;int j=s.length()-1;\n while(i<j){\n char temp=ch[i];\n ch[i]=ch[j];\n ch[j]=temp;\n i++;j--;\n }\n String str=new String(ch);\n return str;\n }\n public String reversePrefix(String word, char ch) {\n int i=word.indexOf(ch);\n String s=word.substring(0,i+1);\n String temp="";\n if(i+1<word.length()){\n temp=word.substring(i+1,word.length());\n }\n s=reverse(s);\n return s+temp;\n }\n}\n```\n```Python []\nclass Solution:\n def reversePrefix(self, word: str, ch: str) -> str:\n i = word.find(ch)\n s = word[:i + 1]\n temp = ""\n if i + 1 < len(word):\n temp = word[i + 1:]\n s = s[::-1]\n return s + temp\n\n\n``` | 3 | 0 | ['Two Pointers', 'String', 'Python', 'C++', 'Java', 'Python3'] | 0 |
reverse-prefix-of-word | ✅ Simple 3 line solution beat 100% 🚀 | simple-3-line-solution-beat-100-by-cs_ba-335x | Code\n\nclass Solution {\npublic:\n string reversePrefix(string word, char ch) {\n int ind = word.find(ch);\n if (ind >= word.size())\n | cs_balotiya | NORMAL | 2024-05-01T04:30:51.316661+00:00 | 2024-05-01T04:31:15.930088+00:00 | 9 | false | # Code\n```\nclass Solution {\npublic:\n string reversePrefix(string word, char ch) {\n int ind = word.find(ch);\n if (ind >= word.size())\n return word; // IF CH IS NOT IN WORD;\n reverse(word.begin(), word.begin() + (ind + 1)); // REVERSE FROM STARTING TO POSITION OF CH +1;\n return word;\n }\n};\n\n``` | 3 | 0 | ['Two Pointers', 'String', 'C++'] | 0 |
reverse-prefix-of-word | 🍉0ms||✅Beats 100%🔥|| Beginner friendly || Explained🙌 | 0msbeats-100-beginner-friendly-explained-i2f3 | Intuition\nNothing but we just traverse whole string until we find given ch in word\n\n# Approach\n1) Intialize index = 0; //for finding index\n2) So first we f | dharmikgohil | NORMAL | 2024-05-01T04:19:01.434942+00:00 | 2024-05-01T04:19:01.434964+00:00 | 207 | false | # Intuition\nNothing but we just traverse whole string until we find given ch in word\n\n# Approach\n1) Intialize index = 0; //for finding index\n2) So first we find the index of ch at which index it occuring in word\n3) If we find that index so we given it to index = i;\n4) Now let\'s create empty string and stores character from index to 0\nin first half of empty string\n5) Now start index from index+1 to word.length() to strores remaing character of word in ans;\n\n\n# Complexity\n- Time complexity:\n $$O(n)$$ //because we traverse whole string to find ch in word\n\n- Space complexity:\n$$O(n)$$\n\n# Code\n<!-- ```\nclass Solution {\n public String reversePrefix(String word, char ch) {\n StringBuilder ans = new StringBuilder();\n int index = 0;\n for(int i=0;i<word.length();i++){\n if(word.charAt(i)==ch){\n index = i;\n break;\n }\n }\n\n if(index!=0){\n for(int i=index;i>=0;i--){\n ans.append(word.charAt(i));\n }\n for(int i=index+1;i<word.length();i++){\n ans.append(word.charAt(i));\n }\n }\n return index==0?word:ans.toString();\n }\n}\n``` -->\n```Java []\nclass Solution {\n public String reversePrefix(String word, char ch) {\n StringBuilder ans = new StringBuilder();\n int index = 0;\n for(int i=0;i<word.length();i++){\n if(word.charAt(i)==ch){\n index = i;\n break;\n }\n }\n\n if(index!=0){ //only if index of ch found in index\n for(int i=index;i>=0;i--){\n ans.append(word.charAt(i));\n }\n for(int i=index+1;i<word.length();i++){\n ans.append(word.charAt(i));\n }\n }\n return index==0?word:ans.toString(); //if no index found return word itself\n }\n}\n```\n```C++ []\n#include <iostream>\n#include <string>\n\nclass Solution {\npublic:\n std::string reversePrefix(std::string word, char ch) {\n std::string ans;\n int index = 0;\n for(int i = 0; i < word.length(); i++){\n if(word[i] == ch){\n index = i;\n break;\n }\n }\n\n if(index != 0){ //only if index of ch found in index\n for(int i = index; i >= 0; i--){\n ans += word[i];\n }\n for(int i = index + 1; i < word.length(); i++){\n ans += word[i];\n }\n }\n return index == 0 ? word : ans;\n }\n};\n\n```\n```Python []\nclass Solution:\n def reversePrefix(self, word: str, ch: str) -> str:\n ans = ""\n index = 0\n for i in range(len(word)):\n if word[i] == ch:\n index = i\n break\n\n if index != 0: \n for i in range(index, -1, -1):\n ans += word[i]\n for i in range(index + 1, len(word)):\n ans += word[i]\n\n return word if index == 0 else ans\n\n```\n\n# Ab yaha tak aa gaye ho to UPVOTE bhi kar hi do\uD83D\uDE05\uD83D\uDC4D\n\n## And milte he kal, Thanks for reading....... (Leetcode Outro\uD83C\uDFB5\uD83C\uDFB6\uD83C\uDF9A\uFE0F\uD83C\uDFA7)\n\n\n | 3 | 0 | ['String', 'Python', 'C++', 'Java'] | 0 |
reverse-prefix-of-word | Full Detailed Explanation 🔥✅ | full-detailed-explanation-by-shivakumar1-knvo | Intuition\nSimple brute force, find the index of ch and just reverse from 0 to chth index.\n# Code Explanation\n\n\n - Two integer variables left and right are | shivakumar1 | NORMAL | 2024-05-01T03:09:29.498930+00:00 | 2024-05-01T03:09:29.498954+00:00 | 555 | false | # Intuition\nSimple brute force, find the index of `ch` and just reverse from 0 to `ch`th index.\n# Code Explanation\n\n\n - Two integer variables `left` and `right` are initialized to 0 and the index of the first occurrence of character `ch` in the string `word`, respectively.\n - A `StringBuilder` named `sb` is initialized with the content of the string `word`.\n\n - A `while` loop is initiated with the condition `left < right`, which ensures that the reversal occurs only within the segment delimited by `left` and `right`.\n - Inside the loop, character at index `left` is stored in a temporary variable `temp`.\n - Character at index `left` is set to the character at index `right`, and vice versa, effectively swapping the characters.\n - `left` is incremented and `right` is decremented to move towards the center of the segment.\n\n - After the reversal is complete, the content of the `StringBuilder` is converted back to a string using `toString()` method and returned.\n# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public String reversePrefix(String word, char ch) {\n int left = 0;\n int right = word.indexOf(ch);\n StringBuilder sb = new StringBuilder(word);\n while(left < right){\n char temp = sb.charAt(left);\n sb.setCharAt(left, sb.charAt(right));\n sb.setCharAt(right,temp);\n left++;\n right--;\n }\n\n return sb.toString();\n }\n}\n```\n# Follow me on LinkedIn https://www.linkedin.com/in/shivakumar139/\n# If you found this helpful, Please Upvote it \u2764\uFE0F\n\n\n | 3 | 0 | ['Two Pointers', 'String', 'Java'] | 1 |
reverse-prefix-of-word | Beginner friendly Easy JAVA solution🚀 | beginner-friendly-easy-java-solution-by-anjih | Intuition\nThe approach involves finding the index of the first occurrence of the given character ch in the string word. If the index is greater than 0, reverse | parthiv_77 | NORMAL | 2024-02-04T06:01:40.543075+00:00 | 2024-02-04T06:01:40.543101+00:00 | 123 | false | # Intuition\nThe approach involves finding the index of the first occurrence of the given character ch in the string word. If the index is greater than 0, reverse the substring from the beginning of the word up to that index, and concatenate it with the remaining portion of the word.\n\n# Approach\nFind the index of the first occurrence of character ch using the firstOccurrence helper function.\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(n)\n\n# Code\n```\nclass Solution {\n private int firstOccurence(String s, char ch){\n for(int i = 0; i < s.length(); i++){\n if(s.charAt(i) == ch) return i;\n }\n return -1;\n }\n public String reversePrefix(String word, char ch) {\n int index = firstOccurence(word, ch);\n\n if(index > 0){\n String ans = "";\n for(int i = index; i >= 0; i--){\n ans += word.charAt(i);\n }\n return ans + word.substring(index + 1);\n }\n return word;\n }\n}\n``` | 3 | 0 | ['Java'] | 0 |
reverse-prefix-of-word | Simple Solution | simple-solution-by-adwxith-wgtg | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | adwxith | NORMAL | 2023-11-15T15:03:36.875883+00:00 | 2023-11-15T15:03:36.875912+00:00 | 198 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n/**\n * @param {string} word\n * @param {character} ch\n * @return {string}\n */\nvar reversePrefix = function(word, ch) {\n word.split(\'\')\n let i=word.indexOf(ch)\n \n return word.slice(0,i+1).split(\'\').reverse().join(\'\') + word.slice(i+1)\n};\n``` | 3 | 0 | ['JavaScript'] | 1 |
reverse-prefix-of-word | ✅Just in 3 lines | 0ms | Easy Approach | just-in-3-lines-0ms-easy-approach-by-ash-ek4e | Intuition\nWe just need the index of the character \'ch\', then just reverse the order from beginning to the end. That\'s it!!\n\n# Approach\nI\'m getting the i | ashitoshsable07 | NORMAL | 2023-06-08T21:29:33.640698+00:00 | 2023-06-08T21:29:33.640728+00:00 | 253 | false | # Intuition\nWe just need the **index** of the character \'ch\', then just reverse the order from beginning to the end. That\'s it!!\n\n# Approach\nI\'m getting the index of the character \'ch\' by using find function after that I\'m reversing the string from word.begin() to that index of ch.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n string reversePrefix(string word, char ch) {\n int index=word.find(ch);\n reverse(word.begin(),word.end()-(word.size()-index-1)); \n return word;\n }\n};\n``` | 3 | 0 | ['C++'] | 1 |
reverse-prefix-of-word | Java Easy Solution | 0 ms - 100% beats | java-easy-solution-0-ms-100-beats-by-ako-l0vd | Approach\n Describe your approach to solving the problem. \n1. Find the index of the first occurrence of the character \'ch\' in the given string \'word\' using | akobirswe | NORMAL | 2023-05-30T13:53:34.094454+00:00 | 2023-05-30T13:53:34.094484+00:00 | 283 | false | # Approach\n<!-- Describe your approach to solving the problem. -->\n1. Find the index of the first occurrence of the character \'ch\' in the given string \'word\' using the `indexOf` method. If the character is not found (index is -1), return the original string \'word\' since there is nothing to reverse.\n2. Create a character array \'res\' of size (i + 1), where \'i\' is the index found in the previous step. This array will store the reversed segment of the string.\n3. Iterate from \'i\' to 0 using a loop and for each iteration, assign the characters from the original string \'word\' in reverse order to the \'res\' array. The index difference between \'i\' and \'j\' is used to determine the correct index in the \'res\' array.\n4. Convert the character array \'res\' into a string using the `String` constructor and concatenate it with the remaining part of the original string \'word\' starting from index \'i + 1\'.\n5. Return the resulting string as the reversed prefix.\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public String reversePrefix(String word, char ch) {\n int i = word.indexOf(ch);\n if (i == -1) return word;\n char[] res = new char[i + 1];\n for (int j = i; j > -1; j--)\n res[i - j] = word.charAt(j);\n return new String(res) + word.substring(i + 1);\n }\n}\n``` | 3 | 0 | ['Array', 'Two Pointers', 'String', 'Java'] | 1 |
reverse-prefix-of-word | C# easy | c-easy-by-ghmarek-bi0m | Code\n\npublic class Solution {\n public string ReversePrefix(string word, char ch) {\n\n char[] tempCharArr = word.ToArray();\n\n Array.Revers | GHMarek | NORMAL | 2023-04-24T16:32:05.038599+00:00 | 2023-04-24T16:32:05.038632+00:00 | 39 | false | # Code\n```\npublic class Solution {\n public string ReversePrefix(string word, char ch) {\n\n char[] tempCharArr = word.ToArray();\n\n Array.Reverse(tempCharArr, 0, word.IndexOf(ch) + 1);\n\n return new string(tempCharArr);\n \n }\n}\n``` | 3 | 0 | ['C#'] | 0 |
reverse-prefix-of-word | Go easy solution | go-easy-solution-by-azizjon003-glh1 | \n# Complexity\n- Time complexity:59%\n Add your time complexity here, e.g. O(n) \n\n- Space complexity:70%\n Add your space complexity here, e.g. O(n) \n\n# Co | Azizjon003 | NORMAL | 2023-04-12T08:48:16.737121+00:00 | 2023-04-12T08:48:16.737163+00:00 | 199 | false | \n# Complexity\n- Time complexity:59%\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:70%\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nfunc reversePrefix(word string, ch byte) string {\n a := []byte(word)\n\n for i := 0; i < len(word); i++ {\n if word[i] == ch {\n for j := 0; j <= i/2; j++ {\n temp := a[j]\n a[j] = a[i-j]\n a[i-j] = temp\n }\n\n return string(a)\n }\n }\n\n return word\n}\n\n``` | 3 | 0 | ['Array', 'String', 'Go'] | 1 |
reverse-prefix-of-word | Easy Python3 Solution | easy-python3-solution-by-smisuol-s34b | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | smisuol | NORMAL | 2023-02-05T04:55:53.023500+00:00 | 2023-02-05T04:56:23.629684+00:00 | 621 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(N)\n<!-- Add your space complexity here, e.g. $$O(n)$$ --> \n\n# Code\n```\nclass Solution:\n def reversePrefix(self, word: str, ch: str) -> str:\n if ch not in word:\n return word\n s = list(word)\n start = end = 0\n n = len(word)\n while end < n and s[end] != ch:\n end += 1\n while start < end:\n s[start], s[end] = s[end], s[start]\n start += 1\n end -= 1\n return "".join(s) \n``` | 3 | 0 | ['Python3'] | 2 |
reverse-prefix-of-word | Beats 99.38% | beats-9938-by-codequeror-xlcw | Upvote it :)\n\nclass Solution:\n def reversePrefix(self, word: str, ch: str) -> str:\n try:\n idx = word.index(ch)\n w = word[: | Codequeror | NORMAL | 2023-01-21T14:14:08.418562+00:00 | 2023-01-21T14:14:08.418603+00:00 | 624 | false | # Upvote it :)\n```\nclass Solution:\n def reversePrefix(self, word: str, ch: str) -> str:\n try:\n idx = word.index(ch)\n w = word[:idx + 1]\n return w[::-1] + word[idx + 1:]\n except: return word\n``` | 3 | 1 | ['Python', 'Python3'] | 0 |
reverse-prefix-of-word | JAVA || TWO POINTER APPROACH || BEATS 96% | java-two-pointer-approach-beats-96-by-sh-fdd0 | \n\n# Code\n\nclass Solution {\n public String reversePrefix(String word, char ch) {\n char[] array = word.toCharArray();\n int i = 0;\n | sharforaz_rahman | NORMAL | 2022-12-05T17:56:06.705542+00:00 | 2022-12-05T17:56:06.705578+00:00 | 808 | false | \n\n# Code\n```\nclass Solution {\n public String reversePrefix(String word, char ch) {\n char[] array = word.toCharArray();\n int i = 0;\n int j = word.length();\n int index = 0;\n while (i < j) {\n if (array[i] == ch) {\n index = i;\n break;\n }\n i++;\n }\n boolean b = index != 0;\n if (b) {\n int x = 0;\n int y = array.length;\n while (x < index) {\n char temp = array[x];\n array[x] = array[index];\n array[index] = temp;\n x++;\n index--;\n }\n return(String.valueOf(array));\n } else {\n return(word);\n }\n }\n}\n``` | 3 | 0 | ['Java'] | 1 |
reverse-prefix-of-word | Java Two pointers approach(1ms) | java-two-pointers-approach1ms-by-amrishr-3qg4 | public String reversePrefix(String word, char ch) {\n int start=0;\n char[] temp=word.toCharArray();\n for(int end=0;end<temp.length;end++) | AmrishRaaj | NORMAL | 2022-10-31T05:04:52.531531+00:00 | 2022-10-31T05:04:52.531571+00:00 | 653 | false | public String reversePrefix(String word, char ch) {\n int start=0;\n char[] temp=word.toCharArray();\n for(int end=0;end<temp.length;end++)\n {\n if(temp[end]==ch)\n {\n while(start<end)\n {\n char tempS=temp[start];\n temp[start]=temp[end];\n temp[end]=tempS;\n start++;\n end--;\n }\n break;\n }\n }\n return new String(temp);\n } | 3 | 0 | ['Java'] | 1 |
reverse-prefix-of-word | Javascript O(N) - One Iteration | javascript-on-one-iteration-by-videshgho-vb00 | \n/**\n * @param {string} word\n * @param {character} ch\n * @return {string}\n */\nvar reversePrefix = function(word, ch) {\n const index = word.indexOf(ch | videshghodarop | NORMAL | 2022-10-06T14:04:56.108354+00:00 | 2022-10-06T14:04:56.108394+00:00 | 358 | false | ```\n/**\n * @param {string} word\n * @param {character} ch\n * @return {string}\n */\nvar reversePrefix = function(word, ch) {\n const index = word.indexOf(ch);\n if (index === -1) return word;\n let result = \'\';\n\n for (let i = 0; i < word.length; i++) {\n if (i <= index) {\n result = word[i] + result;\n } else {\n result += word[i];\n }\n }\n\n return result;\n};\n``` | 3 | 0 | ['JavaScript'] | 0 |
reverse-prefix-of-word | Python Easy Solution in 5 Lines | python-easy-solution-in-5-lines-by-pulki-whm1 | \nclass Solution:\n def reversePrefix(self, word: str, ch: str) -> str:\n if ch not in word:\n return word\n i=word.index(ch)\n | pulkit_uppal | NORMAL | 2022-10-02T13:56:22.422498+00:00 | 2022-10-02T13:56:22.422539+00:00 | 503 | false | ```\nclass Solution:\n def reversePrefix(self, word: str, ch: str) -> str:\n if ch not in word:\n return word\n i=word.index(ch)\n word=word[i::-1]+word[i+1:]\n return word\n``` | 3 | 0 | ['Python'] | 2 |
reverse-prefix-of-word | c++ easy | c-easy-by-sailakshmi1-4sm5 | ```\nclass Solution {\npublic:\n string reversePrefix(string word, char ch) {\n int j=0;\n int n=word.length();\n for(int i=0;i<n;i++){\ | sailakshmi1 | NORMAL | 2022-06-15T14:15:02.983243+00:00 | 2022-06-15T14:15:43.256753+00:00 | 136 | false | ```\nclass Solution {\npublic:\n string reversePrefix(string word, char ch) {\n int j=0;\n int n=word.length();\n for(int i=0;i<n;i++){\n if(word[i]==ch){\n reverse(word.begin(),word.begin()+i+1);\n break;\n }\n }\n return word;\n }\n}; | 3 | 0 | ['C'] | 0 |
reverse-prefix-of-word | java 76% easy to understand! | java-76-easy-to-understand-by-m_israilov-evvi | \n\nclass Solution {\n public String reversePrefix(String word, char ch) {\n Integer a = word.indexOf(ch + "");\n StringBuilder b = new | m_israilovv | NORMAL | 2022-05-22T16:14:02.522223+00:00 | 2022-05-22T16:14:11.461870+00:00 | 88 | false | ```\n\n```class Solution {\n public String reversePrefix(String word, char ch) {\n Integer a = word.indexOf(ch + "");\n StringBuilder b = new StringBuilder(word.substring(0, a + 1));\n return b.reverse() + word.substring(a + 1, word.length());\n }\n} | 3 | 0 | [] | 2 |
reverse-prefix-of-word | Smart & fastest java solution using substring and without any loop 3 line code. 0 ms | smart-fastest-java-solution-using-substr-t1xi | \nclass Solution {\n public String reversePrefix(String word, char ch) \n {\n StringBuilder s = new StringBuilder();\n int index = word.inde | saurabh_173 | NORMAL | 2022-02-23T15:28:54.070531+00:00 | 2022-02-23T15:28:54.070574+00:00 | 196 | false | ```\nclass Solution {\n public String reversePrefix(String word, char ch) \n {\n StringBuilder s = new StringBuilder();\n int index = word.indexOf(ch);\n s.append(word.substring(0,index+1));\n s.reverse();\n s.append(word.substring(index+1));\n return s.toString();\n }\n}\n```\nUpvote if you like the solution | 3 | 0 | ['String', 'Java'] | 0 |
reverse-prefix-of-word | [Python3/Golang] Easy to understand | python3golang-easy-to-understand-by-frol-ae78 | First of all we want to check if there is a ch in the word, then we have to return ch index plus 1, reverse the order and add the remainder of the word unchange | frolovdmn | NORMAL | 2021-09-15T08:43:59.331564+00:00 | 2025-01-19T14:37:37.689396+00:00 | 136 | false | First of all we want to check if there is a **ch** in the **word**, then we have to return **ch** index plus 1, reverse the order and add the remainder of the **word** unchanged
```python []
class Solution:
def reversePrefix(self, word: str, ch: str) -> str:
return word[:word.index(ch) + 1][::-1] + word[word.index(ch) + 1:] if ch in word else word
```
```golang []
func reversePrefix(word string, ch byte) string {
if strings.Contains(word, string(ch)) == true {
return reverse(word[:index(word, rune(ch)) + 1]) + word[index(word, rune(ch)) + 1:]
} else {
return word
}
}
func index(str string, char rune) int {
for idx, val := range(str) {
if val == char {
return idx
}
}
return -1
}
func reverse(str string) string {
runes := []rune(str)
for i, j := 0, len(runes) - 1; i < j; i, j = i + 1, j - 1 {
runes[i], runes[j] = runes[j], runes[i]
}
return string(runes)
}
``` | 3 | 0 | ['Python', 'Go', 'Python3'] | 0 |
reverse-prefix-of-word | C++ very easy solution | c-very-easy-solution-by-pk_87-oapj | ```\nclass Solution {\npublic:\n string reversePrefix(string word, char ch) {\n \n int index=word.find(ch);\n if(index == -1)\n | pawan_mehta | NORMAL | 2021-09-12T04:09:27.889522+00:00 | 2021-09-12T04:09:27.889549+00:00 | 128 | false | ```\nclass Solution {\npublic:\n string reversePrefix(string word, char ch) {\n \n int index=word.find(ch);\n if(index == -1)\n return word;\n reverse(word.begin(),word.begin()+index+1);\n return word;\n }\n}; | 3 | 0 | [] | 2 |
reverse-prefix-of-word | 🔥🚀Two Easy Approach💯 || Time --O(n) | two-easy-approach-time-on-by-0xjwuvdyfc-h4eb | Reverse Prefix of a WordProblem StatementGiven a string word and a character ch, reverse the prefix of word that ends with ch. If ch does not exist in word, ret | 0XjwUvdYfc | NORMAL | 2025-03-24T07:52:28.629085+00:00 | 2025-03-24T07:52:28.629085+00:00 | 157 | false | ## Reverse Prefix of a Word
### Problem Statement
Given a string `word` and a character `ch`, reverse the prefix of `word` that ends with `ch`. If `ch` does not exist in `word`, return `word` unchanged.
### Approach
1. Use a stack to store characters until we find `ch`.
2. If `ch` is found, reverse the stored characters.
3. Append the remaining characters after the reversed prefix.
4. If `ch` is not found, return the original string.
### Java Solution
```java
import java.util.Stack;
class Solution {
public String reversePrefix(String word, char ch) {
Stack<Character> stack = new Stack<>();
int index = 0, count = 0;
StringBuilder s = new StringBuilder();
for (int i = 0; i < word.length(); i++) {
char ch1 = word.charAt(i);
if (ch1 == ch) {
stack.push(ch1);
index = i + 1;
count++;
break;
} else {
stack.push(ch1);
}
}
if (count == 0) {
return word;
}
while (!stack.isEmpty()) {
s.append(stack.pop());
}
for (int k = index; k < word.length(); k++) {
s.append(word.charAt(k));
}
return s.toString();
}
}
```
### Time and Space Complexity Analysis
#### Time Complexity: **O(n)**
- The loop iterates over the string `word`, which has `n` characters.
- The worst-case scenario is iterating through all `n` characters (when `ch` is the last character or not present).
- Pushing and popping from the stack takes **O(1)** time per operation.
- Thus, the overall time complexity is **O(n)**.
#### Space Complexity: **O(n)**
- In the worst case, the stack stores all `n` characters of `word` before popping them.
- The `StringBuilder` also stores the final result, which takes **O(n)** space.
- Therefore, the space complexity is **O(n)**.
## Approach number --->2
## Reverse Prefix of a Word
### Problem Statement
Given a string `word` and a character `ch`, reverse the prefix of `word` that ends with `ch`. If `ch` does not exist in `word`, return `word` unchanged.
### Approach
1. Find the index of `ch` in `word` using `indexOf(ch)`.
2. If `ch` is not found, return `word` as is.
3. Extract the substring from the start of `word` to `index + 1` and reverse it.
4. Append the remaining part of the word after the reversed prefix.
5. Return the final modified string.
### Java Solution
```java
class Solution {
public String reversePrefix(String word, char ch) {
int index = word.indexOf(ch);
if (index == -1) return word;
StringBuilder sb = new StringBuilder(word.substring(0, index + 1));
sb.reverse();
sb.append(word.substring(index + 1));
return sb.toString();
}
}
```
### Time and Space Complexity Analysis
#### Time Complexity: **O(n)**
- The `indexOf(ch)` operation runs in **O(n)**.
- Creating and reversing the substring takes **O(n)** in the worst case.
- Appending the remaining part of the string also takes **O(n)**.
- Thus, the overall time complexity is **O(n)**.
#### Space Complexity: **O(n)**
- The `StringBuilder` stores the reversed prefix and remaining characters, requiring **O(n)** space.
- The substring operations also create new strings, contributing to **O(n)** space usage.
- Therefore, the overall space complexity is **O(n)**.
| 2 | 0 | ['String', 'Stack', 'Java'] | 0 |
reverse-prefix-of-word | Beats 100% in runtime 🔥| Optimal O(1) solution ⏳| Very Easy Approach ✨ | beats-100-in-runtime-optimal-o1-solution-fa79 | IntuitionThe problem requires reversing a prefix of a given string up to the first occurrence of a specified character. The idea is to locate this character and | Dev_Sh | NORMAL | 2025-03-14T00:00:59.409499+00:00 | 2025-03-14T00:00:59.409499+00:00 | 70 | false | # Intuition
The problem requires reversing a prefix of a given string up to the first occurrence of a specified character. The idea is to locate this character and reverse the portion of the string from the beginning to that index.
# Approach
1. First, check if the character `ch` exists in the string using `word.find(ch)`. If it does not exist, return the original string.
2. Iterate through the string to find the first occurrence of `ch`.
3. Reverse the portion of the string from the start to this index using `reverse(word.begin(), word.begin() + j + 1)`.
4. Return the modified string.
# Complexity
- Time complexity: $$O(n)$$, where `n` is the length of the string. The `find()` function and the `reverse()` operation both run in linear time.
- Space complexity: $$O(1)$$, as we are modifying the string in-place without using extra space.
# Code
```cpp
class Solution {
public:
string reversePrefix(string word, char ch) {
if(word.find(ch) == -1) return word;
int j = 0;
while(word[j] != ch) {
j++;
}
reverse(word.begin(), word.begin() + j + 1);
return word;
}
};
``` | 2 | 0 | ['C++'] | 0 |
reverse-prefix-of-word | beats 100%,super simple python3 code | beats-100super-simple-python3-code-by-pr-5zgk | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | PranaviGuddanti | NORMAL | 2025-02-03T13:53:03.957506+00:00 | 2025-02-03T13:53:03.957506+00:00 | 157 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```python3 []
class Solution:
def reversePrefix(self, word: str, ch: str) -> str:
x=0
for i in range(len(word)):
if word[i]==ch:
x=i+1
break
string=word[0:x]
return string[::-1]+word[x:len(word)]
``` | 2 | 0 | ['Python3'] | 0 |
reverse-prefix-of-word | C++ 100% beating Brute Force | c-100-beating-brute-force-by-itsaditya7-bz3v | null | itsaditya7 | NORMAL | 2024-12-11T07:52:13.530642+00:00 | 2024-12-11T07:52:31.772900+00:00 | 45 | false | # Intuition\nJust find the ch.and reverse the string till the ith index.\n\n# Approach\nStart the code with onw for loop to find the character position from where we want to reverse the string.\n\n# Complexity\n- Time complexity:\nO(MN)\nwhere \nM:number at which the ch is found\n\n- Space complexity:\nO(1)\n\n# Code\n```cpp []\nclass Solution {\npublic:\n string reversePrefix(string word, char ch) {\n int idx=-1;\n for(int i=0;i<word.size();i++)\n {\n if(word[i]==ch)\n {\n idx=i;\n break;\n }\n }\n if(idx==-1)\n return word;\n reverse(word.begin(),word.begin()+idx+1);\n return word;\n }\n};\n```\n\n | 2 | 0 | ['C++'] | 0 |
reverse-prefix-of-word | Effortless Character-Based Prefix Reversal in C++ | effortless-character-based-prefix-revers-4r6q | Intuition\n\nWhen thinking about how to reverse a part of a string based on the presence of a specific character, the first thought is to determine the position | MahmoudMohamedElsayed | NORMAL | 2024-10-10T19:04:10.813172+00:00 | 2024-10-10T19:04:10.813201+00:00 | 21 | false | # Intuition\n\nWhen thinking about how to reverse a part of a string based on the presence of a specific character, the first thought is to determine the position of that character. Once the character is found, we can reverse the portion of the string that precedes it. This will allow us to achieve the desired result easily.\n\n# Approach\n\n1-Find the Character: We start by using the find function to locate the specified character in the string.\n2-Check for Existence: If the character is found, we reverse the portion of the string from the beginning up to the position of the character using the reverse function.\n3-Return the String: After reversing the required part, we return the modified string.\n\n# Complexity\n\n- Time complexity:\nO(n) since both the find and reverse functions operate in linear time relative to the length of the string.\n\n- Space complexity:\n O(1) because we do not use any additional data structures that depend on the size of the input.\n\n# Code\n```cpp\nclass Solution {\npublic:\n // Function to reverse the prefix of the string \'word\' up to the character \'ch\'\n string reversePrefix(string word, char ch) {\n // Find the index of the character \'ch\' in the string \'word\'\n auto index = word.find(ch);\n \n // Check if the character was found\n if (index != word.npos) {\n // Reverse the substring from the beginning to the found index (inclusive)\n reverse(word.begin(), word.begin() + index + 1);\n }\n \n // Return the modified string\n return word;\n }\n};\n\n``` | 2 | 0 | ['C++'] | 0 |
reverse-prefix-of-word | easy solution | 100.00% beats | easy-solution-10000-beats-by-q0art-3gfv | \n\ntypescript []\nconst reversePrefix = (string: string, char: string) => {\n const index = string.indexOf(char)\n\n return string.slice(0, index + 1).split( | q0art | NORMAL | 2024-09-24T22:03:57.498754+00:00 | 2024-09-24T22:03:57.498785+00:00 | 45 | false | \n\n```typescript []\nconst reversePrefix = (string: string, char: string) => {\n const index = string.indexOf(char)\n\n return string.slice(0, index + 1).split("").reverse().join("").concat(string.slice(index + 1))\n};\n``` | 2 | 0 | ['TypeScript'] | 0 |
reverse-prefix-of-word | Q. 2000 | ✅Beginner-Friendly Python Code | 4️⃣ lined. | q-2000-beginner-friendly-python-code-4-l-lttx | Intuition\nThe problem asks us to reverse the prefix of a string up to and including the first occurrence of a given character ch. The most efficient approach i | charan1kh | NORMAL | 2024-08-08T16:29:17.798771+00:00 | 2024-09-21T08:01:37.318440+00:00 | 87 | false | # Intuition\nThe problem asks us to reverse the prefix of a string up to and including the first occurrence of a given character ch. The most efficient approach is to locate ch once, reverse the portion of the string up to its index, and then concatenate it with the remaining part of the string.\n\n\n# Approach\n1. Find the index of ch: Use the find() method to locate the first occurrence of ch in the string word. If ch is found, it will return the index; otherwise, it will return -1.\n2. Slice and Reverse: If ch is found, slice the string from the beginning to the index of ch, reverse that part, and store it.\n3. Concatenate: Concatenate the reversed substring with the remainder of the string that comes after ch.\n4. Return the result: If ch is not found, return the original string.\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Updated Code, as loop is unnecessary\n```\nclass Solution:\n def reversePrefix(self, word: str, ch: str) -> str:\n idx = word.find(ch) \n if idx != -1: \n part1, part2 = word[:idx+1][::-1], word[idx+1:] \n return part1 + part2 \n return word \n```\n\n```# Old Code```\n\n```\nclass Solution:\n def reversePrefix(self, word: str, ch: str) -> str:\n for i in word:\n part1 = (word[:word.find(ch)+1:])[::-1]\n part2 = word[word.find(ch)+1::]\n return (part1+part2)\n``` | 2 | 0 | ['Python3'] | 2 |
reverse-prefix-of-word | Best and Easy to Understand ✅ || Beats 100% 🎯 | best-and-easy-to-understand-beats-100-by-ynlk | Intuition\n Describe your first thoughts on how to solve this problem. The task requires reversing a part of the string from the start up to and including the f | rckrockerz | NORMAL | 2024-05-23T09:37:10.623796+00:00 | 2024-05-23T09:37:10.623825+00:00 | 39 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->The task requires reversing a part of the string from the start up to and including the first occurrence of a given character. If the character does not exist in the string, the string remains unchanged. The idea is straightforward: find the position of the character, then reverse the substring up to that position.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. **Find the Character Position:** Use the $$find()$$ function to determine the position of the first occurrence of the given character in the string.\n2. **Check if Character Exists:** If the character is not found $$(find() returns -1)$$, return the original string.\n3. **Manual Reversal:**\n - **Initialize two pointers:** one starting at the beginning of the string (`start`) and the other at the found position (`pos`).\n - Swap the characters at these two pointers.\n - Move the `start` pointer forward and the `pos` pointer backward, and continue swapping until the pointers meet or cross each other.\n4. **Return the Result:** After performing the swaps, return the modified string.\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n string reversePrefix(string word, char ch) {\n int pos = word.find(ch);\n if (pos == -1) {\n return word;\n }\n \n int start = 0;\n while (start < pos) {\n char temp = word[start];\n word[start] = word[pos];\n word[pos] = temp;\n start++;\n pos--;\n }\n\n return word;\n }\n};\n``` | 2 | 0 | ['Two Pointers', 'String', 'C++'] | 0 |
reverse-prefix-of-word | JAVA SOLUTION | java-solution-by-deleted_user-q2xe | Code\n\nclass Solution {\n public String reversePrefix(String word, char ch) {\n # initialise strings\n String ans = "";\n String rev = | deleted_user | NORMAL | 2024-05-03T16:04:08.987809+00:00 | 2024-05-03T16:04:08.987837+00:00 | 434 | false | # Code\n```\nclass Solution {\n public String reversePrefix(String word, char ch) {\n # initialise strings\n String ans = "";\n String rev = "";\n # iterate through word and find the character\n int n = word.length();\n for(int i = 0; i < n; i++) {\n if(word.charAt(i) != ch) {\n ans = ans + word.charAt(i);\n } \n else{\n # if found, reverse the ans string\n ans = ans + word.charAt(i);\n for(int j = 0; j < ans.length(); j++) { \n char c = ans.charAt(j); \n rev = c + rev;\n }\n # continue adding the other characters till end\n ans = rev;\n for(int j = i + 1; j < n; j++) {\n ans = ans + word.charAt(j);\n }\n break; \n }\n }\n # return ans\n return ans;\n }\n}\n\n``` | 2 | 0 | ['Java'] | 0 |
reverse-prefix-of-word | Golang beats 100% | golang-beats-100-by-do2358-ju1d | Intuition\n Describe your first thoughts on how to solve this problem. \n- The reversePrefix function iterates through each character of the input word.\n- For | do2358 | NORMAL | 2024-05-02T15:20:03.901615+00:00 | 2024-05-02T15:20:03.901651+00:00 | 66 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n- The reversePrefix function iterates through each character of the input word.\n- For each character at index i, it checks if it matches the target character ch.\n- If a match is found, the function proceeds to reverse the prefix.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- The reverse function is called with the slice of the word from the beginning up to the index of the matched character (inclusive). This slice represents the prefix to be reversed.\n- Inside reverse, the string is converted to a rune slice to handle potentially non-ASCII characters.\n- A classic two-pointer approach is used to swap characters from the beginning and end of the rune slice until they meet in the middle, effectively reversing the slice.\n- The reversed rune slice is converted back to a string and returned.\n\n# Complexity\n- Time complexity: O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(N)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n\n\n\n# Code\n```\nfunc reversePrefix(word string, ch byte) string {\n for i := 0; i < len(word); i++ {\n if word[i] == ch {\n return reverse(word[:i+1]) + word[i+1:]\n }\n }\n return word // ch not found in word\n}\n\nfunc reverse(s string) string {\n runes := []rune(s)\n for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {\n runes[i], runes[j] = runes[j], runes[i]\n }\n return string(runes)\n}\n``` | 2 | 0 | ['Go'] | 0 |
reverse-prefix-of-word | Simple Solution [Faster than 82% Runtime]✅ | simple-solution-faster-than-82-runtime-b-tu7j | Approach\n- Exit function block early, if word does not contain given ch\n- Get the index for ch in the word string\n- Split word into two subsequences, reverse | ProbablyLost | NORMAL | 2024-05-02T12:54:40.377943+00:00 | 2024-05-02T12:57:35.951565+00:00 | 52 | false | # Approach\n- Exit function block early, if `word` does not contain given `ch`\n- Get the `index` for ch in the word string\n- Split word into two subsequences, `reversedFirstPart` and `secondPart`\n- Concatenate and **return** the subsequences\n\n# Code\n```\nclass Solution {\n func reversePrefix(_ word: String, _ ch: Character) -> String {\n // Early exit if no common char\n guard word.contains(ch) else { return word }\n \n let index = word.firstIndex(of: ch)!\n let reversedFirstPart = String(word[...index].reversed())\n let secondPart = word[index...].dropFirst()\n \n return reversedFirstPart + secondPart\n }\n}\n``` | 2 | 0 | ['String', 'Swift'] | 0 |
reverse-prefix-of-word | C++ easiest solution Beats 100% solutions. 2 pointer method | c-easiest-solution-beats-100-solutions-2-tudj | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | _chitransh_9 | NORMAL | 2024-05-01T18:02:50.425590+00:00 | 2024-05-01T18:02:50.425617+00:00 | 193 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n string reversePrefix(string word, char ch) {\n int j=0,f=0;\n for(int i=0;i<word.size();i++){\n //if(word[0]==ch) return word;\n if(word[i]==ch){\n while(j<=i){\n swap(word[i],word[j]);\n j++;\n i--;\n f++;\n }\n if(f!=0) break;\n }\n }\n return word;\n }\n};\n``` | 2 | 0 | ['C++'] | 2 |
monotone-increasing-digits | Simple and very short C++ solution | simple-and-very-short-c-solution-by-zee-3eoc | \nclass Solution {\npublic:\n int monotoneIncreasingDigits(int N) {\n string n_str = to_string(N);\n \n int marker = n_str.size();\n | zee | NORMAL | 2017-12-03T04:22:26.099000+00:00 | 2018-08-16T19:01:56.570651+00:00 | 13,652 | false | ```\nclass Solution {\npublic:\n int monotoneIncreasingDigits(int N) {\n string n_str = to_string(N);\n \n int marker = n_str.size();\n for(int i = n_str.size()-1; i > 0; i --) {\n if(n_str[i] < n_str[i-1]) {\n marker = i;\n n_str[i-1] = n_str[i-1]-1;\n }\n }\n \n for(int i = marker; i < n_str.size(); i ++) n_str[i] = '9';\n \n return stoi(n_str);\n }\n};\n``` | 156 | 5 | [] | 18 |
monotone-increasing-digits | Clean Code | clean-code-by-gracemeng-zzyw | The result should be:\n\npreceding monotone increasing digits (ending digit should decrease by 1) \n\nfollowed by \n\nall remaining digits set to \'9\'\n\n.\n\n | gracemeng | NORMAL | 2018-07-17T07:00:20.750349+00:00 | 2020-08-21T15:33:16.652768+00:00 | 6,270 | false | The result should be:\n```\npreceding monotone increasing digits (ending digit should decrease by 1) \n```\nfollowed by \n```\nall remaining digits set to \'9\'\n```\n.\n\n`e.g. N = 12321, the result is 12299`.\n```\nmonotoneIncreasingEnd is finalized as : 2\ncurrent arrN : 12211\narrN is finalized as : 12299\n```\n****\n```\nclass Solution {\n public int monotoneIncreasingDigits(int N) {\n char[] arrN = String.valueOf(N).toCharArray();\n \n int monotoneIncreasingEnd = arrN.length - 1;\n for (int i = arrN.length - 1; i > 0; i--) {\n if (arrN[i] < arrN[i - 1]) {\n monotoneIncreasingEnd = i - 1;\n arrN[i - 1]--;\n }\n }\n // System.out.println("monotoneIncreasingEnd is finalized as : " + monotoneIncreasingEnd);\n // System.out.println("current arrN : " + new String(arrN));\n for (int i = monotoneIncreasingEnd + 1; i < arrN.length; i++) {\n arrN[i] = \'9\';\n }\n // System.out.println("arrN is finalized as : " + new String(arrN));\n return Integer.parseInt(new String(arrN));\n }\n}\n```\n | 96 | 1 | [] | 8 |
monotone-increasing-digits | Simple Python solution w/ Explanation | simple-python-solution-w-explanation-by-zadha | The idea is to go from the LSB to MSB and find the last digit, where an inversion happens.\nThere are 2 cases to consider:\n\ncase 1:\nIn 14267 , we see that in | Cubicon | NORMAL | 2017-12-03T04:04:22.478000+00:00 | 2018-09-12T07:23:11.031465+00:00 | 7,588 | false | The idea is to go from the LSB to MSB and find the last digit, where an inversion happens.\nThere are 2 cases to consider:\n\ncase 1:\nIn 14267 , we see that inversion happens at 4. In this case, then answer is obtained by reducing 4 to 3, and changing all the following digits to 9. \n=> 13999\n\ncase 2:\n1444267, here eventhough the last inversion happens at the last 4 in 1444, if we reduce it to 3, then that itself breaks the rule. So once we find the last digit where inversion happens, if that digit is repeated, then we have to find the last position of that digit. After that it is same as case1, where we reduce it by 1 and set the remaining digits to 9.\n=> 1399999\n\nThe steps are:\n1) Convert n into num array in reverse order\n2) Find the leftmost position that is inverted and if the inverted character repeats itself, find the leftmost repeated digit. \n3) Fill the digits after inversion as 9\n4) Reduce the digit that caused the inversion by -1\n5) Reverse back the num array and convert to int\n```\ndef monotoneIncreasingDigits(self, N):\n if N < 10: return N\n n, inv_index = N, -1\n num = [int(d) for d in str(n)[::-1]] \n\n for i in range(1, len(num)): \n if num[i] > num[i - 1] or (inv_index != -1 and num[inv_index] == num[i]):\n inv_index = i\n\n if inv_index == -1: return N\n\n for i in range(inv_index): num[i] = 9\n num[inv_index] -= 1\n \n return int(''.join([ str(i) for i in num[::-1]])) \n``` | 64 | 3 | [] | 13 |
monotone-increasing-digits | Simple java solution with clear explanation. Very easy to understand. | simple-java-solution-with-clear-explanat-foaw | \nclass Solution {\n public int monotoneIncreasingDigits(int N) {\n //1. Convert the given integer to character array\n char[] ch = String.valu | sushant_chaudhari | NORMAL | 2018-05-04T00:05:28.074020+00:00 | 2018-05-04T00:05:28.074020+00:00 | 3,623 | false | ```\nclass Solution {\n public int monotoneIncreasingDigits(int N) {\n //1. Convert the given integer to character array\n char[] ch = String.valueOf(N).toCharArray();\n \n //2. Create a integer mark variable and initialize it to the length of the character array \n int mark = ch.length;\n \n //3. Iterate from the end of the array to the beginning of the array.\n //Everytime you find current digit less then previous digit, reduce the previous digit by 1 and set that digit as the mark\n for(int i = ch.length-1;i>0;i--){\n if(ch[i]<ch[i-1]){\n mark = i-1;\n ch[i-1]--;\n }\n }\n \n //4. Set all digits after mark to 9 as we want the highest number.\n //In step 3 we made sure that all digits before mark are in increasing order\n for(int i = mark+1;i<ch.length;i++){\n ch[i] = \'9\';\n }\n return Integer.parseInt(new String(ch));\n }\n}\n```\n | 42 | 2 | [] | 4 |
monotone-increasing-digits | Python, Straightforward Greedy Solution Explained | python-straightforward-greedy-solution-e-9zgs | Let\'s look at a few examples:\n\nInput Output\n55627 -> 55599\n55427 -> 49999\n99996 -> 89999 \n100 -> 99\n\nFrom the | ruxinzzz | NORMAL | 2022-02-12T01:34:18.333730+00:00 | 2022-02-18T20:37:25.571505+00:00 | 1,304 | false | Let\'s look at a few examples:\n```\nInput Output\n55627 -> 55599\n55427 -> 49999\n99996 -> 89999 \n100 -> 99\n```\nFrom the above examples we can see that if a number is **not** monotone increasing digits, we will need to convert as many digits as posible to `9` and decrease the digit before the `9`s by 1. But how to decide which digit to decrease by 1?\n\nIf we try to tranverse the digits from left to right, there are many different cases we need to consider. But if we **tranverse the digits from right to left**, it is very straightforward! Whenever a digit is smaller than a digit to its left, decrease its left digit by 1 and convert all the digits from here until the end to 9. \n\nTo make the digits easy to access, tranverse, and modify, I converted the number into a list of integers.\n\n```\nclass Solution(object):\n def monotoneIncreasingDigits(self, n):\n # First, handle the single-digit cases.\n if n < 10:\n return n\n\n\t\t# Convert the number into a list of integers\n l = []\n for _,c in enumerate(str(n)):\n l.append(int(c))\n n = len(l)\n\n\t\t# Tranverse from right to left \n for i in range(n-1,0,-1):\n if l[i] < l[i-1]:\n l[i-1] -= 1\n for i in range(i,n):\n l[i] = 9\n \n\t\t# Convert the list back to a number\n return int("".join([str(x) for x in l]))\n```\n\nPlease VOTE UP if you find this explanation helpful! | 23 | 0 | ['Greedy', 'Python'] | 3 |
monotone-increasing-digits | cpp simple solution explanation with example beats 100% time and space | cpp-simple-solution-explanation-with-exa-3o0d | Runtime: 0 ms, faster than 100.00% of C++ online submissions for Monotone Increasing Digits.\nMemory Usage: 5.9 MB, less than 100.00% of C++ online submissions | _mrbing | NORMAL | 2020-05-25T12:59:05.879052+00:00 | 2020-05-25T12:59:05.879091+00:00 | 1,554 | false | Runtime: 0 ms, faster than 100.00% of C++ online submissions for Monotone Increasing Digits.\nMemory Usage: 5.9 MB, less than 100.00% of C++ online submissions for Monotone Increasing Digits.\nLogic : any number \'xxxxx..\' a number monotonically increasing largest but smaller than original number will be one less than the point before which every number is monotonically increasing and after that point all places are filled whith 9 to get maximum\n\neg: 5 4 3 7 7 6\n 7 6 if this was our number than 6 9 will be ans which is 7-1 and rest 9\n 7 7 6 ------------------------- 6 9 9\n 3 7 7 6 -----------------------3 7(till here monotonically increasing so one less than this is 3 6 and rest 9 9 ) 3 6 9 9 \n 4 3 7 7 6 --- 3 9 9 9 9\n 5 4 3 7 7 6 -- 4 9 9 9 9 9 \n ``` \n class Solution {\npublic:\n int monotoneIncreasingDigits(int N) {\n if(N < 10){\n return N;\n }\n string s = to_string(N);\n int index = s.length();\n int i;\n for(i = index -1 ; i > 0; i--){\n if(s[i-1] > s[i]){\n s[i-1]--;\n index = i; \n }\n }\n for(i = index; i < s.length(); i++){\n s[i] = \'9\';\n }\n N = stoi(s);\n return N;\n }\n}; | 22 | 0 | ['C++'] | 2 |
monotone-increasing-digits | C++ | BFS approach | c-bfs-approach-by-wh0ami-fg48 | \nclass Solution {\npublic:\n int monotoneIncreasingDigits(int N) {\n \n queue<long>q;\n for (int i = 1; i <= 9; i++)\n q.pus | wh0ami | NORMAL | 2020-06-18T05:34:06.752796+00:00 | 2020-06-18T05:34:06.752849+00:00 | 918 | false | ```\nclass Solution {\npublic:\n int monotoneIncreasingDigits(int N) {\n \n queue<long>q;\n for (int i = 1; i <= 9; i++)\n q.push(i);\n \n int res = INT_MIN;\n while (!q.empty()) {\n int t = q.front();\n q.pop();\n \n if (t > N) break;\n res = max(res, t);\n \n int r = t % 10;\n for (int i = r; i <= 9; i++)\n q.push((long)t*10 + i);\n }\n \n return res;\n }\n};\n``` | 20 | 0 | [] | 3 |
monotone-increasing-digits | Simple and very short Java solution | simple-and-very-short-java-solution-by-b-f083 | //translated from the simple and very short c++ solution\n\n\n public int monotoneIncreasingDigits(int N) {\n\n if(N<=9)\n return N;\n | brucezu | NORMAL | 2017-12-03T09:00:47.355000+00:00 | 2017-12-03T09:00:47.355000+00:00 | 4,504 | false | //translated from the simple and very short c++ solution\n\n```\n public int monotoneIncreasingDigits(int N) {\n\n if(N<=9)\n return N;\n char[] x = String.valueOf(N).toCharArray();\n\n int mark = x.length;\n for(int i = x.length-1;i>0;i--){\n if(x[i]<x[i-1]){\n mark = i-1;\n x[i-1]--;\n }\n }\n for(int i = mark+1;i<x.length;i++){\n x[i] = '9';\n }\n return Integer.parseInt(new String(x));\n }\n``` | 17 | 1 | [] | 1 |
monotone-increasing-digits | Python3 || 7 lines w/explanation || T/S: 82% / 87% | python3-7-lines-wexplanation-ts-82-87-by-pkys | \nclass Solution:\n def monotoneIncreasingDigits(self, n: int) -> int:\n\n n = str(n) # For example: n = 246621 | Spaulding_ | NORMAL | 2022-09-20T17:22:20.540912+00:00 | 2024-05-29T19:16:36.568363+00:00 | 786 | false | ```\nclass Solution:\n def monotoneIncreasingDigits(self, n: int) -> int:\n\n n = str(n) # For example: n = 246621 --> "246621"\n N = len(n)\n\n for i in range(N-1): # find the first break in monotonicity\n if n[i] > n[i+1]: break # Ex: "2466 21"\n # ^\n else: return int(n) # if no break, then n is a mono non-decr seq\n \n while i>0 and n[i]==n[i-1]: i-=1 # back up to the last digit in the mono incr seq \n # Ex: "246 621"\n # ^\n return int(str(int(n[:i+1])-1)+\'9\'*(N-i-1)) # borrow a 1 from the mono incr portion and pad with 9s\n # Ex: ("246"-"1")+ \'9\'*4 = "245999"--> 245999\n```\n[https://leetcode.com/problems/monotone-increasing-digits/submissions/1271737030/](https://leetcode.com/problems/monotone-increasing-digits/submissions/1271737030/)\n\nI could be wrong, but I think that time complexity is *O*(*N*) and space complexity is *O*(*N*), in which *N* ~ `len(str(n))`. | 16 | 1 | ['Python', 'Python3'] | 1 |
monotone-increasing-digits | Simple Java, from back to front, no extra space and no conversion to char[] | simple-java-from-back-to-front-no-extra-fl047 | \nclass Solution {\n public int monotoneIncreasingDigits(int N) {\n int res = 0;\n int pre = Integer.MAX_VALUE;\n int offset = 1;\n | shibai86 | NORMAL | 2018-07-03T06:12:30.639364+00:00 | 2018-10-10T19:12:50.924558+00:00 | 1,052 | false | ```\nclass Solution {\n public int monotoneIncreasingDigits(int N) {\n int res = 0;\n int pre = Integer.MAX_VALUE;\n int offset = 1;\n while(N != 0) {\n int digit = N % 10;\n if(digit > pre) {\n res = digit * offset - 1;\n pre = digit - 1;\n }else {\n res = res + digit * offset;\n pre = digit;\n }\n offset *= 10;\n N = N / 10;\n }\n return res;\n }\n \n}\n``` | 14 | 1 | [] | 3 |
monotone-increasing-digits | [Java/C++] 0ms || Awesome approach || 100% faster | javac-0ms-awesome-approach-100-faster-by-yak8 | Attention \u2757\nAvoid the following approach, it is too expensive because of n-- statements\u2757. \n\npublic int monotoneIncreasingDigits(int n) {\n w | im_obid | NORMAL | 2023-01-15T21:35:53.354207+00:00 | 2023-01-15T23:40:44.004404+00:00 | 1,731 | false | # Attention \u2757\nAvoid the following approach, it is too expensive because of ```n--``` statements\u2757. \n```\npublic int monotoneIncreasingDigits(int n) {\n while (!isSatisfies(n)) {\n n--;\n }\n return n;\n }\n\n public boolean isSatisfies(int n) {\n int k = 10;\n while (n > 0) {\n if (k < n % 10) {\n return false;\n } else {\n k = n % 10;\n n /= 10;\n }\n }\n return true;\n }\n```\n\n# My Approach\n\nLet\'s we will improve above code.\n```isSatisfies(int n)``` method returns just ```true``` , ```false``` if ```n``` has ```monotone``` ```increasing digits```, hasn\'t respectively. \nI changed it to ```getThePositionNotSatisfied(int n)``` and it returns the position of the digit not satisfied the condition or -1 if satisfies all condition. \n\nAnd, instead of ```n--```, I write the following statements to increase loop steps and to improve speed : \n```\ndigitInTheNextPosition = ((int) (n / Math.pow(10, position - 1))) % 10;\n n -= Math.pow(10, position - 1) * (digitInTheNextPosition + 1);\n n -= n % Math.pow(10, position);\n n += Math.pow(10, position) - 1;\n```\n\nFor example, if ```n=3423```.\nThen ```getThePositionNotSatisfied(3423) = 2```, it means that from right the digit in \n```2-index```, i.e ```4``` not satisfies the condition.\nThen \n ```position = 2```\n ```digitNextInThePosition = 3423/ Math.pow(10,2 - 1) % 10 = 2;```\n ```n = 3423 - Math.pow(10,2 - 1)(2+1) = 3393;```\n\nProbably, there are other numbers between ```3393``` and ```3399``` that we looking for. So we need to check these numbers. And new value of ```n``` to check should be ```3399```.\nFor this, we need to swap all digits after the ```position``` with 9. In my code, I achive it as following :\n\n```n = 3393 - 3393 % Math.pow(10, 2) = 3300;```\n```n = 3300 + (Math.pow(10, 2) - 1) = 3300 + 99 = 3399;```\n\nand, so on. \n\nIn the first approach to down from ```3423``` to ```3399``` you have to walk **23 steps**, in the second approach just **1 step** :)\n\n\n*Please upvote, if you find it useful*\uD83D\uDE0A\n\n\n# Java\n```\nclass Solution {\n public int monotoneIncreasingDigits(int n) {\n int position;\n int digitInTheNextPosition;\n while ((position = getThePositionNotSatisfied(n)) != -1) {\n digitInTheNextPosition = ((int) (n / Math.pow(10, position - 1))) % 10;\n n -= Math.pow(10, position - 1) * (digitInTheNextPosition + 1);\n n -= n % Math.pow(10, position);\n n += Math.pow(10, position) - 1;\n }\n return n;\n }\n\n public int getThePositionNotSatisfied(int n) {\n int k = 10;\n int position = 0;\n while (n > 0) {\n if (k < n % 10) {\n return position;\n } else {\n k = n % 10;\n n /= 10;\n position++;\n }\n }\n return -1;\n }\n}\n```\n---\n\n# C++\n```\n#include<math.h>\nclass Solution {\npublic: \n int getThePositionNotSatisfied(int n) {\n int k = 10;\n int position = 0;\n while (n > 0) {\n if (k < n % 10) {\n return position;\n } else {\n k = n % 10;\n n /= 10;\n position++;\n }\n }\n return -1;\n }\npublic:\n int monotoneIncreasingDigits(int n) {\n int position;\n int digitInTheNextPosition;\n while ((position = getThePositionNotSatisfied(n)) != -1) {\n digitInTheNextPosition = ((int) (n / pow(10, position - 1))) % 10;\n n -= pow(10, position - 1) * (digitInTheNextPosition + 1);\n n -= (n %(int) pow(10, position));\n n += pow(10, position) - 1;\n }\n return n;\n }\n};\n```\n# Result\n\n | 12 | 0 | ['C++', 'Java'] | 4 |
monotone-increasing-digits | Fast and simple 40ms Python solution using recursion | fast-and-simple-40ms-python-solution-usi-bxj8 | We scan through S from left to right:\n If it\'s monotonically increasing we just adding corresponding part to result\n If not then we simply decrease result by | rouroukerr | NORMAL | 2018-10-16T01:18:35.834038+00:00 | 2018-10-24T14:55:12.274831+00:00 | 802 | false | We scan through S from left to right:\n* If it\'s monotonically increasing we just adding corresponding part to result\n* If not then we simply decrease result by 1, which would result in some 9s in the tail\n* However, decrease by 1 might lead to our result being not monotonically increasing, so we run recursion base on our current result number\n\nExample - say the input was 1221\n1. i=0, res=1000\n2. i=1, res=1200\n3. i=2, res=1220\n4. i=3, res=1219 because it\'s not increasing anymore\n5. then we recursively call with input being 1219\n6. i=0, res=1000\n7. i=1, res=1200\n8. i=2, res=1199 because it\'s not increasing anymore\n9. then we recursively call with input being 1199\n10. voila! we got it\n```\nclass Solution:\n def monotoneIncreasingDigits(self, N):\n """\n :type N: int\n :rtype: int\n """\n s = str(N)\n l = len(s)\n res = 0\n for i in range(len(s)):\n if i == 0 or s[i] >= s[i-1]:\n res += int(s[i]) * pow(10, l-1)\n else:\n return self.monotoneIncreasingDigits(res-1)\n l -= 1\n return res\n``` | 10 | 0 | [] | 3 |
monotone-increasing-digits | easy java | easy-java-by-0xdeadbeef-vszc | \n public int monotoneIncreasingDigits(int N) {\n char[] digit = (N + "").toCharArray();\n int flag = digit.length;\n for (int i = digit | 0xdeadbeef_ | NORMAL | 2017-12-14T14:54:30.249000+00:00 | 2017-12-14T14:54:30.249000+00:00 | 1,281 | false | ```\n public int monotoneIncreasingDigits(int N) {\n char[] digit = (N + "").toCharArray();\n int flag = digit.length;\n for (int i = digit.length - 1; i > 0; i--) {\n if (digit[i] < digit[i - 1]) {\n digit[i - 1]--;\n flag = i;\n }\n }\n Arrays.fill(digit, flag, digit.length, '9');\n return Integer.parseInt(new String(digit));\n }\n``` | 8 | 0 | [] | 0 |
monotone-increasing-digits | 738: Solution with step by step explanation | 738-solution-with-step-by-step-explanati-so3v | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n\ndigits = list(str(n))\n\nWe first convert the integer n to its string r | Marlen09 | NORMAL | 2023-10-20T18:48:59.005595+00:00 | 2023-10-20T18:48:59.005621+00:00 | 540 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n```\ndigits = list(str(n))\n```\nWe first convert the integer n to its string representation and then create a list of its characters.\nThis step allows us to easily modify individual digits if needed.\n\n```\nn = len(digits)\nidx_to_modify = n\n```\n\nn now represents the length of the digits list.\nidx_to_modify will store the position where the first monotonicity violation occurs. Initially, it\'s set to the length of the digits list, assuming the number is already monotonic.\n\n```\nfor i in range(n - 1, 0, -1):\n if digits[i] < digits[i - 1]:\n idx_to_modify = i\n digits[i - 1] = str(int(digits[i - 1]) - 1)\n```\n\nStarting from the end of the list, we move towards the beginning.\nWe compare each digit with its preceding digit.\nThe first time we find a digit that\'s smaller than its predecessor (digits[i] < digits[i - 1]), we\'ve found a monotonicity violation.\nAt this point, we reduce the preceding digit by 1 (digits[i - 1] -= 1) to make it smaller and set the idx_to_modify to the current index i.\n\n```\nfor i in range(idx_to_modify, n):\n digits[i] = \'9\'\n```\n\nTo get the largest possible number after modifying a digit, we need to make all digits to its right as \'9\'.\nThis loop sets every digit after the idx_to_modify to \'9\'.\n\n```\nreturn int("".join(digits))\n```\n\nWe join the modified list of characters to form the string representation of the new number and then convert it back to an integer.\n\n# Complexity\n- Time complexity:\nO(log n)\n\n- Space complexity:\nO(log n)\n\n# Code\n```\nclass Solution:\n def monotoneIncreasingDigits(self, n: int) -> int:\n digits = list(str(n))\n n = len(digits)\n idx_to_modify = n \n\n for i in range(n - 1, 0, -1):\n if digits[i] < digits[i - 1]:\n idx_to_modify = i\n digits[i - 1] = str(int(digits[i - 1]) - 1)\n \n for i in range(idx_to_modify, n):\n digits[i] = \'9\'\n \n return int("".join(digits))\n\n``` | 7 | 0 | ['Math', 'Greedy', 'Python', 'Python3'] | 0 |
monotone-increasing-digits | [C++] Simplest Greedy Solution Faster than 100% | c-simplest-greedy-solution-faster-than-1-u9hn | We need to return the largest number that is less than or equal to the given n, that has monotome increasing digits.\n\nAPPROACH :\n\n If the number n is monoto | Mythri_Kaulwar | NORMAL | 2022-02-18T04:06:12.029495+00:00 | 2022-02-18T04:06:53.233991+00:00 | 966 | false | We need to return the largest number that is less than or equal to the given ```n```, that has monotome increasing digits.\n\n**APPROACH :**\n\n* If the number ```n``` is monotone increasing then, we can return the number itself.\n* Otherwise, we start traversing from the last digit.\n* Wherever we find a digit that\'s less than it\'s previous digit (ie; ```s[i] < s[i-1]```), we mark that index & decrement the previous index digit by ```1``` (Since we want a number smaller than the given one)\n* To return the largest number possible : We make all the digits from the marked index = ```9```.\n\n**Time Complexity :** O(n)\n\n**Space Complexity :** O(n) - We need to create a string in order to traverse digit by digit.\n\n**Code :**\n```\nclass Solution {\npublic:\n int monotoneIncreasingDigits(int n) {\n string s = to_string(n);\n int size = s.size(), lim = s.size();\n for(int i=size-1; i>0; i--){\n if(s[i-1] > s[i]) lim = i, s[i-1] -= 1;\n }\n for(int i=lim; i<size; i++) s[i] = \'9\';\n return stoi(s);\n }\n};\n```\n\n**Do upvote if you\'ve found my post helpful :)** | 6 | 0 | ['Greedy', 'C', 'C++'] | 1 |
monotone-increasing-digits | Solution in c++ | solution-in-c-by-ashish_madhup-dwxk | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | ashish_madhup | NORMAL | 2023-02-26T16:29:37.900514+00:00 | 2023-02-26T16:29:37.900618+00:00 | 673 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int monotoneIncreasingDigits(int n) {\n string s = to_string(n);\n int size = s.size(), lim = s.size();\n for(int i=size-1; i>0; i--){\n if(s[i-1] > s[i]) lim = i, s[i-1] -= 1;\n }\n for(int i=lim; i<size; i++) s[i] = \'9\';\n return stoi(s);\n }\n};\n``` | 5 | 0 | ['C++'] | 0 |
monotone-increasing-digits | java simple | java-simple-by-jstm2022-lkrt | \nclass Solution {\n public int monotoneIncreasingDigits(int n) {\n char[] arr = String.valueOf(n).toCharArray();\n int start = arr.length;\n | JSTM2022 | NORMAL | 2022-04-26T02:00:47.759331+00:00 | 2022-04-26T02:00:47.759378+00:00 | 673 | false | ```\nclass Solution {\n public int monotoneIncreasingDigits(int n) {\n char[] arr = String.valueOf(n).toCharArray();\n int start = arr.length;\n for (int i = arr.length - 2; i >= 0; i --) {\n if (arr[i] > arr[i + 1]) {\n start = i + 1;\n arr[i] --;\n }\n }\n \n for (int i = start; i < arr.length; i ++) {\n arr[i] = \'9\';\n }\n \n return Integer.parseInt(String.valueOf(arr));\n }\n}\n``` | 5 | 0 | ['Java'] | 0 |
monotone-increasing-digits | very intuitional Java solution using stack | very-intuitional-java-solution-using-sta-xo56 | ```\n public int monotoneIncreasingDigits(int N) {\n char[] num = String.valueOf(N).toCharArray();\n Stack stack = new Stack<>();\n boolea | peachfan | NORMAL | 2019-09-28T15:11:22.087463+00:00 | 2019-09-28T15:11:22.087504+00:00 | 273 | false | ```\n public int monotoneIncreasingDigits(int N) {\n char[] num = String.valueOf(N).toCharArray();\n Stack<Character> stack = new Stack<>();\n boolean find = false;\n for (int i = 0; i < num.length; i++) {\n char ch = num[i];\n while (!stack.isEmpty() && stack.peek() > ch) {\n ch = (char)(stack.pop() - 1);\n find = true;\n }\n stack.push(ch);\n if (find) {\n break;\n }\n }\n StringBuffer sb = new StringBuffer();\n while (!stack.isEmpty()) {\n sb.append(stack.pop());\n }\n sb.reverse();\n while (sb.length() < num.length) {\n sb.append(\'9\');\n }\n return Integer.parseInt(sb.toString());\n } | 5 | 0 | [] | 0 |
monotone-increasing-digits | [Java] ✅ O(1) ✅ 1MS ✅ 100% ✅ FAST ✅ BEST ✅ CLEAN CODE | java-o1-1ms-100-fast-best-clean-code-by-d380f | Approach\n1. Looking at the numbers, the highest monotone increasing increasing is ending with 9 (unless number is already monotone: eg: 12345)\n2. To obtain nu | StefanelStan | NORMAL | 2024-10-14T08:47:49.801271+00:00 | 2024-10-14T08:47:49.801306+00:00 | 219 | false | # Approach\n1. Looking at the numbers, the highest monotone increasing increasing is ending with 9 (unless number is already monotone: eg: 12345)\n2. To obtain numbers ending with 9, subtract n % (j) + 1 from n, where j is a power of 10: 10,100, 1000.\n3. EG: \n - 332 - (332 % 10 + 1) = 332 - (2 + 1) = 332 - 3 = 329. This is not monotone, so we need to increase the modulo factor to 100\n - 332 - (332 % 100 + 1) = 332 - 33 = 299= > This is a monotone increasing.\n4. Subtract power(10, i) + 1 from n until n becomes monotone.\n\n# Complexity\n- Time complexity:$$O(l)$$ (l - length of number as string)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:$$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```java []\nclass Solution {\n public int monotoneIncreasingDigits(int n) {\n int multiplier = 10, decreasedN = n;\n while (!isMonotone(decreasedN)) {\n decreasedN = n - (n % multiplier + 1); \n multiplier *= 10;\n }\n return decreasedN;\n }\n\n private boolean isMonotone(int n) {\n int prev = Integer.MAX_VALUE, current;\n while (n > 0) {\n current = n % 10;\n if (current > prev) {\n return false;\n }\n prev = current;\n n = n / 10;\n }\n return true;\n }\n}\n``` | 4 | 0 | ['Java'] | 1 |
monotone-increasing-digits | O(n) Python solution - very simple logic | on-python-solution-very-simple-logic-by-axagf | Example: n = 4329762\nfor loop: i = 6 -> if condition: 2 < 6 is true: n_str = 4329762 - 63 = 4329699\nfor loop: i = 5 -> if condition: 9 < 6 is false\nfor loop | getsatnow | NORMAL | 2021-10-02T20:37:03.098544+00:00 | 2021-10-02T20:46:05.513469+00:00 | 287 | false | Example: n = 4329762\nfor loop: i = 6 -> if condition: 2 < 6 is true: n_str = 4329762 - 63 = 4329699\nfor loop: i = 5 -> if condition: 9 < 6 is false\nfor loop i = 4 -> if condition: 6 < 9 is true: n_str = 4329699 - 9700 = 4319999\nand so on...\n```\nclass Solution:\n def monotoneIncreasingDigits(self, n: int) -> int:\n n_str = str(n)\n len_n = len(n_str)\n for i in range(len_n-1, 0, -1):\n if int(n_str[i]) < int(n_str[i - 1]):\n n_str = str(int(n_str) - (int(n_str[i:]) + 1))\n return int(n_str)\n``` | 4 | 0 | [] | 2 |
monotone-increasing-digits | Simple O(log n) Java solution with one pass | simple-olog-n-java-solution-with-one-pas-4nf5 | We scan from right to left, i.e., least significant to most significan, take 7634 fro example: \n1. if the digits are strictly increasing from left to right, we | linvava | NORMAL | 2020-06-16T04:56:46.888120+00:00 | 2020-06-16T04:58:07.530833+00:00 | 373 | false | We scan from right to left, i.e., least significant to most significan, take 7634 fro example: \n1. if the digits are strictly increasing from left to right, we do nothing, so 34 -> 34.\n2. if a one digit is smaller than any digit on the right, the result would be the digit minus 1, and fill remaining digits with 9. 634 -> 599, 7599 -> 6999.\n3. \n\n public int monotoneIncreasingDigits(int N) {\n int res = 0;\n int digit = 0;\n int max = 9;\n \n while(N > 0)\n {\n int cur = N % 10;\n N /= 10;\n if(cur <= max)\n {\n res += cur * Math.pow(10, digit);\n max = cur;\n }\n else\n {\n res = (int)(cur * Math.pow(10, digit) - 1);\n max = cur - 1;\n }\n digit++;\n }\n \n return res;\n } | 4 | 0 | [] | 0 |
monotone-increasing-digits | Simple Python Solution | simple-python-solution-by-bigshen-romf | class Solution(object):\n def monotoneIncreasingDigits(self, N):\n """\n :type N: int\n :rtype: int\n """\n \n if N | bigshen | NORMAL | 2017-12-25T03:42:30.241000+00:00 | 2018-10-24T15:14:16.938836+00:00 | 795 | false | class Solution(object):\n def monotoneIncreasingDigits(self, N):\n """\n :type N: int\n :rtype: int\n """\n \n if N == 10:\n return 9\n if N < 20:\n return N\n num = [s for s in str(N)]\n i = len(num) - 1\n index = len(num) \n while i > 0:\n if int(num[i]) < int(num[i-1]):\n num[i-1] = str(int(num[i-1]) -1)\n index = i\n i -= 1\n for n in range(index,len(num)):\n num[n] = '9'\n return int(''.join(s for s in num)) | 4 | 1 | [] | 0 |
monotone-increasing-digits | Easy Java Solution || Beats 95% | easy-java-solution-beats-95-by-ravikumar-2qc8 | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | ravikumar50 | NORMAL | 2023-09-07T14:36:09.951772+00:00 | 2023-09-07T14:36:09.951794+00:00 | 227 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int monotoneIncreasingDigits(int n) {\n char arr[] = String.valueOf(n).toCharArray();\n\n int x = arr.length;\n int st = x;\n \n for(int i=x-2; i>=0; i--){\n if(arr[i]>arr[i+1]){\n st = i+1;\n arr[i]--;\n }\n }\n\n for(int i=st; i<x; i++){\n arr[i] = \'9\';\n }\n\n return Integer.valueOf(String.valueOf(arr));\n }\n}\n``` | 3 | 0 | ['Java'] | 1 |
monotone-increasing-digits | very easy to understand ! converting to string and solving in c++ | very-easy-to-understand-converting-to-st-65ij | Approach\n1.First convert the number into a string using to_string( ).\n2.Then check each digit in a for loop if the prev digit is smaller than or equal to the | Trivial_03 | NORMAL | 2023-03-21T19:39:41.690681+00:00 | 2023-03-21T19:39:41.690713+00:00 | 593 | false | # Approach\n1.First convert the number into a string using to_string( ).\n2.Then check each digit in a for loop if the prev digit is smaller than or equal to the next digit or not. If yes,then continue.\n3.If no then just make the rest leftout digits(to the right of index where condition is violated) to \'9\' and decrement the current digit by 1.\n4.We will continue this process using a while loop till we get the desired condition where every prev digits are less or equal to the next digits.\n\neg. 332\n->we see that condition is violated at index 1 where s[i]>s[i+1] (3>2)\n->here we convert all the rest digits to 9(here 2 is converted to 9)\nand then we decrement the ith digit by 1(here 3 becomes 2).\n->then we concatenate the prefix and suffix. Here prefix was \'3\' and suffix is \'29\',resultant is \'329\'.But there is again violation in 0th index where \'3\'>\'2\'.So again loop goes on to convert it finally.\n\nTIME complexity will not be much as nums can go upto 10^9 so it can be a 9 letter string to the max,and we can apply while loop nested with for loop for many times.\n\n# Code\n```\nclass Solution {\npublic:\n int monotoneIncreasingDigits(int n) {\n string s=to_string(n); //num converted to string\n int len=s.size(),ind,flag=0;\n while(1)\n {\n flag=0; //initially flag is set to zero to indicate no problem is there in string\n for(int i=0;i<len-1;i++)\n {\n if(s[i]<=s[i+1])\n continue;\n else\n {\n ind=i; //ind refers to the index at which the problem occurs\n string ans="";\n for(int j=1;j<=len-1-ind;j++)\n ans+=\'9\';\n s=s.substr(0,ind)+(--s[ind])+ans; //final string is formed and s is replaced with new string\n flag=1; //flag is set to one to indicate the string was problematic and the while loop will continue further\n } \n }\n if(flag==0) //if string is perfect(no error) then exit the while loop\n break;\n }\n int final=stoi(s);\n return final;\n }\n};\n``` | 3 | 0 | ['C++'] | 0 |
monotone-increasing-digits | 8 Line JS code | 8-line-js-code-by-yutingkung-tebm | \nvar monotoneIncreasingDigits = function(n) {\n let arr = String(n).split(\'\');\n for (let i=arr.length-2; i>=0; i--) {\n if (arr[i]>arr[i+1]) {\ | yutingkung | NORMAL | 2022-01-07T03:52:23.385616+00:00 | 2022-01-07T03:52:23.385660+00:00 | 151 | false | ```\nvar monotoneIncreasingDigits = function(n) {\n let arr = String(n).split(\'\');\n for (let i=arr.length-2; i>=0; i--) {\n if (arr[i]>arr[i+1]) {\n arr[i]--;\n for(let j=i+1; j<arr.length; j++) arr[j]=\'9\';\n }\n }\n return Number(arr.join(\'\'));\n};\n``` | 3 | 0 | ['JavaScript'] | 0 |
monotone-increasing-digits | 92 % ,Intuitive,Easy to Understand,GREEDY , Java | 92-intuitiveeasy-to-understandgreedy-jav-9045 | ```\nclass Solution {\n public int monotoneIncreasingDigits(int n) {\n char [] arr=String.valueOf(n).toCharArray();\n for(int i=arr.length-2;i> | rtvksingh | NORMAL | 2021-05-29T17:32:35.382147+00:00 | 2021-05-29T17:34:48.244907+00:00 | 141 | false | ```\nclass Solution {\n public int monotoneIncreasingDigits(int n) {\n char [] arr=String.valueOf(n).toCharArray();\n for(int i=arr.length-2;i>=0;i--){\n if(arr[i]<=arr[i+1])\n continue;\n else{\n arr[i]--;\n for(int j=i+1;j<arr.length;j++)\n arr[j]=\'9\';\n }\n }\n return Integer.valueOf(new String(arr));\n }\n} | 3 | 1 | [] | 0 |
monotone-increasing-digits | Easy O(N) JavaScript with explanation | easy-on-javascript-with-explanation-by-f-log5 | \n\nconst monotoneIncreasingDigits = N => {\n \n // create any array of integers from number N\n const n = Array.from(\'\'+N, Number);\n \n let i = 0;\n \ | fl4sk | NORMAL | 2021-01-10T03:02:20.999461+00:00 | 2021-01-10T03:02:20.999498+00:00 | 276 | false | ```\n\nconst monotoneIncreasingDigits = N => {\n \n // create any array of integers from number N\n const n = Array.from(\'\'+N, Number);\n \n let i = 0;\n \n // find the cliff\n while(i < n.length-1 && n[i] <= n[i+1])\n i++;\n\n // decremnet the cliff and any values before the cliff which satisfy this condition n[i] > n[i+1]\n while( i >= 0 && n[i] > n[i+1]){\n n[i]--;\n i--;\n }\n \n // assign any value after the first cliff to 9\n for(let j = i+2; j < n.length; j++)\n n[j] = 9;\n \n // convert the integer array to a string then to a number and return\n return +n.join(\'\')\n};\n\n``` | 3 | 0 | ['JavaScript'] | 0 |
monotone-increasing-digits | StraightForward Greedy Python Solution | straightforward-greedy-python-solution-b-xpeh | \n def monotoneIncreasingDigits(self, N):\n """\n :type N: int\n :rtype: int\n """\n s = str(N)\n if len(s) < 2:\n | yuchenliu0513 | NORMAL | 2020-12-03T08:15:02.377923+00:00 | 2020-12-03T08:15:02.377965+00:00 | 562 | false | ```\n def monotoneIncreasingDigits(self, N):\n """\n :type N: int\n :rtype: int\n """\n s = str(N)\n if len(s) < 2:\n return N\n ans = ""\n pre = 0\n for i in range(len(s)):\n if int(s[i]) >= pre:\n ans += s[i]\n pre = int(s[i])\n else:\n j = len(ans)-1\n while j-1 >= 0 and ans[j] == ans[j-1]:\n j -= 1\n ans = ans[:j+1] + (len(s)-j-1)*\'0\'\n return int(ans)-1\n return int(ans)\n``` | 3 | 0 | ['Greedy', 'Python', 'Python3'] | 0 |
monotone-increasing-digits | c++,stack | cstack-by-sharma_amit-87ax | \nclass Solution {\n vector<int> convert_to_arr(int n){\n vector<int> v;\n while(n){\n int t = n%10;\n n = n/10;\n | sharma_amit | NORMAL | 2020-09-29T16:18:41.544555+00:00 | 2020-09-29T16:19:51.815516+00:00 | 381 | false | ```\nclass Solution {\n vector<int> convert_to_arr(int n){\n vector<int> v;\n while(n){\n int t = n%10;\n n = n/10;\n v.push_back(t);\n }\n reverse(v.begin(),v.end());\n return v;\n }\n \n int convert_int(vector<int> nums){\n int ans = 0;\n for(int i=0;i<nums.size();i++)\n ans = ans*10 + nums[i];\n return ans;\n }\npublic:\n int monotoneIncreasingDigits(int N) {\n vector<int> nums = convert_to_arr(N);\n stack<int> st;\n int n = nums.size();\n int count = 0;\n for(int i=n-1;i>=0;i--){\n int count = 0;\n if(st.size()>0 and nums[i]>nums[st.top()]){\n while(st.size()>0){\n nums[st.top()] = 9;\n st.pop();\n }\n count = -1;\n }\n nums[i] += count;\n st.push(i);\n }\n \n return convert_int(nums); \n }\n};\n``` | 3 | 0 | ['Stack', 'C'] | 0 |
monotone-increasing-digits | java 1ms solution with detailed explanation | java-1ms-solution-with-detailed-explanat-nwq4 | This problem can be solved in greedy strategy:\n1. At first, we use a list to represent the given number N where list.get(0) is the highest number.\n2. Then, we | pangeneral | NORMAL | 2019-05-09T00:38:42.625310+00:00 | 2019-05-09T00:38:42.625340+00:00 | 653 | false | This problem can be solved in greedy strategy:\n1. At first, we use a list to represent the given number ```N``` where list.get(0) is the highest number.\n2. Then, we traverse from 0 to list.size() - 1 to find the **first** i that list[i] > list[i + 1]\n3. If we don\'t find such i, then return the given number. Otherwise, we **backwardly** traverse from i to 0 to find the **first** j that list[j] > list[j - 1] or until j equals 0. \n4. list[j] minus one, and for all k > j, set list[k] to 9. \n\n```\npublic int monotoneIncreasingDigits(int N) {\n // Represent N with a list\n\tList<Integer> num = new ArrayList<Integer>();\n while( N != 0 ) {\n num.add(0, N % 10);\n N /= 10;\n }\n\t\n for(int i = 0; i < num.size() - 1; i++) {\n if( num.get(i) > num.get(i + 1) ) { // find the first i that num[i] > num[i + 1]\n for(int j = i; j >= 0; j--) {\n if( j == 0 || num.get(j) > num.get(j - 1) ) { // find the first j that num[j] > num[j - 1]\n num.set(j, num.get(j) - 1);\n for(int k = j + 1; k < num.size(); k++) // set all num[k] where k > j to 9\n num.set(k, 9);\n break;\n }\n }\n break;\n }\n }\n int result = 0;\n for(int i = 0; i < num.size(); i++)\n result = result * 10 + num.get(i);\n return result;\n}\n``` | 3 | 0 | ['Math', 'Greedy', 'Java'] | 0 |
monotone-increasing-digits | Optimized Approach || 100% T.C || CPP | optimized-approach-100-tc-cpp-by-ganesh_-f7qu | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | Ganesh_ag10 | NORMAL | 2024-04-11T05:35:24.233137+00:00 | 2024-04-11T05:35:24.233173+00:00 | 555 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int monotoneIncreasingDigits(int n) {\n string ag=to_string(n);\n int i=1;\n while(i<ag.size() && ag[i]>=ag[i-1]){\n i++;\n }\n while(i>0 && i<ag.size() && ag[i-1]>ag[i]){\n ag[i-1]--;\n i--;\n }\n for(int j=i+1;j<ag.size();j++){\n ag[j]=\'9\';\n }\n return stoi(ag);\n }\n};\n``` | 2 | 1 | ['C++'] | 0 |
monotone-increasing-digits | Easy C++ solution || Math Based | easy-c-solution-math-based-by-bharathgow-d43x | \n# Code\n\nclass Solution {\npublic:\n bool isMonotonic(int n){\n int k = 10;\n while(n > 0){\n if(k < n%10){\n retu | bharathgowda29 | NORMAL | 2023-12-27T15:43:01.273264+00:00 | 2023-12-27T15:43:01.273291+00:00 | 542 | false | \n# Code\n```\nclass Solution {\npublic:\n bool isMonotonic(int n){\n int k = 10;\n while(n > 0){\n if(k < n%10){\n return false;\n }\n else{\n k = n%10;\n n = n/10;\n }\n }\n\n return true;\n }\n\n int monotoneIncreasingDigits(int n) {\n while(!(isMonotonic(n))){\n n = n-(n%10)-1;\n }\n\n return n;\n }\n};\n``` | 2 | 0 | ['Math', 'Greedy', 'C++'] | 0 |
monotone-increasing-digits | Solution | solution-by-deleted_user-tga5 | C++ []\nclass Solution {\npublic:\n int monotoneIncreasingDigits(int n) {\n string s = to_string(n);\n while(1){\n bool flag = false | deleted_user | NORMAL | 2023-04-23T04:00:49.023701+00:00 | 2023-04-23T04:49:07.534319+00:00 | 873 | false | ```C++ []\nclass Solution {\npublic:\n int monotoneIncreasingDigits(int n) {\n string s = to_string(n);\n while(1){\n bool flag = false;\n for(int i = 1; i < s.length(); i++){\n if(s[i] >= s[i-1]) continue;\n else{\n s[i-1]--;\n while(i != s.length()){\n s[i] = \'9\';\n i++;\n }\n flag = true;\n }\n }\n if(!flag) break;\n }\n return stoi(s);\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def monotoneIncreasingDigits(self, n: int) -> int:\n strn = list(str(n))\n flag = len(strn)\n\n for i in range(flag-1,0,-1):\n if strn[i] < strn[i-1]:\n flag = i\n strn[i-1] = str(int(strn[i-1]) -1)\n \n for i in range(flag, len(strn)):\n strn[i] = \'9\'\n\n return int("".join(strn))\n```\n\n```Java []\nclass Solution {\n public int monotoneIncreasingDigits(int n) {\n int[] digits = new int[10];\n int num = n;\n int index = 0;\n\n while(n > 0){\n digits[index++] = n % 10;\n n /= 10;\n }\n int start = 0, len = index;\n int end = len - 1;\n while(start < end){\n int d = digits[start];\n digits[start++] = digits[end];\n digits[end--] = d;\n }\n int i = 1;\n for(;i < len;i++){\n if(digits[i - 1] > digits[i]) break;\n }\n if(i == len) return num;\n i--;\n while(i > 0 && digits[i - 1] == digits[i]){\n i--;\n }\n digits[i++]--;\n while(i < len) digits[i++] = 9;\n int ans = 0;\n for( i = 0;i < len;i++) ans = ans * 10 + digits[i];\n return ans;\n }\n}\n```\n | 2 | 0 | ['C++', 'Java', 'Python3'] | 0 |
monotone-increasing-digits | Simple C++ Sloution | simple-c-sloution-by-sunnyyad2002-fwzx | Intuition\n Describe your first thoughts on how to solve this problem. \nSuppose we have a non-negative integer N, we have to find the largest number that is le | sunnyyad2002 | NORMAL | 2023-03-17T15:00:05.898375+00:00 | 2023-03-17T15:00:05.898399+00:00 | 905 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nSuppose we have a non-negative integer N, we have to find the largest number that is less than or equal to N with monotone increasing digits. We know that an integer has monotone increasing digits if and only if each pair of adjacent digits\u2019 x and y satisfy x <= y.) So if the input is like 332, then the result will be 299.\n\nTo solve this, we will follow these steps \u2212\n\ns := N as string, i := 1, n := size of s\nwhile i < n and s[i] >= s[i \u2013 1]\nincrease i by 1\nif i < n\nwhile i > 0 and s[i \u2013 1] > s[i], then\ndecrease i by 1\ndecrease s[i] by 1\nfor j in range i + 1 to n\ns[j] := \u20189\u2019\nreturn s as number\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int monotoneIncreasingDigits(int N) {\n string s = to_string(N);\n int i = 1;\n int n = s.size();\n while(i < n && s[i] >= s[i - 1]) i++;\n if( i < n)\n while(i > 0 && s[i - 1] > s[i]){\n i--;\n s[i]--;\n }\n for(int j = i + 1; j < n; j++)s[j] = \'9\';\n return stoi(s);\n }\n};\n``` | 2 | 0 | ['C++'] | 0 |
monotone-increasing-digits | Java faster than 100% | java-faster-than-100-by-ritik652018-jvnu | ```\nclass Solution {\n \n public int monotoneIncreasingDigits(int n) {\n \n for(int i=n;i>=0;i--){\n int k=i;\n int x=k%10; | ritik652018 | NORMAL | 2022-09-24T08:10:16.458388+00:00 | 2023-10-20T06:48:49.243064+00:00 | 424 | false | ```\nclass Solution {\n \n public int monotoneIncreasingDigits(int n) {\n \n for(int i=n;i>=0;i--){\n int k=i;\n int x=k%10;\n int flag=0;\n int count=1;\n \n while(k>1){\n k=k/10;\n int y= k%10;\n if(x>=y){\n ++count;\n x=y;\n }\n else{\n flag=1;\n i =(k*((int)Math.pow(10,count)));\n break;\n }\n }\n\n if(flag==0){\n return i;\n }\n }\n return 0;\n }\n} | 2 | 1 | ['Math', 'Java'] | 1 |
monotone-increasing-digits | Java Simple Solution without DP | java-simple-solution-without-dp-by-adity-uv1o | \nclass Solution {\n public int monotoneIncreasingDigits(int n) {\n int len = size(n);\n int[] dig = new int[len];\n len--;\n whi | Aditya001 | NORMAL | 2022-08-17T14:28:29.038537+00:00 | 2022-08-17T14:28:29.038605+00:00 | 995 | false | ```\nclass Solution {\n public int monotoneIncreasingDigits(int n) {\n int len = size(n);\n int[] dig = new int[len];\n len--;\n while(n>0){\n dig[len] = n%10;\n n /= 10;\n len--;\n }\n n = dig.length;\n int t = 10;\n\n while(t>0){\n boolean change = false;\n for(int i=0;i<n-1;i++){\n if(dig[i]>dig[i+1]){\n dig[i]--;\n for(int j=i+1;j<n;j++){\n dig[j]=9;\n }\n change = true;\n break;\n }\n }\n if(!change){\n break;\n }\n t--;\n }\n int ans = 0;\n \n for(int i=0;i<n;i++){\n ans += dig[i]*(int)Math.pow(10,n-i-1);\n }\n return ans;\n }\n public int size(int num){\n if(0<=num && num<10){\n return 1;\n }\n if(10<=num && num<100){\n return 2;\n }\n if(100<=num && num<1000){\n return 3;\n }\n if(1000<=num && num<10000){\n return 4;\n }\n if(10000<=num && num<100000){\n return 5;\n }\n if(100000<=num && num<1000000){\n return 6;\n }\n if(1000000<=num && num<10000000){\n return 7;\n }\n if(10000000<=num && num<100000000){\n return 8;\n }\n if(100000000<=num && num<1000000000){\n return 9;\n }\n return 10;\n }\n}\n\n``` | 2 | 0 | ['Java'] | 0 |
monotone-increasing-digits | Easiest C++ solution | easiest-c-solution-by-kazuma0803-5h2r | \nclass Solution {\npublic:\n int monotoneIncreasingDigits(int n) {\\\n string s=to_string(n);\n int x=s.size();\n for (int i=s.size()-1 | Kazuma0803 | NORMAL | 2022-06-18T10:11:53.931180+00:00 | 2022-06-18T10:11:53.931210+00:00 | 336 | false | ```\nclass Solution {\npublic:\n int monotoneIncreasingDigits(int n) {\\\n string s=to_string(n);\n int x=s.size();\n for (int i=s.size()-1;i>0;i--) {\n if (s[i]<s[i-1]) {\n x=i;\n s[i-1]=s[i-1]-1;\n }\n }\n for (int i=x;i<s.size();i++) s[i]=\'9\';\n stringstream geek(s);\n geek>>x;\n return x;\n }\n};\n``` | 2 | 0 | ['C'] | 0 |
monotone-increasing-digits | C++ 100% Faster | c-100-faster-by-kunal_patil-1koh | ,,,\n\n int monotoneIncreasingDigits(int n) {\n \n vector v;\n \n while(n)\n {\n v.push_back(n%10);\n n | kunal_patil | NORMAL | 2022-02-09T06:50:08.896254+00:00 | 2022-02-09T06:50:08.896284+00:00 | 219 | false | ,,,\n\n int monotoneIncreasingDigits(int n) {\n \n vector<int> v;\n \n while(n)\n {\n v.push_back(n%10);\n n=n/10;\n }\n \n for(int i=0;i<v.size();i++)\n {\n if(i<v.size()-1 && v[i]<v[i+1])\n {\n v[i]=9;\n v[i+1]--;\n int k=i;\n while(k>0 && v[k]>v[k-1])\n {\n v[k-1]=v[k];\n k--;\n }\n \n }\n \n }\n \n reverse(v.begin(),v.end());\n \n long ans=0;\n for(int i=0;i<v.size();i++)\n {\n ans = ans*10;\n ans += v[i];\n }\n \n return ans;\n }\n\n\'\'\' | 2 | 0 | ['Math', 'C'] | 0 |
monotone-increasing-digits | Simple C++ || Without changing into string || Stack Solution | simple-c-without-changing-into-string-st-4l5s | \nclass Solution {\npublic:\n int monotoneIncreasingDigits(int n) {\n int ans = 0;\n stack<int> st;\n \n while(n)\n {\n | goyalnaman198 | NORMAL | 2022-01-01T14:48:56.742441+00:00 | 2022-01-01T14:51:42.034462+00:00 | 236 | false | ```\nclass Solution {\npublic:\n int monotoneIncreasingDigits(int n) {\n int ans = 0;\n stack<int> st;\n \n while(n)\n {\n int last = n % 10; n /= 10;\n \n if(st.empty() or st.top() >= last)\n {\n st.push(last);\n }\n else\n {\n while(n and n % 10 == last)\n {\n st.push(last);\n last = n % 10;\n n /= 10;\n }\n st.top()--;\n \n n = (n*10) + last;\n n = (n*10) + st.top(); st.pop();\n \n while(!st.empty())\n {\n n = n * 10 + 9;\n st.pop();\n }\n \n }\n }\n \n while(!st.empty())\n {\n n = n * 10 + st.top();\n st.pop();\n }\n return n;\n }\n};\n``` | 2 | 0 | ['Stack', 'C'] | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.