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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
monotone-increasing-digits | Digit DP | C++ | digit-dp-c-by-prerit2001-86jj | Using Digit Dynamic Programming \n\nclass Solution {\npublic:\n int str_to_int(string temp){\n int ans = 0, prod = 1;\n while(temp.size()){\n | prerit2001 | NORMAL | 2021-06-17T14:47:11.719685+00:00 | 2021-06-17T14:47:11.719726+00:00 | 164 | false | Using Digit Dynamic Programming \n```\nclass Solution {\npublic:\n int str_to_int(string temp){\n int ans = 0, prod = 1;\n while(temp.size()){\n ans += prod*(temp.back()-\'0\');\n temp.pop_back();\n if(prod == 1e9) break;\n prod *= 10;\n }\n return ans;\n }\n \n string int_to_str(int temp){\n deque<char> d;\n while(temp){\n d.push_front(char((temp%10)+\'0\'));\n temp/=10;\n }\n string ans; \n for(char c : d){\n ans += c;\n }\n return ans;\n }\n \n string s;\n int dp[10][2][10];\n string go(int curr, int n, bool tight, int last){\n if(curr == n){\n return "";\n }\n if(dp[curr][tight][last] != -1) return int_to_str(dp[curr][tight][last]);\n string ans = "";\n int ub = 9;\n if(tight == 1) ub = s[curr] - \'0\';\n for(int i = 0; i <= ub; i++){\n if( i >= last ){\n string c1 = char(i+\'0\') + go(curr+1,n,tight&(i==ub),i);\n string c2 = go(curr+1,n,tight,last);\n int choice1 = str_to_int(c1);\n int choice2 = str_to_int(c2);\n int cnt = str_to_int(ans);\n cnt = max({cnt,choice1,choice2});\n ans = int_to_str(cnt);\n }\n }\n dp[curr][tight][last] = str_to_int(ans);\n return ans;\n }\n \n int monotoneIncreasingDigits(int n) {\n while(n){\n s = char((n%10)+\'0\') + s;\n n/=10;\n }\n memset(dp, -1, sizeof dp);\n string ans = go(0,s.size(),1,0);\n return str_to_int(ans);\n }\n};\n``` | 2 | 0 | [] | 0 |
monotone-increasing-digits | simple python and easy to understand | simple-python-and-easy-to-understand-by-0k638 | \n def monotoneIncreasingDigits(self, N: int) -> int:\n\t\n N = str(N)\n mono = True # indicator of monotone digit sequence\n mid = 0\n | dagebbw | NORMAL | 2021-01-02T17:43:11.490786+00:00 | 2021-01-02T17:43:11.490814+00:00 | 407 | false | \n def monotoneIncreasingDigits(self, N: int) -> int:\n\t\n N = str(N)\n mono = True # indicator of monotone digit sequence\n mid = 0\n for i in range(len(N)-1):\n\t\t #find the last position where N[i+1] > N[i], if the digit sequence is not monotone,\n\t\t\t#we can decrease the number at this position by one and set all the following numbers as 9\n if int(N[i+1]) - int(N[i]) >= 1: \n mid = i+1\n if int(N[i]) > int(N[i+1]):\n mono = False\n break\n \n if mono: #if monotone, return original number\n return int(N)\n\n if mid == 0:\n return int(str(int(N[0])-1) + (len(N)-1)*\'9\')\n\n return int(str(int(N[:mid])) + str(int(N[mid])-1) + (len(N)-mid-1)*\'9\') | 2 | 0 | ['Python'] | 0 |
monotone-increasing-digits | python 3 | python-3-by-bakerston-lkj1 | Find the index of the first digit which is smaller than previous digit.\nFor example, in 135248, the number 2 is the first digit because it is smaller than 5. T | Bakerston | NORMAL | 2020-12-18T07:32:04.032645+00:00 | 2020-12-18T07:32:04.032688+00:00 | 113 | false | Find the index of the first digit which is smaller than previous digit.\nFor example, in **135248**, the number 2 is the first digit because it is smaller than 5. The maximum monotone digits is 134999.\nJust decrease the previous digit (5) by 1 (if it is bigger than 1, otherwise just ignore it), so we have 134 as the first three digits of the new number, and change all the following digits (248) to 9 (999).\n\n\n\n```\ndef monotoneIncreasingDigits(self, N: int) -> int:\n s=list(str(N))\n n=len(s)\n ans=""\n cur=0\n for x in range(n):\n if x==0 or s[x]==s[x-1]:\n cur+=1\n elif s[x]>s[x-1]:\n ans+=cur*str(s[x-1])\n cur=1\n else:\n if int(s[x-1])>1:\n ans+=str(int(s[x-1])-1)\n ans+="9"*(cur+n-x-1)\n return ans\n ans+=str(s[x])*cur\n return ans\n\t``` | 2 | 0 | [] | 0 |
monotone-increasing-digits | [Java] Clean solution. Beat 100%. O(D) Time and O(1) space | java-clean-solution-beat-100-od-time-and-z6qc | \nclass Solution {\n public int monotoneIncreasingDigits(int n) {\n int power = 1;\n int toAdd = 0;\n int prev = 9;\n \n w | roka | NORMAL | 2020-05-15T07:03:39.098374+00:00 | 2020-05-15T07:03:39.098434+00:00 | 174 | false | ```\nclass Solution {\n public int monotoneIncreasingDigits(int n) {\n int power = 1;\n int toAdd = 0;\n int prev = 9;\n \n while (n != 0) {\n int current = n % 10;\n n /= 10;\n \n if (current > prev) {\n toAdd = power - 1;\n current -= 1;\n prev = current;\n }\n \n toAdd += current * power;\n prev = Math.min(prev, current);\n power *= 10;\n }\n \n return toAdd;\n }\n}\n``` | 2 | 0 | [] | 0 |
monotone-increasing-digits | Java Solution that beats 91.99% of java online submissions in O (n^2) in worst case | java-solution-that-beats-9199-of-java-on-in61 | class Solution {\n int n_num=0;\n public int monotoneIncreasingDigits(int N) {\n int num=N; int rem=0; boolean flag=true; \n\t\t//case 1\n w | tarushi | NORMAL | 2020-02-20T10:46:37.568225+00:00 | 2020-02-20T10:47:29.211001+00:00 | 99 | false | class Solution {\n int n_num=0;\n public int monotoneIncreasingDigits(int N) {\n int num=N; int rem=0; boolean flag=true; \n\t\t***//case 1***\n while(num!=1){\n rem=num%10;\n if(rem!=0){flag=false; break;}\n num=num/10;\n }\n if(num==1&&flag==true){return N-1;}\n\t\t***//case 2***\n int old_rem=-1;\n num=N; flag=true;\n while(num!=0){\n rem=num%10;\n if(old_rem!=-1&&rem>old_rem){\n flag=false; break;\n }\n old_rem=rem;\n num=num/10;\n }\n if(flag==true){return N;}\n\t\t***//case 3***\n int count=0; num=N;rem=0;\n while(num!=0){\n rem=num%10;\n count+=1;\n num=num/10;\n }\n int arr[]=new int[count];\n Arrays.fill(arr,0);\n num=N; rem=0;\n int id=arr.length-1;\n while(num!=0){\n rem=num%10;\n arr[id]=rem;\n id--;\n num=num/10;\n }\n id=arr.length-1;\n while(true){\n int j=arr[id]; flag=false;\n for( j=arr[id];j>=0;j--){\n arr[id]=j;\n if(sorted(arr,N)==true){\n flag=true; break;\n }\n }\n if(flag==false&&j<=0){\n arr[id]=9;\n }\n if(flag==true){\n break;\n }\n id=id-1;\n }\n if(flag==true){return n_num;}\n return 0;\n }\n public boolean sorted(int []arr ,int N){\n n_num=0;\n for(int i=0;i<=arr.length-2;i++){\n if(arr[i]>arr[i+1]){\n return false;\n }\n }\n for(int val:arr){\n n_num=n_num*10+val;\n }\n if(n_num>N){return false;}\n return true;\n }\n}\n\n***///DESCRIPTION\n// case 1- for numbers like 100, 1000, 10000, etc\n//case 2 for already increasing numbers eg 1234\n// case 3 for numbers like 4321, 332, etc***\n | 2 | 0 | [] | 0 |
monotone-increasing-digits | creative c++ solution | creative-c-solution-by-mamaly100-ipyh | \nclass Solution {\npublic:\n int check_index = 0;\n string process(int n)\n {\n string str = to_string(n);\n if (str.size()==1) // one d | mamaly100 | NORMAL | 2019-08-06T19:53:18.211097+00:00 | 2019-08-06T19:53:18.211131+00:00 | 257 | false | ```\nclass Solution {\npublic:\n int check_index = 0;\n string process(int n)\n {\n string str = to_string(n);\n if (str.size()==1) // one digit\n return str;\n if (check_index == 1) return str; // check if string is not monotone\n for(int i =check_index-1;i>0;i--)\n {\n if ((str[i]-\'0\'<str[i-1]-\'0\')) // if not monotone decrease current digit by one;\n {\n str[i-1] =(str[i-1]-\'0\'-1)+\'0\';\n check_index = i;\n for(int t = i;t<str.size();t++) str[t] = 9 + \'0\'; //all next values set to 9\n }\n else if(i==1) return str;\n }\n return process(stoi(str));\n }\n \n int monotoneIncreasingDigits(int N) {\n check_index = to_string(N).size();\n return stoi(process(N));\n }\n};\n``` | 2 | 0 | [] | 0 |
monotone-increasing-digits | Swift 8ms & beat 100 with space | swift-8ms-beat-100-with-space-by-buburin-wz6p | \nfunc monotoneIncreasingDigits(_ N: Int) -> Int {\n if N < 10{\n return N\n }\n var N = String(N).characters.map{Int(String($0) | Buburino | NORMAL | 2019-04-16T16:30:14.103796+00:00 | 2019-04-16T16:30:14.103868+00:00 | 88 | false | ```\nfunc monotoneIncreasingDigits(_ N: Int) -> Int {\n if N < 10{\n return N\n }\n var N = String(N).characters.map{Int(String($0))!}\n var lastChanged = -1\n for i in stride(from: N.count - 1, to:0, by: -1){\n if N[i-1] > N[i]{\n N[i] = 9\n N[i-1] = N[i-1] - 1\n lastChanged = i\n }\n }\n \n if lastChanged != -1{\n var rightIndex = lastChanged + 1\n while(rightIndex < N.count){\n N[rightIndex] = 9\n rightIndex += 1\n }\n }\n \n if N[0] <= 0{\n N.remove(at: 0)\n }\n return Int(N.map{String($0)}.joined())!\n }\n``` | 2 | 0 | [] | 0 |
monotone-increasing-digits | My simple Java solution | my-simple-java-solution-by-davidsoon-53nz | Starting from the right most bit. It should be greater than or equal to the one to its left. If it is true, skip. For example, 1234. It will return 1234. \nelse | davidsoon | NORMAL | 2018-01-05T06:41:47.502000+00:00 | 2018-01-05T06:41:47.502000+00:00 | 342 | false | Starting from the right most bit. It should be greater than or equal to the one to its left. If it is true, skip. For example, 1234. It will return 1234. \nelse, arr[i - 1] - 1 and use j to track the position of i. Lastly, set all bits to 9 from j to the end. For example, 322 becomes 299.\n\n```\npublic int monotoneIncreasingDigits(int N) {\n char[] arr = String.valueOf(N).toCharArray();\n int len = arr.length, j = len;\n for (int i = len - 1; i > 0; i--) {\n if (arr[i] >= arr[i - 1]) continue;\n arr[i - 1]--;\n j = i;\n }\n for (int i = j; i < len; i++) {\n arr[i] = '9';\n }\n return Integer.valueOf(new String(arr));\n } | 2 | 0 | [] | 0 |
monotone-increasing-digits | Simple Java Solution with comments, explanation | simple-java-solution-with-comments-expla-dd5n | Scan the digits from right to left and mark the position of the digit which is greater than its right digit. Also, decrement this digit by one\nThen, all digits | ashish53v | NORMAL | 2017-12-03T04:02:02.783000+00:00 | 2017-12-03T04:02:02.783000+00:00 | 519 | false | Scan the digits from right to left and mark the position of the digit which is greater than its right digit. Also, decrement this digit by one\nThen, all digits from index 0 to index pos will be taken as it is (as they are at their correct place, montone increasing), whereas digits from index pos + 1 to the last digit will be taken as 9\n```\nclass Solution {\n public int monotoneIncreasingDigits(int N) {\n if(N < 10)\n return N;\n List<Integer> list = new ArrayList<>();\n \n // get the digits of N in list;\n helper(list,N);\n \n int l = list.size();\n \n int pos = l - 1;\n \n //scan the list from right to left\n //mark the position of the digit which is greater than it's right digit\n //decrement this digit by one.\n for(int i=l-1;i>0;i--){\n if(list.get(i) < list.get(i-1)){// here digit at i is less than digit at i-1, so decrement list(i-1) and set pos to i-1\n int num = list.get(i-1);\n pos = i - 1;\n list.set(i-1,num-1);\n }\n }\n int res = 0;\n //scan the list from left to right\n //digits which are in the index range 0 to pos, add them as it is\n //digits after pos+1 index will be taken as 9\n for(int i=0;i<l;i++){\n if(i <= pos){\n int n = list.get(i); \n res = (res * 10) + n;\n }else{\n res = (res * 10) + 9;\n }\n } \n return res;\n \n }\n \n public void helper(List<Integer> list,int n){\n while(n > 0){\n int k = n % 10;\n list.add(k);\n n /= 10;\n } \n Collections.reverse(list); \n return;\n }\n}\n```\n\n// e.g. N = 1234267\n//first, take the digits of N in a list\n\n//in first for loop \n// scan from right to left\n// i = 6 67 ok\n// i = 5 then 26 is also fine\n// i = 4 then 42...not ok..as 4 is greater than its right digit 2..so mark this position (i-1) (pos = 3) and decrement 4 by 1,\n//now list contains 1 2 3 3 2 6 7\n//then keep on scanning, there are no changes in list as rest digits are in correct position and pos is still 3 (4th digit)\n\n//second for loop\n//take the digits from index 0 to index pos as it is\n// so now number is 1233\n//then for digits at index pos + 1 to last digit, take them as 9\n// so number becomes 1233999\n//this is the answer | 2 | 2 | [] | 0 |
monotone-increasing-digits | Greedy Solution C++ | greedy-solution-c-by-venkadkrishna-3vm5 | IntuitionGreedily try to maximise the number monotonically. When we encounter digits that are not monotonous, decrease its value and set the following number to | venkadkrishna | NORMAL | 2025-01-01T02:47:13.008904+00:00 | 2025-01-01T02:47:13.008904+00:00 | 118 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
Greedily try to maximise the number monotonically. When we encounter digits that are not monotonous, decrease its value and set the following number to 9. Do this till monotonocity is satisfied
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
$$O(K)$$ where $$K$$ is the number of digits in the input.
# Code
```cpp []
class Solution {
public:
int monotoneIncreasingDigits(int n) {
string s = to_string(n);
bool monotone = true;
int i = 0;
for (i = 0; i < s.size() - 1; i++) {
if (s[i] > s[i+1]) {
monotone = false;
break;
}
}
int k = i + 1;
for (; k < s.size(); k++) {
s[k] = '9';
}
s[i] = char(s[i] - 1);
while (i-1 >= 0 && s[i] < s[i-1]) {
s[i-1] = char(s[i-1] - 1);
s[i] = '9';
i--;
}
if (monotone) return n;
return stoi(s);
}
};
``` | 1 | 0 | ['C++'] | 0 |
monotone-increasing-digits | SImple Python integer to string conversion | O(logn) solution beats 100% | simple-python-integer-to-string-conversi-9iag | Intuition\n Describe your first thoughts on how to solve this problem. \nFairly simple solution, by converting the number to a string.\n# Approach\n Describe yo | FFblaze | NORMAL | 2024-11-26T04:15:53.530809+00:00 | 2024-11-26T04:19:04.184625+00:00 | 76 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nFairly simple solution, by converting the number to a string.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nBasically, we traverse throught the string and find the first occurrence where the current digit is smaller thant the previous digit (as it needs to be monotonically increasing).\n\nThe next step is to subtract the number in the string present from the ith index to the end of the string from the position where k[i] < k[i-1].\n\nSo for example, if I have the number 33332201, we can find the first index where \nk[i] < k[i-1]. \n\nFrom the example we can see that at the index = 4 (3>2) is smaller than the element at index = 3.\n\nSo now we take number from index 4 to the end of the string and subtract it with the original number and one.\n```\n 33332201 - 2201 - 1 = 33329999\n```\n\nHowever, the number still does not satisfy the condition, as the element at index 2 is greater than the element at index 3, hence we reset the loop and compute the process again, untill the number is increasing.\n```\n33329999 - 29999 -1 = 33299999\n33299999 - 299999 -1 = 32999999\n32999999 - 2999999 -1 = 29999999\n```\n\n\n# Complexity\n- Time complexity: O(logn)\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```python3 []\nclass Solution:\n def monotoneIncreasingDigits(self, n: int) -> int:\n k=str(n)\n i=1\n while i<len(k):\n if k[i]<k[i-1]:\n k=str(int(k)-int(k[i:])-1) \n i=1\n elsee:\n i+=1\n return int(k)\n \n\n``` | 1 | 0 | ['Python3'] | 0 |
monotone-increasing-digits | Simple solution | Arrays | | simple-solution-arrays-by-mriprasanna192-zbs3 | Intuition\nThe goal is to find the largest number less than or equal to n that has its digits in non-decreasing order (i.e. monotone increasing). To achieve thi | prasanna192005 | NORMAL | 2024-07-24T11:05:13.898351+00:00 | 2024-07-24T11:05:13.898376+00:00 | 29 | false | # Intuition\nThe goal is to find the largest number less than or equal to n that has its digits in non-decreasing order (i.e. monotone increasing). To achieve this, we can follow these steps:\n\nIdentify the Problem: If a digit is smaller than the digit before it, the number is not monotone increasing.\nAdjust the Digits: To make the number monotone increasing, we can decrement the digit before the drop and set all subsequent digits to \'9\'(as 9 is the larget digit(0-9)) to maximize the resulting number.\n\n# Approach\n> You can also use Stringbuilder or Stacks to do same\n\n1.Convert the Integer to a Character Array:\n\n2.Convert the integer n to a string and then to a character array. This allows us to easily manipulate individual digits.\nIdentify the First Decreasing Digit:\n\n3.Traverse the character array from right to left. Find the first digit that is smaller than the digit before it. This indicates where the sequence starts to decrease.\nAdjust the Digits:\n\n4.Once a decreasing point is identified, decrement the digit before the point where the sequence starts to decrease. Set all digits to the right of this position to \'9\' to maximize the number while ensuring it remains monotone increasing.\nConvert Back to an Integer:\n\n9.Convert the adjusted character array back to a string and then to an integer to obtain the final result.\n\n# Complexity\n- Time complexity:\nO(n) n is number of digits in given int.\n\n- Space complexity:\nO(n) n is number of digits in given int.\n\n# Code\n```\nclass Solution {\n public int monotoneIncreasingDigits(int n) {\n \n char []chara =Integer.toString(n).toCharArray();\n \n int track=chara.length;\n for(int i=track-1;i>0;i--){\n if(chara[i]<chara[i-1]){\n track=i;\n chara[i-1]--;\n }\n }\n for (int i =track; i <chara.length; i++) {\n chara[i] = \'9\';\n }\n return Integer.parseInt(new String(chara));\n }\n}\n``` | 1 | 0 | ['Java'] | 0 |
monotone-increasing-digits | Solution #085 | solution-085-by-coderx85-eydm | Intuition\nTo find the largest monotone increasing number less than or equal to the given number n, we need to iterate through the digits of n. Whenever we enco | coderx85 | NORMAL | 2024-05-01T05:56:42.787914+00:00 | 2024-05-01T05:56:42.787950+00:00 | 9 | false | # Intuition\nTo find the largest monotone increasing number less than or equal to the given number `n`, we need to iterate through the digits of `n`. Whenever we encounter a digit that is greater than its next digit, we decrement that digit by 1 and set all the following digits to 9 to maintain the monotonicity property.\n\n# Approach\n1. Convert the given integer `n` to a string `s`.\n2. Iterate through the string from right to left.\n3. Whenever we find a digit that is greater than its next digit, mark the position and decrement the current digit by 1.\n4. Set all the digits to the right of the marked position to 9.\n5. Convert the modified string back to an integer and return the result.\n\n# Complexity\n- Time complexity: $$O(\\log n)$$, where `n` is the given integer. Converting `n` to a string takes $$O(\\log n)$$ time, and iterating through the string once takes linear time.\n \n- Space complexity: $$O(\\log n)$$ for storing the string representation of `n`.\n\n# Code\n```\nclass Solution {\nprivate:\n int solve(int n){\n string s = to_string(n);\n int t = s.size();\n int lim = s.size();\n for(int i = t - 1; i > 0; i--){\n if(s[i - 1] > s[i]){\n lim = i;\n s[i - 1] -= 1;\n }\n }\n for(int i = lim; i < t; i++) \n s[i] = \'9\';\n return stoi(s);\n }\n\npublic:\n int monotoneIncreasingDigits(int n) {\n return solve(n);\n }\n};\n``` | 1 | 0 | ['C++'] | 0 |
monotone-increasing-digits | Simple Java Solution | simple-java-solution-by-shubhamp1406-v5ug | Intuition\ncheck the number and find out the digit where the condition is not statisfied.Suppose the index at which the condition is not statisfied is "i", then | ShubhamP1406 | NORMAL | 2024-04-03T01:58:36.276443+00:00 | 2024-04-03T01:58:36.276467+00:00 | 20 | false | # Intuition\ncheck the number and find out the digit where the condition is not statisfied.Suppose the index at which the condition is not statisfied is "i", then reduce it by 1 and make the remaining digits 9(i.e. convert the digits from i+1 to 9). This will give you the greatest possible number.\n\n# Approach\nConvert the given number into an array. From back side check the monoonic condition.if it is being voilated at particular index mark that index. \n\nFor eg:- in 332 condition is being voileted at index 1 i.e. 3 so reduce it by 1 now the number will be 322. since we are iterating from backsidethe condition is being violated so again reduce it by 1 so the number will be 222 but is this largest number?\n\nNo , so that is the reason we need to convert every digit to 9 from the index where the digit has been reduced. Hence number will be 299.\n\n# Complexity\n- Time complexity:\nO(n)+ O(length of digit array- last index where the digit is reduced) + O(n) ~ O(n)\n\n- Space complexity:\nSuppose there are n digits in number so Space complexity will be O(n), since we are using an array.\n\n# Code\n```\nclass Solution {\n\n \n\n \n public int monotoneIncreasingDigits(int n) {\n\n int[] dig = Integer.toString(n).chars().map(c -> c - \'0\').toArray();\n\n \n int idx=dig.length;\n\n for(int i=dig.length-1;i>0;i--)\n {\n if(dig[i]<dig[i-1])\n {\n idx=i;\n dig[i-1]--;\n }\n }\n\n\n for(int i=idx;i<dig.length;i++)\n {\n dig[i]=9;\n\n }\n\n\n\n\n int num=0;\n\n for(int i=0;i<dig.length;i++)\n {\n num=10*num+ dig[i];\n }\n \n return num;\n }\n \n}\n``` | 1 | 0 | ['Greedy', 'Java'] | 0 |
monotone-increasing-digits | 2-solution with Concept | 2-solution-with-concept-by-shree_govind_-laqt | 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 | Shree_Govind_Jee | NORMAL | 2023-12-20T01:32:24.739028+00:00 | 2023-12-20T01:32:24.739062+00:00 | 23 | false | # 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 {\n // private boolean satisfies(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 // public int monotoneIncreasingDigits(int n) {\n // while(!satisfies(n)){\n // n--;\n // }\n // return n;\n // }\n\n\n public int monotoneIncreasingDigits(int n) {\n int p, dnp;\n while((p=helper(n)) != -1){\n dnp = ((int)(n/Math.pow(10, p-1)))%10;\n n -= Math.pow(10, p-1)*(dnp+1);\n n -= n%Math.pow(10, p);\n n += Math.pow(10, p) - 1;\n }\n return n;\n }\n\n private int helper(int n){\n int k = 10;\n int p=0;\n while(n>0){\n if(k < n%10){\n return p;\n } else{\n k = n%10;\n n /= 10;\n p++;\n }\n }\n return -1;\n }\n}\n``` | 1 | 0 | ['Math', 'Greedy', 'Java'] | 0 |
monotone-increasing-digits | simple priority queue approach to optimised sol || 2 ways | simple-priority-queue-approach-to-optimi-8ngi | Simply genrate all numbers according to constrain take maximum till we reach the same length as given number \n\nclass Solution {\npublic:\n \n \n int | demon_code | NORMAL | 2023-09-16T11:40:33.809486+00:00 | 2023-09-16T11:41:37.060006+00:00 | 448 | false | Simply genrate all numbers according to constrain take maximum till we reach the same length as given number \n```\nclass Solution {\npublic:\n \n \n int monotoneIncreasingDigits(int n) \n {\n long long num=n;\n if(num==0) return 0;\n if(num<=10)return 9;\n priority_queue<long long>pq;\n for(int i=1; i<=9; i++)\n {\n pq.push(i);\n }\n \n long long ans=0;\n int s= to_string(num).size();\n int c=0;\n while(!pq.empty())\n {\n long long it= pq.top();\n pq.pop();\n c++;\n ans=max(ans, it);\n if(to_string(it).size()==s)\n {\n break;\n }\n int last= it%10;\n for(int i=last; i<=9; i++)\n {\n if(((1ll*it*10) +i) <=num) pq.push(it*10+i);\n }\n }\n \n return (int)ans;\n \n \n }\n};\n\n```\n\n\n\nOptimised version\n\n```\nclass Solution {\npublic:\n \n \n int monotoneIncreasingDigits(int n) \n {\n long long num=n;\n if(num==0) return 0;\n if(num<=10)return 9;\n priority_queue<long long>pq;\n for(int i=1; i<=9; i++)\n {\n pq.push(i);\n }\n \n long long ans=0;\n int s= to_string(num).size();\n int c=0;\n while(!pq.empty())\n {\n long long it= pq.top();\n pq.pop();\n c++;\n ans=max(ans, it);\n if(to_string(it).size()==s)\n {\n break;\n }\n int last= it%10;\n for(int i=last; i<=9; i++)\n {\n if(((1ll*it*10) +i) <=num) pq.push(it*10+i);\n }\n }\n \n return (int)ans;\n \n \n }\n};\n``` | 1 | 0 | ['Greedy', 'C', 'Heap (Priority Queue)'] | 0 |
monotone-increasing-digits | Beats 100% | beats-100-by-antony_ft-5gb7 | 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 | antony_ft | NORMAL | 2023-07-24T15:58:31.319743+00:00 | 2023-07-24T15:58:31.319766+00:00 | 12 | 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 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``` | 1 | 0 | ['C++'] | 0 |
monotone-increasing-digits | Python Solution Using Backtracking || Easy to Understand | python-solution-using-backtracking-easy-bt0wl | \nclass Solution:\n def monotoneIncreasingDigits(self, n: int) -> int:\n\t\t# max size of string\n self.maxlen = len(str(n))\n\t\t# maximum ans store | mohitsatija | NORMAL | 2023-01-21T13:11:46.858223+00:00 | 2023-01-21T13:11:46.858268+00:00 | 1,126 | false | ```\nclass Solution:\n def monotoneIncreasingDigits(self, n: int) -> int:\n\t\t# max size of string\n self.maxlen = len(str(n))\n\t\t# maximum ans store here\n self.maxans = 0\n self.find(str(n))\n return self.maxans\n \n def find(self,num,idx=0,curnum=\'\',pb=None):\n\t\t# idx is size counter of current number (curnum) pb represents previous bit/number at idx position\n\t\t\'\'\'\n\t\t\tThis Approach uses leading zeros in number that means\n\t\t\tif we are looking for ans for value 10 it will be 09 instead of 9\n\t\t\tbut int(\'09\') = 9 so we receive our output. hence length of final\n\t\t\toutput will always be equal to length of string i.e. self.maxlen\n\t\t\t\n\t\t\twe\'ll start creating number from backside for example if we are looking for\n\t\t\tn = 1234 first bit in first iteration will be 1 then we\'ll place second bit in the range\n\t\t\tof 1-9 and third bit in the range of 2-9.\n\t\t\t\n\t\t\tAs soon as we receive one ans that will be the largest one we stop the recursion and returns\n\t\t\tthe answer\n\t\t\'\'\'\n if idx == self.maxlen:\n self.maxans = max(self.maxans,int(curnum))\n\t\t# if we have received our ans we will stop backtracking immediatly\n if idx >= self.maxlen or self.maxans:\n return\n\t\t# if first time call\n if not pb:\n for i in range(int(num[idx]),-1,-1):\n self.find(num,idx+1,curnum+str(i),num[idx])\n\t\t# otherwise\n else:\n for i in range(9,int(pb)-1,-1):\n if int(curnum+str(i))<=int(num[:idx+1]):\n self.find(num,idx+1,curnum+str(i),num[idx])\n``` | 1 | 0 | ['Math', 'Backtracking', 'Greedy', 'Recursion', 'Python', 'Python3'] | 0 |
monotone-increasing-digits | [javascript]fast than 100% | javascriptfast-than-100-by-youhan26-4nei | Intuition\n Describe your first thoughts on how to solve this problem. \nfind first decrease number and set it 9\n\n# Approach\n Describe your approach to solvi | youhan26 | NORMAL | 2023-01-12T03:40:30.308580+00:00 | 2023-01-12T03:40:30.308625+00:00 | 134 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nfind first decrease number and set it 9\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n* return n if n is less then 10\n* for i: String(n)\n* find first y that is less then before\n* find max number x before y\n\ncombine result:\n* same with n when index < x\n* x-1 when index == x\n* 9 when index >=y\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```\n/**\n * @param {number} n\n * @return {number}\n */\nvar monotoneIncreasingDigits = function(n) {\n const str = String(n);\n const len = str.length;\n\n let increaseIndex = 0;\n let nineIndex = 0;\n\n for(let i = 1;i<len;i++){\n const diff = str[i] - str[i-1];\n if(diff === 0){\n continue;\n }\n if(diff > 0){\n increaseIndex = i;\n }\n if(diff <0){\n nineIndex = i;\n break;\n }\n }\n if(increaseIndex === nineIndex){\n return n;\n }\n if(nineIndex ==0){\n return n;\n }\n let result = \'\';\n for(let i =0;i<len;i++){\n if(i<increaseIndex){\n result += str[i];\n continue;\n }\n if(i>=nineIndex || i >increaseIndex){\n result += \'9\'\n continue;\n }\n if(i == increaseIndex){\n result += str[i]-1; \n }\n }\n return result;\n};\n``` | 1 | 0 | ['JavaScript'] | 0 |
monotone-increasing-digits | Recursion + Greedy | Clean and concise code | recursion-greedy-clean-and-concise-code-m99fd | Approach\nTry every possible valid combination\n\n# Complexity\n- Time complexity: O(2^N)\n- Space complexity: O(N) for ans string\n\n# Code\n\nclass Solution { | _Pinocchio | NORMAL | 2022-10-26T05:30:12.283388+00:00 | 2022-10-26T05:30:12.283429+00:00 | 80 | false | # Approach\nTry every possible valid combination\n\n# Complexity\n- Time complexity: O(2^N)\n- Space complexity: O(N) for ans string\n\n# Code\n```\nclass Solution {\nprivate:\n bool solve(int i,string &ans,bool lim,string &str){\n if(i == str.size()) return ans <= str;\n char st = lim ? str[i] : \'9\';\n for(char ch = st;ch >= ans.back();ch--){\n ans += ch;\n if(solve(i+1,ans,lim ? ch == str[i] : false,str)) return true;\n ans.pop_back();\n }\n\n return false;\n }\npublic:\n int monotoneIncreasingDigits(int n) {\n string str = to_string(n);\n for(char ch = str[0];ch>=\'0\';ch--){\n string ans;\n ans+=ch;\n if(solve(1,ans,ch == str[0],str)) return stoi(ans);\n }\n return -1;\n }\n};\n``` | 1 | 0 | ['Greedy', 'Recursion', 'C++'] | 0 |
monotone-increasing-digits | Easy C++ solution with explaination. | easy-c-solution-with-explaination-by-cha-yr14 | Main Concept\n\nFirst let us consider the number as a string of digits. E.g: 123 is "123" with size 3.\n\n Violation occurs if for any digit the previous digit | chandanmahto00761 | NORMAL | 2022-09-06T20:48:11.726117+00:00 | 2022-09-06T20:48:11.726150+00:00 | 452 | false | ### Main Concept\n\nFirst let us consider the number as a string of digits. E.g: 123 is "123" with size 3.\n\n* Violation occurs if for any digit the previous digit is greater i.e \n\n\t``` s[i-1] > s[i] for i in 1...n-1``` where n is number of digits.\n\t\t\t\t\n* For any violation, we can decrease the previous digit and set the following digits to 9 to remove the violation.\n\n\tEg: In `14211` the violating digits are `4` and `2`. If we decrease `4` and set the digits following `4` to `9` we get `13999` which is the optimal solution.\n\n* Doing the previous step will also remove all other violations as well if they exist.\n* If there are digits immediately before the previous digit of the violating pair, that are equal to the previous digit, we need to decrease the first occurance of the previous digit and set the following digits to 9.\n\n\tEg: In `188882` the violating pair is `8` and `2` at index `4` and `5` respectively. \n\tNow since the digits between indices `1` and `3` are equal to previous digit `8` at index `4` we will decrease the first occurance of `8` at index `1` and set the following digits to `9`. \n\tThis will give us the solution `179999` which is the optimal solution.\n\t\n<hr>\n<br>\n\n### Code\n\n```\nclass Solution {\n \n string num;\n \n int findViolationPosition() {\n for(int i=1; i < num.size(); i++) {\n // check if previous number greater than next i.e violation\n if(num[i-1] > num[i])\n return i;\n }\n return -1; \n }\n \n int findSmallestIndexToChange(int violation_position) {\n int smallest_index = violation_position - 1;\n for(; smallest_index >=0; smallest_index--) {\n if(num[smallest_index] != num[violation_position-1]) {\n break;\n }\n }\n return smallest_index+1;\n }\n \n string removeViolations(int smallest_index) {\n string sol = num;\n sol[smallest_index]--;\n for(int i=smallest_index+1; i<sol.size(); i++) {\n sol[i] = \'9\';\n }\n return sol;\n }\n \npublic:\n int monotoneIncreasingDigits(int n) {\n \n // store the number in string format \n num = to_string(n);\n \n // find the position where violation occurs\n int violation_position = findViolationPosition();\n \n // if no violation then the current number is the answer\n if(violation_position == -1) \n return n;\n \n // find the smallest index that must be changed to remove violation.\n int smallest_index = findSmallestIndexToChange(violation_position);\n \n \n // decrease the number at the smallest_index and make every number after it as 9\n string ans = removeViolations(smallest_index);\n \n return stoi(ans);\n }\n};\n```\n\n\n### Variable values for sample input.\n\n```\nn = 182\nnum = "182"\nviolation_position = 2\nsmallest_index = 1\nans = "179"\n```\n\n\n```\nn = 188882\nnum = "188882"\nviolation_position = 5\nsmallest_index = 1\nans = "179999"\n```\n\n<hr>\n<br>\n\n\n### Complexities\n\nTime Complexity = O(1)\nSpace Complexity = O(1) \n | 1 | 0 | ['Greedy'] | 1 |
monotone-increasing-digits | Follow up | Can't cast into string/array | follow-up-cant-cast-into-stringarray-by-5eb27 | The simpler solution is to cast the number into a string/array, run the algorithm and cast back.\n\nA follow up question is to perform the algorithm without cas | nadaralp | NORMAL | 2022-08-11T13:54:07.197706+00:00 | 2022-08-11T13:54:55.955243+00:00 | 67 | false | The simpler solution is to cast the number into a string/array, run the algorithm and cast back.\n\nA follow up question is to perform the algorithm without casting.\n\nWe still need to iterate and find "indexes" in the number where the monotonic property breaks. Whenever we find such location we decrease the current number by -1 and maximize all numbers to the right to 9.\n\nTo iterate over the numbers we\'ll have to divide by `10^k` and take the `%10` of the result to look at the right most number.\n\n```\nclass Solution:\n def monotoneIncreasingDigits(self, n: int) -> int:\n if n < 10: return n\n \n output = 0\n k = 0\n \n while n >= 10**k:\n if k == 0:\n output += n % 10\n k += 1\n continue\n \n cur = (n // 10**k) % 10\n _next = output // 10**(k-1) % 10\n \n if cur > _next:\n # decrement current by one\n output += (cur - 1) * 10**k\n \n\t\t\t\t# Change all to the right to 9\n for j in range(k-1, -1, -1):\n num_in_location = output // 10**j % 10\n output += (9 - num_in_location) * 10**j # complement to 9\n \n else:\n output += cur * 10**k\n \n k += 1\n \n return output\n``` | 1 | 0 | [] | 0 |
monotone-increasing-digits | Python solution with explanation | python-solution-with-explanation-by-vinc-nznl | \n135549 --> 134999\n1. The monotone increasing stop at index = 3 with digit \'5\'\n2. The left most digit of \'5\' is at index = 2 \n3. The left part of the an | vincent_great | NORMAL | 2022-08-09T22:41:28.754026+00:00 | 2022-08-09T22:41:28.754062+00:00 | 61 | false | ```\n135549 --> 134999\n1. The monotone increasing stop at index = 3 with digit \'5\'\n2. The left most digit of \'5\' is at index = 2 \n3. The left part of the answer is str(int(s[:2+1])-1)\n4. The remaining part is filled up with \'9\' \n```\n\nThe following is the python implementation\n\n```\ndef monotoneIncreasingDigits(self, n: int) -> int:\n\tif n<10:\n\t\treturn n\n\tn, i = str(n), 0\n\twhile(i<len(n)-1 and n[i]<=n[i+1]):\n\t\ti+=1 # find the index breaking monotone changes\n\tif i==len(n)-1:\n\t\treturn int(n) # It means all of digits are monotone increased\n\twhile(i>0 and n[i]==n[i-1]):\n\t\ti-=1\n\ta = str(int(n[:i+1])-1)+\'9\'*(len(n)-i-1)\n\treturn int(a)\n``` | 1 | 0 | [] | 0 |
monotone-increasing-digits | C++ 0ms 100%faster approach | c-0ms-100faster-approach-by-dg150602-ptj5 | ```\nclass Solution {\npublic:\n int monotoneIncreasingDigits(int n) {\n int check=0,index=0;\n if(n<10)\n return n;\n string | dg150602 | NORMAL | 2022-05-01T09:05:51.761113+00:00 | 2023-06-20T03:02:04.487608+00:00 | 100 | false | ```\nclass Solution {\npublic:\n int monotoneIncreasingDigits(int n) {\n int check=0,index=0;\n if(n<10)\n return n;\n string s=to_string(n);\n for(int i=0;i<s.length()-1;i++)\n {\n if(s[i]>s[i+1])\n {index=i;\n check=1;\n break;\n }}\n if(check==0)\n return n;\n s[index]--;\n if(index>=1)\n {for(int i=index;i>0;i--)\n{\n if(s[i-1]>s[i])\n {s[i-1]=s[i];\n index=i-1;\n}}}\n for(int i=index+1;i<s.length();i++)\n s[i]=\'9\';\n return stoi(s);\n }\n}; | 1 | 0 | ['Math', 'Greedy'] | 0 |
monotone-increasing-digits | Concise BruteForce [Java] | concise-bruteforce-java-by-student2091-wz1e | We can really just bruteforce it and it\'d be fast enough given there aren\'t that many eligible numbers to try anyways.\n\nJava\nclass Solution {\n public i | Student2091 | NORMAL | 2022-04-16T08:20:05.384777+00:00 | 2022-04-16T08:20:05.384810+00:00 | 101 | false | We can really just bruteforce it and it\'d be fast enough given there aren\'t that many eligible numbers to try anyways.\n\n```Java\nclass Solution {\n public int monotoneIncreasingDigits(int n) {\n return (int)solve(1, 0, n);\n }\n\n private int solve(int st, long cur, int max){\n if (cur > max)\n return 0;\n long ans = cur;\n for (int i = st; i <= 9; i++){\n ans = Math.max(solve(i, 10 * cur + i, max), ans);\n }\n return (int)ans;\n }\n}\n``` | 1 | 0 | ['Java'] | 0 |
monotone-increasing-digits | java || 99% faster code | java-99-faster-code-by-shivrastogi-b4j1 | \'\'\'\n\nclass Solution {\n public int monotoneIncreasingDigits(int n) {\n String str = String.valueOf(n);\n int length = str.length();\n | shivrastogi | NORMAL | 2022-03-19T11:47:23.882224+00:00 | 2022-03-19T11:47:23.882259+00:00 | 83 | false | \'\'\'\n\nclass Solution {\n public int monotoneIncreasingDigits(int n) {\n String str = String.valueOf(n);\n int length = str.length();\n int[] nums = new int[length];\n int idx = length;\n int ans = 0;\n for (int i = 0; i < length; i++) {\n nums[i] = Integer.parseInt(str.substring(i, i + 1));\n if (i > 0 && nums[i-1] > nums[i]) {\n idx = Math.min(idx, i - 1);\n while (idx > 0 && nums[idx - 1] == nums[idx]) {\n idx--;\n }\n }\n }\n for (int i = 0; i < length; i++) {\n if (i < idx) {\n ans = 10 * ans + nums[i];\n } else if (i == idx) {\n ans = 10 * ans + (nums[i] - 1);\n } else {\n ans = 10 * ans + 9;\n }\n }\n return ans;\n }\n} | 1 | 0 | [] | 0 |
monotone-increasing-digits | easy c++ solution | easy-c-solution-by-adtyaofficial17-qk4a | ```\nclass Solution {\npublic:\n int monotoneIncreasingDigits(int n) {\n if(n==0)\n return n;\n \n vector mad;\n while | AdityaGupta-Official | NORMAL | 2022-02-18T22:39:02.722294+00:00 | 2022-02-18T22:39:02.722328+00:00 | 81 | false | ```\nclass Solution {\npublic:\n int monotoneIncreasingDigits(int n) {\n if(n==0)\n return n;\n \n vector<int> mad;\n while(n>0)\n {\n mad.push_back(n%10);\n n=n/10;\n }\n reverse(mad.begin(),mad.end());\n for(int i=(mad.size()-2);i>=0;i--)\n {\n if(mad[i]>mad[i+1])\n {\n mad[i]--;\n for(int j=i+1;j<mad.size();j++)\n {\n mad[j]=9;\n }\n }\n }\n \n long long ans=0;\n for(int i=0;i<mad.size();i++)\n {\n ans=ans*10 + mad[i];\n }\n \n return ans;\n \n }\n}; | 1 | 0 | [] | 0 |
monotone-increasing-digits | 0ms beats 100%, c++ recursive solution | 0ms-beats-100-c-recursive-solution-by-an-3n3v | ```\nint monotoneIncreasingDigits(int n) {\n if(n>=0&&n<=9){\n return n;\n }\n string s=to_string(n);\n int i=1;\n | animesh8 | NORMAL | 2022-02-18T17:49:01.848319+00:00 | 2022-02-18T17:49:01.848371+00:00 | 85 | false | ```\nint monotoneIncreasingDigits(int n) {\n if(n>=0&&n<=9){\n return n;\n }\n string s=to_string(n);\n int i=1;\n for(i;i<s.size();i++){\n if(s[i]<s[i-1]){\n break;\n }\n }\n if(i==s.size()){\n return n;\n }\n string temp;\n for(int j=i;j<s.size();j++){\n temp+=s[j];\n }\n int x=stoi(temp);\n return monotoneIncreasingDigits(n-x-1);\n } | 1 | 0 | [] | 0 |
monotone-increasing-digits | Java 100% fast solution | java-100-fast-solution-by-rahaman612-q5sz | \nclass Solution {\n public int monotoneIncreasingDigits(int n) {\n for(int i = 10;n/i>0;i*=10){\n int digit = (n/i)%10;\n int e | rahaman612 | NORMAL | 2022-01-16T16:51:19.780651+00:00 | 2022-01-16T16:51:19.780692+00:00 | 117 | false | ```\nclass Solution {\n public int monotoneIncreasingDigits(int n) {\n for(int i = 10;n/i>0;i*=10){\n int digit = (n/i)%10;\n int endnum = n%i;\n int firstendnum = endnum*10/i;\n if(digit>firstendnum){\n n-=endnum+1;\n }\n }\n return(n);\n }\n}\n``` | 1 | 0 | [] | 1 |
monotone-increasing-digits | Python Solution beats 96.78% of Python Submissions | python-solution-beats-9678-of-python-sub-rg77 | Runtime: 24 ms, faster than 96.78% of Python3 online submissions for Monotone Increasing Digits.\nMemory Usage: 14.2 MB, less than 77.49% of Python3 online subm | reaper_27 | NORMAL | 2021-11-19T15:17:38.783408+00:00 | 2021-11-19T15:17:38.783449+00:00 | 116 | false | **Runtime: 24 ms, faster than 96.78% of Python3 online submissions for Monotone Increasing Digits.\nMemory Usage: 14.2 MB, less than 77.49% of Python3 online submissions for Monotone Increasing Digits.**\n\n```\nclass Solution:\n def monotoneIncreasingDigits(self, n: int) -> int:\n num=str(n)\n leng=len(num)\n prev=0\n ans=""\n for i in range(1,leng+1):\n if i==leng:\n while prev<leng:\n ans+=str(num[prev])\n prev+=1\n return int(ans)\n elif num[prev]==num[i]:continue\n elif num[prev]<num[i]:\n while prev<i:\n ans+=num[prev]\n prev+=1\n else:\n ans+=str(int(num[prev])-1)\n ans+=\'9\'*(leng-len(ans))\n return int(ans)\n``` | 1 | 0 | ['Greedy'] | 0 |
monotone-increasing-digits | WEEB DOES PYTHON (BEATS 96.76%) | weeb-does-python-beats-9676-by-skywalker-b1lh | \n\n1. The logic is simple, if we find that there is a digit that is greater than the next digit to the right. Then we minus 1 to the current digit and leave th | Skywalker5423 | NORMAL | 2021-11-16T03:59:53.930505+00:00 | 2021-11-16T04:00:36.820770+00:00 | 371 | false | \n\n1. The logic is simple, if we find that there is a digit that is greater than the next digit to the right. Then we minus 1 to the current digit and leave the remainding ["9"] until the len(result) == len(n), Otherwise, we copy the digit and change nothing to our result. Doing this, we can maintain a monotonic increasing result.\n\n2. However, consecutive digits of the same values can be a problem. Rather than coding it so that the current element is decremented by 1, we should actually be decrementing the first consecutive element by 1 instead.\n\n3. So, how do you do that? The answer is using a counter. This allows us to subtract the index of the current consectutive element with the counter to get the first occurence of the consecutive element.\n\n4. Once we get the first consective element, follow step 1.\n\t\n\t\n\t\tclass Solution:\n\t\t\tdef monotoneIncreasingDigits(self, n: int) -> int:\n\t\t\t\t# if n is sorted in the first place, the answer is n\n\t\t\t\tif int("".join(sorted(str(n)))) == n:\n\t\t\t\t\treturn n\n\n\t\t\t\tresult = ["9"] * len(str(n))\n\t\t\t\tnums = [int(i) for i in str(n)]\n\t\t\t\tcount = -1 # -1 because we are dealing with index\n\n\t\t\t\tfor i in range(len(nums)-1):\n\t\t\t\t\tif nums[i] > nums[i+1]: # step 1\n\t\t\t\t\t\tresult[i] = str(nums[i] - 1)\n\t\t\t\t\t\treturn int("".join(result))\n\n\t\t\t\t\telif nums[i] == nums[i+1]: # check for consecutive elements, step 2 to 3\n\t\t\t\t\t\tcount += 1\n\t\t\t\t\t\tif i+2 < len(nums) and nums[i+1] > nums[i+2]: \n\t\t\t\t\t\t\tresult[i-count] = str(nums[i-count] - 1) # step 4\n\t\t\t\t\t\t\t# backtrack to first consecutive element and minus 1, then add the remainding ["9"] until len(result) == len(nums)\n\t\t\t\t\t\t\treturn int("".join(result[:i-count+1] + ["9"] * (len(nums) - i + count - 1)))\n\n\t\t\t\t\t\t# if there are consecutive elements of different values, eg. 668841\n\t\t\t\t\t\t# check whether the i+1th consecutive element is <= to the i+2th element\n\t\t\t\t\t\telif i+2 < len(nums) and nums[i+1] <= nums[i+2]: \n\t\t\t\t\t\t\t# if both statements are true, that means we can maintain monotone increasing digits so we can safely copy the digit and change nothing to our result.\n\t\t\t\t\t\t\tresult[i] = str(nums[i])\n\n\t\t\t\t\telse: # step 1, we copy the digit and change nothing to our result.\n\t\t\t\t\t\tresult[i] = str(nums[i])\n\t\t\t\t\t\tcount = -1\n\t\t\t\t\t\t# reset counter since there could be multiple cosecutive elements\n\t\nAlright, hope this explanation is clear\nAnyways, its time for some anime recommendations\nTake a break, watch some anime\nCheck out **\u5F92\u7136\u30C1\u30EB\u30C9\u30EC\u30F3 (Tsuredure Children)**\n\n# Episodes: 12\n# Genres: Comedy, Romance\n# Theme: School\n# Demographic: Shounen\n\nA collection of multiple short stories jumbled up into 12 episodes. Enjoy the anime. | 1 | 0 | ['Math', 'Greedy', 'Python', 'Python3'] | 0 |
monotone-increasing-digits | 📌📌 O(n) 98% faster || Simple Logic || Well-Explained 🐍 | on-98-faster-simple-logic-well-explained-jnss | IDEA :\nKey point is for finding the monotonic increasing digit of any number you have to subtract its remainder+1 from the given number when you encounter oppo | abhi9Rai | NORMAL | 2021-10-29T14:58:17.257496+00:00 | 2021-10-29T14:58:17.257528+00:00 | 174 | false | ## IDEA :\nKey point is for finding the monotonic increasing digit of any number you have to subtract its **remainder+1** from the given number when you encounter opposite of it.\n\'\'\'\n\n\tExample: 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\n\'\'\'\n\n\tclass Solution:\n def monotoneIncreasingDigits(self, n: int) -> int:\n s = str(n)\n for i in range(len(s)-1,0,-1):\n if s[i]<s[i-1]:\n n = n-(int(s[i:])+1)\n s = str(n)\n return n\n \n**Thanks and Upvote if you like the idea !!\uD83E\uDD1E** | 1 | 4 | ['Greedy', 'Python', 'Python3'] | 0 |
monotone-increasing-digits | Runtime: 0 ms, faster than 100.00% of C++ | runtime-0-ms-faster-than-10000-of-c-by-c-yfn4 | \nclass Solution {\npublic:\n int monotoneIncreasingDigits(int n) {\n \n string s=to_string(n);\n int mark=s.size();\n for(int i= | code1511 | NORMAL | 2021-10-24T13:46:09.148362+00:00 | 2021-10-24T13:46:09.148388+00:00 | 151 | false | ```\nclass Solution {\npublic:\n int monotoneIncreasingDigits(int n) {\n \n string s=to_string(n);\n int mark=s.size();\n for(int i=s.size()-1;i>0;i--){\n if(s[i-1]>s[i]){\n mark=i;\n s[i-1]=s[i-1]-1;\n }\n }\n for(int i=mark;i<s.size();i++){\n s[i]=\'9\';\n }\n return stoi(s);\n }\n};\n``` | 1 | 1 | ['C', 'C++'] | 0 |
monotone-increasing-digits | c++ simple | c-simple-by-zlfzeng-ylll | ```\nclass Solution {\npublic:\n int monotoneIncreasingDigits(int n) {\n auto s = to_string(n);\n for(int i = s.size() -2 ; i>=0;i--){\n | zlfzeng | NORMAL | 2021-08-15T21:11:38.495030+00:00 | 2021-08-15T21:11:38.495080+00:00 | 154 | false | ```\nclass Solution {\npublic:\n int monotoneIncreasingDigits(int n) {\n auto s = to_string(n);\n for(int i = s.size() -2 ; i>=0;i--){\n if(s[i] > s[i+1]){\n // s[i] >= \'1\'\n s[i] = s[i]-1;\n for(int k = i+1; k< s.size(); k++){\n s[k] = \'9\'; \n } \n }\n }\n \n if(s[0] == \'0\'){\n s.erase(s.begin());\n }\n return stoi(s);\n }\n}; | 1 | 0 | [] | 0 |
monotone-increasing-digits | javascript greedy 84ms | javascript-greedy-84ms-by-henrychen222-k1u0 | \nconst monotoneIncreasingDigits = (N) => {\n let a = (N + \'\').split("");\n let n = a.length;\n let j = n;\n for (let i = n - 1; i > 0; i--) {\n | henrychen222 | NORMAL | 2021-08-12T06:22:19.920869+00:00 | 2021-08-12T06:22:19.920902+00:00 | 145 | false | ```\nconst monotoneIncreasingDigits = (N) => {\n let a = (N + \'\').split("");\n let n = a.length;\n let j = n;\n for (let i = n - 1; i > 0; i--) {\n if (a[i - 1] <= a[i]) continue;\n a[i - 1]--;\n j = i;\n }\n for (let i = j; i < n; i++) a[i] = 9;\n return a.join("") - \'0\';\n};\n``` | 1 | 0 | ['Greedy', 'JavaScript'] | 1 |
monotone-increasing-digits | C++ Simple, Easy Understanding || 0 ms, beats 100% | c-simple-easy-understanding-0-ms-beats-1-sghf | The basic steps used to solve this question are the following:\n\n1.) Converting n to its string representation.\n2.) Checking for monotonicity.\n3.) Convert th | Vaibhav_1704 | NORMAL | 2021-08-10T14:12:50.267964+00:00 | 2021-08-21T15:50:00.385557+00:00 | 135 | false | The basic steps used to solve this question are the following:\n\n1.) Converting n to its string representation.\n2.) Checking for monotonicity.\n3.) Convert the digits to 0 which make our number non-monotonic.\n4.) Calling the function again to work with the modified number.\n\nI have taken an example given in the commented code to provide a better understanding of the code as it runs. Recursion is the key step used to solve the question.\n\n```\nclass Solution {\npublic:\n int monotoneIncreasingDigits(int n) {\n\t\t\t//Let n=1872\n\t\t\tstring p="";\n int copy=n,rem=0;\n\t\t\t//extracting the digits and storing in string\n while(copy>0)\n {\n rem=copy%10;\n p.push_back(\'0\'+rem);\n copy/=10;\n }\n\t\t\t//p="2781" is obtained after while loop\n\t\t\t\n\t\t\t//reverse is required to get the same order of digits\n reverse(p.begin(),p.end());\n\t\t\t//p="1872" after reversing\n\t\t\t\n int flag=0;\n int i;//denotes the position upto which our number is monotonic\n\t\t\t//checking whether monotonic or not\n for(i=0;i<p.size()-1;i++)\n {\n if(p[i]<=p[i+1])\n continue;\n else\n {\n flag=1;\n break;\n }\n }\n if(flag==0)//if monotonic return n\n {\n return n;\n }\n i++;\n for(;i<p.size();i++)\n {\n p[i]=\'0\';//converting the digits from ith index to 0 as the next smaller number has the most chances to be monotonic\n }\n //p="1800"\n\t\t\n int val=0;\n for(auto it:p)\n val=val*10+(it-\'0\');//converting the string back to its numeric value\n\t\t\t//val=1800 after for loop\n\t\t\tval--; // val=1799 \n\t\t\n\t\t\t//recursion done to evaluate 1799\n\t\t\treturn monotoneIncreasingDigits(val);\n\t\t}\n}\n```\n\n**If you found the solution helpful, do consider Upvoting :)** | 1 | 0 | [] | 0 |
monotone-increasing-digits | ugly but intuitive solution | ugly-but-intuitive-solution-by-jac0786ky-xh2w | \nclass Solution:\n def monotoneIncreasingDigits(self, n: int) -> int:\n # yx,,, y<=x monotone increasing\n manipulate = list(int(i) for i in s | jac0786ky | NORMAL | 2021-07-05T14:23:38.931068+00:00 | 2021-07-05T14:24:12.170792+00:00 | 186 | false | ```\nclass Solution:\n def monotoneIncreasingDigits(self, n: int) -> int:\n # yx,,, y<=x monotone increasing\n manipulate = list(int(i) for i in str(n))\n i=0\n while i < len(manipulate)-1:\n if manipulate[i] <= manipulate[i+1]:\n i += 1\n elif manipulate[i] > manipulate[i+1]:\n while i-1>=0 and manipulate[i-1] == manipulate[i]:\n i-=1\n manipulate[i] -= 1\n while i < len(manipulate)-1:\n i += 1\n manipulate[i] = 9\n return int(\'\'.join([str(i) for i in manipulate]))\n``` | 1 | 0 | ['Math', 'Python'] | 0 |
monotone-increasing-digits | C++ 100% faster O(digits) solution | c-100-faster-odigits-solution-by-ashvik_-qdvn | It can be solved greedily\nVery Easy Approach:-\nStore the last index where the next element is greater is than current element moving from LSB->MSB, while con | ashvik_marku | NORMAL | 2021-06-20T10:48:34.019776+00:00 | 2021-06-20T10:48:34.019820+00:00 | 156 | false | **It can be solved greedily**\n**Very Easy Approach:-**\n**Store** the last index where the **next element** is greater is than current element **moving from LSB->MSB**, while continuously changing the current element element to 9 and **next element** to **(next-1)**. In the end change every element to 9 from the **stored value**.\n\n***Note** :-`stoi function is used to convert string to int and to_stirng is used to convert any data type to string.` \n```\nclass Solution {\npublic:\n int monotoneIncreasingDigits(int n) {\n string s=to_string(n);\n int index;\n for(int i=s.length()-1;i>0;i--)\n if(s[i-1]>s[i]) s[i]=\'9\',s[i-1]-=1,index=i;\n for(int i=index;i<s.length();i++) s[i]=\'9\';\n\t\treturn stoi(s);\n }\n};\n``` | 1 | 1 | ['Greedy', 'C++'] | 0 |
monotone-increasing-digits | Simple and crisp C++ solution | simple-and-crisp-c-solution-by-txc_rhaeg-d40t | First find the index of the element which is not monotonically increasing.\nSubtract 1 fom that number and change all the numbers after that to 9.\nWe also need | TXC_RHAEGAR | NORMAL | 2021-05-20T09:43:55.272525+00:00 | 2021-05-20T09:43:55.272564+00:00 | 89 | false | First find the index of the element which is not monotonically increasing.\nSubtract 1 fom that number and change all the numbers after that to 9.\nWe also need to check that the index we found must not be repeating.\n```\nclass Solution {\npublic:\n int monotoneIncreasingDigits(int n) {\n string s=to_string(n);\n bool f=true;\n int ind;\n for(int i=1;i<s.size();i++)\n {\n if(s[i]<s[i-1])\n {\n ind=i-1;\n while(ind>0 && s[ind-1]==s[i-1])\n {\n ind--;\n }\n f=false;\n break;\n }\n }\n if(f)\n {\n return n;\n }\n s[ind]--;\n for(int i=ind+1;i<s.size();i++)\n {\n s[i]=\'9\';\n }\n return stoi(s);\n }\n};\n``` | 1 | 0 | [] | 0 |
monotone-increasing-digits | JAVA SOLUTION | Runtime: 1 ms | faster than 92.15% | java-solution-runtime-1-ms-faster-than-9-bq81 | Approach:\n1. Iterate the number in reverse order.\n2. When we found x>y do x-- and store it\'s index.\n\tex. N=324\n\t2>4 --> False\n\t3>2--> True, so x-- => 2 | janvibuddhadev | NORMAL | 2021-04-13T03:40:59.307748+00:00 | 2021-04-13T03:41:48.728424+00:00 | 138 | false | Approach:\n1. Iterate the number in reverse order.\n2. When we found x>y do x-- and store it\'s index.\n\tex. N=324\n\t2>4 --> False\n\t3>2--> True, so x-- => 2, mark=>0 (mark is a variable where i am storing index)\n3. \tput 9 all the indexes at the right of the array.\n mark is at oth index put 9 after that index so, 299\n```\nclass Solution {\n public int monotoneIncreasingDigits(int N) {\n \n char a[]= String.valueOf(N).toCharArray();\n \n \n int mark=a.length;\n \n for(int i=a.length-1;i>0;i--)\n {\n if(a[i]<a[i-1])\n {\n mark=i-1;\n a[i-1]--;\n }\n }\n for(int i=mark+1;i<a.length;i++)\n {\n a[i]=\'9\';\n }\n \n return Integer.parseInt(new String(a));\n }\n}\n``` | 1 | 0 | ['Java'] | 0 |
monotone-increasing-digits | python3 : digit by digit with stacks | python3-digit-by-digit-with-stacks-by-da-5erd | \nclass Solution:\n def monotoneIncreasingDigits(self, N: int) -> int:\n # Go through examples by hand to find the pattern going digit by digit;\n | dachwadachwa | NORMAL | 2021-03-09T18:52:23.090135+00:00 | 2021-03-09T18:54:33.751175+00:00 | 78 | false | ```\nclass Solution:\n def monotoneIncreasingDigits(self, N: int) -> int:\n # Go through examples by hand to find the pattern going digit by digit;\n # starting from ones digit, take the existing value. Move over to the\n # tens digit: if the value there is strictly larger, then update ones\n # digit to 9, and decrement tens digit by one. Repeat this process\n # through all digits to find largest monotonically increasing value <= N\n\n # Implement with stacks: pop off digit from nums stack, process and\n # place onto minc stack. If new digit is larger than top of minc stack,\n # update all minc stack values to 9. Flip minc stack at end since\n # reversed.\n\n # O(logN ^ 2) time and space\n\n nums = [int(i) for i in str(N)]\n minc = []\n\n while nums:\n dgt = nums.pop()\n if minc and dgt > minc[-1]:\n for i in range(len(minc)):\n minc[i] = 9\n dgt -= 1\n minc.append(dgt)\n return int("".join((str(i) for i in reversed(minc))))\n``` | 1 | 0 | [] | 0 |
monotone-increasing-digits | C++|0ms|Faster than 100% | 100% Calculation based| No string is used | c0msfaster-than-100-100-calculation-base-m241 | \nclass Solution {\npublic:\n int monotoneIncreasingDigits(int N) {\n int ans;\n for(int x=N;x>=0;)\n {\n bool f=false;\n | codingsuju | NORMAL | 2021-01-17T06:24:04.345825+00:00 | 2021-01-17T06:24:04.345868+00:00 | 94 | false | ```\nclass Solution {\npublic:\n int monotoneIncreasingDigits(int N) {\n int ans;\n for(int x=N;x>=0;)\n {\n bool f=false;\n int n=x;\n long long b=10;\n while(n>0)\n {\n int x=(n%100)/10;\n int y=n%10;\n if(x<=y)\n {\n f=true;\n }\n else\n {\n f=false;\n break;\n }\n n=n/10;\n b=b*10;\n }\n if(f==true)\n {\n ans=x;\n break;\n }\n x=x-(x%b);\n x--;\n }\n return ans;\n }\n};\n``` | 1 | 0 | [] | 0 |
monotone-increasing-digits | [Python3] O(N) via stack | python3-on-via-stack-by-ye15-gtg1 | Algo\nThe key is to find the first place where a digit is smaller than its neighbor before. Upon finding such place, decrement its previous neighbor and possibl | ye15 | NORMAL | 2020-11-02T22:52:31.667869+00:00 | 2020-11-02T23:01:18.421615+00:00 | 212 | false | Algo\nThe key is to find the first place where a digit is smaller than its neighbor before. Upon finding such place, decrement its previous neighbor and possibly recursively decrease its neighbor until non-decreasing order is retained. Padding 9 after such change results in the correct answer. \n\nImplementation \n```\nclass Solution:\n def monotoneIncreasingDigits(self, N: int) -> int:\n nums = [int(x) for x in str(N)] # digits \n stack = []\n for i, x in enumerate(nums): \n while stack and stack[-1] > x: x = stack.pop() - 1\n stack.append(x) \n if len(stack) <= i: break \n return int("".join(map(str, stack)).ljust(len(nums), "9")) # right padding with "9"\n```\n\nAnalysis\nTime complexity `O(N)`\nSpace complexity `O(N)` | 1 | 0 | ['Python3'] | 0 |
monotone-increasing-digits | Python 3 Solution | python-3-solution-by-leetcodemj-pqp9 | \nclass Solution:\n def monotoneIncreasingDigits(self, N: int) -> int:\n N_vec = [int(d) for d in str(N)]\n nlen = len(N_vec)\n idx = nl | leetcodemj | NORMAL | 2020-10-13T05:08:40.052872+00:00 | 2020-10-13T05:08:40.052915+00:00 | 147 | false | ```\nclass Solution:\n def monotoneIncreasingDigits(self, N: int) -> int:\n N_vec = [int(d) for d in str(N)]\n nlen = len(N_vec)\n idx = nlen\n for i in range(1, nlen)[::-1]:\n if N_vec[i]<N_vec[i-1]:\n N_vec[i-1] -= 1\n idx = i\n for i in range(idx, nlen):\n N_vec[i] = 9\n \n return int("".join(str(d) for d in N_vec))\n``` | 1 | 0 | [] | 1 |
monotone-increasing-digits | [C++] 0ms Code | c-0ms-code-by-applefanboi-0gtj | Status: Accepted (0ms Code)\nIdea: \n Find the index which distrubs the vector being monotonic.\n Find the find occurence of that element and reduce it by 1. Ch | applefanboi | NORMAL | 2020-07-27T16:57:07.387697+00:00 | 2020-07-27T17:00:49.439086+00:00 | 178 | false | **Status**: Accepted (0ms Code)\n**Idea:** \n* Find the index which distrubs the vector being monotonic.\n* Find the find occurence of that element and reduce it by 1. Change all the number to the right by 9.\n\n**Complexity Analysis:**\n* Time: O(N) (Two pass)\n* Space: O(1)\n```\nint monotoneIncreasingDigits(int N) {\n int index = -1;\n string s = to_string(N);\n bool sorted = true;\n for(int i = 1; i < s.length(); i++){\n if(s[i - 1] > s[i]){\n sorted = false;\n index = i - 1;\n break;\n }\n }\n if(sorted) return N;\n index = s.find(s[index]);\n s[index] = ((s[index] - \'0\') - 1) + \'0\';\n for(int i = index + 1; i < s.length(); i++){\n s[i] = \'9\';\n }\n while(s.front() == \'0\') s = s.substr(1);\n return stoi(s);\n }\n``` | 1 | 0 | ['C', 'C++'] | 0 |
monotone-increasing-digits | Java, using array | java-using-array-by-sandip_chanda-4pta | \nclass Solution {\n public int monotoneIncreasingDigits(int N) {\n int len = String.valueOf(N).length();\n int[] digits = new int[len];\n | sandip_chanda | NORMAL | 2020-07-12T08:13:26.009774+00:00 | 2020-07-12T08:14:04.793501+00:00 | 130 | false | ```\nclass Solution {\n public int monotoneIncreasingDigits(int N) {\n int len = String.valueOf(N).length();\n int[] digits = new int[len];\n for(int i=len-1; i>=0; i--) {\n digits[i] = N % 10;\n N = N/10;\n }\n int k = len;\n for(int i=len-2; i>=0; i--) {\n if(digits[i] > digits[i+1]) {\n k = i+1;\n digits[i]--;\n }\n }\n while(k<len) {\n digits[k] = 9;\n k++;\n }\n int res = 0;\n for(int i=0; i<len; i++) {\n res = res*10 + digits[i];\n }\n return res;\n }\n}\n\n\n``` | 1 | 0 | [] | 0 |
monotone-increasing-digits | Java Solution with String manipulation | java-solution-with-string-manipulation-b-8rol | Process the number from right to left, if any digit is greater than next digit then reduce (one, -1) the value of that digit, and track the position, after proc | kind5 | NORMAL | 2020-07-07T16:44:19.097217+00:00 | 2020-07-07T16:44:19.097270+00:00 | 102 | false | Process the number from right to left, if any digit is greater than next digit then reduce (one, -1) the value of that digit, and track the position, after processing entire number, now convert all right side digits to \'9\'.\n```\nclass Solution {\n public int monotoneIncreasingDigits(int n) {\n return greedy1(n);\n }\n \n public int greedy1(int n) {\n Integer it = new Integer(n);\n StringBuilder sb = new StringBuilder(it.toString());\n int len = sb.length();\n boolean first = true;\n int k = len;\n for(int j=len-1;j>0;j--)\n {\n int i = j-1;\n if(sb.charAt(i) > sb.charAt(j))\n {\n //Track position which cause to reduce cliff.\n k = j;\n int ch = sb.charAt(i);\n ch--;\n char ch1 = (char)ch;\n sb.setCharAt(i,ch1);\n \n }\n }\n for(;k<len;k++)\n {\n sb.setCharAt(k,\'9\');\n }\n it = new Integer(sb.toString());\n return it;\n }\n}\n``` | 1 | 0 | [] | 0 |
monotone-increasing-digits | [C++] Easy To Understand - Faster than 100% | c-easy-to-understand-faster-than-100-by-jwi7u | 12966->12866->12899\n12644->12544->12599\nStep 1:Find the first position where digit[i-1]>digiti\nStep 2:Decrease that digit by 1. Move a digit backward ie. i c | pratyush63 | NORMAL | 2020-06-21T10:12:38.999367+00:00 | 2020-06-21T10:12:38.999401+00:00 | 94 | false | 12966->12866->12899\n12644->12544->12599\nStep 1:Find the first position where digit[i-1]>digit[i](The first posn where monotonic increasing seq fails)\nStep 2:Decrease that digit by 1. Move a digit backward ie. i changed to i-1\nStep 3: If digit[i-1]<=digit[i]. Change all digits from posn i+1 till end to 9\nElse repeat from step 1.\n\nclass Solution {\npublic:\n\n int monotoneIncreasingDigits(int N) {\n string num=to_string(N);\n int pos=1;\n while(pos<num.length()&&num[pos]>=num[pos-1]) pos++;\n if(pos==num.length()) return N;\n //Here pos= position where num[pos-1]>num[pos]\n while(pos-1>=0&&num[pos-1]>num[pos])\n {\n num[pos-1]--;\n pos--;\n }\n //Change all digits from pos+1 to 9\n for(int i=pos+1;i<num.length();i++) num[i]=\'9\';\n return stoi(num);\n }\n}; | 1 | 0 | [] | 0 |
monotone-increasing-digits | C++ Backtracking solution. Not optimal but work and easy to understand | c-backtracking-solution-not-optimal-but-se54j | ```\nclass Solution {\npublic:\n int ans;\n void dfs(int N, int base, int prev, int num, int cnt) {\n if (cnt == 0) {\n if (num <= N && | voquocthang99 | NORMAL | 2020-06-09T06:42:58.260845+00:00 | 2020-06-09T06:43:32.442416+00:00 | 75 | false | ```\nclass Solution {\npublic:\n int ans;\n void dfs(int N, int base, int prev, int num, int cnt) {\n if (cnt == 0) {\n if (num <= N && ans < num) ans = num;\n return;\n }\n for (int i = 0; i <= prev; i++) \n if (num <= (INT_MAX - base * i) && num + i*base <= N ) \n dfs(N, base * 10, i, num + i*base, cnt-1);\n }\n int monotoneIncreasingDigits(int N) {\n ans = 0;\n dfs(N, 1, 9, 0, to_string(N).size());\n return ans;\n }\n}; | 1 | 0 | [] | 0 |
monotone-increasing-digits | Short,simple and intuitive C++ solution, faster than 100% | shortsimple-and-intuitive-c-solution-fas-wr8l | The idea is to make the digits from right 0 and subtract 1 from it at each step. After every such step we check if it satisfies the condition, we return that nu | werewolf97 | NORMAL | 2020-06-09T06:41:50.398880+00:00 | 2020-06-09T06:41:50.398926+00:00 | 77 | false | The idea is to make the digits from right 0 and subtract 1 from it at each step. After every such step we check if it satisfies the condition, we return that number, if not we repeat making the next digit from right 0 and subtracting 1.\n```\nclass Solution {\npublic:\n \n bool chk(int n){\n string s = to_string(n);\n for(int i=1;i<s.size();i++){\n if(s[i]<s[i-1]) return 0;\n }\n return 1;\n }\n \n int monotoneIncreasingDigits(int N) {\n int c=10;\n while(!chk(N)){\n N/=c;\n N*=c;\n N--;\n c*=10;\n }\n return N;\n }\n};\n``` | 1 | 0 | [] | 1 |
monotone-increasing-digits | C#, O(n) greedy solution using Stack | c-on-greedy-solution-using-stack-by-edev-evwr | \npublic class Solution {\n public int MonotoneIncreasingDigits(int N) {\n Stack<int> stack = new Stack<int>();\n while (N > 0) {\n | edevyatkin | NORMAL | 2020-05-14T15:45:21.575438+00:00 | 2020-05-14T15:45:56.679893+00:00 | 137 | false | ```\npublic class Solution {\n public int MonotoneIncreasingDigits(int N) {\n Stack<int> stack = new Stack<int>();\n while (N > 0) {\n int digit = N % 10;\n N /= 10;\n if (stack.Count == 0 || stack.Peek() >= digit) {\n stack.Push(digit);\n }\n else {\n int count = stack.Count;\n stack.Clear(); \n if (count > 0) {\n while (count > 0) {\n stack.Push(9);\n count--; \n }\n stack.Push(digit-1);\n }\n }\n }\n var arr = stack.ToArray();\n Array.Reverse(arr);\n int p = 1;\n int result = 0;\n foreach (int i in arr) {\n result += i*p;\n p *= 10;\n }\n return result;\n }\n}\n``` | 1 | 0 | ['Stack', 'Greedy', 'C#'] | 0 |
monotone-increasing-digits | Java explained greedy solution | java-explained-greedy-solution-by-luyao_-zqi3 | \nclass Solution {\n public int monotoneIncreasingDigits(int N) {\n if (N < 10) {\n return N;\n }\n String str = String.value | luyao_jin | NORMAL | 2020-05-13T08:08:27.471387+00:00 | 2020-05-13T08:08:27.471423+00:00 | 396 | false | ```\nclass Solution {\n public int monotoneIncreasingDigits(int N) {\n if (N < 10) {\n return N;\n }\n String str = String.valueOf(N);\n StringBuilder sb = new StringBuilder();\n int counter = 0;\n \n for (; counter < str.length() - 1; counter++) {\n //put all continuous non-decreasing digits in its original order\n if (str.charAt(counter) <= str.charAt(counter + 1)) {\n sb.append(str.charAt(counter));\n } else{\n break;\n }\n }\n \n if (counter == str.length() - 1) {\n //if all digits is in non-decreasing order\n sb.append(str.charAt(counter));\n } else {\n //there is decreasing......\n //999998 -> 899999, replace all equal digits before decreasing\n while (sb.length() >= 1 && str.charAt(counter) == sb.charAt(sb.length() - 1)) {\n sb.deleteCharAt(sb.length() - 1);\n --counter;\n } \n \n //as long as we find a decreasing such as 532, we can replace 5 with 4 and set all digits after it to be 9\n //no need to worry about 1 -> 0, we can handle it later easily since it will be the start of stringbuilder\n sb.append(str.charAt(counter) - \'1\');\n ++counter; \n \n while (counter < str.length()) {\n sb.append(\'9\');\n ++counter;\n }\n }\n \n //for corner case like "10" -> "09" -> "9","100" -> "099" -> "99",....\n if (sb.charAt(0) == \'0\') {\n sb.deleteCharAt(0);\n }\n \n String res = sb.toString();\n return Integer.valueOf(res);\n }\n}\n``` | 1 | 0 | ['Greedy', 'Java'] | 0 |
monotone-increasing-digits | C++: 100% time 100% space easy to understand | c-100-time-100-space-easy-to-understand-qcfcd | \nclass Solution {\npublic:\n int monotoneIncreasingDigits(int N) {\n string str=to_string(N);\n int i;\n for(i=0; i<str.size()-1; i++)\ | leetcode07 | NORMAL | 2020-01-13T22:37:04.889617+00:00 | 2020-01-13T22:37:04.889669+00:00 | 129 | false | ```\nclass Solution {\npublic:\n int monotoneIncreasingDigits(int N) {\n string str=to_string(N);\n int i;\n for(i=0; i<str.size()-1; i++)\n if(str[i]>str[i+1])\n break;\n if(i==str.size()-1)\n return N;\n while(i>0 && str[i-1]>str[i]-1)\n i--;\n int num=0, j=0;\n while(j<str.size()){\n if(j==i)\n num=(num*10)+((str[j]-\'0\')-1);\n else if(j>i)\n num=(num*10)+9;\n else\n num=(num*10)+(str[j]-\'0\');\n j++;\n }\n return num;\n }\n};\n``` | 1 | 0 | [] | 0 |
monotone-increasing-digits | C++, faster than 100%. O(N) Recursive solution | c-faster-than-100-on-recursive-solution-cbm3w | The main observation is that assuming an Integer N has digits a_0a_1...a_n, the desired monotonous increasing digits (MID) can be found from getting the solutio | theash | NORMAL | 2019-12-09T15:56:44.980152+00:00 | 2019-12-09T15:57:26.702231+00:00 | 128 | false | The main observation is that assuming an Integer ```N``` has digits ```a_0a_1...a_n```, the desired monotonous increasing digits (MID) can be found from getting the solution for ```a_1...a_n``` and comparing its most significant digit with ```a_0```.\n\n```\n#include <vector>\n#include <cmath>\n\n\nvoid int_to_digits(int N, std::vector<int> & digits)\n{\n while(N>=10)\n {\n digits.push_back(N%10);\n N/=10;\n }\n digits.push_back(N);\n\n}\n\nint largest_smaller_MID(const std::vector<int> & N)\n{\n //assuming that the most significan digit of N is at the end of the vector\n int s=N.size();\n\n if(s==1)\n {\n return N[0];\n }\n\n if(N[s-1]>N[s-2])\n {\n return (N[s-1]*pow(10,s-1))-1;\n }\n else\n {\n std::vector<int> q(N.begin(),N.end()-1);\n int u=largest_smaller_MID(q);\n if(u<N[s-1]*pow(10,s-2))\n {\n return N[s-1]*(pow(10,s-1))-1;\n }\n else\n {\n return u+pow(10,s-1)*N[s-1];\n }\n\n }\n return -1;\n}\n\nclass Solution\n{\n public:\n int monotoneIncreasingDigits(int N) \n {\n std::vector<int> digits;\n int_to_digits(N,digits);\n int res=largest_smaller_MID(digits);\n return res;\n }\n};\n``` | 1 | 0 | ['Recursion'] | 0 |
monotone-increasing-digits | Go %100 | go-100-by-zhangqilike2015-l3d0 | use twolevel iterative algorithm\uFF1A\n1: use []int to record the digits of N, the high digits in the right\n2: traverse the array and set 0th to ith elements | zhangqilike2015 | NORMAL | 2019-09-10T03:12:43.152964+00:00 | 2019-09-10T05:55:25.735942+00:00 | 62 | false | use twolevel iterative algorithm\uFF1A\n1: use []int to record the digits of N, the high digits in the right\n2: traverse the array and set 0th to ith elements to \'9\' if i<i+1 and digits[i] < digits[i+1], maybe one elements are set to \'9\' several times,this is a point need to be optimized\n\n```\nfunc monotoneIncreasingDigits(N int) int {\n\tvar digits []int\n\tfor N > 0 {\n\t\tdigits = append(digits, N%10)\n\t\tN = N / 10\n\t}\n\ti := 0\n\tfor i < len(digits)-1 {\n\t\tif digits[i] < digits[i+1] {\n\t\t\tfor j := 0; j <= i; j++ {\n\t\t\t\tdigits[j] = 9\n\t\t\t}\n\t\t\tdigits[i+1]--\n\t\t}\n\t\ti++\n\t}\n\n\tret := 0\n\tfor i := len(digits) - 1; i >= 0; i-- {\n\t\tret = ret*10 + digits[i]\n\t}\n\treturn ret\n}\n``` | 1 | 0 | [] | 0 |
monotone-increasing-digits | Solution in Python 3 (beats 95%) | solution-in-python-3-beats-95-by-junaidm-v5e6 | ```\nclass Solution:\n def monotoneIncreasingDigits(self, n: int) -> int:\n \tN = [int(i) for i in str(n)]\n \tL = len(N)\n \tfor I in range(L-1):\n | junaidmansuri | NORMAL | 2019-08-19T06:56:52.659853+00:00 | 2019-08-19T06:56:52.659887+00:00 | 571 | false | ```\nclass Solution:\n def monotoneIncreasingDigits(self, n: int) -> int:\n \tN = [int(i) for i in str(n)]\n \tL = len(N)\n \tfor I in range(L-1):\n \t\tif N[I] > N[I+1]: break\n \tif N[I] <= N[I+1]: return n\n \tN[I+1:], N[I] = [9]*(L-I-1), N[I] - 1\n \tfor i in range(I,0,-1):\n \t\tif N[i] >= N[i-1]: break\n \t\tN[i], N[i-1] = 9, N[i-1] - 1\n \treturn sum([N[i]*10**(L-i-1) for i in range(L)])\n\t\t\n\t\t\n- Junaid Mansuri\n(LeetCode ID)@hotmail.com | 1 | 0 | ['Python', 'Python3'] | 1 |
monotone-increasing-digits | C# simple solution | c-simple-solution-by-monster71-e9g9 | \npublic class Solution {\n public int MonotoneIncreasingDigits(int N) {\n var list = new List<int>();\n\n while (N > 0)\n {\n list.Add | monster71 | NORMAL | 2019-04-10T09:51:32.520716+00:00 | 2019-04-10T09:51:32.520783+00:00 | 110 | false | ```\npublic class Solution {\n public int MonotoneIncreasingDigits(int N) {\n var list = new List<int>();\n\n while (N > 0)\n {\n list.Add(N % 10);\n N /= 10;\n }\n\n for (int i = 0; i < list.Count - 1; i++)\n {\n if (list[i + 1] > list[i])\n {\n for (int j = i; j >= 0 && list[j] != 9; j--)\n list[j] = 9;\n\n list[i + 1]--;\n }\n\n }\n\n var num = 0;\n for (int i = list.Count - 1; i >= 0; i--)\n num = num * 10 + list[i];\n\n return num;\n }\n}\n``` | 1 | 0 | [] | 0 |
monotone-increasing-digits | A simple C solution[Accepted][Runtime:4ms] | a-simple-c-solutionacceptedruntime4ms-by-uubl | \nint howMuchDigits(int N){\n int ret=0;\n while(N>0){\n N/=10;\n ret++;\n }\n return ret;\n}\nint monotoneIncreasingDigits(int N) {\n | blue_keroro | NORMAL | 2019-03-04T02:37:17.245823+00:00 | 2019-03-04T02:37:17.245865+00:00 | 128 | false | ```\nint howMuchDigits(int N){\n int ret=0;\n while(N>0){\n N/=10;\n ret++;\n }\n return ret;\n}\nint monotoneIncreasingDigits(int N) {\n int count=howMuchDigits(N);\n int* array=(int*)calloc(10,sizeof(int));\n for(int i=0;i<count;i++){\n int temp=pow(10,count-i-1);\n array[i]=N/temp;\n N%=temp;\n }\n int start=0;\n for(int i=0;i<count-1;i++){\n if(array[i]==array[i+1]){\n continue;\n }\n if(array[i]<array[i+1]){\n start=i+1;\n }\n if(array[i]>array[i+1]){\n array[start]--;\n for(int j=start+1;j<count;j++){\n array[j]=9;\n }\n break;\n }\n }\n int ret=0;\n for(int i=0;i<count;i++){\n ret=ret*10+array[i];\n }\n return ret;\n}\n``` | 1 | 0 | [] | 0 |
monotone-increasing-digits | c++ solution 4ms, faster than 100% | c-solution-4ms-faster-than-100-by-feidia-acdk | \nclass Solution {\npublic:\n int monotoneIncreasingDigits(int N) {\n int a[10]={0};\n int ans=0;\n int num = 0;// cout the num of figur | feidian | NORMAL | 2018-12-26T03:01:23.804907+00:00 | 2018-12-26T03:01:23.804965+00:00 | 176 | false | ```\nclass Solution {\npublic:\n int monotoneIncreasingDigits(int N) {\n int a[10]={0};\n int ans=0;\n int num = 0;// cout the num of figures\n for(int i = 0;i<10;i++)\n {\n a[i] = N%10;\n N/=10;\n num++;\n if(N==0)\n {break;}\n }\n for(int j=0;j<num-1;j++)\n {\n\t\t\tfor(int i = weishu;i>0;i--)\n\t\t\t{\n\t\t\t\tif(a[i])\n\t\t\t\t{\n\t\t\t\t\tif((a[i]>a[i-1]))\n\t\t\t\t\t{\n\t\t\t\t\t\ta[i]--;\n\t\t\t\t\t\tfor(int k = 0;k<i;k++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ta[k] = 9;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n }\n\t\tfor (int i = 0; i < weishu; i++)\n\t\t{\n\t\t\tans += a[i]*pow(10,i);\n\t\t}\n\t\treturn ans;\n }\n};\n``` | 1 | 0 | [] | 0 |
monotone-increasing-digits | concise python solution beats 98% | concise-python-solution-beats-98-by-plea-y9fx | \n def monotoneIncreasingDigits(self, N):\n """\n :type N: int\n :rtype: int\n """\n digits = [int(x) for x in str(N)]\n | please_ac | NORMAL | 2018-10-28T03:28:43.566664+00:00 | 2018-10-28T03:28:43.566710+00:00 | 186 | false | ```\n def monotoneIncreasingDigits(self, N):\n """\n :type N: int\n :rtype: int\n """\n digits = [int(x) for x in str(N)]\n count = 0 #store the number of same digit\n \n for i in range(len(digits)-1):\n if digits[i] > digits[i+1]:\n digits[i-count] -= 1\n for j in range(i-count+1,len(digits)):\n digits[j] = 9\n break\n elif digits[i] == digits[i+1]:\n count += 1\n else:\n count = 0\n \n return int(\'\'.join([str(x) for x in digits]))\n``` | 1 | 0 | [] | 0 |
customers-who-never-order | ||TO THE POINT SOLUTION || WITHOUT JOIN || | to-the-point-solution-without-join-by-uj-qcrc | Please Upvote if you like the approach\n\n\n# Code\n\nSELECT name as Customers\nfrom Customers\nwhere id not in (\n select customerId\n from Orders\n);\n | ujjwalvarma6948 | NORMAL | 2023-02-18T16:30:39.672363+00:00 | 2023-04-12T17:12:32.919505+00:00 | 63,033 | false | **Please Upvote if you like the approach**\n\n\n# Code\n```\nSELECT name as Customers\nfrom Customers\nwhere id not in (\n select customerId\n from Orders\n);\n``` | 440 | 0 | ['MySQL'] | 19 |
customers-who-never-order | Easy pandas (2 methods) with detailed explanation | easy-pandas-2-methods-with-detailed-expl-4esq | \n# Code -1\n\nimport pandas as pd\n\ndef find_customers(customers: pd.DataFrame, orders: pd.DataFrame) -> pd.DataFrame:\n # Select the customers whose \'id\ | sriganesh777 | NORMAL | 2023-08-01T14:22:26.074961+00:00 | 2023-08-01T14:22:26.075009+00:00 | 31,601 | false | \n# Code -1\n```\nimport pandas as pd\n\ndef find_customers(customers: pd.DataFrame, orders: pd.DataFrame) -> pd.DataFrame:\n # Select the customers whose \'id\' is not present in the orders DataFrame\'s \'customerId\' column.\n df = customers[~customers[\'id\'].isin(orders[\'customerId\'])]\n\n # Build a DataFrame that only contains the \'name\' column and rename it as \'Customers\'.\n df = df[[\'name\']].rename(columns={\'name\': \'Customers\'})\n\n return df\n\n```\n# Explanation\n- df = customers[\\~customers[\'id\'].isin(orders[\'customerId\'])]: In this line, we use boolean indexing to filter the rows from the \'customers\' DataFrame. The condition \\~customers[\'id\'].isin(orders[\'customerId\']) checks if the \'id\' column in the \'customers\' DataFrame is not present in the \'customerId\' column of the \'orders\' DataFrame. The tilde (~) operator negates the result, so we select only the rows where the \'id\' is not found in the \'customerId\' column of the \'orders\' DataFrame.\n\n- df = df[[\'name\']].rename(columns={\'name\': \'Customers\'}): After filtering, we create a new DataFrame df containing only the \'name\' column. The [[\'name\']] part is used to select only the \'name\' column and keep it as a DataFrame. Then, we rename this column from \'name\' to \'Customers\' using the rename function. The resulting DataFrame df contains the names of customers who never placed any orders, and the column is labeled as \'Customers\'.\n\n\nIn summary, the find_customers function takes two DataFrames, \'customers\' and \'orders\', and filters the \'customers\' DataFrame to find customers whose \'id\' is not present in the \'orders\' DataFrame\'s \'customerId\' column. It then returns a new DataFrame with the names of these customers, labeled as \'Customers\'. This function effectively finds customers who never placed any orders.\n\n# Code -2\n```\nimport pandas as pd\n\ndef find_customers(customers: pd.DataFrame, orders: pd.DataFrame) -> pd.DataFrame:\n # Merge the customers DataFrame with the orders DataFrame using a left join on \'id\' and \'customerId\'\n merged_df = customers.merge(orders, how=\'left\', left_on=\'id\', right_on=\'customerId\')\n \n # Use the \'customerId\' column to create a boolean mask for customers who never placed any orders\n mask = merged_df[\'customerId\'].isna()\n \n # Filter the rows using the boolean mask\n result_df = merged_df[mask]\n \n # Select only the \'name\' column from the result DataFrame and rename it as \'Customers\'\n result_df = result_df[[\'name\']].rename(columns={\'name\': \'Customers\'})\n \n return result_df\n```\n# Approach\n- We first merge the \'customers\' DataFrame with the \'orders\' DataFrame using a left join. This allows us to have a DataFrame where each row represents a customer and includes any orders they may have placed.\n\n- We create a boolean mask named mask by checking if the \'customerId\' column in the merged DataFrame is null. This mask will be True for customers who never placed any orders and False for customers who placed orders.\n\n- We use the boolean mask mask to filter the rows from the \'customers\' DataFrame, selecting only those customers who never placed any orders.\n\n- We select only the \'name\' column from the filtered DataFrame and rename it as \'Customers\'.\n\n- Finally, we return the resulting DataFrame containing the names of customers who never placed any orders, labeled as \'Customers\'.\n\nThis approach achieves the same goal of finding customers who never placed any orders but uses a different technique involving a left join and boolean masking.\n\n\n | 349 | 0 | ['Pandas'] | 8 |
customers-who-never-order | Three accepted solutions | three-accepted-solutions-by-kent-huang-u4d9 | SELECT A.Name from Customers A\n WHERE NOT EXISTS (SELECT 1 FROM Orders B WHERE A.Id = B.CustomerId)\n\n SELECT A.Name from Customers A\n LEFT JOIN Ord | kent-huang | NORMAL | 2015-01-21T05:27:52+00:00 | 2018-10-16T16:07:26.887918+00:00 | 57,540 | false | SELECT A.Name from Customers A\n WHERE NOT EXISTS (SELECT 1 FROM Orders B WHERE A.Id = B.CustomerId)\n\n SELECT A.Name from Customers A\n LEFT JOIN Orders B on a.Id = B.CustomerId\n WHERE b.CustomerId is NULL\n\n SELECT A.Name from Customers A\n WHERE A.Id NOT IN (SELECT B.CustomerId from Orders B) | 294 | 4 | [] | 27 |
customers-who-never-order | LEFT JOIN 💥 | left-join-by-adityabhate-iepj | Please Upvote if it helps \uD83E\uDEF0\n# Code :-\n\n# Write your MySQL query statement below\nSELECT c.name AS Customers \nFROM Customers c LEFT JOIN Orders o | AdityaBhate | NORMAL | 2022-12-23T17:44:50.345786+00:00 | 2023-11-28T12:33:47.861115+00:00 | 34,302 | false | # ***Please Upvote if it helps \uD83E\uDEF0***\n# Code :-\n```\n# Write your MySQL query statement below\nSELECT c.name AS Customers \nFROM Customers c LEFT JOIN Orders o \nON c.id=o.customerId \nWHERE o.customerId IS NULL;\n```\nOR\n```\nSELECT name AS Customers FROM Customers WHERE Customers.id \nNOT IN (SELECT CustomerId FROM Orders);\n``` | 150 | 0 | ['Database', 'MySQL', 'MS SQL Server'] | 9 |
customers-who-never-order | easy solution | easy-solution-by-rm221-j27k | select name as customers from customers\nwhere id not in (select customerId from orders);\n\n#upvote is appreciated. | robot1212 | NORMAL | 2022-08-18T22:22:49.837591+00:00 | 2022-08-18T22:22:49.837615+00:00 | 16,721 | false | select name as customers from customers\nwhere id not in (select customerId from orders);\n\n#upvote is appreciated. | 147 | 0 | ['MySQL'] | 5 |
customers-who-never-order | Faster | Easy | faster-easy-by-manya24-66d6 | Do upvote if you like the solution to keep me motivated \uD83D\uDE0A\u270C\n\nSELECT Name AS Customers\nFROM CUSTOMERS\nLEFT JOIN ORDERS\nON ORDERS.CustomerID = | manya24 | NORMAL | 2021-07-01T09:59:03.435624+00:00 | 2021-07-01T09:59:03.435672+00:00 | 10,509 | false | ***Do upvote if you like the solution to keep me motivated*** \uD83D\uDE0A\u270C\n```\nSELECT Name AS Customers\nFROM CUSTOMERS\nLEFT JOIN ORDERS\nON ORDERS.CustomerID = Customers.Id\nWHERE Orders.CustomerID IS NULL\n```\n | 145 | 1 | [] | 6 |
customers-who-never-order | ✔️ Easy Joins with attached document | easy-joins-with-attached-document-by-ale-86w6 | \n\nSELECT Customers.name AS Customers\nFROM Customers\nLEFT JOIN Orders\nON Customers.id = Orders.customerId\nWHERE Orders.customerId is null;\n\n\n | alex3560 | NORMAL | 2022-09-25T01:27:44.341896+00:00 | 2022-10-12T18:00:52.146168+00:00 | 12,517 | false | \n```\nSELECT Customers.name AS Customers\nFROM Customers\nLEFT JOIN Orders\nON Customers.id = Orders.customerId\nWHERE Orders.customerId is null;\n```\n\n | 91 | 0 | [] | 4 |
customers-who-never-order | || Fundamental Approach || SQL || SELECT || | fundamental-approach-sql-select-by-vasud-1oti | Code\n\n# Write your MySQL query statement below\nSELECT name AS "Customers"\nFROM Customers WHERE Customers.id not in (\n SELECT customerId FROM Orders\n);\ | VasudevaK | NORMAL | 2023-03-27T19:01:42.294823+00:00 | 2023-03-27T19:01:42.294858+00:00 | 7,758 | false | # Code\n```\n# Write your MySQL query statement below\nSELECT name AS "Customers"\nFROM Customers WHERE Customers.id not in (\n SELECT customerId FROM Orders\n);\n// Please consider upvoting, if the solution helped! Thank you :)\n``` | 43 | 0 | ['MySQL'] | 0 |
customers-who-never-order | MySql Solution using not in | mysql-solution-using-not-in-by-arif_-_ul-nf7t | \nselect name as Customers from customers where id not in (select customerid from orders);\n | arif_-_ul_- | NORMAL | 2018-06-23T13:04:20.732474+00:00 | 2018-09-19T01:33:50.606936+00:00 | 2,355 | false | ```\nselect name as Customers from customers where id not in (select customerid from orders);\n``` | 42 | 1 | [] | 4 |
customers-who-never-order | A solution using NOT IN and another one using LEFT JOIN | a-solution-using-not-in-and-another-one-t82gr | 605 ms\n\n SELECT Name as Customers from Customers\n LEFT JOIN Orders\n ON Customers.Id = Orders.CustomerId\n WHERE Orders.CustomerId IS NULL;\n\n67 | ohini | NORMAL | 2015-08-21T03:51:15+00:00 | 2015-08-21T03:51:15+00:00 | 13,037 | false | 605 ms\n\n SELECT Name as Customers from Customers\n LEFT JOIN Orders\n ON Customers.Id = Orders.CustomerId\n WHERE Orders.CustomerId IS NULL;\n\n675ms\n\n SELECT Name as Customers from Customers\n WHERE Id NOT IN (SELECT CustomerId from Orders); | 42 | 1 | ['MySQL'] | 9 |
customers-who-never-order | Easy and straight forward SQL Query. | easy-and-straight-forward-sql-query-by-a-fux0 | \n# Write your MySQL query statement below\nSELECT Customers.name AS Customers \nFROM Customers\nWHERE Customers.id NOT IN \n(\n SELECT customerId from Orders | aman_2_0_2_3 | NORMAL | 2022-04-07T21:19:49.069331+00:00 | 2022-04-07T21:19:49.069368+00:00 | 1,810 | false | ```\n# Write your MySQL query statement below\nSELECT Customers.name AS Customers \nFROM Customers\nWHERE Customers.id NOT IN \n(\n SELECT customerId from Orders\n);\n```\n**Please don\'t forget to upvote me.** | 22 | 0 | ['MySQL'] | 1 |
customers-who-never-order | ⭐2 different solutions || Easy to understand⭐ | 2-different-solutions-easy-to-understand-kruu | \n# 1.\nSELECT c.name as Customers\nFROM Customers c LEFT JOIN Orders o\nON c.id = o.customerId\nwhere o.customerId is NULL;\n\n# 2.\nSELECT c.name as Customer | 123_tripathi | NORMAL | 2022-08-06T06:47:47.796120+00:00 | 2022-08-06T17:53:33.955518+00:00 | 1,427 | false | ```\n# 1.\nSELECT c.name as Customers\nFROM Customers c LEFT JOIN Orders o\nON c.id = o.customerId\nwhere o.customerId is NULL;\n\n# 2.\nSELECT c.name as Customers from Customers c\nWHERE c.id not in (select o.customerId from Orders o);\n```\n**If you have any doubts, feel free to ask...\nIf you understand the concept. Don\'t Forget to upvote \uD83D\uDE0A\nand PLEASE DO UPVOTE** | 17 | 0 | ['MySQL'] | 4 |
customers-who-never-order | 5 easy solutions || MySQL || Pandas || Beats 100% in both time and space !! | 5-easy-solutions-mysql-pandas-beats-100-k8hlm | Code\n\n# Solution 1\nSELECT name as Customers\nFROM Customers C\nWHERE C.Id NOT IN (SELECT O.CustomerId from Orders O)\n\n# Solution 2\nSELECT name as Customer | prathams29 | NORMAL | 2023-07-31T17:46:10.413956+00:00 | 2023-07-31T17:46:52.027962+00:00 | 3,153 | false | # Code\n```\n# Solution 1\nSELECT name as Customers\nFROM Customers C\nWHERE C.Id NOT IN (SELECT O.CustomerId from Orders O)\n\n# Solution 2\nSELECT name as Customers\nFROM Customers A LEFT JOIN Orders B on A.Id = B.CustomerId\nWHERE B.CustomerId is NULL\n\n# Solution 3\nSELECT name as Customers\nFROM Customers A\nWHERE NOT EXISTS (SELECT name FROM Orders B WHERE A.Id = B.CustomerId)\n```\n```\n# Solution 1\nimport pandas as pd\n\ndef customers_who_never_order(customers: pd.DataFrame, orders: pd.DataFrame)->pd.DataFrame:\n # Select the rows which `id` is not present in orders[\'customerId\'].\n df = customers[~customers[\'id\'].isin(orders[\'customerId\'])]\n\n # Build a dataframe that only contains the column `name` \n # and rename the column `name` as `Customers`.\n df = df[[\'name\']].rename(columns={\'name\': \'Customers\'})\n return df\n\n# Solution 2\nimport pandas as pd\n\ndef customers_who_never_order(customers: pd.DataFrame, orders: pd.DataFrame) -> pd.DataFrame:\n df = customers.merge(orders, left_on=\'id\', right_on=\'customerId\', how=\'left\')\n df = df[df[\'customerId\'].isna()]\n df = df[[\'name\']].rename(columns={\'name\': \'Customers\'})\n return df\n```\n\n | 15 | 0 | ['MySQL', 'Pandas'] | 3 |
customers-who-never-order | ✅ 100% EASY || FAST 🔥|| CLEAN SOLUTION 🌟 | 100-easy-fast-clean-solution-by-kartik_k-99sf | Code\n\n/* Write your PL/SQL query statement below */\nSELECT name AS Customers FROM Customers WHERE \n\nCustomers.id NOT IN (SELECT customerId FROM Orders)\n\n | kartik_ksk7 | NORMAL | 2023-07-28T06:18:08.609122+00:00 | 2023-07-28T06:18:08.609141+00:00 | 1,242 | false | # Code\n```\n/* Write your PL/SQL query statement below */\nSELECT name AS Customers FROM Customers WHERE \n\nCustomers.id NOT IN (SELECT customerId FROM Orders)\n```\nIF THIS WILL BE HELPFUL TO YOU,PLEASE UPVOTE !\n\n\n\n | 13 | 0 | ['MySQL', 'Oracle', 'MS SQL Server'] | 1 |
customers-who-never-order | ✔️ 2 ways | EXISTS | nested | MySQL | 2-ways-exists-nested-mysql-by-coding_men-kkwv | Here are two ways of solving the query:\n\n1. Using EXISTS:\n\nMySQL []\nSELECT name AS Customers FROM Customers A WHERE NOT EXISTS (SELECT * FROM Orders B WHER | coding_menance | NORMAL | 2022-10-27T08:09:26.709683+00:00 | 2022-12-24T06:41:57.562919+00:00 | 2,469 | false | ## Here are two ways of solving the query:\n\n1. Using EXISTS:\n\n```MySQL []\nSELECT name AS Customers FROM Customers A WHERE NOT EXISTS (SELECT * FROM Orders B WHERE A.id = B.customerId);\n```\n\n2. Using nested Query\n\n```MySQL []\nSELECT name as customers FROM Customers WHERE id not in (SELECT customerId FROM Orders);\n```\n\n`Another Note:`\n`\nRemember, mySQL is case-insensitive. Typing the table names in lower case or all upper case makes on difference. Same goes for data contents within the table.\n`\n\n*Leave a upvote if it helped!*\n\nConnect on LinkedIn: https://www.linkedin.com/in/gourab-roy-824652172/ | 13 | 0 | ['MySQL'] | 1 |
customers-who-never-order | Find Customers Not in Orders using Pandas | find-customers-not-in-orders-using-panda-0glu | Intuition\nTo identify customers who do not have any orders, we need to filter the customers DataFrame to exclude those whose IDs appear in the orders DataFrame | d_sushkov | NORMAL | 2024-08-01T00:29:50.206169+00:00 | 2024-08-01T00:29:50.206201+00:00 | 1,123 | false | # Intuition\nTo identify customers who do not have any orders, we need to filter the customers DataFrame to exclude those whose IDs appear in the orders DataFrame. The goal is to obtain a list of customer names who are not represented in the orders.\n\n# Approach\n1. Filter Out Orders:\n\n- Use the `isin()` method to determine if each id in the customers DataFrame is present in the orders DataFrame.\n- Apply the negation operator `(~)` to select customers whose IDs are not in the orders list.\n2. Select and Rename:\n\n- After filtering, select only the name column from the customers DataFrame.\n- Rename the column name to Customers for clarity in the result.\n\n# Complexity\n- Time complexity: Filtering: The `isin()` method involves a membership check for each id in customers against customerId in orders. The complexity is approximately $$O(n + m)$$, where n is the number of rows in customers and m is the number of rows in orders.\n\n- Space complexity: Intermediate Results - $$O(n)$$ for storing the boolean mask used for filtering. Final Result Set - $$O(n)$$ for storing the resulting DataFrame of customer names.\nOverall - $$O(n + m)$$, accounting for both the intermediate storage and the final output.\n\n# Code\n```\nimport pandas as pd\n\ndef find_customers(customers: pd.DataFrame, orders: pd.DataFrame) -> pd.DataFrame:\n # Filter customers whose \'id\' is not in the list of \'customerId\' from orders\n filtered_customers = customers[~customers[\'id\'].isin(orders[\'customerId\'])]\n \n # Select the \'name\' column and rename it to \'Customers\'\n result = filtered_customers[[\'name\']].rename(columns={\'name\': \'Customers\'})\n \n return result\n``` | 12 | 0 | ['Database', 'Pandas'] | 0 |
customers-who-never-order | Here are 3 solutions | here-are-3-solutions-by-harshloomba-71f8 | select c.Name from Customers c\nwhere c.Id not in (select customerId from Orders)\n\nselect c.Name from Customers c\nwhere (select count(*) from Orders o where | harshloomba | NORMAL | 2016-03-17T16:31:13+00:00 | 2018-10-24T06:04:16.981780+00:00 | 4,798 | false | select c.Name from Customers c\nwhere c.Id not in (select customerId from Orders)\n\nselect c.Name from Customers c\nwhere (select count(*) from Orders o where o.customerId=c.id)=0 \n\nselect c.Name from Customers c\nwhere not exists (select * from Orders o where o.customerId=c.id) | 12 | 0 | [] | 3 |
customers-who-never-order | simple pandas , pls upvote ❤ | simple-pandas-by-y4hew1qdc3-3ki3 | IntuitionApproachUse the isin function to check if customers['id'] exists in orders['customerId'].
Use the tilde (~) operator to negate this, identifying custom | Y4heW1qDC3 | NORMAL | 2025-01-14T09:58:21.789922+00:00 | 2025-01-14T16:13:45.613112+00:00 | 1,075 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->The goal is to find customers whose IDs are not present in the orders DataFrame. This can be achieved using a filtering operation that excludes customer IDs found in the orders DataFrame.

# Approach
<!-- Describe your approach to solving the problem. -->1. Filter Non-Matching IDs:
Use the isin function to check if customers['id'] exists in orders['customerId'].
Use the tilde (~) operator to negate this, identifying customers whose IDs are not in the orders DataFrame.
Select and Rename Columns:
2. Select the name column from the filtered DataFrame.
Rename the column to "Customers" as required.
Return Result:
3. Return the resulting DataFrame containing only the names of the customers who have not placed any orders.
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```pythondata []
import pandas as pd
def find_customers(customers: pd.DataFrame, orders: pd.DataFrame) -> pd.DataFrame:
df_cus=customers[~customers['id'].isin(orders['customerId'])]
return df_cus[['name']].rename(columns={'name':'Customers'})
``` | 10 | 0 | ['Pandas'] | 2 |
customers-who-never-order | Easy | Fast (142ms) | easy-fast-142ms-by-codepulkit-pr2u | Upvote if you like the solution\u270C\uFE0F\n\nselect c.name as Customers \nfrom Customers c\nwhere c.id not in (select customerId from Orders);\n | CodePulkit | NORMAL | 2022-10-10T15:34:10.227105+00:00 | 2022-10-10T15:34:10.227153+00:00 | 2,042 | false | **Upvote if you like the solution**\u270C\uFE0F\n```\nselect c.name as Customers \nfrom Customers c\nwhere c.id not in (select customerId from Orders);\n``` | 10 | 0 | ['MySQL'] | 0 |
customers-who-never-order | SQL simplest solution | sql-simplest-solution-by-yehudisk-v6kx | \nSELECT Name as Customers\nFROM Customers\nWHERE Id not in (SELECT CustomerId \n FROM Orders)\n | yehudisk | NORMAL | 2020-08-20T14:47:17.946262+00:00 | 2020-08-20T14:47:17.946326+00:00 | 910 | false | ```\nSELECT Name as Customers\nFROM Customers\nWHERE Id not in (SELECT CustomerId \n FROM Orders)\n``` | 10 | 0 | [] | 1 |
customers-who-never-order | MySQL: Find Customers Not in Orders | mysql-find-customers-not-in-orders-by-fi-4q3k | Intuition\nYou need to find the names of customers from the Customers table who are not in the Orders table.\n\n# Approach\n1. Select Statement: Choose the name | d_sushkov | NORMAL | 2024-08-01T00:29:45.945034+00:00 | 2024-08-17T23:37:13.215354+00:00 | 2,065 | false | # Intuition\nYou need to find the names of customers from the Customers table who are not in the Orders table.\n\n# Approach\n1. Select Statement: Choose the name column from the Customers table.\n2. Alias: Rename the output column to Customers for clarity.\n3. Subquery: Use a subquery to get the list of customer IDs from the Orders table.\n4. Filtering: Use the `NOT IN` condition to exclude customers whose IDs are present in the list obtained from the subquery.\n\n# Complexity\n- Time complexity: $$O(m*n)$$ in the worst case, where $$m$$ is the number of rows in Customers and $$n$$ is the number of rows in Orders.\n\n- Space complexity: $$O(n + m)$$, where: $$O(n)$$ is for storing the subquery results. $$O(m)$$ is for storing the final output.\n\n# Code\n```\n# Write your MySQL query statement below\nSELECT name AS `Customers`\nFROM Customers\nWHERE id NOT IN (\n SELECT customerId \n FROM Orders\n);\n``` | 9 | 0 | ['Database', 'MySQL'] | 1 |
customers-who-never-order | MySQL | Pandas | Very Easy Solution | With Explanation 🔥🔥🔥 | mysql-pandas-very-easy-solution-with-exp-7nl4 | Code MYSQL\n\nselect name as customers from customers\nwhere id not in (select customerid from orders)\n\n\nHere\'s a breakdown of how this query works:\n\n1. s | KG-Profile | NORMAL | 2024-06-06T13:02:57.217749+00:00 | 2024-06-26T09:25:14.343591+00:00 | 3,727 | false | # Code MYSQL\n```\nselect name as customers from customers\nwhere id not in (select customerid from orders)\n```\n\nHere\'s a breakdown of how this query works:\n\n1. select name as customers: This selects the name of the customer from the customers table and aliases the column as customers.\n2. from customers: This specifies the primary table customers from which we are selecting the data.\n3. where id not in (select customerid from orders): This filters the results to include only those customers whose id is not present in the list of customerid values from the orders table.\n\n# Code Pandas\n```\nimport pandas as pd\n\ndef find_customers(customers: pd.DataFrame, orders: pd.DataFrame) -> pd.DataFrame:\n df = customers.merge(orders, left_on=\'id\', right_on=\'customerId\', how=\'left\')\n return df[df[\'customerId\'].isna()][[\'name\']].rename(columns={\'name\':\'Customers\'})\n```\n | 9 | 0 | ['MySQL', 'Pandas'] | 0 |
customers-who-never-order | pandas || 3 lines merge and filter | pandas-3-lines-merge-and-filter-by-spaul-qyas | \nimport pandas as pd\n\ndef find_customers(customers: pd.DataFrame,\n orders: pd.DataFrame) -> pd.DataFrame:\n\n df = customers.merge(orde | Spaulding_ | NORMAL | 2024-05-14T05:40:52.663602+00:00 | 2024-05-14T05:40:52.663637+00:00 | 856 | false | ```\nimport pandas as pd\n\ndef find_customers(customers: pd.DataFrame,\n orders: pd.DataFrame) -> pd.DataFrame:\n\n df = customers.merge(orders, how=\'left\',\n right_on=\'customerId\', left_on=\'id\')\n \n df = df.loc[df.customerId.isnull()\n ].rename(columns = {"name": "Customers"})\n\n return df.iloc[:,[1]] \n``` | 9 | 0 | ['Pandas'] | 0 |
customers-who-never-order | Awesome Code Sql | awesome-code-sql-by-ganjinaveen-wlql | \n# Code\n\nselect name as Customers from customers where id not in\n(\n select customerId from orders \n)\n\n\n# please upvote me it would encourage me alot | GANJINAVEEN | NORMAL | 2023-04-16T14:32:51.991762+00:00 | 2023-04-16T14:32:51.991795+00:00 | 2,538 | false | \n# Code\n```\nselect name as Customers from customers where id not in\n(\n select customerId from orders \n)\n\n```\n# please upvote me it would encourage me alot\n | 9 | 0 | ['MySQL'] | 1 |
customers-who-never-order | 183: Solution with step by step explanation | 183-solution-with-step-by-step-explanati-6eva | 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 | Marlen09 | NORMAL | 2023-02-21T13:58:01.766869+00:00 | 2023-02-21T13:58:01.766901+00:00 | 5,809 | 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\nTo find the customers who never ordered anything, we can use a LEFT JOIN between the Customers table and the Orders table. This will give us all customers with NULL orders. Here is the SQL query for this problem:\n\n```\nSELECT c.name AS Customers\nFROM Customers c\nLEFT JOIN Orders o ON c.id = o.customerId\nWHERE o.id IS NULL;\n\n```\nThis query selects the name column from the Customers table and left joins it with the Orders table on the customer ID. Then, it uses a WHERE clause to filter out the customers who have placed an order by checking for NULL values in the Orders table. Finally, the result is sorted by the customer name.\n\nThe output of the given input will be:\n```\n+-----------+\n| Customers |\n+-----------+\n| Henry |\n| Max |\n+-----------+\n``` | 9 | 0 | ['Database', 'MySQL'] | 2 |
customers-who-never-order | [MySQL] easy IN solution | mysql-easy-in-solution-by-olsh-n9mi | \nselect name as Customers from customers where id not in\n(select customerId from orders)\n | olsh | NORMAL | 2022-09-06T11:18:31.698148+00:00 | 2022-09-06T11:18:31.698183+00:00 | 387 | false | ```\nselect name as Customers from customers where id not in\n(select customerId from orders)\n``` | 9 | 0 | [] | 0 |
customers-who-never-order | Microsoft SQL Server: Find Customers Not in Orders | microsoft-sql-server-find-customers-not-f19xc | Intuition\nYou need to find the names of customers from the Customers table who are not in the Orders table.\n\n# Approach\n1. Select Statement: Choose the name | d_sushkov | NORMAL | 2024-08-01T00:29:40.802437+00:00 | 2024-08-17T23:36:58.773980+00:00 | 370 | false | # Intuition\nYou need to find the names of customers from the Customers table who are not in the Orders table.\n\n# Approach\n1. Select Statement: Choose the name column from the Customers table.\n2. Alias: Rename the output column to Customers for clarity.\n3. Subquery: Use a subquery to get the list of customer IDs from the Orders table.\n4. Filtering: Use the `NOT IN` condition to exclude customers whose IDs are present in the list obtained from the subquery.\n\n# Complexity\n- Time complexity: $$O(m*n)$$ in the worst case, where $$m$$ is the number of rows in Customers and $$n$$ is the number of rows in Orders.\n\n- Space complexity: $$O(n + m)$$, where: $$O(n)$$ is for storing the subquery results. $$O(m)$$ is for storing the final output.\n\n# Code\n```\n/* Write your T-SQL query statement below */\nSELECT name AS [Customers]\nFROM Customers\nWHERE id NOT IN (\n SELECT customerId \n FROM Orders\n);\n``` | 8 | 0 | ['Database', 'MS SQL Server'] | 0 |
customers-who-never-order | Pandas vs SQL | Elegant & Short | All 30 Days of Pandas solutions ✅ | pandas-vs-sql-elegant-short-all-30-days-gsaca | Complexity\n- Time complexity: O(n^2)\n- Space complexity: O(n)\n\n# Code\nPython []\ndef find_customers(customers: pd.DataFrame, orders: pd.DataFrame) -> pd.Da | Kyrylo-Ktl | NORMAL | 2023-08-01T14:37:29.089155+00:00 | 2023-08-06T16:39:44.399005+00:00 | 1,004 | false | # Complexity\n- Time complexity: $$O(n^2)$$\n- Space complexity: $$O(n)$$\n\n# Code\n```Python []\ndef find_customers(customers: pd.DataFrame, orders: pd.DataFrame) -> pd.DataFrame:\n return customers[\n ~customers[\'id\'].isin(orders[\'customerId\'])\n ][[\'name\']].rename(columns={\'name\': \'Customers\'})\n```\n```SQL []\nSELECT name AS \'Customers\'\n FROM Customers\n WHERE id NOT IN (\n SELECT customerId\n FROM Orders\n);\n```\n\n# Important!\n###### If you like the solution or find it useful, feel free to **upvote** for it, it will support me in creating high quality solutions)\n\n# 30 Days of Pandas solutions\n\n### Data Filtering \u2705\n- [Big Countries](https://leetcode.com/problems/big-countries/solutions/3848474/pandas-elegant-short-1-line/)\n- [Recyclable and Low Fat Products](https://leetcode.com/problems/recyclable-and-low-fat-products/solutions/3848500/pandas-elegant-short-1-line/)\n- [Customers Who Never Order](https://leetcode.com/problems/customers-who-never-order/solutions/3848527/pandas-elegant-short-1-line/)\n- [Article Views I](https://leetcode.com/problems/article-views-i/solutions/3867192/pandas-elegant-short-1-line/)\n\n\n### String Methods \u2705\n- [Invalid Tweets](https://leetcode.com/problems/invalid-tweets/solutions/3849121/pandas-elegant-short-1-line/)\n- [Calculate Special Bonus](https://leetcode.com/problems/calculate-special-bonus/solutions/3867209/pandas-elegant-short-1-line/)\n- [Fix Names in a Table](https://leetcode.com/problems/fix-names-in-a-table/solutions/3849167/pandas-elegant-short-1-line/)\n- [Find Users With Valid E-Mails](https://leetcode.com/problems/find-users-with-valid-e-mails/solutions/3849177/pandas-elegant-short-1-line/)\n- [Patients With a Condition](https://leetcode.com/problems/patients-with-a-condition/solutions/3849196/pandas-elegant-short-1-line-regex/)\n\n\n### Data Manipulation \u2705\n- [Nth Highest Salary](https://leetcode.com/problems/nth-highest-salary/solutions/3867257/pandas-elegant-short-1-line/)\n- [Second Highest Salary](https://leetcode.com/problems/second-highest-salary/solutions/3867278/pandas-elegant-short/)\n- [Department Highest Salary](https://leetcode.com/problems/department-highest-salary/solutions/3867312/pandas-elegant-short-1-line/)\n- [Rank Scores](https://leetcode.com/problems/rank-scores/solutions/3872817/pandas-elegant-short-1-line-all-30-days-of-pandas-solutions/)\n- [Delete Duplicate Emails](https://leetcode.com/problems/delete-duplicate-emails/solutions/3849211/pandas-elegant-short/)\n- [Rearrange Products Table](https://leetcode.com/problems/rearrange-products-table/solutions/3849226/pandas-elegant-short-1-line/)\n\n\n### Statistics \u2705\n- [The Number of Rich Customers](https://leetcode.com/problems/the-number-of-rich-customers/solutions/3849251/pandas-elegant-short-1-line/)\n- [Immediate Food Delivery I](https://leetcode.com/problems/immediate-food-delivery-i/solutions/3872719/pandas-elegant-short-1-line-all-30-days-of-pandas-solutions/)\n- [Count Salary Categories](https://leetcode.com/problems/count-salary-categories/solutions/3872801/pandas-elegant-short-1-line-all-30-days-of-pandas-solutions/)\n\n\n### Data Aggregation \u2705\n- [Find Total Time Spent by Each Employee](https://leetcode.com/problems/find-total-time-spent-by-each-employee/solutions/3872715/pandas-elegant-short-1-line-all-30-days-of-pandas-solutions/)\n- [Game Play Analysis I](https://leetcode.com/problems/game-play-analysis-i/solutions/3863223/pandas-elegant-short-1-line/)\n- [Number of Unique Subjects Taught by Each Teacher](https://leetcode.com/problems/number-of-unique-subjects-taught-by-each-teacher/solutions/3863239/pandas-elegant-short-1-line/)\n- [Classes More Than 5 Students](https://leetcode.com/problems/classes-more-than-5-students/solutions/3863249/pandas-elegant-short/)\n- [Customer Placing the Largest Number of Orders](https://leetcode.com/problems/customer-placing-the-largest-number-of-orders/solutions/3863257/pandas-elegant-short-1-line/)\n- [Group Sold Products By The Date](https://leetcode.com/problems/group-sold-products-by-the-date/solutions/3863267/pandas-elegant-short-1-line/)\n- [Daily Leads and Partners](https://leetcode.com/problems/daily-leads-and-partners/solutions/3863279/pandas-elegant-short-1-line/)\n\n\n### Data Aggregation \u2705\n- [Actors and Directors Who Cooperated At Least Three Times](https://leetcode.com/problems/actors-and-directors-who-cooperated-at-least-three-times/solutions/3863309/pandas-elegant-short/)\n- [Replace Employee ID With The Unique Identifier](https://leetcode.com/problems/replace-employee-id-with-the-unique-identifier/solutions/3872822/pandas-elegant-short-1-line-all-30-days-of-pandas-solutions/)\n- [Students and Examinations](https://leetcode.com/problems/students-and-examinations/solutions/3872699/pandas-elegant-short-1-line-all-30-days-of-pandas-solutions/)\n- [Managers with at Least 5 Direct Reports](https://leetcode.com/problems/managers-with-at-least-5-direct-reports/solutions/3872861/pandas-elegant-short/)\n- [Sales Person](https://leetcode.com/problems/sales-person/solutions/3872712/pandas-elegant-short-1-line-all-30-days-of-pandas-solutions/)\n\n | 8 | 1 | ['Python', 'Python3', 'Pandas'] | 1 |
customers-who-never-order | 2 Simple SQL Solutions | 2-simple-sql-solutions-by-nathanpaceydev-qfm0 | Solution 1.\nMore concise but less common.\n\nSELECT name AS Customers FROM Customers \nWHERE id not in (SELECT customerId FROM Orders)\n\n\nSolution 2.\nLonger | NathanPaceydev | NORMAL | 2022-04-27T22:08:00.223838+00:00 | 2022-04-27T22:08:00.223864+00:00 | 828 | false | Solution 1.\nMore concise but less common.\n```\nSELECT name AS Customers FROM Customers \nWHERE id not in (SELECT customerId FROM Orders)\n```\n\nSolution 2.\nLonger but more common and readable.\n```\nSELECT name AS Customers FROM Customers \nLEFT JOIN Orders\n ON Customers.id = Orders.customerId\nWHERE Orders.id IS NULL\n``` | 8 | 0 | ['MySQL'] | 0 |
customers-who-never-order | Simle accepted solution | simle-accepted-solution-by-tovam-v70h | \nselect Name as Customers\nfrom Customers c\nwhere c.Id not in (select CustomerId from Orders)\n\n\nLike it ? lease upvote ! | TovAm | NORMAL | 2021-10-24T15:25:59.289079+00:00 | 2021-10-24T15:25:59.289123+00:00 | 654 | false | ```\nselect Name as Customers\nfrom Customers c\nwhere c.Id not in (select CustomerId from Orders)\n```\n\n**Like it ? lease upvote !** | 8 | 0 | ['MySQL'] | 1 |
customers-who-never-order | PostgreSQL: Find Customers Not in Orders | postgresql-find-customers-not-in-orders-nky0d | Intuition\nYou need to find the names of customers from the Customers table who are not in the Orders table.\n\n# Approach\n1. Select Statement: Choose the name | d_sushkov | NORMAL | 2024-08-01T00:29:31.384188+00:00 | 2024-08-17T23:36:23.197247+00:00 | 1,425 | false | # Intuition\nYou need to find the names of customers from the Customers table who are not in the Orders table.\n\n# Approach\n1. Select Statement: Choose the name column from the Customers table.\n2. Alias: Rename the output column to Customers for clarity.\n3. Subquery: Use a subquery to get the list of customer IDs from the Orders table.\n4. Filtering: Use the `NOT IN` condition to exclude customers whose IDs are present in the list obtained from the subquery.\n\n# Complexity\n- Time complexity: $$O(m*n)$$ in the worst case, where $$m$$ is the number of rows in Customers and $$n$$ is the number of rows in Orders.\n\n- Space complexity: $$O(n + m)$$, where: $$O(n)$$ is for storing the subquery results. $$O(m)$$ is for storing the final output.\n\n# Code\n```\n-- Write your PostgreSQL query statement below\nSELECT name AS "Customers"\nFROM Customers\nWHERE id NOT IN (\n SELECT customerId \n FROM Orders\n);\n``` | 7 | 0 | ['Database', 'PostgreSQL'] | 0 |
customers-who-never-order | (5 methods) Pandas & SQL FULL EXPLANATION STEP BY STEP + Full commented code + One-Liners | 5-methods-pandas-sql-full-explanation-st-xuci | Panda\n\nAs we will see, you have 3 different methods to solve this problem (the 3rd will surprise you!) :\n- Filtering \n- Masking\n- Just For Fun\n\n## Approa | K_Le_Viking | NORMAL | 2024-04-21T02:00:31.897266+00:00 | 2024-04-21T02:00:31.897288+00:00 | 1,246 | false | # Panda\n\nAs we will see, you have 3 different methods to solve this problem (***the 3rd will surprise you!***) :\n- Filtering \n- Masking\n- Just For Fun\n\n## Approach #1\nThe idea in this approach is to create a filter and apply it to our DataFrame to get our result.\n#### Explanation\n1. We want to know all the customers who never ordered. To do that we will look the IDs of the customers who DO appear in the orders DataFrame and then negate the result.\n`.isin()` this function check if the element of the caller appear in the argument\n`~` the tilde at the beggining negates the result\n2. Apply the filter we just created to find the non-buyers customers\n`non_buyers = customers.loc[filter]` an alternative using this locate function also exists, even though the direct filtering is more straightforward and appropriate here.\n3. Finally select the column containing the names and rename it as asked.\n`columns={\'name\':"Customers"}` is an important argument of the renaming function. First you specify that you want to rename the columns. Then you specify which one to rename with which name with a dictionary as follow : `{"OLD_NAME":"NEW_NAME"}`\n#### Implementation\n```Python []\nimport pandas as pd\n\ndef find_customers(customers: pd.DataFrame, orders: pd.DataFrame) -> pd.DataFrame:\n # Create the filter of all the customer who doesn\'t appear in \'orders\'\n filter = ~customers["id"].isin(orders["customerId"])\n\n # Filter the DataFrame to get the non-buyers\n non_buyers = customers[filter]\n\n # Select the proper column and rename it\n result = non_buyers[[\'name\']].rename(columns={\'name\':"Customers"})\n\n # Return the result\n return result\n```\nYou can write this whole chunk as a one-liner:\n```\ndef find_customers(customers: pd.DataFrame, orders: pd.DataFrame) -> pd.DataFrame: return customers[~customers["id"].isin(orders["customerId"])][[\'name\']].rename(columns={\'name\':"Customers"})\n```\n## Approach #2\n\n#### Explanation\n1. Merge the orders DataFrame onto the customers one via a left join and by joining the IDs together\n`how="left"` indicates to the merging function how to perform the merge. We want orders to be merged onto customers and not the opposite.\n`left_on="id"` `right_on="customerId"` those two arguments are to specify that we want to join `customers["id"]` with `orders["customerId"]`\n2. Create a mask that will tell us which customer did not place any order\n`.isna()` this function checks the non number element in the given dataframe or dataseries\n3. Simply apply the mask we just created to our merged dataframe\n4. Take this masked dataframe, select the proper column and rename it.\n`columns={\'name\':"Customers"}` is an important argument of the renaming function. First you specify that you want to rename the columns. Then you specify which one to rename with which name with a dictionary as follow : `{"OLD_NAME":"NEW_NAME"}`\n#### Implementation\n```Python []\nimport pandas as pd\n\ndef find_customers(customers: pd.DataFrame, orders: pd.DataFrame) -> pd.DataFrame:\n # Merge the orders DataFrame onto the customers one\n merged = customers.merge(orders, how="left", left_on="id", right_on="customerId")\n\n # Create the mask by identifying all the non numbers customerId in the previously merged dataframe\n mask = merged[\'customerId\'].isna()\n\n # Apply it\n masked = merged[mask]\n\n # Select the right column and rename it\n result = masked[["name"]].rename(columns={"name":"Customers"})\n\n return result\n```\nA bit more bulky and maybe not the most optimized but here again a one-liner also exists:\n```\ndef find_customers(customers: pd.DataFrame, orders: pd.DataFrame) -> pd.DataFrame: return customers.merge(orders, how=\'left\', left_on=\'id\', right_on=\'customerId\')[customers.merge(orders, how=\'left\', left_on=\'id\', right_on=\'customerId\')[\'customerId\'].isna()][["name"]].rename(columns={"name":"Customers"})\n```\n\n## Approach #3\nThe idea in this particular approach is to write the most pythonic code possible (meaning, using the less pandas-related functions). Obviously this goes without saying that this is far from efficient, but as an exercise, it could be fun !\n#### Explanation\n1. Retrieve the customers IDs who ordered and make it a python list to stick to the theme :\n`list( orders[\'customerId\'] )` does just that by selecting the *customerId* column and converting it to a list.\n`orders[\'customerId\']).unique()` also achieve the same purpose but for the sake of this exercise let\'s stick to the pythonic way. \n2. Read each row of the customers dataframe, then check whether or not this ID already ordered:\n`len(customers)` simply use the built-in len() function to retrieve the length\nagain, `customers.shape[0]` does the job, but in a less "pure-pythonic" way.\n`[customers.name[i]]` here, don\'t forget the bracket, otherwise it will add the letters of the name to the list, and not the name itself.\n3. Finally, convert our list to the right data type and return it:\n`columns = ["Customers"]` don\'t forget to name the column\n#### Implementation\n```Python []\nimport pandas as pd\n\ndef find_customers(customers: pd.DataFrame, orders: pd.DataFrame) -> pd.DataFrame:\n # Get the customers IDs who ordered as a python list\n ordered_id = list(orders[\'customerId\']) #.unique()\n\n # Create a list of the clients names who never ordered\n clients = []\n\n # Iterate through all the rows of the dataframe\n for i in range(len(customers)): #customers.shape[0]\n # If a customer ID doesn\'t appear in the list of IDs, add that name to our list\n if customers.id[i] not in ordered_id:\n clients += [customers.name[i]] # You could use .append() here, but I prefer the += operator which seems easier to read to me.\n \n # Finally, convert our python list to the desired Pandas dataframe and return it\n clients = pd.DataFrame(clients, columns = ["Customers"])\n return clients\n```\nA nice One-Liner solution also exist for this approach:\n```\ndef find_customers(customers: pd.DataFrame, orders: pd.DataFrame) -> pd.DataFrame: return pd.DataFrame([customers.name[i] for i in range(customers.shape[0]) if customers.id[i] not in list(orders[\'customerId\'])], columns = [\'Customers\'])\n```\n \n\n# Database / SQL\n\nFor the database option, we also have a couple of options:\n- Conditionning\n- Joining\n\n## Approach #4\nHere we will place a condition and the select statement to retrieve only what we want.\n#### Explanation\n1. Just select the names in Customers and rename it as wanted\n`as Customers` don\'t forget this to rename it\n2. Specify from which table you want to do your selection\n3. Specify the condition. Here we want all the `Customers.id` that are not already in `Orders.customerId`\n#### Implementation\n```MySQL []\nSELECT \n name as Customers\nFROM \n Customers\nWHERE \n id not in (\n select customerId\n from Orders\n );\n```\n```MySQL_Server []\nSELECT \n name as Customers\nFROM \n Customers\nWHERE \n id not in (\n select customerId\n from Orders\n );\n```\n```Oracle []\nSELECT \n name as Customers\nFROM \n Customers\nWHERE \n id not in (\n select customerId\n from Orders\n );\n```\n```PostgreSQL []\nSELECT \n name as Customers\nFROM \n Customers\nWHERE \n id not in (\n select customerId\n from Orders\n );\n```\n\n## Approach #5\n\nNow, let\'s explore the final option with join\n#### Explanation\n1. As before, select the names and rename them\n2. Join Orders onto Customers\n3. Match the respective customers IDs\n4. Specify that you want only the customers that didn\'t place any order\n#### Implementation\n```MySQL []\nSELECT \n Customers.name AS Customers \nFROM \n Customers LEFT JOIN Orders \nON \n Customers.id=Orders.customerId \nWHERE \n Orders.customerId IS NULL;\n```\n```MySQL_Server []\nSELECT \n Customers.name AS Customers \nFROM \n Customers LEFT JOIN Orders \nON \n Customers.id=Orders.customerId \nWHERE \n Orders.customerId IS NULL;\n```\n```Oracle []\nSELECT \n Customers.name AS Customers \nFROM \n Customers LEFT JOIN Orders \nON \n Customers.id=Orders.customerId \nWHERE \n Orders.customerId IS NULL;\n```\n```PostgreSQL []\nSELECT \n Customers.name AS Customers \nFROM \n Customers LEFT JOIN Orders \nON \n Customers.id=Orders.customerId \nWHERE \n Orders.customerId IS NULL;\n```\nHere a shorthad is also possible by attributing an alias to the tables:\n\n```MySQL []\nSELECT \n c.name AS Customers \nFROM \n Customers c LEFT JOIN Orders o\nON \n c.id=o.customerId \nWHERE \n o.customerId IS NULL;\n```\n```MySQL_Server []\nSELECT \n c.name AS Customers \nFROM \n Customers c LEFT JOIN Orders o\nON \n c.id=o.customerId \nWHERE \n o.customerId IS NULL;\n```\n```Oracle []\nSELECT \n c.name AS Customers \nFROM \n Customers c LEFT JOIN Orders o\nON \n c.id=o.customerId \nWHERE \n o.customerId IS NULL;\n```\n```PostgreSQL []\nSELECT \n c.name AS Customers \nFROM \n Customers c LEFT JOIN Orders o\nON \n c.id=o.customerId \nWHERE \n o.customerId IS NULL;\n```\n---\n\n\nThanks for reading me ! Have a good one ! | 7 | 0 | ['Database', 'Python', 'Python3', 'MySQL', 'Oracle', 'MS SQL Server', 'PostgreSQL', 'Pandas'] | 1 |
customers-who-never-order | MySQL Solution | mysql-solution-by-redallium-zxkz | \nSelection of only those people whose id does not fall into the selection of people who made orders.\n\nSELECT name AS \'Customers\'\n FROM Customers\n W | Redallium | NORMAL | 2022-10-09T11:08:41.404451+00:00 | 2023-05-06T09:29:34.362867+00:00 | 1,986 | false | \nSelection of only those people whose id does not fall into the selection of people who made orders.\n```\nSELECT name AS \'Customers\'\n FROM Customers\n WHERE id NOT IN (\n SELECT C.id\n FROM Customers AS C INNER JOIN Orders AS O\n ON O.customerId = C.id\n )\n``` | 7 | 0 | ['MySQL'] | 0 |
customers-who-never-order | Easiest Solution || MySQL || Beginners | easiest-solution-mysql-beginners-by-varu-b3vf | \nSELECT name as Customers FROM Customers\nWHERE Customers.ID NOT IN (SELECT customerID FROM Orders);\n\n | varun_jadon | NORMAL | 2022-09-10T03:26:17.723235+00:00 | 2022-09-10T03:26:17.723261+00:00 | 1,028 | false | ```\nSELECT name as Customers FROM Customers\nWHERE Customers.ID NOT IN (SELECT customerID FROM Orders);\n\n``` | 7 | 0 | ['MySQL', 'Oracle'] | 0 |
customers-who-never-order | ✅MySQL-2 Different Approach ||One Line Solution|| Beginner level|| Simple, Short ,Solution✅ | mysql-2-different-approach-one-line-solu-qr8f | Please upvote to motivate me in my quest of documenting all leetcode solutions. HAPPY CODING:)\nAny suggestions and improvements are always welcome.\n____\n\u27 | Anos | NORMAL | 2022-08-13T18:34:35.309456+00:00 | 2022-08-13T18:52:26.429697+00:00 | 319 | false | ***Please upvote to motivate me in my quest of documenting all leetcode solutions. HAPPY CODING:)\nAny suggestions and improvements are always welcome**.*\n______________________\n\u2705 **MySQL Code :**\n***Approach 1:***\n```\nSELECT name AS Customers FROM Customers LEFT JOIN Orders ON (Orders.customerId = Customers.id) WHERE Orders.id IS NULL\n```\n__________________________________\n***Approach 2***:\n\n```\nSELECT A.Name AS Customers FROM Customers A WHERE A.Id NOT IN (SELECT B.CustomerId FROM Orders B)`\n```\n______________________\nIf you like the solution, please upvote \uD83D\uDD3C\nFor any questions, or discussions, comment below. \uD83D\uDC47\uFE0F | 7 | 0 | ['MySQL'] | 0 |
customers-who-never-order | 📌 Simple MySql solution using left JOIN | simple-mysql-solution-using-left-join-by-41uv | \nSELECT Name AS \'Customers\' FROM Customers c LEFT JOIN Orders o ON c.Id = o.CustomerId WHERE o.CustomerId IS NULL\n | dark_wolf_jss | NORMAL | 2022-06-24T10:52:24.711962+00:00 | 2022-06-24T10:52:24.711990+00:00 | 411 | false | ```\nSELECT Name AS \'Customers\' FROM Customers c LEFT JOIN Orders o ON c.Id = o.CustomerId WHERE o.CustomerId IS NULL\n``` | 7 | 0 | ['MySQL'] | 0 |
customers-who-never-order | simple and easy solution || MySQL | simple-and-easy-solution-mysql-by-shishi-8b79 | if it\'s help, please up \u2B06 vote! \u2764\uFE0F\n\n###### Let\'s Connect on LinkedIn: www.linkedin.com/in/shishirrsiam\n###### Let\'s Connect on Facebook: ww | shishirRsiam | NORMAL | 2024-09-20T19:18:46.365503+00:00 | 2024-09-20T19:18:46.365531+00:00 | 1,500 | false | # if it\'s help, please up \u2B06 vote! \u2764\uFE0F\n\n###### Let\'s Connect on LinkedIn: www.linkedin.com/in/shishirrsiam\n###### Let\'s Connect on Facebook: www.fb.com/shishirrsiam\n\n# Code\n```mysql []\nselect Customers.name as Customers from Customers\nleft join Orders on Customers.id = Orders.customerId\ngroup by Customers.id having not count(Orders.customerId) or null;\n``` | 6 | 0 | ['Database', 'MySQL'] | 5 |
customers-who-never-order | MySQL Solution for Customers Who Never Order Problem | mysql-solution-for-customers-who-never-o-3127 | Intuition\n Describe your first thoughts on how to solve this problem. \nThe query aims to find customers who are not present in the Orders table, indicating th | Aman_Raj_Sinha | NORMAL | 2023-05-15T03:37:39.915240+00:00 | 2023-05-15T03:37:39.915271+00:00 | 1,526 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe query aims to find customers who are not present in the Orders table, indicating that they have not placed any orders.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. The subquery (Select CustomerId from Orders) retrieves the customer IDs from the Orders table.\n2. The main query Select Name as Customers from Customers selects the names (Name) of customers from the Customers table.\n3. The where clause where Id not in (Select CustomerId from Orders) filters the customers based on their IDs, excluding those IDs that are present in the subquery result.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nThe time complexity of the SQL query depends on the size of the Customers and Orders tables and the efficiency of the database engine\'s query optimization and execution. Assuming proper indexing and optimization, the time complexity can vary but is typically in the order of O(n log n) or O(n), where n is the number of rows in the Customers table.\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nThe space complexity of the SQL query is determined by the memory required to store the result set, which in this case is the names of customers who have not placed any orders. The space complexity is proportional to the number of rows returned by the query.\n\n# Code\n```\n# Write your MySQL query statement below\nSelect Name as Customers from Customers where Id not in \n(\n Select CustomerId from Orders\n)\n``` | 6 | 0 | ['MySQL'] | 0 |
customers-who-never-order | ✅MySQL || LEFT JOIN and Alias || EASY to understand | mysql-left-join-and-alias-easy-to-unders-f0bz | \n\n\n\tSELECT c.name AS Customers FROM \n\t(customers AS c LEFT JOIN orders AS o ON c.id = o.customerId) WHERE o.id IS NULL;\n | abhinav_0107 | NORMAL | 2023-01-16T19:14:58.234817+00:00 | 2023-01-16T19:14:58.234858+00:00 | 4,439 | false | \n\n\n\tSELECT c.name AS Customers FROM \n\t(customers AS c LEFT JOIN orders AS o ON c.id = o.customerId) WHERE o.id IS NULL;\n | 6 | 0 | ['MySQL'] | 0 |
customers-who-never-order | [MySQL] NOT IN Clause Solution | mysql-not-in-clause-solution-by-blackspi-ynts | \nSELECT name AS Customers\nFROM Customers\nWHERE Customers.id NOT IN\n(\nSELECT customerId FROM Orders\n)\n | blackspinner | NORMAL | 2022-08-15T07:08:47.537863+00:00 | 2022-08-15T07:08:47.537899+00:00 | 372 | false | ```\nSELECT name AS Customers\nFROM Customers\nWHERE Customers.id NOT IN\n(\nSELECT customerId FROM Orders\n)\n``` | 6 | 0 | [] | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.