question_slug
stringlengths
3
77
title
stringlengths
1
183
slug
stringlengths
12
45
summary
stringlengths
1
160
author
stringlengths
2
30
certification
stringclasses
2 values
created_at
stringdate
2013-10-25 17:32:12
2025-04-12 09:38:24
updated_at
stringdate
2013-10-25 17:32:12
2025-04-12 09:38:24
hit_count
int64
0
10.6M
has_video
bool
2 classes
content
stringlengths
4
576k
upvotes
int64
0
11.5k
downvotes
int64
0
358
tags
stringlengths
2
193
comments
int64
0
2.56k
count-substrings-that-differ-by-one-character
[Java] Brute Force: Generating All Substrings
java-brute-force-generating-all-substrin-vsi8
\nclass Solution {\n public int countSubstrings(String s, String t) {\n Map<String, Integer> substrs = new HashMap<>();\n Map<String, Integer>
blackspinner
NORMAL
2020-10-31T17:04:23.266509+00:00
2020-11-04T18:47:13.970491+00:00
1,385
false
```\nclass Solution {\n public int countSubstrings(String s, String t) {\n Map<String, Integer> substrs = new HashMap<>();\n Map<String, Integer> substrs2 = new HashMap<>();\n for (int i = 0; i < s.length(); i++) {\n StringBuilder sb = new StringBuilder();\n for (int j = i; j < s.length(); j++) {\n sb.append(s.charAt(j));\n String cur = sb.toString();\n substrs.merge(cur, 1, Integer::sum);\n }\n }\n for (int i = 0; i < t.length(); i++) {\n StringBuilder sb = new StringBuilder();\n for (int j = i; j < t.length(); j++) {\n sb.append(t.charAt(j));\n String cur = sb.toString();\n substrs2.merge(cur, 1, Integer::sum);\n }\n }\n int res = 0;\n for (String substr : substrs.keySet()) {\n char[] arr = substr.toCharArray();\n for (int i = 0; i < arr.length; i++) {\n for (char ch = \'a\'; ch <= \'z\'; ch++) {\n if (arr[i] != ch) {\n char temp = arr[i];\n arr[i] = ch;\n String cur = new String(arr);\n res += substrs2.containsKey(cur) ? substrs.get(substr) * substrs2.get(cur) : 0;\n arr[i] = temp;\n }\n }\n }\n }\n return res;\n }\n}\n```
6
0
[]
1
count-substrings-that-differ-by-one-character
100% faster and simple to understand c++ dp solution
100-faster-and-simple-to-understand-c-dp-htf3
\nint countSubstrings(string s, string t) {\n int m = s.length();\n int n = t.length();\n int dp[m+1][n+1][2];\n for(int i=0; i<=m;
subh913
NORMAL
2022-05-16T18:31:21.329260+00:00
2022-05-16T18:31:21.329289+00:00
677
false
```\nint countSubstrings(string s, string t) {\n int m = s.length();\n int n = t.length();\n int dp[m+1][n+1][2];\n for(int i=0; i<=m; i++)\n {\n for(int j=0; j<=n; j++)\n {\n //dp[i][j][0] denotes number of substring ending at i that matches with\n //substrings ending at j\n dp[i][j][0]=0; \n //dp[i][j][1] denotes number of substrings ending at i that differs from\n //substrings ending at j by one character\n dp[i][j][1]=0;\n }\n }\n int out = 0;\n for(int i=1; i<=m; i++)\n {\n for(int j=1; j<=n; j++)\n {\n //If chars at i and j matches then either continue previous one\n //or just take the current one(new string)\n dp[i][j][0]= (s[i-1]==t[j-1])?dp[i-1][j-1][0]+1:0;\n //If chars at i and j matches then continue with previous one\n //else just take the previous matching substrings and increase it by 1\n dp[i][j][1]= (s[i-1]==t[j-1])?dp[i-1][j-1][1]:dp[i-1][j-1][0]+1;\n out += dp[i][j][1];\n }\n }\n return out;\n }\n```
5
0
['Dynamic Programming']
0
count-substrings-that-differ-by-one-character
Java | Trie Solution | Clear examples
java-trie-solution-clear-examples-by-spa-tbuf
Lets say,\ns="aba"\nt="aab"\n\nSubstrings of t will be,\n\n\ta .................... answer = 1 ( \'b\' = 1 )\n\taa .................... answer = 2 ( \'
spandanx
NORMAL
2022-02-09T09:52:42.506258+00:00
2022-02-09T09:55:10.038799+00:00
665
false
Lets say,\ns="aba"\nt="aab"\n\nSubstrings of t will be,\n\n\ta .................... answer = 1 ( \'b\' = 1 )\n\taa .................... answer = 2 ( \'ba\' = 1, \'ab\' = 1 ).\n\taab .................... answer = 0 as no eligible strings are present.\n\t a .................... answer = 1 ( \'b\' = 1 )\n\t ab .................... answer = 0 as no eligible strings are present.\n\t b .................... answer = 2 ( \'a\' = 2 )\nAnswer will be 6.\n\n**Solution:**\n\nSubstrings of s will be,\n\n\ta\n\tab\n\taba\n\t b\n\t ba\n\t a\n\t\nLets insert them in a Trie.\n![image](https://assets.leetcode.com/users/images/d12b0ac3-b64a-49fd-82eb-1662fc6b96af_1644394712.4317794.png)\n Everytime a substring enters into a node we increment the count by 1.\n \n Now our target is to find the the counts by iterating over them.\n \n **Example:**\n \n lets say our target string is **aa**.\n Also lets consider we can take all the characters (a-z) to generate substrings.\n **then, substrings with length 1 would be:**\n a,b,c,d,.....,z\n Among them answer for substring \'a\' would be 0 as there is no difference b/w source string (a) and current string (a).\n And for \'b\' to \'z\' ans would be 1 as difference b/w source string (a) and current string (b-z) is exactly 1. But only \'b\' is present in the Trie so only \'b\' is valid.\n \n **substrings with length 2 would be:**\n \n aa, ab, ac, .... az\n &\n ba, bb, bc, ... bz\n &\n ca, cb, .. cz\n ....\n .....\n za, .. zz\n \n Among them \'aa\' is not valid.\n But we can have answer for \'ab\' or \'ba\' as they have exactly 1 difference and they are present in the tree.\n \n Seeing those examples we can go with this way:\n At each step we can either go with\n\t **1. unchanged element with given difference (default 0).**\n\t **2. changed element with increased difference. (given + 1).**\n\nNow look at the below graph:\nHere our target string is \'aa\'.\nAnd we are calculating answer for each substring that have the last element as \'a\'.\n\n\taa\n\t----\n\ta\n\taa\n\t a\n\n![image](https://assets.leetcode.com/users/images/f887d5a9-0ae4-4d0f-9d46-7b5ca01da83f_1644399882.0430264.png)\n\n\nSimilarly for \'aab\':\nsubstrings will be:\n\t\n\ta\n\taa\n\taab\n\t a\n\t ab\n\t b\n\t\t\nHere is the code:\n\n```\nclass Solution {\n class Trie{\n Trie[] nodes = new Trie[26];\n int count = 0;\n Set<Integer> child = new HashSet<>();\n void add(String s, int startIndex, int endIndex){\n Trie current = this;\n for (int i = startIndex; i<endIndex; i++){\n if (current.nodes[getInt(s.charAt(i))]==null){\n\t\t\t\t\t// if trie node is not present at ith index, we create a new node\n\t\t\t\t\t// and the index gets added to current child set.\n\t\t\t\t\t// instead of iterating over all 26 nodes, we are iterating over the child set, to enhance performance\n current.nodes[getInt(s.charAt(i))] = new Trie();\n current.child.add(getInt(s.charAt(i)));\n }\n current.nodes[getInt(s.charAt(i))].count++;\n current = current.nodes[getInt(s.charAt(i))];\n }\n }\n }\n int find(Trie t, String s, int index, int difference, String carry){\n \tint ans = 0;\n \tif (difference==1)\n \t\tans+=t.count;//if current difference is 1 we increment the answer with current node\'s count\n \tif (difference==2)\n \t\treturn ans;\n \tif (index>s.length()-1) {\n \t\treturn ans;\n \t}\n \tif (t==null)\n \t\treturn 0;\n\t\t//without changing the current element and keeping the given difference\n \tif (t.nodes[getInt(s.charAt(index))]!=null) {\n \t\tans+=find(t.nodes[getInt(s.charAt(index))], s, index+1, difference, carry+s.charAt(index));\n \t}\n\t\t//changing the current element and incrementing difference by 1\n \tfor (int inx: t.child) {\n \t\tif (inx!=getInt(s.charAt(index))) { //only proceed when it is a different element\n \t\t\tans+=find(t.nodes[inx], s, index+1, difference+1, carry+(char)(inx+\'a\'));\n \t\t}\n \t}\n \treturn ans;\n }\n int getInt(char c){\n return c-\'a\';\n }\n public int countSubstrings(String s, String t) {\n Trie trie = new Trie();\n for (int i = 0; i<s.length(); i++){\n trie.add(s, i, s.length()); // generating the Trie\n }\n int ans = 0;\n for (int i = 0; i<t.length(); i++) {\n \tans+=find(trie, t, i, 0, ""); // getting the answer for substrings i to n\n }\n return ans;\n }\n}\n```\n\nTime Complexity:\nCorrect me if I am wrong.\ns_len = sizeof(s);\nt_len = sizeof(t);\n\ns_len * s_len + t_len * k^(t_len)\nwhere k can be between 1 to 26\n\n
5
0
['Depth-First Search', 'Trie', 'Java']
0
count-substrings-that-differ-by-one-character
A Trie Solution
a-trie-solution-by-nasus-bbci
Interesting that no one mentions a Trie solution. Time O(mm+nn)\n\n\nclass Solution {\n class Node{\n Node[] children;\n int size;\n pub
nasus
NORMAL
2021-02-03T16:39:11.514074+00:00
2021-02-03T16:41:27.993787+00:00
444
false
Interesting that no one mentions a Trie solution. Time O(m*m+n*n)\n\n```\nclass Solution {\n class Node{\n Node[] children;\n int size;\n public Node(){\n children = new Node[26];\n size = 0;\n }\n }\n class Trie{\n Node root;\n public Trie(){\n root = new Node();\n }\n public void insert(String s, int start){\n Node current = root;\n while(start<s.length()){\n int index = s.charAt(start)-\'a\';\n if(current.children[index]==null){\n current.children[index] = new Node();\n }\n current.children[index].size++;\n current = current.children[index];\n start++;\n }\n }\n public int looseSearch(String s, int start){\n int count = 0;\n Node current = root;\n for(int i=start; i<s.length(); i++){\n char c = s.charAt(i);\n if(current.children[c-\'a\']==null){\n //this is a miss match\n for(int j=0; j<26; j++){\n if(current.children[j]!=null){\n int temp = strictSearch(s, i+1, current.children[j]);\n count += temp;\n }\n }\n break;\n }else{\n // make this a miss match\n for(int j=0; j<26; j++){\n if(j==c-\'a\' || current.children[j]==null){\n continue;\n }\n int temp = strictSearch(s, i+1, current.children[j]);\n count += temp;\n }\n // this is a match, proceed\n current = current.children[c-\'a\'];\n }\n }\n return count;\n }\n \n private int strictSearch(String s, int start, Node current){\n int count = current.size;\n while(start<s.length()){\n if(current.children[s.charAt(start)-\'a\']!=null){\n current = current.children[s.charAt(start)-\'a\'];\n count += current.size;\n start++;\n }else{\n break;\n }\n }\n return count;\n }\n }\n public int countSubstrings(String s, String t) {\n Trie trie = new Trie();\n for(int i=0; i<t.length(); i++){\n trie.insert(t, i);\n }\n int count = 0;\n for(int i=0; i<s.length(); i++){\n count += trie.looseSearch(s, i);\n }\n return count;\n }\n}\n```
5
0
[]
2
count-substrings-that-differ-by-one-character
Java DP solution O(MN)
java-dp-solution-omn-by-motorix-netm
\nDefine: dp[i][j][k] is the number of substrings where s[0,..i] and t[0, j] have k different characters.\n\nCase 1: same character s[i] == t[j]\n dp[i][j][0]
motorix
NORMAL
2020-10-31T21:36:02.772348+00:00
2020-10-31T21:38:57.461063+00:00
422
false
\nDefine: ```dp[i][j][k]``` is the number of substrings where ```s[0,..i]``` and ```t[0, j]``` have ```k``` different characters.\n\nCase 1: same character ```s[i] == t[j]```\n* ```dp[i][j][0] = dp[i-1][j-1][0]```, which means the number of same substrings of ```s[0,...,i]``` and ```t[0,...,j]``` equals to those of ```s[0,...,i-1]``` and ```t[0,...,j-1]```.\n* ```dp[i][j][0] = dp[i-1][j-1][0]```, which means the number of one-character-diff substrings of ```s[0,...,i]``` and ```t[0,...,j]``` equals to those of ```s[0,...,i-1]``` and ```t[0,...,j-1]```.\n\t\nCase 2: different characters ```s[i] != t[j]```\n* ```dp[i][j][0] = 0```, which means ```s[0,...,i]``` and ```t[0,...,j]``` are different.\n* ```dp[i][j][1] = dp[i-1][j-1][0]```, which means ```s[0,...,i-1]``` and ```t[0,...,j-1]``` have ```dp[i-1][j-1][0]``` same substrings but the character ```s[i]``` and ```t[j]``` are different.\n\nThe answer is the total number of substrings that differ by one character. So, sum up all the ```dp[i][j][1]```.\n\n\n```\nclass Solution {\n public int countSubstrings(String s, String t) {\n int n = s.length(), m = t.length(), ans = 0;\n int[][][] dp = new int[n+1][m+1][2];\n for(int i = 0; i < n; i++) {\n for(int j = 0; j < m; j++) {\n if(s.charAt(i) == t.charAt(j)) {\n dp[i+1][j+1][0] = dp[i][j][0] + 1;\n dp[i+1][j+1][1] = dp[i][j][1];\n }\n else {\n dp[i+1][j+1][1] = dp[i][j][0] + 1;\n }\n ans += dp[i+1][j+1][1];\n }\n }\n return ans;\n }\n}\n```
5
0
[]
1
count-substrings-that-differ-by-one-character
[Python] clean top-down DP solution - O(MN)
python-clean-top-down-dp-solution-omn-by-y6zi
Idea\n\nWe can use DP to solve this problem. \n\ndp(i, j, k) means the number of substrings ending at s[i] and t[j] and differed by k (0 or 1) character. Please
alanlzl
NORMAL
2020-10-31T19:06:58.344276+00:00
2020-10-31T19:19:12.664966+00:00
592
false
**Idea**\n\nWe can use DP to solve this problem. \n\n`dp(i, j, k)` means the number of substrings ending at `s[i]` and `t[j]` and differed by `k` (0 or 1) character. Please see code below for bases cases and dp transition function.\n\n</br>\n\n**Complexity**\n\n- Time complexity: `O(MN)`\n- Space complexity: `O(MN)`\n\n</br>\n\n**Python**\n\n```Python\nclass Solution:\n def countSubstrings(self, s: str, t: str) -> int:\n \n m, n = len(s), len(t)\n \n @lru_cache(None)\n def dp(i, j, k):\n # base cases\n if i < 0 or j < 0 or k < 0:\n return 0\n if k == 0 and s[i] != t[j]:\n return 0\n \n # dp transition\n\t\t\tans = 0\n if s[i] == t[j]:\n ans += dp(i-1, j-1, k) + (k == 0)\n else:\n ans += dp(i-1, j-1, k-1) + 1\n \n return ans\n \n ans = 0\n for i in range(m):\n for j in range(n):\n ans += dp(i, j, 1)\n return ans\n```
5
0
[]
3
count-substrings-that-differ-by-one-character
C++ Brute Force
c-brute-force-by-yog3shwar-zzb8
\nclass Solution {\npublic:\n int helper(string s, string t,int len)\n {\n int count=0;\n for(int i=0;i<=t.size()-len;i++)\n {\n
yog3shwar
NORMAL
2020-10-31T16:28:28.188239+00:00
2020-10-31T16:28:28.188276+00:00
672
false
```\nclass Solution {\npublic:\n int helper(string s, string t,int len)\n {\n int count=0;\n for(int i=0;i<=t.size()-len;i++)\n {\n int c=0;\n string temp=t.substr(i,len);\n // cout<<s<<"\\t"<<temp<<"\\n";\n for(int i=0;i<len;i++)\n if(s[i]!=temp[i])\n c++;\n \n if(c==1)\n count++;\n }\n return count;\n }\n int countSubstrings(string s, string t) {\n int count=0;\n for(int i=0;i<s.size();i++)\n {\n for(int j=1;j<=s.size()-i;j++)\n {\n string subs=s.substr(i,j);\n count += helper(subs,t,j);\n }\n }\n return count; \n }\n};\n```
5
0
['C', 'C++']
0
count-substrings-that-differ-by-one-character
[Python] Brute force
python-brute-force-by-raymondhfeng-njer
Wasted a lot of time trying to come up with top down DP, but gave up and luckily brute force worked. Just iterate through all substrings of s and t, and check i
raymondhfeng
NORMAL
2020-10-31T16:01:14.535001+00:00
2020-10-31T16:01:14.535044+00:00
497
false
Wasted a lot of time trying to come up with top down DP, but gave up and luckily brute force worked. Just iterate through all substrings of s and t, and check if corresponding length substrings differ by 1 letter or less. O(n^3) O(n) time and space. \n\n```\nclass Solution:\n def countSubstrings(self, s: str, t: str) -> int:\n def differ(i,j,k):\n count = 1\n for l in range(k):\n if s[i+l] != t[j+l]:\n count -= 1\n if count < 0:\n return False\n return count == 0\n \n count = 0\n for i in range(1,len(s)+1): # length of substring in s\n for j in range(len(s)-i+1): # iterate through s\n for k in range(len(t)-i+1): # iterate through t\n if differ(j,k,i):\n count += 1\n \n return count\n```
5
1
[]
3
count-substrings-that-differ-by-one-character
Tries || well explained
tries-well-explained-by-evilshadow01-lq1z
Describe your first thoughts on how to solve this problem. \nThe problem can also be solved using dp but i was not able to figure out the states, I saw the hi
evilshadow01
NORMAL
2024-01-25T17:15:53.495860+00:00
2024-01-25T17:15:53.495886+00:00
113
false
<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem can also be solved using dp but i was not able to figure out the states, I saw the hint, where I got the idea of using Tries.\n\nI did not find any solution in cpp using tries so I am posting this one. Please give it an upvote if you liked it.\n\nThe code may seem big but it\'s all standered stuff, be patient and go through this a couple of times, you will definately understand.\uD83D\uDE0A\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nThe approach is simple just put every substring of t in a Trie. Then for every substring of s (obviously, whose length is less than or equal to t) we can check how many substrings are there in the trie.\n\nTo do so we are just adding an extra parameter of terminatingCount which will store how any substrings will end at that particular character(node).\n\nThis can be understood as in the first sample example we can see that for the substring "a" in s we have two substrings "b" in t.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(t.length() * L * 26 + s.length() * L * 26)\nL=length of substring inserted in trie\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(t.length() * L * 26 + 2).\nL=length of substring inserted in trie\n\n# Code\n```\nclass TrieNode{\n public:\n TrieNode* children[26];\n int terminatingCount;\n TrieNode(){\n for(int i=0;i<26;i++){\n children[i]=NULL;\n }\n terminatingCount=0;\n }\n};\nclass Solution {\nprivate:\n // inserting the word in the trie.\n void insertWord(TrieNode* root,string s){\n if(s==""){\n root->terminatingCount+=1;\n return;\n }\n char x=s.front();\n if(!((root->children)[x-\'a\'])){\n TrieNode* newNode=new TrieNode();\n root->children[x-\'a\']=newNode;\n }\n root=root->children[x-\'a\'];\n insertWord(root,s.substr(1));\n }\n int check(TrieNode* root,string s,int cnt){\n if(cnt==2){\n // if we have replaced more than 1 character just return 0\n return 0;\n }\n if(s==""){\n if(cnt==1){\n // reaching the end if we have only replaced 1 char then return the number of substrings ending at current node.\n return root->terminatingCount;\n }\n // else return 0 as we have to replace only 1 character.\n return 0;\n }\n char x=s.front();\n int ans=0;\n for(int i=0;i<26;i++){\n if(root->children[i]){\n if(i==x-\'a\'){\n // not replacing current character\n ans=ans+(check(root->children[i],s.substr(1),cnt));\n }\n else{\n // replacing current character\n ans=ans+(check(root->children[i],s.substr(1),cnt+1));\n }\n }\n }\n return ans;\n }\npublic:\n int countSubstrings(string s, string t) {\n ios_base::sync_with_stdio(false);\n TrieNode* root=new TrieNode();\n int ans=0;\n\n // inserting every substring of t in trie.\n for(int i=0;i<t.length();i++){\n string str="";\n for(int j=i;j<t.length();j++){\n str.push_back(t[j]);\n insertWord(root,str);\n }\n }\n\n // calculating ans\n for(int i=0;i<s.length();i++){\n string str="";\n for(int j=i;j<s.length();j++){\n str.push_back(s[j]);\n if(str.length()<=t.length()){\n int res=check(root,str,0);\n ans=ans+res;\n }\n }\n }\n return ans;\n }\n};\n```
4
0
['Trie', 'C++']
0
count-substrings-that-differ-by-one-character
c++ solution
c-solution-by-dilipsuthar60-vp60
\nclass Solution {\npublic:\n int countSubstrings(string s, string t) \n {\n int n=s.size();\n int m=t.size();\n int ans=0;\n
dilipsuthar17
NORMAL
2021-09-28T14:28:52.752455+00:00
2021-09-28T14:29:08.451626+00:00
809
false
```\nclass Solution {\npublic:\n int countSubstrings(string s, string t) \n {\n int n=s.size();\n int m=t.size();\n int ans=0;\n for(int i=0;i<n;i++)\n {\n for(int j=0;j<m;j++)\n {\n int diff=0;\n for(int k=0;i+k<n&&j+k<m;k++)\n {\n if(s[i+k]!=t[j+k])\n {\n diff++;\n }\n if(diff>1)\n {\n break;\n }\n ans+=diff;\n }\n }\n }\n return ans;\n }\n};\n```
4
0
['C', 'C++']
0
count-substrings-that-differ-by-one-character
O(mn)
omn-by-shankha117-4dft
\nclass Solution:\n def countSubstrings(self, s: str, t: str) -> int:\n \n if s == t: return 0 \n len_s = len(s) \n
shankha117
NORMAL
2020-11-30T19:58:32.824017+00:00
2020-11-30T19:58:32.824054+00:00
681
false
```\nclass Solution:\n def countSubstrings(self, s: str, t: str) -> int:\n \n if s == t: return 0 \n len_s = len(s) \n len_t = len(t) \n ans = 0 \n for i in range(len_s): \n for j in range(len_t): \n \n Si, Tj, d = i,j,0 \n \n while Si < len_s and Tj < len_t:\n\n if s[Si] != t[Tj]:\n\n d += 1\n\n if d == 1:\n ans += 1\n \n if d == 2:\n break\n\n Si += 1\n Tj += 1\n \n return ans\n```
4
1
['Python', 'Python3']
0
count-substrings-that-differ-by-one-character
python dp O(MN) and O(N) memory
python-dp-omn-and-on-memory-by-akbc-unz0
\nclass Solution:\n def countSubstrings(self, s: str, t: str) -> int:\n m,n = len(s), len(t)\n A, B = [0]*(n+1), [0]*(n+1)\n ans = 0\n
akbc
NORMAL
2020-11-09T20:10:15.634329+00:00
2020-11-09T20:10:15.634364+00:00
757
false
```\nclass Solution:\n def countSubstrings(self, s: str, t: str) -> int:\n m,n = len(s), len(t)\n A, B = [0]*(n+1), [0]*(n+1)\n ans = 0\n for i in range(m):\n AA, BB = [0]*(n+1), [0]*(n+1)\n for j in range(n):\n AA[j+1] = 1 + A[j] if s[i]==t[j] else 0\n BB[j+1] = B[j] if s[i]==t[j] else 1 + A[j]\n ans += BB[j+1]\n A, B = AA, BB\n return ans\n```
4
0
['Python3']
2
count-substrings-that-differ-by-one-character
Python DP O(mn) | O(mn) solution with Thoughts
python-dp-omn-omn-solution-with-thoughts-tn22
Intuitive\nAfter brute force , I am thinking this string problems might can use dp(memorized search) to approach due to in O(n^3) solution , we basically will v
wst54321
NORMAL
2020-11-04T17:30:02.356741+00:00
2020-11-04T17:30:34.679429+00:00
476
false
**Intuitive**\nAfter brute force , I am thinking this string problems might can use dp(memorized search) to approach due to in O(n^3) solution , we basically will visit same location again and again. \n\n**Transition Equation:**\nFirst , DP array always for the purpose of finding the final res. \nLet\'s use `f(i, j) = the total number of one char differnt subStrs at i-th char of s and j-th char of t`\n\n1. if `s[i] == t[j]`, then `f(i, j) = f(i-1, j-1)`\n2. if `s[i] != t[j]`, then `f(i, j) = count of same subStr at i-1 th of s and j-1 th of t` + 1 . Note : +1 here is due to we can also not picking anything from previous string , single char at `i` and `j` already forms a solution.\n\nSo , from equation #2 , we need another dp to track at given index `(i, j)`, what will be the count of same substrings as well.\nWe will define `g(i ,j) = the total number of same subStrs at i-th char of s and j-th char of t`\n\nThe whole transition will be \n\n`g(i, j) == 0 if s[i] != s[j] else g(i, j) == g(i-1, j-1) + 1`\n`f(i, j) == f(i-1,j-1) if s[i] == s[j] else g(i-1, j-1)+1` \n\n**Solution**\n\n```\nclass Solution(object):\n def countSubstrings(self, s, t):\n """\n :type s: str\n :type t: str\n :rtype: int\n """\n m, n = len(s), len(t)\n sameDP = [[0 for _ in range(n+1)] for _ in range(m+1)] # sameDP[i][j]: The same subStr count at i of s and j of t\n diffDP = [[0 for _ in range(n+1)] for _ in range(m+1)] # diffDP[i][j]: The 1 char diff subStr count at i of s and j of t \n \n for i in range(m):\n for j in range(n):\n sameDP[i+1][j+1] = 0 if s[i]!=t[j] else sameDP[i][j] + 1\n\n for i in range(m):\n for j in range(n):\n diffDP[i+1][j+1] = diffDP[i][j] if s[i] == t[j] else sameDP[i][j] + 1\n \n res = 0\n for i in range(m+1):\n res += sum(diffDP[i])\n \n return res\n```
4
0
[]
0
count-substrings-that-differ-by-one-character
Java O(n^2) - beats 100%
java-on2-beats-100-by-infprime-b8k3
diff[i][j] here is the number of substrings differing in 1 character ending in indices i and j in strings s and t respectively\n\nid[i][j] is the number of iden
infprime
NORMAL
2020-10-31T17:58:20.402911+00:00
2020-10-31T18:08:12.176097+00:00
421
false
`diff[i][j] ` here is the number of substrings differing in 1 character ending in indices `i` and `j` in strings `s` and `t` respectively\n\n`id[i][j]` is the number of identical substrings ending in indices `i` and `j` in strings `s` and `t` respectively\n\nThe answer is the summation over of `diff[i][j] ` over all possible `i` and `j`\n\n```class Solution {\n public int countSubstrings(String s, String t) {\n int n = s.length();\n int m = t.length();\n \n int[][] diff = new int[n][m];\n int[][] id = new int[n][m];\n int total = 0;\n for (int i = 0; i < n ; i++) { \n diff[i][0] = s.charAt(i) == t.charAt(0) ? 0 : 1;\n id[i][0] = s.charAt(i) == t.charAt(0) ? 1 : 0;\n total += diff[i][0];\n }\n for (int j = 0; j < m ; j++) { \n diff[0][j] = s.charAt(0) == t.charAt(j) ? 0 : 1;\n id[0][j] = s.charAt(0) == t.charAt(j) ? 1 : 0;\n total += diff[0][j];\n }\n total -= diff[0][0]; //double counted\n \n for (int i = 1; i < n; i++) {\n for (int j = 1; j < m; j++) {\n if (s.charAt(i) == t.charAt(j)) {\n diff[i][j] = diff[i-1][j-1];\n id[i][j] = 1+ id[i-1][j-1];\n } else {\n diff[i][j] = 1 + id[i-1][j-1];\n id[i][j] = 0;\n }\n total += diff[i][j];\n }\n }\n return total;\n }\n}\n\nBelow is the space optimised version of the same, we only need the previous row in each iteration\n\n```class Solution {\n public int countSubstrings(String s, String t) {\n int n = s.length();\n int m = t.length();\n int[][] diff = new int[m][2];\n int[][] id = new int[m][2];\n int total = 0;\n for (int i = 0; i < n; i++) {\n int now = i % 2;\n int prev = 1 - now;\n for (int j = 0; j < m; j++) {\n if (s.charAt(i) == t.charAt(j)) {\n diff[j][now] = j == 0 ? 0 : diff[j-1][prev];\n id[j][now] = j == 0 ? 1 : 1 + id[j-1][prev];\n } else {\n diff[j][now] = j == 0 ? 1 : 1 + id[j-1][prev];\n id[j][now] = 0;\n }\n total += diff[j][now];\n }\n }\n return total;\n }\n}
4
0
[]
0
count-substrings-that-differ-by-one-character
C++ Easy Solution
c-easy-solution-by-md_aziz_ali-kbef
Code\n\nclass Solution {\npublic:\n int solve(string& s,string &t,int i,int j,bool diff,vector<vector<vector<int>>>&dp){\n if(i == s.length() || j ==
Md_Aziz_Ali
NORMAL
2023-09-21T02:15:47.759990+00:00
2023-09-21T02:15:47.760022+00:00
330
false
# Code\n```\nclass Solution {\npublic:\n int solve(string& s,string &t,int i,int j,bool diff,vector<vector<vector<int>>>&dp){\n if(i == s.length() || j == t.length())\n return 0;\n if(dp[i][j][diff] != -1)\n return dp[i][j][diff];\n if(diff){\n if(s[i] != t[j])\n return dp[i][j][diff] = 0;\n return dp[i][j][diff] = 1 + solve(s,t,i+1,j+1,diff,dp);\n }\n if(s[i] != t[j])\n return dp[i][j][diff] = 1 + solve(s,t,i+1,j+1,true,dp);\n return dp[i][j][diff] = solve(s,t,i+1,j+1,diff,dp);\n }\n int countSubstrings(string s, string t) {\n int ans = 0;\n vector<vector<vector<int>>>dp(s.length(),vector<vector<int>>(t.length(),vector<int>(2,-1)));\n for(int i = 0;i < s.length();i++)\n for(int j = 0;j < t.length();j++)\n ans += solve(s,t,i,j,false,dp);\n return ans;\n }\n};\n```
3
0
['Dynamic Programming', 'Recursion', 'Memoization', 'C++']
1
count-substrings-that-differ-by-one-character
C++ || Brute Force || Two pointers || 100% fast
c-brute-force-two-pointers-100-fast-by-v-dynb
\nclass Solution {\npublic:\n int countSubstrings(string s, string t) {\n int ans=0;\n for(int i=0;i<s.size();i++){\n for(int j=0;j<
vibhanshu2001
NORMAL
2022-07-08T06:39:23.380924+00:00
2022-07-08T06:39:23.380965+00:00
151
false
```\nclass Solution {\npublic:\n int countSubstrings(string s, string t) {\n int ans=0;\n for(int i=0;i<s.size();i++){\n for(int j=0;j<t.size();j++){\n int x=i;\n int y=j;\n int diff=0;\n while(x<s.size()&& y<t.size()){\n if(s[x]!=t[y]){\n diff++;\n }\n if(diff==1){\n ans++;\n }\n if(diff>1){\n break;\n }\n x++;\n y++;\n }\n }\n }\n return ans;\n }\n};\n```
3
0
[]
0
count-substrings-that-differ-by-one-character
C++, DP / state machine, O(n^2)
c-dp-state-machine-on2-by-oaixuroab-lmxm
\n\n\nconst int N = 110;\n\nclass Solution {\n int f[N][N][2];\npublic:\n int countSubstrings(string s, string t) {\n \n int n = s.size(), m
oaixuroab
NORMAL
2022-03-05T23:19:10.921424+00:00
2022-03-05T23:20:06.797618+00:00
315
false
![image](https://assets.leetcode.com/users/images/cfaf35fa-4079-49c6-8e87-e2c3cb2adb8a_1646522330.7448306.png)\n\n```\nconst int N = 110;\n\nclass Solution {\n int f[N][N][2];\npublic:\n int countSubstrings(string s, string t) {\n \n int n = s.size(), m = t.size();\n for (int i = 1; i <= n; ++ i)\n for (int j = 1;j <= m; ++ j)\n if (s[i-1] == t[j-1]) f[i][j][0] = 1;\n else f[i][j][1] = 1;\n for (int i = 1; i <= n; ++ i)\n for (int j = 1; j <= m; ++ j)\n {\n if (s[i-1] == t[j-1])\n {\n f[i][j][1] += f[i-1][j-1][1];\n f[i][j][0] += f[i-1][j-1][0];\n }\n else\n {\n f[i][j][1] += f[i-1][j-1][0];\n }\n }\n \n int ans = 0;\n for (int i = 1; i <= n; ++ i)\n for (int j = 1; j <= m; ++ j)\n {\n ans += f[i][j][1];\n }\n \n return ans;\n \n }\n};\n```
3
0
[]
0
count-substrings-that-differ-by-one-character
Without DP
without-dp-by-karna001-ygkl
int countSubstrings(string s, string t) {\n \n int ans =0;\n int i,j;\n int m = s.size();\n int n = t.size();\n for(i=
karna001
NORMAL
2022-02-13T14:55:22.311276+00:00
2022-02-13T14:55:22.311315+00:00
165
false
int countSubstrings(string s, string t) {\n \n int ans =0;\n int i,j;\n int m = s.size();\n int n = t.size();\n for(i=0;i<m;i++)\n {\n for(j=0;j<n;j++)\n {\n int x=i;\n int y=j;\n int d=0;\n while(x<m && y<n)\n {\n if(s[x]!=t[y])\n {\n d++;\n }\n if(d==1)\n {\n ans++;\n }\n if(d==2)\n {\n break;\n }\n x++;\n y++;\n }\n }\n }\n return ans;\n }
3
1
['C']
0
count-substrings-that-differ-by-one-character
Python 3 (easy to understand; with detailed explanation and comments)
python-3-easy-to-understand-with-detaile-csxr
Because every pair of string must have only one mismatch, it is more efficient to start with mismatched characters. Once you find a pair of mismatched pair of c
jiediao
NORMAL
2021-09-17T17:10:51.300902+00:00
2021-09-17T17:10:51.300935+00:00
340
false
Because every pair of string must have only one mismatch, it is more efficient to start with mismatched characters. Once you find a pair of mismatched pair of characters, poke both backward and forward to find the number of matchs before and after the mismatched pair (num_pre and num_post). The total number of substring pairs that include this particular mismatched pair can be then calculated by (num_pre + 1) * (num_post + 1). Please note that this formula automatically includes the occurrence of the stand alone mismatched pair. \n\n\n```\nclass Solution:\n def countSubstrings(self, s: str, t: str) -> int:\n n1, n2 = len(s), len(t)\n count = 0\n for i in range(0,n1):\n for j in range(0,n2):\n # Only start to count when two characters differ\n if s[i] != t[j]:\n # Counter how many matches immediately preceding the pair\n p = 1\n pre, post = 0, 0\n while i-p >=0 and j-p >= 0:\n if s[i-p] == t[j-p]:\n pre += 1\n p += 1\n else:\n break\n # Counter how many matches immediately following the pair\n p = 1\n while i+p < n1 and j+p < n2:\n if s[i+p] == t[j+p]:\n post += 1\n p += 1\n else:\n break\n # The total count should be increased by all combinations caused by preceding and following matches\n count += (pre + 1) * (post + 1)\n return count \n```
3
0
[]
0
count-substrings-that-differ-by-one-character
Easy to understand for beginners as well(runtime 64ms 100%)
easy-to-understand-for-beginners-as-well-wg0z
\nvar countSubstrings = function(s, t) {\n let res=0;\n for(let i=0;i<s.length;i++){\n for(let j=0;j<t.length;j++){\n let diff=0;\n
lssuseendharlal
NORMAL
2021-08-17T06:42:47.543290+00:00
2021-08-17T06:42:47.543337+00:00
414
false
```\nvar countSubstrings = function(s, t) {\n let res=0;\n for(let i=0;i<s.length;i++){\n for(let j=0;j<t.length;j++){\n let diff=0;\n let x=i;\n let y=j;\n while(x<s.length && y<t.length){\n if(s[x]!==t[y]){\n diff++\n }\n if(diff===1)res++\n if(diff>1) break;\n x++\n y++\n }\n }\n }\n return res;\n};\n```\nRuntime: 64 ms, faster than 100.00% of JavaScript online submissions for Count Substrings That Differ by One Character.\nMemory Usage: 39.2 MB, less than 63.16% of JavaScript online submissions for Count Substrings That Differ by One Character.
3
0
['JavaScript']
0
count-substrings-that-differ-by-one-character
Dynamic Programming Java Solution Memoization with explanation
dynamic-programming-java-solution-memoiz-t8ly
We make a grid with rows = length of string2 and columns = length= string1\nIf the charecters in string 1 and string 2 differ we increment the existing count.\n
prigo9
NORMAL
2021-07-11T18:57:58.297809+00:00
2021-07-14T11:34:53.148302+00:00
343
false
We make a grid with rows = length of string2 and columns = length= string1\nIf the charecters in string 1 and string 2 differ we increment the existing count.\nIf the charecters in string 1 and string 2 are similar , we check for substrings to the left and right that differ by 1 .\n\n\nTest Case :\n"bbbbb"\n"abbab"\nMemoisation table of rows = string1.length() and columns = string2.length()\n```\n\t\t a b b a b\n\tb\t1 3 5 6 6 \n\tb\t7 10 12 13 14 \n\tb\t15 17 20 21 22 \n\tb\t23 24 26 27 28 \n\tb\t29 30 31 32 33 \n```\n\n```\nclass Solution {\n public int countSubstrings(String s, String t) {\n int[][] mapping = new int[s.length()][t.length()];\n for(int i=0; i< s.length(); i++){\n if(i!=0){\n mapping[i][0]=mapping[i-1][t.length()-1] ;\n }\n for(int j=0; j< t.length() ;j++ ) { \n if( s.charAt(i) != t.charAt(j) ){\n if(j!=0){\n mapping[i][j]=1+ mapping[i][j-1];\n }else{\n mapping[i][j]=1+mapping[i][j];\n }\n \n }else{\n int left_s = i-1;\n int right_s= i+1;\n int left_t = j-1;\n int right_t = j+1;\n int add_val=0; \n\t\t\t\t // checking substrings to the left that differ by one character\n while(left_s >= 0 && left_t >=0 ){\n \n if(s.charAt(left_s)!= t.charAt(left_t)){\n add_val++;\n \n break;\n }\n left_s--;\n left_t--;\n }\n\t\t\t\t // checking substrings to the right that differ by one character\n while(right_s < s.length() && right_t < t.length() ){\n \n if(s.charAt(right_s)!= t.charAt(right_t)){\n add_val++;\n right_s++;\n right_t++;\n\t\t\t\t\t\t // checking substrings which contain the given substring and not differ by 1\n while( right_s < s.length() && right_t < t.length() && s.charAt(right_s)==t.charAt(right_t) ){\n add_val++;\n right_s++;\n right_t++;\n }\n break;\n }\n right_s++;\n right_t++;\n } \n \n if(j!=0){\n mapping[i][j]=add_val+ mapping[i][j-1];\n }else{\n mapping[i][j]=add_val+mapping[i][j];\n } \n \n }\n }\n }\n \n return mapping[s.length()-1][t.length()-1];\n }\n}\n\n
3
1
[]
1
count-substrings-that-differ-by-one-character
C++ Fast solution with explaination
c-fast-solution-with-explaination-by-rak-25am
\nclass Solution {\npublic:\n int countSubstrings(string s, string t) {\n int n = s.size();\n int m = t.size();\n // Select an element a
rakshal
NORMAL
2021-06-27T08:36:45.543148+00:00
2021-06-27T08:36:45.543180+00:00
428
false
```\nclass Solution {\npublic:\n int countSubstrings(string s, string t) {\n int n = s.size();\n int m = t.size();\n // Select an element and check whether the element belongs to an substring of which all other elements are same\n int ans = 0;\n for(int i=0;i<n;i++){\n for(int j=0;j<m;j++){\n if(s[i]!=t[j]){\n int countback=0,countfront=0,index_back=i-1,index_front=i+1,indexj_back=j-1,indexj_front=j+1;\n while(index_back>=0 and indexj_back>=0 and s[index_back]==t[indexj_back]){\n index_back--;\n indexj_back--;\n countback++;\n }\n while(index_front<n and indexj_front<m and s[index_front]==t[indexj_front]){\n index_front++;\n indexj_front++;\n countfront++;\n }\n // We will add all the substring which contain that element + all the substrings which ends with that element + all the substrings which start from that element + that element.\n ans+=(countback*countfront + countback + countfront + 1);\n }\n }\n }\n return ans;\n }\n};\n```
3
0
[]
0
count-substrings-that-differ-by-one-character
O(nm) ^^
onm-by-andrii_khlevniuk-0lr5
The solution superimposes two strings in all possible ways (hence quadratic complexity) and accumulates in variable out the number of respective substrings that
andrii_khlevniuk
NORMAL
2021-04-20T01:21:46.170304+00:00
2021-04-22T22:34:17.975854+00:00
468
false
The solution superimposes two strings in all possible ways (hence quadratic complexity) and accumulates in variable `out` the number of respective substrings that differ by on character. \n<br>\n\n![image](https://assets.leetcode.com/users/images/02321361-adc2-48fc-9872-6aaa427d47e0_1618927668.0751498.png)\n\n<br>\n\nWhen simultaniously traversing the two strings we keep track of lengths of "runs" (`l`) - the same consequetive characters in both strings. We also need the length of the previous run (`p`). When characters match we add `p` to `out`. If characters mismatch we add `l` to `out` and set `p` to `l`. Take a look at the picture to convince yourself.\n\n![image](https://assets.leetcode.com/users/images/2112ee61-4738-4a7d-a0cb-76e070bcbf74_1618927256.2312179.png)\n\n```\n int countSubstrings(string s, string t) \n { \n int out{0};\n for(auto i{0}; i<size(s); i++) \n for(auto j{i}, k{0}, p{0}, l{1}; k<size(t) and j<size(s); ++k, ++j, ++l)\n out += s[j]!=t[k] ? p=exchange(l,0) : p;\n \n for(auto i{1}; i<size(t); i++)\n for(auto j{i}, k{0}, p{0}, l{1}; k<size(s) and j<size(t); ++k, ++j, ++l)\n out += t[j]!=s[k] ? p=exchange(l,0) : p;\n return out;\n }\n```
3
0
['C', 'C++']
1
count-substrings-that-differ-by-one-character
Python O(mn) solution DP
python-omn-solution-dp-by-chang_liu-lvp4
\nclass Solution:\n def countSubstrings(self, s: str, t: str) -> int:\n m = len(s)\n n = len(t)\n \n match = [[0 for _ in range(n
chang_liu
NORMAL
2021-01-12T05:43:33.229515+00:00
2021-01-12T05:43:33.229543+00:00
247
false
```\nclass Solution:\n def countSubstrings(self, s: str, t: str) -> int:\n m = len(s)\n n = len(t)\n \n match = [[0 for _ in range(n+1)] for _ in range(m + 1)]\n matchOne = [[0 for _ in range(n+1)] for _ in range(m + 1)]\n \n match[0][0] = 0\n \n total = 0\n \n for i in range(1,m+1):\n for j in range(1, n+1):\n # print(i,j,s[i-1],t[j-1])\n # print(match[i-1][j-1])\n if s[i-1] == t[j-1]:\n match[i][j] = 1 + match[i-1][j-1]\n matchOne[i][j] = matchOne[i-1][j-1]\n else:\n # print("Here")\n match[i][j] = 0\n matchOne[i][j] = 1 + match[i-1][j-1]\n \n total += matchOne[i][j]\n \n \n # print(match)\n # print(matchOne)\n return total\n```
3
0
[]
1
count-substrings-that-differ-by-one-character
Java Dynamic Programming Time O(nm) Space O(nm)
java-dynamic-programming-time-onm-space-jyb4m
Example: s="abbab", t="bbbbb"\nCompare each substring of s {a,ab,abb,abba,abbab} with each substring of \nt {b,bb,bbb,bbbb,bbbb}\n\nUsing dp, there are only two
yifeigong
NORMAL
2020-12-30T07:50:32.411446+00:00
2020-12-30T07:55:35.883380+00:00
275
false
Example: s="abbab", t="bbbbb"\nCompare each substring of s {a,ab,abb,abba,abbab} with each substring of \nt {b,bb,bbb,bbbb,bbbb}\n\nUsing dp, there are only two cases, when s[i]==t[j] or s[i]!=t[j]\nfor example:\n\n(1) when compare s="abb" with t="bbb", since s[2]==t[2], you only need to know what is the preivous result, that is when compare s="ab" with t="bb"\n\n(2) when compare s="abba" with t="bbbb", since s[3]!=t[3], you need to know how many consecutive characters before s[3] and before t[3] are the same, here two characters "bb" in "abba" are the same with "bb" in "bbbb", so the result of compaing s=abba and t=bbbb is 1+number of consecutively same characters, becuase you will have {bbb,bb,b} differs in 1 character with {bba,ba,a} correspodingly\n\ndp1 used for saving the number of previous consecutive same characters\ndp2 is the result of comparing s[ 0 to i ] with t[ 0 to j ]\n\n```\nclass Solution {\n public int countSubstrings(String s, String t) {\n int len1=s.length();\n int len2=t.length();\n int res=0;\n int[][] dp1=new int[len1][len2];\n int[][] dp2=new int[len1][len2];\n \n for(int i=0;i<len1;i++){\n char c1=s.charAt(i);\n for(int j=0;j<len2;j++){\n char c2=t.charAt(j);\n if(c1==c2){\n if(i==0||j==0){\n dp1[i][j]=1;\n }\n else{\n dp1[i][j]=dp1[i-1][j-1]+1;\n dp2[i][j]=dp2[i-1][j-1];\n }\n }\n else{\n dp1[i][j]=0; \n if(i==0||j==0){\n dp2[i][j]=1;\n }\n else{\n dp2[i][j]=dp1[i-1][j-1]+1;\n }\n }\n res+=dp2[i][j];\n }\n }\n return res; \n }\n}\n```
3
0
[]
0
count-substrings-that-differ-by-one-character
❇ count-substrings-that-differ-by-one-character Images👌 🏆O(1)❤️ Javascript🎯 Memory👀80.45%🕕 ++Ex
count-substrings-that-differ-by-one-char-dhej
\nTime Complexity: O(N^3)\nSpace Complexity: O(1)\n\n\n\n\n\nLogic:\n1. Initialize a counter cnt to 0.\n2. Loop through each character in the substring.\n3. Com
anurag-sindhu
NORMAL
2024-07-11T14:04:28.807759+00:00
2024-07-12T06:22:11.999715+00:00
170
false
\nTime Complexity: O(N^3)\nSpace Complexity: O(1)\n\n```\n\n\n\nLogic:\n1. Initialize a counter cnt to 0.\n2. Loop through each character in the substring.\n3. Compare characters from str1 and str2.\n4. If characters differ, increment the mismatch counter.\n5. If there is more than 1 mismatch, return Infinity.\n6. Return the mismatch count.\n\nfunction numberOfMismatch(str1, str2, str1Index, str2Index, count) {\n let cnt = 0;\n for (let index = 0; index < count; index++) {\n if (str1[str1Index + index] !== str2[str2Index + index]) {\n if (cnt === 1) {\n return Infinity;\n }\n cnt++;\n }\n }\n return cnt;\n}\n\n\nLogic:\n\n1. Initialize a counter cnt to 0.\n2. Loop through all possible starting indices for substrings in str1 and str2.\n3. Use numberOfMismatch to check if substrings have exactly one mismatch.\n4. Increment cnt if exactly one mismatch is found.\n5. Return the count of such substrings.\n\nfunction compareString(str1, str2, count) {\n let cnt = 0;\n for (let str1Index = 0; str1Index <= str1.length - count; str1Index++) {\n for (let str2Index = 0; str2Index <= str2.length - count; str2Index++) {\n if (numberOfMismatch(str1, str2, str1Index, str2Index, count) === 1) {\n cnt++;\n }\n }\n }\n return cnt;\n}\n\nvar countSubstrings = function (str1, str2) {\n let count = 0;\n for (let index = 0; index < str1.length; index++) {\n count += compareString(str1, str2, index + 1);\n }\n return count;\n};\n```\n\n![image](https://assets.leetcode.com/users/images/9a54bca4-fc53-4acc-ab5d-b3c02f1f790d_1720706065.8514032.png)\n
2
0
['String', 'JavaScript']
0
count-substrings-that-differ-by-one-character
Brute force but even it's not easier to think upon(a smarter brute force)
brute-force-but-even-its-not-easier-to-t-rami
Intuition\nwe are going to do this problem with brute force since constraints are low\n\n# Approach\nthere are two main problems with brute force too \n1.the si
nikkiraikkoken
NORMAL
2024-01-16T02:05:37.035137+00:00
2024-01-16T02:05:37.035166+00:00
132
false
# Intuition\nwe are going to do this problem with brute force since constraints are low\n\n# Approach\nthere are two main problems with brute force too \n1.the size of sliding window while iterating all substring is not fixed so it will take a lot of lot of time complexity in order to math the strings\n\nsoln- this can be resolved by just taking eqial length of substrings and just compare them as unequal length substrings would never be same so why check for them (k is incremented equally on bith strings so thus maintaining eequal length)\n\n2. just one character should differ and thw rest of substring should come in same alignment as the other substring how do we keep track of this \n\nsoln- we keep checking each character from both substrings of equal length by moving both pointer after every check thus maintaining the alignment(k is incremented equally on both substrings )\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int countSubstrings(String s, String t) {\n int ans =0;\n for(int i=0;i<s.length();i++)\n {\n for(int j=0;j<t.length();j++)\n {\n int count =0;\n for(int k=0;i+k<s.length()&&j+k<t.length();k++)\n {\n if(s.charAt(i+k)!=t.charAt(j+k))\n {\n count++;\n }\n if(count==1)\n ans++;\n }\n }\n \n }\n return ans;\n }\n}\n```
2
0
['Java']
0
count-substrings-that-differ-by-one-character
Java DP solution with detail explanation. O(nm) runtime.
java-dp-solution-with-detail-explanation-56sb
Intuition\n1. Let\'s first look at the case where s and t differ by 1 letter and all the other letters are the same. For example, if we have something like "com
y55deng
NORMAL
2022-12-28T00:23:00.215871+00:00
2022-12-28T00:23:53.111754+00:00
405
false
# Intuition\n1. Let\'s first look at the case where s and t differ by 1 letter and all the other letters are the same. For example, if we have something like "com" and "coe" -> there\'s 3 pairs {com, coe}, {om, oe}, {m,e}. From this, we can see that total # of different pairs formed becase of "m" and "e" being different is longest common substring before m and e plus 1 for the pair {m,e}. Hence it would be LCS being "co" which is lenght 2 + 1. \n\nWe can say that m and e from the example above is at position i and j. We can denote this as if s(i) != t(j) then diff[i][j] == LSC(i - 1, j - 1) + 1.\n\n2. Let\'s look at when s(i) == t(j), then we know that including letter at s(i) and t(j) itself does not cause any more pairs at this point in time. For example, let\'s image building the string "com" and "coe". At s(i)==s(j) = o, adding o to c doesn\'t cause any additional pairs. Hence the number of differing by 1 pairs at s(i) and t(j) is the same as before. \n\nLet\'s denote that as s(i) == t(j), then diff[i][j] == diff[i - 1][j - 1]. \n\nThis will help us count cases where the differ letter is in the beging i.e. {tom, com}, since for o and m we will be counting them as a difference of 1 due to {t,c} being different. \n\n3. Edge cases (length 1 substring) -> when we count substrings that are lenght 1 and differ by 1. For example in 2 even if s(i)==s(j) the letters s(i) and s(j) can still cause a new pair being the length 1 substring pair. i.e. {o, c} {o, e} etc. We count the length 1 pairs by looking at when i == 0 and j == 0 which will allow us to build lenght 1 substrings from s and t. \n\nHence, if i == 0 or j == 0, diff[i][j] = 1 if s(i) == t(j) else = 0. \n\n4. Answer is simple the sum of all the differences at each i, j. \n\n# Approach\n\nUse two nested arays to loop through s and t for each index i and j. Use two 2d arrays to keep track of diff[i][j] and lcs[i][j]. Sum up all the values in diff array. \n\nI would recommend drawing out a few LCS and diff matrix to understand this logic better if there is any confusion.\n\n# Complexity\n- Time complexity:\nFor s and t lenght of n and m respectively runtime is O(n*m) since we just loop once (nested) for each i and j being index of string s and t. \n\n- Space complexity:\nSince I used 2 2d arrays of nxm it\'s O(2n*m). We can reduce to O(n) or O(m) this by using 1 d arrays and just keeping track of the previous row. \n\n# Code\n```\nclass Solution {\n public int countSubstrings(String s, String t) {\n int n = s.length();\n int m = t.length(); \n \n int [][] lcs = new int[n][m];\n int [][] diff = new int[n][m]; // we will return the sum of all the cells as the answer\n int count = 0; \n for (int i = 0; i < n; i++) { // loop for string s \n for (int j = 0; j < m; j++) { // loop for string t \n if (s.charAt(i) == t.charAt(j)) {\n // diff same as difference before we added this letter since it doesn\'t do \n // anything \n diff[i][j] = (i == 0 || j == 0) ? 0 : diff[i - 1][j - 1]; \n // add 1 to the lcs we\'ve seen at this point since s(i) == t(j)\n lcs[i][j] = (i == 0 || j == 0) ? 1 : lcs[i - 1][j - 1] + 1; \n } else {\n diff[i][j] = (i == 0 || j == 0) ? 1 : lcs[i - 1][j - 1] + 1;\n lcs[i][j] = 0; \n }\n count += diff[i][j];\n }\n }\n\n return count;\n }\n}\n```
2
0
['Java']
2
count-substrings-that-differ-by-one-character
Python (Simple DP)
python-simple-dp-by-rnotappl-hj6w
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
rnotappl
NORMAL
2022-11-22T15:49:31.166477+00:00
2022-11-22T15:49:31.166523+00:00
458
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def countSubstrings(self, s, t):\n n, m = len(s), len(t)\n\n match = [[0 for _ in range(m+1)] for _ in range(n+1)]\n matchone = [[0 for _ in range(m+1)] for _ in range(n+1)]\n\n for i in range(1,n+1):\n for j in range(1,m+1):\n if s[i-1] == t[j-1]:\n match[i][j] = 1 + match[i-1][j-1]\n matchone[i][j] = matchone[i-1][j-1]\n else:\n match[i][j] = 0\n matchone[i][j] = 1 + match[i-1][j-1]\n\n return sum([sum(i) for i in matchone])\n\n\n \n \n```
2
0
['Python3']
0
count-substrings-that-differ-by-one-character
c++ | easy | short
c-easy-short-by-venomhighs7-f5gb
\n\n# Code\n\nclass Solution {\npublic:\n int countSubstrings(string s, string t) {\n int res = 0 ;\n for (int i = 0; i < s.length(); ++i)\n
venomhighs7
NORMAL
2022-10-27T03:07:02.762705+00:00
2022-10-27T03:07:02.762752+00:00
693
false
\n\n# Code\n```\nclass Solution {\npublic:\n int countSubstrings(string s, string t) {\n int res = 0 ;\n for (int i = 0; i < s.length(); ++i)\n res += helper(s, t, i, 0);\n for (int j = 1; j < t.length(); ++j)\n res += helper(s, t, 0, j);\n return res;\n }\n\n int helper(string s, string t, int i, int j) {\n int res = 0, pre = 0, cur = 0;\n for (int n = s.length(), m = t.length(); i < n && j < m; ++i, ++j) {\n cur++;\n if (s[i] != t[j])\n pre = cur, cur = 0;\n res += pre;\n }\n return res;\n }\n};\n```
2
0
['C++']
0
count-substrings-that-differ-by-one-character
C# | Combinations | Left and right choices -> combination
c-combinations-left-and-right-choices-co-pie0
April 14, 2022\nIntroduction\nIt takes me three steps to understand the problem, first I read the problem statement and test cases, but I was not sure what to a
jianminchen
NORMAL
2022-04-15T01:09:51.496109+00:00
2022-04-15T05:11:16.497726+00:00
73
false
April 14, 2022\n**Introduction**\nIt takes me three steps to understand the problem, first I read the problem statement and test cases, but I was not sure what to ask for; I read the analysis done by one most voted discuss post, votrubac, and I did not follow; so I studied the code and then wrote C# code, and I understood the analysis and how to solve it. I will write down my own explanation. \n\n**Analsysis | My explanation**\nI just quickly copied one analysis with an example in the following:\nIntuition: We can find each pair of s[i] != t[j]. Then try to extend both sides when s[i + t] == t[j + t]. If we have left steps extended on the left side and right steps on the right side, we have (left + 1) * (right + 1) options for this { i, j } case.\n\nExample:\n\ns = xbabc\nt = ybbbc\nFor i = 2 and j = 2, we have s[i] = a and t[j] = b that doesn\'t match. Now look leftwards, we can extend left-side by 1 time due to b, and extend right-side by 2 times due to bc. So for this specific center { i = 2, j = 2 }, we have 2 * 3 = 6 options.\n\nIn total, the count of substring is 32. But i = 2 and j = 2, substring of s can start from "ba" or "a" two options, and can end in three options, "a", "ab", "abc"; substring of t can start from "bb" or "b", end with "b" or "bb" or "bbc". So it is multiplication of left variable and right variable. \n\n**My explanation**\nIt takes a few minutes for me to figure out the above example\'s answer is 2 * 3 = 6 options. Why?\nLeft side substring only has options which is the length of left variable. \n\nThe following C# code passes online judge. \n\n```\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\n\nnamespace _1638_countSubstrings\n{\n class Program\n {\n static void Main(string[] args)\n {\n //var result = CountSubstrings("aba", "baba");\n var result = CountSubstrings("xbabc", "ybbbc");\n Debug.Assert(result == 32);\n }\n\n /// <summary>\n /// study code\n /// https://leetcode.com/problems/count-substrings-that-differ-by-one-character/discuss/917690/C%2B%2B-O(N3)-with-explanation\n /// Time complexity: O(N^3)\n /// </summary>\n /// <param name="s"></param>\n /// <param name="t"></param>\n /// <returns></returns>\n public static int CountSubstrings(string s, string t)\n {\n if (s == null || t == null)\n {\n return 0; \n }\n\n var sLength = s.Length;\n var tLength = t.Length;\n var combinations = 0;\n\n for (int i = 0; i < sLength; ++i)\n {\n for (int j = 0; j < tLength; ++j)\n {\n if (s[i] == t[j])\n {\n continue;\n }\n\n int left = 1;\n var right = 1;\n\n while (i - left >= 0 && j - left >= 0 && s[i - left] == t[j - left])\n {\n ++left;\n }\n\n while (i + right < sLength && j + right < tLength && s[i + right] == t[j + right])\n {\n ++right;\n }\n\n combinations += left * right; // including one char substring \n }\n }\n\n return combinations;\n }\n }\n}\n```
2
0
[]
0
count-substrings-that-differ-by-one-character
C++ simple, short and easy to read solution
c-simple-short-and-easy-to-read-solution-y9w0
\n int countSubstrings(string s, string t){\n int flag=0; \n //flag=0 : all chatracters same\n //flag=1 : 1 chatracter differen
quater_nion
NORMAL
2022-03-10T20:55:00.231944+00:00
2022-03-13T09:02:20.254550+00:00
441
false
```\n int countSubstrings(string s, string t){\n int flag=0; \n //flag=0 : all chatracters same\n //flag=1 : 1 chatracter different\n //flag=2 : >1 chatracter different\n int ans=0;\n int sLen=s.length();\n int tLen=t.length();\n for(int i=0; i<sLen; i++)\n for(int j=0; j<tLen; j++){\n flag=0;\n for(int pos=0; i+pos<sLen && j+pos<tLen; pos++){\n if(s[i+pos]!=t[j+pos]) //if one diff. in chars seen, increase flag by 1\n flag++;\n if(flag==2) //if more than 1 char diff\n break;\n if(flag==1) //if 1 char diff\n ans++;\n\t\t\t\t} \n }\n return ans;\n }\n```
2
1
['Dynamic Programming', 'C']
1
count-substrings-that-differ-by-one-character
[Python3] Top down DP O(mn)
python3-top-down-dp-omn-by-caijun-9fj2
Top down DP is always simpler to code. The idea is to calculate the number of good substring pairs for each index pair (i, j), which means s[0, i] and t[0, j].
caijun
NORMAL
2022-01-07T05:10:15.027921+00:00
2022-01-07T05:16:32.901243+00:00
408
false
Top down DP is always simpler to code. The idea is to calculate the number of good substring pairs for each index pair `(i, j)`, which means `s[0, i]` and `t[0, j]`. To achieve that, there are two different cases:\n1. `s[i] == s[j]`, then the answer is `diff1(i - 1, j - 1)`, the diff1 function calculates the number of string pairs ending at index `i` and `j` that have exactly one different character.\n2. `s[i] != s[j]`, we found the different character, so the answer will be number of exactly same strings plus pair `(i, j)` itself, namely `1 + same(i - 1, j - 1)` \n\nHere\'s the code.\n```\nclass Solution:\n def countSubstrings(self, s: str, t: str) -> int:\n @lru_cache(None)\n def same(se, te):\n if se < 0 or te < 0:\n return 0\n return 1 + same(se - 1, te - 1) if s[se] == t[te] else 0\n \n @lru_cache(None)\n def diff1(se, te):\n if se < 0 or te < 0:\n return 0\n \n if s[se] == t[te]:\n return diff1(se - 1, te - 1)\n else:\n return 1 + same(se - 1, te - 1)\n \n ans = 0\n for i in range(len(s)):\n for j in range(len(t)):\n ans += diff1(i, j)\n return ans\n```
2
0
[]
2
count-substrings-that-differ-by-one-character
C++ | short O{n*m*min(n,m)} solution with comments
c-short-onmminnm-solution-with-comments-047sz
\nclass Solution {\npublic:\n int countSubstrings(string s, string t) {\n int n=s.size(),m=t.size(),ans=0;\n for(int i=0; i<n; i++){\n
yash598
NORMAL
2021-08-12T14:30:37.355046+00:00
2021-08-28T17:09:47.743706+00:00
327
false
```\nclass Solution {\npublic:\n int countSubstrings(string s, string t) {\n int n=s.size(),m=t.size(),ans=0;\n for(int i=0; i<n; i++){\n for(int j=0; j<m; j++){\n //index to start comaparing the subarrays as given in the condition of exactly one character differing\n if(s[i]!=t[j]){\n int c1=0,c2=0,iprev=i-1,inext=i+1,jprev=j-1,jnext=j+1;\n //counting the characters before the current one\n while(iprev>=0 and jprev>=0 and s[iprev]==t[jprev]){\n c1++; iprev--; jprev--;\n }\n //counting the characters after the current one\n while(inext<n and jnext<m and s[inext]==t[jnext]){\n c2++; inext++; jnext++;\n }\n //c1*c2 indicates number of subarrays created using all combinations from left and right sides of current\n //c1 indicates just the subarrays to the left side\n //c2 indicates just the subarrys to the right side\n //adding extra 1 for the single current character subarray\n ans+=c1*c2+c1+c2+1;\n }\n }\n }\n return ans;\n }\n};\n```
2
0
[]
1
count-substrings-that-differ-by-one-character
Java || Brute Force || T.C - O(n^3) S.C - O(1)
java-brute-force-tc-on3-sc-o1-by-legenda-5juf
\n public int countSubstrings(String s, String t) {\n \n int len1 = s.length(), len2 = t.length(), ans = 0;\n for(int i = 0; i < len1; i
LegendaryCoder
NORMAL
2021-07-21T08:21:34.114664+00:00
2021-07-21T08:21:34.114713+00:00
107
false
\n public int countSubstrings(String s, String t) {\n \n int len1 = s.length(), len2 = t.length(), ans = 0;\n for(int i = 0; i < len1; i++){\n for(int j = 0; j < len2; j++){\n int ptr1 = i, ptr2 = j, diff = 0;\n while(ptr1 < len1 && ptr2 < len2){\n if(s.charAt(ptr1) != t.charAt(ptr2))\n diff++;\n if(diff == 1)\n ans++;\n else if(diff == 2)\n break;\n ptr1++;\n ptr2++;\n }\n }\n }\n return ans;\n }
2
0
[]
0
count-substrings-that-differ-by-one-character
Java Easy Dp recursion solution with explanation
java-easy-dp-recursion-solution-with-exp-dk2l
The idea behind this solution is:\nthere can be two cases:\n1) Case 1 : both characters are same --> If both characters are same this means we need to look for
shabana121197
NORMAL
2021-06-28T04:54:56.817678+00:00
2021-06-28T04:54:56.817720+00:00
325
false
The idea behind this solution is:\nthere can be two cases:\n1) Case 1 : both characters are same --> If both characters are same this means we need to look for one character which is different. If we get the differnet character then in following iterations look only for same characters, if you encounter the one more different character again then it means we encounter two different characters, in this case there is no point on going more further so simply return 0.. This is exactly implemented in first if case i.e.\n```\nif(isSame == 1) {\n if(a.charAt(i) != b.charAt(j)) {\n dp.put(key,0);\n return dp.get(key);\n } else {\n dp.put(key, 1 + findMaximumSubstr(i+1,j+1,1, dp,a, b));\n return dp.get(key);\n }\n } \n```\n\n2) Case 2 : When both characters are different, then look only for similiar characters. The code is as follows:\n```\nif(isSame == 0) {\n dp.put(key, (a.charAt(i) != b.charAt(j) ? 1 : 0) + findMaximumSubstr(i+1,j+1,(a.charAt(i) != b.charAt(j) ? 1 : 0),dp, a, b));\n return dp.get(key);\n }\n```\n\n\nComplete code is as follows:\n\t\t\n```\nclass Solution {\n String createDpKey(int i, int j, int k) {\n return Integer.toString(i) + "_" + Integer.toString(j) + "_" + Integer.toString(k);\n }\n int findMaximumSubstr(int i, int j, int isSame, Map<String,Integer> dp, String a, String b) {\n if(i >= a.length() || j >= b.length()) return 0;\n String key = createDpKey(i,j,isSame);\n if(dp.containsKey(key)) return dp.get(key);\n if(isSame == 1) {\n if(a.charAt(i) != b.charAt(j)) {\n dp.put(key,0);\n return dp.get(key);\n } else {\n dp.put(key, 1 + findMaximumSubstr(i+1,j+1,1, dp,a, b));\n return dp.get(key);\n }\n } else if(isSame == 0) {\n dp.put(key, (a.charAt(i) != b.charAt(j) ? 1 : 0) + findMaximumSubstr(i+1,j+1,(a.charAt(i) != b.charAt(j) ? 1 : 0),dp, a, b));\n return dp.get(key);\n }\n return 0; \n }\n public int countSubstrings(String a, String b) {\n Map<String,Integer> dp = new HashMap<>();\n int ans = 0;\n for(int i = 0 ;i < a.length(); i++)\n for(int j = 0;j<b.length();j++)\n {\n ans += findMaximumSubstr(i,j,0,dp,a,b);\n }\n return ans;\n \n }\n}\n```
2
0
[]
1
count-substrings-that-differ-by-one-character
C++ | Faster than 100% | 2 pointers | Easy Solution
c-faster-than-100-2-pointers-easy-soluti-doic
\nclass Solution {\npublic:\n int countSubstrings(string s, string t) {\n int n = s.size(), m = t.size(), ans = 0;\n for(int i = 0; i < n; i++)
ankit-SM
NORMAL
2021-06-24T03:18:32.355530+00:00
2021-06-24T03:18:32.355568+00:00
647
false
```\nclass Solution {\npublic:\n int countSubstrings(string s, string t) {\n int n = s.size(), m = t.size(), ans = 0;\n for(int i = 0; i < n; i++){\n for(int j = 0; j < m; j++){\n if(s[i] != t[j]){\n int cnt1 = 0, cnt2 = 0;\n int ips = i - 1, ipt = j - 1, ifs = i + 1, ift = j + 1;\n while(ips >= 0 && ipt >= 0 && s[ips] == t[ipt]){\n cnt1++, ips--, ipt--;\n }\n while(ifs < n && ift < m && s[ifs] == t[ift]){\n cnt2++, ifs++, ift++;\n }\n ans += cnt1 * cnt2 + cnt1 + cnt2 + 1;\n }\n }\n }\n return ans;\n }\n};\n```
2
2
['Two Pointers', 'C']
1
count-substrings-that-differ-by-one-character
Python3 simple solution
python3-simple-solution-by-eklavyajoshi-tdho
\nclass Solution:\n def countSubstrings(self, s: str, t: str) -> int:\n count = 0\n for i in range(len(s)):\n for j in range(len(t))
EklavyaJoshi
NORMAL
2021-05-02T04:40:02.858115+00:00
2021-05-02T04:40:02.858150+00:00
335
false
```\nclass Solution:\n def countSubstrings(self, s: str, t: str) -> int:\n count = 0\n for i in range(len(s)):\n for j in range(len(t)):\n x,y = i,j\n d = 0\n while x < len(s) and y < len(t):\n if s[x] != t[y]:\n d += 1\n if d == 1:\n count += 1\n if d == 2:\n break\n x += 1\n y += 1\n return count \n```\n**If you like this solution, please upvote for this**
2
1
['Python3']
0
count-substrings-that-differ-by-one-character
Java easy solution | 3ms
java-easy-solution-3ms-by-gauravkumar-ws45
\nclass Solution {\n public int countSubstrings(String s, String t) {\n int lenS = s.length();\n int lenT = t.length();\n int count = 0;
gauravkumar
NORMAL
2021-02-24T17:16:53.607133+00:00
2021-02-24T17:16:53.607197+00:00
404
false
```\nclass Solution {\n public int countSubstrings(String s, String t) {\n int lenS = s.length();\n int lenT = t.length();\n int count = 0;\n for(int i=0;i<lenS;i++) {\n for(int j=0;j<lenT;j++) {\n int diff = 0;\n for(int m=i,n=j ; m<lenS && n < lenT ; m++,n++) {\n if(s.charAt(m) != t.charAt(n)) {\n diff++;\n }\n if(diff == 1) {\n count++;\n }\n if(diff == 2) {\n break;\n }\n }\n }\n }\n return count;\n }\n}\n```
2
0
['Java']
1
count-substrings-that-differ-by-one-character
C++ Solution (with explanation)
c-solution-with-explanation-by-sukanya11-hjia
\nclass Solution {\npublic:\n int countSubstrings(string s, string t) {\n //here in this que the difference between characters should not be 1 like a-
sukanya1109
NORMAL
2021-02-22T13:44:59.161445+00:00
2021-02-22T13:44:59.161475+00:00
248
false
```\nclass Solution {\npublic:\n int countSubstrings(string s, string t) {\n //here in this que the difference between characters should not be 1 like a->b or b->c\n //instead the diff between the substring characters should differ by one like\n //appl & appe here l&e are different that is the diff we need to find out(i.e diff=1 and not >1), then increment the ans by one\n //if that diff is 2 break from the loop like for ex:- abc and bbe here (a,b) & (c,e) are diff in this \n //substring.\n //For all possible substring in s we need to check for all substring in t\n \n \n int ans=0;\n for(int i=0; i<s.length(); i++)\n {\n \tfor(int j=0; j<t.length(); j++)\n \t{\n \t\t//here x&y are used to form substring of s&t \n \t\tint x=i, y=j, diff=0;\n \t\twhile(x<s.size() && y<t.size())\n \t\t{\n \t\t\tif(s[x]!=t[y]) diff++;\n \t\t\tif(diff==1) ans++;\n \t\t\tif(diff==2) break;\n \t\t\tx++;\n \t\t\ty++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n return ans;\n }\n};\n```
2
0
[]
0
count-substrings-that-differ-by-one-character
JAVA solution
java-solution-by-mohd-aman-qnaz
\nclass Solution {\n public int countSubstrings(String s, String t) {\n int ans = 0;\n for(int i=0;i<s.length();i++){\n for(int j=0;
mohd-aman
NORMAL
2020-11-14T14:45:31.272275+00:00
2020-11-14T14:45:31.272301+00:00
253
false
```\nclass Solution {\n public int countSubstrings(String s, String t) {\n int ans = 0;\n for(int i=0;i<s.length();i++){\n for(int j=0;j<t.length();j++){\n int x=i;\n int y=j;\n int d=0;\n while(x<s.length()&&y<t.length()){\n if(s.charAt(x)!=t.charAt(y)){\n d++;\n }\n if(d==1){\n ans++;\n }\n if(d==2){\n break;\n }\n x++;\n y++;\n }\n }\n }\n return ans;\n }\n}\n```
2
1
[]
0
count-substrings-that-differ-by-one-character
Python easy to understand O(mn) 100% time
python-easy-to-understand-omn-100-time-b-7no7
\nclass Solution:\n def countSubstrings(self, s: str, t: str) -> int:\n \n @lru_cache(None)\n def count(ssub, tsub):\n if not
wenyu3
NORMAL
2020-11-02T04:22:01.900300+00:00
2020-11-02T04:22:01.900356+00:00
167
false
```\nclass Solution:\n def countSubstrings(self, s: str, t: str) -> int:\n \n @lru_cache(None)\n def count(ssub, tsub):\n if not ssub or not tsub:\n return 1\n if ssub[0] != tsub[0]:\n return 1\n return 1 + count(ssub[1:], tsub[1:])\n \n output = 0\n for i in range(len(s)):\n for j in range(len(t)):\n if s[i] != t[j]:\n output += count(s[:i][::-1], t[:j][::-1]) * count(s[(i + 1):], t[(j + 1):])\n \n return output\n```
2
0
[]
1
count-substrings-that-differ-by-one-character
Simple C# DP Solution with some comments. O(n^2)
simple-c-dp-solution-with-some-comments-u3vdw
\n public class Solution\n {\n public int CountSubstrings(string s, string t)\n {\n checked\n {\n int r
maxpushkarev
NORMAL
2020-11-01T06:55:43.409722+00:00
2020-11-02T04:04:20.643031+00:00
332
false
```\n public class Solution\n {\n public int CountSubstrings(string s, string t)\n {\n checked\n {\n int res = 0;\n\t\t\t\t//lcs = longest common substring\n int[,] lcsLeft = new int[s.Length, t.Length];\n int[,] lcsRight = new int[s.Length, t.Length];\n\n for (int i = 0; i < s.Length; i++)\n {\n for (int j = 0; j < t.Length; j++)\n {\n if (s[i] != t[j])\n {\n lcsLeft[i, j] = 0;\n }\n else\n {\n if (i > 0 && j > 0)\n {\n lcsLeft[i, j] = lcsLeft[i - 1, j - 1] + 1;\n }\n else\n {\n lcsLeft[i, j] = 1;\n }\n }\n }\n }\n\n\n for (int i = s.Length - 1; i >= 0; i--)\n {\n for (int j = t.Length - 1; j >= 0; j--)\n {\n if (s[i] != t[j])\n {\n lcsRight[i, j] = 0;\n }\n else\n {\n if (i < s.Length - 1 && j < t.Length - 1)\n {\n lcsRight[i, j] = lcsRight[i + 1, j + 1] + 1;\n }\n else\n {\n lcsRight[i, j] = 1;\n }\n }\n }\n }\n\n\n for (int i = 0; i < s.Length; i++)\n {\n for (int j = 0; j < t.Length; j++)\n {\n if (s[i] != t[j]) //if characters mismatch we can make it equal and calculate how much substrings in s and t are equal\n {\n var left = 0;\n var right = 0;\n if (i > 0 && j > 0)\n {\n left = lcsLeft[i - 1, j - 1];\n }\n\n left++; //empty string can be on the left side\n if (i < s.Length - 1 && j < t.Length - 1)\n {\n right = lcsRight[i + 1, j + 1];\n }\n\n right++; // empty string can be on the right side\n\n res += left * right; //for any left prefix we can concatenate current char + any right postfix\n }\n }\n }\n\n\n return res;\n }\n }\n }\n```
2
0
['Dynamic Programming']
0
count-substrings-that-differ-by-one-character
[Python3] Brutal force with HashTable(dictionary)
python3-brutal-force-with-hashtabledicti-smhw
Idea:\n1. For s: store all the possible matches in a dictionary, and do the encoding with "\". The key is the possible match and the value is the substring itse
diihuu
NORMAL
2020-10-31T16:19:24.950606+00:00
2020-10-31T16:23:55.907372+00:00
140
false
Idea:\n1. For s: store all the possible matches in a dictionary, and do the encoding with "\\*". The key is the possible match and the value is the substring itself\nFor example, "ab"=> {\'a*\': \'ab\', \'*b\': \'ab\'}\n2. For t: check each substring of t, and find its corresponding matches in the dictionary, add to result. Counter() is used to count the number of matches for a given matching value\n\nNote: the substring is [i:j ), so j should be len(s) + 1 \n```\nclass Solution:\n def countSubstrings(self, s: str, t: str) -> int:\n d = defaultdict(list)\n for i in range(len(s)+1):\n for j in range(i):\n substring = s[j:i]\n if len(substring):\n for k in range(len(substring)):\n n = substring[:k] + "*" + substring[k+1:]\n d[n].append(substring) \n count = 0\n for i in range(len(t)+1):\n for j in range(i):\n substring = t[j:i]\n if len(substring):\n for k in range(len(substring)): \n n = substring[:k] + "*" + substring[k+1:]\n if d[n]:\n chances = d[n]\n c = Counter(chances)\n for sub in c:\n if substring != sub:\n count += c[sub]\n \n return count\n \n```
2
0
[]
0
count-substrings-that-differ-by-one-character
Java | BruteForce | Explained
java-bruteforce-explained-by-abideenzain-lt78
\nclass Solution {\n public int countSubstrings(String s, String t) {\n List<String> subStrings = new ArrayList<>();\n List<String> subStringt=
abideenzainuel
NORMAL
2020-10-31T16:10:48.459870+00:00
2020-10-31T16:29:32.114100+00:00
371
false
```\nclass Solution {\n public int countSubstrings(String s, String t) {\n List<String> subStrings = new ArrayList<>();\n List<String> subStringt= new ArrayList<>();\n \n\t\t//generate all possible substrings of both the given string\n generateSubString(s,subStrings);\n generateSubString(t,subStringt);\n \n int count = 0;\n \n\t\t//(i)compare each substring of s with each substring of n.\n for(String ss : subStrings){\n for(String st: subStringt){\n int diff = 0;\n\t\t//if lengths of both the substring(s and t) are equal then further compare each character of both sub strings.\t\t\n if(ss.length() == st.length()){\n for(int i=0; i<ss.length();i++){\n\t\t\t\t\t//the difference between both the sub strings should be 1 character.\n if(ss.charAt(i)!=st.charAt(i))\n diff++;\n //if difference between both the sub string is more than 1 character than no need to check further.\n if(diff > 1) break;\n }\n\t\t\t\t //if difference between both the sub string is one then consider it as answer, and look for more possible answers.\t\n if(diff==1) count++;\n }\n }\n \n }\n return count;\n }\n \n private void generateSubString(String s, List<String> list){\n int window = 0;\n \n while(window<s.length()){\n \n for(int i=0; i+window<s.length(); i++){\n list.add(s.substring(i,i+window+1));\n }\n window++;\n }\n }\n}\n```\n\n**Upvote if you like the solution.**
2
0
['Java']
0
count-substrings-that-differ-by-one-character
Using Trie, in Javascript
using-trie-in-javascript-by-manideep39-q833
\n\n# Code\n\nclass TrieNode {\n constructor() {\n this.children = new Map()\n this.count = 0\n }\n}\n\nclass Trie {\n constructor() {\n
manideep39
NORMAL
2024-05-25T12:10:08.661981+00:00
2024-05-25T12:10:08.662007+00:00
36
false
\n\n# Code\n```\nclass TrieNode {\n constructor() {\n this.children = new Map()\n this.count = 0\n }\n}\n\nclass Trie {\n constructor() {\n this.root = new TrieNode()\n }\n\n insert(word) {\n let curr = this.root\n for (const char of word) {\n if (!curr.children.has(char)) {\n curr.children.set(char, new TrieNode())\n }\n curr = curr.children.get(char)\n }\n curr.count++\n }\n}\n\n/**\n * @param {string} s\n * @param {string} t\n * @return {number}\n */\nvar countSubstrings = function (s, t) {\n const trie = new Trie()\n\n for (let i = 0; i < t.length; i++) {\n let subStr = \'\'\n for (let j = i; j < t.length; j++) {\n subStr += t[j]\n trie.insert(subStr)\n }\n }\n\n let count = 0\n for (let i = 0; i < s.length; i++) {\n let subStr = \'\'\n for (let j = i; j < s.length; j++) {\n subStr += s[j]\n count += countHelper(trie, subStr)\n }\n }\n\n return count\n};\n\nfunction countHelper(trie, subStr) {\n let count = 0\n dfs(trie.root, 0, 0)\n return count\n\n function dfs(node, d, i) {\n if (d > 1) return\n if (i == subStr.length) {\n if (d == 1) count += node.count\n return\n }\n\n const children = node.children\n for (const [char, child] of children) {\n dfs(child, d + (char != subStr[i]), i + 1)\n }\n }\n}\n```
1
0
['JavaScript']
0
count-substrings-that-differ-by-one-character
MAP || C++ || EASY || SIMPLE || TIME O(n^2log(n))
map-c-easy-simple-time-on2logn-by-abhay_-0ssk
\nclass Solution {\npublic:\n int check(string s1,string s2){\n // cout<<s1<<" "<<s2<<endl;\n int k = 0;\n int i,n = s1.length();\n
abhay_12345
NORMAL
2022-09-17T09:53:11.137490+00:00
2022-09-17T09:53:11.137549+00:00
838
false
```\nclass Solution {\npublic:\n int check(string s1,string s2){\n // cout<<s1<<" "<<s2<<endl;\n int k = 0;\n int i,n = s1.length();\n for(i = 0; i < n; i++){\n if(s1[i] != s2[i]){\n k++;\n }\n }\n return k;\n }\n int countSubstrings(string s, string t) {\n unordered_map<string,int> m1,m2;\n int k = min(s.length(),t.length());\n string str = "";\n int i,j,n = s.length();\n for(i = 0; i < n; i++){\n str = "";\n for(j = i; j < n && (j-i)<k ; j++){\n str += s[j];\n m1[str]++;\n }\n }\n n = t.length();\n for(i = 0; i < n; i++){\n str = "";\n for(j = i; j < n && (j-i) < k; j++){\n str += t[j];\n m2[str]++;\n }\n }\n // for(auto &i: m1){\n // cout<<i.first<<" "<<i.second<<endl;\n // }for(auto &i: m2){\n // cout<<i.first<<" "<<i.second<<endl;\n // }\n int ans = 0;\n for(auto &i: m1){\n \n for(auto &j: m2){\n if(((i.first).length() == (j.first).length()) && (check(i.first,j.first)==1)){\n ans += i.second * j.second;\n }\n }\n }\n return ans;\n }\n};\n```
1
0
['C', 'C++']
0
count-substrings-that-differ-by-one-character
C++ easy solution
c-easy-solution-by-ayushpanchal0523-jlex
**** upvote if it\'s helpful\n\nint countSubstrings(string s, string t)\n {\n int ans=0;\n \n int n=s.size(),m=t.size() ;\n for(int I=0;I
ayushpanchal0523
NORMAL
2022-08-03T18:38:34.440063+00:00
2022-08-03T18:38:34.440099+00:00
313
false
**** upvote if it\'s helpful\n```\nint countSubstrings(string s, string t)\n {\n int ans=0;\n \n int n=s.size(),m=t.size() ;\n for(int I=0;I<n;I++)\n {\n \n for(int J=0;J<m;J++)\n {\n int i=I;\n int j=J;\n int diff=0;\n while(i<n and j<m and diff<=1)\n {\n if(s[i]!=t[j])\n diff++;\n if(diff==1)\n ans++;\n i++;\n j++;\n }\n }\n }\n \n return ans; \n }\n```
1
0
['C']
0
count-substrings-that-differ-by-one-character
[JAVA] CONSTANT SPACE SOLUTION
java-constant-space-solution-by-avneetsi-ixwy
class Solution {\n\n public int countSubstrings(String s, String t) {\n int ans = 0;\n for(int i = 0; i<s.length(); i++){\n for(int
avneetsingh2001
NORMAL
2022-07-31T18:42:05.691532+00:00
2022-07-31T18:42:05.691574+00:00
333
false
class Solution {\n\n public int countSubstrings(String s, String t) {\n int ans = 0;\n for(int i = 0; i<s.length(); i++){\n for(int j = 0; j<t.length(); j++){\n int x = i;\n int y = j;\n int d = 0;\n while(x<s.length() && y<t.length()){\n if(s.charAt(x)!=t.charAt(y))d++;\n if(d==1)ans++;\n if(d==2)break;\n x++;\n y++;\n }\n }\n }\n return ans;\n }\n}
1
0
['Dynamic Programming', 'Java']
0
count-substrings-that-differ-by-one-character
C++ Solution || Backtracking + Predicate Function ||
c-solution-backtracking-predicate-functi-q12r
\nclass Solution {\npublic:\n \n bool predicate(string sub1, string sub2)\n {\n if(sub1.size() == 0 || sub2.size() == 0) return false;\n
cosmiiccat
NORMAL
2022-07-13T07:27:37.010249+00:00
2022-07-13T07:27:37.010281+00:00
511
false
```\nclass Solution {\npublic:\n \n bool predicate(string sub1, string sub2)\n {\n if(sub1.size() == 0 || sub2.size() == 0) return false;\n if(sub1.size() != sub2.size()) return false;\n int count = 0, i = 0;\n while(true)\n {\n if(i == sub1.size() || i == sub2.size())\n {\n break;\n }\n \n if(sub1[i] != sub2[i]) count += 1;\n \n i++;\n }\n \n if(count == 1 && i == sub1.size() && i == sub2.size()) return true;\n return false;\n }\n \n void substr(string str, string sub, vector<string> &v, int i)\n {\n if(i == str.size())\n {\n if(sub.size() != 0)\n {\n v.push_back(sub);\n }\n return;\n }\n \n sub.push_back(str[i]);\n substr(str, sub, v, i+1);\n sub.pop_back();\n if(sub.size() != 0)\n {\n v.push_back(sub);\n sub.clear();\n return;\n }\n substr(str, sub, v, i+1);\n }\n \n int countSubstrings(string s, string t) {\n \n string s1, s2;\n vector<string> sub1, sub2;\n int count = 0;\n \n substr(s, s1, sub1, 0);\n substr(t, s2, sub2, 0);\n \n for(int i=0; i<sub1.size(); i++)\n {\n for(int j=0; j<sub2.size(); j++)\n {\n if(sub1[i].size() == sub2[j].size())\n {\n if(predicate(sub1[i], sub2[j]) == true)\n {\n count++;\n }\n }\n }\n }\n \n return count;\n }\n};\n```
1
0
['Backtracking', 'Recursion', 'C', 'C++']
0
count-substrings-that-differ-by-one-character
c++ code | memoization
c-code-memoization-by-comeon_1826-tudf
\nclass Solution {\npublic:\n int dp[105][105];\n \n int func(string &s,string &t,int i,int j,int status){\n if (i<0 || j<0){\n retur
comeOn_1826
NORMAL
2022-06-12T08:45:19.193528+00:00
2022-06-12T08:45:19.193575+00:00
317
false
```\nclass Solution {\npublic:\n int dp[105][105];\n \n int func(string &s,string &t,int i,int j,int status){\n if (i<0 || j<0){\n return 0;\n }\n \n if (dp[i][j]!=-1){\n return dp[i][j];\n }\n \n int val=0;\n \n if (status==0){\n if (s[i]==t[j]){\n val=func(s,t,i-1,j-1,0);\n }\n else{\n val=1+func(s,t,i-1,j-1,1);\n }\n }\n else{\n if (s[i]==t[j]){\n val=1+func(s,t,i-1,j-1,1);\n }\n else{\n val=0;\n }\n }\n \n return dp[i][j]=val;\n }\n \n int countSubstrings(string s, string t) {\n int ans=0;\n \n \n for (int i=0; i<s.length(); i++){\n for (int j=0; j<t.length(); j++){\n memset(dp,-1,sizeof(dp));\n ans+=func(s,t,i,j,0);\n }\n } \n \n return ans;\n }\n};\n```
1
0
[]
1
count-substrings-that-differ-by-one-character
C++ || recursive || memoization || easy to understand
c-recursive-memoization-easy-to-understa-cssa
\nclass Solution {\npublic:\n \n map <pair<int,int>, int> dp;\n \n int same(string s, string t, int i, int j) {\n \n if(i < 0 or j < 0
yash_8080
NORMAL
2022-06-07T12:08:53.074659+00:00
2022-06-07T12:08:53.074695+00:00
671
false
```\nclass Solution {\npublic:\n \n map <pair<int,int>, int> dp;\n \n int same(string s, string t, int i, int j) {\n \n if(i < 0 or j < 0) {\n \n return 0;\n }\n \n if(s[i] == t[j]) {\n \n return 1 + same(s, t, i - 1, j - 1);\n }\n else {\n return 0;\n }\n }\n \n int calc(string s, string t, int i, int j) {\n \n if(i < 0 or j < 0 or i >= s.length() or j >= t.length()) {\n return 0;\n }\n else if(dp.find({i, j}) != dp.end()) {\n \n return dp[{i, j}];\n }\n \n int ans = 0;\n \n if(s[i] == t[j]) {\n \n ans = calc(s, t, i - 1, j - 1);\n }\n else {\n \n ans = 1 + same(s, t, i - 1, j - 1);\n \n }\n \n return dp[{i, j}] = ans;\n }\n \n int countSubstrings(string s, string t) {\n \n int ans = 0;\n \n for(int i = 0 ; i < s.length(); i++) {\n \n for(int j = 0 ; j < t.length(); j++) {\n \n ans += calc(s, t, i, j);\n }\n }\n \n return ans;\n }\n};\n```
1
0
['Recursion', 'Memoization', 'C']
0
count-substrings-that-differ-by-one-character
Java | DP explained
java-dp-explained-by-user5778vr-okuh
\nclass Solution {\n public int countSubstrings(String s, String t) {\n /*\n diff0[i][j] = number of s substring ending at i is t substring
user5778vR
NORMAL
2022-04-24T01:04:47.411785+00:00
2022-04-24T01:04:47.411827+00:00
193
false
```\nclass Solution {\n public int countSubstrings(String s, String t) {\n /*\n diff0[i][j] = number of s substring ending at i is t substring ending at j\n diff1[i][j] = number of s substring ending at i is 1-char diff from substring of t ending at j\n if (s.charAt(i) == t.charat(j)){\n diff0[i][j] = diff0[i-1][j-1]+1;\n diff1[i][j] = diff1[i-1][j-1];\n } else {\n diff0[i][j] = 0;\n diff1[i][j] = diff0[i-1][j-1]+1;\n }\n */\n int count = 0, lenS = s.length(), lenT = t.length();\n int[][] diff0 = new int[lenS][lenT];\n int[][] diff1 = new int[lenS][lenT];\n for (var i=0; i<lenS; i++){\n for (var j=0; j<lenT; j++){\n var match = s.charAt(i) == t.charAt(j);\n if (i==0 || j==0){\n diff0[i][j] = match ? 1 : 0;\n diff1[i][j] = match ? 0 : 1;\n } else {\n if (match){\n diff0[i][j] = diff0[i-1][j-1]+1;\n diff1[i][j] = diff1[i-1][j-1];\n } else {\n diff0[i][j] = 0;\n diff1[i][j] = diff0[i-1][j-1] + 1;\n }\n }\n \n count += diff1[i][j];\n }\n }\n return count;\n }\n}\n```
1
0
[]
0
count-substrings-that-differ-by-one-character
c++||easy to understand
ceasy-to-understand-by-return_7-w4u8
```\nclass Solution {\npublic:\n int countSubstrings(string s, string t) \n {\n int res=0;\n int n=s.size(),m=t.size();\n for(int i=0
return_7
NORMAL
2022-04-06T11:11:43.502643+00:00
2022-04-06T11:11:43.502673+00:00
167
false
```\nclass Solution {\npublic:\n int countSubstrings(string s, string t) \n {\n int res=0;\n int n=s.size(),m=t.size();\n for(int i=0;i<n;i++)\n {\n for(int j=0;j<m;j++)\n {\n if(s[i]!=t[j])\n {\n int l=1,r=1;\n while(min(i-l,j-l)>=0&&s[i-l]==t[j-l])\n l++;\n while(i+r<n&&j+r<m&&s[i+r]==t[j+r])\n r++;\n res+=l*r;\n }\n }\n }\n return res;\n \n }\n};\n//If you like the solution plz upvote.
1
0
['C']
0
count-substrings-that-differ-by-one-character
C++ || EASY TO UNDERSTAND || 3 Appraches
c-easy-to-understand-3-appraches-by-aari-hzxs
Time Complexity O(NxNxN)\n\nclass Solution {\npublic:\n int countSubstrings(string s, string t) {\n int ans=0;\n int n=s.length();\n int
aarindey
NORMAL
2022-04-04T11:03:24.564751+00:00
2022-04-05T14:35:53.520250+00:00
205
false
**Time Complexity O(NxNxN)**\n```\nclass Solution {\npublic:\n int countSubstrings(string s, string t) {\n int ans=0;\n int n=s.length();\n int m=t.length();\n for(int i=0;i<n;i++)\n {\n for(int j=0;j<m;j++)\n {\n if(s[i]!=t[j])\n {\n int left=1,right=1;\n while(i-left>=0&&j-left>=0&&s[i-left]==t[j-left])\n {\n ++left;\n }\n while((i+right)<n&&(j+right)<m&&s[i+right]==t[j+right])\n {\n ++right;\n }\n ans+=(left*right);\n }\n }\n }\n return ans;\n }\n};\n```\n**Another Approach with The Same Time Complexity**\n```\nclass Solution {\npublic:\n int countSubstrings(string s, string t) {\n int ans=0;\n int n=s.length();\n int m=t.length();\n for(int i=0;i<n;i++)\n {\n for(int j=0;j<m;j++)\n {\n int miss=0;\n for(int p=0;i+p<n&&j+p<m;p++)\n {\n if(s[i+p]!=t[j+p])\n {\n miss++;\n if(miss>=2)\n break;\n }\n ans+=miss;\n }\n }\n }\n return ans;\n }\n};\n```\n**DP approach T.C. O(s.size()Xt.size())**\n```\nclass Solution {\npublic:\n int countSubstrings(string &s, string &t) {\n int res = 0;\n int dp1[101][101] = {}, dp2[101][101] = {};\n for (int i = 1; i <= s.size(); ++i)\n for (int j = 1; j <= t.size(); ++j)\n if (s[i - 1] == t[j - 1])\n dp1[i][j] = 1 + dp1[i - 1][j - 1];\n \n for (int i = s.size(); i > 0; --i)\n for (int j = t.size(); j > 0; --j)\n if (s[i - 1] == t[j - 1])\n dp2[i - 1][j - 1] = 1 + dp2[i][j];\n \n for (int i = 0; i < s.size(); ++i)\n for (int j = 0; j < t.size(); ++j)\n if (s[i] != t[j])\n res += (dp1[i][j] + 1) * (dp2[i + 1][j + 1] + 1);\n \n return res;\n }\n};\n```\n**Please upvote to motivate me in my quest of documenting all leetcode solutions(to help the community). HAPPY CODING:)\nAny suggestions and improvements are always welcome**
1
0
[]
1
count-substrings-that-differ-by-one-character
simple java solution
simple-java-solution-by-amir-ammar-m1xp
\tpublic int countSubstrings(String s, String t) {\n\t\t\tint ans = 0;\n\t\t\tfor (int i = 0; i < s.length(); i++) {\n\t\t\t\tfor (int j = 0; j < t.length(); j+
amir-ammar
NORMAL
2022-03-22T06:49:00.531353+00:00
2022-03-22T06:49:00.531386+00:00
267
false
\tpublic int countSubstrings(String s, String t) {\n\t\t\tint ans = 0;\n\t\t\tfor (int i = 0; i < s.length(); i++) {\n\t\t\t\tfor (int j = 0; j < t.length(); j++) {\n\t\t\t\t\tint diff = 0;\n\t\t\t\t\tint x = i;\n\t\t\t\t\tint y = j;\n\t\t\t\t\twhile (x<s.length() && y<t.length()){\n\t\t\t\t\t\tif(s.charAt(x)!=t.charAt(y)) diff++;\n\t\t\t\t\t\tif(diff == 1) ans++;\n\t\t\t\t\t\tif(diff==2) break;\n\t\t\t\t\t\tx++;\n\t\t\t\t\t\ty++;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn ans;\n\t\t}
1
0
['Java']
0
count-substrings-that-differ-by-one-character
C++ || 100% FAST || O(N ^ 3)
c-100-fast-on-3-by-easy_coder-1c47
```\nclass Solution {\npublic:\n int countSubstrings(string s, string t) {\n int m = s.size(), n = t.size(), ans = 0;\n \n for(int i=0
Easy_coder
NORMAL
2022-02-08T07:30:43.425914+00:00
2022-02-08T07:30:43.425944+00:00
189
false
```\nclass Solution {\npublic:\n int countSubstrings(string s, string t) {\n int m = s.size(), n = t.size(), ans = 0;\n \n for(int i=0; i<m ; i++){\n for(int j=0; j<n; j++){\n int left = 1, right = 1;\n if(s[i] == t[j]) continue;\n \n // to left\n \n \n while(i - left >= 0 && j - left >= 0 && s[i - left] == t[j - left]) left++;\n \n // to right\n \n while(i + right < m && j + right < n && s[i + right] == t[j + right]) right++; \n ans += left * right;\n }\n }\n \n return ans;\n }\n};
1
0
['C']
0
count-substrings-that-differ-by-one-character
SImple JAVA Solution
simple-java-solution-by-prachiigoyal-vgxr
\nclass Solution {\n public int countSubstrings(String s, String t) {\n int count=0;\n for(int i=0;i<s.length();i++){\n for(int j=0;
prachiigoyal
NORMAL
2022-01-28T18:54:44.467977+00:00
2022-01-28T18:54:44.468042+00:00
251
false
```\nclass Solution {\n public int countSubstrings(String s, String t) {\n int count=0;\n for(int i=0;i<s.length();i++){\n for(int j=0;j<t.length();j++){\n int x=i;\n int y=j;\n int d=0;\n while(x<s.length() && y<t.length()){\n if(s.charAt(x)!=t.charAt(y)){\n d++;\n }\n if(d==1) count++;\n if(d==2) break;\n x++;\n y++;\n }\n }\n }\n return count;\n }\n}\n```
1
0
['Java']
0
count-substrings-that-differ-by-one-character
Java Dp
java-dp-by-prathihaspodduturi-665d
\nclass Solution {\n public int countSubstrings(String s, String t) {\n int ans=0,n=s.length(),m=t.length();\n int dp[][]=new int[n+1][m+1];\n
prathihaspodduturi
NORMAL
2021-10-25T05:35:48.090375+00:00
2021-10-25T05:35:48.090416+00:00
220
false
```\nclass Solution {\n public int countSubstrings(String s, String t) {\n int ans=0,n=s.length(),m=t.length();\n int dp[][]=new int[n+1][m+1];\n int tp[][]=new int[n+1][m+1];\n for(int i=n-1;i>=0;i--)\n {\n for(int j=m-1;j>=0;j--)\n {\n if(s.charAt(i)==t.charAt(j))\n {\n dp[i][j]=dp[i+1][j+1]+1;\n tp[i][j]=tp[i+1][j+1];\n }\n else\n {\n tp[i][j]=dp[i+1][j+1]+1;\n }\n ans=ans+tp[i][j];\n }\n }\n return ans;\n }\n}\n```
1
0
[]
0
count-substrings-that-differ-by-one-character
Java Solution in more efficient way
java-solution-in-more-efficient-way-by-v-4yy8
\nclass Solution {\n\tpublic int countSubstrings(String s, String t) {\n\t\tint r = s.length();\n\t\tint c = t.length();\n\t\tint[][] dp = new int[r][c];\n\t\ti
victordey2007
NORMAL
2021-10-14T14:53:49.378510+00:00
2022-01-21T15:30:57.412832+00:00
210
false
```\nclass Solution {\n\tpublic int countSubstrings(String s, String t) {\n\t\tint r = s.length();\n\t\tint c = t.length();\n\t\tint[][] dp = new int[r][c];\n\t\tint resp = 0;\n\t\tfor (int i = 0; i < r; i++) {\n\t\t\tfor (int j = 0; j < c; j++) {\n\t\t\t\tif (s.charAt(i) != t.charAt(j))\n\t\t\t\t\tdp[i][j] = 1;\n\n\t\t\t\tint p = i;\n\t\t\t\tint q = j;\n\t\t\t\tint count = 0;\n\t\t\t\twhile (p >= 0 && q >= 0) {\n\t\t\t\t\tcount = count + dp[p][q];\n\n\t\t\t\t\tif (count > 1)\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tif (count == 1)\n\t\t\t\t\t\tresp = resp + 1;\n\t\t\t\t\tp--;\n\t\t\t\t\tq--;\n\n\t\t\t\t}\n\n\t\t\t}\n\t\t}\n\n\t\treturn resp;\n\t}\n}\n```
1
1
[]
1
count-substrings-that-differ-by-one-character
Java Solution
java-solution-by-arunindian10-cmhg
\tclass Solution {\n public int countSubstrings(String s, String t) {\n int m = s.length();\n int n = t.length();\n int res = 0;\n
arunindian10
NORMAL
2021-09-23T18:58:54.162991+00:00
2021-09-23T18:58:54.163037+00:00
170
false
\tclass Solution {\n public int countSubstrings(String s, String t) {\n int m = s.length();\n int n = t.length();\n int res = 0;\n for(int i = 0; i < m; i++)\n {\n for(int j = 0; j < n; j++)\n {\n int diff = 0;\n for(int k = i, l = j; k < m && l < n; k++, l++)\n {\n if(s.charAt(k) != t.charAt(l))\n {\n if(diff > 0)\n {\n break;\n }\n \n res++;\n diff++;\n }\n else if(diff == 1)\n {\n res++;\n }\n }\n }\n }\n \n return res;\n }\n\t}
1
0
[]
0
count-substrings-that-differ-by-one-character
Python soln
python-soln-by-heckt27-ddv7
\nclass Solution:\n def countSubstrings(self, s: str, t: str) -> int:\n ans=0\n arr=[]\n for i in range(len(s)):#Get All Substrings\n
heckt27
NORMAL
2021-07-22T13:24:48.968564+00:00
2021-07-22T13:24:48.968611+00:00
421
false
```\nclass Solution:\n def countSubstrings(self, s: str, t: str) -> int:\n ans=0\n arr=[]\n for i in range(len(s)):#Get All Substrings\n for j in range(i+1,len(s)+1):\n arr.append(s[i:j])\n \n for w in arr:\n i=0\n j=len(w)\n while j<=len(t):\n wrd=t[i:j]\n k=1#Only one difference allowed\n flag=True\n for m in range(len(wrd)):\n if w[m]!=wrd[m]:\n if k==1:\n k=0\n else:\n flag=False\n break\n if flag and k==0:\n ans+=1\n i+=1\n j+=1\n return ans\n```
1
0
['Python3']
0
count-substrings-that-differ-by-one-character
Just brutal force O(n2) for such boring question
just-brutal-force-on2-for-such-boring-qu-c9ct
scala\n def countSubstrings(s: String, t: String): Int = {\n\n val sl = s.length\n val tl = t.length\n (0 until sl)\n .map(i => {\n (0 unt
qiuqiushasha
NORMAL
2021-06-14T01:55:12.582597+00:00
2021-06-14T01:55:12.582636+00:00
245
false
```scala\n def countSubstrings(s: String, t: String): Int = {\n\n val sl = s.length\n val tl = t.length\n (0 until sl)\n .map(i => {\n (0 until tl)\n .filter(s.charAt(i) != t.charAt(_))\n .map(j => {\n var a = i + 1\n var b = j + 1\n while (a < sl && b < tl && s.charAt(a) == t.charAt(b)) { a += 1; b += 1 }\n val right = a - i - 1\n a = i - 1\n b = j - 1\n while (a >= 0 && b >= 0 && s.charAt(a) == t.charAt(b)) { a -= 1; b -= 1 }\n val left = i - a - 1\n right * left + right + left + 1\n\n })\n .sum\n\n })\n .sum\n\n }\n```
1
1
[]
1
count-substrings-that-differ-by-one-character
JavaScript Solution - Brute Force
javascript-solution-brute-force-by-deadi-dsko
\nvar countSubstrings = function(s, t) {\n const count1 = countAllSubstr(s);\n const count2 = countAllSubstr(t);\n \n let res = 0;\n \n for (c
Deadication
NORMAL
2021-04-27T12:10:18.541546+00:00
2021-04-27T12:10:18.541574+00:00
188
false
```\nvar countSubstrings = function(s, t) {\n const count1 = countAllSubstr(s);\n const count2 = countAllSubstr(t);\n \n let res = 0;\n \n for (const [substr1, freq1] of count1) {\n for (const [substr2, freq2] of count2) {\n \n if (differByOneChar(substr1, substr2)) {\n res += freq1 * freq2;\n }\n }\n }\n \n return res;\n \n \n function countAllSubstr(str) {\n const n = str.length;\n const count = new Map();\n \n for (let i = 0; i < n; i++) {\n let substr = ""; \n for (let j = i; j < n; j++) {\n substr += str.charAt(j);\n \n if (!count.has(substr)) count.set(substr, 0);\n count.set(substr, count.get(substr) + 1);\n }\n }\n \n return count;\n }\n \n function differByOneChar(str1, str2) {\n if (str1.length != str2.length) return false;\n \n const n = str1.length;\n \n let missed = 0;\n \n for (let i = 0; i < n; i++) {\n const char1 = str1.charAt(i);\n const char2 = str2.charAt(i);\n \n if (char1 != char2) missed++;\n \n if (missed > 1) return false;\n }\n \n return missed === 1;\n }\n \n}; \n```
1
0
['JavaScript']
0
count-substrings-that-differ-by-one-character
Python 3 - simple counting
python-3-simple-counting-by-yunqu-9kee
From each character in string s, and character t, 2 cases may appear:\n\n1. If the current characters differ, go ahead and make sure the remaining characters ar
yunqu
NORMAL
2021-04-25T14:56:31.338433+00:00
2021-04-25T14:57:34.353765+00:00
179
false
From each character in string s, and character t, 2 cases may appear:\n\n1. If the current characters differ, go ahead and make sure the remaining characters are equal. When enlarging the substring, increment answer by 1 each time.\n2. If the current characters are the same, go ahead and look for the first pair of characters that are different, and then go back to case 1.\n\n\n```python\nclass Solution:\n def countSubstrings(self, s: str, t: str) -> int:\n n1, n2 = len(s), len(t)\n ans = 0\n\n for i1, c1 in enumerate(s):\n for i2, c2 in enumerate(t):\n i, j = i1, i2\n\t\t\t\t# case 2\n while i < n1 and j < n2 and s[i] == t[j]:\n i += 1\n j += 1\n\t\t\t\t# case 1\n if i < n1 and j < n2 and s[i] != t[j]:\n i += 1\n j += 1\n ans += 1\n while i < n1 and j < n2 and s[i] == t[j]:\n i += 1\n j += 1\n ans += 1\n return ans\n```
1
0
[]
0
count-substrings-that-differ-by-one-character
Python 3, True Brute Force, Explained
python-3-true-brute-force-explained-by-l-ue5f
~~~\nclass Solution:\n def countSubstrings(self, s: str, t: str) -> int:\n res = 0\n length_s, length_t = len(s), len(t)\n for i in rang
lucliu
NORMAL
2021-04-09T21:49:32.973026+00:00
2021-04-09T21:49:32.973058+00:00
564
false
~~~\nclass Solution:\n def countSubstrings(self, s: str, t: str) -> int:\n res = 0\n length_s, length_t = len(s), len(t)\n for i in range(1, length_s+1): # finding out all possbile substrings in "s" sorted by the "s" length.\n for j in range(length_s-i+1): # listing all possbile substrings in "s" with length been i.\n for k in range(length_t-i+1): # listing all possbile substrings in "t" with length been i.\n # print("s:", s[j:j+i], "t:", t[k:k+i])\n cnt = 0\n for x, y in zip(s[j:j+i], t[k:k+i]):\n if x != y:\n cnt += 1\n if cnt > 1:\n break\n if cnt <= 1 and cnt != 0:\n res += 1\n return res\n~~~\n\n#Runtime: 1240 ms, faster than 15.64% of Python3 online submissions for Count Substrings That Differ by One Character.\n#Memory Usage: 14 MB, less than 96.92% of Python3 online submissions for Count Substrings That Differ by One Character.\n
1
0
['Python', 'Python3']
0
count-substrings-that-differ-by-one-character
c++ very simple solution
c-very-simple-solution-by-user7415ba-smtm
\nclass Solution {\npublic:\n int countSubstrings(string s, string t) {\n int SN = s.length(), TN = t.length();\n int res = 0;\n for(int
user7415ba
NORMAL
2021-04-06T00:10:40.034928+00:00
2021-04-06T00:10:40.034959+00:00
255
false
```\nclass Solution {\npublic:\n int countSubstrings(string s, string t) {\n int SN = s.length(), TN = t.length();\n int res = 0;\n for(int i = 0; i < SN; ++i) {\n for(int j = 0; j < TN; ++j) {\n int p = i, q = j, diff = 0;\n while(p < SN && q < TN) {\n if(s[p++] != t[q++]) {\n diff++;\n if(diff > 1) {\n break;\n }\n }\n if(diff == 1) {\n res++;\n }\n }\n }\n }\n return res;\n }\n};\n```
1
0
[]
0
count-substrings-that-differ-by-one-character
Python solution with comments
python-solution-with-comments-by-flyings-r1d6
class Solution:\n\n def countSubstrings(self, s: str, t: str) -> int:\n ans = 0\n for i in range(len(s)): # for every substring starting with s
flyingspa
NORMAL
2021-04-05T13:29:40.212374+00:00
2021-04-05T13:29:40.212420+00:00
319
false
class Solution:\n\n def countSubstrings(self, s: str, t: str) -> int:\n ans = 0\n for i in range(len(s)): # for every substring starting with s[i], we search all possible starting index in t\n for j in range(len(t)):\n start_s, start_t = i, j\n count = 0\n while(start_s<len(s) and start_t<len(t)):\n if s[start_s]!=t[start_t]: # if current letter is different, add one to the count\n count+=1\n if count==1: # only if count == 1 we add 1 to the ans\n ans+=1\n if count>=2: # early stop for two or more diffferent letters\n break\n start_s+=1\n start_t+=1\n return ans
1
0
['Python']
1
count-substrings-that-differ-by-one-character
c++ Brute force but efficient 4ms
c-brute-force-but-efficient-4ms-by-harsh-k1il
\nclass Solution {\npublic:\n int countSubstrings(string s, string t) {\n int ans = 0;\n for(int i=0;i<s.length();i++){\n for(int j=
harshjee2018
NORMAL
2021-02-11T06:23:40.731271+00:00
2021-02-11T06:23:40.731321+00:00
141
false
```\nclass Solution {\npublic:\n int countSubstrings(string s, string t) {\n int ans = 0;\n for(int i=0;i<s.length();i++){\n for(int j=0;j<t.size();j++){\n int x = i;\n int y = j;\n int d = 0;\n while(x<s.length()&&y<t.length()){\n if(s[x]!=t[y])\n d++;\n if(d==1) ans++;\n if(d==2) break;\n \n x++;\n y++;\n }\n }\n }\n return ans;\n }\n};\n```
1
0
[]
0
count-substrings-that-differ-by-one-character
Simple Java solution using Trie for slow learners like myself (2ms)
simple-java-solution-using-trie-for-slow-28s6
The idea is to create all possible substrings of s and store it in trie.\n\nThen iterate all possible substrings of t and try finding a match in the trie.\n\n\n
dumbleeter
NORMAL
2021-01-23T02:00:02.596210+00:00
2021-01-23T02:02:27.658593+00:00
249
false
The idea is to create all possible substrings of s and store it in trie.\n\nThen iterate all possible substrings of t and try finding a match in the trie.\n\n```\nclass Solution {\n public int countSubstrings(String s, String t) {\n s = s == null ? "" : s;\n t = t == null ? "" : t;\n if (s.length() > t.length())\n return countSubstrings(t, s);\n \n Node root = buildTrie(s);\n int count = 0;\n char[] arr = t.toCharArray();\n \n for (int i = 0; i < t.length(); i++) \n count += findMatch(root, arr, i, false);\n \n return count;\n }\n \n private int findMatch(Node root, char[] arr, int pos, boolean used) {\n if (root == null || pos == arr.length)\n return 0;\n char c = arr[pos];\n int total = 0;\n if (used) {\n if (root.nodes[c - \'a\'] == null)\n return 0;\n return root.nodes[c - \'a\'].count + findMatch(root.nodes[c - \'a\'], arr, pos + 1, true);\n }\n \n for (char a = \'a\'; a <= \'z\'; a++) {\n if (root.nodes[a - \'a\'] == null)\n continue;\n if (a == c)\n total += findMatch(root.nodes[a - \'a\'], arr, pos + 1, false);\n else\n total += (findMatch(root.nodes[a - \'a\'], arr, pos + 1, true) + root.nodes[a - \'a\'].count);\n }\n \n return total;\n }\n \n private static final class Node {\n final Node[] nodes = new Node[26];\n int count = 0;\n }\n \n private Node buildTrie(String s) {\n Node root = new Node();\n char[] arr = s.toCharArray();\n for (int i = 0; i < s.length(); i++)\n insert(root, arr, i);\n return root;\n }\n \n private void insert(Node root, char[] arr, int start) {\n int len = arr.length, size = 0;\n Node cur = root;\n \n while (start < len) {\n char c = arr[start++];\n if (cur.nodes[c - \'a\'] == null)\n cur.nodes[c - \'a\'] = new Node(); \n cur = cur.nodes[c - \'a\'];\n cur.count++;\n }\n }\n}\n```
1
0
[]
0
count-substrings-that-differ-by-one-character
JavaScript Brute Force Code
javascript-brute-force-code-by-swolecode-e10s
\n\n\n```\n/*\n * @param {string} s\n * @param {string} t\n * @return {number}\n /\nvar countSubstrings = function(s, t) {\n \n let ans = 0;\n \n fo
swolecoder
NORMAL
2021-01-23T01:26:08.461617+00:00
2021-01-23T01:26:08.461644+00:00
97
false
\n\n\n```\n/**\n * @param {string} s\n * @param {string} t\n * @return {number}\n */\nvar countSubstrings = function(s, t) {\n \n let ans = 0;\n \n for(let i=0; i < s.length; i++){\n for(let j=0; j < t.length; j++){\n \n let x = i;\n let y = j;\n let d = 0\n while(x < s.length && y < t.length){\n if(s[x] != t[y])d++;\n if(d ==1)ans++;\n if(d ==2)break\n x++;\n y++\n \n }\n \n \n }\n }\n \n return ans\n};
1
0
[]
0
count-substrings-that-differ-by-one-character
0 ms, faster than 100.00% | Memory Usage: 6.1 MB, less than 100.00%
0-ms-faster-than-10000-memory-usage-61-m-ild2
inspired from https://leetcode.com/pintushingade100 \'s brilliant solution.\n\nclass Solution {\npublic:\n int countSubstrings(string&s, string&t) {\n
maverick09
NORMAL
2021-01-13T08:21:09.872511+00:00
2021-01-13T08:21:09.872539+00:00
225
false
inspired from https://leetcode.com/pintushingade100 \'s brilliant solution.\n```\nclass Solution {\npublic:\n int countSubstrings(string&s, string&t) {\n int szs=s.length(),szt=t.length(),res=0;\n for(int i=0;i<szs;++i){\n for(int j=0;j<szt;++j){\n int x=i,y=j,dif=0;\n for(;x<szs && y<szt && dif<2;++x,++y){\n if(s[x]!=t[y])\n ++dif;\n if(dif==1)\n ++res;\n }\n }\n }\n return res;\n }\n};\n```
1
0
[]
0
count-substrings-that-differ-by-one-character
C++ simple easy modified brute force with a trick, all test cases passed
c-simple-easy-modified-brute-force-with-7tmnd
\nclass Solution {\npublic:\n \n bool one_diff(string a, string b){\n int d=0;\n if(a.size()!=b.size())\n return false;\n
chase_master_kohli
NORMAL
2020-12-19T18:13:20.860832+00:00
2020-12-19T18:13:20.860870+00:00
123
false
```\nclass Solution {\npublic:\n \n bool one_diff(string a, string b){\n int d=0;\n if(a.size()!=b.size())\n return false;\n if(a.size()==b.size()){\n int n=a.size();\n for(int i=0;i<n;i++){\n if(a[i]!=b[i]){\n d++;\n }\n if(d>1)\n return false;\n }\n }\n return d==1;\n }\n \n int countSubstrings(string s, string t) {\n int count=0;\n int n=s.size(),m=t.size();\n for(int i=0;i<n;i++){\n for(int j=1;j<=n-i;j++){\n for(int k=0;k<m;k++){\n int l=min(m-k,j);\n if(one_diff(s.substr(i,j),t.substr(k,l)))\n count++;\n }\n }\n }\n return count;\n }\n};\n```
1
0
[]
0
count-substrings-that-differ-by-one-character
C++ Trie Tree
c-trie-tree-by-xpharry-sz9o
\nstruct TrieNode {\n TrieNode* children[26];\n bool is_end;\n int count;\n \n TrieNode() {\n memset(children, 0, sizeof(children));\n
xpharry
NORMAL
2020-12-03T00:22:26.389623+00:00
2020-12-03T00:22:26.389671+00:00
316
false
```\nstruct TrieNode {\n TrieNode* children[26];\n bool is_end;\n int count;\n \n TrieNode() {\n memset(children, 0, sizeof(children));\n is_end = false;\n count = 0;\n }\n};\n\nclass Solution {\npublic:\n int countSubstrings(string s, string t) {\n TrieNode* root = new TrieNode();\n int ret = 0;\n \n for(int i = 0; i < s.size(); i++) {\n insert(root, s, i, s.size());\n }\n \n for(int i = 0; i < t.size(); i++) {\n search(root, t, i, t.size(), 0, ret);\n }\n\n return ret;\n }\n\nprivate:\n void insert(TrieNode* root, string word, int i, int len) {\n root->is_end = true;\n root->count += 1;\n \n if(i >= len) return;\n \n if(root->children[word[i]-\'a\'] == nullptr) {\n root->children[word[i]-\'a\'] = new TrieNode();\n }\n \n insert(root->children[word[i]-\'a\'], word, i+1, len);\n }\n \n void search(TrieNode* root, string word, int i, int len, int mismatches, int& ret) {\n if(mismatches > 1) return;\n \n if(1) {\n if(mismatches == 1) {\n ret += root->count;\n }\n }\n \n if(i >= len) return;\n \n for(int k = 0; k < 26; k++) {\n if(root->children[k]) {\n if(k == word[i]-\'a\') {\n search(root->children[k], word, i+1, len, mismatches, ret);\n } else {\n search(root->children[k], word, i+1, len, mismatches+1, ret);\n }\n }\n }\n }\n};\n```
1
3
[]
0
count-substrings-that-differ-by-one-character
Rust Trie
rust-trie-by-michielbaird-d57b
Fix size try node for the 26 letters of the alphabet. All suffixes of s are inserted into the Trie. We also keep track in the TrieNode\nof the amount of times e
michielbaird
NORMAL
2020-11-19T04:18:15.245510+00:00
2020-11-19T04:18:15.245539+00:00
230
false
Fix size try node for the 26 letters of the alphabet. All suffixes of `s` are inserted into the Trie. We also keep track in the TrieNode\nof the amount of times each node can be reached. \n\nI decided to generalize the count method, so you technically could use this solution to track a substring difference of any size.\n\n```\n#[derive(Debug)]\nstruct Trie {\n children: [Option<Box<Trie>>; 26],\n count: usize,\n}\n\nimpl Trie {\n fn new() -> Self {\n Self {\n children: Default::default(),\n count: 0,\n }\n }\n fn insert(&mut self, word: &[u8], index: usize) {\n self.count += 1;\n if word.len() == index {\n return;\n }\n let v = (word[index] - b\'a\') as usize;\n if self.children[v].is_none() {\n self.children[v] = Some(Box::new(Self::new()));\n }\n self.children[v].as_mut().unwrap().insert(word, index+1);\n }\n fn count_one_diff(&self, word: &[u8], index: usize, allowed: usize, answer: &mut i32) {\n if word.len() == index {\n return;\n }\n let v = (word[index] - b\'a\') as usize;\n if self.children[v].is_some() {\n let child_ref = self.children[v].as_ref().unwrap();\n if allowed == 0 {\n *answer += child_ref.count as i32;\n }\n child_ref.count_one_diff(word, index+1, allowed, answer);\n }\n if allowed > 0 {\n for i in 0..self.children.len() {\n if v != i && self.children[i].is_some() {\n let child_ref = self.children[i].as_ref().unwrap();\n if allowed == 1 {\n *answer += child_ref.count as i32;\n }\n child_ref.count_one_diff(word, index+1, allowed-1, answer);\n }\n }\n }\n }\n}\n\nimpl Solution {\n pub fn count_substrings(s: String, t: String) -> i32 {\n let mut root = Trie::new();\n for i in 0..s.len() {\n root.insert(&s.as_bytes()[i..], 0);\n }\n root.count = 0; // This is unnecessary...\n let mut answer = 0;\n for i in 0..t.len() {\n root.count_one_diff(&t.as_bytes()[i..], 0, 1, &mut answer);\n }\n \n answer\n }\n}\n```
1
1
['Rust']
1
count-substrings-that-differ-by-one-character
Python Trie O(N^2)
python-trie-on2-by-lijinc100-978c
```\nfrom collections import defaultdict\nclass TrieNode:\n def init(self):\n self.is_word = False\n self.count = 0\n self.children = {}
lijinc100
NORMAL
2020-11-13T07:00:17.117966+00:00
2020-11-13T07:00:28.125849+00:00
254
false
```\nfrom collections import defaultdict\nclass TrieNode:\n def __init__(self):\n self.is_word = False\n self.count = 0\n self.children = {}\n\t\t\ndef insert(node, word, i, j):\n node.is_word = True\n node.count +=1\n if i >=j:\n return\n if word[i] in node.children:\n insert(node.children[word[i]], word, i+1, j)\n else:\n node.children[word[i]] = TrieNode()\n insert(node.children[word[i]], word, i+1, j)\n \ndef search(node, word, i, j, mismatch_count, result):\n if mismatch_count >1:\n return\n if node.is_word:\n if mismatch_count ==1:\n result[0] += node.count\n if i>=j:\n return\n for child, child_node in node.children.items():\n if child == word[i]:\n search(child_node, word, i+1, j, mismatch_count, result)\n else:\n search(child_node, word, i+1, j, mismatch_count+1, result)\n \ndef countSubstrings(s, t):\n root = TrieNode() \n for i in range(len(s)):\n insert(root, s, i, len(s))\n result = [0]\n for i in range(len(t)):\n search(root, t, i, len(t), 0, result)\n return result[0]\n
1
1
[]
2
count-substrings-that-differ-by-one-character
Java two round of DP. Space O(M*N), Time O(M*N)
java-two-round-of-dp-space-omn-time-omn-nx2hm
First loop, dp is for count of same substring starts from i and j. If s[i]==t[j], dp[i][j]=1+dp[i+1][j+1], otherwise 0.\n\nSecond loop, res is for count of targ
DaviLu
NORMAL
2020-11-05T03:50:24.777332+00:00
2020-11-05T03:50:24.777382+00:00
156
false
First loop, `dp` is for count of same substring starts from `i` and `j`. If `s[i]==t[j]`, `dp[i][j]=1+dp[i+1][j+1]`, otherwise `0`.\n\nSecond loop, `res` is for count of target substring with one diff starts from `i` and `j`. if `s[i]==t[j]`, `res[i][j]=res[i+1][j+1]`(add both to front of `res[i+1][j+1]`), otherwise is `res[i][j]=1+dp[i+1][j+1]`(add both to front of `dp[i+1][j+1]`, plus `1` for themself). Meanwhile `sum` of `res[i][j]` is the result.\n```\nclass Solution {\n public int countSubstrings(String s, String t) {\n var sl=s.length();\n var tl=t.length();\n var dp=new int[sl+1][tl+1];\n for(var i=sl-1;i>=0;i--) {\n for(var j=tl-1;j>=0;j--) {\n if(s.charAt(i)==t.charAt(j)) dp[i][j]=1+dp[i+1][j+1];\n }\n }\n \n var res=new int[sl+1][tl+1];\n var sum=0;\n for(var i=sl-1;i>=0;i--) {\n for(var j=tl-1;j>=0;j--) {\n if(s.charAt(i)==t.charAt(j)) res[i][j]=res[i+1][j+1]; \n else res[i][j]=1+dp[i+1][j+1];\n sum+=res[i][j];\n }\n }\n return sum;\n }\n}\n```
1
0
[]
1
count-substrings-that-differ-by-one-character
C++ O(N^3) Solution
c-on3-solution-by-ahsan83-tmo2
Runtime: 4 ms, faster than 88.92% of C++ online submissions for Count Substrings That Differ by One Character.\nMemory Usage: 6.7 MB, less than 5.49% of C++ onl
ahsan83
NORMAL
2020-11-03T00:12:25.699426+00:00
2020-11-03T00:13:10.651619+00:00
256
false
Runtime: 4 ms, faster than 88.92% of C++ online submissions for Count Substrings That Differ by One Character.\nMemory Usage: 6.7 MB, less than 5.49% of C++ online submissions for Count Substrings That Differ by One Character.\n\n\nTake substring from every pair of points of 0 to s.length and 0 to t.length and count the number of substrings\nwhich has exactly 1 mismatch.\n\n```\nclass Solution {\npublic:\n \n int countSubstrings(string s, string t) {\n \n // count of substring differ in 1 charecter only \n int count = 0;\n \n // take substring starting from every pair of points between 0 to s.length and 0 to t.length => O(N^2)\n // count the number of substring which has exactly 1 mismatch => O(N) \n for(int i=0;i<s.length();i++)\n {\n for(int j=0;j<t.length();j++)\n {\n int misMatch = 0;\n \n for(int k=0;i+k<s.length() && j+k<t.length();k++)\n {\n if(s[i+k]!=t[j+k])misMatch++;\n \n if(misMatch>1) break;\n \n count+= misMatch;\n }\n }\n }\n \n return count;\n }\n};\n```
1
0
['String', 'C']
0
count-substrings-that-differ-by-one-character
C++ O(mn) using dp
c-omn-using-dp-by-lituni-3col
use vector same[i][j] to record the number of same substrings that substr1 ends with s[i] and substr2 ends with t[j]\nuse vector diff[i][j] to record the numbse
lituni
NORMAL
2020-11-02T08:33:58.307619+00:00
2020-11-02T08:34:11.635687+00:00
133
false
use vector same[i][j] to record the number of same substrings that substr1 ends with s[i] and substr2 ends with t[j]\nuse vector diff[i][j] to record the numbser of substrings differ by one char that substr1 ends with s[i] and substr2 ends with t[j]\n\n```\nclass Solution {\npublic:\n int countSubstrings(string s, string t) {\n vector<vector<int>> same(s.size(), vector<int>(t.size(), 0));\n vector<vector<int>> diff(s.size(), vector<int>(t.size(), 0));\n if (s[0] == t[0]) {\n same[0][0] = 1;\n } else {\n diff[0][0] = 1;\n }\n int ret = diff[0][0];\n for (int i = 1; i < s.size(); i++) {\n if (s[i] == t[0]) same[i][0] = 1;\n else diff[i][0] = 1;\n ret += diff[i][0];\n }\n for (int j = 1; j < t.size(); j++) {\n if (s[0] == t[j]) same[0][j] = 1;\n else diff[0][j] = 1;\n ret += diff[0][j];\n }\n for (int i = 1; i < s.size(); i++) {\n for (int j = 1; j < t.size(); j++) {\n if (s[i] == t[j]) {\n diff[i][j] = diff[i - 1][j - 1];\n same[i][j] = same[i - 1][j - 1] + 1;\n } else {\n diff[i][j] = same[i - 1][j - 1] + 1;\n }\n ret += diff[i][j];\n }\n }\n return ret;\n }\n};\n```\nit is ok to replace 2D vectors with few variables, but lazy to do that.
1
0
[]
1
count-substrings-that-differ-by-one-character
Rust from votrubac, 4ms 100%
rust-from-votrubac-4ms-100-by-qiuzhanghu-5f6y
rust\nimpl Solution {\n pub fn count_substrings(s: String, t: String) -> i32 {\n let mut ans = 0;\n let mut dpl = vec![vec![0; 101]; 101];\n
qiuzhanghua
NORMAL
2020-11-01T02:38:16.420921+00:00
2020-11-01T02:38:16.420955+00:00
69
false
```rust\nimpl Solution {\n pub fn count_substrings(s: String, t: String) -> i32 {\n let mut ans = 0;\n let mut dpl = vec![vec![0; 101]; 101];\n let mut dpr = vec![vec![0; 101]; 101];\n for i in 1..=s.len() {\n for j in 1..=t.len() {\n if s.as_bytes()[i - 1] == t.as_bytes()[j - 1] {\n dpl[i][j] = 1 + dpl[i - 1][j - 1];\n }\n }\n }\n\n for i in (1..=s.len()).rev() {\n for j in (1..=t.len()).rev() {\n if s.as_bytes()[i - 1] == t.as_bytes()[j - 1] {\n dpr[i - 1][j - 1] = 1 + dpr[i][j];\n }\n }\n }\n\n for i in 0..s.len() {\n for j in 0..t.len() {\n if s.as_bytes()[i] != t.as_bytes()[j] {\n ans += (dpl[i][j] + 1) * (dpr[i + 1][j + 1] + 1);\n }\n }\n }\n\n ans\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n\n #[test]\n fn test_count_substrings() {\n assert_eq!(\n Solution::count_substrings("aba".to_owned(), "baba".to_owned()),\n 6\n );\n }\n\n #[test]\n fn test_count_substrings_02() {\n assert_eq!(\n Solution::count_substrings("ab".to_owned(), "bb".to_owned()),\n 3\n );\n }\n\n #[test]\n fn test_count_substrings_03() {\n assert_eq!(\n Solution::count_substrings("a".to_owned(), "a".to_owned()),\n 0\n );\n }\n\n #[test]\n fn test_count_substrings_04() {\n assert_eq!(\n Solution::count_substrings("abe".to_owned(), "bbc".to_owned()),\n 10\n );\n }\n}\n```
1
1
[]
0
count-substrings-that-differ-by-one-character
Python 60ms, O(n^2), Trie + DFS
python-60ms-on2-trie-dfs-by-alanmiller-oydy
Construct a trie counting the number of substrings of t. It takes O(n^2).\nStarting at different characters in s with index i, use a dfs to sum up how many vali
alanmiller
NORMAL
2020-10-31T19:27:57.870822+00:00
2020-10-31T19:27:57.870852+00:00
190
false
Construct a trie counting the number of substrings of t. It takes O(n^2).\nStarting at different characters in s with index i, use a dfs to sum up how many valid substrings are there in s[i:]. Then sum up all i.\n\n\'\'\'\n\n\n def countSubstrings(self, s: str, t: str) -> int:\n Trie = lambda: defaultdict(Trie)\n trie = Trie()\n \n for i in range(n):\n node = trie\n for x in t[i:]:\n node = node[x]\n if \'end\' in node:\n node[\'end\'] += 1\n else:\n node[\'end\'] = 1\n \n\n \n ans = 0\n m = len(s)\n\n def helper(i, node = trie, p = 1):\n\n if i == m:\n return node[\'end\']*(1 - p)\n \n ans = node[\'end\']*(1 - p) if \'end\' in node else 0\n for x in node:\n if x != s[i] and p and x != \'end\':\n ans += helper(i + 1, node[x], 0)\n elif x == s[i]:\n ans += helper(i + 1, node[x], p)\n\n return ans\n \n\n for i in range(m):\n ans += helper(i)\n return ans\n\n\'\'\'
1
1
[]
0
largest-plus-sign
Java/C++/Python O(N^2) solution using only one grid matrix
javacpython-on2-solution-using-only-one-8d297
Algorithms: For each position (i, j) of the grid matrix, we try to extend in each of the four directions (left, right, up, down) as long as possible, then take
fun4leetcode
NORMAL
2018-01-14T18:23:52.082000+00:00
2019-11-11T00:08:26.813399+00:00
24,315
false
**Algorithms**: For each position `(i, j)` of the `grid` matrix, we try to extend in each of the four directions (left, right, up, down) as long as possible, then take the minimum length of `1`\'s out of the four directions as the order of the largest axis-aligned plus sign centered at position `(i, j)`.\n\n---\n\n**Optimizations**: Normally we would need a total of five matrices to make the above idea work -- one matrix for the `grid` itself and four more matrices for each of the four directions. However, these five matrices can be combined into one using two simple tricks:\n\n1. For each position `(i, j)`, we are only concerned with the minimum length of `1`\'s out of the four directions. This implies we may combine the four matrices into one by only keeping track of the minimum length.\n\n2. For each position `(i, j)`, the order of the largest axis-aligned plus sign centered at it will be `0` if and only if `grid[i][j] == 0`. This implies we may further combine the `grid` matrix with the one obtained above.\n\n---\n\n**Implementations**:\n\n1. Create an `N-by-N` matrix `grid`, with all elements initialized with value `N`.\n2. Reset those elements to `0` whose positions are in the `mines` list.\n3. For each position `(i, j)`, find the maximum length of `1`\'s in each of the four directions and set `grid[i][j]` to the minimum of these four lengths. Note that there is a simple recurrence relation relating the maximum length of `1`\'s at current position with previous position for each of the four directions (labeled as `l`, `r`, `u`, `d`).\n4. Loop through the `grid` matrix and choose the maximum element which will be the largest axis-aligned plus sign of `1`\'s contained in the grid.\n\n---\n\n**Solutions**: Here is a list of solutions for Java/C++/Python based on the above ideas. All solutions run at `O(N^2)` time with `O(N^2)` extra space. Further optimizations are possible such as keeping track of the maximum plus sign currently available and terminating as early as possible if no larger plus sign can be found for current row/column.\n\n**Note**: For those of you who got confused by the logic within the first nested for-loop, refer to [andier\'s comment](https://leetcode.com/problems/largest-plus-sign/discuss/113314/JavaC++Python-O(N2)-solution-using-only-one-grid-matrix/114381) and [my comment](https://leetcode.com/problems/largest-plus-sign/discuss/113314/JavaC++Python-O(N2)-solution-using-only-one-grid-matrix/114382) below for a more clear explanation.\n\n**Java solution:**\n\n```\npublic int orderOfLargestPlusSign(int N, int[][] mines) {\n int[][] grid = new int[N][N];\n \n for (int i = 0; i < N; i++) {\n Arrays.fill(grid[i], N);\n }\n \n for (int[] m : mines) {\n grid[m[0]][m[1]] = 0;\n }\n \n for (int i = 0; i < N; i++) {\n for (int j = 0, k = N - 1, l = 0, r = 0, u = 0, d = 0; j < N; j++, k--) {\n grid[i][j] = Math.min(grid[i][j], l = (grid[i][j] == 0 ? 0 : l + 1)); // left direction\n grid[i][k] = Math.min(grid[i][k], r = (grid[i][k] == 0 ? 0 : r + 1)); // right direction\n grid[j][i] = Math.min(grid[j][i], u = (grid[j][i] == 0 ? 0 : u + 1)); // up direction\n grid[k][i] = Math.min(grid[k][i], d = (grid[k][i] == 0 ? 0 : d + 1)); // down direction\n }\n }\n \n int res = 0;\n \n for (int i = 0; i < N; i++) {\n for (int j = 0; j < N; j++) {\n res = Math.max(res, grid[i][j]);\n }\n }\n \n return res;\n}\n```\n\n<br>\n\n**C++ solution:**\n\n```\nint orderOfLargestPlusSign(int N, vector<vector<int>>& mines) {\n vector<vector<int>> grid(N, vector<int>(N, N));\n \n for (auto& m : mines) {\n grid[m[0]][m[1]] = 0;\n }\n \n for (int i = 0; i < N; i++) {\n for (int j = 0, k = N - 1, l = 0, r = 0, u = 0, d = 0; j < N; j++, k--) {\n grid[i][j] = min(grid[i][j], l = (grid[i][j] == 0 ? 0 : l + 1));\n grid[i][k] = min(grid[i][k], r = (grid[i][k] == 0 ? 0 : r + 1));\n grid[j][i] = min(grid[j][i], u = (grid[j][i] == 0 ? 0 : u + 1));\n grid[k][i] = min(grid[k][i], d = (grid[k][i] == 0 ? 0 : d + 1));\n }\n }\n \n int res = 0;\n \n for (int i = 0; i < N; i++) {\n for (int j = 0; j < N; j++) {\n res = max(res, grid[i][j]);\n }\n }\n \n return res;\n}\n```\n\n<br>\n\n**Python solution:**\n\n```\ndef orderOfLargestPlusSign(self, N, mines):\n """\n :type N: int\n :type mines: List[List[int]]\n :rtype: int\n """\n grid = [[N] * N for i in range(N)]\n \n for m in mines:\n grid[m[0]][m[1]] = 0\n \n for i in range(N):\n l, r, u, d = 0, 0, 0, 0\n \n for j, k in zip(range(N), reversed(range(N))):\n l = l + 1 if grid[i][j] != 0 else 0\n if l < grid[i][j]:\n grid[i][j] = l\n \n r = r + 1 if grid[i][k] != 0 else 0\n if r < grid[i][k]:\n grid[i][k] = r\n\n u = u + 1 if grid[j][i] != 0 else 0\n if u < grid[j][i]:\n grid[j][i] = u\n \n d = d + 1 if grid[k][i] != 0 else 0\n if d < grid[k][i]:\n grid[k][i] = d\n \n res = 0\n \n for i in range(N):\n for j in range(N):\n if res < grid[i][j]:\n res = grid[i][j]\n \n return res\n```
296
7
[]
37
largest-plus-sign
Intuitive| Explained with image | Short and Clean | C++
intuitive-explained-with-image-short-and-s6pt
Step 1: Create n x n matrix having all values 1 and assign the mines values as 0.\nStep 2: Create another 4 matrix (say lef, rig, top, bot).\n lef means left an
av1shek
NORMAL
2021-09-09T08:48:17.563923+00:00
2021-09-09T09:22:29.923979+00:00
5,346
false
**Step 1:** Create n x n matrix having all values 1 and assign the mines values as 0.\n**Step 2:** Create another 4 matrix (say lef, rig, top, bot).\n* ``` lef``` means left and ```lef[i][j]``` will represent no of continious block in left having values 1\n\t\t```lef[ 3 ][ 2 ] = 3```\n\t\t![image](https://assets.leetcode.com/users/images/0471bc00-e5e8-40e0-a166-beb0c62452a7_1631176416.7804954.png) \n\n* ``` rig``` means right and ```rig[i][j]``` will represent no of continious block in right having values 1\n\t\t```rig[ 3 ] [ 2 ] = 2```\n\t\t![image](https://assets.leetcode.com/users/images/db6685de-3044-4151-b786-231e391a0720_1631176553.0291495.png)\n\n* ``` top``` means top and ```top[i][j]``` will represent no of continious block in top having values 1\n\t\t```top[ 3 ] [ 2 ] = 4```\n\t\t![image](https://assets.leetcode.com/users/images/c1ed5229-65bb-46b0-a9fb-ea44fa621caa_1631176680.5248642.png)\n\n* ``` bot``` means bottom and ```bot[i][j]``` will represent no of continious block in bottom having values 1\n\t\t```bot[ 3 ] [ 2 ] = 3```\n\t\t![image](https://assets.leetcode.com/users/images/4caacd49-6037-44c8-9a81-fe9f101b413e_1631176732.806423.png)\n\n**Step 3:** Fill the above four matrix \n* If values inside a cell is equal to 0, means that cell can not be center of the plus sign, so just ignore those cells.\n* If values inside a cell is equal to 1, so value of this cell will be 1 more that other adjacent cells in different direction of corresponding matrix.\n* **Note:** For matrix ```bot```, ```rig``` we need the value of the cells from the bottom cell and right cell. But as we are moving ``` i = 0 to n```, ```j = 0 to n``` means from left to right and top to bottom so those cells are not filled yet. So we have to fill these two matrix from right to left and bottom to top. And in order to so, we just have to change the index ``` x = n - 1 - i```, ```y = n - 1 - j```.\n\n**Step 4:** For each index check what is maximum size of "+" symbol we can find. \nTo create "+" from a given index we have to choose all fours arms of equal length. So by selecting minimum of all the four arms we can get "+" sign of maximum size from that index.\n\n```min({3, 2, 4, 3}) = 2```\n![image](https://assets.leetcode.com/users/images/5c5511f0-ea03-4906-a6f9-cf7f976dee31_1631177082.7194176.png)\n\n**Code:** \n```\nint orderOfLargestPlusSign(int n, vector<vector<int>>& mines) {\n\n vector<vector<int>> mat(n, vector<int>(n, 1));\n for(auto it : mines)\n {\n int x = it[0] ;\n int y = it[1] ;\n mat[x][y] = 0;\n }\n\n vector<vector<int>> lef, rig, top, bot;\n lef = rig = top = bot = mat;\n\n for(int i=0;i<n;i++)\n {\n for(int j=0;j<n;j++)\n {\n int x = n - i - 1;\n int y = n - j - 1;\n if( (i>0) && top[i][j] ) top[i][j] += top[i-1][j];\n if( (j>0) && lef[i][j] ) lef[i][j] += lef[i][j-1];\n if( (x<n-1) && bot[x][y] ) bot[x][y] += bot[x+1][y];\n if( (y<n-1) && rig[x][y] ) rig[x][y] += rig[x][y+1];\n }\n }\n\n int ans = 0;\n for(int i=0;i<n;i++)\n for(int j=0;j<n;j++)\n ans = max(ans, min({lef[i][j], rig[i][j], top[i][j], bot[i][j]}));\n\n return ans;\n}\n```
128
1
['C']
16
largest-plus-sign
[C++] Easy Top Down DP - Clean & Concise
c-easy-top-down-dp-clean-concise-by-hiep-0i2j
Idea\n- Try all possible pair of (r, c) in range [0..n-1] as the center of the axis-aligned plus sign.\n\t- Get the length of 4 arms: RIGHT, DOWN, LEFT, UP\n\t-
hiepit
NORMAL
2021-09-10T03:41:27.685365+00:00
2021-09-10T04:26:20.664518+00:00
3,293
false
**Idea**\n- Try all possible pair of `(r, c)` in range `[0..n-1]` as the center of the **axis-aligned plus sign**.\n\t- Get the length of 4 arms: RIGHT, DOWN, LEFT, UP\n\t- The size of **plus-sign** is the minimum between 4 arms.\n- Choose the sign with have the maximum size.\n- **HOW to get the length of 4 arms efficient?**\n\t- We can use **Dynamic Programming** to calculate the maximum size of 4 arms start with pos `(r, c)` in 4 directions: RIGHT, DOWN, LEFT, UP.\n\t- Let `dp(r, c, d)` is the longest arm start at cell `r, c` and extend in direction `d`. If we define `DIR = [0, 1, 0, -1, 0]`, then:\n\t\t- `d = 0` means RIGHT direction, corresponding to `(r + DIR[0], c + DIR[1])`\n\t\t- `d = 1` means DOWN direction, corresponding to `(r + DIR[1], c + DIR[2])`\n\t\t- `d = 2` means LEFT direction, corresponding to `(r + DIR[2], c + DIR[3])`\n\t\t- `d = 3` means TOP direction, corresponding to `(r + DIR[3], c + DIR[4])`\n\t- Base case: If `(r, c)` is out of bound or `grid[r][c] is a mined cell` then `dp(r, c, d) = 0`.\n\t- Transition state: `dp(r, c, d) = dp(r + DIR[i], c + DIR[i+1], d) + 1`.\n```c++\nclass Solution {\npublic:\n int orderOfLargestPlusSign(int n, vector<vector<int>>& mines) {\n vector<vector<bool>> isMine(n, vector<bool>(n, false));\n for (auto& pos: mines) isMine[pos[0]][pos[1]] = true;\n int ans = 0;\n for (int r = 0; r < n; ++r) {\n for (int c = 0; c < n; ++c) {\n int plusSignSize = dpMaxArm(n, isMine, r, c, 0);\n for (int d = 1; d < 4; ++d)\n plusSignSize = min(plusSignSize, dpMaxArm(n, isMine, r, c, d));\n ans = max(ans, plusSignSize);\n }\n }\n return ans;\n }\n\n int DIR[5] = {0, 1, 0, -1, 0};\n int memo[500][500][4] = {};\n int dpMaxArm(int n, vector<vector<bool>>& isMine, int r, int c, int d) {\n if (r < 0 or r >= n or c < 0 or c >= n or isMine[r][c]) return 0;\n if (memo[r][c][d] != 0) return memo[r][c][d];\n return memo[r][c][d] = dpMaxArm(n, isMine, r + DIR[d], c + DIR[d+1], d) + 1;\n }\n};\n```\n**Complexity**\n- Time: `O(N^2)`, where `N <= 500` is the side size of the square grid.\n- Space: `O(N^2)`\n\nIf you think this **post is useful**, I\'m happy if you **give a vote**. Any **questions or discussions are welcome!** Thank a lot.
51
4
[]
4
largest-plus-sign
java simple DP solution, using one matrix, easy to undersatnd
java-simple-dp-solution-using-one-matrix-58xs
\n public int orderOfLargestPlusSign(int N, int[][] mines) {\n int[][]M = new int[N][N];\n for(int[]arr : M){\n Arrays.fill(arr, 1);
yizeliu
NORMAL
2018-07-07T16:53:34.873800+00:00
2018-09-06T15:51:24.024142+00:00
4,203
false
```\n public int orderOfLargestPlusSign(int N, int[][] mines) {\n int[][]M = new int[N][N];\n for(int[]arr : M){\n Arrays.fill(arr, 1);\n }\n for(int[]arr : mines){\n M[arr[0]][arr[1]] = 0;\n }\n for(int i = 0; i < N; i++){\n int count = 0; //left\n for (int j = 0; j < N; j++) {\n if (M[i][j] != 0) {\n count++;\n } else {\n count = 0;\n }\n M[i][j] = count;\n }\n count = 0; //right\n for(int j = N - 1; j >= 0; j--){\n if (M[i][j] != 0){\n count++;\n } else {\n count = 0;\n }\n M[i][j] = Math.min(M[i][j], count);\n }\n }\n int result = 0;\n for(int j = 0; j < N; j++){\n int count = 0;\n for(int i = 0; i < N; i++){ //up\n if(M[i][j] != 0){\n count++;\n } else {\n count = 0;\n }\n M[i][j] = Math.min(M[i][j], count);\n }\n count = 0; //down\n for(int i = N-1; i >=0; i--){\n if(M[i][j] != 0){\n count++;\n } else {\n count = 0;\n }\n M[i][j] = Math.min(M[i][j], count);\n result = Math.max(result, M[i][j]);\n }\n }\n return result;\n }\n```
44
1
[]
5
largest-plus-sign
Python 250ms solution
python-250ms-solution-by-pedro-sa7v
\nfrom bisect import bisect_right\n\nclass Solution(object):\n def orderOfLargestPlusSign(self, N, mines):\n """\n :type N: int\n :type
pedro
NORMAL
2018-01-15T01:51:05.551000+00:00
2018-09-19T19:22:58.506711+00:00
4,135
false
```\nfrom bisect import bisect_right\n\nclass Solution(object):\n def orderOfLargestPlusSign(self, N, mines):\n """\n :type N: int\n :type mines: List[List[int]]\n :rtype: int\n """\n rows = [[-1, N] for _ in xrange(N)]\n cols = [[-1, N] for _ in xrange(N)]\n for r, c in mines:\n rows[r].append(c)\n cols[c].append(r)\n for i in xrange(N):\n rows[i].sort()\n cols[i].sort()\n mxp = 0\n for r in xrange(N):\n for i in xrange(len(rows[r])-1):\n left_b = rows[r][i]\n right_b = rows[r][i+1]\n for c in xrange(left_b+mxp+1, right_b-mxp):\n idx = bisect_right(cols[c], r)-1\n up_b = cols[c][idx]\n down_b = cols[c][idx+1]\n mxp = max(mxp, min(c-left_b, right_b-c, r-up_b, down_b-r))\n return mxp\n ```
41
2
[]
9
largest-plus-sign
[Python] short (but not very fast) dp, explained
python-short-but-not-very-fast-dp-explai-1nv1
Classical grid dp, where for each cell we need to find biggest number of continuous ones in for directions: up, down, left, right. We need to traverse our grid
dbabichev
NORMAL
2021-09-09T09:23:01.163656+00:00
2021-09-09T09:23:01.163695+00:00
1,486
false
Classical grid `dp`, where for each cell we need to find biggest number of continuous ones in for directions: up, down, left, right. We need to traverse our grid in `4` different directions and for this I use couple of tricks to make code shorter (notice though that it becomes slower, though complexity is still `O(n^2)`.\n\n1. We create `(N+2)x(N+2)` grid where we add zero padding of size `1` in each direction.\n2. To traverse in direct or opposite direction we use `range(1,N+1)[::(-dx>=0)*2-1]`. Notice that if `dx = 1`, we have `1, ..., N+1` and if we have `dx = -1`, then range is `(N+1, ..., 1)`. Similar logic for `dy`.\n\n#### Complexity\nTime complexity is `O(n^2)`, however with quite big constant: we have `4` directions and also a lot of time spend for creating of empty dp array and finding maximum: so, it is like `O(12n^2)` in all. Space complexity is `O(4n^2)`.\n\n#### Code\n```python\nclass Solution:\n def orderOfLargestPlusSign(self, N, mines):\n grid = {tuple([x+1, y+1]) for x, y in mines}\n dp = [[[0] * 4 for _ in range(N+2)] for _ in range(N+2)]\n \n for dx, dy, dr in [(-1,0,0),(1,0,1),(0,-1,2),(0,1,3)]:\n for x in range(1,N+1)[::(-dx>=0)*2-1]:\n for y in range(1,N+1)[::(-dy>=0)*2-1]:\n if (y, x) not in grid:\n dp[y][x][dr] = dp[y+dy][x+dx][dr] + 1\n \n return max(min(q) for p in dp for q in p) \n```\n\nIf you have any questions, feel free to ask. If you like solution and explanations, please **Upvote!**
31
5
['Dynamic Programming']
0
largest-plus-sign
Python 6 lines O(N * |mines|) with explanation. Easy to understand
python-6-lines-on-mines-with-explanation-k2dv
g[x][y] is the largest plus sign allowed centered at position (x, y). When no mines are presented, it is only limited by the boundary and should be something si
peterzjx
NORMAL
2018-07-13T03:31:44.484444+00:00
2018-09-18T02:47:32.000267+00:00
1,941
false
`g[x][y]` is the largest plus sign allowed centered at position (x, y). When no mines are presented, it is only limited by the boundary and should be something similar to\n```\n1 1 1 1 1\n1 2 2 2 1\n1 2 3 2 1\n1 2 2 2 1\n1 1 1 1 1\n```\nEach mine would affect the row and column it is at, causing the value of `g[x][y]` to be no larger than the distance between (x, y) and the mine.\n```\nclass Solution(object):\n def orderOfLargestPlusSign(self, N, mines):\n """\n :type N: int\n :type mines: List[List[int]]\n :rtype: int\n """\n g = [[min(i, N-1-i, j, N-1-j) + 1 for j in range(N)] for i in range(N)]\n for (x, y) in mines:\n for i in range(N):\n g[i][y] = min(g[i][y], abs(i - x))\n g[x][i] = min(g[x][i], abs(i - y))\n return max([max(row) for row in g])\n```
26
6
[]
6
largest-plus-sign
Figure illustration of DP process
figure-illustration-of-dp-process-by-cod-cbqs
Illustration with figure:\n\nLet\'s begin with an example: \nN = 3;\nmines = {{0, 1}, {2,1}}\nWith the above information, you can easily get the input matrix: g
codedayday
NORMAL
2020-05-05T22:52:42.628954+00:00
2020-05-05T22:52:42.629003+00:00
1,210
false
Illustration with figure:\n\nLet\'s begin with an example: \nN = 3;\nmines = {{0, 1}, {2,1}}\nWith the above information, you can easily get the input matrix: grid\n![image](https://assets.leetcode.com/users/codedayday/image_1588718965.png)\n\nBy searching along 4 directions, you will get 4 sub matrix.\nBy combining them, you can get final dp, from which you can search matrix value as returned answer.\n\n\n\n```\nclass Solution {\npublic:\n int orderOfLargestPlusSign(int N, vector<vector<int>>& mines) {\n vector<vector<int>> dp(N, vector<int>(N, N));\n for(auto& e: mines) dp[e[0]][e[1]] = 0;\n for(int i = 0; i < N; i++)\n for(int j = 0, k = N - 1, u = 0, d = 0, l = 0, r =0; j < N; j++,k--){\n dp[i][j] = min(dp[i][j], l = dp[i][j] ? l + 1 : 0 ); // from left, Note1\n dp[j][i] = min(dp[j][i], u = dp[j][i] ? u + 1 : 0); // from up/top\n dp[i][k] = min(dp[i][k], r = dp[i][k] ? r + 1 : 0); // from right\n dp[k][i] = min(dp[k][i], d = dp[k][i]? d + 1 : 0); // from down/bottom\n }\n \n int ans = 0;\n //for(auto& row: dp) for(auto e: row) ans = max(ans, e); //ok\n for(int i = 0; i < N * N; i++) ans = max(ans, dp[i / N] [i % N]);\n return ans;\n }\n};\nNote1:\ndp[i][j]: how many continous 1 are in the immediate left of location [i,j]\n\n```
23
0
[]
1
largest-plus-sign
C++ || Faster than 100% || Time O(N^2) || DP ||
c-faster-than-100-time-on2-dp-by-sjai786-9999
In this approach, firstly we will find largest continuous of 1s for upper and left side\nafter this we will find largest continuous of 1s for lower and right si
Sjai786
NORMAL
2021-03-03T12:18:32.514867+00:00
2021-04-08T13:10:47.495858+00:00
2,209
false
In this approach, firstly we will find largest continuous of 1s for upper and left side\nafter this we will find largest continuous of 1s for lower and right side\nafter getting largest value for all direction for every index we will select min value from all direction so we will get largest \'+\' sign for every index \n\nhere, dp[][][0] for store largest value from upper side\n\t\t dp[][][1] for store largest value from left side\n\t\t dp[][][2] for store largest value from lower side\n\t\t dp[][][3] for store largest value from right side\n\t\t \nand array v[N][N] is for showing 1s and 0s postion in the array\t\t \n\n```\nclass Solution {\npublic:\n int orderOfLargestPlusSign(int N, vector<vector<int>>& mines) {\n int ans=0,s,i,j,k;\n int dp[N+2][N+2][4],v[N][N]; // v[N][N] for showing 0 and 1 position and dp[][][] for getting largest value \n for(i=0;i<N;i++)for(j=0;j<N;j++)v[i][j]=1;\n for(i=0;i<mines.size();i++)v[mines[i][0]][mines[i][1]]=0;\n memset(dp,0,sizeof dp);\n \n\t\t//first we store largest value from top left to bottom right\n for(i=0;i<N;i++){\n for(j=0;j<N;j++){\n if(v[i][j]==1){\n dp[i+1][j+1][0]=dp[i][j+1][0]+1; //dp[][][0] for store largest value from upper side\n dp[i+1][j+1][1]=dp[i+1][j][1]+1; //dp[][][1] for store largest value from left side\n }\n }\n }\n \n\t\t// we store largest value from bottom right to top left\n for(i=N-1;i>=0;i--){\n for(j=N-1;j>=0;j--){\n if(v[i][j]==1){\n dp[i+1][j+1][2]=dp[i+2][j+1][2]+1; //dp[][][2] for store largest value from lower side\n dp[i+1][j+1][3]=dp[i+1][j+2][3]+1; //dp[][][3] for store largest value from right side\n }\n }\n }\n for(i=1;i<=N;i++){\n for(j=1;j<=N;j++){\n s=min(dp[i][j][0],min(dp[i][j][1],min(dp[i][j][2],dp[i][j][3]))); // now we will select min value from all direction .. hence we will get largest \'+\' sign for index (i,j)\n ans=max(ans,s);\n }\n }\n \n return ans;\n }\n};\n```\n\nIf you like this approach then pls Thumbs Up :)\n
22
0
['Dynamic Programming', 'C', 'Iterator']
2
largest-plus-sign
C++ Simple Dynamic-Programming Solution, With Explanation
c-simple-dynamic-programming-solution-wi-wvah
Idea:\nFirst, we create the matrix of 1\'s and 0\'s.\nThen, we fill the DP matrix the following way:\nWe iterate through the matrix in four ways - left tp right
yehudisk
NORMAL
2021-09-09T08:53:58.364277+00:00
2021-09-09T08:54:08.835160+00:00
1,400
false
**Idea:**\nFirst, we create the matrix of 1\'s and 0\'s.\nThen, we fill the DP matrix the following way:\nWe iterate through the matrix in four ways - left tp right, right to left, top to bottom, bottom to top.\nWe fill the maximum length of contiguous 1\'s.\nWe store in the dp matrix the minimum of all directions.\n=> \nAfter `fillDP`, we have a matrix where each position has the largest plus sign centered in that cell.\n```\nclass Solution {\npublic:\n void fillDP(vector<vector<int>>& dp, vector<vector<int>>& mat, int n) {\n int down, right, up, left;\n \n for (int i = 0; i < n; i++) {\n down = 0, right = 0;\n \n for (int j = 0; j < n; j++) {\n right = mat[i][j] ? right+1 : 0;\n dp[i][j] = min(dp[i][j], right);\n \n down = mat[j][i] ? down+1 : 0;\n dp[j][i] = min(dp[j][i], down);\n }\n }\n \n for (int i = 0; i < n; i++) {\n up = 0, left = 0;\n for (int j = n-1; j >= 0; j--) {\n left = mat[i][j] ? left+1 : 0;\n dp[i][j] = min(dp[i][j], left);\n \n up = mat[j][i] ? up+1 : 0;\n dp[j][i] = min(dp[j][i], up);\n }\n }\n }\n \n int orderOfLargestPlusSign(int n, vector<vector<int>>& mines) {\n vector<vector<int>> dp(n, vector<int>(n, INT_MAX));\n vector<vector<int>> mat(n, vector<int>(n, 1));\n \n for (auto mine : mines)\n mat[mine[0]][mine[1]] = 0;\n \n fillDP(dp, mat, n);\n \n int res = 0;\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < n; j++) {\n res = max(res, dp[i][j]);\n }\n }\n return res;\n }\n};\n```\n**Like it? please upvote!**
21
5
['C']
2
largest-plus-sign
My Simple O(N^2) Time and O(N^2) Space Accepted Solution 150ms
my-simple-on2-time-and-on2-space-accepte-5le2
Created 4 matrices for storing largest streak of ones on left, right top and bottom. Finally, take the min of all four directions. \nThe maximum of these minimu
yashjain28
NORMAL
2018-01-14T19:27:43.065000+00:00
2021-09-11T05:31:27.827479+00:00
3,100
false
Created 4 matrices for storing largest streak of ones on left, right top and bottom. Finally, take the min of all four directions. \nThe maximum of these minimums is the answer.\n```\nclass Solution {\n public int orderOfLargestPlusSign(int N, int[][] mines) {\n int[][] matrix = new int[N][N];\n for(int[] mat:matrix){\n Arrays.fill(mat, 1);\n }\n for(int[] mine: mines){\n matrix[mine[0]][mine[1]] = 0;\n }\n int ans = 0;\n if(mines.length<N*N) ans = 1;\n int[][] left = new int[N][N];\n int[][] right = new int[N][N];\n int[][] top = new int[N][N];\n int[][] bottom = new int[N][N];\n \n for(int i=0;i<N;i++){\n for(int j=0;j<N;j++){\n if(matrix[i][j]==1){ \n top[i][j] = (i-1>=0)?top[i-1][j]+1:1;\n left[i][j] = (j-1>=0)?left[i][j-1]+1:1;\n }\n } \n }\n \n \n for(int i=N-1;i>=0;i--){\n for(int j=N-1;j>=0;j--){\n if(matrix[i][j]==1){ \n bottom[i][j] = (i+1<N)?bottom[i+1][j]+1:1;\n right[i][j] = (j+1<N)?right[i][j+1]+1:1;\n }\n \n ans = Math.max(ans, Math.min(Math.min(left[i][j],bottom[i][j]), Math.min(right[i][j],top[i][j])));\n } \n }\n return ans;\n }\n}\n```
20
2
[]
4
largest-plus-sign
Easy to Understand Java Solution
easy-to-understand-java-solution-by-sidd-vtlz
\npublic int orderOfLargestPlusSign(int N, int[][] mines) {\n int[][] grid = new int[N][N];\n int ans = 0;\n for (int i = 0; i < N; i++) {\
siddheshshirke
NORMAL
2018-01-17T05:19:29.503000+00:00
2018-10-23T01:17:34.837218+00:00
3,385
false
```\npublic int orderOfLargestPlusSign(int N, int[][] mines) {\n int[][] grid = new int[N][N];\n int ans = 0;\n for (int i = 0; i < N; i++) {\n Arrays.fill(grid[i], 1);\n }\n \n for (int[] m : mines) {\n grid[m[0]][m[1]] = 0;\n }\n \n for(int i = 0; i < N; i++){\n for(int j = 0; j < N; j++){\n if(grid[i][j] == 1){\n int count = 1;\n int dir = 1;\n while(j-dir >= 0 && j+dir < N && i-dir >= 0 && i+dir < N && \n grid[i][j-dir] == 1 && grid[i][j+dir] == 1 && \n grid[i-dir][j] == 1 && grid[i+dir][j] == 1){\n count++;\n dir++; \n }\n ans = Math.max(count, ans);\n }\n } \n }\n return ans;\n }\n```
18
3
[]
3
largest-plus-sign
Easiest c++ solution | DP O(n^2)
easiest-c-solution-dp-on2-by-rac101ran-7eaa
\nclass Solution {\npublic:\n int orderOfLargestPlusSign(int n, vector<vector<int>>& mines) {\n int ans=0;\n\t\t// just walk from every direction one
rac101ran
NORMAL
2021-08-05T17:58:12.721339+00:00
2021-08-05T18:00:13.990906+00:00
931
false
```\nclass Solution {\npublic:\n int orderOfLargestPlusSign(int n, vector<vector<int>>& mines) {\n int ans=0;\n\t\t// just walk from every direction one by one to each cell and store the min. contiguous valid 1\'s length of every direction\n vector<vector<int>> dp(n,vector<int>(n,INT_MAX));\n vector<vector<int>> mat(n,vector<int>(n,1));\n for(int i=0; i<mines.size(); i++) mat[mines[i][0]][mines[i][1]]=0;\n for(int i=0; i<n; i++) {\n int c=0;\n for(int j=0; j<n; j++) { // walk right to each pos \n mat[i][j]?c++:c=0; \n dp[i][j]=min(dp[i][j],c);\n }\n }\n for(int i=0; i<n; i++) {\n int c=0;\n for(int j=n-1; j>=0; j--) { // walk left to each pos\n mat[i][j]?c++:c=0; \n dp[i][j]=min(dp[i][j],c);\n }\n }\n for(int i=0; i<n; i++) {\n int c=0;\n for(int j=0; j<n; j++) {\n mat[j][i]?c++:c=0; // walk down to each pos\n dp[j][i]=min(dp[j][i],c);\n }\n }\n for(int i=0; i<n; i++) {\n int c=0;\n for(int j=n-1; j>=0; j--) { // walk up to each pos \n mat[j][i]?c++:c=0;\n dp[j][i]=min(c,dp[j][i]);\n }\n }\n for(int i=0; i<n; i++) {\n for(int j=0; j<n; j++) {\n ans=max(ans,dp[i][j]); \n }\n }\n return ans;\n }\n};\n```
14
0
['Math', 'Dynamic Programming', 'C']
2
largest-plus-sign
✅Largest Plus Sign || DP W/ O(N^2) Approach || C++ | JAVA
largest-plus-sign-dp-w-on2-approach-c-ja-3ar2
IDEA\n\n Create the matrix of 1 and 0.\n Then, fill the DP matrix the following way:\n\t Iterate through the matrix in four ways - left to right, right to left,
Maango16
NORMAL
2021-09-09T19:14:25.145630+00:00
2021-09-09T19:21:19.247337+00:00
830
false
**IDEA**\n\n* Create the matrix of `1` and `0`.\n* Then, fill the DP matrix the following way:\n\t* Iterate through the matrix in four ways - `left to right`, `right to left`, `top to bottom`, `bottom to top`.\n\t* Store in the `vectors for directions` the **maximum length of contiguous** `1`.\n* Hence we have a matrix where each position has the largest plus sign centered in that cell.\n* The maximum length from either directions will be our answer \n\n**SOLUTION**\n`IN C++`\n```\nint orderOfLargestPlusSign(int n, vector<vector<int>>& mines) {\n vector<vector<int>> mat(n, vector<int>(n, 1)) ;\n for(auto it : mines)\n {\n int x = it[0] ;\n int y = it[1] ;\n mat[x][y] = 0 ;\n }\n vector<vector<int>> lef, rig, top, bot ;\n lef = rig = top = bot = mat ;\n for(int i=0; i < n ; i++)\n {\n for(int j = 0 ; j < n ; j++)\n {\n int x = n - i - 1 ;\n int y = n - j - 1 ;\n if(i > 0 && top[i][j]) \n\t\t\t\ttop[i][j] += top[i-1][j];\n if(j > 0 && lef[i][j]) \n\t\t\t\tlef[i][j] += lef[i][j-1];\n if(x < n-1 && bot[x][y]) \n\t\t\t\tbot[x][y] += bot[x+1][y];\n if(y < n-1 && rig[x][y]) \n\t\t\t\trig[x][y] += rig[x][y+1];\n }\n }\n int ans = 0;\n for(int i = 0 ; i < n ; i++)\n for(int j = 0 ; j < n ; j++)\n ans = max(ans, min({lef[i][j], rig[i][j], top[i][j], bot[i][j]}));\n\t\t\t\n return ans;\n}\n```\n`In JAVA`\n```\nclass Solution {\n public int orderOfLargestPlusSign(int n, int[][] mines) { \n boolean[][] mat = new boolean[n][n] ;\n for(int[] pos:mines){\n mat[pos[0]][pos[1]] = true;\n }\n int[][] left = new int[n][n];\n int[][] right = new int[n][n];\n int[][] up = new int[n][n];\n int[][] down = new int[n][n];\n int ans = 0;\n // For Left and Up only\n for(int i = 0 ; i < n ; i++){ \n for(int j = 0 ; j < n ; j++){\n left[i][j] = mat[i][j]?0:1+(j==0?0:left[i][j-1]);\n up[i][j] = mat[i][j]?0:1+(i==0?0:up[i-1][j]);\n }\n }\n // For Right and Down and simoultaneously get answer\n for(int i = n - 1 ; i >= 0 ; i--){\n for(int j = n - 1 ; j >= 0 ; j--){\n right[i][j] = mat[i][j]?0:1+(j==n-1?0:right[i][j+1]);\n down[i][j] = mat[i][j]?0:1+(i==n-1?0:down[i+1][j]);\n int x = Math.min(Math.min(left[i][j],up[i][j]),Math.min(right[i][j],down[i][j]));\n ans = Math.max(ans, x);\n }\n }\n return ans ;\n }\n};\n```\n**TIME COMPLEXITY - O(N^2)**\n**SPACE COMPLEXITY - O(N^2)**
12
1
[]
2
largest-plus-sign
Python straightforward simple self-explanatory AC solution
python-straightforward-simple-self-expla-v6di
\nclass Solution:\n def orderOfLargestPlusSign(self, N, mines):\n #up, left, down, right\n dp, res, mines = [[[0, 0, 0, 0] for j in range(N)] f
cenkay
NORMAL
2018-06-30T18:03:36.566954+00:00
2018-06-30T18:03:36.566954+00:00
895
false
```\nclass Solution:\n def orderOfLargestPlusSign(self, N, mines):\n #up, left, down, right\n dp, res, mines = [[[0, 0, 0, 0] for j in range(N)] for i in range(N)], 0, {(i, j) for i, j in mines}\n for i in range(N):\n for j in range(N):\n if (i, j) not in mines:\n try:\n dp[i][j][0] = dp[i - 1][j][0] + 1\n except:\n dp[i][j][0] = 1\n try:\n dp[i][j][1] = dp[i][j - 1][1] + 1\n except:\n dp[i][j][1] = 1\n for i in range(N - 1, -1, -1):\n for j in range(N - 1, -1, -1):\n if (i, j) not in mines:\n try:\n dp[i][j][2] = dp[i + 1][j][2] + 1\n except:\n dp[i][j][2] = 1\n try:\n dp[i][j][3] = dp[i][j + 1][3] + 1\n except:\n dp[i][j][3] = 1\n res = max(res, min(dp[i][j]))\n return res\n```
12
1
[]
1
largest-plus-sign
Python 3 | DP - Bomb Enemy | Explanations
python-3-dp-bomb-enemy-explanations-by-i-zovl
Code is long, but trust me, they are super easy to understand.\n\n### Intuition\n- Brutal force will definitely fail given N can be up to 500 and brutal force i
idontknoooo
NORMAL
2020-09-07T07:35:45.620330+00:00
2020-09-07T07:35:45.620387+00:00
859
false
Code is long, but trust me, they are super easy to understand.\n\n### Intuition\n- Brutal force will definitely fail given N can be up to 500 and brutal force is a `O(N^3)` solution; need to think of something else\n- For a `+` sign, there are 4 directions, up/down/left/right\n\t- If we just check 1 direction in each iteration, and store the value somewhere, then we can reuse the value since it\'s a matrix (we can have previous/next row or column\'s values).\n\t- So we check 4 directions separately, then the time complexity is `O(N^2) * constant = O(N^2)`\n- A `+` should have 4 directions same number of `1`s\n\t- meaning we need to take the minimum of 4 directions\n- Finally, iterate over one more time to find the max\n\n### Explanation\n```\nclass Solution:\n def orderOfLargestPlusSign(self, N: int, mines: List[List[int]]) -> int:\n mat = [[1]*N for _ in range(N)]\n for x, y in mines: mat[x][y] = 0 # create matrix with mine\n \n up = [[0]*N for _ in range(N)] # count 1s above mat[i][j] if mat[i][j] is 1\n for i in range(N):\n for j in range(N):\n if mat[i][j]: \n up[i][j] = 1\n if i > 0: up[i][j] += up[i-1][j] \n \n down = [[0]*N for _ in range(N)] # count 1s below mat[i][j] if mat[i][j] is 1\n for i in range(N-1, -1, -1):\n for j in range(N):\n if mat[i][j]: \n down[i][j] = 1\n if i < N-1: down[i][j] += down[i+1][j] \n \n left = [[0]*N for _ in range(N)] # count 1s on the left side of mat[i][j] if mat[i][j] is 1\n for i in range(N):\n for j in range(N):\n if mat[i][j]:\n left[i][j] = 1\n if j > 0: left[i][j] += left[i][j-1]\n \n right = [[0]*N for _ in range(N)] # count 1s on the right side of mat[i][j] if mat[i][j] is 1\n for i in range(N):\n for j in range(N-1, -1, -1):\n if mat[i][j]:\n right[i][j] = 1\n if j < N-1: right[i][j] += right[i][j+1]\n \n\t\t# find the largest + sign by using cached directions information\n return max(min([up[i][j], down[i][j], left[i][j], right[i][j]]) for i in range(N) for j in range(N))\n```
9
1
['Dynamic Programming', 'Python', 'Python3']
0
largest-plus-sign
🎨 The ART of Dynamic Programming
the-art-of-dynamic-programming-by-clayto-i2qw
\uD83C\uDFA8 The ART of Dynamic Programming: Use prefix sums to track the length of continuous 1s from all four cardinal directions: up, down, left, right. The
claytonjwong
NORMAL
2018-01-14T04:04:55.931000+00:00
2022-01-17T00:13:29.064685+00:00
1,272
false
[\uD83C\uDFA8 The ART of Dynamic Programming:](https://leetcode.com/discuss/general-discussion/712010/The-ART-of-Dynamic-Programming-An-Intuitive-Approach%3A-from-Apprentice-to-Master) Use prefix sums to track the length of continuous 1s from all four cardinal directions: up, down, left, right. Then perform a scan of the board cell\'s `i`, `j` to find and return the maximum of each cell\'s minimum length of continuous 1s of all four cardinal directions as the `best` answer.\n\n---\n\n*Kotlin*\n```\nclass Solution {\n fun orderOfLargestPlusSign(N: Int, X: Array<IntArray>): Int {\n var A = Array<IntArray>(N) { IntArray(N) { 1 } }\n for ((i, j) in X)\n A[i][j] = 0\n var (U, D, L, R) = Array(4) { A.map{ it.copyOf() } }\n for (i in 1 until N - 1) {\n for (j in 1 until N - 1) {\n var u = N - 1 - i\n var v = N - 1 - j\n if (A[i][j] == 1) {\n U[i][j] = 1 + U[i - 1][j]\n L[i][j] = 1 + L[i][j - 1]\n }\n if (A[u][v] == 1) {\n D[u][v] = 1 + D[u + 1][v]\n R[u][v] = 1 + R[u][v + 1]\n }\n }\n }\n return Array(N){ IntArray(N){ it } }.mapIndexed{ i, row -> row.map{ j -> listOf(U[i][j], D[i][j], L[i][j], R[i][j]).min()!! }.max()!! }.max()!!\n }\n}\n```\n\n*Javascript*\n```\nlet orderOfLargestPlusSign = (N, X, best = 0) => {\n let A = [...Array(N)].map(_ => Array(N).fill(1));\n for (let [i, j] of X)\n A[i][j] = 0;\n let [U, D, L, R] = [...Array(4)].map(_ => A.map(row => [...row]));\n for (let i = 1; i < N - 1; ++i) {\n for (let j = 1; j < N - 1; ++j) {\n let u = N - 1 - i,\n v = N - 1 - j;\n if (A[i][j]) {\n U[i][j] = 1 + U[i - 1][j];\n L[i][j] = 1 + L[i][j - 1];\n }\n if (A[u][v]) {\n D[u][v] = 1 + D[u + 1][v];\n R[u][v] = 1 + R[u][v + 1];\n }\n }\n }\n return Math.max(...[...Array(N).keys()].map(i => Math.max(...[...Array(N).keys()].map(j => Math.min(U[i][j], D[i][j], L[i][j], R[i][j])))));\n};\n```\n\n*Python3*\n```\nclass Solution:\n def orderOfLargestPlusSign(self, N: int, X: List[List[int]], best = 0) -> int:\n A = [N * [1] for _ in range(N)]\n for i, j in X:\n A[i][j] = 0\n U, D, L, R = [[row[:] for row in A] for _ in range(4)]\n for i in range(1, N - 1):\n for j in range(1, N - 1):\n u = N - 1 - i\n v = N - 1 - j\n if A[i][j]:\n U[i][j] = 1 + U[i - 1][j]\n L[i][j] = 1 + L[i][j - 1]\n if A[u][v]:\n D[u][v] = 1 + D[u + 1][v]\n R[u][v] = 1 + R[u][v + 1]\n return max(min(U[i][j], D[i][j], L[i][j], R[i][j]) for j in range(N) for i in range(N))\n```\n\n*C++*\n```\nclass Solution {\npublic:\n using VI = vector<int>;\n using VVI = vector<VI>;\n int orderOfLargestPlusSign(int N, VVI& X, int best = 0) {\n VVI A(N, VI(N, 1));\n for (auto& x: X) {\n auto [i, j] = tie(x[0], x[1]);\n A[i][j] = 0;\n }\n VVI U{ A }, D{ A }, L{ A }, R{ A };\n for (auto i{ 1 }; i < N - 1; ++i) {\n for (auto j{ 1 }; j < N - 1; ++j) {\n auto u = N - 1 - i,\n v = N - 1 - j;\n if (A[i][j]) {\n U[i][j] = 1 + U[i - 1][j];\n L[i][j] = 1 + L[i][j - 1];\n }\n if (A[u][v]) {\n D[u][v] = 1 + D[u + 1][v];\n R[u][v] = 1 + R[u][v + 1];\n }\n }\n }\n for (auto i{ 0 }; i < N; ++i)\n for (auto j{ 0 }; j < N; ++j)\n best = max(best, min({ U[i][j], D[i][j], L[i][j], R[i][j] }));\n return best;\n }\n};\n```\n
9
1
[]
3
largest-plus-sign
C++ O(n^3) solution 226ms with explanation.
c-on3-solution-226ms-with-explanation-by-3f7f
For this problem, I first think of the related problem finding largest square, and I tried DP as DP can give O(n^2) time complexity. They way I do it is use a d
zhutianqi
NORMAL
2018-01-14T15:10:34.958000+00:00
2018-09-09T22:53:24.620595+00:00
1,392
false
For this problem, I first think of the related problem finding largest square, and I tried DP as DP can give O(n^2) time complexity. They way I do it is use a dp[N][N][4] to record each 1s consecutive 1s in 4 directions and they can be abrupt by 0. However, my code fails at last test case because of memory. Obviously, there is a tradeoff in space and time.\n\nIn order to pass I take advantage of having limited 0s on last test case and generated the following O(N^3) solution, the general idea is do bfs (I actually update everything on row and col) and update grid every time we meet a 0. There could be total N^2 0s and update board takes additional N so it's N^3.\n\nTo make things easier, I initialize the board with rules to take in count of boarder. \n\n```\nint orderOfLargestPlusSign(int N, vector<vector<int>>& mines)\n{\n vector<vector<int>> grid(N,vector<int>(N,N));\n \n for(int i =0; i < N; i++)\n for(int j =0; j< N; j++)\n {\n grid[i][j] = min(i-0+1,j-0+1);\n grid[i][j] = min(grid[i][j],N-i);\n grid[i][j] = min(grid[i][j],N-j);\n }\n \n for(auto v : mines)\n {\n int i = v[0];\n int j = v[1];\n \n for(int ii =0; ii< N;ii++)\n grid[ii][j] = min(grid[ii][j],abs(ii-i));\n \n for(int jj =0; jj< N;jj++)\n grid[i][jj] = min(grid[i][jj],abs(jj-j));\n }\n \n \n int result =0;\n \n for(int i =0; i < N; i++)\n for(int j =0; j< N; j++)\n result = max(result,grid[i][j]);\n\n return result;\n}\n````
9
3
[]
2
largest-plus-sign
Java solution || simple || Easy to Understand || O(N^2) solution
java-solution-simple-easy-to-understand-czrs0
The code aims to find the maximum order of the largest plus sign that can be formed in a grid of size n, while considering the presence of mines at certain posi
Amritanshu23
NORMAL
2024-04-13T11:14:41.329352+00:00
2024-04-13T11:14:41.329383+00:00
387
false
The code aims to find the maximum order of the largest plus sign that can be formed in a grid of size n, while considering the presence of mines at certain positions within the grid. The grid is represented by a 2D array where each cell initially contains a value of 1 (indicating no mine). Mines are represented by setting specific cells to 0.\n\nHere\'s a summary of the code:\n**Inner Class Total:**\n\nThis class represents the lengths of arms (left, right, up, down) for each cell in the grid.\nIt has four integer fields: l, r, u, d, representing the lengths of the left, right, up, and down arms respectively.\nThe constructor initializes these fields with the provided values.\n\n**orderOfLargestPlusSign Method:**\n\nThis method takes two parameters: n (an integer representing the size of the grid) and mine (a 2D array representing the positions of mines).\n\n**Initializing the Grid:**\n\nThe method initializes a 2D array called mines to represent the grid. Initially, all cells are set to 1, indicating no mines.\nIt uses Arrays.fill() method to initialize each row of the grid with 1s.\n\n**Setting Mines:**\n\nThe method iterates through the mine array, which contains the positions of mines, and sets the corresponding cells in the mines grid to 0, indicating the presence of a mine.\n\n**Initializing nums Array:**\n\nThe method initializes another 2D array called nums of type Total to store the lengths of arms for each cell.\nIt iterates through each cell of the grid and initializes the corresponding cell in the nums array with a new instance of the Total class, initializing all arm lengths to 0.\n\n**Calculating Arm Lengths:**\n\nThe method iterates through each row of the grid to calculate the lengths of the left and right arms for each cell.\nIt maintains a sum variable to keep track of the consecutive empty cells encountered (indicating the length of the arm).\nIf a mine is encountered, the sum is reset to 0, otherwise, it is incremented for each consecutive empty cell.\n\n**Similar Process for Columns:**\n\nThe method then repeats a similar process for columns to calculate the lengths of the up and down arms for each cell.\n\n**Finding Maximum Order:**\n\nOnce all arm lengths are calculated for each cell, the method iterates through the nums array to find the minimum of the lengths of all four arms for each cell.\nIt keeps track of the maximum of these minimums, which represents the order of the largest plus sign that can be formed.\n\n**Returning the Result:**\n\nFinally, the method returns the maximum order of the largest plus sign that can be formed considering the positions of mines.\n\n```\nclass Solution {\n \n public class Total {\n int l;\n int r;\n int u;\n int d;\n \n Total(int l, int r, int u, int d){\n this.l = l;\n this.r = r;\n this.u = u;\n this.d = d;\n }\n }\n \n public int orderOfLargestPlusSign(int n, int[][] mine) {\n int[][] mines = new int[n][n];\n \n \n for (int[] row : mines) {\n Arrays.fill(row, 1);\n }\n \n \n for (int[] m : mine) {\n mines[m[0]][m[1]] = 0;\n }\n \n Total[][] nums = new Total[n][n];\n \n for (int i = 0; i < n; i++) {\n for (int j = 0; j < n; j++) {\n nums[i][j] = new Total(0, 0, 0, 0);\n }\n }\n \n for (int i = 0; i < n; i++) {\n int sum = 0;\n for (int j = 0; j < n; j++) {\n if (mines[i][j] == 0) {\n sum = 0;\n nums[i][j].l = sum;\n } else {\n nums[i][j].l = ++sum;\n }\n }\n }\n \n for (int i = 0; i < n; i++) {\n int sum = 0;\n for (int j = n - 1; j >= 0; j--) {\n if (mines[i][j] == 0) {\n sum = 0;\n nums[i][j].r = sum;\n } else {\n nums[i][j].r = ++sum;\n }\n }\n }\n \n for (int i = 0; i < n; i++) {\n int sum = 0;\n for (int j = 0; j < n; j++) {\n if (mines[j][i] == 0) {\n sum = 0;\n nums[j][i].u = sum;\n } else {\n nums[j][i].u = ++sum;\n }\n }\n }\n \n for (int i = 0; i < n; i++) {\n int sum = 0;\n for (int j = n - 1; j >= 0; j--) {\n if (mines[j][i] == 0) {\n sum = 0;\n nums[j][i].d = sum;\n } else {\n nums[j][i].d = ++sum;\n }\n }\n }\n \n int max = 0;\n for (int i = 0; i < nums.length; i++) {\n for (int j = 0; j < nums[0].length; j++) {\n max = Math.max(Math.min(nums[i][j].l, Math.min(nums[i][j].r, Math.min(nums[i][j].d, nums[i][j].u))), max);\n }\n }\n \n return max;\n }\n}\n\n```
7
0
['Array', 'Dynamic Programming', 'Java']
0