File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -268,6 +268,7 @@ My accepted leetcode solutions to some of the common interview problems.
268268- [ String Compression] ( problems/src/string/StringCompression.java ) (Easy)
269269- [ Longest Common Prefix] ( problems/src/string/LongestCommonPrefix.java ) (Easy)
270270- [ Find the Closest Palindrome] ( problems/src/string/FindTheClosestPalindrome.java ) (Hard)
271+ - [ Monotone Increasing Digits] ( problems/src/string/MonotoneIncreasingDigits.java ) (Medium)
271272
272273#### [ Tree] ( problems/src/tree )
273274
Original file line number Diff line number Diff line change 1+ package string ;
2+
3+ /**
4+ * Created by gouthamvidyapradhan on 01/05/2018.
5+ * Given a non-negative integer N, find the largest number that is less than or equal to N with monotone
6+ * increasing digits.
7+
8+ (Recall that an integer has monotone increasing digits if and only if each pair of
9+ adjacent digits x and y satisfy x <= y.)
10+
11+ Example 1:
12+ Input: N = 10
13+ Output: 9
14+ Example 2:
15+ Input: N = 1234
16+ Output: 1234
17+ Example 3:
18+ Input: N = 332
19+ Output: 299
20+ Note: N is an integer in the range [0, 10^9].
21+
22+ Solution O(N): Convert to string for easier manipulation.
23+ Start from N.length - 1 and iterate through until index 0.Mark the index where the violation occurs.
24+ Decrement the value of the latest index where the violation occurs and append '9' to
25+ rest of the trailing digits. Convert the string to integer before returning.
26+ */
27+ public class MonotoneIncreasingDigits {
28+ /**
29+ * Main method
30+ * @param args
31+ * @throws Exception
32+ */
33+ public static void main (String [] args ) throws Exception {
34+ System .out .println (new MonotoneIncreasingDigits ().monotoneIncreasingDigits (100001 ));
35+ }
36+
37+ public int monotoneIncreasingDigits (int N ) {
38+ String s = String .valueOf (N );
39+ if (s .length () == 1 ) return N ;
40+ int p = -1 ;
41+ int prev = N % 10 ;
42+ for (int i = s .length () - 2 ; i >= 0 ; i --){
43+ int curr = Integer .parseInt (String .valueOf (s .charAt (i )));
44+ if (curr > prev ){
45+ p = i ;
46+ prev = curr - 1 ;
47+ } else {
48+ prev = curr ;
49+ }
50+ }
51+ if (p == -1 ) return N ;
52+ StringBuilder result = new StringBuilder ();
53+ for (int i = 0 ; i < s .length (); i ++){
54+ if (i == p ){
55+ int pV = Integer .parseInt (String .valueOf (s .charAt (i )));
56+ result .append (pV - 1 );
57+ break ;
58+ } result .append (String .valueOf (s .charAt (i )));
59+ }
60+ for (int i = p + 1 ; i < s .length (); i ++){
61+ result .append ("9" );
62+ }
63+ return Integer .parseInt (result .toString ());
64+ }
65+
66+ }
You can’t perform that action at this time.
0 commit comments