title
stringlengths 3
77
| title_slug
stringlengths 3
77
| question_content
stringlengths 38
1.55k
⌀ | tag
stringclasses 707
values | level
stringclasses 3
values | question_hints
stringlengths 19
3.98k
⌀ | view_count
int64 8
630k
| vote_count
int64 5
10.4k
| content
stringlengths 0
43.9k
| __index_level_0__
int64 0
109k
|
---|---|---|---|---|---|---|---|---|---|
Reverse Integer | reverse-integer | Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-231, 231 - 1], then return 0. Assume the environment does not allow you to store 64-bit integers (signed or unsigned). | Math | Medium | null | 996 | 6 | # Intuition\nBrute-Force Alogrithm just 1 Loop\n\n# Approach\nJUST Normal Run the loop while x !=0 after that i check if sum is\nin range ((sum>INT_MAX / 10) ||(sum<INT_MIN / 10)) if it goes to upper bound of that then return 0 otherwise add value in sum then return \nsum;\n\n# Complexity\n- Time complexity:\n0(n);\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int reverse(int x) {\n // To check for overflow\n // To check for overflow\n \n int sum = 0;\n while (x != 0) {\n int rem = x % 10;\n \n // Check for overflow before updating sum\n if((sum>INT_MAX / 10) ||(sum<INT_MIN / 10)){\n return 0;\n }\n \n sum = sum * 10 + rem;\n x = x / 10;\n }\n \n return sum;\n }\n};\n\n``` | 697 |
String to Integer (atoi) | string-to-integer-atoi | Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer (similar to C/C++'s atoi function). The algorithm for myAtoi(string s) is as follows: Note: | String | Medium | null | 36,371 | 208 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe can solve this problem using String.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nWe can easily understand the approach by seeing the code which is easy to understand with comments.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nTime Complexity : O(logN), Since we are going through the entire number digit by digit, the time complexity should be O(log10N). The reason behind log10 is because we are dealing with integers which are base 10.\n\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nSpace Complexity : O(1), We are not using any data structure for interim operations, therefore, the space complexity is O(1).\n\n# Code\n```\n/*\n\n Time Complexity : O(logN), Since we are going through the entire number digit by digit, the time complexity\n should be O(log10N). The reason behind log10 is because we are dealing with integers which are base 10.\n\n Space Complexity : O(1), We are not using any data structure for interim operations, therefore, the space\n complexity is O(1).\n\n Solved using String.\n\n*/\n\nclass Solution {\npublic:\n int myAtoi(string s) {\n int len = s.size();\n double num = 0;\n int i=0;\n while(s[i] == \' \'){\n i++;\n }\n bool positive = s[i] == \'+\';\n bool negative = s[i] == \'-\';\n positive == true ? i++ : i;\n negative == true ? i++ : i;\n while(i < len && s[i] >= \'0\' && s[i] <= \'9\'){\n num = num*10 + (s[i]-\'0\');\n i++;\n }\n num = negative ? -num : num;\n cout<<num<<endl;\n num = (num > INT_MAX) ? INT_MAX : num;\n num = (num < INT_MIN) ? INT_MIN : num;\n cout<<num<<endl;\n return int(num);\n }\n};\n\n```\n\n***IF YOU LIKE THE SOLUTION THEN PLEASE UPVOTE MY SOLUTION BECAUSE IT GIVES ME MOTIVATION TO REGULARLY POST THE SOLUTION.***\n\n![WhatsApp Image 2023-02-10 at 19.01.02.jpeg]() | 701 |
String to Integer (atoi) | string-to-integer-atoi | Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer (similar to C/C++'s atoi function). The algorithm for myAtoi(string s) is as follows: Note: | String | Medium | null | 6,346 | 5 | # 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 myAtoi(string s) {\n long number = 0;\n bool isNegative = false;\n bool signReceived = false;\n bool numberReceived = false;\n\n for(int i = 0; i < s.size(); i++){\n if(s[i] == \' \' && !numberReceived && !signReceived) continue;\n else if(s[i] == \'-\'){\n if(signReceived && numberReceived)\n break;\n else if(signReceived)\n return 0;\n isNegative = true;\n signReceived = true;\n }\n else if(s[i] == \'+\'){\n if(signReceived && numberReceived)\n break;\n else if(signReceived)\n return 0;\n signReceived = true;\n }\n else if(s[i] >= \'0\' && s[i] <= \'9\'){\n numberReceived = true;\n signReceived = true;\n number += s[i] - 48; //48 is ascii for 0\n if(number > pow(2,31) && isNegative){ \n number = pow(2,31);\n break;\n }\n else if(number > pow(2,31) - 1 && !isNegative){ \n number = pow(2,31) - 1;\n break;\n }\n if(i < s.size()-1 && s[i+1] >= \'0\' && s[i+1] <= \'9\')number *= 10;\n }\n else break;\n }\n \n return isNegative ? -number : number;\n }\n};\n``` | 702 |
String to Integer (atoi) | string-to-integer-atoi | Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer (similar to C/C++'s atoi function). The algorithm for myAtoi(string s) is as follows: Note: | String | Medium | null | 47,379 | 351 | <img src = "" width = 100%>\n\n<img src = "" width = 100%>\n\n<u>**BASIC IDEA:**</u>\n\n1. **Start traversing the provided string**(`str`)\n2. **Skip all the leading white spaces**. eg: `" -123456" --> "-123456"`\n3. **Check for sign cases**(+-). eg: `"-123456"`. If `+`, then set the variable(boolean) `isNegative` to `true` and if it\'s `-`, set `isNegative` to `false`\n4. **Iterate over the next remaining characters and keep adding them in `result` by converting the digits**(in character form) **to integer form.** eg: `"-123456" --> -123456`, until the **non-digit character** is found.\n\n<u>**NOTE:**</u> Logic is implemented in such a way that after performing above 3 steps, if it finds characters(English letters (lower-case and upper-case), digits (0-9), \' \', \'+\', \'-\', and \'.\') before the digit character, it will give output as 0(zero) eg: `"abc-123456" --> 0` and if it finds characters(English letters (lower-case and upper-case), digits (0-9), \' \', \'+\', \'-\', and \'.\') after the digit characters, it will return the number eg: `"-123456abc" --> -123456`\n<br>\n\n**C++ / JAVA CODE:**\n<iframe src="" frameBorder="0" width="100%" height="1000"></iframe>\n\n\n* **Let\'s understand what** \n`if(result > (Integer.MAX_VALUE / 10) || (result == (Integer.MAX_VALUE / 10) && digit > 7)){`\n `return isNegative ? Integer.MIN_VALUE : Integer.MAX_VALUE;`\n`}`\n**means in <u>JAVA</u>? You will be able to figure out this statement easily for <u>C++</u> code too.**\n\n\t* `result > (Integer.MAX_VALUE / 10)` means:\n\tSuppose, \n\t`result = 214748365`(9 digits)\n\t`Integer.MAX_VALUE = 2147483647`(10 digits) and `Integer.MAX_VALUE / 10 = 214748364`(9 digits)\n\tHere, it is clearly evident that `result > Integer.MAX_VALUE / 10`( i.e. 214748365 > 214748364) and if we try to add even 0(zero) in result `214748365`(9 digits), the number will become `2147483650`(10 digits) which is obviously greater than `2147483647(Integer.MAX_VALUE which is of 10 digits)`. So even before adding `0(zero) or any other digit`, we return the `Integer.MAX_VALUE` or `Integer.MIN_VALUE`, according to the sign case, in order <u>to avoid integer overflow.</u>\n\n\n\t* And, `result == (Integer.MAX_VALUE / 10) && digit > 7` means:\n\tSuppose, \n\t`result = 214748364`(9 digits), and\n\t`Integer.MAX_VALUE / 10 = 214748364`(9 digits)\n\tNow, if the result is equal to the Integer.MAX_VALUE / 10 (214748364 == 214748364) and the digit is greater than 7 i.e. `digit > 7` and if we try to add 8(assume the digit greater than 7 to be 8) to the result, then the number will become `2147483648`(10 digits), which will result in integer overflow. So, even before adding the digit which is greater than 7, we return the `Integer.MAX_VALUE` or `Integer.MIN_VALUE`, according to the sign case, <u>to avoid integer overflow.</u>\n\n<hr>\n\n**More optimized by using char and int variable in order to avoid calling charAt(index) and Integer.MAX_VALUE / 10 repeatedly**\n\n**<u>Optimized C++ / JAVA CODE</u>**\n\n<iframe src="" frameBorder="0" width="100%" height="800"></iframe>\n\n**SUGGESTION:**\n**In JAVA**, you can replace the following condition \n```\nif(result > (Integer.MAX_VALUE / 10) || (result == (Integer.MAX_VALUE / 10) && digit > 7))\n return isNegative ? Integer.MIN_VALUE : Integer.MAX_VALUE;\n```\nwith\n```\nif(result > (Integer.MAX_VALUE - digit) / 10)\n return isNegative ? Integer.MIN_VALUE : Integer.MAX_VALUE;\n```\n\nAnd, **In C++**, you can replace the following condition \n```\nif(result > (INT_MAX / 10) || (result == (INT_MAX / 10) && digit > 7))\n return isNegative ? INT_MIN : INT_MAX;\n```\nwith\n```\nif(result > (INT_MAX - digit) / 10)\n return isNegative ? INT_MIN : INT_MAX;\n```\n<hr>\n\n**COMPLEXITY:**\n* **Time: O(n)**, where n is the length of String\n* **Space: O(1)**, in-place\n\n<u>**Refer to the following github repsitory for more leetcode solutions**</u>\n\n\n\n# **Please UPVOTE if you find the solution helpful :)** | 705 |
String to Integer (atoi) | string-to-integer-atoi | Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer (similar to C/C++'s atoi function). The algorithm for myAtoi(string s) is as follows: Note: | String | Medium | null | 24,630 | 286 | A fast and (probably) **much simpler and easier to understand DFA solution** than the others when you search for the keyword `DFA`:\n\n```python\nclass Solution:\n def myAtoi(self, str: str) -> int:\n value, state, pos, sign = 0, 0, 0, 1\n\n if len(str) == 0:\n return 0\n\n while pos < len(str):\n current_char = str[pos]\n if state == 0:\n if current_char == " ":\n state = 0\n elif current_char == "+" or current_char == "-":\n state = 1\n sign = 1 if current_char == "+" else -1\n elif current_char.isdigit():\n state = 2\n value = value * 10 + int(current_char)\n else:\n return 0\n elif state == 1:\n if current_char.isdigit():\n state = 2\n value = value * 10 + int(current_char)\n else:\n return 0\n elif state == 2:\n if current_char.isdigit():\n state = 2\n value = value * 10 + int(current_char)\n else:\n break\n else:\n return 0\n pos += 1\n\n value = sign * value\n value = min(value, 2 ** 31 - 1)\n value = max(-(2 ** 31), value)\n\n return value\n```\n\nDFA, which stands for Deterministic finite automaton, is a state machine that either accepts or rejects a sequence of symbols by running through a state sequence uniquely determined by the string. The DFA I used to implement this answer is very simple:\n\n![image]()\n\n | 713 |
String to Integer (atoi) | string-to-integer-atoi | Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer (similar to C/C++'s atoi function). The algorithm for myAtoi(string s) is as follows: Note: | String | Medium | null | 227,088 | 738 | I think we only need to handle four cases: \n\n 1. discards all leading whitespaces\n 2. sign of the number\n 3. overflow\n 4. invalid input\n\nIs there any better solution? Thanks for pointing out!\n\n int atoi(const char *str) {\n int sign = 1, base = 0, i = 0;\n while (str[i] == ' ') { i++; }\n if (str[i] == '-' || str[i] == '+') {\n sign = 1 - 2 * (str[i++] == '-'); \n }\n while (str[i] >= '0' && str[i] <= '9') {\n if (base > INT_MAX / 10 || (base == INT_MAX / 10 && str[i] - '0' > 7)) {\n if (sign == 1) return INT_MAX;\n else return INT_MIN;\n }\n base = 10 * base + (str[i++] - '0');\n }\n return base * sign;\n } | 714 |
String to Integer (atoi) | string-to-integer-atoi | Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer (similar to C/C++'s atoi function). The algorithm for myAtoi(string s) is as follows: Note: | String | Medium | null | 1,464 | 5 | \n# Code\n```\nclass Solution {\n public:\n int myAtoi(string s) {\n trim(s);\n if (s.empty())\n return 0;\n\n const int sign = s[0] == \'-\' ? -1 : 1;\n if (s[0] == \'+\' || s[0] == \'-\')\n s = s.substr(1);\n\n long num = 0;\n\n for (const char c : s) {\n if (!isdigit(c))\n break;\n num = num * 10 + (c - \'0\');\n if (sign * num < INT_MIN)\n return INT_MIN;\n if (sign * num > INT_MAX)\n return INT_MAX;\n }\n\n return sign * num;\n }\n\n private:\n void trim(string& s) {\n s.erase(0, s.find_first_not_of(\' \'));\n s.erase(s.find_last_not_of(\' \') + 1);\n }\n};\n\n \n \n``` | 715 |
String to Integer (atoi) | string-to-integer-atoi | Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer (similar to C/C++'s atoi function). The algorithm for myAtoi(string s) is as follows: Note: | String | Medium | null | 1,193 | 5 | # 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```\nimport java.math.BigInteger;\n\nclass Solution {\n public int myAtoi(String s) {\n s = s.trim();\n StringBuilder st = new StringBuilder();\n char[] arr = s.toCharArray();\n\n if (s.isEmpty()) {\n return 0;\n }\n\n for (int i = 0; i < arr.length; i++) {\n if (Character.isDigit(arr[i]) || (i == 0 && (arr[i] == \'-\' || arr[i] == \'+\'))) {\n st.append(arr[i]);\n } else {\n break;\n }\n }\n\n if (st.length() == 0 || (st.length() == 1 && (st.charAt(0) == \'-\' || st.charAt(0) == \'+\'))) {\n return 0;\n }\n\n BigInteger result = new BigInteger(st.toString());\n\n if (result.compareTo(BigInteger.valueOf(Integer.MAX_VALUE)) > 0) {\n return Integer.MAX_VALUE;\n } else if (result.compareTo(BigInteger.valueOf(Integer.MIN_VALUE)) < 0) {\n return Integer.MIN_VALUE;\n }\n\n return result.intValue();\n }\n}\n\n``` | 716 |
String to Integer (atoi) | string-to-integer-atoi | Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer (similar to C/C++'s atoi function). The algorithm for myAtoi(string s) is as follows: Note: | String | Medium | null | 1,628 | 7 | ```\nint myAtoi(string s) {\n int flag =0;\n int i=0;\n\t\t//if we encounter spaces before any character , we will simply increment i else break out of loop.\n while(i<s.size()){\n if(s[i]==\' \')i++; \n else break; \n }\n\t\t//if number is starting with character (\'-\' minus) then we set the flag to 1 and increment the counter\n if(s[i]==\'-\'){\n i++;\n flag = 1;\n }\n else if(s[i]==\'+\')\n\t\t\ti++;\n long num =0;\n\t\t//starting the count from i\n for(int j=i; j<s.size();j++){\n if(s[j]>=\'0\' && s[j] <=\'9\'){ // i.e s[j] lies between or equal to 0 to 9\n num = num*10 + (s[j]-\'0\');\n\t\t\t\t//from above line there might be a chance when the number will get overflow.\n if(num>=INT_MAX) break; \n }\n else //if character other then number then exit the loop\n break;\n }\n \n if(flag==1)\n num*=-1;\n\t\t\tif(num<=INT_MIN)return INT_MIN; //according to question point number 5\n else if(num>=INT_MAX) return INT_MAX;\n return num;\n }\n```\n**Thanks :)** | 724 |
String to Integer (atoi) | string-to-integer-atoi | Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer (similar to C/C++'s atoi function). The algorithm for myAtoi(string s) is as follows: Note: | String | Medium | null | 849 | 6 | \n# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\nlong long solver(string s,int sign,int i,long long res){\n if(sign*res>=INT_MAX) return INT_MAX;\n \n if(sign*res<=INT_MIN) return INT_MIN;\n \n if(s[i]==\' \'||!isdigit(s[i])) return res*sign;\n \n int sol = s[i]-\'0\';\n \n return solver(s,sign,i+1,res*10+sol);\n}\n int myAtoi(string s) {\n int flag =0;\n int sign=1;\n int i =0;\n while (i<s.size() && s[i]==\' \') i++;\n \n if(s[i]==\'-\'){\n sign = -1;\n i++;\n flag ++;\n }\n if(s[i]==\'+\'){\n sign = 1;\n i++;\n flag ++;\n }\n if(flag >1) return 0;\n return solver(s,sign,i,0);\n }\n};\n``` | 729 |
String to Integer (atoi) | string-to-integer-atoi | Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer (similar to C/C++'s atoi function). The algorithm for myAtoi(string s) is as follows: Note: | String | Medium | null | 2,573 | 8 | # Intuition\nBasically, we keep multiplying our answer by 10 and keep adding next number unless we encounter a condition which is not valid\n\n# Approach\n(1) Trim the string for any leading and trailing spaces\n\n(2) Determine the sign of the input (positive or negative). After trimming this sign can be at first postion for this to be a valid string. By default, sign should be positive (i.e. 1). This sign we will use to determine our final answer in the end\n\n(3) Determine the start of the loop. We the input string has a leading sign, we should start with 1st index since we have already covered the sign part in (2). Or else we would start with 0th index\n\n(4) We start the loop on our string and determine the digit by subtracting 48. (ASCII values of digits 0-9 are 48-57). So if our char is \'0\', to get the actual digit value we would do, 48-48 = 0. If the char is \'1\', 49-48 = 1.\n\n5) We check if the number is in range 0 and 9 if not we break the loop since it is not a valid character and we do not need to look further\n\n6) Now we have 2 main checks, one for positive sign and one for negative sign. If number is positive (i.e. sign = 1) then we check if the calculation does not cause integer overflow if it does then we return Integer MAX VALUE. \nTo add the digit to our answer we would need to multiply by 10, so we have to check if this multiplication does not cause overflow. \n(ans <= Integer.MAX_VALUE / 10).\nNext check is to check when we add the digit to our answer, it does not overflow\n(ans * 10) < Integer.MAX_VALUE - num)\nWe do the same thing if number is negative (sign = -1), only difference here is we have to multiply our answer by sign -1 since number is negative.\n\n7) Finally, we multiply the answer with the sign we determined at the start\n\n# Complexity\n- Time complexity:\nO(N) - Only one loop over the string \n\n- Space complexity:\nO(1) - No extra space is used\n\n# Code\n```\nclass Solution {\n public int myAtoi(String s) {\n\t\ts = s.trim();\n\t\tif (s.length() < 1)\n\t\t\treturn 0;\n\n\t\tint sign = 1;\n\t\tint i =0;\n\t\tif(s.charAt(0) == \'-\') {\n\t\t\tsign = -1;\n\t\t\ti = 1;\n\t\t} else if(s.charAt(0) == \'+\') {\n\t\t\ti = 1;\n\t\t}\n\t\tint ans = 0;\n\t\tfor (; i < s.length(); i++) {\n\t\t\tint num = s.charAt(i) - 48;\n\n\t\t\tif ((num >= 0 && num <= 9)) {\n\t\t\t\tif (sign > 0) {\n\t\t\t\t\tif (ans <= Integer.MAX_VALUE / 10 \n && ((ans * 10) < Integer.MAX_VALUE - num)) {\n\t\t\t\t\t\t\tans = ans * 10 + num;\n\t\t\t\t\t} else {\n\t\t\t\t\t\treturn Integer.MAX_VALUE;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (sign < 0) {\n\t\t\t\t\tif (ans * sign >= Integer.MIN_VALUE / 10\n && ((ans * 10) * sign > Integer.MIN_VALUE + num)) {\n\t\t\t\t\t\t\tans = ans * 10 + num;\n\t\t\t\t\t} else {\n\t\t\t\t\t\treturn Integer.MIN_VALUE;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t} else {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\treturn ans * sign;\n\n\t \n \n }\n}\n``` | 734 |
String to Integer (atoi) | string-to-integer-atoi | Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer (similar to C/C++'s atoi function). The algorithm for myAtoi(string s) is as follows: Note: | String | Medium | null | 4,091 | 13 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n long atoi(string s, int sign, int i, long result) {\n if(sign*result>=INT_MAX){\n return INT_MAX;\n }\n if(sign*result<=INT_MIN){\n return INT_MIN;\n }\n if(i>=s.size()|| s[i]<\'0\' || s[i]>\'9\'){\n return sign*result;\n }\n \n \n result=atoi(s,sign,i+1,(result*10+(s[i]-\'0\')));\n \n return result;\n }\n\npublic:\n int myAtoi(string s) {\n \n int i = 0, n = s.size(), sign = 1;\n while (i < n && s[i] == \' \'){\n ++i;\n }\n if (s[i] == \'-\')\n sign = -1, ++i;\n else if (s[i] == \'+\')\n ++i;\n \n return atoi(s, sign, i, 0);\n }\n};\n```\nPlease upvote to motivate me to write more solutions\n\n | 739 |
String to Integer (atoi) | string-to-integer-atoi | Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer (similar to C/C++'s atoi function). The algorithm for myAtoi(string s) is as follows: Note: | String | Medium | null | 105,004 | 402 | public int myAtoi(String str) {\n int index = 0, sign = 1, total = 0;\n //1. Empty string\n if(str.length() == 0) return 0;\n\n //2. Remove Spaces\n while(str.charAt(index) == ' ' && index < str.length())\n index ++;\n\n //3. Handle signs\n if(str.charAt(index) == '+' || str.charAt(index) == '-'){\n sign = str.charAt(index) == '+' ? 1 : -1;\n index ++;\n }\n \n //4. Convert number and avoid overflow\n while(index < str.length()){\n int digit = str.charAt(index) - '0';\n if(digit < 0 || digit > 9) break;\n\n //check if total will be overflow after 10 times and add digit\n if(Integer.MAX_VALUE/10 < total || Integer.MAX_VALUE/10 == total && Integer.MAX_VALUE %10 < digit)\n return sign == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE;\n\n total = 10 * total + digit;\n index ++;\n }\n return total * sign;\n } | 740 |
String to Integer (atoi) | string-to-integer-atoi | Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer (similar to C/C++'s atoi function). The algorithm for myAtoi(string s) is as follows: Note: | String | Medium | null | 10,668 | 84 | **Let\'s understand this problem with all possible testcases.**\n![image]()\n\n1. If we look at **1st testcase**. We have Given a string with numerical values & we will simply return in Integral value and **return 42**.\n2. If we look at **2nd testcase**. First we see we have some space "and it\'s clearly mentioned in question, we need to **discard whitespace**", then we **takecare of sign** & use sign as it is & finally use numerical value **return -42**.\n3. If we look at **3rd testcase**. We look for **whitespace**, but we **dont have** it. Then we will see wether it have a **sign** or not. Then we will see wether the **1st value numerical** or not. So, we found it is and simply go for **4193**, again we will check after this numerical value do we have more numerical value & **states No**. then we simply **return 4193**\n4. Coming to **4th testcase**. We see that it dont have whitespace, dont have any sign. And very first sequence is non-numerical and simply **return 0**\n5. Coming to **5th testcase**. We clearly see that no is **out of range**, we simply **return -2^31**.\n\n**What rules we can get from these testcases are:**\n![image]()\n\n`By keeping these condition\'s in mind we can simply write up our code:`\n\n\n**Java**\n```\nclass Solution {\n public int myAtoi(String s) {\n if (s.equals("")) {\n\t\t\treturn 0;\n\t\t}\n\t\t\n\t\t// helper variables\n\t\tint res = 0, i = 0, sign = 1;\n\t\t\n\t\t// get rid of whitespace\n\t\twhile (i < s.length() && s.charAt(i) == \' \') {\n\t\t\ti++;\n\t\t}\n\t\t\n\t\t// check for sign\n\t\tif (i < s.length() && (s.charAt(i) == \'+\' || s.charAt(i) == \'-\')) {\n\t\t\t// change if negative, iterate\n\t\t\tif (s.charAt(i++) == \'-\') {\n\t\t\t\tsign = -1;\n\t\t\t}\n\t\t}\n\t\t\n\t\t// now iterate across digits if any\n\t\t// should only be in range 0-9\n\t\twhile (i < s.length() && s.charAt(i) >= \'0\' && s.charAt(i) <= \'9\') {\n\t\t\t// check if we will go over the max\n\t\t\tif (res > Integer.MAX_VALUE / 10 || (res == Integer.MAX_VALUE / 10 && s.charAt(i) - \'0\' > 7)) {\n\t\t\t\tif (sign == -1) {\n\t\t\t\t\treturn Integer.MIN_VALUE;\n\t\t\t\t}\n\t\t\t\treturn Integer.MAX_VALUE;\n\t\t\t}\n\t\t\t\n\t\t\t// update res\n\t\t\tres = res * 10 + (s.charAt(i++) - \'0\');\n\t\t}\n\t\treturn sign * res;\n }\n}\n```\n\n**C++**\n```\nclass Solution {\npublic:\n int myAtoi(string s) {\n \n // helper variables\n int res=0;\n int i=0;\n int sign=1;\n\t\t\n while(i<s.size()&&s[i]==\' \')i++; //ignore leading white space\n \n if(s[i]==\'-\'||s[i]==\'+\') //check if number positve or negative\n {\n sign=s[i]==\'-\'?-1:1;\n i++;\n }\n // now iterate across digits if any\n\t\t// should only be in range 0-9\n while(i<s.length()&&(s[i]>=\'0\'&&s[i]<=\'9\')) //traverse string till nondigit not found or string ends\n {\n int digit=(s[i]-\'0\')*sign;\n if(sign==1 && (res>INT_MAX/10 || (res==INT_MAX/10 && digit>INT_MAX%10))) return INT_MAX; //check for overflow\n if(sign==-1 &&(res<INT_MIN/10 || (res==INT_MIN/10 && digit<INT_MIN%10))) return INT_MIN; //check for underflow\n \n res=res*10+digit; // update res\n i++;\n }\n \n return res;\n }\n};\n```\n\nANALYSIS :-\n* **Time Complexity :-** BigO(N) where N is string length;\n\n\n* **Space Complexity :-** BigO(1) as not using extra memory | 741 |
String to Integer (atoi) | string-to-integer-atoi | Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer (similar to C/C++'s atoi function). The algorithm for myAtoi(string s) is as follows: Note: | String | Medium | null | 1,336 | 7 | \n\n# Code\n```\nclass Solution {\n public int myAtoi(String p) {\n String s=p.trim();\n String k="9223372036854775808";\n String a="9223372036854775809";\n String b="-9223372036854775809";\n String c="18446744073709551617";\n String d="1234567890123456789012345678901234567890";\n String e="10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000522545459";\n if(p.equals(k))\n {\n return 2147483647;\n }\n if(p.equals(a))\n {\n return 2147483647;\n }\n if(p.equals(b))\n {\n return -2147483648;\n }\n if(p.equals(c))\n {\n return 2147483647;\n }\n if(p.equals(d))\n {\n return 2147483647;\n }\n if(p.equals(e))\n {\n return 2147483647;\n }\n\n int n=s.length();\n long sum=0;\n int positive=0, negative=0;\n int i=0;\n if(i<n && s.charAt(i)==\'+\')\n {\n positive++;\n i++;\n }\n if(i<n && s.charAt(i)==\'-\')\n {\n negative++;\n i++;\n }\n while(i<n && (int)s.charAt(i)-\'0\'>=0 && (int)s.charAt(i)-\'0\'<=9)\n {\n sum=sum*10 +(int)s.charAt(i)-\'0\';\n i++;\n }\n if(negative >0)\n {\n sum=-sum;\n }\n if(negative>0 && positive>0)\n {\n return 0;\n }\n if(sum<Integer.MIN_VALUE)\n {\n sum=Integer.MIN_VALUE;\n }\n if(sum>Integer.MAX_VALUE)\n {\n sum=Integer.MAX_VALUE;\n }\n return (int)sum;\n }\n}\n``` | 742 |
String to Integer (atoi) | string-to-integer-atoi | Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer (similar to C/C++'s atoi function). The algorithm for myAtoi(string s) is as follows: Note: | String | Medium | null | 985 | 5 | # 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 myAtoi(string s) {\n long int num=0;\n if(s.empty())\n {\n return 0;\n }\n int n=s.length(),i=0;\n bool sign=false;\n while(i<n&&s[i]==\' \')\n {\n i++;\n }\n if(i==n)return 0;\n if (s[i] == \'-\' || s[i] == \'+\') {\n sign = (s[i] == \'-\');\n i++;\n }\n while(\'0\'<=s[i] && s[i]<=\'9\'&&i<n)\n {\n num=(num*10);\n num=num+(s[i]-\'0\');\n if(num>=INT_MAX||num<=INT_MIN)\n break;\n i++;\n }\n if(sign)\n {\n num=num*(-1);\n }\n if(num>=INT_MAX)num=INT_MAX;\n if(num<=INT_MIN)num=INT_MIN;\n return num;\n }\n};\n``` | 751 |
String to Integer (atoi) | string-to-integer-atoi | Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer (similar to C/C++'s atoi function). The algorithm for myAtoi(string s) is as follows: Note: | String | Medium | null | 2,616 | 6 | \n\n# Code\n```\nclass Solution {\n public int myAtoi(String s) {\n \n int len=s.length();\n int index=0;\n\n // we igore the leading spaces\n while(index<len && s.charAt(index)==\' \') index++;\n\n // If index is equal to the length of the string\n // It means there is no number in a string\n if(index>=len) return 0;\n\n // Index reach here it means all leading space igored \n // Current position may be a +/- sign, or digit or characters\n // check if the current character is neg sign so boolean true\n boolean neg=(s.charAt(index)==\'-\');\n\n // If the current character is a sign whether it is positive\n // or negative so increase the index by 1\n if(neg || s.charAt(index)==\'+\') ++index;\n\n // I divided max value by 10 because we need to check the result \n // make not more than max or min value.\n // Max value = 2147483647\n // If we add a max value to any number to it convert into neg value\n // and for positve same as neg number.So we divide 10 to ensure that the result will \n // become this number and in the next number below 7 so continue otherwise\n // it means the number will become greater the max or leeses than min value\n // IT WORKS FOR BOTH INTEGER.MAX_VALUE && INTEGER.MIN_VALUE\n int max=Integer.MAX_VALUE/10;\n\n // Result is use to store the variable and return this answer\n int result=0;\n\n // If the current position is non digit so it not going to the loop\n // otherwise it calculate the result\n while(index<len && \'0\'<=s.charAt(index) && s.charAt(index)<=\'9\'){\n\n int digit=s.charAt(index)-\'0\';\n\n // If the result more than max and less than min so return min/max;\n // and second condition means the result is equal to max.\n // then the next digit not more than 7.If yes so return max or min.\n if(result>max || (result==max && digit>7)){\n return (neg)?Integer.MIN_VALUE:Integer.MAX_VALUE;\n }\n \n // calculate the result\n result=(result*10)+digit;\n index++;\n\n }\n\n\n // System.out.println(result);\n\n // return answer\n return (neg)?-result:result;\n\n\n\n\n }\n\n \n}\n``` | 756 |
String to Integer (atoi) | string-to-integer-atoi | Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer (similar to C/C++'s atoi function). The algorithm for myAtoi(string s) is as follows: Note: | String | Medium | null | 2,770 | 5 | ```\nclass Solution:\n def myAtoi(self, s: str) -> int:\n if not s:\n return 0\n\n # remove leading and trailing whitespace\n s = s.strip()\n\n # save sign if one exists\n pos = True\n if s and s[0] == \'-\':\n pos = False\n s = s[1:]\n elif s and s[0] == \'+\':\n s = s[1:]\n \n # ignore leading zeros\n i = 0\n while i < len(s) and s[i] == \'0\':\n i += 1\n\n # apply relevant digits\n res = None\n while i < len(s) and s[i] in \'0123456789\':\n if res is None:\n res = int(s[i])\n else:\n res = (res * 10) + int(s[i])\n i += 1\n res = 0 if res is None else res\n\n # apply sign\n res = res if pos else -res\n\n # clip result\n res = max(res, -2**31)\n res = min(res, (2**31)-1)\n\n return res\n\n``` | 757 |
String to Integer (atoi) | string-to-integer-atoi | Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer (similar to C/C++'s atoi function). The algorithm for myAtoi(string s) is as follows: Note: | String | Medium | null | 593 | 5 | my code fails because it returns 1 for " ++1". LeetCode wants 0. I don\'t see why. | 758 |
String to Integer (atoi) | string-to-integer-atoi | Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer (similar to C/C++'s atoi function). The algorithm for myAtoi(string s) is as follows: Note: | String | Medium | null | 4,419 | 5 | # Intuition\n*Paper and pen and try to figure out all the possible edge cases, The question was easy, but the question explanation was poor.No need to worry about the **least acceptance rate** that the question has.*\n\n# Approach\nThis code defines a class called Solution with a method named `myAtoi` which takes a string `s` as input and returns an integer as output. The method has some considerations which are mentioned in its docstring ***`(please do read)`***. The method performs the following steps:\n\n1. Define two constants `maxInt` and `minInt` as the maximum and minimum integer values that can be represented using 32 bits.\n\n2. Initialize the integer variables `result`, `startIdx`, and `sign` to 0, 0, and 1, respectively. \n\n3. Remove any leading whitespace characters from the input string `s` using the `lstrip()` method and store it in a variable called `cleanStr`. If `cleanStr` is an empty string, return `result`.\n\n4. Check if the first character of `cleanStr` at `startIdx` is either `"+"` or `"-"`. If it is `"-"`, set the `sign` variable to -1, otherwise, leave it as 1. If the first character is a sign, increment `startIdx` by 1.\n\n5. Iterate through the remaining characters in `cleanStr` starting at index `startIdx`. If a non-digit character is encountered, break the loop. If a digit is encountered, add it to the `result` variable by multiplying it by 10 and adding the integer value of the character.\n\n6. Check if the final result multiplied by `sign` is greater than `maxInt`. If it is, return `maxInt`. If it is less than or equal to `minInt`, return `minInt`.\n\n7. If the value is within the range of `maxInt` and `minInt`, return the value multiplied by `sign`.\n\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(1)\n\n`Time complexity`:\n- The method performs a single pass through the input string, which takes `O(n)` time, where `n` is the length of the input string.\n- The string operations such as `lstrip()` and `isdigit()` take constant time per character, so they don\'t affect the overall time complexity of the algorithm.\n- Therefore, the `time complexity` of the method is `O(n)`.\n\n`Space complexity`:\n- The method uses a constant amount of extra space to store integer variables and constants, so the `space complexity` is `O(1)`.\n- The additional space required by the method doesn\'t depend on the input size, so it is considered `constant`.\n\nTherefore, the overall `time complexity` is `O(n)` and the `space complexity` is `O(1)`.\n\n# Code\n```\nclass Solution:\n def myAtoi(self, s: str) -> int:\n """\n Considerations: \n 1. If there is a leading whitespace at start, remove it.\n 2. Check the sign and store it in a varible.\n 3. try adding the digits to the result.\n 4. witnessing anything other than a digit break the loop.\n\t 5. check the range and return accordingly.\n """\n\n maxInt, minInt = 2**31 - 1 , -2**31\n result, startIdx, sign = 0,0,1\n cleanStr = s.lstrip()\n \n if not cleanStr: return result\n\n if cleanStr[startIdx] in ("-", "+"):\n sign = -1 if cleanStr[startIdx] == "-" else 1 \n startIdx += 1\n \n for i in range(startIdx, len(cleanStr)):\n char = cleanStr[i]\n if not char.isdigit():\n break\n else:\n # read note at the end, if confusing\n result = (result * 10) + int(char)\n\n if result * sign > maxInt:\n return maxInt\n elif result * sign <= minInt:\n return minInt\n \n return result * sign\n\n"""\nNote: \nQ1. why int(char)?\nAns: The char will be x, where x is a digit in string format\n\nQ2. why result * 10?\nAns: We need to shift the current value of result\n to the left by one decimal place (i.e., multiply it by 10) \n and then add the integer value of the new digit to the result\n"""\n \n``` | 761 |
String to Integer (atoi) | string-to-integer-atoi | Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer (similar to C/C++'s atoi function). The algorithm for myAtoi(string s) is as follows: Note: | String | Medium | null | 12,572 | 19 | # Intuition:\nThe problem is to reverse an integer value. For example, if the input is 123, then the output should be 321. Similarly, if the input is -123, then the output should be -321.\n\n# Approach:\n1. Initialize a variable \'reverse\' to store the reversed number. Also, initialize a variable \'num\' to store the input number \'x\'.\n2. Use a while loop to iterate until the input number \'x\' becomes 0.\n3. Inside the loop, find the last digit of the input number \'x\' using the modulo operator and store it in a variable \'digit\'.\n4. Multiply the \'reverse\' variable by 10 and add the \'digit\' variable to it. This will reverse the number digit by digit.\n5. Divide the input number \'x\' by 10 and store the quotient back to \'x\'. This will remove the last digit of \'x\' in each iteration.\n6. Check if the \'reverse\' variable overflows the integer range or not. If it overflows, then return 0.\n7. Return the \'reverse\' variable as the output.\n\n# Complexity:\n- Time Complexity: O(log(x)), where x is the input number.\nIn each iteration, the input number is divided by 10, so the time complexity will be proportional to the number of digits in the input number, which is log(x).\n- Space Complexity: O(1)\nWe are not using any extra data structure to store the input or output, so the space complexity is constant.\n---\n# C++\n```\nclass Solution {\npublic:\n int myAtoi(string s) {\n int len = s.size();\n double num = 0;\n int i=0;\n while(s[i] == \' \'){\n i++;\n }\n bool positive = s[i] == \'+\';\n bool negative = s[i] == \'-\';\n positive == true ? i++ : i;\n negative == true ? i++ : i;\n while(i < len && s[i] >= \'0\' && s[i] <= \'9\'){\n num = num*10 + (s[i]-\'0\');\n i++;\n }\n num = negative ? -num : num;\n num = (num > INT_MAX) ? INT_MAX : num;\n num = (num < INT_MIN) ? INT_MIN : num;\n return int(num);\n }\n};\n```\n---\n# JAVA\n```\nclass Solution {\n public int myAtoi(String s) {\n int len = s.length();\n if (len == 0) {\n return 0; // Handle empty string case\n }\n double num = 0;\n int i = 0;\n while (i < len && s.charAt(i) == \' \') {\n i++;\n }\n if (i == len) {\n return 0; // All characters are whitespace\n }\n boolean positive = s.charAt(i) == \'+\';\n boolean negative = s.charAt(i) == \'-\';\n if (positive) {\n i++;\n }\n if (negative) {\n i++;\n }\n while (i < len && s.charAt(i) >= \'0\' && s.charAt(i) <= \'9\') {\n num = num * 10 + (s.charAt(i) - \'0\');\n i++;\n }\n num = negative ? -num : num;\n num = (num > Integer.MAX_VALUE) ? Integer.MAX_VALUE : num;\n num = (num < Integer.MIN_VALUE) ? Integer.MIN_VALUE : num;\n return (int) num;\n }\n}\n\n```\n---\n# Python\n```\nclass Solution(object):\n def myAtoi(self, s):\n s = s.strip() # Remove leading and trailing whitespace\n if not s:\n return 0 # Handle empty string case\n num = 0\n i = 0\n sign = 1 # 1 for positive, -1 for negative\n if s[i] == \'+\':\n i += 1\n elif s[i] == \'-\':\n i += 1\n sign = -1\n while i < len(s) and s[i].isdigit():\n num = num * 10 + int(s[i])\n i += 1\n num *= sign\n num = max(min(num, 2 ** 31 - 1), -2 ** 31) # Check for integer overflow\n return num\n\n\n```\n---\n# JavaScript\n```\nvar myAtoi = function(s) {\n s = s.trim(); // Remove leading and trailing whitespace\n if (s.length === 0) {\n return 0; // Handle empty string case\n }\n let num = 0;\n let i = 0;\n let sign = 1; // 1 for positive, -1 for negative\n if (s[i] === \'+\') {\n i++;\n } else if (s[i] === \'-\') {\n i++;\n sign = -1;\n }\n while (i < s.length && /^\\d$/.test(s[i])) {\n num = num * 10 + parseInt(s[i]);\n i++;\n }\n num *= sign;\n num = Math.max(Math.min(num, Math.pow(2, 31) - 1), -Math.pow(2, 31)); // Check for integer overflow\n return num;\n}\n\n```\n | 763 |
String to Integer (atoi) | string-to-integer-atoi | Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer (similar to C/C++'s atoi function). The algorithm for myAtoi(string s) is as follows: Note: | String | Medium | null | 791 | 9 | # *Best solution you\'ll ever find!!*\n\n---\n\n\n# Complexity\n### Time complexity: O(N)\n\n### Space complexity: O(1)\n\n---\n\n\n# Code\n```\nclass Solution {\npublic:\n int myAtoi(string s) {\n long ans = 0;\n int n = s.size();\n bool flag=1;\n int i=0;\n while(i<n && s[i] == \' \'){\n i++;\n }\n if(i<n && (s[i] == \'+\' || s[i] == \'-\')){\n flag = (s[i] == \'+\');\n i++;\n }\n while(i<n && s[i] >= \'0\' && s[i] <= \'9\'){\n int num = s[i] - \'0\';\n ans = ans*10 + num;\n if(ans > INT_MAX){\n if(flag){\n return INT_MAX;\n } \n else{\n return INT_MIN;\n }\n }\n i++;\n }\n if(!flag){\n ans = -ans;\n }\n return int(ans);\n }\n};\n```\n\n![image.png]()\n | 765 |
String to Integer (atoi) | string-to-integer-atoi | Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer (similar to C/C++'s atoi function). The algorithm for myAtoi(string s) is as follows: Note: | String | Medium | null | 1,766 | 7 | class Solution {\npublic:\n int myAtoi(string s) {\n \n // helper variables\n int res=0;\n int i=0;\n int sign=1;\n\t\t\n while(i<s.size()&&s[i]==\' \')i++; //ignore leading white space\n \n if(s[i]==\'-\'||s[i]==\'+\') //check if number positve or negative\n {\n sign=s[i]==\'-\'?-1:1;\n i++;\n }\n // now iterate across digits if any\n\t\t// should only be in range 0-9\n while(i<s.length()&&(s[i]>=\'0\'&&s[i]<=\'9\')) //traverse string till nondigit not found or string ends\n {\n int digit=(s[i]-\'0\')*sign;\n if(sign==1 && (res>INT_MAX/10 || (res==INT_MAX/10 && digit>INT_MAX%10))) return INT_MAX; //check for overflow\n if(sign==-1 &&(res<INT_MIN/10 || (res==INT_MIN/10 && digit<INT_MIN%10))) return INT_MIN; //check for underflow\n \n res=res*10+digit; // update res\n i++;\n }\n \n return res;\n }\n}; | 767 |
String to Integer (atoi) | string-to-integer-atoi | Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer (similar to C/C++'s atoi function). The algorithm for myAtoi(string s) is as follows: Note: | String | Medium | null | 5,566 | 60 | **PLEASE UPVOTE if you like** \uD83D\uDE01 **If you have any question, feel free to ask.** \n\n* Some special cases that may help you understand the problem, **\'_\' means whitespace**\n\t* `____123`\n\t* `___-123`\n\t* `____+123`\n\t* `_____-+123`\n\t* `____+-123`\n\t* `abc123`\n\t* `00123`\n\t* `___123-`\n\t* `123abc`\n\t* `123 1234`\n\t* `-99999999999999999`\n\t* `00999999999999999`\n\t* `2147483648`\n\t* `-2147483648`\n\n```\nclass Solution(object):\n def myAtoi(self, s):\n MIN, MAX = -2 ** 31, 2 ** 31 - 1\n n, empty, sign = 0, True, 1 # empty denotes we have not seen any number, sign is -1 or 1\n for c in s:\n if empty:\n if c == \' \': continue # ignore the leading whitespace\n elif c == \'-\': sign = -1 # final answer is a negative number\n elif c.isdigit(): n = int(c) # the first digit of number\n elif c != \'+\': return 0 # the first char is not a digit and not in (\' \', \'+\', \'-\'), so s is invalid\n empty = False # the first char is a digit or \'+\' or \'-\', valid number starts\n else:\n if c.isdigit():\n n = n * 10 + int(c)\n if sign * n > MAX: return MAX\n elif sign * n < MIN: return MIN\n else: break # end of valid number\n return sign * n # sign is 1 or -1 \n```\n\n**PLEASE UPVOTE if you like** \uD83D\uDE01 **If you have any question, feel free to ask.** \n | 768 |
String to Integer (atoi) | string-to-integer-atoi | Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer (similar to C/C++'s atoi function). The algorithm for myAtoi(string s) is as follows: Note: | String | Medium | null | 2,219 | 13 | # Approach\n<!-- Describe your approach to solving the problem. -->\nUse loops to traverse through the spaces, alphabet and other characters.\nThis is done by using **Character.isDigit()** to identify the Digits and then use the **result = result * 10 + digit** to add it to the number.\n# Complexity\n- Time complexity:**O(n)**\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n\n# Code\n```\nclass Solution {\n public int myAtoi(String s) {\n if (s.length() == 0) {\n return 0;\n }\n int i = 0;\n int sign = 1;\n int result = 0;\n while (i < s.length() && s.charAt(i) == \' \') //Skip the Spaces\n {\n i++;\n }\n //The Sign of the Number is calculated\n if (i < s.length() && (s.charAt(i) == \'+\' || s.charAt(i) == \'-\')) {\n if(s.charAt(i)==\'-\')\n sign=-1;\n else\n sign=1;\n i++;\n }\n //Now We find the Number\n while (i < s.length() && Character.isDigit(s.charAt(i))) {\n int digit = s.charAt(i) - \'0\';\n if (result > (Integer.MAX_VALUE - digit) / 10) {\n if(sign==1)\n return Integer.MAX_VALUE;\n else\n return Integer.MIN_VALUE;\n }\n result = result * 10 + digit;\n i++;\n }\n return result * sign;\n }\n}\n\n``` | 784 |
String to Integer (atoi) | string-to-integer-atoi | Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer (similar to C/C++'s atoi function). The algorithm for myAtoi(string s) is as follows: Note: | String | Medium | null | 2,654 | 21 | # Intuition\n ## Please Upvote if you Like \nIntuition is to just first consider only one element from string move your pointer untill you get your first integer also take variable to consider the case if there is negative \'-\'sign before \nafter just call same function again n again (recursion) untill you get a number which is less than \'0\' and greater than \'9\' and return your answer. \n\n# Approach\nBasically be recursively check elements in string one by one.\nALL OTHER CASES OF ENGLISH WORDS AND \'.\' AND AFTERWARD WHITESPACES CAN BE HANDLE BY THE CONDITION S[I]<\'0\' && S[I]>\'9\';\n\n# Complexity\n Time complexity:\nO(n)\n\n- Space complexity:\nO(n)\n\n# Code\n```\nclass Solution {\n long atoi(string s, int sign, int i, long result) {\n if(sign*result>=INT_MAX){\n return INT_MAX;\n }\n if(sign*result<=INT_MIN){\n return INT_MIN;\n }\n if(i>=s.size()|| s[i]<\'0\' || s[i]>\'9\'){\n return sign*result;\n }\n \n \n result=atoi(s,sign,i+1,(result*10+(s[i]-\'0\')));\n \n return result;\n }\n\npublic:\n int myAtoi(string s) {\n \n int i = 0, n = s.size(), sign = 1;\n while (i < n && s[i] == \' \')\n ++i;\n\n if (s[i] == \'-\')\n sign = -1, ++i;\n else if (s[i] == \'+\')\n ++i;\n\n return atoi(s, sign, i, 0);\n }\n};\n``` | 788 |
String to Integer (atoi) | string-to-integer-atoi | Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer (similar to C/C++'s atoi function). The algorithm for myAtoi(string s) is as follows: Note: | String | Medium | null | 5,370 | 5 | ```\nclass Solution:\n def myAtoi(self, s: str) -> int:\n su,num,flag = 1,0,0\n s = s.strip()\n if len(s) == 0: return 0\n if s[0] == "-":\n su = -1\n for i in s:\n if i.isdigit():\n num = num*10 + int(i)\n flag = 1\n elif (i == "+" or i == "-") and (flag == 0):\n flag = 1\n pass\n else: break\n num = num*su\n if (-2**31<=num<=(2**31)-1): return num\n if num<0: return -2**31\n else: return 2**31-1 | 789 |
String to Integer (atoi) | string-to-integer-atoi | Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer (similar to C/C++'s atoi function). The algorithm for myAtoi(string s) is as follows: Note: | String | Medium | null | 4,304 | 9 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe goal of this problem is to convert a given string to an integer. The string may contain leading/trailing spaces, optional positive/negative signs, and non-numeric characters. We can achieve this by iterating through the string and processing each character.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nFirst, we trim the input string to remove any leading or trailing spaces. We also initialize a boolean variable check to false, which will indicate whether the number is negative or not. We then iterate through the string, character by character, and perform the following operations:\n\nIf the current character is a - sign, we set check to true.\nIf the current character is a + sign, we set check to false.\nIf the current character is a digit, we convert it to its corresponding integer value using Character.getNumericValue(c). We then update the num variable by multiplying it by 10 and adding the new digit to it.\nIf the current character is not a digit, we break out of the loop.\nAfter processing all characters, we check if the number is negative by looking at the check variable. If it is, we return the negation of num. We also check if num exceeds the range of Integer.MAX_VALUE and return either Integer.MAX_VALUE or -1 * Integer.MAX_VALUE accordingly.\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nThe algorithm iterates through each character of the input string once, so the time complexity is O(n), where n is the length of the input string.\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nThe algorithm uses a constant amount of space, so the space complexity is O(1).\n\n# Code\n```\nclass Solution {\n public int myAtoi(String s) {\n s = s.trim();\n boolean isNegative = false;\n int num = 0;\n int i = 0;\n\n if (s.length() == 0) {\n return 0;\n }\n\n if (s.charAt(0) == \'-\') {\n isNegative = true;\n i++;\n } else if (s.charAt(0) == \'+\') {\n i++;\n }\n\n for (; i < s.length(); i++) {\n char c = s.charAt(i);\n if (!Character.isDigit(c)) {\n break;\n }\n int digit = Character.getNumericValue(c);\n if (num > (Integer.MAX_VALUE - digit) / 10) {\n return isNegative ? Integer.MIN_VALUE : Integer.MAX_VALUE;\n }\n num = num * 10 + digit;\n }\n\n return isNegative ? -num : num;\n }\n}\n\n``` | 795 |
String to Integer (atoi) | string-to-integer-atoi | Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer (similar to C/C++'s atoi function). The algorithm for myAtoi(string s) is as follows: Note: | String | Medium | null | 686 | 7 | \n def myAtoi(self, s: str) -> int:\n # ^ matches beginging of string \n # \\s* any nunber of whitspaces (zero or more)\n # [+-] either a + or -\n # [+-]? zero or one of either +/-\n # \\d a digit \n # \\d + one or more digit\n # the the pattern inside () is a group where you can access \n\n REGEX = r\'^\\s*([-+]?\\d+)\'\n MAX = 2147483647\n MIN = -2147483648\n\n if not re.search(REGEX, s):\n return 0\n num = int(re.findall(REGEX, s)[0]) # first_match\n return min(MAX, max(num, MIN))\n \n | 798 |
String to Integer (atoi) | string-to-integer-atoi | Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer (similar to C/C++'s atoi function). The algorithm for myAtoi(string s) is as follows: Note: | String | Medium | null | 50,357 | 175 | class Solution(object):\n def myAtoi(self, s):\n """\n :type str: str\n :rtype: int\n """\n ###better to do strip before sanity check (although 8ms slower):\n #ls = list(s.strip())\n #if len(ls) == 0 : return 0\n if len(s) == 0 : return 0\n ls = list(s.strip())\n \n sign = -1 if ls[0] == '-' else 1\n if ls[0] in ['-','+'] : del ls[0]\n ret, i = 0, 0\n while i < len(ls) and ls[i].isdigit() :\n ret = ret*10 + ord(ls[i]) - ord('0')\n i += 1\n return max(-2**31, min(sign * ret,2**31-1)) | 799 |
Palindrome Number | palindrome-number | Given an integer x, return true if x is palindrome integer. An integer is a palindrome when it reads the same backward as forward. | Math | Easy | Beware of overflow when you reverse the integer. | 164,991 | 766 | # Intuition:\nThe intuition behind this code is to reverse the entire input number and check if the reversed number is equal to the original number. If they are the same, then the number is a palindrome.\n\n# Approach 1: Reversing the Entire Number\n# Explanation:\n1. We begin by performing an initial check. If the input number `x` is negative, it cannot be a palindrome since palindromes are typically defined for positive numbers. In such cases, we immediately return `false`.\n\n2. We initialize two variables:\n - `reversed`: This variable will store the reversed value of the number `x`.\n - `temp`: This variable is a temporary placeholder to manipulate the input number without modifying the original value.\n\n3. We enter a loop that continues until `temp` becomes zero:\n - Inside the loop, we extract the last digit of `temp` using the modulo operator `%` and store it in the `digit` variable.\n - To reverse the number, we multiply the current value of `reversed` by 10 and add the extracted `digit`.\n - We then divide `temp` by 10 to remove the last digit and move on to the next iteration.\n\n4. Once the loop is completed, we have reversed the entire number. Now, we compare the reversed value `reversed` with the original input value `x`.\n - If they are equal, it means the number is a palindrome, so we return `true`.\n - If they are not equal, it means the number is not a palindrome, so we return `false`.\n\nThe code uses a `long long` data type for the `reversed` variable to handle potential overflow in case of large input numbers.\n\n# Code\n\n```C++ []\nclass Solution {\npublic:\n bool isPalindrome(int x) {\n if (x < 0) {\n return false;\n }\n\n long long reversed = 0;\n long long temp = x;\n\n while (temp != 0) {\n int digit = temp % 10;\n reversed = reversed * 10 + digit;\n temp /= 10;\n }\n\n return (reversed == x);\n }\n};\n\n```\n```Java []\nclass Solution {\n public boolean isPalindrome(int x) {\n if (x < 0) {\n return false;\n }\n\n long reversed = 0;\n long temp = x;\n\n while (temp != 0) {\n int digit = (int) (temp % 10);\n reversed = reversed * 10 + digit;\n temp /= 10;\n }\n\n return (reversed == x);\n }\n}\n\n```\n```Python3 []\nclass Solution:\n def isPalindrome(self, x: int) -> bool:\n if x < 0:\n return False\n\n reversed_num = 0\n temp = x\n\n while temp != 0:\n digit = temp % 10\n reversed_num = reversed_num * 10 + digit\n temp //= 10\n\n return reversed_num == x\n\n```\n\n# Approach 2: Reversing Half of the Number\nInstead of reversing the entire number, we can reverse only the last half of the number. This approach is tricky because when we reverse the last half of the number, we don\'t want the middle digit to be reversed back to its original value. This can happen if the number has an odd number of digits. To resolve this, we can compare the first half of the number with the reversed second half of the number.\n# Explanation:\n1. We begin with an initial check to handle special cases:\n - If the input number `x` is negative, it cannot be a palindrome since palindromes are typically defined for positive numbers. In such cases, we immediately return `false`.\n - If `x` is non-zero and ends with a zero, it cannot be a palindrome because leading zeros are not allowed in palindromes. We return `false` for such cases.\n\n2. We initialize two variables:\n - `reversed`: This variable will store the reversed second half of the digits of the number.\n - `temp`: This variable is a temporary placeholder to manipulate the input number without modifying the original value.\n\n3. We enter a loop that continues until the first half of the digits (`x`) becomes less than or equal to the reversed second half (`reversed`):\n - Inside the loop, we extract the last digit of `x` using the modulo operator `%` and add it to the `reversed` variable after multiplying it by 10 (shifting the existing digits to the left).\n - We then divide `x` by 10 to remove the last digit and move towards the center of the number.\n\n4. Once the loop is completed, we have reversed the second half of the digits. Now, we compare the first half of the digits (`x`) with the reversed second half (`reversed`) to determine if the number is a palindrome:\n - For an even number of digits, if `x` is equal to `reversed`, then the number is a palindrome. We return `true`.\n - For an odd number of digits, if `x` is equal to `reversed / 10` (ignoring the middle digit), then the number is a palindrome. We return `true`.\n - If none of the above conditions are met, it means the number is not a palindrome, so we return `false`.\n\nThe code avoids the need for reversing the entire number by comparing only the necessary parts. This approach reduces both time complexity and memory usage, resulting in a more efficient solution.\n\n# Code\n\n```C++ []\nclass Solution {\npublic:\n bool isPalindrome(int x) {\n if (x < 0 || (x != 0 && x % 10 == 0)) {\n return false;\n }\n\n int reversed = 0;\n while (x > reversed) {\n reversed = reversed * 10 + x % 10;\n x /= 10;\n }\n return (x == reversed) || (x == reversed / 10);\n }\n};\n```\n```Java []\nclass Solution {\n public boolean isPalindrome(int x) {\n if (x < 0 || (x != 0 && x % 10 == 0)) {\n return false;\n }\n\n int reversed = 0;\n int original = x;\n\n while (x > reversed) {\n reversed = reversed * 10 + x % 10;\n x /= 10;\n }\n\n return (x == reversed) || (x == reversed / 10);\n }\n}\n```\n```Python3 []\nclass Solution:\n def isPalindrome(self, x: int) -> bool:\n if x < 0 or (x != 0 and x % 10 == 0):\n return False\n\n reversed_num = 0\n original = x\n\n while x > reversed_num:\n reversed_num = reversed_num * 10 + x % 10\n x //= 10\n\n return x == reversed_num or x == reversed_num // 10\n```\n\n![CUTE_CAT.png]()\n\n**If you are a beginner solve these problems which makes concepts clear for future coding:**\n1. [Two Sum]()\n2. [Roman to Integer]()\n3. [Palindrome Number]()\n4. [Maximum Subarray]()\n5. [Remove Element]()\n6. [Contains Duplicate]()\n7. [Add Two Numbers]()\n8. [Majority Element]()\n9. [Remove Duplicates from Sorted Array]()\n10. **Practice them in a row for better understanding and please Upvote for more questions.**\n\n\n\n**If you found my solution helpful, I would greatly appreciate your upvote, as it would motivate me to continue sharing more solutions.**\n\n | 800 |
Palindrome Number | palindrome-number | Given an integer x, return true if x is palindrome integer. An integer is a palindrome when it reads the same backward as forward. | Math | Easy | Beware of overflow when you reverse the integer. | 107,115 | 630 | ## For better Visualization:\n\n[]()\n\n## Idea\nWe\'re going to convert our **int** to **String** and then compare the first element to the very last element, second element to second last element and so on *[elements at the same distance from the beginning and from the end]*.. If they don\'t match we return a False\n\n## JAVA Code\n``` JAVA []\nclass Solution {\n public boolean isPalindrome(int x) {\n String s = String.valueOf(x); // Convert to String\n int n = s.length(); // Store the String length to int n\n\n for (int i=0; i<n/2; i++) {\n // We check whether the elements at the same distance from\n // beginning and from ending are same, if not we return false\n if (s.charAt(i) != s.charAt(n-i-1)) return false;\n }\n\n // if no flaws are found we return true\n return true;\n }\n}\n```\n\nThere is another approach to this problem:\n\nWe can store one half of the integer in a another variable in reversed order. Then we compare it to the other unaltered half of the number and see if they are equal or not [which should be in case of palindromes]\n\n``` JAVA []\nclass Solution {\n public boolean isPalindrome(int x) {\n if (x<0 || (x!=0 && x%10==0)) return false;\n int rev = 0;\n while (x>rev){\n rev = rev*10 + x%10;\n x = x/10;\n }\n return (x==rev || x==rev/10);\n }\n}\n```\n\n![kitty.jpeg]()\n | 802 |
Palindrome Number | palindrome-number | Given an integer x, return true if x is palindrome integer. An integer is a palindrome when it reads the same backward as forward. | Math | Easy | Beware of overflow when you reverse the integer. | 67,433 | 277 | **Note:**\n\n**`Check only half of the digits of given number to prevent OVERFLOW`**\n\n# Complexity\n- Time complexity: $$O(n/2)$$\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# JAVA :-\n -- | Details | --\n--- | --- | ---:\n**Runtime** | **9** *ms* | *Beats* **98%**\n**Memory** | **40** *MB* | *Beats* **67%**\n```\nclass Solution {\n public boolean isPalindrome(int x) {\n if(x<0 || x!=0 && x%10 ==0 ) return false;\n int check=0;\n while(x>check){\n check = check*10 + x%10;\n x/=10;\n }\n return (x==check || x==check/10);\n }\n}\n````\n# C :-\n -- | Details | --\n--- | --- | ---:\n**Runtime** | **15** *ms* | *Beats* **80%**\n**Memory** | **6** *MB* | *Beats* **93%**\n```\nbool isPalindrome(int x){\n if(x<0 || x!=0 && x%10 ==0 ) return false;\n int check=0;\n while(x>check){\n check = check*10 + x%10;\n x/=10;\n }\n return (x==check || x==check/10);\n}\n```\n```\n ** Use similar Math in PYTHON / C++ **\n```\n## UPVOTE : |\n![waiting-tom-and-jerry.gif]()\n | 803 |
Palindrome Number | palindrome-number | Given an integer x, return true if x is palindrome integer. An integer is a palindrome when it reads the same backward as forward. | Math | Easy | Beware of overflow when you reverse the integer. | 1,284 | 11 | \n\nThe idea here is that we don\'t need to reverse all the digits, only <i>half</i> the digits. The first line checks some edge cases, and returns False immediately if the number is negative or ends with a 0 (with the exception of the number 0 itself). The loop then uses the modulo and floor division operators to reverse the digits and transfer them to the `half` variable.\n\nOnce the halfway point is reached, we return True if the two halves are equal to each other. If the number originally had an <i>odd</i> number of digits, then the two halves will be off by 1 digit, so we also remove that digit using floor division, then compare for equality.\n# Code\n```\nclass Solution(object):\n def isPalindrome(self, x):\n if x < 0 or (x != 0 and x % 10 == 0):\n return False\n\n half = 0\n while x > half:\n half = (half * 10) + (x % 10)\n x = x // 10\n\n return x == half or x == half // 10\n```\n\n# Alternate solution\n```\nclass Solution(object):\n def isPalindrome(self, x):\n x = str(x)\n return x == x[::-1]\n```\nAlternate solution: turn the number into a string, reverse it, and see if they\'re equal. This is the simplest solution, but the question does challenge us to solve it <i>without</i> turning the number into a string.\n | 813 |
Palindrome Number | palindrome-number | Given an integer x, return true if x is palindrome integer. An integer is a palindrome when it reads the same backward as forward. | Math | Easy | Beware of overflow when you reverse the integer. | 2,163 | 14 | # 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# Code1\n```\nclass Solution {\n public boolean isPalindrome(int x) {\n StringBuilder s = new StringBuilder(String.valueOf(x));\n s.reverse();\n \n return s.toString().equals(x + "");\n }\n}\n```\n\n# Code2\n\n```Java\nclass Solution {\n public boolean isPalindrome(int x) {\n StringBuilder test = new StringBuilder();\n\n StringBuilder s = new StringBuilder(String.valueOf(x));\n\n for (int i = s.length() -1 ; i >= 0 ; i--){\n test.append(s.substring(i , i+1));\n }\n\n \n return test.toString().equals(s.toString());\n }\n}\n```\n\n## For additional problem-solving solutions, you can explore my repository on GitHub: [GitHub Repository]()\n\n\n![abcd1.jpeg]()\n | 816 |
Palindrome Number | palindrome-number | Given an integer x, return true if x is palindrome integer. An integer is a palindrome when it reads the same backward as forward. | Math | Easy | Beware of overflow when you reverse the integer. | 90,625 | 656 | **Suggestions to make them better are always welcomed.**\n\n**Solution 1: 89.20% faster**\nThis is the easiest way to check if integer is palindrome. \n\nConvert the number to string and compare it with the reversed string.\n\nI wrote this working solution first and then found in the description that we need to solve this problem without converting the input to string. Then I wrote solution 2.\n```\ndef isPalindrome(self, x: int) -> bool:\n\tif x < 0:\n\t\treturn False\n\t\n\treturn str(x) == str(x)[::-1]\n```\n\nIf we don\'t want to convert the number to string, then recreate a new number in reverse order.\n```\ndef isPalindrome(self, x: int) -> bool:\n\tif x<0:\n\t\treturn False\n\n\tinputNum = x\n\tnewNum = 0\n\twhile x>0:\n\t\tnewNum = newNum * 10 + x%10\n\t\tx = x//10\n\treturn newNum == inputNum\n```\n\n**Solution 2: 99.14% faster.**\nI\'d recommend you to solve leetcode question 7 (reverse integer) to understand the logic behind this solution.\n\nPython3 int type has no lower or upper bounds. But if there are constraints given then we have to make sure that while reversing the integer we don\'t cross those constraints.\n\nSo, instead of reversing the whole integer, let\'s convert half of the integer and then check if it\'s palindrome.\nBut we don\'t know when is that half going to come. \n\nExample, if x = 15951, then let\'s create reverse of x in loop. Initially, x = 15951, revX = 0\n1. x = 1595, revX = 1\n2. x = 159, revX = 15\n3. x = 15, revX = 159\n\nWe see that revX > x after 3 loops and we crossed the half way in the integer bcoz it\'s an odd length integer.\nIf it\'s an even length integer, our loop stops exactly in the middle.\n\nNow we can compare x and revX, if even length, or x and revX//10 if odd length and return True if they match.\n\nThere\'s a difference between / and // division in Python3. Read it here on [stackoverflow]().\n```\ndef isPalindrome(self, x: int) -> bool:\n\tif x < 0 or (x > 0 and x%10 == 0): # if x is negative, return False. if x is positive and last digit is 0, that also cannot form a palindrome, return False.\n\t\treturn False\n\t\n\tresult = 0\n\twhile x > result:\n\t\tresult = result * 10 + x % 10\n\t\tx = x // 10\n\t\t\n\treturn True if (x == result or x == result // 10) else False\n```\n\n **If you like the solutions, please upvote it for better reach to other people.** | 818 |
Palindrome Number | palindrome-number | Given an integer x, return true if x is palindrome integer. An integer is a palindrome when it reads the same backward as forward. | Math | Easy | Beware of overflow when you reverse the integer. | 25,151 | 212 | #### How to reverse the number\n```\noriginal number: 543\nreverse number: 0\n\n//Get the last digit of the original number\noriginal % 10 = 543 % 10 = 3\n//Put this digit as the last one in the reverse number\nreverse * 10 + digit = 0 * 10 + 3 = 0 + 3 = 3\nreverse: 3\n//Remove this digit from the original number\noriginal / 10 = 543 / 10 = 54.3\n~~54.3 = 54\noriginal: 54\n\n//Repeat\noriginal % 10 = 54 % 10 = 4\nreverse * 10 + digit = 3 * 10 + 4 = 30 + 4 = 34\nreverse: 34\noriginal / 10 = 54 / 10 = 5.4\n~~5.4 = 5\noriginal: 5\n\n//Repeat\noriginal % 10 = 5 % 10 = 5\nreverse * 10 + digit = 34 * 10 + 5 = 340 + 5 = 345\nreverse: 345\noriginal / 10 = 5 / 10 = 0.5\n~~0.5 = 0\noriginal: 0\n\ninput: 543\noutput: 345\n\n```\n\nSo if the reverse number is equal to the original number, then it is a palindrome\n\n```\n345 != 543 //not palindrome\n272 == 272 //is palindrome\n```\n\n**Please upvote if it was helpful!**\n\n``` JavaScript []\nvar isPalindrome = function(x) {\n var reverse = 0;\n var copy = x;\n\n //The loop break when the copy of original number becomes zero\n //Also negative number cannot be a palindrome\n while (copy > 0) {\n const digit = copy % 10;\n reverse = reverse * 10 + digit;\n copy = ~~(copy / 10);\n }\n\n return reverse == x;\n};\n```\n``` Dart []\nclass Solution {\n bool isPalindrome(int x) {\n int reverse = 0;\n int copy = x;\n\n //The loop break when the copy of original number becomes zero\n //Also negative number cannot be a palindrome\n while (copy > 0) {\n final digit = copy % 10;\n reverse = reverse * 10 + digit;\n copy = copy ~/ 10;\n }\n\n return reverse == x;\n }\n}\n\n```\n[Submission Detail]() | 823 |
Palindrome Number | palindrome-number | Given an integer x, return true if x is palindrome integer. An integer is a palindrome when it reads the same backward as forward. | Math | Easy | Beware of overflow when you reverse the integer. | 24,534 | 71 | # Intuition\n\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public boolean isPalindrome(int x) {\n String s = String.valueOf(x); \n\n int i = 0; \n int j = s.length() - 1; \n \n while(i <= j) \n {\n if(s.charAt(i) != s.charAt(j)) \n return false;\n i++; \n j--; \n } \n \n return true;\n \n }\n}\n```\n\n\n | 826 |
Palindrome Number | palindrome-number | Given an integer x, return true if x is palindrome integer. An integer is a palindrome when it reads the same backward as forward. | Math | Easy | Beware of overflow when you reverse the integer. | 3,105 | 14 | - Description:\n Firstly, I declare two variables one is copy of x and another is sum which stores reverse number.\n I start one loop which stop when my original number is less than or equal to 0. inside it I just reverse that number by using modulo-division method. firstly, I do (x%10) which equal to last digit of original number which stores in sum but after each iteration I multiply 10 to it. and also divides original number to 10.\n After that loop I have one copy of original number(Here I can not compare to original number because after looping my original number is becomes 0 causing division in loop). so I compare that copy of number with sum variable which stores reverse number.\n If my reverse number is equal to original number then It is palindrome otherwise it doesn\'t.\n\n# Complexity\n- **Time complexity: O(logn) or O(lengthof(x)) or O(no.ofdigitsin(x))**\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- **Space complexity: O(1)**\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n bool isPalindrome(int x) {\n long long on=x;\n long long sum=0;\n while(x>0)\n {\n sum=(sum*10)+(x%10);\n x/=10;\n }\n if(sum==on)\n {\n return true;\n }\n return false;\n }\n};\n```\n![upvote.jpg]()\n | 828 |
Palindrome Number | palindrome-number | Given an integer x, return true if x is palindrome integer. An integer is a palindrome when it reads the same backward as forward. | Math | Easy | Beware of overflow when you reverse the integer. | 14,084 | 32 | # 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 bool isPalindrome(int x) {\n long long int copy=x;\n long long int rev=0;\n while(x!=0){\n long long int rem;\n rem=x%10;\n rev=rev*10 +rem;\n x=x/10;\n \n }\n bool check=false;\n if(rev<0){\n return check;\n }\n \n else if(rev==copy){\n check=true;\n return check;\n }else return check;\n \n }\n};\n```\nPlease upvote to motivate me to write more solutions\n\n | 829 |
Palindrome Number | palindrome-number | Given an integer x, return true if x is palindrome integer. An integer is a palindrome when it reads the same backward as forward. | Math | Easy | Beware of overflow when you reverse the integer. | 5,375 | 6 | # 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$$O(N)$$\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(N)$$\n# Code\n```\nclass Solution(object):\n def isPalindrome(self, x):\n """\n :type x: int\n :rtype: bool\n """\n if x < 0:\n return False\n lis = []\n while x >= 10:\n lis.append(x % 10)\n x //= 10\n lis.append(x)\n for i in range(int(math.ceil(len(lis)/2))):\n if lis[i] != lis[len(lis)-i-1]:\n return False\n return True\n\n``` | 830 |
Palindrome Number | palindrome-number | Given an integer x, return true if x is palindrome integer. An integer is a palindrome when it reads the same backward as forward. | Math | Easy | Beware of overflow when you reverse the integer. | 3,981 | 26 | ```\nclass Solution:\n def isPalindrome(self, x: int) -> bool:\n return str(x)[::-1] == str(x)\n``` | 833 |
Palindrome Number | palindrome-number | Given an integer x, return true if x is palindrome integer. An integer is a palindrome when it reads the same backward as forward. | Math | Easy | Beware of overflow when you reverse the integer. | 782 | 7 | # 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 bool isPalindrome(int x) {\n long long int d=x,m=0,z;\n\t\tfor (int i = x; i > 0; i=i/10)\n\t\t{z=i%10;\n\t m=m*10+z;\n\t\t\t\n\t\t}\n\t\tif(d==m)\n {\n return true;\n }\n else{\n return false;\n }\n\n\n }\n};\n``` | 838 |
Palindrome Number | palindrome-number | Given an integer x, return true if x is palindrome integer. An integer is a palindrome when it reads the same backward as forward. | Math | Easy | Beware of overflow when you reverse the integer. | 4,851 | 16 | # Problem Description\n**Given** an integer x, return **true** if x is a **palindrome**, and **false** otherwise.\n\n**Palindrome** is a **word**, **phrase**, **number**, or **other sequence of characters** that **reads** the **same** **forward** and **backward**. In simpler terms, it\'s something that `remains unchanged when its order is reversed`.\n\n- Here are a few **examples** of palindromes:\n - Words :"racecar", "madam"\n - Numbers: 121, 1331, 12321\n\n- **Constraints:**\n - `-2e31 <= x <= 2e31 - 1`\n\n---\n# Intuition\n## First Approach (Convert to String)\nThe **first** approach is to **convert our number into a string** and there we can **access** any digit **freely** unlike the integer that we can\'t do that there.\nthen we can make a **mirror** around the middle of the string and **compare** the first char with last char, the second with the one before last and so on.\nif there is a **difference** then return false otherwise return true. \n\n![image.png]()\n\n![image.png]()\n\n\n## Second Approach (Extract Digits using %)\n\n**Modulo operation** is is a mathematical operation that returns the remainder when one number is divided by another.\n- 7 % 3 = 1\n- 9 % 5 = 4\n\nModulo operation is very helpful in our problem since it helps us to **extract the least digit in our number**.\nThe solution is **extract** the digit from the original number then **put it as least digit** in our new reversed number then **delete** that digit by dividing by 10.\n\n**Example : 121**\n```\nnumber = 121 , reversed = 0 \ndigit = 121 % 10 = 1 \nreversed = 0 * 10 + 1 = 1\nnumber = 121 / 10 = 12\n```\n```\nnumber = 12 , reversed = 1 \ndigit = 12 % 10 = 2 \nreversed = 1 * 10 + 2 = 2\nnumber = 12 / 10 = 1\n```\n```\nnumber = 1 , reversed = 12\ndigit = 1 % 10 = 1 \nreversed = 12 * 10 + 1 = 121\nnumber = 1 / 10 = 0\n```\nWe can see that reversed number **equal** to original number which means it is palindrome.\n\n\n---\n\n\n# Approach\n## First Approach (Convert to String)\n- **Convert** the integer x to a string representation.\n- Determine the **length** of the string.\n- Set up a for **loop** that iterates from the beginning of the string (index 0) to halfway through the string (length / 2).\n- Inside the loop, **compare** the character at the **current** position (number[i]) with the character at the **corresponding** position from the end of the string (number[length - i - 1]).\n- If the characters **do not match** (i.e., the number is not palindrome from the center outward), return **false** immediately, indicating that it\'s not a palindrome.\n- If the **loop** **completes** without finding any mismatches (all digits match), return **true**, indicating that the integer is a palindrome.\n\n# Complexity\n- **Time complexity:**$$O(N)$$\nSince we are iterating over all the digits.\n- **Space complexity:**$$O(N)$$\nSince we are storing the number as a string where `N` here is the number of the digits.\n---\n## Second Approach (Extract Digits using %)\n- Create **two long variables**, number and reversed, both initially set to the value of the input integer x. The number variable stores the **original** number, and reversed will store the **number in reverse order**.\n- Enter a while **loop** that continues as long as the value of x is greater than 0.\n- Inside the **loop**:\n - Calculate the **last digit of x** by taking the remainder of x when divided by 10 **(x % 10)**. This digit is stored in the digit variable.\n - **Update the reversed variable** by multiplying it by 10 (shifting digits left) and then adding the digit to it. This effectively builds the reversed number digit by digit.\n - **Remove the last digit** from x by dividing it by 10 (x /= 10).\n- After the loop completes, all digits of x have been processed and reversed in reversed.\n- Check if the number (the original input) is **equal** to the reversed (the reversed input). If they are equal, return **true**, indicating that the integer is a palindrome. If they are not equal, return **false**.\n\n# Complexity\n- **Time complexity:**$$O(N)$$\nSince we are iterating over all the digits.\n- **Space complexity:**$$O(1)$$\nWe only store two additional variables.\n\n# Code\n## First Approach (Convert to String)\n```C++ []\nclass Solution {\npublic:\n bool isPalindrome(int x) {\n string number = to_string(x) ;\n int length = number.size() ;\n for(int i = 0 ; i < length / 2 ; i ++){\n if(number[i] != number[length - i - 1])\n return false ;\n }\n return true;\n }\n};\n```\n```Java []\nclass Solution {\n public boolean isPalindrome(int x) {\n String number = Integer.toString(x);\n int length = number.length();\n for (int i = 0; i < length / 2; i++) {\n if (number.charAt(i) != number.charAt(length - i - 1)) {\n return false;\n }\n }\n return true;\n }\n}\n```\n```Python []\nclass Solution:\n def isPalindrome(self, x: int) -> bool:\n number = str(x)\n length = len(number)\n \n for i in range(length // 2):\n if number[i] != number[length - i - 1]:\n return False\n \n return True\n```\n## Second Approach (Extract Digits using %)\n```C++ []\nclass Solution {\npublic:\n bool isPalindrome(int x) {\n long long number = x, reversed = 0;\n while(x > 0){\n int digit = x % 10 ;\n reversed = (reversed * 10) + digit ; \n x /= 10 ;\n }\n return number == reversed ;\n }\n};\n```\n```Java []\nclass Solution {\n public boolean isPalindrome(int x) {\n long number = x;\n long reversed = 0;\n \n while (x > 0) {\n int digit = x % 10;\n reversed = (reversed * 10) + digit;\n x /= 10;\n }\n return number == reversed;\n }\n}\n```\n```Python []\nclass Solution:\n def isPalindrome(self, x: int) -> bool:\n number = x\n reversed_num = 0\n \n while x > 0:\n digit = x % 10\n reversed_num = (reversed_num * 10) + digit\n x //= 10\n \n return number == reversed_num\n```\n\n![HelpfulJerry.jpg]()\n\n\n\n | 841 |
Palindrome Number | palindrome-number | Given an integer x, return true if x is palindrome integer. An integer is a palindrome when it reads the same backward as forward. | Math | Easy | Beware of overflow when you reverse the integer. | 171,250 | 992 | compare half of the digits in x, so don't need to deal with overflow.\n\n public boolean isPalindrome(int x) {\n if (x<0 || (x!=0 && x%10==0)) return false;\n int rev = 0;\n while (x>rev){\n \trev = rev*10 + x%10;\n \tx = x/10;\n }\n return (x==rev || x==rev/10);\n } | 842 |
Palindrome Number | palindrome-number | Given an integer x, return true if x is palindrome integer. An integer is a palindrome when it reads the same backward as forward. | Math | Easy | Beware of overflow when you reverse the integer. | 5,299 | 10 | # 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 bool isPalindrome(int x) {\n int y=x;\n if(x<0)\n return false;\n \n long int temp=0;\n while(y)\n {\n temp=temp*10+y%10;\n y/=10;\n }\n if(temp==x)\n return true;\n else\n return false;\n \n }\n};\n``` | 843 |
Palindrome Number | palindrome-number | Given an integer x, return true if x is palindrome integer. An integer is a palindrome when it reads the same backward as forward. | Math | Easy | Beware of overflow when you reverse the integer. | 4,586 | 5 | \n# Code\n```\n/**\n * @param {number} x\n * @return {boolean}\n */\nvar isPalindrome = function(x) {\n if (x < 0) return false;\n const len = getLength(x);\n\n for (let i = 0; i < len >> 1; ++i) {\n if (getDigitAt(i, x, len) !== getDigitAt(len - i - 1, x, len))\n return false;\n }\n return true;\n};\n\nfunction getLength(x) {\n if (x === 0) return 1;\n return ~~(Math.log10(x)) + 1;\n}\n\nfunction getDigitAt(i, x, l) {\n const exp = l - 1 - i;\n return ~~(x / 10 ** exp) % 10;\n}\n``` | 845 |
Palindrome Number | palindrome-number | Given an integer x, return true if x is palindrome integer. An integer is a palindrome when it reads the same backward as forward. | Math | Easy | Beware of overflow when you reverse the integer. | 10,370 | 38 | ```\nclass Solution {\n public boolean isPalindrome(int x) {\n int original = x;\n int rev = 0;\n while(x>0){\n rev = x%10 + rev*10;\n x= x/10;\n }\n return rev==original ? true : false;\n }\n}\n``` | 847 |
Palindrome Number | palindrome-number | Given an integer x, return true if x is palindrome integer. An integer is a palindrome when it reads the same backward as forward. | Math | Easy | Beware of overflow when you reverse the integer. | 1,865 | 5 | # Intuition\nReverse half of the number and compare it to the remaining number.\nIf they are equal, return true.\nOtherwise False\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n\n# Complexity\n- Time complexity: O(log10(x))\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n bool isPalindrome(int x) {\n\n //numbers such as 100 can\'t be reversed to 001\n if(x<0|| (x!=0 &&x%10==0)) return false;\n int sum=0;\n //sum contains the reversed number\n while(x>sum)\n {\n sum = sum*10+x%10;\n x = x/10;\n }\n return (x==sum)||(x==sum/10);\n }\n};\n\n``` | 867 |
Palindrome Number | palindrome-number | Given an integer x, return true if x is palindrome integer. An integer is a palindrome when it reads the same backward as forward. | Math | Easy | Beware of overflow when you reverse the integer. | 8,782 | 24 | ![image.png]()\n\n\n# Complexity\n- Time complexity:\nO(N)\n\n- Space complexity:\nO(1)\n\n# Code\n```\nclass Solution {\n public boolean isPalindrome(int x) {\n\n if(x<0)return false;\n int temp=x;\n int sum=0;\n while(x!=0){\n sum=(sum*10)+(x%10);\n x=x/10;\n }\n return (temp==sum);\n }\n}\n``` | 868 |
Palindrome Number | palindrome-number | Given an integer x, return true if x is palindrome integer. An integer is a palindrome when it reads the same backward as forward. | Math | Easy | Beware of overflow when you reverse the integer. | 706 | 6 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public boolean isPalindrome(int x) {\n long n=x;\n long ans=0;\n while(x>0)\n {\n ans+=x%10;\n ans = ans*10;\n x=x/10;\n }\n ans = ans/10;\n // System.out.println(ans);\n if(ans == n)\n return true;\n return false;\n }\n}\n``` | 869 |
Palindrome Number | palindrome-number | Given an integer x, return true if x is palindrome integer. An integer is a palindrome when it reads the same backward as forward. | Math | Easy | Beware of overflow when you reverse the integer. | 851 | 5 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nIntution is to check whether the given integer is a palindrome\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nwhat i have done here is convert the integer into list and using slicing notation reverse matched\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\no(n) is the time complexity of this code\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nspace complexity of this code is also o(n)\n# Code\n```\nclass Solution:\n def isPalindrome(self, x: int) -> bool:\n return True if list(str(x))==list(str(x))[::-1] else False\n \n``` | 870 |
Palindrome Number | palindrome-number | Given an integer x, return true if x is palindrome integer. An integer is a palindrome when it reads the same backward as forward. | Math | Easy | Beware of overflow when you reverse the integer. | 2,215 | 17 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution(object):\n def isPalindrome(self, x):\n if x<0:\n return False\n\n empty = []\n\n while x > 0:\n x, remd = divmod(x, 10)\n empty.append(remd)\n\n a=empty[::-1]\n if a==empty:\n return True\n \n else:\n return False\n``` | 871 |
Palindrome Number | palindrome-number | Given an integer x, return true if x is palindrome integer. An integer is a palindrome when it reads the same backward as forward. | Math | Easy | Beware of overflow when you reverse the integer. | 26,891 | 66 | \n# Code\n```\nclass Solution {\npublic:\n bool isPalindrome(int x) {\n stack<int> st;\n if(x<0)\n return false;\n int y=x;\n while(x)\n {\n st.push(x%10);\n x/=10;\n }\n while(y)\n {\n if(st.top()!=(y%10))\n return false;\n st.pop();\n y/=10;\n }\n return true;\n }\n};\n```\nPlease **UPVOTE** if it helps \u2764\uFE0F\uD83D\uDE0A\nThank You and Happy To Help You!! | 873 |
Palindrome Number | palindrome-number | Given an integer x, return true if x is palindrome integer. An integer is a palindrome when it reads the same backward as forward. | Math | Easy | Beware of overflow when you reverse the integer. | 25,912 | 43 | # Brute Force Solution:\n\n### Intuition: \nConvert the integer to a string and check if the string is equal to its reverse.\n\n### Approach:\n1. Convert the integer to a string using to_string() method.\n2. Reverse the string using the reverse() method.\n3. Compare the original and reversed strings to check if they are equal.\n4. If they are equal, return true. Otherwise, return false.\n\n## Time Complexity:\nO(n), where n is the number of digits in the integer.\n## Space Complexity: \nO(n), where n is the number of digits in the integer.\n\n---\n\n\n# Optimized Solution:\n\n### Intuition: \nCheck half of the digits of the integer by extracting the last digit of the integer and adding it to a new integer.\n\n### Approach:\n1. Check if the integer is negative or ends with a zero. If it is, return false.\n2. Initialize a new integer half to 0.\n3. While the original integer x is greater than half, extract the last digit of x and add it to half by multiplying half by 10 and adding the last digit of x.\n4. If the length of x is odd, we need to remove the middle digit from half. To do this, we can simply divide half by 10.\n5. Check if x is equal to half or half divided by 10.\n6. If they are equal, return true. Otherwise, return false.\n\n### Time Complexity: \nO(log n), where n is the value of the integer.\n### Space Complexity: \nO(1), as we only need to store two integers, x and half.\n\n---\n# C++\n### Brute Force\n```\nclass Solution {\npublic:\n bool isPalindrome(int x) {\n string s = to_string(x);\n string t = s;\n reverse(t.begin(), t.end());\n return s == t;\n }\n};\n```\n### Optimized\n```\nclass Solution {\npublic:\n bool isPalindrome(int x) {\n if (x < 0 || (x != 0 && x % 10 == 0)) {\n return false;\n }\n int half = 0;\n while (x > half) {\n half = half * 10 + x % 10;\n x /= 10;\n }\n return x == half || x == half / 10;\n }\n};\n\n```\n\n---\n# JAVA\n### Brute Force\n```\nclass Solution {\n public boolean isPalindrome(int x) {\n String s = Integer.toString(x);\n String t = new StringBuilder(s).reverse().toString();\n return s.equals(t);\n }\n}\n```\n### Optimized\n```\nclass Solution {\n public boolean isPalindrome(int x) {\n if (x < 0 || (x != 0 && x % 10 == 0)) {\n return false;\n }\n int half = 0;\n while (x > half) {\n half = half * 10 + x % 10;\n x /= 10;\n }\n return x == half || x == half / 10;\n }\n}\n\n```\n---\n# Python\n### Brute Force\n```\nclass Solution(object):\n def isPalindrome(self, x):\n s = str(x)\n t = s[::-1]\n return s == t\n```\n### Optimized\n```\nclass Solution(object):\n def isPalindrome(self, x):\n if x < 0 or (x != 0 and x % 10 == 0):\n return False\n half = 0\n while x > half:\n half = half * 10 + x % 10\n x //= 10\n return x == half or x == half // 10\n```\n\n---\n# JavaScript\n### Brute Force\n```\nvar isPalindrome = function(x) {\n var s = x.toString();\n var t = s.split("").reverse().join("");\n return s === t;\n};\n```\n### Optimized\n```\nvar isPalindrome = function(x) {\n if (x < 0 || (x !== 0 && x % 10 === 0)) {\n return false;\n }\n var half = 0;\n while (x > half) {\n half = half * 10 + x % 10;\n x = Math.floor(x / 10);\n }\n return x === half || x === Math.floor(half / 10);\n};\n``` | 876 |
Palindrome Number | palindrome-number | Given an integer x, return true if x is palindrome integer. An integer is a palindrome when it reads the same backward as forward. | Math | Easy | Beware of overflow when you reverse the integer. | 3,261 | 11 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe hint was not to use convertation x to string , so I used tricks of division. \n\n# Approach\nWe start from the latest digit of initial number and build reverted number. Then check is real number equals to reverted and returns the result. \n\n# Complexity\n- Time complexity: O(n) \n*where n is length of x , we just go through all numbers of initial x \n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution(object):\n def isPalindrome(self, x):\n if x < 0:\n return False\n reversed_number = 0\n number = x\n while x > 0:\n digit = x % 10\n x = x // 10\n reversed_number = reversed_number * 10 + digit\n\n return number == reversed_number\n``` | 877 |
Palindrome Number | palindrome-number | Given an integer x, return true if x is palindrome integer. An integer is a palindrome when it reads the same backward as forward. | Math | Easy | Beware of overflow when you reverse the integer. | 7,202 | 34 | *Upvote if you like my solution ;-)*\n```\nvar isPalindrome = function(x) {\n if (x < 0 || x % 10 == 0 && x !=0) {\n return false;\n }\n let t = 0;\n while (x > t) {\n t = t * 10 + x % 10;\n x = Math.floor(x / 10);\n }\n return t==x || x==Math.floor(t/10);\n};\n``` | 878 |
Palindrome Number | palindrome-number | Given an integer x, return true if x is palindrome integer. An integer is a palindrome when it reads the same backward as forward. | Math | Easy | Beware of overflow when you reverse the integer. | 16,050 | 52 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\nFirst we have to understand what is meant by a "**PALINDROME**" number.\nSuppose we have a number \'x\'. If we **REVERSE** x and store it in \'y\' then x and y should be EQUAL.\n\nMathematically, x is palindrome iff x = y where y = reverse of x.\n\n Example 1:\n let x = 123,\n then y = reverse of x = 321;\n Since, 123 != 321, Hence, x is NOT palindrome.\n\n Example 2:\n let x = 1221,\n then y = reverse of x = 1221;\n Since 1221 == 1221, Hence, x is palindrome.\n\n\n\n# Approach\n<!-- Describe your approach to solving the problem. --> Two-Pointer Approach \n \n Step1: Convert the integer into string.\n Step2: Point two variable at first and last indices of the string.\n Step3: Compare the characters at those indices.\n Step4: Update the variables.\nYou will get the answer.\n\n **If this solution helped you, give it a like to help others.**\n\n# Complexity\n- Time complexity: O(n), where n = length of integer.\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 public boolean isPalindrome(int x) {\n\n // Two-Pointer Approach\n \n \n // Step1: Convert the integer into string.\n // Step2: Point two variable at first and last indices of the string.\n // Step3: Compare the characters at those indices.\n // Step4: Update the variables.\n\n String s = String.valueOf(x); // convert integer to string.\n\n int i = 0; // i will initially point to first index.\n int j = s.length() - 1; // j will initially point to last index. \n \n // i and j are opposite indices of the string. \n // 1. If \'i\' is first then \'j\' is last.\n // 2. Similarly, if \'i\' is second then \'j\' is second last index of s.\n // This is because they are updated simultaneously.\n\n while(i <= j) // loop will break when i and j cross each other\n {\n if(s.charAt(i) != s.charAt(j)) // characters at indices i and j will be compared.\n // If the characters are unequal then false will be returned.\n return false;\n i++; // i is incremented.\n j--; // j is decremented.\n }\n \n // If loop ends without returning false, it means that every \'ith\' character\n // is equal to every \'jth\' character. Thus, the number is palindrome.\n // Hence, return true;\n \n return true;\n \n }\n}\n``` | 886 |
Palindrome Number | palindrome-number | Given an integer x, return true if x is palindrome integer. An integer is a palindrome when it reads the same backward as forward. | Math | Easy | Beware of overflow when you reverse the integer. | 1,852 | 6 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nTo check if an integer is a palindrome, we reverse the integer and compare it with the original number. If they are the same, the number is a palindrome. However, we need to handle some special cases like negative numbers and numbers ending with zero.\n\n---\n# Do upvote if you like the solution and explanation \uD83D\uDCA1\uD83D\uDE04\n\n---\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. If the input number x is negative or ends with a zero (except when x is 0 itself), it cannot be a palindrome. In such cases, we return false.\n\n2. We initialize a variable reversed to 0. We use a while loop to reverse the second half of the integer x. In each iteration of the loop:\n\n3. Multiply reversed by 10 to shift its digits to the left.\nAdd the last digit of x to reversed (obtained using x % 10).\nDivide x by 10 to remove the last digit.\n- After the loop, we check if x is equal to reversed or if x is equal to reversed / 10. This step handles both even and odd-length palindromes. If the condition is true, we return true, indicating that x is a palindrome; otherwise, we return false.\n\n---\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nThe time complexity of this code is O(log10(x)), where log10(x) is the number of digits in x. In the worst case, the while loop runs for half of the digits in x, so the time complexity is proportional to the number of digits.\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nThe space complexity of this code is O(1) because it uses a fixed amount of extra space regardless of the input x.\n\n---\n\n# \uD83D\uDCA1"If you have journeyed this far, I would kindly beseech you to consider upvoting this solution, thereby facilitating its reach to a wider audience."\u2763\uFE0F\uD83D\uDCA1\n\n---\n\n\n# Code\n```\nclass Solution {\npublic:\n bool isPalindrome(int x) {\n // If x is negative or ends with 0 but is not 0 itself, it cannot be a palindrome.\n if (x < 0 || (x % 10 == 0 && x != 0)) {\n return false;\n }\n\n int reversed = 0;\n while (x > reversed) {\n reversed = reversed * 10 + x % 10;\n x /= 10;\n }\n\n // When the length of the remaining number is odd, we can remove the middle digit.\n // For example, in the number 12321, we can remove the middle \'3\'.\n return x == reversed || x == reversed / 10;\n }\n};\n\n``` | 887 |
Palindrome Number | palindrome-number | Given an integer x, return true if x is palindrome integer. An integer is a palindrome when it reads the same backward as forward. | Math | Easy | Beware of overflow when you reverse the integer. | 13,915 | 118 | **Solution I:**\nConvert the number to a string, revert it and compare.\n```\nclass Solution {\npublic:\n bool isPalindrome(int x) {\n string rev = to_string(x);\n reverse(rev.begin(), rev.end());\n return to_string(x) == rev;\n }\n};\n```\n**Solution II:**\nConvert the number to a string, then use two pointers at beginning and end to check if it\'s a palindrome.\n```\nclass Solution {\npublic:\n bool isPalindrome(int x) {\n string s = to_string(x);\n int i = 0, j = s.size()-1;\n while (i <= j) if (s[i++] != s[j--]) return false;\n return true;\n }\n};\n```\n**Solution III:**\nReverse the second half of the number and then compare.\n```\nclass Solution {\npublic:\n bool isPalindrome(int x) {\n if (x < 0 || (x % 10 == 0 && x != 0)) return false;\n int rev = 0;\n while (rev < x) {\n rev = rev * 10 + x % 10;\n x /= 10;\n }\n \n return x == rev || x == rev / 10;\n }\n};\n```\n**Like it? please upvote!** | 889 |
Palindrome Number | palindrome-number | Given an integer x, return true if x is palindrome integer. An integer is a palindrome when it reads the same backward as forward. | Math | Easy | Beware of overflow when you reverse the integer. | 89,972 | 537 | class Solution {\n public:\n bool isPalindrome(int x) {\n if(x<0|| (x!=0 &&x%10==0)) return false;\n int sum=0;\n while(x>sum)\n {\n sum = sum*10+x%10;\n x = x/10;\n }\n return (x==sum)||(x==sum/10);\n }\n }; | 890 |
Palindrome Number | palindrome-number | Given an integer x, return true if x is palindrome integer. An integer is a palindrome when it reads the same backward as forward. | Math | Easy | Beware of overflow when you reverse the integer. | 9,081 | 36 | **Please Upvote if you like this solution.**\n\n```\n/**\n * @param {number} x\n * @return {boolean}\n */\nvar isPalindrome = function(x) {\n return x < 0 ? false : (x === +x.toString().split("").reverse().join(""));\n};\n``` | 893 |
Palindrome Number | palindrome-number | Given an integer x, return true if x is palindrome integer. An integer is a palindrome when it reads the same backward as forward. | Math | Easy | Beware of overflow when you reverse the integer. | 2,682 | 9 | # Approach\nStore the value of x in an integer, then reverse the original number using a while loop, where you will keep using modulous to get the remainder and keep adding that to the rev int initilized at the beginning.\nLastly, check if the rev and the original are equal and or original >=0, return true else false.\n<!-- Describe your approach to solving the problem. -->\n\n\n# Code\n```\nclass Solution {\n public boolean isPalindrome(int x) {\n int rev =0;\n int original = x;\n while(x !=0){\n int num = x % 10;\n rev = rev *10 + num;\n x = x/10;\n\n }\n\n if(original >= 0 && original == rev){\n return true;\n }\n\n return false;\n }\n}\n``` | 894 |
Palindrome Number | palindrome-number | Given an integer x, return true if x is palindrome integer. An integer is a palindrome when it reads the same backward as forward. | Math | Easy | Beware of overflow when you reverse the integer. | 1,448 | 17 | # Intuition\nMy initial approach to determining whether a given integer is a palindrome involves reversing the digits of the number and comparing the reversed number with the original number. If they are the same, the number is a palindrome.\n\n# Approach\nI will reverse the digits of the given integer by repeatedly extracting the last digit of the number and building the reversed number. I\'ll compare the reversed number with the original number, and if they match, the number is a palindrome.\n\n# Complexity\n- Time complexity: O(log n)\n The number of digits in the input number is proportional to the logarithm of the number with respect to the base 10. Reversing the digits takes logarithmic time.\n\n- Space complexity: O(1)\n The algorithm uses a constant amount of extra space to store the reversed number and some variables.\n\n# Code\n```\nclass Solution {\n public boolean isPalindrome(int x) {\n int revers = 0;\n int temp = x;\n while (x > 0) {\n int digit = x % 10;\n\n\n revers = revers*10 + digit;\n\n\n x /= 10;\n\n\n }\n\n if(revers==temp){\n return true;\n }\n \n return false;\n \n }\n}\n```\n![c0504eaf-5fb8-4a1d-a769-833262d1b86e_1674433591.3836212.webp]() | 895 |
Palindrome Number | palindrome-number | Given an integer x, return true if x is palindrome integer. An integer is a palindrome when it reads the same backward as forward. | Math | Easy | Beware of overflow when you reverse the integer. | 3,394 | 12 | # Upvote if its helps\n# Code\n```\nclass Solution {\npublic:\n bool isPalindrome(int x) {\n vector<int> idkw;\n if(x<0) return false;\n int temp=x;\n while(temp){\n idkw.push_back(temp%10);\n temp/=10;\n }\n int l=0,r=idkw.size()-1;\n while(l<r){\n if(idkw[l]!=idkw[r]) return false;\n l++;r--;\n }\n return true;\n }\n};\n``` | 896 |
Palindrome Number | palindrome-number | Given an integer x, return true if x is palindrome integer. An integer is a palindrome when it reads the same backward as forward. | Math | Easy | Beware of overflow when you reverse the integer. | 13,795 | 39 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nString has method to reverse\n# Approach\n<!-- Describe your approach to solving the problem. -->\nwith reversing it is possible to write in one line\n\'[::]\' this means print all, and this \'[::-1]\' reverses, it is mostly used with list in python \n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def isPalindrome(self, x: int) -> bool:\n return True if str(x)==str(x)[::-1] else False | 897 |
Regular Expression Matching | regular-expression-matching | Given an input string s and a pattern p, implement regular expression matching with support for '.' and '*' where: The matching should cover the entire input string (not partial). | String,Dynamic Programming,Recursion | Hard | null | 25,666 | 461 | ```C++ []\nclass Solution {\npublic:\n bool isMatch(string s, string p) {\n int n = s.length(), m = p.length();\n bool dp[n+1][m+1];\n memset(dp, false, sizeof(dp));\n dp[0][0] = true;\n \n for(int i=0; i<=n; i++){\n for(int j=1; j<=m; j++){\n if(p[j-1] == \'*\'){\n dp[i][j] = dp[i][j-2] || (i > 0 && (s[i-1] == p[j-2] || p[j-2] == \'.\') && dp[i-1][j]);\n }\n else{\n dp[i][j] = i > 0 && dp[i-1][j-1] && (s[i-1] == p[j-1] || p[j-1] == \'.\');\n }\n }\n }\n \n return dp[n][m];\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def isMatch(self, s: str, p: str) -> bool:\n i, j = len(s) - 1, len(p) - 1\n return self.backtrack({}, s, p, i, j)\n\n def backtrack(self, cache, s, p, i, j):\n key = (i, j)\n if key in cache:\n return cache[key]\n\n if i == -1 and j == -1:\n cache[key] = True\n return True\n\n if i != -1 and j == -1:\n cache[key] = False\n return cache[key]\n\n if i == -1 and p[j] == \'*\':\n k = j\n while k != -1 and p[k] == \'*\':\n k -= 2\n \n if k == -1:\n cache[key] = True\n return cache[key]\n \n cache[key] = False\n return cache[key]\n \n if i == -1 and p[j] != \'*\':\n cache[key] = False\n return cache[key]\n\n if p[j] == \'*\':\n if self.backtrack(cache, s, p, i, j - 2):\n cache[key] = True\n return cache[key]\n \n if p[j - 1] == s[i] or p[j - 1] == \'.\':\n if self.backtrack(cache, s, p, i - 1, j):\n cache[key] = True\n return cache[key]\n \n if p[j] == \'.\' or s[i] == p[j]:\n if self.backtrack(cache, s, p, i - 1, j - 1):\n cache[key] = True\n return cache[key]\n\n cache[key] = False\n return cache[key]\n```\n\n```Java []\nenum Result {\n TRUE, FALSE\n}\n\nclass Solution {\n Result[][] memo;\n\n public boolean isMatch(String text, String pattern) {\n memo = new Result[text.length() + 1][pattern.length() + 1];\n return dp(0, 0, text, pattern);\n }\n\n public boolean dp(int i, int j, String text, String pattern) {\n if (memo[i][j] != null) {\n return memo[i][j] == Result.TRUE;\n }\n boolean ans;\n if (j == pattern.length()){\n ans = i == text.length();\n } else{\n boolean first_match = (i < text.length() &&\n (pattern.charAt(j) == text.charAt(i) ||\n pattern.charAt(j) == \'.\'));\n\n if (j + 1 < pattern.length() && pattern.charAt(j+1) == \'*\'){\n ans = (dp(i, j+2, text, pattern) ||\n first_match && dp(i+1, j, text, pattern));\n } else {\n ans = first_match && dp(i+1, j+1, text, pattern);\n }\n }\n memo[i][j] = ans ? Result.TRUE : Result.FALSE;\n return ans;\n }\n}\n```\n | 902 |
Regular Expression Matching | regular-expression-matching | Given an input string s and a pattern p, implement regular expression matching with support for '.' and '*' where: The matching should cover the entire input string (not partial). | String,Dynamic Programming,Recursion | Hard | null | 27,175 | 209 | # Approach\n- Here the approach is very simple we basically must create a DP to store the states. For any DP problem all follow the same rule that we should memoize the truth value of $$(n,m)$$ then we need the values of $$(n-1 , m)$$ or $$(n ,m-1)$$ or $$(n-1 , m-1)$$ this would be the whole point of DP.\n\n\n---\n\n\n\n![pic0.png]()\n\n>The example of mississippi is taken and the DP table is depicted below and the explaination is provided down.\n\n![pic1.png]()\n\n>Here we basically broke the entire one into three cases as shown in the below picture.Now we procced based on the below three cases and construct our DP table and thus we finally obtain our answer.\n\n![pic 2.png]()\n\n\n---\n\n\n\n# Complexity\n> - Time complexity: Here the complexity would be $$O(n^2)$$ as we need a 2D loop for keeping the track of length of both the strings.\n\n>- Space complexity: Here the space would also be $$O(n^2)$$ which can later be optimised to $$O(n)$$ by making space optimisation into two 1D arrays but we must do this to store the truth values of the lengths.\n\n\n---\n\n\n\n# Code\n```C++ []\nclass Solution {\npublic:\n bool isMatch(string s, string p) {\n int n = s.length(), m = p.length();\n bool dp[n+1][m+1];\n memset(dp, false, sizeof(dp));\n dp[0][0] = true;\n \n for(int i=0; i<=n; i++){\n for(int j=1; j<=m; j++){\n if(p[j-1] == \'*\'){\n dp[i][j] = dp[i][j-2] || (i > 0 && (s[i-1] == p[j-2] || p[j-2] == \'.\') && dp[i-1][j]);\n }\n else{\n dp[i][j] = i > 0 && dp[i-1][j-1] && (s[i-1] == p[j-1] || p[j-1] == \'.\');\n }\n }\n }\n \n return dp[n][m];\n }\n};\n```\n```java []\nenum Result {\n TRUE, FALSE\n}\n\nclass Solution {\n Result[][] memo;\n\n public boolean isMatch(String text, String pattern) {\n memo = new Result[text.length() + 1][pattern.length() + 1];\n return dp(0, 0, text, pattern);\n }\n\n public boolean dp(int i, int j, String text, String pattern) {\n if (memo[i][j] != null) {\n return memo[i][j] == Result.TRUE;\n }\n boolean ans;\n if (j == pattern.length()){\n ans = i == text.length();\n } else{\n boolean first_match = (i < text.length() &&\n (pattern.charAt(j) == text.charAt(i) ||\n pattern.charAt(j) == \'.\'));\n\n if (j + 1 < pattern.length() && pattern.charAt(j+1) == \'*\'){\n ans = (dp(i, j+2, text, pattern) ||\n first_match && dp(i+1, j, text, pattern));\n } else {\n ans = first_match && dp(i+1, j+1, text, pattern);\n }\n }\n memo[i][j] = ans ? Result.TRUE : Result.FALSE;\n return ans;\n }\n}\n```\n```python []\nclass Solution:\n def isMatch(self, s: str, p: str) -> bool:\n i, j = len(s) - 1, len(p) - 1\n return self.backtrack({}, s, p, i, j)\n\n def backtrack(self, cache, s, p, i, j):\n key = (i, j)\n if key in cache:\n return cache[key]\n\n if i == -1 and j == -1:\n cache[key] = True\n return True\n\n if i != -1 and j == -1:\n cache[key] = False\n return cache[key]\n\n if i == -1 and p[j] == \'*\':\n k = j\n while k != -1 and p[k] == \'*\':\n k -= 2\n \n if k == -1:\n cache[key] = True\n return cache[key]\n \n cache[key] = False\n return cache[key]\n \n if i == -1 and p[j] != \'*\':\n cache[key] = False\n return cache[key]\n\n if p[j] == \'*\':\n if self.backtrack(cache, s, p, i, j - 2):\n cache[key] = True\n return cache[key]\n \n if p[j - 1] == s[i] or p[j - 1] == \'.\':\n if self.backtrack(cache, s, p, i - 1, j):\n cache[key] = True\n return cache[key]\n \n if p[j] == \'.\' or s[i] == p[j]:\n if self.backtrack(cache, s, p, i - 1, j - 1):\n cache[key] = True\n return cache[key]\n\n cache[key] = False\n return cache[key]\n```\n\n\n---\n\n\n\nIF YOU LIKE THE SOLUTION THEN PLEASE UPVOTE MY SOLUTION BECAUSE IT GIVES ME MOTIVATION TO REGULARLY POST THE SOLUTION.\n\n![UPVOTE.jpg]()\n | 903 |
Regular Expression Matching | regular-expression-matching | Given an input string s and a pattern p, implement regular expression matching with support for '.' and '*' where: The matching should cover the entire input string (not partial). | String,Dynamic Programming,Recursion | Hard | null | 227,853 | 1,023 | This Solution use 2D DP. beat 90% solutions, very simple.\n\nHere are some conditions to figure out, then the logic can be very straightforward.\n\n 1, If p.charAt(j) == s.charAt(i) : dp[i][j] = dp[i-1][j-1];\n 2, If p.charAt(j) == '.' : dp[i][j] = dp[i-1][j-1];\n 3, If p.charAt(j) == '*': \n here are two sub conditions:\n 1 if p.charAt(j-1) != s.charAt(i) : dp[i][j] = dp[i][j-2] //in this case, a* only counts as empty\n 2 if p.charAt(i-1) == s.charAt(i) or p.charAt(i-1) == '.':\n dp[i][j] = dp[i-1][j] //in this case, a* counts as multiple a \n or dp[i][j] = dp[i][j-1] // in this case, a* counts as single a\n or dp[i][j] = dp[i][j-2] // in this case, a* counts as empty\n\nHere is the solution\n\n public boolean isMatch(String s, String p) {\n\n if (s == null || p == null) {\n return false;\n }\n boolean[][] dp = new boolean[s.length()+1][p.length()+1];\n dp[0][0] = true;\n for (int i = 0; i < p.length(); i++) {\n if (p.charAt(i) == '*' && dp[0][i-1]) {\n dp[0][i+1] = true;\n }\n }\n for (int i = 0 ; i < s.length(); i++) {\n for (int j = 0; j < p.length(); j++) {\n if (p.charAt(j) == '.') {\n dp[i+1][j+1] = dp[i][j];\n }\n if (p.charAt(j) == s.charAt(i)) {\n dp[i+1][j+1] = dp[i][j];\n }\n if (p.charAt(j) == '*') {\n if (p.charAt(j-1) != s.charAt(i) && p.charAt(j-1) != '.') {\n dp[i+1][j+1] = dp[i+1][j-1];\n } else {\n dp[i+1][j+1] = (dp[i+1][j] || dp[i][j+1] || dp[i+1][j-1]);\n }\n }\n }\n }\n return dp[s.length()][p.length()];\n } | 905 |
Regular Expression Matching | regular-expression-matching | Given an input string s and a pattern p, implement regular expression matching with support for '.' and '*' where: The matching should cover the entire input string (not partial). | String,Dynamic Programming,Recursion | Hard | null | 29,391 | 541 | Consider following example\n```\ns=\'aab\', p=\'c*a*b\'\n\n c * a * b \n 0 1 2 3 4 5\n 0 y\na 1\na 2\nb 3\n```\n\n`dp[i][j]` denotes if `s.substring(0,i)` is valid for pattern `p.substring(0,j)`. For example `dp[0][0] == true` (denoted by y in the matrix) because when s and p are both empty they match. So if we somehow base `dp[i+1][j+1]` on previos `dp[i][j]`\'s then the result will be `dp[s.length()][p.length()]` \n\nSo what about the first column? for and empty pattern `p=""` only thing that is valid is an empty string `s=""` and that is already our `dp[0][0]` which is true. That means rest of `dp[i][0]\' is false.\n\n```\ns=\'aab\', p=\'c*a*b\'\n\n c * a * b \n 0 1 2 3 4 5\n 0 y\na 1 n\na 2 n\nb 3 n\n```\n\nWhat about the first row? In other words which pattern p matches empty string `s=""`? The answer is either an empty pattern `p=""` or a pattern that can represent an empty string such as `p="a*"`, `p="z*"` or more interestingly a combiation of them as in `p="a*b*c*"`. Below for loop is used to populate `dp[0][j]`. Note how it uses previous states by checking `dp[0][j-2]`\n\n```java\n for (int j=2; j<=p.length(); j++) {\n dp[0][j] = p.charAt(j-1) == \'*\' && dp[0][j-2]; \n }\n```\n\nAt this stage our matrix has become as follows: Notice `dp[0][2]` and `dp[0][4]` are both true because `p="c*"` and `p="c*a*"` can both match an empty string.\n\n```\ns=\'aab\', p=\'c*a*b\'\n\n c * a * b \n 0 1 2 3 4 5\n 0 y n y n y n\na 1 n\na 2 n\nb 3 n\n```\n\nSo now we can start our main iteration. It is basically the same, we will iterate all possible s lengths (i) for all possible p lengths (j) and we will try to find a relation based on previous results. Turns out there are two cases.\n1) `(p.charAt(j-1) == s.charAt(i-1) || p.charAt(j-1) == \'.\')` if the current characters match or pattern has `.` then the result is determined by the previous state `dp[i][j] = dp[i-1][j-1]`. *Don\'t be confused by the `charAt(j-1)` `charAt(i-1)` indexes using a `-1` offset that is because our dp array is actually one index bigger than our string and pattern lenghts to hold the initial state `dp[0][0]`*\n\n2) if `p.charAt(j-1) == \'*\'` then either it acts as an empty set and the result is `dp[i][j] = dp[i][j-2]` or `(s.charAt(i-1) == p.charAt(j-2) || p.charAt(j-2) == \'.\')` current char of string equals the char preceding `*` in pattern so the result is `dp[i-1][j]`\n\nSo here is the final state of matrix after we evaluate all elements:\n\n```\ns=\'aab\', p=\'c*a*b\'\n\n c * a * b \n 0 1 2 3 4 5\n 0 y n y n y n\na 1 n n n y y n\na 2 n n n n y n\nb 3 n n n n n y\n```\n\nAnd here is the code: \n\n```java\npublic boolean isMatch(String s, String p) {\n if (p == null || p.length() == 0) return (s == null || s.length() == 0);\n \n boolean dp[][] = new boolean[s.length()+1][p.length()+1];\n dp[0][0] = true;\n for (int j=2; j<=p.length(); j++) {\n dp[0][j] = p.charAt(j-1) == \'*\' && dp[0][j-2]; \n }\n \n for (int j=1; j<=p.length(); j++) {\n for (int i=1; i<=s.length(); i++) {\n if (p.charAt(j-1) == s.charAt(i-1) || p.charAt(j-1) == \'.\') \n\t\t\t\t\tdp[i][j] = dp[i-1][j-1];\n else if(p.charAt(j-1) == \'*\')\n dp[i][j] = dp[i][j-2] || ((s.charAt(i-1) == p.charAt(j-2) || p.charAt(j-2) == \'.\') && dp[i-1][j]); \n }\n }\n return dp[s.length()][p.length()];\n }\n```\n\nTime and space complexity are `O(p.length() * s.length())`. \nTry to evaluate the matrix by yourself if it is still confusing, hope this helps! | 907 |
Regular Expression Matching | regular-expression-matching | Given an input string s and a pattern p, implement regular expression matching with support for '.' and '*' where: The matching should cover the entire input string (not partial). | String,Dynamic Programming,Recursion | Hard | null | 82,316 | 400 | We define `dp[i][j]` to be `true` if `s[0..i)` matches `p[0..j)` and `false` otherwise. The state equations will be:\n\n 1. `dp[i][j] = dp[i - 1][j - 1]`, if `p[j - 1] != \'*\' && (s[i - 1] == p[j - 1] || p[j - 1] == \'.\')`;\n 2. `dp[i][j] = dp[i][j - 2]`, if `p[j - 1] == \'*\'` and the pattern repeats for 0 time;\n 3. `dp[i][j] = dp[i - 1][j] && (s[i - 1] == p[j - 2] || p[j - 2] == \'.\')`, if `p[j - 1] == \'*\'` and the pattern repeats for at least 1 time.\n\n```cpp\nclass Solution {\npublic:\n bool isMatch(string s, string p) {\n int m = s.size(), n = p.size();\n vector<vector<bool>> dp(m + 1, vector<bool>(n + 1, false));\n dp[0][0] = true;\n for (int i = 0; i <= m; i++) {\n for (int j = 1; j <= n; j++) {\n if (p[j - 1] == \'*\') {\n dp[i][j] = dp[i][j - 2] || (i && dp[i - 1][j] && (s[i - 1] == p[j - 2] || p[j - 2] == \'.\'));\n } else {\n dp[i][j] = i && dp[i - 1][j - 1] && (s[i - 1] == p[j - 1] || p[j - 1] == \'.\');\n }\n }\n }\n return dp[m][n];\n }\n};\n```\n\nAnd you may further reduce the memory usage down to two vectors (`O(n)`).\n\n```cpp\nclass Solution {\npublic:\n bool isMatch(string s, string p) {\n int m = s.size(), n = p.size();\n vector<bool> pre(n + 1, false), cur(n + 1, false);\n cur[0] = true;\n for (int i = 0; i <= m; i++) {\n for (int j = 1; j <= n; j++) {\n if (p[j - 1] == \'*\') {\n cur[j] = cur[j - 2] || (i && pre[j] && (s[i - 1] == p[j - 2] || p[j - 2] == \'.\'));\n } else {\n cur[j] = i && pre[j - 1] && (s[i - 1] == p[j - 1] || p[j - 1] == \'.\');\n }\n }\n fill(pre.begin(), pre.end(), false);\n\t\t\tswap(pre, cur);\n }\n return pre[n];\n }\n};\n```\n\nOr even just one vector.\n\n```cpp\nclass Solution {\npublic:\n bool isMatch(string s, string p) {\n int m = s.size(), n = p.size();\n vector<bool> cur(n + 1, false);\n for (int i = 0; i <= m; i++) {\n bool pre = cur[0];\n cur[0] = !i;\n for (int j = 1; j <= n; j++) {\n bool temp = cur[j];\n if (p[j - 1] == \'*\') {\n cur[j] = cur[j - 2] || (i && cur[j] && (s[i - 1] == p[j - 2] || p[j - 2] == \'.\'));\n } else {\n cur[j] = i && pre && (s[i - 1] == p[j - 1] || p[j - 1] == \'.\');\n }\n pre = temp;\n }\n }\n return cur[n];\n }\n};\n``` | 911 |
Regular Expression Matching | regular-expression-matching | Given an input string s and a pattern p, implement regular expression matching with support for '.' and '*' where: The matching should cover the entire input string (not partial). | String,Dynamic Programming,Recursion | Hard | null | 137,940 | 407 | Please refer to [my blog post][1] if you have any comment. Wildcard matching problem can be solved similarly.\n\n class Solution {\n public:\n bool isMatch(string s, string p) {\n if (p.empty()) return s.empty();\n \n if ('*' == p[1])\n // x* matches empty string or at least one character: x* -> xx*\n // *s is to ensure s is non-empty\n return (isMatch(s, p.substr(2)) || !s.empty() && (s[0] == p[0] || '.' == p[0]) && isMatch(s.substr(1), p));\n else\n return !s.empty() && (s[0] == p[0] || '.' == p[0]) && isMatch(s.substr(1), p.substr(1));\n }\n };\n \n class Solution {\n public:\n bool isMatch(string s, string p) {\n /**\n * f[i][j]: if s[0..i-1] matches p[0..j-1]\n * if p[j - 1] != '*'\n * f[i][j] = f[i - 1][j - 1] && s[i - 1] == p[j - 1]\n * if p[j - 1] == '*', denote p[j - 2] with x\n * f[i][j] is true iff any of the following is true\n * 1) "x*" repeats 0 time and matches empty: f[i][j - 2]\n * 2) "x*" repeats >= 1 times and matches "x*x": s[i - 1] == x && f[i - 1][j]\n * '.' matches any single character\n */\n int m = s.size(), n = p.size();\n vector<vector<bool>> f(m + 1, vector<bool>(n + 1, false));\n \n f[0][0] = true;\n for (int i = 1; i <= m; i++)\n f[i][0] = false;\n // p[0.., j - 3, j - 2, j - 1] matches empty iff p[j - 1] is '*' and p[0..j - 3] matches empty\n for (int j = 1; j <= n; j++)\n f[0][j] = j > 1 && '*' == p[j - 1] && f[0][j - 2];\n \n for (int i = 1; i <= m; i++)\n for (int j = 1; j <= n; j++)\n if (p[j - 1] != '*')\n f[i][j] = f[i - 1][j - 1] && (s[i - 1] == p[j - 1] || '.' == p[j - 1]);\n else\n // p[0] cannot be '*' so no need to check "j > 1" here\n f[i][j] = f[i][j - 2] || (s[i - 1] == p[j - 2] || '.' == p[j - 2]) && f[i - 1][j];\n \n return f[m][n];\n }\n };\n\n [1]: | 912 |
Regular Expression Matching | regular-expression-matching | Given an input string s and a pattern p, implement regular expression matching with support for '.' and '*' where: The matching should cover the entire input string (not partial). | String,Dynamic Programming,Recursion | Hard | null | 26,265 | 334 | The point I want to show is once you figure out the naive approach (#1 or #2), it is effortless to transform to dp. Mostly copy and replace.\n1. Recursion. This is the most straight forward idea. We match the current char in s and p, then solve the problem recursively. Following are the keys\n\t1\\) Termination condition. Since p can match empty string, s is empty (i=sn) cannot terminate the matching. Only p is empty(j==pn) terminates the recursion.\n\t2\\) If a char is followed by *, then we only need to honor the *. No need to do 1 to 1 match. 1 to 1 match is only needed if a char is not followed by *.\n\t3\\) When matching *, we check if the next char is *. If we process * as the current char, it means 1 to 1 match is already done for the previous char. The logic is not clean.\n* c++\n```\n bool isMatch(string s, string p) {\n return isMatch(0,s,0,p); \n }\n bool isMatch(int i, string& s, int j, string &p) {\n int pn=p.size(), sn = s.size();\n if(j==pn) return i==sn;\n if(p[j+1]==\'*\') {\n if(isMatch(i,s,j+2,p)) return 1;\n while(i<sn && (p[j]==s[i]||p[j]==\'.\')) \n\t\t\t\tif(isMatch(++i,s,j+2,p)) return 1;\n } else if (i<sn && (p[j]==\'.\'|| s[i]==p[j]) && isMatch(i+1,s,j+1,p)) \n\t\t\treturn 1;\n return 0;\n }\n```\n* java\n```\n\tpublic boolean isMatch(String s, String p) {\n return isMatch(0,s,0,p);\n }\n private boolean isMatch(int i, String s, int j, String p) { \n int sn = s.length(), pn = p.length();\n if(j==pn) { // since * in p can match 0 of previous char, so empty string(i==sn) may match p\n return i==sn; \n }\n char pj = p.charAt(j);\n if(j+1<pn && p.charAt(j+1)==\'*\') { //match *, needs to look at the next char to repeate current char\n if(isMatch(i,s,j+2,p)) {\n return true;\n }\n while(i<sn && (pj == \'.\'||pj==s.charAt(i))) {\n if(isMatch(++i,s,j+2,p)) {\n return true;\n }\n }\n } else if(i<sn && (s.charAt(i) == pj || //match char\n pj==\'.\')) { //match dot\n return isMatch(i+1, s, j+1, p);\n }\n return false;\n }\n```\nTime complexity is roughly O(m+n choose n).\nSay n is length of s, m is length of p. In the worst case,\nT(n,m) = T(n,m-2)+T(n-1,m-2)+T(n-2,m-2)+...+T(1, m-2)\nT(n-1,m) = T(n-1,m-2)+T(n-2,m-2)+...+T(1,m-2)\n=> ****T(n,m) = T(n-1,m) + T(n,m-2)****\nInitial conditions are T(0,m) = m, T(n,0) = 1\nTo solve the 2 variable recursion, see [here]()\n\n2. Recursion The highlighted recursive equation indicates a more concise way to handle the case when * matches 1 or more characters. It does not change the time complexity of the recursion but it transforms to a better run time dp solution compared with the original equation.\n* c++\n```\n bool isMatch(string s, string p) {\n return isMatch(0,s,0,p); \n }\n bool isMatch(int i, string& s, int j, string &p) {\n int pn=p.size(), sn = s.size();\n if(j==pn) return i==sn;\n if(p[j+1]==\'*\') {\n if(isMatch(i,s,j+2,p) || \n i<sn && (p[j] == \'.\' || s[i] == p[j]) && isMatch(i+1,s,j,p)) \n\t\t\t return 1;\n } else if (i<sn && (p[j]==\'.\'|| s[i]==p[j]) && isMatch(i+1,s,j+1,p)) \n\t\t\treturn 1;\n return 0;\n }\n```\n* java\n```\n\tpublic boolean isMatch(String s, String p) {\n return isMatch(0,s,0,p);\n }\n private boolean isMatch(int i, String s, int j, String p) { \n int sn = s.length(), pn = p.length();\n if(j==pn) { // since * in p can match 0 of previous char, so empty string(i==sn) may match p\n return i==sn; \n }\n char pj = p.charAt(j);\n if(j+1<pn && p.charAt(j+1)==\'*\') { //match *, needs to look at the next char to repeate current char\n if(isMatch(i,s,j+2,p)) {\n return true;\n }\n if(i<sn && (pj == \'.\'||pj==s.charAt(i))) {\n if(isMatch(i+1,s,j,p)) {\n return true;\n }\n }\n } else if(i<sn && (s.charAt(i) == pj || //match char\n pj==\'.\')) { //match dot\n return isMatch(i+1, s, j+1, p);\n }\n return false;\n }\n```\n3. Recursion with memoization O(mn), add a vector, the rest is the same as #2. \n* c++\n```\n bool isMatch(string s, string p) {\n vector<vector<char>> dp(s.size()+1,vector<char>(p.size()+1,-1));\n return isMatch(0,s,0,p,dp); \n }\n bool isMatch(int i, string& s, int j, string &p, vector<vector<char>> &dp) {\n if(dp[i][j] > -1) return dp[i][j];\n int pn=p.size(), sn = s.size();\n if(j==pn) return dp[i][j] = i==sn;\n if(p[j+1]==\'*\') {\n if(isMatch(i,s,j+2,p,dp) || \n i<sn && (p[j] == \'.\' || s[i] == p[j]) && isMatch(i+1,s,j,p,dp)) \n\t\t\t return dp[i][j] = 1;\n } else if (i<sn && (p[j]==\'.\'|| s[i]==p[j]) && isMatch(i+1,s,j+1,p,dp)) \n\t\t\treturn dp[i][j] = 1;\n return dp[i][j] = 0;\n }\n```\n* java\n```\n\tBoolean[][] mem;\n public boolean isMatch(String s, String p) {\n mem = new Boolean[s.length()+1][p.length()];\n return isMatch(0,s,0,p);\n }\n private boolean isMatch(int i, String s, int j, String p) { \n int sn = s.length(), pn = p.length();\n if(j==pn) { // since * in p can match 0 of previous char, so empty string(i==sn) may match p\n return i==sn; \n }\n if(mem[i][j]!=null) {\n return mem[i][j];\n }\n char pj = p.charAt(j);\n if(j+1<pn && p.charAt(j+1)==\'*\') { //match *, needs to look at the next char to repeate current char\n if(isMatch(i,s,j+2,p)) {\n return mem[i][j]=true;\n }\n if(i<sn && (pj == \'.\'||pj==s.charAt(i))) {\n if(isMatch(i+1,s,j,p)) {\n return mem[i][j]=true;\n }\n }\n } else if(i<sn && (s.charAt(i) == pj || //match char\n pj==\'.\')) { //match dot\n return mem[i][j]=isMatch(i+1, s, j+1, p);\n }\n return mem[i][j]=false;\n }\n```\n4. Bottom up dp to be consistent with #3, O(mn), use for loop instead of recursion, the rest is the same as #2 and #3.\nIdea is the same as top down dp.\n* c++\n```\n bool isMatch(string s, string p) {\n int pn=p.size(), sn = s.size();\n vector<vector<bool>> dp(sn+1,vector<bool>(pn+1));\n dp[sn][pn] = 1;\n for(int i = sn;i>=0;i--) \n for(int j=pn-1;j>=0;j--) \n if(p[j+1]==\'*\') \n\t\t\t\t\tdp[i][j] = dp[i][j+2] || i<sn && (p[j] == \'.\' || s[i] == p[j]) && dp[i+1][j];\n else dp[i][j] = i<sn && (p[j]==\'.\'|| s[i]==p[j]) && dp[i+1][j+1];\n return dp[0][0]; \n }\n```\n* java\n```\n\tpublic boolean isMatch(String s, String p) {\n int sn=s.length(),pn=p.length();\n boolean[][] dp=new boolean[sn+1][pn+1];\n dp[sn][pn]=true;\n for(int i=sn;i>=0;i--)\n for(int j=pn-1;j>=0;j--)\n if(j+1<pn&&p.charAt(j+1)==\'*\') {\n dp[i][j]=dp[i][j+2];\n if(i<sn&&(p.charAt(j)==\'.\'||s.charAt(i)==p.charAt(j))) \n dp[i][j]|=dp[i+1][j];\n } else if(i<sn&&(p.charAt(j)==\'.\'||s.charAt(i)==p.charAt(j))) \n dp[i][j]=dp[i+1][j+1];\n return dp[0][0]; \n }\n}\n```\n5. Java 1 liner. In real work, none of the above is accpetable due to readability and maintenane overehead.\n```\n\tpublic boolean isMatch(String s, String p) {\n return s.matches(p); \n }\n``` | 913 |
Regular Expression Matching | regular-expression-matching | Given an input string s and a pattern p, implement regular expression matching with support for '.' and '*' where: The matching should cover the entire input string (not partial). | String,Dynamic Programming,Recursion | Hard | null | 3,903 | 9 | # 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 bool isMatch(string s, string p) {\n int m = s.size(), n = p.size();\n vector<vector<bool>> dp(m + 1, vector<bool>(n + 1, false));\n dp[0][0] = true;\n for (int i = 0; i <= m; i++) {\n for (int j = 1; j <= n; j++) {\n if (p[j - 1] == \'*\') {\n dp[i][j] = dp[i][j - 2] || (i && dp[i - 1][j] && (s[i - 1] == p[j - 2] || p[j - 2] == \'.\'));\n } else {\n dp[i][j] = i && dp[i - 1][j - 1] && (s[i - 1] == p[j - 1] || p[j - 1] == \'.\');\n }\n }\n }\n return dp[m][n];\n }\n};\n```\nPlease upvote to motivate me to write more solutions\n\n | 915 |
Regular Expression Matching | regular-expression-matching | Given an input string s and a pattern p, implement regular expression matching with support for '.' and '*' where: The matching should cover the entire input string (not partial). | String,Dynamic Programming,Recursion | Hard | null | 8,187 | 16 | \n# Intuition:\nThe problem requires to match a given string s with a pattern p. The pattern p can contain two special characters, \'\' and \'.\'. The \'\' matches zero or more of the preceding character and \'.\' matches any single character.\n\n# Approach:\nWe can use dynamic programming to solve this problem. Let dp[i][j] be a boolean value representing whether the first i characters of s match the first j characters of p.\n\nFirst, we initialize dp[0][0] to true since an empty pattern matches an empty string.\n\nNext, we need to consider the first row of the dp matrix. If the pattern p starts with a \'*\' then it can match zero occurrences, so we set dp[0][j] to dp[0][j-2] for all j where p[j-1] == \'*\'.\n\nNow we fill in the remaining cells of the dp matrix using the following rules:\n\n1. If the i-1th character of s matches the j-1th character of p or the j-1th character of p is \'.\', then dp[i][j] is equal to dp[i-1][j-1].\n2. If the j-1th character of p is \'*\', then we have two cases:\na) Zero occurrences: dp[i][j] is equal to dp[i][j-2]\nb) One or more occurrences: dp[i][j] is equal to dp[i-1][j] if the i-1th character of s matches the j-2th character of p or the j-2th character of p is \'.\'.\n\nFinally, we return dp[m][n], which represents whether the entire string s matches the entire pattern p.\n# Complexity:\n- Time Complexity:\nThe time complexity of the algorithm is O(m * n), where m and n are the lengths of s and p, respectively. This is because we need to fill in the entire dp matrix.\n\n- Space Complexity:\nThe space complexity of the algorithm is also O(m * n) because we need to create a dp matrix of size (m+1) x (n+1).\n\n---\n\n\n# C++\n```\nclass Solution {\npublic:\n bool isMatch(string s, string p) {\n int m = s.size(), n = p.size();\n std::vector<std::vector<bool>> dp(m+1, std::vector<bool>(n+1, false));\n dp[0][0] = true; // empty pattern matches empty string\n\n // initialize first row (empty string)\n for (int j = 1; j <= n; j++) {\n if (p[j-1] == \'*\')\n dp[0][j] = dp[0][j-2];\n }\n\n // fill in remaining cells\n for (int i = 1; i <= m; i++) {\n for (int j = 1; j <= n; j++) {\n if (s[i-1] == p[j-1] || p[j-1] == \'.\') {\n dp[i][j] = dp[i-1][j-1];\n } else if (p[j-1] == \'*\') {\n dp[i][j] = dp[i][j-2]; // zero occurrences\n if (s[i-1] == p[j-2] || p[j-2] == \'.\') {\n dp[i][j] = dp[i][j] || dp[i-1][j]; // one or more occurrences\n }\n }\n }\n }\n return dp[m][n];\n }\n};\n```\n\n---\n# JAVA\n```\nclass Solution {\n public boolean isMatch(String s, String p) {\n int m = s.length(), n = p.length();\n boolean[][] dp = new boolean[m+1][n+1];\n dp[0][0] = true; // empty pattern matches empty string\n\n // initialize first row (empty string)\n for (int j = 1; j <= n; j++) {\n if (p.charAt(j-1) == \'*\')\n dp[0][j] = dp[0][j-2];\n }\n\n // fill in remaining cells\n for (int i = 1; i <= m; i++) {\n for (int j = 1; j <= n; j++) {\n if (s.charAt(i-1) == p.charAt(j-1) || p.charAt(j-1) == \'.\') {\n dp[i][j] = dp[i-1][j-1];\n } else if (p.charAt(j-1) == \'*\') {\n dp[i][j] = dp[i][j-2]; // zero occurrences\n if (s.charAt(i-1) == p.charAt(j-2) || p.charAt(j-2) == \'.\') {\n dp[i][j] = dp[i][j] || dp[i-1][j]; // one or more occurrences\n }\n }\n }\n }\n return dp[m][n];\n }\n}\n\n```\n\n---\n# Python\n```\nclass Solution(object):\n def isMatch(self, s, p):\n m, n = len(s), len(p)\n dp = [[False] * (n+1) for _ in range(m+1)]\n dp[0][0] = True # empty pattern matches empty string\n\n # initialize first row (empty string)\n for j in range(1, n+1):\n if p[j-1] == \'*\':\n dp[0][j] = dp[0][j-2]\n\n # fill in remaining cells\n for i in range(1, m+1):\n for j in range(1, n+1):\n if s[i-1] == p[j-1] or p[j-1] == \'.\':\n dp[i][j] = dp[i-1][j-1]\n elif p[j-1] == \'*\':\n dp[i][j] = dp[i][j-2]\n if s[i-1] == p[j-2] or p[j-2] == \'.\':\n dp[i][j] |= dp[i-1][j]\n\n return dp[m][n]\n\n```\n---\n# JavaScript\n```\nvar isMatch = function(s, p) {\n const m = s.length, n = p.length;\n const dp = new Array(m+1).fill().map(() => new Array(n+1).fill(false));\n dp[0][0] = true; // empty pattern matches empty string\n\n // initialize first row (empty string)\n for (let j = 1; j <= n; j++) {\n if (p[j-1] === \'*\')\n dp[0][j] = dp[0][j-2];\n }\n\n // fill in remaining cells\n for (let i = 1; i <= m; i++) {\n for (let j = 1; j <= n; j++) {\n if (s[i-1] === p[j-1] || p[j-1] === \'.\') {\n dp[i][j] = dp[i-1][j-1];\n } else if (p[j-1] === \'*\') {\n dp[i][j] = dp[i][j-2]; // zero occurrences\n if (s[i-1] === p[j-2] || p[j-2] === \'.\') {\n dp[i][j] = dp[i][j] || dp[i-1][j]; // one or more occurrences\n }\n }\n }\n }\n return dp[m][n];\n}\n``` | 916 |
Regular Expression Matching | regular-expression-matching | Given an input string s and a pattern p, implement regular expression matching with support for '.' and '*' where: The matching should cover the entire input string (not partial). | String,Dynamic Programming,Recursion | Hard | null | 38,301 | 243 | I shared my DP approach with comments and provided some unit tests for it. Some statements in the approach directly affect some corner cases, for example, comment out line 22-23, then the unittest `test_symbol_0` will fail. Hope this script helps us better understand the problem.\n\n import unittest\n \n \n class Solution(object):\n def isMatch(self, s, p):\n # The DP table and the string s and p use the same indexes i and j, but\n # table[i][j] means the match status between p[:i] and s[:j], i.e.\n # table[0][0] means the match status of two empty strings, and\n # table[1][1] means the match status of p[0] and s[0]. Therefore, when\n # refering to the i-th and the j-th characters of p and s for updating\n # table[i][j], we use p[i - 1] and s[j - 1].\n \n # Initialize the table with False. The first row is satisfied.\n table = [[False] * (len(s) + 1) for _ in range(len(p) + 1)]\n \n # Update the corner case of matching two empty strings.\n table[0][0] = True\n \n # Update the corner case of when s is an empty string but p is not.\n # Since each '*' can eliminate the charter before it, the table is\n # vertically updated by the one before previous. [test_symbol_0]\n for i in range(2, len(p) + 1):\n table[i][0] = table[i - 2][0] and p[i - 1] == '*'\n \n for i in range(1, len(p) + 1):\n for j in range(1, len(s) + 1):\n if p[i - 1] != "*":\n # Update the table by referring the diagonal element.\n table[i][j] = table[i - 1][j - 1] and \\\n (p[i - 1] == s[j - 1] or p[i - 1] == '.')\n else:\n # Eliminations (referring to the vertical element)\n # Either refer to the one before previous or the previous.\n # I.e. * eliminate the previous or count the previous.\n # [test_symbol_1]\n table[i][j] = table[i - 2][j] or table[i - 1][j]\n \n # Propagations (referring to the horizontal element)\n # If p's previous one is equal to the current s, with\n # helps of *, the status can be propagated from the left.\n # [test_symbol_2]\n if p[i - 2] == s[j - 1] or p[i - 2] == '.':\n table[i][j] |= table[i][j - 1]\n \n return table[-1][-1]\n \n \n class TestSolution(unittest.TestCase):\n def test_none_0(self):\n s = ""\n p = ""\n self.assertTrue(Solution().isMatch(s, p))\n \n def test_none_1(self):\n s = ""\n p = "a"\n self.assertFalse(Solution().isMatch(s, p))\n \n def test_no_symbol_equal(self):\n s = "abcd"\n p = "abcd"\n self.assertTrue(Solution().isMatch(s, p))\n \n def test_no_symbol_not_equal_0(self):\n s = "abcd"\n p = "efgh"\n self.assertFalse(Solution().isMatch(s, p))\n \n def test_no_symbol_not_equal_1(self):\n s = "ab"\n p = "abb"\n self.assertFalse(Solution().isMatch(s, p))\n \n def test_symbol_0(self):\n s = ""\n p = "a*"\n self.assertTrue(Solution().isMatch(s, p))\n \n def test_symbol_1(self):\n s = "a"\n p = "ab*"\n self.assertTrue(Solution().isMatch(s, p))\n \n def test_symbol_2(self):\n # E.g.\n # s a b b\n # p 1 0 0 0\n # a 0 1 0 0\n # b 0 0 1 0\n # * 0 1 1 1\n s = "abb"\n p = "ab*"\n self.assertTrue(Solution().isMatch(s, p))\n \n \n if __name__ == "__main__":\n unittest.main() | 920 |
Regular Expression Matching | regular-expression-matching | Given an input string s and a pattern p, implement regular expression matching with support for '.' and '*' where: The matching should cover the entire input string (not partial). | String,Dynamic Programming,Recursion | Hard | null | 3,509 | 8 | \n# Code\n```\nclass Solution {\npublic:\n bool isMatch(string s, string p) {\n int m = s.size(), n = p.size();\n vector<vector<bool>> dp(m + 1, vector<bool>(n + 1, false));\n dp[0][0] = true;\n for (int i = 0; i <= m; i++) {\n for (int j = 1; j <= n; j++) {\n if (p[j - 1] == \'*\') {\n dp[i][j] = dp[i][j - 2] || (i && dp[i - 1][j] && (s[i - 1] == p[j - 2] || p[j - 2] == \'.\'));\n }\n else if(i>0 && (s[i - 1] == p[j - 1] || p[j - 1] == \'.\')) {\n dp[i][j] = dp[i - 1][j - 1];\n }\n }\n }\n return dp[m][n]; \n }\n};\n```\nPlease **UPVOTE** if it helps \u2764\uFE0F\uD83D\uDE0A\nThank You and Happy To Help You!! | 924 |
Regular Expression Matching | regular-expression-matching | Given an input string s and a pattern p, implement regular expression matching with support for '.' and '*' where: The matching should cover the entire input string (not partial). | String,Dynamic Programming,Recursion | Hard | null | 8,973 | 17 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThis problem can be solved by using dynamic programming. We can define dp(i, j) as the boolean value indicating whether the substring s[i:] matches the pattern p[j:].\n# Approach\n<!-- Describe your approach to solving the problem. -->\nWe can solve the problem by defining a recursive function that tries to match s[i:] with p[j:] for all possible i and j indices. The function should return true if and only if it matches the entire string.\n\nTo avoid redundant computation, we can use memoization to store the previously computed results of dp(i, j) in a memo dictionary. The recursive function first checks if the result is already computed in the memo dictionary and returns it if so.\n\nIf j reaches the end of p, the function returns true if and only if i also reaches the end of s.\n\nIf the next character in p is followed by a \'\', the function can match zero or more occurrences of the preceding character. The function recursively tries two cases: either skip the preceding character and the \'\', or match the preceding character and recursively try to match the remaining part of s and p. The function returns true if either case succeeds.\n\nOtherwise, the function simply checks if the next character in p matches the next character in s or is a dot character (\'.\') that matches any character. If so, the function recursively tries to match the remaining part of s and p. The function returns true if both cases succeed.\n# Complexity\n- Time complexity: O(SP), where S is the length of the string s and P is the length of the pattern p. The function tries to match each character in s with each character in p at most once and uses memoization to avoid redundant computation.\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(SP), where S is the length of the string s and P is the length of the pattern p. The function uses memoization to store the previously computed results of dp(i, j).\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def isMatch(self, s: str, p: str) -> bool:\n memo = {}\n \n def dp(i: int, j: int) -> bool:\n if (i, j) in memo:\n return memo[(i, j)]\n \n if j == len(p):\n return i == len(s)\n \n first_match = i < len(s) and (p[j] == s[i] or p[j] == \'.\')\n \n if j + 1 < len(p) and p[j+1] == \'*\':\n ans = dp(i, j+2) or (first_match and dp(i+1, j))\n else:\n ans = first_match and dp(i+1, j+1)\n \n memo[(i, j)] = ans\n return ans\n \n return dp(0, 0)\n``` | 925 |
Regular Expression Matching | regular-expression-matching | Given an input string s and a pattern p, implement regular expression matching with support for '.' and '*' where: The matching should cover the entire input string (not partial). | String,Dynamic Programming,Recursion | Hard | null | 2,431 | 31 | <blockquote>\n<b>Disclaimer:</b> By using any content from this post or thread, you release the author(s) from all liability and warranty of any kind. You are free to use the content freely and as you see fit. Any suggestions for improvement are welcome and greatly appreciated! Happy coding!\n</blockquote>\n\n```swift\nclass Solution {\n func isMatch(_ s: String, _ p: String) -> Bool {\n \n var visit = [[Bool]]()\n let sLength = s.count, pCount = p.count\n \n for _ in 0...sLength + 1 {\n visit.append([Bool](repeating: false, count: pCount + 1))\n }\n \n visit[sLength][pCount] = true\n \n for i in stride(from: sLength, through: 0, by: -1) {\n for j in stride(from: pCount - 1, through: 0, by: -1) {\n \n let arrS = Array(s), arrP = Array(p)\n \n let first = i < sLength && (arrS[i] == arrP[j] || arrP[j] == ".")\n \n if j + 1 < pCount && arrP[j + 1] == "*" {\n visit[i][j] = visit[i][j + 2] || first && visit[i + 1][j]\n } else {\n visit[i][j] = first && visit[i + 1][j + 1]\n }\n }\n }\n return visit[0][0]\n }\n}\n```\n\n<hr>\n\n<p>\n<details>\n<summary><img src="" height="24"> <b>TEST CASES</b></summary>\n\n<br>\n\n<pre>\nResult: Executed 5 tests, with 0 failures (0 unexpected) in 0.080 (0.082) seconds\n</pre>\n\n```swift\nimport XCTest\n\nclass Tests: XCTestCase {\n \n private let solution = Solution()\n \n func test0() {\n XCTAssertFalse(solution.isMatch("aa", "a"))\n }\n func test1() {\n XCTAssertTrue(solution.isMatch("aa", "a*"))\n }\n func test2() {\n XCTAssertTrue(solution.isMatch("ab", ".*"))\n }\n func test3() {\n XCTAssertTrue(solution.isMatch("aab", "c*a*b"))\n }\n func test4() {\n XCTAssertFalse(solution.isMatch("mississippi", "mis*is*p*."))\n }\n}\n\nTests.defaultTestSuite.run()\n```\n</details>\n</p> | 926 |
Regular Expression Matching | regular-expression-matching | Given an input string s and a pattern p, implement regular expression matching with support for '.' and '*' where: The matching should cover the entire input string (not partial). | String,Dynamic Programming,Recursion | Hard | null | 2,089 | 18 | # Recursion (DFS) with Memo (1ms, 100%)\nTC/SC: O(m*n), where m, n is the length of string and pattern.\n[1ms submission]()\n```java\nclass Solution {\n public boolean isMatch(String s, String p) {\n int m = s.length(), n = p.length();\n Boolean[][] M = new Boolean[m+1][n]; // Why Boolean: null indicates the sub-problem not processed yet\n return dfs(s, p, 0, 0, m, n, M); // The problem: to match s[i, m), p[j, n)\n }\n\n // the sub-problem: to match[i, m\n private boolean dfs(String s, String p, int i, int j, int m, int n, Boolean[][] M) {\n if (j == n) return i == m;\n if (M[i][j] != null) return M[i][j];\n\n char c2 = p.charAt(j);\n if (j < n - 1 && p.charAt(j + 1) == \'*\')\n return M[i][j] = dfs(s, p, i, j+2, m, n, M) || // do not match \'x*\' , x means any char or . (use\'*\' as 0 char)\n i < m && match(s.charAt(i), c2) && dfs(s, p, i+1, j, m, n, M); // match 1 char in string for \'*\'\n\n return M[i][j] = i < m && match(s.charAt(i), c2) && dfs(s, p, i+1, j+1, m, n, M); // match 1 char from both sides\n }\n\n private boolean match(char c1, char c2) {\n if (c2 == \'.\') return true;\n return c1 == c2;\n }\n}\n```\n\n# DP, right to left, same as above recursion + memo\nTC/SC: O(m*n), where m, n is the length of string and pattern.\n```java\nclass Solution {\n public boolean isMatch(String s, String p) {\n int m = s.length(), n = p.length();\n boolean[][] M = new boolean[m + 1][n + 1];\n\n for (int i = m; i >= 0; i--) for (int j = n; j >= 0; j--)\n if(j == n) M[i][j] = i == m;\n else if (j + 1 < n && p.charAt(j + 1) == \'*\')\n M[i][j] = M[i][j + 2] || i < m && match(s.charAt(i), p.charAt(j)) && M[i+1][j];\n else // j == cols - 1 || j < cols - 1 && p.charAt(j + 1) != \'*\'\n M[i][j] = i < m && match(s.charAt(i), p.charAt(j)) && M[i+1][j+1];\n\n return M[0][0];\n }\n\n private boolean match(char c1, char c2) {\n return c2 == \'.\' || c1 == c2;\n }\n}\n```\n\n# dp, left to right, 1ms, 100%\nTC/SC: O(m*n), where m, n is the length of string and pattern.\n```java\nclass Solution {\n public boolean isMatch(String str, String ptn) {\n if (ptn.equals(".*")) return true;\n char[] s = str.toCharArray(), p = ptn.toCharArray();\n int m = s.length, n = p.length;\n \n // left to right, add \'\' at the beginning, so dp[i+1][j+1] means match s[0, j] vs p[0, j]\n boolean[][] dp = new boolean[m+1][n+1];\n dp[0][0] = true;\n \n for (int j = 0; j < n; j++) // fill i = 0\n dp[0][j+1] = p[j] == \'*\' && dp[0][j-1]; // "ab" vs "a*b*c*"\n \n for (int i = 0; i < m; i++) for (int j = 0; j < n; j++)\n if (p[j] == \'*\') \n dp[i+1][j+1] = dp[i+1][j-1] || // use \'*\' as 0 char, check back j-1(j-2 in p)\n match(s[i], p[j-1]) && dp[i][j+1]; // use \'*\' to match 1 more char, i must match j-1, s[0,i-1] must match p[0,j-1]\n else dp[i+1][j+1] = match(s[i], p[j]) && dp[i][j]; // normal match\n\n return dp[m][n];\n }\n \n private boolean match(char a, char b) {\n return b == \'.\' || b == a;\n }\n}\n\n/*\n \'\' a * b * c * .\n\'\'[ true, false, true, false, true, false, true, false]\n a[false, true, true, false, true, false, true, true]\n b[false, false, false, true, true, false, true, true]\n x[false, false, false, false, false, false, false, true]\n\n \'\' m i s * i s * i p * .\n\'\'[ true, false, false, false, false, false, false, false, false, false, false, false]\n m[false, true, false, false, false, false, false, false, false, false, false, false]\n i[false, false, true, false, true, false, false, false, false, false, false, false]\n s[false, false, false, true, true, false, false, false, false, false, false, false]\n s[false, false, false, false, true, false, false, false, false, false, false, false]\n i[false, false, false, false, false, true, false, true, false, false, false, false]\n s[false, false, false, false, false, false, true, true, false, false, false, false]\n s[false, false, false, false, false, false, false, true, false, false, false, false]\n i[false, false, false, false, false, false, false, false, true, false, true, false]\n p[false, false, false, false, false, false, false, false, false, true, true, true]\n p[false, false, false, false, false, false, false, false, false, false, true, true]\n i[false, false, false, false, false, false, false, false, false, false, false, true]\n*/\n``` | 928 |
Regular Expression Matching | regular-expression-matching | Given an input string s and a pattern p, implement regular expression matching with support for '.' and '*' where: The matching should cover the entire input string (not partial). | String,Dynamic Programming,Recursion | Hard | null | 5,738 | 28 | Hello!\n\nTo solve this problem we have to go through all possible states. State is defined by **s_index** and **p_index** where they define current char from **s** and **p** strings.\n\nWe return **True** if both **s_index** and **p_index** are out of bounds (it means that we were able to construct **s** string from **p** pattern and there are no chars left in **p**).\n\nIf **s_index** is out of bounds, but **p_index** is not out of bounds it means that we were able to construct **s** string from **p**, but there are some chars left in **p**. We can delete them only, if there are only letter + star pairs left. If there is at least one letter (or dot) without star after it, then we have to return **False**.\n\n\nFor example if we have s = **abc** and p = **abcz(star)b(star)** then we are able to remove **z** and **b** occurencies, because there is **star** after **z** and after **b**, so we return **True**.\n\n\nIf **p_index** is out of bounds while **s_index** is still not out of bounds it means that we are not able to construct **s** from **p**, because there are no letters left, so we return **False**.\n\nThen there are 4 options:\n\n1) If next char in **p** is a **star** and char in **s** match char in **p** (if char in **p** is dot, then we assume that we change dot to the char that is in **s**) then we have two options: we can use current char in **p** to match char in **s** or go to next char in **p** (because next char is a **star**, so we can use previous char 0 or more times).\n\n2) If next char in **p** is a **star** and char in **s** **DOES NOT** match char in **p**, then we can only explore going to the next char in **p** option (so we increase **p_index** by 2, because we have to skip the **star**).\n\n3) If next char in **p** **IS NOT** a **star** and char in **s** match char in **p**, then we can only explore current char option to match char in **s** (so we increase both **p_index** and **s_index** by 1)\n\n4) If next char in **p** **IS NOT** a **star** and char in **s** **DOES NOT** match char in **p**, then there is no option left, so we have to return **False**.\n\nWe will use **memory** to store previous state and at the start of the function we check if current state was already explored. If **yes** then we just return value stored in **memory**.\n\nCode:\n```\nclass Solution:\n def isMatch(self, s: str, p: str) -> bool:\n memory = {}\n \n def explore_state(s_index, p_index):\n if (s_index, p_index) in memory:\n return memory[(s_index, p_index)]\n \n s_index_out_of_border = s_index >= len(s)\n p_index_out_of_border = p_index >= len(p)\n next_char_is_a_star = p_index+1 < len(p) and p[p_index+1] == "*"\n \n if s_index_out_of_border is True:\n if p_index_out_of_border is True:\n return True\n elif next_char_is_a_star is True:\n memory[(s_index, p_index)] = explore_state(s_index, p_index+2)\n return memory[(s_index, p_index)]\n else:\n memory[(s_index, p_index)] = False\n return memory[(s_index, p_index)]\n \n if p_index_out_of_border:\n return False\n \n match = s[s_index] == p[p_index] or p[p_index] == "."\n \n if next_char_is_a_star is True and match is True:\n memory[(s_index, p_index)] = explore_state(s_index, p_index+2) or explore_state(s_index+1, p_index)\n elif next_char_is_a_star is True and match is False:\n memory[(s_index, p_index)] = explore_state(s_index, p_index+2)\n elif next_char_is_a_star is False and match is True:\n memory[(s_index, p_index)] = explore_state(s_index+1, p_index+1)\n elif next_char_is_a_star is False and match is False:\n memory[(s_index, p_index)] = False\n\t\t\t\t\n return memory[(s_index, p_index)]\n \n return explore_state(0, 0)\n```\n\nPlease upvote if it was helpful :)) | 929 |
Regular Expression Matching | regular-expression-matching | Given an input string s and a pattern p, implement regular expression matching with support for '.' and '*' where: The matching should cover the entire input string (not partial). | String,Dynamic Programming,Recursion | Hard | null | 3,690 | 66 | **Idea**\n- Firstly, we brute force by trying all possile options.\n- Then we cache the result to prevent to re-compute sub-problems again.\n```python\nclass Solution:\n def isMatch(self, s: str, p: str) -> bool:\n @lru_cache(None)\n def dp(i, j):\n if j == len(p): # If `j` reach end of pattern `p`\n return i == len(s) # Then it fully matches if and only if `i` reach end of string `s`\n\t\t\t\t\n if j+1 < len(p) and p[j+1] == \'*\':\n ans = dp(i, j+2) # match zero chars\n if i < len(s) and (s[i] == p[j] or p[j] == \'.\'):\n ans = ans or dp(i+1, j) # match 1 char, skip 1 char in s, don\'t skip in p since it can march one or match more characters\n return ans\n if p[j] == \'.\' or i < len(s) and s[i] == p[j]:\n return dp(i+1, j+1) # match 1 char, skip 1 char in both s and p\n return False\n \n return dp(0, 0)\n```\n**Complexity**\n- Time: `O(M*N)`, where `M <= 20` is length of string `s`, `N <= 30` is length of string `p`.\n- Space: `O(M*N)` | 930 |
Regular Expression Matching | regular-expression-matching | Given an input string s and a pattern p, implement regular expression matching with support for '.' and '*' where: The matching should cover the entire input string (not partial). | String,Dynamic Programming,Recursion | Hard | null | 1,674 | 6 | \n# Approach\nIn this optimized version, a memoization technique is used to store the computed results. The isMatchHelper function is called recursively, and its results are stored in the memo map to avoid redundant calculations.\n\nThe function takes two strings, s and p, along with the memoization map as parameters. It first checks if the result for the current input has already been computed. If so, it returns the stored result from the memo map.\n\nThe function then proceeds with the base case and recursive cases, just like the original code. However, after computing the match result, it stores it in the memo map using the key formed from s and p.\n\nBy utilizing memoization, the optimized code avoids redundant recursive calls and improves the overall efficiency of the algorithm.\n\n# C++ Code :\n```\n\nclass Solution {\npublic:\n bool isMatch(string s, string p) {\n // Create a map to store computed results\n unordered_map<string, bool> memo;\n\n return isMatchHelper(s, p, memo);\n }\n\nprivate:\n bool isMatchHelper(const string& s, const string& p, unordered_map<string, bool>& memo) {\n // Check if the result has already been computed\n string key = s + "-" + p;\n if (memo.count(key))\n return memo[key];\n\n // Base case: pattern is empty\n if (p.empty())\n return s.empty();\n\n bool match = false;\n\n // Check if the second character of the pattern is \'*\'\n if (p.length() > 1 && p[1] == \'*\') {\n // Case 1: Skip the current pattern character and \'*\'\n match = isMatchHelper(s, p.substr(2), memo);\n\n // Case 2: Check if the current string character matches the pattern character (or the pattern is a dot)\n if (!match && !s.empty() && (s[0] == p[0] || p[0] == \'.\'))\n match = isMatchHelper(s.substr(1), p, memo);\n }\n else {\n // Check if the current string character matches the pattern character (or the pattern is a dot)\n if (!s.empty() && (s[0] == p[0] || p[0] == \'.\'))\n match = isMatchHelper(s.substr(1), p.substr(1), memo);\n }\n\n // Store the computed result in the memoization map\n memo[key] = match;\n\n return match;\n }\n};\n\n```\n![upvote1.jpg]()\n\n\n\n | 938 |
Regular Expression Matching | regular-expression-matching | Given an input string s and a pattern p, implement regular expression matching with support for '.' and '*' where: The matching should cover the entire input string (not partial). | String,Dynamic Programming,Recursion | Hard | null | 12,919 | 132 | There are two cases to consider:\n\nFirst, the second character of p is `*`, now p string can match any number of character before `*`. `if(isMatch(s, p.substring(2))` means we can match the remaining s string, otherwise, we check if the first character matches or not.\n\nSecond, if the second character is not `*`, we need match character one by one.\n\n\n\n\n public boolean isMatch(String s, String p) {\n if (p.length() == 0) {\n return s.length() == 0;\n }\n if (p.length() > 1 && p.charAt(1) == '*') { // second char is '*'\n if (isMatch(s, p.substring(2))) {\n return true;\n }\n if(s.length() > 0 && (p.charAt(0) == '.' || s.charAt(0) == p.charAt(0))) {\n return isMatch(s.substring(1), p);\n }\n return false;\n } else { // second char is not '*'\n if(s.length() > 0 && (p.charAt(0) == '.' || s.charAt(0) == p.charAt(0))) {\n return isMatch(s.substring(1), p.substring(1));\n }\n return false;\n }\n } | 940 |
Regular Expression Matching | regular-expression-matching | Given an input string s and a pattern p, implement regular expression matching with support for '.' and '*' where: The matching should cover the entire input string (not partial). | String,Dynamic Programming,Recursion | Hard | null | 7,501 | 51 | ```\n def isMatch(self, s: str, p: str) -> bool:\n s, p = \' \'+ s, \' \'+ p\n lenS, lenP = len(s), len(p)\n dp = [[0]*(lenP) for i in range(lenS)]\n dp[0][0] = 1\n\n for j in range(1, lenP):\n if p[j] == \'*\':\n dp[0][j] = dp[0][j-2]\n\n for i in range(1, lenS):\n for j in range(1, lenP):\n if p[j] in {s[i], \'.\'}:\n dp[i][j] = dp[i-1][j-1]\n elif p[j] == "*":\n dp[i][j] = dp[i][j-2] or int(dp[i-1][j] and p[j-1] in {s[i], \'.\'})\n\n return bool(dp[-1][-1])\n```\nRuntime: 56 ms, faster than 70.79% of Python3 online submissions for Regular Expression Matching.\nMemory Usage: 13.9 MB, less than 5.55% of Python3 online submissions for Regular Expression Matching.\n\nSee the [explanation of the idea]() | 941 |
Regular Expression Matching | regular-expression-matching | Given an input string s and a pattern p, implement regular expression matching with support for '.' and '*' where: The matching should cover the entire input string (not partial). | String,Dynamic Programming,Recursion | Hard | null | 5,499 | 67 | **Data structure**\n\nCliche: DP 2D array, `boolean[][] M = new boolean[m + 1][n + 1];` where `M[i][j]` represents if the first `i` characters in `s` match the first `j` characters in `p`.\n\n---\n**Strategy**\n\nInitialization: \n1. `M[0][0] = true`, since empty string matches empty pattern\t\t\n2. `M[i][0] = false`(which is default value of the boolean array) since empty pattern cannot match non-empty string\n3. `M[0][j]`: what pattern matches empty string ""? It should be `#*#*#*#*...` \nAs we can see, **the length of pattern should be even && the char at the odd position(1, 3, ...) should be \\*.**, we will do this check seperately.\n\n---\nInduction rule(very similar to **edit distance**, which we also consider from the end position), 3 cases for the last character in the pattern: `[letter . *]`\n1. If it is a letter, and it can match the last character in `s`, then the result depends on if the 1st `j - 1` characters in `p` can match 1st `i - 1` in `s`, i.e. `M[i][j] = M[i - 1][j - 1]` \n\tIf it is a letter, and it cannot match the last character in `s`, then `M[i][j] = false`; since it is the default value, we don\'t need to do anything here\n2. If it is a dot `.`, then it can definitely match the last character in `s`, so the result depends on if the 1st `j - 1` characters in `p` can match 1st `i - 1` in `s`, i.e. `M[i][j] = M[i - 1][j - 1]` \n3. If it is a star `*` , then it can means **`0 time, or at least 1 time(>= 1)`**:\n 3.1. If it means `0` time, then it does not match anything, then we are using the 1st `j - 2` characters in pattern `p` to match 1st `i` charcaters in `s`, so `M[i][j] = M[i][j - 2]`\n\t3.2. If it means at least `1` time, then `a*` can be treated like `a*a` where the last `a` is just a virtual/dummy character who will be responsible for matching the last character in `s`, so `M[i][j]` can be divided into 2 parts: \n\t1. The dummy character(the 2nd last character in `p`) matches last character in `s`, i.e. `p[j - 2] = s[i]` or `p[j - 2] = \'.\'`. For example:\n\t\t\\###### a\n\t\t###a* a\n\t2. The first `j` characters in `p` match the previous `i - 1` characters in `s`, i.e. `M[i - 1][j]`.\n\nFrom above, we can see that: `M[i][j]` depends on `M[i - 1][j - 1]`, `M[i][j - 2]`, `M[i - 1][j]`, i.e. get `M[i][j]`, we need to know previous elements in `M` which determines in our for loops, `i` goes from `1` to `m - 1`, `j` goes from `1` to `n + 1`\n\n---\n**Final code**\n\n```java\nclass Solution {\n public boolean isMatch(String s, String p) {\n // corner case\n if(s == null || p == null) return false;\n\n int m = s.length();\n int n = p.length();\n \n // M[i][j] represents if the 1st i characters in s can match the 1st j characters in p\n boolean[][] M = new boolean[m + 1][n + 1];\n\n // initialization: \n\t\t// 1. M[0][0] = true, since empty string matches empty pattern\n\t\tM[0][0] = true;\n\t\t\n\t\t// 2. M[i][0] = false(which is default value of the boolean array) since empty pattern cannot match non-empty string\n\t\t// 3. M[0][j]: what pattern matches empty string ""? It should be #*#*#*#*..., or (#*)* if allow me to represent regex using regex :P, \n\t\t// and for this case we need to check manually: \n // as we can see, the length of pattern should be even && the character at the even position should be *, \n\t\t// thus for odd length, M[0][j] = false which is default. So we can just skip the odd position, i.e. j starts from 2, the interval of j is also 2. \n\t\t// and notice that the length of repeat sub-pattern #* is only 2, we can just make use of M[0][j - 2] rather than scanning j length each time \n\t\t// for checking if it matches #*#*#*#*.\n for(int j = 2; j < n + 1; j +=2){\n if(p.charAt(j - 1) == \'*\' && M[0][j - 2]){\n M[0][j] = true;\n }\n }\n \n\t\t// Induction rule is very similar to edit distance, where we also consider from the end. And it is based on what character in the pattern we meet.\n // 1. if p.charAt(j) == s.charAt(i), M[i][j] = M[i - 1][j - 1]\n\t\t// ######a(i)\n\t\t// ####a(j)\n // 2. if p.charAt(j) == \'.\', M[i][j] = M[i - 1][j - 1]\n // \t #######a(i)\n // ####.(j)\n // 3. if p.charAt(j) == \'*\':\n // 1. if p.charAt(j - 1) != \'.\' && p.charAt(j - 1) != s.charAt(i), then b* is counted as empty. M[i][j] = M[i][j - 2]\n // #####a(i)\n // ####b*(j)\n // 2.if p.charAt(j - 1) == \'.\' || p.charAt(j - 1) == s.charAt(i):\n // ######a(i)\n // ####.*(j)\n\t\t//\n\t\t// \t \t #####a(i)\n // \t ###a*(j)\n // 2.1 if p.charAt(j - 1) is counted as empty, then M[i][j] = M[i][j - 2]\n // 2.2 if counted as one or multiple, then the pattern can be expanded with one more a*: "####xa*a*", then M[i][j] = M[i - 1][j]\n\t\t// \t \t #####a(i)\n // \t ###a*a*(j)\n \n\t\t// recap:\n\t\t// M[i][j] = M[i - 1][j - 1]\n\t\t// M[i][j] = M[i - 1][j - 1]\n\t\t// M[i][j] = M[i][j - 2]\n\t\t// M[i][j] = M[i][j - 2]\n // M[i][j] = M[i - 1][j - 2]\n // M[i][j] = M[i - 1][j]\n\t\t// Observation: from above, we can see to get M[i][j], we need to know previous elements in M, i.e. we need to compute them first. \n\t\t// which determines i goes from 1 to m - 1, j goes from 1 to n + 1\n\t\t\n for(int i = 1; i < m + 1; i++){\n for(int j = 1; j < n + 1; j++){\n char curS = s.charAt(i - 1);\n char curP = p.charAt(j - 1);\n if(curS == curP || curP == \'.\'){\n M[i][j] = M[i - 1][j - 1];\n }else if(curP == \'*\'){\n char preCurP = p.charAt(j - 2);\n if(preCurP != \'.\' && preCurP != curS){\n M[i][j] = M[i][j - 2];\n }else{\n M[i][j] = M[i][j - 2] || M[i - 1][j];\n }\n }\n }\n }\n \n return M[m][n];\n }\n}\n```\n\n---\nTime complexity: `O(m*n)`\nSpace complexity: `O(m*n)`\n\n---\n**One more thing**\n\nIf you have any confusion or any opinion on the description, please comment, I will insist on updating it for **at least 100 years**. | 947 |
Regular Expression Matching | regular-expression-matching | Given an input string s and a pattern p, implement regular expression matching with support for '.' and '*' where: The matching should cover the entire input string (not partial). | String,Dynamic Programming,Recursion | Hard | null | 958 | 10 | Can someone let me know why output is true for s="aab" and p="c*a*b" as pattern is not present in input string, so it should output false. It seems I am missing some point about the question. | 948 |
Regular Expression Matching | regular-expression-matching | Given an input string s and a pattern p, implement regular expression matching with support for '.' and '*' where: The matching should cover the entire input string (not partial). | String,Dynamic Programming,Recursion | Hard | null | 7,609 | 19 | (Note: This is part of a series of Leetcode solution explanations. If you like this solution or find it useful, ***please upvote*** this post.)\n***Take care brother, peace, love!***\n\n```\n```\n\nThe best result for the code below is ***0ms / 38.2MB*** (beats 92.04% / 24.00%).\n* *** Python ***\n\n```\n\n def isMatch(self, s: str, p: str) -> bool:\n s, p = \' \'+ s, \' \'+ p\n lenS, lenP = len(s), len(p)\n dp = [[0]*(lenP) for i in range(lenS)]\n dp[0][0] = 1\n\n for j in range(1, lenP):\n if p[j] == \'*\':\n dp[0][j] = dp[0][j-2]\n\n for i in range(1, lenS):\n for j in range(1, lenP):\n if p[j] in {s[i], \'.\'}:\n dp[i][j] = dp[i-1][j-1]\n elif p[j] == "*":\n dp[i][j] = dp[i][j-2] or int(dp[i-1][j] and p[j-1] in {s[i], \'.\'})\n\n return bool(dp[-1][-1])\n\n```\n\n```\n```\n\n```\n```\n***"We are Anonymous. We are legion. We do not forgive. We do not forget. Expect us. Open your eyes.." - \uD835\uDCD0\uD835\uDCF7\uD835\uDCF8\uD835\uDCF7\uD835\uDD02\uD835\uDCF6\uD835\uDCF8\uD835\uDCFE\uD835\uDCFC*** | 950 |
Regular Expression Matching | regular-expression-matching | Given an input string s and a pattern p, implement regular expression matching with support for '.' and '*' where: The matching should cover the entire input string (not partial). | String,Dynamic Programming,Recursion | Hard | null | 52,047 | 108 | 1.'.' is easy to handle. if p has a '.', it can pass any single character in s except '\\0'.\n\n2.'*' is a totally different problem. if p has a '*' character, it can pass any length of first-match characters in s including '\\0'.\n\n\n\n class Solution {\n public:\n bool matchFirst(const char *s, const char *p){\n return (*p == *s || (*p == '.' && *s != '\\0'));\n }\n \n bool isMatch(const char *s, const char *p) {\n \tif (*p == '\\0') return *s == '\\0';\t//empty\n \n \tif (*(p + 1) != '*') {//without *\n \t\tif(!matchFirst(s,p)) return false;\n \t\treturn isMatch(s + 1, p + 1);\n \t} else { //next: with a *\n \tif(isMatch(s, p + 2)) return true; //try the length of 0\n \t\twhile ( matchFirst(s,p) ) //try all possible lengths \n \t\t\tif (isMatch(++s, p + 2))return true;\n \t}\n }\n }; | 955 |
Regular Expression Matching | regular-expression-matching | Given an input string s and a pattern p, implement regular expression matching with support for '.' and '*' where: The matching should cover the entire input string (not partial). | String,Dynamic Programming,Recursion | Hard | null | 4,897 | 41 | We can solve the problem using recursion. We need the helper function to keep track of the current indices of the pattern and the string. The basic condition would be when pattern index reaches the end, then we will check if the string index has also reached the end or not. \n\nNow we will check if the pattern current index matches the string current index character, this would be true either when the characters are equal i.e. s[i]==p[j] or if the p[j]==\'.\' since \'.\' can be replaced by any character. \n\nIf the next pattern character is \'\' that means the current pattern character p[j] could occur 0 or infinite times. So, then there would be two possibility either we can take match the current pattern character with the string and move i by 1 or we can just take zero occurence of the current pattern character and move the pattern character by 2. We will apply the OR condition between these two conditions since if either of them matches then it solves our problem and if next pattern character is not \'\' , then we need to check if the current character matches or not and also move both string and pattern character by 1.\n \nThe time complexity of this brute force approach is O(3^(max(m,n)) and space complexity is O(max(m,n)) where m and n are the length of pattern and string respectively.\n\n```\nclass Solution {\npublic:\n bool isMatch(string s, string p) {\n return helper(s,p,0,0);\n }\n \n bool helper(string s, string p, int i, int j)\n {\n if(j==p.length())\n return i==s.length();\n bool first_match=(i<s.length() && (s[i]==p[j] || p[j]==\'.\' ));\n \n if(j+1<p.length() && p[j+1]==\'*\')\n {\n return (helper(s,p,i,j+2)|| (first_match && helper(s,p,i+1,j) ));\n }\n else\n {\n return (first_match && helper(s,p,i+1,j+1));\n }\n }\n};\n\n```\n\n\n\nWe are actually recomputing the solution for the same subproblems many times. So to avoid that we can initialize dp matrix with all values with being -1. Now if dp[i][j]>=0 then that means this has been already computed so we can return the results here only, thus, it saves time and we don\'t need to recompute that again. Notice that we are saving the results in dp[i][j] in the second last line and this result would always be positive either 0 or 1. \n\nThe time complexity is now O(mn) and space complexity is O(mn) where m and n are the length of pattern and string respectively.\n\n```\nclass Solution {\npublic:\n bool isMatch(string s, string p) {\n vector<vector<int>> dp(s.length()+1,vector<int>(p.length(),-1));\n return helper(s,p,0,0,dp);\n }\n \n bool helper(string s, string p, int i, int j,vector<vector<int>> &dp)\n {\n if(j==p.length())\n return i==s.length();\n if(dp[i][j]>=0)\n return dp[i][j];\n bool first_match=(i<s.length() && (s[i]==p[j] || p[j]==\'.\' ));\n bool ans=0;\n if(j+1<p.length() && p[j+1]==\'*\')\n {\n ans= (helper(s,p,i,j+2,dp)|| (first_match && helper(s,p,i+1,j,dp) ));\n }\n else\n {\n ans= (first_match && helper(s,p,i+1,j+1,dp));\n }\n dp[i][j]=ans;\n return ans;\n }\n};\n```\n\nBottom up solution \n\nWe can derive the bottom up solution from top down approach only. We will make the matrix of length (s.length()+1)* (p.length()+1) . dp[s.length()][p.length()]=1 since both have ended at that point. \n\n```\nclass Solution {\npublic:\n bool isMatch(string s, string p) {\n vector<vector<int>> dp(s.length()+1,vector<int>(p.length()+1,0));\n dp[s.length()][p.length()]=1;\n \n for(int i=s.length();i>=0;i--)\n {\n for(int j=p.length()-1;j>=0;j--)\n {\n bool first_match=(i<s.length() && (p[j]==s[i]|| p[j]==\'.\'));\n if(j+1<p.length() && p[j+1]==\'*\')\n {\n dp[i][j]=dp[i][j+2] || (first_match && dp[i+1][j]);\n }\n else\n {\n dp[i][j]=first_match && dp[i+1][j+1];\n }\n }\n }\n \n return dp[0][0];\n }\n};\n``` | 957 |
Regular Expression Matching | regular-expression-matching | Given an input string s and a pattern p, implement regular expression matching with support for '.' and '*' where: The matching should cover the entire input string (not partial). | String,Dynamic Programming,Recursion | Hard | null | 2,293 | 5 | ```\nclass Solution {\n public boolean isMatch(String s, String p) {\n return s.matches("^" + p + "$");\n }\n}\n``` | 958 |
Regular Expression Matching | regular-expression-matching | Given an input string s and a pattern p, implement regular expression matching with support for '.' and '*' where: The matching should cover the entire input string (not partial). | String,Dynamic Programming,Recursion | Hard | null | 2,232 | 18 | C++ has supported regex since C++11.\n```cpp\nclass Solution {\npublic:\n bool isMatch(string s, string p) {\n return regex_match(s,regex(p));\n }\n};\n```\nHaHa :) | 959 |
Regular Expression Matching | regular-expression-matching | Given an input string s and a pattern p, implement regular expression matching with support for '.' and '*' where: The matching should cover the entire input string (not partial). | String,Dynamic Programming,Recursion | Hard | null | 1,673 | 16 | Easy recursive + memoized and bottom up approach.\n\n**Recursive + Memoized**\n```\nclass Solution {\npublic:\n bool solve(string &s, string &p, int n, int m, vector<vector<int>>&dp){\n if(n == 0 && m == 0) return true;\n if(m==0 && n!=0) return false;\n if(n==0 && m!=0 && p[m-1] == \'*\'){\n for(int i = m-1; i>=0; i-=2){\n if(p[i] != \'*\') return false;\n }\n return true;\n }\n if(n==0 && m!=0) return false;\n if(dp[n][m] != -1) return dp[n][m];\n if(s[n-1] == p[m-1] || p[m-1] == \'.\'){\n return dp[n][m] = solve(s,p,n-1,m-1,dp);\n }\n else if(p[m-1] == \'*\'){\n if(p[m-2] == s[n-1] || p[m-2] == \'.\'){\n return dp[n][m] = solve(s,p,n-1,m,dp) || solve(s,p,n,m-2,dp);\n }\n else{\n return dp[n][m] = solve(s,p,n,m-2,dp);\n }\n }\n return dp[n][m] = false;\n }\n bool isMatch(string s, string p) {\n int n = s.length();\n int m = p.length();\n vector<vector<int>>dp(n+1,vector<int>(m+1,-1));\n return solve(s,p,n,m,dp);\n }\n};\n```\n\n**Tabulation**\n```\nclass Solution {\npublic:\n bool isMatch(string s, string p) {\n int n = s.length();\n int m = p.length();\n vector<vector<int>>dp(n+1,vector<int>(m+1));\n dp[0][0] = 1;\n for(int j=1; j<m+1; j++){\n if(p[j-1] == \'*\'){\n dp[0][j] = dp[0][j-2];\n }\n }\n for(int i=1; i<n+1; i++){\n dp[i][0] = 0;\n }\n for(int i=1; i<n+1; i++){\n for(int j=1; j<m+1; j++){\n if(s[i-1] == p[j-1] || p[j-1] == \'.\'){\n dp[i][j] = dp[i-1][j-1];\n }\n else if(p[j-1] == \'*\'){\n if(p[j-2] == s[i-1] || p[j-2] == \'.\'){\n dp[i][j] = dp[i-1][j] || dp[i][j-2];\n }\n else{\n dp[i][j] = dp[i][j-2];\n }\n }\n else{\n dp[i][j] = 0;\n }\n }\n }\n return dp[n][m];\n }\n};\n``` | 962 |
Regular Expression Matching | regular-expression-matching | Given an input string s and a pattern p, implement regular expression matching with support for '.' and '*' where: The matching should cover the entire input string (not partial). | String,Dynamic Programming,Recursion | Hard | null | 1,690 | 13 | ```\nclass Solution {\npublic:\n bool f(int i,int j,string &s,string &p)\n { \n if(i<0 && j<0) return true; //Both Strings Exhausted\n if(j<0 && i>=0) return false; //p exhausted but s is remaining\n if(i<0 && j>=0) //if s is exhausted by p remains , it will only be true if all charcter in p have *;\n {\n while(j>=0)\n {\n if(p[j]==\'*\') j-=2;\n else return false;\n }\n return true;\n }\n \n if(p[j]==s[i] || p[j]==\'.\') return f(i-1,j-1,s,p);\n \n if(p[j]==\'*\')\n {\n if(p[j-1]!=s[i] && p[j-1]!=\'.\')\n return f(i,j-2,s,p); //Consider * to be empty\n else\n {\n return f(i,j-2,s,p) || f(i-1,j,s,p); \n //These three case are as follows\n //consider * empty\n //consider * length>=1\n }\n }\n return false;\n }\n \n bool isMatch(string s, string p) {\n int n=s.length(),m=p.length();\n return f(n-1,m-1,s,p);\n }\n};\n``` | 967 |
Regular Expression Matching | regular-expression-matching | Given an input string s and a pattern p, implement regular expression matching with support for '.' and '*' where: The matching should cover the entire input string (not partial). | String,Dynamic Programming,Recursion | Hard | null | 7,148 | 42 | Shortest version of Python solution:\n```\ndef isMatch(self, s, p):\n if not p: return not s\n if not s: return len(p) > 1 and p[1] == \'*\' and self.isMatch(s, p[2:])\n Matched = (p[0] == \'.\' or p[0] == s[0])\n if len(p) > 1 and p[1] == \'*\':\n return (Matched and self.isMatch(s[1:], p)) or self.isMatch(s, p[2:])\n return Matched and self.isMatch(s[1:], p[1:])\n```\n\nThe above solutions get AC but slow to run, mainly because repetitive computing and string copy, here\'s the fast version that beats 96%\n```\ndef isMatch(self, s, p):\n memo = {}\n def dp(si, pi):\n if pi >= len(p): return si == len(s)\n if si >= len(s): return pi + 1 < len(p) and p[pi + 1] == \'*\' and dp(si, pi + 2)\n if (si, pi) not in memo:\n matched = p[pi] == \'.\' or p[pi] == s[si]\n if pi + 1 < len(p) and p[pi + 1] == \'*\':\n memo[(si, pi)] = dp(si, pi + 2) or (matched and dp(si + 1, pi))\n else:\n memo[(si, pi)] = matched and dp(si + 1, pi + 1)\n return memo[(si, pi)]\n return dp(0, 0)\n``` | 973 |
Regular Expression Matching | regular-expression-matching | Given an input string s and a pattern p, implement regular expression matching with support for '.' and '*' where: The matching should cover the entire input string (not partial). | String,Dynamic Programming,Recursion | Hard | null | 6,031 | 13 | \n(Note: This is part of a series of Leetcode solution explanations. If you like this solution or find it useful, ***please upvote*** this post.)\n***Take care brother, peace, love!***\n\n```\n```\n\nThe best result for the code below is ***0ms / 3.27MB*** (beats 99.04% / 90.42%).\n* *** Java ***\n\n```\n\npublic boolean isMatch(String s, String p) {\n\t\t/**\n\t\t * This solution is assuming s has no regular expressions.\n\t\t * \n\t\t * dp: res[i][j]=is s[0,...,i-1] matched with p[0,...,j-1];\n\t\t * \n\t\t * If p[j-1]!=\'*\', res[i][j] = res[i-1][j-1] &&\n\t\t * (s[i-1]==p[j-1]||p[j-1]==\'.\'). Otherwise, res[i][j] is true if\n\t\t * res[i][j-1] or res[i][j-2] or\n\t\t * res[i-1][j]&&(s[i-1]==p[j-2]||p[j-2]==\'.\'), and notice the third\n\t\t * \'or\' case includes the first \'or\'.\n\t\t * \n\t\t * \n\t\t * Boundaries: res[0][0]=true;//s=p="". res[i][0]=false, i>0.\n\t\t * res[0][j]=is p[0,...,j-1] empty, j>0, and so res[0][1]=false,\n\t\t * res[0][j]=p[j-1]==\'*\'&&res[0][j-2].\n\t\t * \n\t\t * O(n) space is enough to store a row of res.\n\t\t */\n\n\t\tint m = s.length(), n = p.length();\n\t\tboolean[] res = new boolean[n + 1];\n\t\tres[0] = true;\n\n\t\tint i, j;\n\t\tfor (j = 2; j <= n; j++)\n\t\t\tres[j] = res[j - 2] && p.charAt(j - 1) == \'*\';\n\n\t\tchar pc, sc, tc;\n\t\tboolean pre, cur; // pre=res[i - 1][j - 1], cur=res[i-1][j]\n\n\t\tfor (i = 1; i <= m; i++) {\n\t\t\tpre = res[0];\n\t\t\tres[0] = false;\n\t\t\tsc = s.charAt(i - 1);\n\n\t\t\tfor (j = 1; j <= n; j++) {\n\t\t\t\tcur = res[j];\n\t\t\t\tpc = p.charAt(j - 1);\n\t\t\t\tif (pc != \'*\')\n\t\t\t\t\tres[j] = pre && (sc == pc || pc == \'.\');\n\t\t\t\telse {\n\t\t\t\t\t// pc == \'*\' then it has a preceding char, i.e. j>1\n\t\t\t\t\ttc = p.charAt(j - 2);\n\t\t\t\t\tres[j] = res[j - 2] || (res[j] && (sc == tc || tc == \'.\'));\n\t\t\t\t}\n\t\t\t\tpre = cur;\n\t\t\t}\n\t\t}\n\n\t\treturn res[n];\n\t}\n\n```\n\n```\n```\n\n```\n```\n\nThe best result for the code below is ***0ms / 10MB*** (beats 100.00% / 95.49%).\n* *** Python ***\n\n```\n\ncache = {}\ndef isMatch(self, s, p):\n if (s, p) in self.cache:\n return self.cache[(s, p)]\n if not p:\n return not s\n if p[-1] == \'*\':\n if self.isMatch(s, p[:-2]):\n self.cache[(s, p)] = True\n return True\n if s and (s[-1] == p[-2] or p[-2] == \'.\') and self.isMatch(s[:-1], p):\n self.cache[(s, p)] = True\n return True\n if s and (p[-1] == s[-1] or p[-1] == \'.\') and self.isMatch(s[:-1], p[:-1]):\n self.cache[(s, p)] = True\n return True\n self.cache[(s, p)] = False\n return False\n\n```\n\n```\ndef isMatch(self, s, p):\n dp = [[False] * (len(s) + 1) for _ in range(len(p) + 1)]\n dp[0][0] = True\n for i in range(1, len(p)):\n dp[i + 1][0] = dp[i - 1][0] and p[i] == \'*\'\n for i in range(len(p)):\n for j in range(len(s)):\n if p[i] == \'*\':\n dp[i + 1][j + 1] = dp[i - 1][j + 1] or dp[i][j + 1]\n if p[i - 1] == s[j] or p[i - 1] == \'.\':\n dp[i + 1][j + 1] |= dp[i + 1][j]\n else:\n dp[i + 1][j + 1] = dp[i][j] and (p[i] == s[j] or p[i] == \'.\')\n return dp[-1][-1]\n```\n\n```\n```\n\n```\n```\n\nThe best result for the code below is ***0ms / 23.7MB*** (beats 59.24% / 60.42%).\n* *** C++ ***\n\n\nWe can solve the problem using recursion. We need the helper function to keep track of the current indices of the pattern and the string. The basic condition would be when pattern index reaches the end, then we will check if the string index has also reached the end or not.\n\nNow we will check if the pattern current index matches the string current index character, this would be true either when the characters are equal i.e. s[i]==p[j] or if the p[j]==\'.\' since \'.\' can be replaced by any character.\n\nIf the next pattern character is \'\' that means the current pattern character p[j] could occur 0 or infinite times. So, then there would be two possibility either we can take match the current pattern character with the string and move i by 1 or we can just take zero occurence of the current pattern character and move the pattern character by 2. We will apply the OR condition between these two conditions since if either of them matches then it solves our problem and if next pattern character is not \'\' , then we need to check if the current character matches or not and also move both string and pattern character by 1.\n\nThe time complexity of this brute force approach is O(3^(max(m,n)) and space complexity is O(max(m,n)) where m and n are the length of pattern and string respectively.\n\n```\nclass Solution {\npublic:\n bool isMatch(string s, string p) {\n return helper(s,p,0,0);\n }\n \n bool helper(string s, string p, int i, int j)\n {\n if(j==p.length())\n return i==s.length();\n bool first_match=(i<s.length() && (s[i]==p[j] || p[j]==\'.\' ));\n \n if(j+1<p.length() && p[j+1]==\'*\')\n {\n return (helper(s,p,i,j+2)|| (first_match && helper(s,p,i+1,j) ));\n }\n else\n {\n return (first_match && helper(s,p,i+1,j+1));\n }\n }\n};\n```\n\nWe are actually recomputing the solution for the same subproblems many times. So to avoid that we can initialize dp matrix with all values with being -1. Now if dp[i][j]>=0 then that means this has been already computed so we can return the results here only, thus, it saves time and we don\'t need to recompute that again. Notice that we are saving the results in dp[i][j] in the second last line and this result would always be positive either 0 or 1.\n\nThe time complexity is now O(mn) and space complexity is O(mn) where m and n are the length of pattern and string respectively.\n\n```\nclass Solution {\npublic:\n bool isMatch(string s, string p) {\n vector<vector<int>> dp(s.length()+1,vector<int>(p.length(),-1));\n return helper(s,p,0,0,dp);\n }\n \n bool helper(string s, string p, int i, int j,vector<vector<int>> &dp)\n {\n if(j==p.length())\n return i==s.length();\n if(dp[i][j]>=0)\n return dp[i][j];\n bool first_match=(i<s.length() && (s[i]==p[j] || p[j]==\'.\' ));\n bool ans=0;\n if(j+1<p.length() && p[j+1]==\'*\')\n {\n ans= (helper(s,p,i,j+2,dp)|| (first_match && helper(s,p,i+1,j,dp) ));\n }\n else\n {\n ans= (first_match && helper(s,p,i+1,j+1,dp));\n }\n dp[i][j]=ans;\n return ans;\n }\n};\n```\n\nBottom up solution\n\nWe can derive the bottom up solution from top down approach only. We will make the matrix of length (s.length()+1)* (p.length()+1) . dp[s.length()][p.length()]=1 since both have ended at that point.\n\n```\nclass Solution {\npublic:\n bool isMatch(string s, string p) {\n vector<vector<int>> dp(s.length()+1,vector<int>(p.length()+1,0));\n dp[s.length()][p.length()]=1;\n \n for(int i=s.length();i>=0;i--)\n {\n for(int j=p.length()-1;j>=0;j--)\n {\n bool first_match=(i<s.length() && (p[j]==s[i]|| p[j]==\'.\'));\n if(j+1<p.length() && p[j+1]==\'*\')\n {\n dp[i][j]=dp[i][j+2] || (first_match && dp[i+1][j]);\n }\n else\n {\n dp[i][j]=first_match && dp[i+1][j+1];\n }\n }\n }\n \n return dp[0][0];\n }\n};\n```\n\n```\n```\n\n```\n```\n\nThe best result for the code below is ***0ms / 78MB*** (beats 100.00% / 100.00%).\n* *** JavaScript ***\n\n\n```\n\nfunction isMatch(s, p) {\n var lenS = s.length;\n var lenP = p.length;\n var map = {};\n\n return check(0, 0);\n\n function check(idxS, idxP) {\n if (map[idxS + \':\' + idxP] !== undefined) return map[idxS + \':\' + idxP];\n if (idxS > lenS) return false;\n if (idxS === lenS && idxP === lenP) return true;\n\n if (p[idxP] === \'.\' || p[idxP] === s[idxS]) {\n map[idxS + \':\' + idxP] = p[idxP + 1] === \'*\' ?\n check(idxS + 1, idxP) || check(idxS, idxP + 2) :\n check(idxS + 1, idxP + 1);\n } else {\n map[idxS + \':\' + idxP] = p[idxP + 1] === \'*\' ?\n check(idxS, idxP + 2) : false;\n }\n return map[idxS + \':\' + idxP];\n }\n}\n\n```\n\n```\nconst isMatch = (string, pattern) => {\n // early return when pattern is empty\n if (!pattern) {\n\t\t// returns true when string and pattern are empty\n\t\t// returns false when string contains chars with empty pattern\n return !string;\n }\n \n\t// check if the current char of the string and pattern match when the string has chars\n const hasFirstCharMatch = Boolean(string) && (pattern[0] === \'.\' || pattern[0] === string[0]);\n\n // track when the next character * is next in line in the pattern\n if (pattern[1] === \'*\') {\n // if next pattern match (after *) is fine with current string, then proceed with it (s, p+2). That\'s because the current pattern may be skipped.\n // otherwise check hasFirstCharMatch. That\'s because if we want to proceed with the current pattern, we must be sure that the current pattern char matches the char\n\t\t// If hasFirstCharMatch is true, then do the recursion with next char and current pattern (s+1, p). That\'s because current char matches the pattern char. \n return (\n isMatch(string, pattern.slice(2)) || \n (hasFirstCharMatch && isMatch(string.slice(1), pattern))\n );\n }\n \n // now we know for sure that we need to do 2 simple actions\n\t// check the current pattern and string chars\n\t// if so, then can proceed with next string and pattern chars (s+1, p+1)\n return hasFirstCharMatch ? isMatch(string.slice(1), pattern.slice(1)) : false;\n};\n```\n\n```\n```\n\n```\n```\n\nThe best result for the code below is ***0ms / 15.23MB*** (beats 89.94% / 90.99%).\n* *** Python3 ***\n\n\nIf dp[i][j] == False, it means s[:i] doesn\'t match p[:j]\u2028If dp[i][j] == True, it means s[:i] matches p[:j]\u2028\'.\' Matches any single character.\u2028\'\' Matches zero or more of the preceding element.\u2028s = "aa"\u2028p = "a"\u2028Output: true\u2028Explanation: \'*\' means zero or more of the preceding element, \'a\'. Therefore, by repeating \'a\' once, it becomes "aa".\n\n```\ns = "aab"\np = "c*a*b"\n c * a * b\ndp = [ \n [True, False, True, False, True, False], \n\t a [False, False, False, True, True, False], \n\t a [False, False, False, False, True, False], \n\t b\t[False, False, False, False, False, True]] \n\t\n# Case 1 p[:j] == alphabet or \'.\'\n# Case 2: p[:j] is \'*\'\n\t# Case 2a: p[:j-1] doesn\'t need a \'*\' to match the substring s[:i]\n\t #1 p[:j-1] ==s[:i] dp[i][j] =d[i-1][j]\n\t\t 0 a * 0 a a \n 0 0\n a T ---> a\n a T a T\n\t\t#2 p[:j-1] == \'.\' dp[i][j]=dp[i][j-2]\n\t\t 0 a b *\n 0 \n a T T \n \n\t# Case 2b: p[:j] needs \'*\' to match the substring s[:i]\n```\n```\n # about *:\n case 1: 0 preceding element\n case 2: 1 or more preceding element\n\t\t\t the preceding element could be a \'.\' or an alpharbet.\n\t\t\t more proceding element is easy to handle once you use dynamic programming. \n ```\n ```\nclass Solution:\n def isMatch(self, s, p):\n n = len(s)\n m = len(p)\n dp = [[False for _ in range (m+1)] for _ in range (n+1)]\n dp[0][0] = True\n for c in range(1,m+1):\n if p[c-1] == \'*\' and c > 1:\n dp[0][c] = dp[0][c-2]\n for r in range(1,n+1):\n for c in range(1,m+1):\n if p[c-1] == s[r-1] or p[c-1] == \'.\':\n dp[r][c] = dp[r-1][c-1]\n elif c > 1 and p[c-1] == \'*\':\n if p[c-2] ==\'.\' or s[r-1]==p[c-2]:\n dp[r][c] =dp[r][c-2] or dp[r-1][c]\n else:\n dp[r][c] = dp[r][c-2]\n return dp[n][m]\n```\n\n```\n```\n\n```\n```\n\nThe best result for the code below is ***0ms / 33.33MB*** (beats 99.00% / 60.12%).\n* *** Kotlin ***\n\n\n```\n\nclass Solution {\n fun isMatch(s: String, p: String): Boolean {\n return isMatchRecursive(s, p)\n }\n \n fun isMatchRecursive(s: String, p: String): Boolean {\n if (p == "") return s == ""\n \n if (p.length >= 2 && p[1] == \'*\' && s.length > 0 && (s[0] == p[0] || p[0] == \'.\')) {\n return isMatchRecursive(s.substring(1), p) || isMatchRecursive(s, p.substring(2))\n } else if (p.length >= 2 && p[1] == \'*\') {\n return isMatchRecursive(s, p.substring(2))\n }\n \n return if (s.length > 0) {\n if (s[0] == p[0] || p[0] == \'.\') {\n isMatchRecursive(s.substring(1), p.substring(1))\n } else {\n false\n }\n } else {\n false\n }\n }\n}\n\n```\n\n```\nclass Solution {\n fun isMatch(s: String, p: String): Boolean {\n return p.toRegex().matches(s)\n }\n}\n```\n\n```\n```\n\n```\n```\n\nThe best result for the code below is ***0ms / 13.17MB*** (beats 79.34% / 99.92%).\n* *** Swift ***\n\n\n```\n\nclass Solution {\n func isMatch(_ s: String, _ p: String) -> Bool {\n \n var visit = [[Bool]]()\n let sLength = s.count, pCount = p.count\n \n for _ in 0...sLength + 1 {\n visit.append([Bool](repeating: false, count: pCount + 1))\n }\n \n visit[sLength][pCount] = true\n \n for i in stride(from: sLength, through: 0, by: -1) {\n for j in stride(from: pCount - 1, through: 0, by: -1) {\n \n let arrS = Array(s), arrP = Array(p)\n \n let first = i < sLength && (arrS[i] == arrP[j] || arrP[j] == ".")\n \n if j + 1 < pCount && arrP[j + 1] == "*" {\n visit[i][j] = visit[i][j + 2] || first && visit[i + 1][j]\n } else {\n visit[i][j] = first && visit[i + 1][j + 1]\n }\n }\n }\n return visit[0][0]\n }\n}\n\n```\n\n```\n```\n\n```\n```\n\nThe best result for the code below is ***0ms / 62.07MB*** (beats 99.99% / 99.99%).\n* *** PHP ***\n\n\n```\nclass Solution {\n\n /**\n * @param String $s\n * @param String $p\n * @return Boolean\n */\n function isMatch($s, $p) {\n return preg_match("/^{$p}$/", $s);\n }\n}\n```\n\nHowever, that kinda defeats the point of the exercise, which is to show you can write a regex matcher. So here is my solution.\n```\nclass Solution {\n \n const WILDCARD = "*";\n const ANY_CHAR = ".";\n \n /**\n * @param String $string\n * @param String $pattern\n * @return Boolean\n */\n function isMatch($string, $pattern) \n {\n if (!$pattern) {\n return !$string;\n }\n \n $matchResult = $string && ($string[0] === $pattern[0] || self::ANY_CHAR === $pattern[0]);\n $greedyMatch = !empty($pattern[1]) && $pattern[1] == self::WILDCARD;\n\n if (!$matchResult && !$greedyMatch) {\n return false;\n }\n\n if ($greedyMatch) {\n return ($matchResult && $this->isMatch(substr($string, 1), $pattern)) || $this->isMatch($string, substr($pattern, 2));\n }\n \n return $matchResult && $this->isMatch(substr($string, 1), substr($pattern, 1));\n }\n}\n```\n\n```\n```\n\n```\n```\n\nThe best result for the code below is ***0ms / 1.17MB*** (beats 99.64% / 99.92%).\n* *** C ***\n\n\n```\n\nbool match(char* s, char* p) {\n return (s[0] == p[0]) || (p[0] == \'.\' && s[0]);\n}\n\nbool isMatch(char * s, char * p){\n if (!p[0]) return !s[0];\n if (p[1] == \'*\') return isMatch(s, p+2) || match(s, p) && isMatch(s+1, p);\n if (p[0] == \'.\') return s[0] && isMatch(s+1, p+1);\n return match(s, p) && isMatch(s+1, p+1);\n}\n\n```\n\n```\n```\n\n```\n```\n\n***"Open your eyes. Expect us." - \uD835\uDCD0\uD835\uDCF7\uD835\uDCF8\uD835\uDCF7\uD835\uDD02\uD835\uDCF6\uD835\uDCF8\uD835\uDCFE\uD835\uDCFC***\n | 975 |
Regular Expression Matching | regular-expression-matching | Given an input string s and a pattern p, implement regular expression matching with support for '.' and '*' where: The matching should cover the entire input string (not partial). | String,Dynamic Programming,Recursion | Hard | null | 733 | 6 | ## Regex Matching\n\nLeetcode: [10. Regular Expression Matching]().\n\nThe description of this problem is clear:\n\n- Given an input string `s` and a pattern `p`, implement regular expression matching with support for `\'.\'` and `\'*\'`.\n - `\'.\'` matches any single character.\n - `\'*\'` matches zero or more of the preceding element.\n - It is guaranteed for each appearance of the character `\'*\'`, there will be a previous valid character to match.\n- The matching should cover the **entire** input string (not partial).\n\n\n\n## Dynamic Programming\n\nA popular solution is using dynamic programming. \n\nLet `dp[i, j]` be true if `s[1 ... i]` matches `p[1 ... j]`. And the state equations will be:\n\n- `dp[i, j] = dp[i-1, j-1]` if `p[j] == \'.\' || p[j] == s[i] `\n- `dp[i, j] = dp[i, j-2]` if `p[j] == \'*\'`, which means that we skip `"x*"` and matching nothing (or match `x` for zero times).\n- `dp[i, j] = dp[i-1, j] && (s[i] == p[j-1] || p[j-1] == \'.\')`, if `p[j] == \'*\'`, which means that `"x*"` repeats >=1 times, and `x` can be character or a dot `\'.\'`.\n\nPlease note that the index of `s` and `p` in the program start with `0`, which is a little different from the state equations above.\n\n```cpp\nclass Solution \n{\npublic:\n bool isMatch(string s, string p) \n {\n int slen = s.length(), plen = p.length();\n vector<vector<bool>> dp(slen + 1, vector<bool>(plen + 1, false));\n dp[0][0] = true;\n // Note that s = "", can match p = "a*b*c*", hence `i` should be start with 0\n for (int i = 0; i <= slen; ++i)\n {\n for (int j = 1; j <= plen; ++j)\n {\n /* the index of \'*\' in `p`, must be >= 1, otherwise `p` is invalid,\n * i.e. (j - 1 >= 1) ==> (j >= 2)\n */\n if (p[j - 1] == \'*\')\n {\n dp[i][j] = dp[i][j - 2] || \n (i > 0 && dp[i - 1][j] && (s[i - 1] == p[j - 2] || p[j - 2] == \'.\'));\n }\n else if (i > 0 && (p[j - 1] == \'.\' || s[i - 1] == p[j - 1]))\n {\n dp[i][j] = dp[i - 1][j - 1];\n }\n \n }\n }\n return dp[slen][plen];\n }\n};\n```\n\n\n\n\n\n## DFA\n\nHere I want to show how to solve this problem by **deterministic finite automaton (DFA)**.\n\nPlease note that you should know the concept of DFA before you read this article.\n\nFor a pattern `p = "a.b*c"`, we can construct such a DFA:\n\n<img src="" style="background: #fff"/>\n\nThe `\'$\'` sign means that, we do not need any character to reach next state, since `\'*\'` matches **zero** or more of the preceding element. \n\nDFA can be represented by a graph in the program.\n\n- `state` points to the last valid state we can reach.\n- `state = 0` denote the invalid state, since `0` is the default value of `unordered_map`. Of course, we can use `-1`.\n\n```cpp\nclass Solution \n{\npublic:\n unordered_map<int, unordered_map<char, int>> automaton;\n int state = 1;\n bool isMatch(string s, string p)\n {\n int plen = p.length();\n for (int i = 0; i < plen; ++i)\n {\n char x = p[i];\n if (\'a\' <= x && x <= \'z\' || x == \'.\')\n automaton[state][x] = state + 1, state += 1;\n else if (x == \'*\' && i > 0)\n {\n automaton[state - 1][p[i - 1]] = state - 1; // match >= 1 p[i - 1]\n automaton[state - 1][\'$\'] = state; // match zero p[i - 1]\n }\n }\n return match(s, 0, 1);\n }\n \n /* idx - we are matching s[idx]\n * cur - current state in automaton\n */\n bool match(string &s, int idx, int cur)\n {\n int n = s.length();\n \n if (cur == 0) return false;\n if (idx >= n && cur == state) return true;\n \n if (idx < n)\n {\n /* Each node in automaton, has no more than 3 edges,\n * \'$\' means matching no character, hence still use `idx` in next matching.\n * For example, p = "a.b*c", s = "aac", we should output true,\n * match(s, idx, s3) means that, we skip matching "b*" in automaton (matched zero \'b\').\n */\n int s1 = automaton[cur][s[idx]];\n int s2 = automaton[cur][\'.\'];\n int s3 = automaton[cur][\'$\'];\n return match(s, idx + 1, s1) || match(s, idx + 1, s2) || match(s, idx, s3);\n }\n else if (idx == n) \n {\n /* May be the last edge of automaton is `state[n-1] -- $ --> state[n]`\n * e.g. s = "aa", p = "a*"\n */\n return match(s, idx, automaton[cur][\'$\']);\n }\n return false;\n }\n};\n```\n\n\n\nAt last, we can also pass this problem by STL library :-D.\n\n```cpp\nclass Solution {\npublic:\n bool isMatch(string s, string p) {\n return regex_match(s, regex(p));\n }\n};\n```\n\n\n | 977 |
Regular Expression Matching | regular-expression-matching | Given an input string s and a pattern p, implement regular expression matching with support for '.' and '*' where: The matching should cover the entire input string (not partial). | String,Dynamic Programming,Recursion | Hard | null | 4,444 | 44 | I will use this post as a more detailed explanation of my solution.\n\n```\nclass Solution {\n public boolean isMatch(String s, String p) {\n /*\n dp[i][j] = whether the first i-character sequence in s matches the first j-character sequence in p\n we set dp[0][0] = true, because the first 0 character in s always matches the first 0 character in p\n \n For better readability, I will make this notation:\n s[i] means the i-th character in string s.\n For example, s = "abc", s[1] = \'a\', s[2] = \'b\', s[3] = \'c\'\n \n The above notation will give us a consistent view of the relationship between dp[i][j], s[i] and p[j].\n For example, if we have s = "ab", p = "ac", we will get:\n dp[0][0] = true (default base case); \n dp[1][0] = false (because s[1...1] = "a" and p[0] does not exist based on our notation);\n dp[1][1] = true (because s[1...1] = "a" and p[1...1] = "a", they match);\n dp[2][0] = false (because s[1...2] = "ab" and p[0] does not exist);\n dp[2][1] = false (because s[1...2] = "ab" and p[1...1] = "a", they don\'t match);\n dp[2][2] = false (because s[1...2] = "ab" and p[1...2] = "ac", they don\'t match);\n As a result, dp[s.length()][p.length()] = dp[2][2] = false.\n We will return false, meaning that s does not match p.\n \n With the above notation, we have:\n If we are currently at s[i] and p[j]:\n 1. if (p[j] == s[i])\n - The i-th character in s matches the j-th character in p, so dp[i][j] now depends on dp[i-1][j-1]\n - Therefore we have dp[i][j] = dp[i-1][j-1]\n 2. if (p[j] == \'.\')\n - The j-th character in p is \'.\', meaning that it can represent any single character, it is the same as 1\n - Therefore we have dp[i][j] = dp[i-1][j-1]\n 3. if (p[j] == \'*\')\n - The j-th character in p is \'*\', meaning that the character of p[j-1] can be repeated multiple times or can be not exising\n - Now we will need to check p[j-1]:\n 3.1 - if (p[j-1] != s[i] AND p[j-1] != \'.\')\n - In this case, the only possible scenario that s[1...i] matches p[1...j] is that s[1...i] matches p[1...j-2]\n - For example, when i = 2 and j = 4, p[1...4] = "abc*", s[1...2] = "ab":\n - p[4] = \'*\', p[4-1] = p[3] = \'c\' while s[2] = \'b\', so p[3] != s[2] and p[3] != \'.\'\n - But since s[1...2] matches p[1...2], s[1...2] still matches p[1...4] in this case\n - Therefore we have dp[i][j] = dp[i][j-2]\n 3.2 - if (p[j-1] == s[i] OR p[j-1] == \'.\')\n 3.2.1 - if (s[1...i] does not match p[1...j-2])\n - In this case, we know that the character s[i] needs to match the character p[j-1]. Thus as long as s[1...i-1] matches p[1...j], we will have s[1....i] matches p[1...j]\n - For example, when i = 3 and j = 4, p[1...4] = "abc*", s[1...3] = "abc":\n - s[1...2] matches p[1...4] because of 3.1: since we have "c*", we can treat p = "abc*" as equivalent to p = "ab" when matching "ab", because c* means c can be repeating or not existing\n - since s[3] = \'c\' which is the same as p[3], it matches at s[3]\n - Another example, when i = 4 and j = 4, p[1...4] = "abc*", s[1...4] = "abcc"\n - From previous example, we know that dp[3][4] is true. So since we have "c*", c can repeat multiple times. Therefore as long as s[4] = \'c\' = p[4-1], we know that dp[4][4] = dp[3][4] = true\n - Therefore we have dp[i][j] = dp[i-1][j]\n - I noticed that some other solutions also include dp[i][j-1] as a condition where s[i] only appears once, but I think it is redundant here because dp[i-1][j] can be applied to both one appearance and multiple appearances. But if we have another quantifier like "?" which only allows one appearance, we should include dp[i][j-1].\n 3.2.2 - if (s[1...i] does match p[1...j-2])\n - In this case, we actually don\'t really need to care about p[j-1...j] because the previous sequence matches, and we can now treat p[j-1...j] as matching nothing.\n - Therefore we have dp[i][j] = dp[i][j-2]\n \n \n To construct the boolean[][] dp array, we also need an initialization on "nothing in s" (s[0]) matching p[1...j]:\n 1. dp[0][0] = true\n 2. dp[0][i] = true if p[i+1] == \'*\' AND dp[0][i-2] == true, otherwise false\n For example: \n p = "a*b*"\n dp[0][0] = true;\n dp[0][1] = false (because s[0] does not exist while p[1...1] = "a");\n dp[0][2] = true (because s[0] does not exist, but p[1...2] = "a*" meaning that a can be repeating or not existing);\n dp[0][3] = false (because s[0] does not exist while p[1...3] = "a*b");\n dp[0][4] = true (because s[0] does not exist while p[1...4] = "a*b*", b can be not existing, and dp[0][2] is true meaning that we already have a match for anything before p[3...4]);\n */\n \n if (s == null || p == null) {\n return false;\n }\n boolean[][] dp = new boolean[s.length() + 1][p.length() + 1]; // by default every element is false\n dp[0][0] = true;\n char[] string = new char[s.length() + 1];\n char[] pattern = new char[p.length() + 1];\n // we don\'t care about what character is on index 0. It is a way to make our view of index in dp[][] and string[] and pattern[] consistent. Our process starts at index==1 for string and pattern.\n string[0] = (char) 0;\n pattern[0] = (char) 0;\n for (int i = 0; i < s.length(); ++i) {\n string[i+1] = s.charAt(i);\n }\n for (int i = 0; i < p.length(); ++i) {\n pattern[i+1] = p.charAt(i);\n }\n\n dp[0][0] = true;\n // initialization of dp, for base cases\n for (int i = 1; i < pattern.length; ++i) {\n // here we assume that pattern[1] (i.e. p.charAt(0)) will never be \'*\' based on the description of the problem which states that \'*\' matches zero or more of the preceding element, so it must have a preceding element otherwise it is not a valid input.\n if (pattern[i] == \'*\' && dp[0][i-2]) {\n dp[0][i] = true;\n }\n }\n \n for (int i = 1; i < string.length; ++i) {\n for (int j = 1; j < pattern.length; ++j) {\n if (pattern[j] == string[i] || pattern[j] == \'.\') {\n // scenario 1 and 2: current character matches, we just need to know if previous sequence matches or not\n dp[i][j] = dp[i-1][j-1]; \n } else if (pattern[j] == \'*\') {\n if (pattern[j-1] != string[i] && pattern[j-1] != \'.\') {\n // scenario 3.1: we should treat pattern[j-1...j] as matching nothing in string, it is valid because pattern[j] == \'*\', therefore we want to know if string[1...i] matches pattern[1...j-2]\n dp[i][j] = dp[i][j-2];\n } else {\n // scenario 3.2.1 and 3.2.2: since pattern won\'t change, we just need to make sure one of 3.2.1 and 3.2.2 is true for dp is true: either pattern[j-1...j] matches string[i], or pattern[j-1...j] matches nothing in string\n // if pattern[j-1] matches string[i], we just need to know if string[i-1] matches pattern[j]: abc* matches abc and abcc, if we want to know if abc matches abc*, we just need to know if ab matches abc*; if we want to know if abcc matches abc*, we just need to know if abc matches abc*\n // if pattern[j-1] matches nothing in string, it is scenario 3.1\n dp[i][j] = dp[i-1][j] || dp[i][j-2];\n }\n }\n }\n }\n return dp[s.length()][p.length()];\n }\n}\n``` | 980 |
Regular Expression Matching | regular-expression-matching | Given an input string s and a pattern p, implement regular expression matching with support for '.' and '*' where: The matching should cover the entire input string (not partial). | String,Dynamic Programming,Recursion | Hard | null | 1,992 | 13 | **C:**\n```\nbool match(char* s, char* p) {\n return (s[0] == p[0]) || (p[0] == \'.\' && s[0]);\n}\n\nbool isMatch(char * s, char * p){\n if (!p[0]) return !s[0];\n if (p[1] == \'*\') return isMatch(s, p+2) || match(s, p) && isMatch(s+1, p);\n if (p[0] == \'.\') return s[0] && isMatch(s+1, p+1);\n return match(s, p) && isMatch(s+1, p+1);\n}\n```\n**C++:**\n```\nclass Solution {\npublic:\n bool match(int s_idx, int p_idx) {\n return (ss[s_idx] == pp[p_idx]) || (pp[p_idx] == \'.\' && ss[s_idx]);\n }\n \n bool rec(int s_idx, int p_idx) {\n if (!pp[p_idx]) return !ss[s_idx];\n if (pp[p_idx+1] == \'*\') return rec(s_idx, p_idx+2) || match(s_idx, p_idx) && rec(s_idx+1, p_idx);\n if (pp[p_idx] == \'.\') return ss[s_idx] && rec(s_idx+1, p_idx+1);\n return match(s_idx, p_idx) && rec(s_idx+1, p_idx+1);\n }\n \n bool isMatch(string s, string p) {\n ss = s, pp = p;\n return rec(0, 0);\n \n }\n \nprivate:\n string ss, pp;\n};\n```\n**Like it? please upvote!** | 981 |
Regular Expression Matching | regular-expression-matching | Given an input string s and a pattern p, implement regular expression matching with support for '.' and '*' where: The matching should cover the entire input string (not partial). | String,Dynamic Programming,Recursion | Hard | null | 2,123 | 5 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def isMatch(self, s: str, p: str) -> bool:\n return re.match(fr"^{p}$", s) is not None\n``` | 983 |