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
minimum-white-tiles-after-covering-with-carpets
Python top-down DP | Almost one-liner
python-top-down-dp-almost-one-liner-by-t-7myh
\nclass Solution:\n def minimumWhiteTiles(self, nums: str, numCarpets: int, carpetLen: int) -> int:\n @cache\n def dfs(i, rem):\n re
TiruT
NORMAL
2022-09-23T11:40:13.527695+00:00
2022-09-23T11:40:13.527739+00:00
49
false
```\nclass Solution:\n def minimumWhiteTiles(self, nums: str, numCarpets: int, carpetLen: int) -> int:\n @cache\n def dfs(i, rem):\n return 0 if i >= len(nums) else min((1 if nums[i]==\'1\' else 0) + dfs(i+1, rem), dfs(i+carpetLen, rem-1) if rem and nums[i]==\'1\' else float(\'inf\'))\n \n return dfs(0, numCarpets)\n```
1
0
['Dynamic Programming', 'Memoization', 'Python']
0
minimum-white-tiles-after-covering-with-carpets
C++ || PrefixSum || DP memoized
c-prefixsum-dp-memoized-by-binaykr-2bl1
\nclass Solution {\n int solve(string &s, int nc, int &lc, vector<int> &pref, int i, vector<vector<int>> &dp)\n {\n if(i<0) return 0;\n if(n
binayKr
NORMAL
2022-06-25T04:58:00.294439+00:00
2022-07-16T12:51:26.102244+00:00
95
false
```\nclass Solution {\n int solve(string &s, int nc, int &lc, vector<int> &pref, int i, vector<vector<int>> &dp)\n {\n if(i<0) return 0;\n if(nc==0) return pref[i];\n if(dp[i][nc]!=-1) return dp[i][nc];\n \n int take = solve(s,nc-1,lc,pref, i-lc, dp);\n int not_take = (s[i] - \'0\') + solve(s,nc,lc,pref,i-1,dp);\n \n return dp[i][nc] = min(take,not_take);\n }\npublic:\n int minimumWhiteTiles(string floor, int numCarpets, int carpetLen) {\n vector<int> pref;\n int sum =0;\n for(int i=0; i<floor.length(); i++)\n {\n sum += (floor[i]-\'0\');\n pref.push_back(sum);\n }\n vector<vector<int>> dp(floor.length()+1, vector<int>(numCarpets+1,-1));\n return solve(floor, numCarpets, carpetLen, pref, floor.length()-1, dp);\n \n }\n};\n```
1
2
['Dynamic Programming', 'Recursion', 'Memoization', 'Prefix Sum']
0
minimum-white-tiles-after-covering-with-carpets
C++ | DP | MEMOIZATION
c-dp-memoization-by-jatinbansal1179-bug5
\nclass Solution {\npublic:\n \n int helper(string &s, int num, int len, int i, vector<vector<int>>&dp){\n if(i>=s.length()){\n return 0
jatinbansal1179
NORMAL
2022-06-24T11:07:35.033862+00:00
2022-06-24T11:07:35.033906+00:00
117
false
```\nclass Solution {\npublic:\n \n int helper(string &s, int num, int len, int i, vector<vector<int>>&dp){\n if(i>=s.length()){\n return 0;\n }\n if(num==0){\n int count = 0;\n for(int j = i; j<=s.length()-1;j++){\n if(s[j]==\'1\'){\n count++;\n }\n\n } \n return count;\n }\n if(dp[i][num]!=-1){\n return dp[i][num];\n }\n if(s[i]==\'0\'){\n return dp[i][num] = helper(s,num,len,i+1,dp);\n }\n int mn = i + len-1;\n if(mn >= s.length()){\n mn = s.length()-1;\n }\n \n return dp[i][num] = min(helper(s,num-1,len,i+len,dp),1+helper(s,num,len,i+1,dp));\n }\n \n \n int minimumWhiteTiles(string floor, int numCarpets, int carpetLen) {\n vector<vector<int>> dp(floor.length()+1, vector<int>(numCarpets+1,-1));\n return helper(floor,numCarpets,carpetLen,0,dp);\n }\n};\n```
1
0
['Memoization', 'C']
0
minimum-white-tiles-after-covering-with-carpets
Python. 2 Liner. using Lambda function and LRU cache///
python-2-liner-using-lambda-function-and-hvl6
\nclass Solution:\n def minimumWhiteTiles(self, x: str, n: int, cl: int) -> int:\n f=lru_cache(None)(lambda i,n: 0 if i>=len(x) else min((1 if x[i]==\
nag007
NORMAL
2022-06-15T06:15:37.091527+00:00
2022-06-15T06:15:37.091579+00:00
57
false
```\nclass Solution:\n def minimumWhiteTiles(self, x: str, n: int, cl: int) -> int:\n f=lru_cache(None)(lambda i,n: 0 if i>=len(x) else min((1 if x[i]==\'1\' else 0)+f(i+1,n),(inf if n==0 else f(i+cl,n-1))))\n return f(0,n)\n```
1
0
[]
0
minimum-white-tiles-after-covering-with-carpets
C++ | DP | Bottom Up Dp | Similar to Knapsack
c-dp-bottom-up-dp-similar-to-knapsack-by-ch9m
Please upvote\n\nclass Solution {\npublic:\n int minimumWhiteTiles(string floor, int numCarpets, int len) {\n int n=floor.size();\n int x=numCa
GeekyBits
NORMAL
2022-06-05T16:25:31.810771+00:00
2022-07-08T17:22:30.056450+00:00
124
false
Please upvote\n```\nclass Solution {\npublic:\n int minimumWhiteTiles(string floor, int numCarpets, int len) {\n int n=floor.size();\n int x=numCarpets;\n floor=\'#\'+floor;//so that ith row of dp matches with the ith character\n vector<vector<int>> dp(n+1,vector<int>(x+1,0));\n dp[0][0]=0;\n for(int i=0;i<=x;i++){\n dp[0][i]=0;\n }\n for(int i=1;i<=n;i++){\n dp[i][0]=dp[i-1][0]+(floor[i]==\'1\');\n }\n for(int i=1;i<=n;i++){\n for(int j=1;j<=x;j++){\n if(j>=1){\n\t\t\t\t//if we have atleast 1 carpet or even more\n\t\t\t\t//then we can use\n\t\t\t\t//however before usuing at i also check if i-len>=0\n if(i-len>=0){\n dp[i][j]=min(dp[i-len][j-1],dp[i-1][j]+(floor[i]==\'1\'));\n }\n }\n else{\n\t\t\t\t//if we do not have any carpet\n dp[i][j]=dp[i-1][j]+(floor[i]==\'1\');\n }\n }\n }\n return dp[n][x];\n }\n};\n```
1
0
[]
0
minimum-white-tiles-after-covering-with-carpets
Java DP Solution
java-dp-solution-by-sycmtic-8knv
\nclass Solution {\n public int minimumWhiteTiles(String floor, int numCarpets, int carpetLen) {\n int n = floor.length();\n int[][] dp = new i
sycmtic
NORMAL
2022-05-19T04:42:23.856979+00:00
2022-05-19T04:42:23.857005+00:00
132
false
```\nclass Solution {\n public int minimumWhiteTiles(String floor, int numCarpets, int carpetLen) {\n int n = floor.length();\n int[][] dp = new int[n + 1][numCarpets + 1];\n for (int i = 1; i <= n; i++) {\n for (int j = 0; j <= numCarpets; j++) {\n if (floor.charAt(i - 1) == \'1\') dp[i][j] = dp[i - 1][j] + 1;\n else dp[i][j] = dp[i - 1][j];\n if (j > 0) dp[i][j] = Math.min(dp[i][j], dp[Math.max(0, i - carpetLen)][j - 1]);\n }\n }\n return dp[n][numCarpets];\n }\n}\n```
1
0
['Dynamic Programming', 'Java']
0
minimum-white-tiles-after-covering-with-carpets
Scala
scala-by-fairgrieve-m476
\nimport scala.math.min\nimport scala.util.chaining._\n\nobject Solution {\n private val Black = \'0\'\n\n def minimumWhiteTiles(floor: String, numCarpets: In
fairgrieve
NORMAL
2022-03-25T00:16:11.091644+00:00
2022-03-25T00:21:55.757888+00:00
18
false
```\nimport scala.math.min\nimport scala.util.chaining._\n\nobject Solution {\n private val Black = \'0\'\n\n def minimumWhiteTiles(floor: String, numCarpets: Int, carpetLen: Int): Int = floor\n .indices\n .zip(floor.map(_ - Black).scanRight(0)(_ + _))\n .toMap\n .withDefaultValue(0)\n .pipe { (1 to numCarpets)\n .foldLeft(_) { case (previousNumWhiteTiles, _) => floor\n .indices\n .foldRight(Map[Int, Int]().withDefaultValue(0)) { case (i, currentNumWhiteTiles) =>\n currentNumWhiteTiles + \n (i -> min(floor(i) - Black + currentNumWhiteTiles(i + 1), previousNumWhiteTiles(i + carpetLen)))\n }\n }\n .apply(0)\n }\n}\n```
1
0
[]
0
minimum-white-tiles-after-covering-with-carpets
Java || Simple || Memiozation
java-simple-memiozation-by-lagahuahubro-6icj
```\nclass Solution {\n int[] suff;\n Integer[][] dp;\n public int minimumWhiteTiles(String floor, int numCarpets, int carpetLen) { \n if (ca
lagaHuaHuBro
NORMAL
2022-03-24T14:55:00.883915+00:00
2022-03-24T14:55:00.883952+00:00
63
false
```\nclass Solution {\n int[] suff;\n Integer[][] dp;\n public int minimumWhiteTiles(String floor, int numCarpets, int carpetLen) { \n if (carpetLen == floor.length()) {\n return 0;\n }\n dp = new Integer[floor.length()][numCarpets + 1];\n // suff[i] = number of white tiles in s[i....]\n\t\tsuff = cumulative(floor);\n return helper(floor, numCarpets, carpetLen, 0);\n }\n \n\t// normal suffix array\n public int[] cumulative(String s) {\n int[] suff = new int[s.length()];\n suff[s.length() - 1] = (s.charAt(s.length() - 1) == \'0\' ? 0 : 1);\n for (int i = s.length() - 2; i >= 0; i--) {\n suff[i] = suff[i + 1] + (s.charAt(i) == \'0\' ? 0 : 1);\n }\n return suff;\n }\n \n public int helper(String s, int n, int k, int idx) {\n \n // no more floors remaining so no white carpets need to be covered\n if (idx >= s.length()) {\n return 0;\n }\n \n if (dp[idx][n] != null) {\n return dp[idx][n];\n }\n \n // floors remaining but carpets exhausted\n if (n == 0) {\n return suff[idx];\n }\n \n // this is already black skip this floor\n if (s.charAt(idx) == \'0\') {\n return helper(s, n, k, idx + 1);\n }\n \n // now we have two choices whether to leave this white\n // as it is or cover this in black\n \n \n // if covering this and any other black floor in range as black\n int answer = helper(s, n - 1, k, idx + k);\n \n // leaving this as white as it was\n answer = Math.min(answer, helper(s, n, k, idx + 1) + 1);\n return dp[idx][n] = answer;\n }\n}\n
1
0
[]
0
minimum-white-tiles-after-covering-with-carpets
Why my bottom-up code is giving TLE?
why-my-bottom-up-code-is-giving-tle-by-k-w441
\nclass Solution {\npublic:\n // int memo(int i, int j, vector<int>& pref, int cl,\n // vector<vector<int>>& dp)\n // {\n // if(i >= pr
kenkaneki124
NORMAL
2022-03-24T11:28:00.423753+00:00
2022-03-24T11:28:23.948191+00:00
92
false
```\nclass Solution {\npublic:\n // int memo(int i, int j, vector<int>& pref, int cl,\n // vector<vector<int>>& dp)\n // {\n // if(i >= pref.size() || j <= 0)\n // return 0;\n // if(dp[i][j] != -1)\n // return dp[i][j];\n // else\n // {\n // dp[i][j] = max(memo(i+cl, j-1, pref, cl, dp)\n // + pref[i], \n // memo(i+1, j, pref, cl, dp));\n // }\n // return dp[i][j];\n // }\n int minimumWhiteTiles(string& f, int n, int cl) {\n vector<vector<int>> dp(1001, vector<int>(1001, -1));\n int tot = 0;\n for(auto x : f)\n if(x == \'1\')\n tot++;\n vector<int> pref(f.size(), 0);\n int x = f.size() - 1;\n for(int i = 0; i < cl; i++, x--)\n {\n if(x < f.size() - 1)\n pref[x] = pref[x+1];\n if(f[x] == \'1\')\n pref[x]++;\n }\n int y = f.size() - 1;\n while(x >= 0)\n {\n pref[x] = pref[x+1];\n if(f[y] == \'1\')\n pref[x]--;\n if(f[x] == \'1\')\n pref[x]++;\n x--;\n y--;\n }\n for(int i = 0; i <= f.size(); i++)\n dp[i][0] = 0;\n for(int j = 0; j <= n; j++)\n dp[f.size()][j] = 0;\n for(int i = f.size()-1; i >= 0; i--)\n {\n for(int j = 1; j <= n; j++)\n {\n dp[i][j] = max(dp[i+1][j],\n dp[min(i+cl,int(f.size()-1))][j-1]\n + pref[i]);\n }\n }\n return tot > dp[0][n] ? tot - dp[0][n] : 0;\n }\n};\n\n```
1
0
['Dynamic Programming', 'Memoization', 'C']
0
minimum-white-tiles-after-covering-with-carpets
Java Simple Top Down DP with explanation
java-simple-top-down-dp-with-explanation-rky2
Basically we consider each suffix from floor[0...I] using J carpets. There are 2 transition options to consider and minimize over for this building upon "smalle
theted
NORMAL
2022-03-21T14:47:12.810235+00:00
2022-03-21T14:47:56.450381+00:00
76
false
Basically we consider each suffix from ```floor[0...I]``` using ```J``` carpets. There are 2 transition options to consider and minimize over for this building upon "smaller"* subproblems.\n\nCase 1: We use a carpet that ends at ```I```th position. So this means we simply need ```subproblem(I-carpetLen, J-1)``` because all tiles from ```I-carpetLen + 1``` to ```I``` now have 0 white tiles due to spending 1 carpet so we are at pos ```I - carpetLen``` with 1 less carpet.\n\nCase 2: We do not use a carpet that ends at ```I```th position. So the ```I```th tile is uncovered. So this tile has to be included towards count of white tiles so add ```floor(I) == 0? 1 : 0```. And then we\'re left with ```subproblem(I-1, J)``` as we haven\'t spent any carpets.\n\nThat is ```subproblem(I, J) = Min(subproblem(I-carpetLen, J-1), subproblem(I-1, J) + floor(I) == 0? 1 : 0)```\n\n\\* "smaller" in sense that subproblem(I\', J\') < subproblem(I, J) if I\' <= I and J\' <= J and not case that (I\', J\') = (I, J)\n\nThere are a few edge cases that should be easily understandable from code below.\nCode:\n```\nclass Solution {\n public int minimumWhiteTiles(String floor, int numCarpets, int carpetLen) {\n // memo[I][J] = subproblem of floor[0...I] with J numCarpets.\n // so I range from 0...(floor.len - 1) so floor.len possibilities\n // and J range from 0 ... numCarpets so numCarpets+1 possibilities\n Integer[][] memo = new Integer[floor.length()][numCarpets + 1];\n return dfs(floor.length() - 1, numCarpets, carpetLen, memo, floor);\n }\n \n // precond. i and j both >=0. don\'t add check at start, instead maintain this\n private int dfs(int i, int j, int carpetLen, Integer[][] memo, String floor) {\n //if (i < 0 || j < 0) {\n //return 0;\n //}\n if (memo[i][j] != null) {\n return memo[i][j];\n }\n int min = Integer.MAX_VALUE;\n // case 1: only when have at least 1 carpet to work with so let one extend and end at I\n if (j > 0) {\n if (i - carpetLen >= 0) {\n min = Math.min(min, dfs(i - carpetLen, j-1, carpetLen, memo, floor));\n } else {\n // have enough carpet to span all of [0...i] so no while tiles visible\n memo[i][j] = 0;\n return 0;\n }\n }\n // case 2: tile does not extend till here\n if (i > 0) {\n min = Math.min(min, dfs(i-1, j, carpetLen, memo, floor) + ((floor.charAt(i) == \'1\')? 1 : 0));\n } else {\n min = Math.min(min, ((floor.charAt(i) == \'1\')? 1 : 0));\n }\n memo[i][j] = min;\n return min;\n }\n}\n```\n
1
0
['Dynamic Programming', 'Java']
1
minimum-white-tiles-after-covering-with-carpets
Java Solution | Top-Down DP | 2 approaches
java-solution-top-down-dp-2-approaches-b-pney
Explanation :\n\nHere, I want to showcase 2 approaches for solving the problem using memoization :\n\t\t1. counting the minimum number of exposed white tiles us
arcpri
NORMAL
2022-03-20T08:33:16.556988+00:00
2022-03-20T08:41:56.786657+00:00
86
false
**Explanation :**\n\nHere, I want to showcase 2 approaches for solving the problem using memoization :\n\t\t1. counting the minimum number of exposed white tiles using `suffix-sum` and\n\t\t2. counting the maximum number of white tiles covered by the given carpets and subtracting this from the total number of white tiles to get the exposed white tiles using `prefix-sum`\n\n**Approach 1 :**\n\n```\npublic int minimumWhiteTiles(String floor, int numCarpets, int carpetLen) {\n Integer[][] dp = new Integer[floor.length() + 1][numCarpets + 1];\n int[] suffixSum = new int[floor.length()];\n suffixSum[floor.length() - 1] = (floor.charAt(floor.length() - 1) == \'1\' ? 1 : 0);\n\n for (int i = floor.length() - 2; i >= 0; i--) {\n suffixSum[i] = suffixSum[i + 1] + (floor.charAt(i) == \'1\' ? 1 : 0);\n }\n\n return coverTilesDP(floor, 0, carpetLen, numCarpets, dp, suffixSum);\n }\n\n private int coverTilesDP(String str, int idx, int carpetLen,\n int numCarpets, Integer[][] dp, int[] suffixSum) {\n if (idx >= str.length()) {\n return 0;\n } else if (numCarpets == 0) {\n return suffixSum[idx];\n }\n\n if (dp[idx][numCarpets] != null) {\n return dp[idx][numCarpets];\n }\n\t\t\n // include\n int min1 = coverTilesDP(str, idx + carpetLen, carpetLen, numCarpets - 1, dp, suffixSum);\n // exclude\n int min2 = coverTilesDP(str, idx + 1, carpetLen, numCarpets, dp, suffixSum) + (str.charAt(idx) == \'1\' ? 1 : 0);\n\n return dp[idx][numCarpets] = Math.min(min1, min2);\n }\n```\n\n**Approach 2 :**\n\n```\n public int minimumWhiteTiles(String floor, int numCarpets, int carpetLen) {\n Integer[][] dp = new Integer[floor.length() + 1][numCarpets + 1];\n int[] prefixSum = new int[floor.length()];\n prefixSum[0] = (floor.charAt(0) == \'1\' ? 1 : 0);\n\n for (int i = 1; i < floor.length(); i++) {\n prefixSum[i] = prefixSum[i - 1] + (floor.charAt(i) == \'1\' ? 1 : 0);\n }\n return prefixSum[floor.length() - 1] - coverTilesDP(floor, 0, carpetLen,\n numCarpets, dp, prefixSum);\n }\n\n private int coverTilesDP(String str, int idx, int carpetLen,\n int numCarpets, Integer[][] dp, int[] prefixSum) {\n if (idx >= str.length() || numCarpets == 0) {\n return 0;\n }\n\n if (dp[idx][numCarpets] != null) {\n return dp[idx][numCarpets];\n }\n\n // include\n int max1 = coverTilesDP(str, idx + carpetLen, carpetLen, numCarpets - 1, dp, prefixSum) +\n (prefixSum[Math.min(idx + carpetLen - 1, prefixSum.length - 1)] - (idx >= 1 ? prefixSum[idx - 1] : 0));\n // exclude\n int max2 = coverTilesDP(str, idx + 1, carpetLen, numCarpets, dp, prefixSum);\n\n return dp[idx][numCarpets] = Math.max(max1, max2);\n }\n```\n\n**PS -** Any suggestions or improvements are most welcome.
1
0
['Dynamic Programming', 'Memoization', 'Prefix Sum', 'Java']
1
minimum-white-tiles-after-covering-with-carpets
Java | DP | Memoization
java-dp-memoization-by-sohailabbas1000-yk4o
Do Binary Search and store indices of whites tiles.\n2. We can use DP here now where:\ndp(floorLength, numCarpets) = max(dp(floorLength - carpetLen, numCarpets
sohailabbas1000
NORMAL
2022-03-20T08:04:30.855153+00:00
2022-03-20T08:04:30.855184+00:00
54
false
1. Do Binary Search and store indices of whites tiles.\n2. We can use DP here now where:\ndp(floorLength, numCarpets) = max(dp(floorLength - carpetLen, numCarpets - 1) + numOfWhiteTilesInRange(floorLength - carpetLen, floorLength), dp(floorLength - carpetLen, numCarpets - 1)) -> number of white tiles covered from index 0 to floorLength using numCarpets number of carpets.\n3. Base Conditions:\nif (floorLength < 0 || numCarpets <= 0) return 0;\n4. ans = whiteTiles.size() - dp(floorLength, numCarpets)\n```\nclass Solution {\n public int minimumWhiteTiles(String floor, int numCarpets, int carpetLen) {\n int floorLength = floor.length();\n List<Integer> whiteTiles = new ArrayList<>();\n for (int tile = 0; tile < floorLength; tile += 1) {\n if (floor.charAt(tile) == \'1\') {\n whiteTiles.add(tile);\n }\n }\n Integer[][] dp = new Integer[floorLength][numCarpets + 1];\n System.out.println(minimumWhiteTiles(floorLength - 1, numCarpets, carpetLen, dp, whiteTiles) + "-" + whiteTiles.size());\n return whiteTiles.size() - minimumWhiteTiles(floorLength - 1, numCarpets, carpetLen, dp, whiteTiles);\n }\n \n private int minimumWhiteTiles(int floorLength, int numCarpets, int carpetLen, Integer[][] dp, List<Integer> whiteTiles) {\n if (floorLength < 0 || numCarpets <= 0) {\n return 0;\n }\n if (dp[floorLength][numCarpets] != null) {\n return dp[floorLength][numCarpets];\n }\n return dp[floorLength][numCarpets] = Math.max(minimumWhiteTiles(floorLength - carpetLen, numCarpets - 1, carpetLen, dp, whiteTiles) + numOfWhiteTilesInRange(floorLength - carpetLen, floorLength, whiteTiles), minimumWhiteTiles(floorLength - 1, numCarpets, carpetLen, dp, whiteTiles));\n }\n \n private int numOfWhiteTilesInRange(int start, int end, List<Integer> whiteTiles) {\n int maxIndex = ceil(end, whiteTiles);\n int minIndex = ceil(start, whiteTiles);\n return maxIndex - minIndex;\n }\n \n int ceil(int idx, List<Integer> whiteTiles) {\n int ans = -1;\n int start = 0;\n int end = whiteTiles.size() - 1;\n while(start <= end) {\n int mid = start + (end - start) / 2;\n if(whiteTiles.get(mid) <= idx) {\n ans = mid;\n start = mid + 1;\n } else {\n end = mid - 1;\n }\n }\n return ans + 1;\n }\n}\n```
1
1
['Dynamic Programming', 'Memoization', 'Java']
0
minimum-white-tiles-after-covering-with-carpets
JAVA Simple Solution with Explaination
java-simple-solution-with-explaination-b-fii3
I was having the problem to think but got intuition of DP by seeing constraints. But Now how to implement DP what will be the variables to play . Basically thin
anmolbisht10
NORMAL
2022-03-19T23:25:57.061831+00:00
2022-03-19T23:25:57.061866+00:00
75
false
I was having the problem to think but got intuition of DP by seeing constraints. But Now how to implement DP what will be the variables to play . Basically think on which variables you are dependent;\nYes You have to travel the complete the floor string so this variable is changing and second the number of carpet is changing. \ncarpet length is constant .\nThis is similar to knapsack yes , here each carpet has value that is length. \nAt each index you have two choice either use carpet or don\'t use it;\nif already black skip and move forward\nif white you can use carpet or you can leave white (thus cnt will be increased)\n\nif all carpet are used and still floor is not completed just return number of white tiles are left;\nbelow is the code\n\n\nclass Solution {\n public int minimumWhiteTiles(String floor, int numCarpets, int carpetLen) {\n // we have to cover the tiles we first see the color if it is black \n // we leave if its white we have option to jump or we cover it;\n int dp[][]= new int[floor.length()+1][numCarpets+1];\n for(int a[]: dp){\n Arrays.fill(a, -1);\n }\n return helper( 0, numCarpets, carpetLen, dp, floor);\n }\n public int helper(int i, int nc, int l, int[][] dp, String s){\n \n if(i>= s.length()) return 0;\n if(nc<=0){\n int cnt=0;\n for(int j= i; j<s.length(); j++){\n if(s.charAt(j)==\'1\'){\n cnt++;\n }\n }\n return cnt;\n }\n \n if(dp[i][nc]!=-1) return dp[i][nc];\n \n \n if(s.charAt(i)==\'0\'){\n return dp[i][nc]= helper(i+1, nc,l , dp , s);\n }\n else{\n int jump= 1+ helper(i+1, nc, l, dp, s);\n int cover= helper(i+ l, nc-1, l, dp, s);\n \n return dp[i][nc]= Math.min(jump, cover);\n }\n \n }\n}
1
0
['Dynamic Programming', 'Java']
0
minimum-white-tiles-after-covering-with-carpets
DP + edge case optimization with explanations
dp-edge-case-optimization-with-explanati-jkdy
Two edge cases can be handled explicitly before running DP:\n(1) if numCarpets * carpetLen >= n, i.e. the totally length of carpets altogether is longer than th
xil899
NORMAL
2022-03-19T20:59:35.455654+00:00
2022-03-19T20:59:35.455683+00:00
98
false
Two edge cases can be handled explicitly before running DP:\n(1) `if numCarpets * carpetLen >= n`, i.e. the totally length of carpets altogether is longer than the length of `floor`, return 0 immediately;\n(2) `if carpetLen == 1`, then the problem becomes trivial and we can cover the carpets "greedily". Adding this edge check is particularly useful for a few long test cases (as it would save half of the time for such cases), which does help to get AC for this problem.\nThe rest of the code deals with the general cases by using DP, where `dp[i][j]` represents the minimum white tiles after covering with `j` carpets for first `i` tiles.\nPlease upvote if you find this solution helpful.\n```\nclass Solution:\n def minimumWhiteTiles(self, floor: str, numCarpets: int, carpetLen: int) -> int:\n n = len(floor)\n\t\t# edge case handling\n if numCarpets * carpetLen >= n:\n return 0\n if carpetLen == 1:\n return max(sum([int(c) for c in floor]) - numCarpets, 0)\n\t\t# DP initialization\n dp = [[None] * (numCarpets + 1) for _ in range(n + 1)]\n for j in range(numCarpets + 1):\n dp[0][j] = 0\n for i in range(1, n + 1):\n dp[i][0] = dp[i - 1][0] + int(floor[i - 1])\n\t\t# DP transition formula\n for i in range(1, n + 1):\n for j in range(1, numCarpets + 1):\n dp[i][j] = min(dp[i - 1][j] + int(floor[i - 1]), dp[max(i - carpetLen, 0)][j - 1])\n return dp[n][numCarpets]\n```
1
0
['Dynamic Programming', 'Python', 'Python3']
0
minimum-white-tiles-after-covering-with-carpets
C++ || EASY TO UNDERSTAND || Memoization Code
c-easy-to-understand-memoization-code-by-wu5n
\nclass Solution {\npublic:\n int dp[1002][1002];\n int solve(string &floor,int i,int n,int l,vector<int> &prefix)\n {\n if(i>=floor.size()||n==
aarindey
NORMAL
2022-03-19T19:59:33.599700+00:00
2022-03-19T19:59:33.599736+00:00
26
false
```\nclass Solution {\npublic:\n int dp[1002][1002];\n int solve(string &floor,int i,int n,int l,vector<int> &prefix)\n {\n if(i>=floor.size()||n==0)\n return 0;\n if(dp[i][n]!=-1)\n return dp[i][n];\n if(floor[i]==\'0\')\n return dp[i][n]=solve(floor,i+1,n,l,prefix);\n int x=min((int)(floor.size()),(int)(i+l))-1;\n int white=prefix[x];\n if(i!=0)\n white-=prefix[i-1];\n int ans1=white+solve(floor,i+l,n-1,l,prefix);\n int ans2=solve(floor,i+1,n,l,prefix);\n return dp[i][n]=max(ans1,ans2);\n }\n int minimumWhiteTiles(string floor, int numCarpets, int carpetLen) {\n int n=floor.size();\n vector<int> prefix(n);\n for(int i=0;i<=n;i++)\n {\n for(int j=0;j<=numCarpets;j++)\n {\n dp[i][j]=-1;\n }\n }\n if(floor[0]==\'1\')\n prefix[0]=1;\n else\n prefix[0]=0;\n for(int i=1;i<n;i++)\n {\n prefix[i]=prefix[i-1]+(floor[i]==\'1\');\n }\n int total_white=prefix[n-1];\n if(total_white==0)\n return 0;\n return total_white-solve(floor,0,numCarpets,carpetLen,prefix);\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
[]
0
minimum-white-tiles-after-covering-with-carpets
C++ | DP | Recursion + Memorization | Easy to Understand
c-dp-recursion-memorization-easy-to-unde-wvus
c++\nclass Solution {\npublic:\n int carpetLen, fLen;\n vector<int> sum;\n vector<vector<int>> dp;\n int solve(int pos, int numCar, string& floor){\
badhansen
NORMAL
2022-03-19T19:45:57.149158+00:00
2022-03-19T19:46:12.781281+00:00
60
false
```c++\nclass Solution {\npublic:\n int carpetLen, fLen;\n vector<int> sum;\n vector<vector<int>> dp;\n int solve(int pos, int numCar, string& floor){\n if(pos >= fLen){\n return 0;\n }\n \n if(numCar == 0){\n return 0;\n }\n \n int &ret = dp[pos][numCar];\n \n if(ret != -1){\n return ret;\n }\n \n int taken = 0, notTaken = 0;\n int fSum = 0, lSum = 0;\n \n fSum = pos > 0 ? sum[pos - 1] : 0;\n lSum = pos + carpetLen > fLen ? sum[fLen - 1] : sum[pos + carpetLen - 1];\n \n taken = lSum - fSum + solve(pos + carpetLen, numCar - 1, floor);\n notTaken = solve(pos + 1, numCar, floor);\n \n return ret = max(taken, notTaken);\n }\n int minimumWhiteTiles(string floor, int numCarpets, int carpetLen) {\n fLen = floor.size();\n this->carpetLen = carpetLen;\n sum.resize(fLen + 1, 0);\n dp.resize(fLen + 1, vector<int> (numCarpets + 1, -1));\n sum[0] = floor[0] - \'0\';\n \n for(int i = 1; i < fLen; i++){\n sum[i] = sum[i - 1] + (floor[i] - \'0\');\n }\n \n return sum[fLen - 1] - solve(0, numCarpets, floor);\n }\n};\n```
1
0
['Dynamic Programming', 'Memoization']
0
minimum-white-tiles-after-covering-with-carpets
✅[Java] || Using dynamic programming || Simple Solution
java-using-dynamic-programming-simple-so-x7zl
First, if numCarpets * carpetLen > floor.size(), the answer is always 0 because the entire floor can be covered.\nOtherwise,This problem can be solved by using
shojin_pro
NORMAL
2022-03-19T17:26:38.647344+00:00
2022-03-20T06:00:34.800927+00:00
41
false
First, if numCarpets * carpetLen > floor.size(), the answer is always 0 because the entire floor can be covered.\nOtherwise,This problem can be solved by using dynamic programming.\nThe variables in the DP are\n1. length of confirmed Floor (starting from the left end at 0)\n2. number of carpets used\n\nThe spatial computational complexity of a 2-dimensional array using the above variables is O(1e6).\n\nPlease see the image below for a sample transition with floor = "10110", numCarpets = 2, carpetLen = 2.\n![image](https://assets.leetcode.com/users/images/20a2a6f5-af47-40d4-a972-6e2e000d96e3_1647710851.003477.png)\n\nThe red arrow shows the transition when the carpet is pulled.\n`dp[i+cl][j+1] = Math.min(dp[i+cl][j+1], dp[i][j]);`\n\u203B Math.min(i+cl,f.length) is used in my code because the index could exceed floor.size().\n\nThe black arrow is the transition if the carpet is not pulled.\nIf the next floor is white, increase the value by +1 from the current value.\n`dp[i+1][j] = Math.min(dp[i+1][j], dp[i][j] + floor[i]);`\n\nWe have solved this problem by performing two different transitions for each item in the dp array.\n\nex) the gray items and arrows are not valid, we can show that there is no transition from dp[0][0] to dp[1][0],dp[1][1] for example, because the length of the carpet is more than 2.\n\n```\nclass Solution {\n public int minimumWhiteTiles(String floor, int numCarpets, int carpetLen) {\n //1. Redefine for variable name shortening\n int ln = floor.length();\n int nc = numCarpets;\n int cl = carpetLen;\n \n //2. Return 0 if all floors can be covered from carpet length * number of carpets.\n char[] f = floor.toCharArray();\n int cover = numCarpets * carpetLen;\n if(cover >= f.length) return 0;\n \n \n //3. Dynamic Programming\n int[][] dp = new int[ln+1][nc+1];\n for(int i = 0; i <= ln; i++) Arrays.fill(dp[i],f.length);\n dp[0][0] = 0;\n for(int i = 0; i < ln; i++){\n int plus = f[i]-\'0\';\n for(int j = 0; j <= nc; j++){\n dp[i+1][j] = Math.min(dp[i+1][j],dp[i][j] + plus);\n if(j != nc) dp[Math.min(i+cl,f.length)][j+1] = Math.min(dp[Math.min(i+cl,f.length)][j+1], dp[i][j]);\n }\n }\n return dp[ln][nc];\n }\n}\n```
1
0
[]
0
minimum-white-tiles-after-covering-with-carpets
C++ DP house robber
c-dp-house-robber-by-nanshan0719-lkv5
This problem can be converted to house robber then solved by dynamic programming.\nWhen the total length of carpet is equal to or exceed the length of the floor
nanshan0719
NORMAL
2022-03-19T17:18:21.911926+00:00
2022-03-20T02:27:47.239637+00:00
89
false
This problem can be converted to [house robber](https://leetcode.com/problems/house-robber/) then solved by dynamic programming.\nWhen the total length of carpet is equal to or exceed the length of the floor, there should be no white left. When it\'s not, we should always looking for non-overlapping solution as at least one of the optimal solution doesn\'t include overlapping. The reason is that we can always rearrange carpets to not overlap and covering all the original tiles and some more.\nSo we can calculate how many white tiles can be covered starting from each position, the problem is to select ```numCarpet``` of positions, with minimum distance of any two position is ```carpetLen```, to get the maximum sum. It\'s equivalent to house robber except that we not only can\'t rob consecutive houses, we can\'t rob houses within some given distance ```carpetLen```. Also we have a fixed amount of house we have to rob, so instead of a 1D DP as we did in house robber, a standard 2D DP approach should suffice. See annotation for details.\n```\nclass Solution {\npublic:\n int minimumWhiteTiles(string floor, int numCarpets, int carpetLen) {\n\t\t//too many carpets, cover all the floor\n int l = floor.size();\n if(numCarpets*carpetLen>=l) {return 0;}\n\t\t\n // sliding window to calculate how many white tiles can be covered for a carpet starting at position i\n int white = 0; // number of total white tiles on the floor\n int m = l-carpetLen+1; // number of possible carpet starting position\n vector<int> cover(m,0); // number of white tiles covered for a carpet starting at each position\n for(int i=0; i<carpetLen; i++){\n cover[0] += (floor[i]==\'1\');\n white += (floor[i]==\'1\');\n }\n for(int i=1; i<m; i++){\n cover[i] = cover[i-1] - (floor[i-1]==\'1\') + (floor[i+carpetLen-1]==\'1\');\n white += (floor[i+carpetLen-1]==\'1\');\n }\n\t\t\n // dp to find the maximum sum of numCarpets elements from cover[0:m-1], \n\t\t// with any of the two elements having minimum distance of carpetLen\n\t\t// dp[k][i] stands for the maximum sum for k elements in cover[0:i]\n vector<vector<int>> dp(numCarpets+1, vector<int>(m,0));\n dp[1][0] = cover[0];\n for(int i=1; i<m; i++){\n dp[1][i] = max(dp[1][i-1],cover[i]);\n }\n for(int carpet=2; carpet<=numCarpets; carpet++){\n for(int i=(carpet-1)*carpetLen; i<m; i++){\n\t\t\t\t// either we don\'t select current element, \n\t\t\t\t// or we select current element and limit the range of last selected element before i-carpetLen\n dp[carpet][i] = max(dp[carpet][i-1],cover[i]+dp[carpet-1][i-carpetLen]);\n }\n }\n return white-dp[numCarpets][m-1];\n }\n};\n```\nThis solution should be able to optimized to O(N) space complexity by using two 1D vectors.
1
0
['Dynamic Programming', 'C']
0
minimum-white-tiles-after-covering-with-carpets
[c++] | DP Solution | Memoization | (100% FAST) | EASY TO UNDERSTAND
c-dp-solution-memoization-100-fast-easy-7a6br
\nclass Solution {\npublic:\n int solve(vector<int> &hash, int &num, int &len, int i, int j, vector<vector<int>> &dp){\n int n = hash.size();\n
narayanbansal35
NORMAL
2022-03-19T17:08:07.382306+00:00
2022-03-21T09:56:59.761543+00:00
77
false
```\nclass Solution {\npublic:\n int solve(vector<int> &hash, int &num, int &len, int i, int j, vector<vector<int>> &dp){\n int n = hash.size();\n if (j >= num or i >= n) return 0;\n if (dp[i][j] != -1) return dp[i][j];\n// Dont want to put the carpet on the ith place\n int not_take = solve(hash, num, len, i+1, j, dp);\n// Want to put the carpet on the ith place and the corresponding value which it gives is added\n int take = hash[i] + solve(hash, num, len, i+len, j+1, dp);\n \n return dp[i][j] = max(not_take, take);\n }\n \n int minimumWhiteTiles(string floor, int num, int len) {\n int n = floor.size();\n if (num*len >= n) return 0; \n int var = 0, count = 0;\n for (int i = 0;i < n;i++) count += (floor[i] == \'1\');\n if (count == n){\n return (n - (num*len));\n }\n// hash stores that if we put the carpet at the ith position \n// then how much white space i\'ll cover\n vector<int> hash(n);\n for (int i = n-1;i >= 0;i--){\n if (floor[i] == \'1\'){\n var += 1;\n }\n if (i+len < n and floor[i+len] == \'1\'){\n var -= 1;\n }\n hash[i] = var;\n }\n// dp[i][j] stores if i am on the ith index and jth carpet is used \n// then how much maximum white spaces i\'ll cover\n vector<vector<int>> dp(n, vector<int> (num, -1));\n// solve gives me the maximus white i can cover with carpet using the num number of carpets \n// of length len\n int temp = solve(hash, num, len, 0, 0, dp);\n return count - temp;\n }\n};\n```\nComment below if you have any doubt\nPlease upvote if you like\n
1
0
['Dynamic Programming', 'Memoization']
0
minimum-white-tiles-after-covering-with-carpets
C++ Solution | Memo + recursive + prefix array
c-solution-memo-recursive-prefix-array-b-e0nz
So , Here i changed the question instead of finding the minimum no of white tiles after placing k tiles , I am trying to find the maximum white tiles i can cove
X30N_73
NORMAL
2022-03-19T16:54:19.113327+00:00
2022-03-19T16:54:19.113365+00:00
69
false
So , Here i changed the question instead of finding the minimum no of white tiles after placing k tiles , I am trying to find the maximum white tiles i can cover with the k tiles and return the answer after subtracting with the intital no of white tiles present in the string.\n\n```\nclass Solution {\npublic:\n int dp[1001][1001];\n vector<int>prefix;\n int helper(int idx,int k,string& floor,int len){\n if(idx >= floor.size())return 0;\n if(dp[idx][k] != -1)return dp[idx][k];\n int op1 = helper(idx + 1,k,floor,len);\n int op2 = 0;\n if(floor[idx] == \'1\' && k > 0){\n int sz = min(idx + len,(int)floor.size());\n int y = prefix[sz - 1];\n if(idx - 1 >= 0){\n y -= prefix[idx - 1];\n }\n op2 = y + helper(idx + len,k - 1,floor,len);\n }\n return dp[idx][k] = max(op1,op2);\n }\n int minimumWhiteTiles(string floor, int numCarpets, int carpetLen) {\n int cnt = 0;\n int n = floor.size();\n memset(dp,-1,sizeof dp);\n for(int i =0;i<floor.size();i++){\n if(floor[i] == \'1\')cnt++;\n }\n prefix.resize(n + 1,0);\n prefix[0] = (floor[0] == \'1\');\n for(int i =1;i<=n;i++){\n if(floor[i] == \'1\'){\n prefix[i] = prefix[i - 1] + 1;\n }\n else prefix[i] = prefix[i - 1];\n }\n if(cnt == 0)return 0;\n return cnt - helper(0,numCarpets,floor,carpetLen);\n }\n};\n```
1
0
['Dynamic Programming', 'Recursion']
0
minimum-white-tiles-after-covering-with-carpets
python3 DP O(N*numCarpets) solution got a TLE. Is this intended?
python3-dp-onnumcarpets-solution-got-a-t-uoav
My solution is given as\n\nclass Solution:\n def minimumWhiteTiles(self, floor: str, numCarpets: int, carpetLen: int) -> int:\n dp = dict() # i, num_c
shovsj
NORMAL
2022-03-19T16:33:00.103502+00:00
2022-03-19T16:33:00.103548+00:00
38
false
My solution is given as\n```\nclass Solution:\n def minimumWhiteTiles(self, floor: str, numCarpets: int, carpetLen: int) -> int:\n dp = dict() # i, num_carpets remaining -> num white\n n = len(floor)\n for i in range(n+1)[::-1]:\n for j in range(numCarpets+1):\n if i == n:\n dp[(i,j)] = 0\n continue\n \n if floor[i] == \'0\':\n dp[(i,j)] = dp[(i+1,j)]\n else:\n dp[(i,j)] = 1+dp[(i+1,j)] \n if j > 0:\n dp[(i,j)] = min(dp[(i,j)], dp[(min(i+carpetLen, n),j-1)])\n \n return dp[(0, numCarpets)]\n```\nShould I make it more faster? \nIs this intended?
1
0
[]
2
minimum-white-tiles-after-covering-with-carpets
dp | intuition with explaination
dp-intuition-with-explaination-by-keepmo-6b03
Intuition\n\n\nlets suppose are at ith index.\n\nsuppose we are at index i and with j carpets\ndp[i][j] denotes minimum number of uncovered white cells from 0 t
KeepMotivated
NORMAL
2022-03-19T16:09:33.008149+00:00
2022-03-19T16:09:33.008180+00:00
78
false
**Intuition**\n\n\nlets suppose are at ith index.\n\nsuppose we are at index i and with j carpets\ndp[i][j] denotes minimum number of uncovered white cells from 0 to i with j \ncarpets.\n\n1. if number of carpets = 0 dp[i][j] = number of carpets from 0 to i.\n\n\nsuppose we are at index i and with j carpets\n1. we dont put carpet. in this case number of uncovered white cells will be \nnumber of uncovered white cells at i-1 + 1 (if ith cell is )\ndp[i][j] = dp[i-1][j] + 1 if ith carpet is red;\n\n\n2. if we are placing carpet (j>0) such that ith is the last cell covered.\n\ni-carpetlength < 0 that means we are fulling covering from 0 to i.\n[i][j] = 0\n\ni-carpetlength >= 0 that means we are covering from\ni-carpetlength+1 to i and number of carpet left are j-1\n\nso dp[i][j] = dp[i-carpetlength][j-1] // cells i-carpetlength+1 to i is covered\n\nat last we will take minimmum of both the values \ndp[i][j] = min(dp[i-1][j]) + 1 if ith carpet is red, 0 if i-carpetlength < 0 else dp[i-carpetlength][j-1]\n\n```\nclass Solution {\npublic:\n int minimumWhiteTiles(string floor, int numCarpets, int carpetLen) {\n int n = floor.size();\n vector<vector<int>>dp(n,vector<int>(numCarpets+1));\n int ans = 0;\n vector<int>freq(n);\n for(int i = 0;i<n;i++)\n {\n ans += floor[i]-\'0\';\n freq[i] = ans;\n }\n for(int i = 0;i<n;i++)\n {\n for(int j = 0;j<=numCarpets;j++)\n {\n if(j == 0)\n {\n dp[i][j] = freq[i];\n continue;\n }\n if(i-carpetLen < 0)\n {\n dp[i][j] = 0;\n }\n else if(i-carpetLen >= 0)\n {\n dp[i][j] = dp[i-carpetLen][j-1];\n }\n int value = 0;\n if(i>0)\n {\n value += floor[i]-\'0\';\n dp[i][j] = min(dp[i-1][j] + value ,dp[i][j]);\n }\n else\n {\n value += floor[i]-\'0\';\n dp[i][j] = min(value ,dp[i][j]);\n }\n }\n \n }\n return dp[n-1][numCarpets];\n }\n};\n```
1
0
['Dynamic Programming']
0
minimum-white-tiles-after-covering-with-carpets
** Python - DP | Memoization solution **
python-dp-memoization-solution-by-arjuho-4olr
\nclass Solution:\n def minimumWhiteTiles(self, floor: str, numCarpets: int, carpetLen: int) -> int:\n if numCarpets*carpetLen >= len(floor):\n
arjuhooda
NORMAL
2022-03-19T16:05:23.885005+00:00
2022-03-19T16:05:37.303184+00:00
72
false
```\nclass Solution:\n def minimumWhiteTiles(self, floor: str, numCarpets: int, carpetLen: int) -> int:\n if numCarpets*carpetLen >= len(floor):\n return 0\n l = list(map(int,list(floor)))\n dp = [[-1]*(numCarpets+1) for j in range(len(l))]\n \n def rec(i,n):\n nonlocal l\n if n == 0 or i >= len(l):\n return sum(l[i:])\n if dp[i][n] != -1:\n return dp[i][n]\n dp[i][n] = min(rec(i+carpetLen,n-1),rec(i+1,n)+l[i])\n return dp[i][n]\n \n return rec(0,numCarpets)\n```
1
0
['Memoization', 'Python']
0
minimum-white-tiles-after-covering-with-carpets
DP | Memorization | Easy to Understand solution | C++ | O(n^2) time and O(n^2) space |
dp-memorization-easy-to-understand-solut-8zlg
We can solve this problem by using standard concepts of solving a 2-d DP problem.\nFor each tile, we have two options --\ni) We place a the carpet starting from
sa01042001
NORMAL
2022-03-19T16:04:22.948737+00:00
2022-03-19T16:04:22.948765+00:00
71
false
We can solve this problem by using standard concepts of solving a 2-d DP problem.\nFor each tile, we have two options --\ni) We place a the carpet starting from the current tile\nii) We do not place a carpet\n\nFurther, here is an observations to be made\n-- Placing carpet starting from a black tile is not feasible. SO before placing a carpet, we will check whether the current tile is white or not.\n\n\nBelow is the code for the approach explained above. Lines have been commented in order to understand better.\n\n```\nint solve(string &a,int i,int j,int k,int len,vector<vector<long long int>> &dp)\n{\n \n // dp states --\n // i --> represents the index of the tiles\n // j --> represents the number of black carpets used\n \n if(i>=a.size())\n {\n // base case\n return 0;\n }\n \n if(dp[i][j]!=-1)\n {\n // since the current tile is already black, no need of covering it\n \n return dp[i][j];\n }\n \n \n if(a[i]==\'1\')\n {\n // the current tile is white in color, so we have two options\n \n int op1=INT_MAX,op2=INT_MAX;\n \n // option 1 - place carpet\n \n if(j<k) // we can only place carpets if we have some remaining black carpets\n op1=solve(a,i+len,j+1,k,len,dp);\n \n // option 2 - dont place the carpet\n op2=1+solve(a,i+1,j,k,len,dp);\n \n \n return dp[i][j]=min(op1,op2);\n }\n \n return dp[i][j]=solve(a,i+1,j,k,len,dp);\n \n}\n\nclass Solution {\npublic:\n int minimumWhiteTiles(string a, int k, int len) {\n \n // creating a two dimensional dp array\n vector<vector<long long int>> dp(a.size()+10,vector<long long int>(k+10,-1));\n \n return solve(a,0,0,k,len,dp);\n \n }\n};\n\n```\n
1
0
['Dynamic Programming', 'Memoization', 'C']
0
minimum-white-tiles-after-covering-with-carpets
[Python3] DP solution in O(MN) time and O(N) space
python3-dp-solution-in-omn-time-and-on-s-xg31
dp solution:\n dp[i][j] represents for the max number of covered white tiles within floor[:j + 1] using i carpets\n dp[i][j] = max(max(dp[i][k] for k in range(j
huayu_ivy
NORMAL
2022-03-19T16:02:44.600122+00:00
2022-03-19T16:07:11.242070+00:00
87
false
# dp solution:\n* `dp[i][j]` represents for the max number of covered white tiles within `floor[:j + 1]` using `i` carpets\n* `dp[i][j] = max(max(dp[i][k] for k in range(j)), white count in floor[j - carpetLen : j + 1] + dp[i - 1][j - carpetLen])`\n```\ndef minimumWhiteTiles(self, floor: str, numCarpets: int, carpetLen: int) -> int:\n # dp\n n = len(floor)\n cnt_white = []\n cnt = 0\n for i in floor:\n cnt += int(i)\n cnt_white.append(cnt)\n\t\t\n dp = [[0] * (n) for _ in range(numCarpets + 1)]\n for i in range(1, numCarpets + 1):\n max_ = 0\n for j in range(n):\n # i carpets\n # cover [0:j + 1] floor\n if j - carpetLen < 0:\n dp[i][j] = cnt_white[j]\n else:\n dp[i][j] = max(max_, cnt_white[j] - cnt_white[j - carpetLen] + dp[i - 1][j - carpetLen])\n max_ = dp[i][j]\n return cnt - dp[-1][-1]\n```\n\n# optimization:\nsince `dp[i]` only depend on `dp[i-1]`, we cound reduce space complexity to `O(N)`\n```\ndef minimumWhiteTiles(self, floor: str, numCarpets: int, carpetLen: int) -> int:\n # dp\n\tn = len(floor)\n cnt_white = []\n cnt = 0\n for i in floor:\n cnt += int(i)\n cnt_white.append(cnt)\n dp = [0] * (n)\n for i in range(1, numCarpets + 1):\n nxt = []\n max_ = 0\n for j in range(n):\n if j - carpetLen < 0:\n nxt.append(cnt_white[j])\n else:\n nxt.append(max(max_, cnt_white[j] - cnt_white[j - carpetLen] + dp[j - carpetLen]))\n max_ = nxt[-1]\n dp = nxt\n return cnt - dp[-1]\n```
1
0
['Dynamic Programming', 'Python']
0
minimum-white-tiles-after-covering-with-carpets
[Python3]2D DP solution explained
python32d-dp-solution-explained-by-prasa-tkk1
\nclass Solution:\n def minimumWhiteTiles(self, floor: str, numCarpets: int, carpetLen: int) -> int:\n \n """\n dp(pos, numC) -> returns
prasanna648
NORMAL
2022-03-19T16:01:37.032874+00:00
2022-03-19T16:01:37.032906+00:00
112
false
```\nclass Solution:\n def minimumWhiteTiles(self, floor: str, numCarpets: int, carpetLen: int) -> int:\n \n """\n dp(pos, numC) -> returns min number of white tiles seen from pos to the end of the floor\n if we have numC number of carpets left\n \n if numC > 0, i.e. we have some carpets remaining:\n if the tile at index pos is white, then we have two choices, \n either place a carpet from pos to pos + carpetLen - 1\n or skip this tile, so number of white tiles increases by one, and calculate the minimum answer from index\n pos + 1\n else\n no need to cover this tile, we can move ahead\n else:\n we cannot cover any more white tiles\n so return number of white tiles from pos to the end of floor\n \n \n time complexity : O(numCarpets * len(floor)) ~ O(n^2)\n """\n \n @lru_cache(None) \n def dp(pos, numC):\n if pos >= n:\n return 0\n \n if numC > 0:\n if floor[pos] == "1":\n return min(1 + dp(pos + 1, numC), dp(pos + carpetLen, numC - 1))\n else:\n return dp(pos + 1, numC)\n else:\n return ones[pos]\n \n \n n = len(floor)\n \n #ones[i] stores the number of white tiles from index i to the end of floor \n ones = [0 for i in range(n)]\n ones[-1] = (floor[-1] == "1")\n \n for i in range(n-2, -1, -1):\n ones[i] = ones[i+1] + (floor[i] == "1")\n \n \n return dp(0, numCarpets)\n \n \n \n```
1
0
[]
0
minimum-white-tiles-after-covering-with-carpets
C++ | with comments | DP
c-with-comments-dp-by-aman282571-fd1r
dp[idx][rem] wil store maximum tiles we can cover from idx to last index if we are at index idx with rem amount of carpet\n\n\nclass Solution {\npublic:\n v
aman282571
NORMAL
2022-03-19T16:00:53.718676+00:00
2022-03-19T16:01:59.274387+00:00
111
false
```dp[idx][rem]``` wil store maximum tiles we can cover from ```idx to last index``` if we are at index ```idx``` with ```rem``` amount of carpet\n\n```\nclass Solution {\npublic:\n vector<int>tile;\n vector<vector<int>>dp;\n int minimumWhiteTiles(string f, int num, int len) {\n int sz=f.size(),totalWHiteTiles=0;\n for(int i=0;i<sz;i++){\n if(f[i]==\'1\')\n totalWHiteTiles++;\n tile.push_back(totalWHiteTiles);\n }\n dp.resize(sz,vector<int>(num+1,-1));\n return totalWHiteTiles-helper(f,0,num,len);\n }\n int helper(string &floor,int idx,int rem,int &len){\n if(idx>=floor.size() || rem==0)\n return 0;\n if(dp[idx][rem]!=-1)\n return dp[idx][rem];\n int sz=floor.size();\n // don\'t start covering the tiles from here\n int a=helper(floor,idx+1,rem,len);\n // start covering the tiles from here\n int b=helper(floor,idx+len,rem-1,len);\n // last index where the carpet can go if we start coering from here\n int lastIdx=idx+len-1;\n // calculating how many tiles we will civer if we start from here\n b+=tile[lastIdx>=sz?(sz-1):lastIdx]-tile[idx];\n if(floor[idx]==\'1\')\n b++;\n dp[idx][rem]=max(a,b);\n return dp[idx][rem];\n }\n};\n```\nDo **UPVOTE** if it helps :)
1
0
['C']
0
minimum-white-tiles-after-covering-with-carpets
dp and prefix sum
dp-and-prefix-sum-by-johnchen-68r4
IntuitionApproachComplexity Time complexity: Space complexity: Code
johnchen
NORMAL
2025-02-21T16:27:27.598971+00:00
2025-02-21T16:27:27.598971+00:00
5
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```cpp [] class Solution { public: int minimumWhiteTiles(string floor, int numCarpets, int carpetLen) { const int n = floor.size(); vector<vector<int>> dp(n + 1, vector<int>(numCarpets + 1, n)); for (int i = 0; i <= numCarpets; ++ i) dp[0][i] = 0; for (int i = 1; i <= n; ++ i) { dp[i][0] = dp[i - 1][0] + static_cast<int>(floor[i - 1] == '1'); } for (int i = 1; i <= n; ++ i) { for (int j = 1; j <= numCarpets; ++ j) { dp[i][j] = min(i < carpetLen ? 0 : dp[i - carpetLen][j - 1], dp[i - 1][j] + static_cast<int>(floor[i - 1] == '1')); } } return dp.back().back(); } }; ```
0
0
['C++']
0
minimum-white-tiles-after-covering-with-carpets
2209. Minimum White Tiles After Covering With Carpets
2209-minimum-white-tiles-after-covering-pdhep
IntuitionApproachComplexity Time complexity: Space complexity: Code
G8xd0QPqTy
NORMAL
2025-01-18T06:41:23.027166+00:00
2025-01-18T06:41:23.027166+00:00
7
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```python3 [] class Solution: def minimumWhiteTiles(self, tiles, maxCuts, length): from functools import lru_cache @lru_cache(None) def helper(pos, cutsLeft): if pos <= 0: return 0 return min(int(tiles[pos - 1]) + helper(pos - 1, cutsLeft), helper(pos - length, cutsLeft - 1) if cutsLeft else float('inf')) return helper(len(tiles), maxCuts) ```
0
0
['Python3']
0
minimum-white-tiles-after-covering-with-carpets
Python Hard
python-hard-by-lucasschnee-zitq
null
lucasschnee
NORMAL
2025-01-15T01:37:08.840227+00:00
2025-01-15T01:37:08.840227+00:00
5
false
```python3 [] class Solution: def minimumWhiteTiles(self, floor: str, numCarpets: int, carpetLen: int) -> int: N = len(floor) @cache def calc(index, k): if index >= N: return 0 best = calc(index + 1, k) + int(floor[index]) if k > 0: best = min(best, calc(index + carpetLen, k-1)) return best return calc(0, numCarpets) ```
0
0
['Python3']
0
minimum-white-tiles-after-covering-with-carpets
Java | Dynamic Programming | Prefix Sum | Comments Explanation
java-dynamic-programming-prefix-sum-comm-vlks
\nclass Solution {\n public Integer dp[][];\n public int minimumWhiteTiles(String floor, int numCarpets, int carpetLen) {\n int n = floor.length();
Sampath1804
NORMAL
2024-12-23T15:25:16.538741+00:00
2024-12-23T15:25:16.538778+00:00
2
false
```\nclass Solution {\n public Integer dp[][];\n public int minimumWhiteTiles(String floor, int numCarpets, int carpetLen) {\n int n = floor.length();\n // if floor length is less than or equal to avaliable tiles return 0\n if(n <= numCarpets*carpetLen) return 0;\n \n //dp array\n dp = new Integer[n+1][numCarpets+1];\n \n //Prefix sum array for floor string\n int[] whiteTiles = new int[n+1];\n for(int i=1;i<=n;i++) {\n int curVal = floor.charAt(i-1)==\'1\' ? 1 : 0;\n whiteTiles[i] = whiteTiles[i-1] + curVal;\n }\n \n //finding maximum tiles we can cover with available numCarpets * carpetLen tiles\n int maxTilesCovered = maxTilesCanCover(whiteTiles, 1, numCarpets, carpetLen, n+1);\n \n // Subtracting all tiles which need to covered minus maximum no of tiles we were able to cover\n return whiteTiles[n] - maxTilesCovered;\n }\n public int maxTilesCanCover(int[] tiles , int ind, int numCarpets, int len, int n) {\n //base condition\n if(ind>=n || numCarpets<=0) return 0;\n \n //dp state to cache precomputed state\n if(dp[ind][numCarpets]!=null) return dp[ind][numCarpets];\n int ans = maxTilesCanCover(tiles, ind+1, numCarpets, len, n);\n \n //if the tile length is greater than array length taking the minimum of them\n int lastInd = Math.min(ind+len-1, n-1);\n \n // finding no of tiles present in the given tile length\n int curTileLen = tiles[lastInd]-tiles[ind-1];\n \n //Only computing when the current Tile length is less than or equal to available numCarpets * carpetLen tiles\n if(curTileLen<=(numCarpets*len)) {\n int noOfTilesReq = (int) Math.ceil((double) curTileLen/len);\n ans = Math.max(ans,curTileLen + maxTilesCanCover(tiles, lastInd+1, numCarpets-noOfTilesReq, len,n));\n }\n \n //Storing and returning the computed result\n return dp[ind][numCarpets]=ans;\n }\n}\n```
0
0
['Dynamic Programming', 'Memoization', 'Prefix Sum', 'Java']
0
minimum-white-tiles-after-covering-with-carpets
DP, O(n^2) TC
dp-on2-tc-by-filinovsky-1sq0
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
Filinovsky
NORMAL
2024-12-05T13:13:11.168961+00:00
2024-12-05T13:13:11.168986+00:00
4
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```python3 []\nclass Solution:\n \n def __init__(self):\n self.mem = {}\n self.pref = []\n \n def findMin(self, floor, i, j, ln):\n n = len(floor)\n if j == 0:\n return self.pref[n - 1] - (self.pref[i - 1] if i > 0 else 0)\n if n - i < ln and j > 0:\n return 0\n if (i, j) in self.mem:\n return self.mem[(i, j)]\n ans = 10**9\n if floor[i] == \'1\' and n - i >= ln:\n ans = min(ans, self.findMin(floor, i + ln, j - 1, ln))\n ans = min(ans, 1 + self.findMin(floor, i + 1, j, ln))\n elif floor[i] == \'0\' and n - i >= ln:\n ans = min(ans, self.findMin(floor, i + ln, j - 1, ln))\n ans = min(ans, self.findMin(floor, i + 1, j, ln))\n self.mem[(i, j)] = ans\n return ans\n \n def minimumWhiteTiles(self, floor: str, numCarpets: int, carpetLen: int) -> int:\n n = len(floor)\n for i in range(n):\n self.pref.append((self.pref[-1] if self.pref else 0) + int(floor[i]))\n return self.findMin(floor, 0, numCarpets, carpetLen)\n \n```
0
0
['Python3']
0
minimum-white-tiles-after-covering-with-carpets
💥 Beats 100% on runtime [EXPLAINED]
beats-100-on-runtime-explained-by-r9n-ukw7
Intuition\nMinimize the number of white tiles visible after covering them with carpets. Carpets can overlap, and each carpet can cover a fixed number of consecu
r9n
NORMAL
2024-11-10T10:10:50.553170+00:00
2024-11-10T10:10:50.553197+00:00
0
false
# Intuition\nMinimize the number of white tiles visible after covering them with carpets. Carpets can overlap, and each carpet can cover a fixed number of consecutive tiles. The problem can be tackled using dynamic programming, where we explore whether it\'s better to cover certain tiles or leave them uncovered.\n\n# Approach\nUse a DP table where each entry represents the minimum number of white tiles left uncovered after covering some portion of the floor with a certain number of carpets; we fill this table by deciding at each tile whether to place a carpet and cover a set of white tiles or to leave the current tile uncovered.\n\n# Complexity\n- Time complexity:\nO(n * numCarpets), where n is the length of the floor, because we compute the result for each tile and each number of carpets using a table of size n * numCarpets.\n\n- Space complexity:\nO(n * numCarpets), due to the storage of the DP table and prefix sum array, which have dimensions based on the floor length and the number of carpets.\n\n# Code\n```csharp []\npublic class Solution {\n private int[] prefix;\n private int[,] dp;\n\n public int MinTiles(int n, string floor, int numCarpets, int carpetLen) {\n if (n < 0) {\n return 0;\n }\n if (numCarpets == 0) {\n return prefix[n];\n }\n if (dp[n, numCarpets] != -1) {\n return dp[n, numCarpets];\n }\n int cover = MinTiles(n - carpetLen, floor, numCarpets - 1, carpetLen);\n int notCover = MinTiles(n - 1, floor, numCarpets, carpetLen) + (floor[n] == \'1\' ? 1 : 0);\n dp[n, numCarpets] = Math.Min(cover, notCover);\n return dp[n, numCarpets];\n }\n\n public int MinimumWhiteTiles(string floor, int numCarpets, int carpetLen) {\n if (numCarpets * carpetLen >= floor.Length) {\n return 0;\n }\n\n int n = floor.Length;\n prefix = new int[n];\n dp = new int[n, numCarpets + 1];\n\n // Initialize the dp array with -1\n for (int i = 0; i < n; i++) {\n for (int j = 0; j <= numCarpets; j++) {\n dp[i, j] = -1;\n }\n }\n\n // Fill the prefix array\n if (floor[0] == \'1\') {\n prefix[0] = 1;\n }\n for (int i = 1; i < n; i++) {\n prefix[i] = (floor[i] == \'1\') ? 1 : 0;\n prefix[i] += prefix[i - 1];\n }\n\n // Call the MinTiles function starting from the last index\n return MinTiles(n - 1, floor, numCarpets, carpetLen);\n }\n}\n\n```
0
0
['String', 'Dynamic Programming', 'Prefix Sum', 'C#']
0
minimum-white-tiles-after-covering-with-carpets
Python (Simple DP)
python-simple-dp-by-rnotappl-v04u
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
2024-11-01T16:55:15.136288+00:00
2024-11-01T16:55:15.136340+00:00
9
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```python3 []\nclass Solution:\n def minimumWhiteTiles(self, floor, numCarpets, carpetLen):\n n, k = len(floor), numCarpets\n\n @lru_cache(None)\n def function(i,k):\n if i >= n:\n return 0 \n\n if k == 0:\n return int(floor[i]) + function(i+1,k)\n\n place = function(i+carpetLen,k-1)\n dont = int(floor[i]) + function(i+1,k)\n return min(place,dont)\n\n return function(0,k)\n```
0
0
['Python3']
0
minimum-white-tiles-after-covering-with-carpets
lee215's PYTHON solution with comments
lee215s-python-solution-with-comments-by-pq16
Copying lee215\'s solution\n# https://leetcode.com/u/lee215/\n\n# Code\npython3 []\n\n# Copying lee215\'s solution\n# https://leetcode.com/u/lee215/\n\nimport f
greg_savage
NORMAL
2024-10-30T04:04:07.814432+00:00
2024-10-30T04:04:07.814470+00:00
4
false
# Copying lee215\'s solution\n# https://leetcode.com/u/lee215/\n\n# Code\n```python3 []\n\n# Copying lee215\'s solution\n# https://leetcode.com/u/lee215/\n\nimport functools\n\nclass Solution:\n\n def minimumWhiteTiles(self, tiles, remaining_carpets, carpet_length):\n\n @lru_cache(None)\n def _layCarpet(next_tile_index, remaining_carpets):\n if next_tile_index <= 0:\n return 0\n\n skip_tile_choice = (\n int(tiles[next_tile_index - 1])\n +\n _layCarpet(\n next_tile_index - 1,\n remaining_carpets\n )\n )\n if remaining_carpets:\n lay_tile_choice = _layCarpet(next_tile_index - carpet_length, remaining_carpets - 1)\n else:\n lay_tile_choice = 1000 # Max\n \n return min(skip_tile_choice, lay_tile_choice)\n\n last_tile_index = len(tiles) \n return _layCarpet(last_tile_index, remaining_carpets) \n```
0
0
['Python3']
0
minimum-white-tiles-after-covering-with-carpets
Python 3: FT 99%, TC O(N*C), SC O(N): 2D DP
python-3-ft-99-tc-onc-sc-on-2d-dp-by-big-cp1n
Intuition\n\nUsually when the problem is on an array and we have a limited number of items, the solution is\n dynamic programming\n with two variables\n one is
biggestchungus
NORMAL
2024-09-28T23:14:36.131321+00:00
2024-09-28T23:14:36.131343+00:00
1
false
# Intuition\n\nUsually when the problem is on an array and we have a limited number of items, the solution is\n* dynamic programming\n* with two variables\n* one is the current index in the array\n* and the other is the number of items we\'ve used\n\nI found the DP relation to be a bit tricky, but after some wrangling, this is what I came up with.\n\nBased on the above insight we guess that we want `vis[i][k]` meaning\n* **fewest** visible white tiles\n* among tiles `0..i`\n* given that `k` carpets have been laid down\n\nFor `vis[i][k]`:\n* if we lay a carpet down ending at `i` there will be `vis[i-carpetLen][k-1]` tiles\n * the carpet we lay down will cover `i-carpetLen+1..i`\n * so the tiles visible are those with the `k-1` carpets up to tile `i-carpetLen`, the last not under the new carpet\n* **if we don\'t lay a carpet down at `i`, the `kth` carpet is earlier**\n * to avoid an `O(N)` search we make `vis` the *fewest* visible up to i`, the cumulative min\n * so the min visible with `k` carpets up to `i` is\n * place `k` carpets among `0..i-1` and get the best answer: `vis[i-1][k]`\n * and if the current tile is white then it\'s visible: `int(floor[i])`\n\nThis is good enough to avoid TLE and MLE.\n\n# Approach\n\nThe actual approach is more optimal to two respects.\n\n**Reduced memory: prior row trick.** The DP relation for `vis` only dpeends on `k-1`. Therefore we only need two rows:\n* the current row, `vis[:][k]`\n* the prior row: `vis[:][k-1]`\n\nThis saves on memory.\n\nMorever we can use the **swap trick.** Instead of allocating a new `curr` row every time, since we solve for all indices, at the end of each iteration, swap `curr` and `prev`. This is because the next iteration\'s `prev` is the current `curr`, and the current `prev` will not be used. So we can swap and overwrite the otherwise-useless `prev` in the next iteration. Not a big deal, but on platforms with refcounting and GC like Python and Java it can make a difference.\n\n(it can also make a difference even in C++, etc. because `malloc` and `free` are not free - have to coalesce free memory, find a suitable range, etc.)\n\n**Reduced time: end-to-end insight: If we lay `k` carpets end to end that covers the first `k*carpetLen` tiles. Therefore we know that `vis[0:k*carpetLen][k] == 0`.** And thus\n* we can set `vis[k*carpetLen-1][k] = 0` at the top of the loop\n* and iterate over `i in range(k*carpetLen, N)`\n\nThis will result in out of bounds errors if `numCarpets*carpetLen > len(floor)`, but that\'s easy to handle: **if we can cover the whole array with the given carpets then we can return `0` immediately.**\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```python3 []\nclass Solution:\n def minimumWhiteTiles(self, floor: str, numCarpets: int, carpetLen: int) -> int:\n # DP? limited carpets\n\n # top-down DFS\n \n # @cache\n # def minVisible(i: int, k: int) -> int:\n # """min visible in 0..i after k carpets"""\n # # if we use a carpet at i answer is minVisible(i-len, k-1)\n # # if not then if the floor is white here it\'s 1 plus minVisible(i-1)[k]\n\n if numCarpets*carpetLen >= len(floor): return 0\n\n N = len(floor)\n prev = list(accumulate(int(c) for c in floor))\n curr = [0]*N\n for k in range(1, numCarpets+1):\n curr[k*carpetLen-1] = 0 # lay end-to-end\n for i in range(k*carpetLen, N):\n curr[i] = min(curr[i-1] + int(floor[i]), prev[i-carpetLen])\n\n curr, prev = prev, curr\n\n return prev[-1]\n```
0
0
['Python3']
0
minimum-white-tiles-after-covering-with-carpets
Java - Recursive DP
java-recursive-dp-by-shinchan_thakur-noli
Intuition\nhttps://youtu.be/lPQSy4WfMOg\n\n# Complexity\n- Time complexity:\nO(floor.length * numCarpets)\n\n- Space complexity:\nO(floor.length * numCarpets)\n
Shinchan_Thakur
NORMAL
2024-09-12T00:09:28.257064+00:00
2024-09-12T00:09:28.257093+00:00
10
false
# Intuition\nhttps://youtu.be/lPQSy4WfMOg\n\n# Complexity\n- Time complexity:\nO(floor.length * numCarpets)\n\n- Space complexity:\nO(floor.length * numCarpets)\n\n# Code\n```java []\nclass Solution {\n private int[][] dp;\n private int n;\n\n private int minWhiteTiles(int pos, int carpetsLeft, String floor, int carpetLen) {\n if(pos >= floor.length())\n return 0;\n if(dp[pos][carpetsLeft] != -1)\n return dp[pos][carpetsLeft];\n \n int ans = (floor.charAt(pos) == \'1\' ? 1 : 0) + minWhiteTiles(pos + 1, carpetsLeft, floor, carpetLen);\n if(carpetsLeft > 0)\n ans = Math.min(ans, minWhiteTiles(pos + carpetLen, carpetsLeft - 1, floor, carpetLen));\n \n return dp[pos][carpetsLeft] = ans;\n }\n \n public int minimumWhiteTiles(String floor, int numCarpets, int carpetLen) {\n n = floor.length();\n dp = new int[n + 1][numCarpets + 1];\n for (int i = 0; i <= n; i++)\n for(int j=0; j <= numCarpets; j++)\n dp[i][j] = -1;\n \n return minWhiteTiles(0, numCarpets, floor, carpetLen);\n }\n}\n```
0
0
['Dynamic Programming', 'Recursion', 'Java']
0
minimum-white-tiles-after-covering-with-carpets
✅DP || python
dp-python-by-darkenigma-y21v
\n# Code\npython3 []\nclass Solution:\n\n def check(self,s,dp,i,j,n,k,l):\n if(i>=n):return 0\n if(dp[i][j]!=-1):return dp[i][j]\n if(s[
darkenigma
NORMAL
2024-09-06T20:48:16.546386+00:00
2024-09-06T20:48:16.546414+00:00
18
false
\n# Code\n```python3 []\nclass Solution:\n\n def check(self,s,dp,i,j,n,k,l):\n if(i>=n):return 0\n if(dp[i][j]!=-1):return dp[i][j]\n if(s[i]==\'0\'):\n dp[i][j]=self.check(s,dp,i+1,j,n,k,l)\n return dp[i][j]\n dp[i][j]=1+self.check(s,dp,i+1,j,n,k,l)\n if(j<k):dp[i][j]=min(dp[i][j],self.check(s,dp,i+l,j+1,n,k,l))\n return dp[i][j]\n\n\n def minimumWhiteTiles(self, floor: str, numCarpets: int, carpetLen: int) -> int:\n n=len(floor)\n dp=[[-1 for i in range(numCarpets+1)] for j in range(n)]\n return self.check(floor,dp,0,0,n,numCarpets,carpetLen)\n```
0
0
['String', 'Dynamic Programming', 'Prefix Sum', 'Python3']
0
minimum-white-tiles-after-covering-with-carpets
Python Solution for minimumWhiteTiles
python-solution-for-minimumwhitetiles-by-yjr6
Code\npython []\nclass Solution(object):\n\n def minimumWhiteTiles(self, floor, numCarpets, carpetLen):\n\n mat = [[0 for i in range(0,len(floor))] fo
asrith_dasari
NORMAL
2024-08-27T14:26:30.440767+00:00
2024-08-27T14:26:30.440797+00:00
0
false
# Code\n```python []\nclass Solution(object):\n\n def minimumWhiteTiles(self, floor, numCarpets, carpetLen):\n\n mat = [[0 for i in range(0,len(floor))] for j in range(0,numCarpets+1)]\n\n count = 1\n\n temp_count = 0\n\n for i in range(0,len(floor)):\n\n if floor[i]==\'1\':\n\n mat[0][i] = count\n\n temp_count = count\n\n count = count+1\n\n\n else:\n\n mat[0][i] = temp_count\n\n for i in range(1,numCarpets+1):\n\n for j in range(0,carpetLen-1):\n\n mat[i][j] = 0\n\n \n\n\n for i in range(1,numCarpets+1):\n\n for j in range(carpetLen-1,len(floor)):\n\n if j==carpetLen-1:\n mat[i][j]=0\n continue\n\n num_whites = mat[i-1][j]-mat[i-1][j-carpetLen]\n\n reduced_whites = num_whites - carpetLen\n\n if reduced_whites<0:\n\n reduced_whites = 0\n\n mat[i][j] = min(mat[i-1][j]+mat[i][j-1]-mat[i-1][j-1],mat[i-1][j-carpetLen]+reduced_whites)\n\n return mat[-1][-1]\n```
0
0
['Python']
0
minimum-white-tiles-after-covering-with-carpets
Interview Preparation
interview-preparation-by-najnifatima01-oeq6
Let me clarify the question once ...\ntestcase\nconstraints :\n1 <= carpetLen <= floor.length <= 1000\nfloor[i] is either \'0\' or \'1\'.\n1 <= numCarpets <= 10
najnifatima01
NORMAL
2024-08-19T09:40:12.360137+00:00
2024-08-19T09:40:12.360172+00:00
3
false
Let me clarify the question once ...\ntestcase\nconstraints :\n1 <= carpetLen <= floor.length <= 1000\nfloor[i] is either \'0\' or \'1\'.\n1 <= numCarpets <= 1000\nGive me a few minutes to think it through\ncomment - BF, optimal\ncode\n\n\n# Intuition\ndp\n\n# Approach - tabulation\n\n# Complexity\n- Time complexity:\n$$O(n*numCarpets)$$\n\n- Space complexity:\n$$O(n*numsCarpets)$$\n\n# Code\n```\nclass Solution {\npublic:\n int minimumWhiteTiles(string floor, int numCarpets, int carpetLen) {\n int n = floor.size();\n vector<vector<int>> dp(1001, vector<int>(1001, 0));\n for(int i=n-1; i>=0; i--) {\n dp[i][0] = dp[i+1][0] + (floor[i] == \'1\');\n for(int j=1; j<=numCarpets; j++) {\n dp[i][j] = min(dp[i+1][j] + (floor[i] == \'1\'), dp[min(1000, i+carpetLen)][j-1]);\n }\n }\n return dp[0][numCarpets];\n }\n};\n```\n\n# Approach - memoization\n\n# Complexity\n- Time complexity:\n$$O(n*numCarpets)$$\n\n- Space complexity:\n$$O(n*numsCarpets)$$\n\n# Code\n```\nclass Solution {\npublic:\n int recursion(string &floor, int numCar, int carLen, int pos, int used, vector<int> &suffix, vector<vector<int>> &dp) {\n if(pos >= floor.size()) {\n return 0;\n }\n if(used == numCar) {\n return suffix[pos];\n }\n if(dp[pos][used] != -1) {\n return dp[pos][used];\n }\n return dp[pos][used] = min(recursion(floor, numCar, carLen, pos+1, used, suffix, dp)+(floor[pos]==\'1\'), recursion(floor, numCar, carLen, pos+carLen, used+1, suffix, dp));\n }\n int minimumWhiteTiles(string floor, int numCarpets, int carpetLen) {\n int n = floor.size();\n vector<vector<int>> dp(1001, vector<int>(1001, -1));\n vector<int> suffix(n);\n suffix[n-1] = floor[n-1]==\'1\';\n for(int i=n-2; i>=0; i--) {\n suffix[i] = suffix[i+1]+(floor[i]==\'1\');\n }\n return recursion(floor, numCarpets, carpetLen, 0, 0, suffix, dp);\n }\n};\n```\n
0
0
['C++']
0
minimum-white-tiles-after-covering-with-carpets
Easy DP explanation with intuition | Memo | Recursion | Bottom-up | Top Down
easy-dp-explanation-with-intuition-memo-j8rxc
Intuition\n Describe your first thoughts on how to solve this problem. \nIf it was a continous carpets question, this could probably solved by sliding window wh
SheetalB
NORMAL
2024-08-07T02:51:32.312689+00:00
2024-08-07T02:51:32.312727+00:00
26
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nIf it was a continous carpets question, this could probably solved by sliding window which were my first thoughts. Later understood that the carpets can be placed anywhere so this becomes including excluding recursion problem.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- If you want to add a carpet at certain integer then you will cover index+carpetLen values as well with one less carpet. So now we need visible tile count of subProblem (i+1,j-1) i being the floor index and j being the carpet count.\n- If you decide not to include a carpet then it means the current integer if its a 1 is visible + the remaining subProblem with same amount of tiles i.e., i+1,j \n- Min of the above two paths is stored in memo\n- Note for basic reference :for top down dp you have i as emptyString\'\'+floor and j->0 to carpets .for bottom up you have floor+emptyString and j->carpets to 0\n- so at dp[i][j] you will store visible tiles at i with j number of tiles\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(floor.length*numOfCarpets)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(floor.length*numOfCarpets)\n\n# Code\nRecursion & Memoization (TLE, just for reference)\n```\n/**\n * @param {string} floor\n * @param {number} numCarpets\n * @param {number} carpetLen\n * @return {number}\n */\nvar minimumWhiteTiles = function (floor, numCarpets, carpetLen) {\n let dp = new Array(floor.length);\n\n for (let i = 0; i < dp.length; i++) {\n dp[i] = new Array(numCarpets.length);\n }\n\n let suffixCount = new Array(floor.length).fill(0);\n suffixCount[floor.length - 1] = floor[floor.length - 1] == \'1\' ? 1 : 0;\n\n for (let i = floor.length - 2; i >= 0; i--) {\n suffixCount[i] = suffixCount[i + 1] + (floor[i] == \'1\');\n }\n\n let helper = function (index, carpsLeft) {\n if (index >= floor.length) {\n return 0;\n }\n if (dp[index] && dp[index][carpsLeft]) return dp[index][carpsLeft];\n if (carpsLeft == 0) {\n return suffixCount[index];\n }\n\n let addCarpet = helper(index + carpetLen, carpsLeft - 1);\n let noCarpet = (floor[index] == 1) + helper(index + 1, carpsLeft);\n\n dp[index][carpsLeft] = Math.min(addCarpet, noCarpet);\n\n return dp[index][carpsLeft];\n }\n\n return helper(0, numCarpets);\n }\n\n};\n\n```\nTop Down approach\n```\nvar minimumWhiteTiles = function (floor, numCarpets, carpetLen) {\n let dp = new Array(floor.length + 1);\n for (let i = 0; i < dp.length; i++) {\n dp[i] = new Array(numCarpets + 1)\n }\n\n for (let i = 0; i < dp.length; i++) {\n for (let j = 0; j < dp[0].length; j++) {\n if ((i == 0 && j == 0) || i == 0) dp[i][j] = 0;\n else if (j == 0) {\n dp[i][j] = floor[i - 1] == \'1\' ? 1 + dp[i - 1][j] : dp[i - 1][j];\n }\n else {\n let addCarpet = 0;\n if (i >= carpetLen) addCarpet = dp[i - carpetLen][j - 1];\n let noCarpet = floor[i - 1] == \'1\' ? 1 + dp[i - 1][j] : dp[i - 1][j];\n dp[i][j] = Math.min(addCarpet, noCarpet);\n }\n }\n }\n\n return dp[floor.length][numCarpets]\n }\n```\nBottom-Up approach\n```\nvar minimumWhiteTiles = function (floor, numCarpets, carpetLen) {\n let dp = new Array(floor.length + 1);\n for (let i = 0; i < dp.length; i++) {\n dp[i] = new Array(numCarpets + 1).fill(0)\n }\n\n let m = dp.length;\n let n = dp[0].length;\n\n for (let i = m - 1; i >= 0; i--) {\n for (let j = n - 1; j >= 0; j--) {\n if ((i == m - 1 && j == n - 1) || i == m - 1) dp[i][j] = 0;\n else if (j == n - 1) {\n dp[i][j] = floor[i] == \'1\' ? 1 + dp[i + 1][j] : dp[i + 1][j];\n }\n else {\n let addCarpet = 0;\n //the carpet will cover the length so we just need to consider visible values after that index with less carpets\n if (i + carpetLen < m) addCarpet = dp[i + carpetLen][j + 1];\n //if we are not considering to add carpet then just check next index value with same carpets\n let noCarpet = floor[i] == \'1\' ? 1 + dp[i + 1][j] : dp[i + 1][j];\n dp[i][j] = Math.min(addCarpet, noCarpet);\n }\n }\n }\n\n return dp[0][0];\n }\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n```
0
0
['String', 'Dynamic Programming', 'Prefix Sum', 'JavaScript']
0
minimum-white-tiles-after-covering-with-carpets
Python (Simple DP)
python-simple-dp-by-rnotappl-qsiq
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
2024-07-25T17:24:02.176897+00:00
2024-07-25T17:24:02.176929+00:00
2
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 minimumWhiteTiles(self, floor, numCarpets, carpetLen):\n n, k = len(floor), numCarpets\n\n @lru_cache(None)\n def function(i,k):\n if i >= n:\n return 0\n\n if k == 0:\n return int(floor[i]) + function(i+1,k)\n else:\n place = function(i+carpetLen,k-1)\n dont = int(floor[i]) + function(i+1,k)\n return min(place,dont)\n\n return function(0,k)\n```
0
0
['Python3']
0
minimum-white-tiles-after-covering-with-carpets
DP || C++
dp-c-by-scraper_nerd-zyax
\n\n# Code\n\nclass Solution {\npublic:\n int dp[1001][1001];\n int nerd(int index,int used,int total,int len,vector<int>&v){\n if(index>=v.size()
Scraper_Nerd
NORMAL
2024-06-16T05:56:40.902412+00:00
2024-06-16T05:56:40.902437+00:00
12
false
\n\n# Code\n```\nclass Solution {\npublic:\n int dp[1001][1001];\n int nerd(int index,int used,int total,int len,vector<int>&v){\n if(index>=v.size() or used==total) return 0;\n if(dp[index][used]!=-1) return dp[index][used];\n int notusing=nerd(index+1,used,total,len,v);\n int usingt=nerd(index+len,used+1,total,len,v);\n int wscovered;\n if(index>0) wscovered=v[index-1];\n else wscovered=0;\n if(index+len>=v.size()) wscovered=v[v.size()-1]-wscovered;\n else wscovered=v[index+len-1]-wscovered;\n return dp[index][used]=max(wscovered+usingt,notusing);\n }\n int minimumWhiteTiles(string s, int n, int l) {\n if(s.size()<=n*l) return 0;\n memset(dp,-1,sizeof(dp));\n vector<int>v(s.size());\n for(int i=0;i<s.size();i++) v[i]=s[i]-\'0\';\n for(int i=1;i<s.size();i++) v[i]+=v[i-1];\n return v[v.size()-1]-nerd(0,0,n,l,v);\n }\n};\n```
0
0
['Dynamic Programming', 'C++']
0
minimum-white-tiles-after-covering-with-carpets
Beats 100!! efficient js solution using dp
beats-100-efficient-js-solution-using-dp-c1p6
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
Jdev740
NORMAL
2024-06-07T04:52:53.202448+00:00
2024-06-07T04:52:53.202482+00:00
12
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nlet dp=Array.from({length:1001},()=>Array(1001).fill(0));\n/**\n * @param {string} floor\n * @param {number} numCarpets\n * @param {number} carpetLen\n * @return {number}\n */\n\nvar minimumWhiteTiles = function(floor, numCarpets, carpetLen) {\n\n // let pfix=new Array(floor.length).fill(0);\n // let cnt=0;\n // pfix[0]=floor[0]==\'1\'?1:0;\n // cnt+=floor[0]==\'1\'?1:0;\n // for(let i=1;i<floor.length;i++){\n\n // pfix[i]=pfix[i-1]+(floor[i]==\'1\'?1:0);\n // cnt+= floor[i]==\'1\'?1:0;\n\n // // if(i-carpetLen>=0) pfix[i]-=pfix[i-carpetLen];\n \n // }\n let all=0;sum=0;\n for(let i=0;i<floor.length;++i){\n all+=floor.charCodeAt(i) & 1;\n sum+=floor.charCodeAt(i) & 1;\n if(i>=carpetLen) sum-=floor.charCodeAt(i-carpetLen) & 1;\n for(let j=0;j<=numCarpets;++j){\n if(!j){\n dp[i][j]=0; continue;\n }\n if(i<carpetLen){\n // dp[i][j]=pfix[i]; continue;\n dp[i][j]=sum; continue;\n\n }\n // dp[i][j]=Math.max(dp[i-1][j],dp[i-carpetLen][j-1]+sum);\n dp[i][j] = Math.max(dp[i - 1][j], dp[i - carpetLen][j - 1] + (sum));\n\n }\n\n }\n // return cnt - dp[floor.length -1][numCarpets];\n return all - dp[floor.length - 1][numCarpets];\n\n// }\n // console.log(dp)\n// function solve(idx=0,num=0,prev=0,ones=0){\n// if(num==numCarpets) {mx=Math.max(mx,ones); return mx;}\n// if (idx>=floor.length){mx=Math.max(mx,(ones+(pfix[floor.length-1]-pfix[prev]))); return mx;}\n// solve(idx+1,num,idx,ones);\n// // include \n// let newOnes=idx-carpetLen>=0?(ones+pfix[idx]-pfix[idx-carpetLen]):pfix[idx];\n// solve(idx+carpetLen,num+1,idx,newOnes);\n// }\n// solve();\n// return cnt-mx;\n// };\n// // dp[i][num]=>at the ith index denotes the most no.of ones covered at the ith index when it\'s covered with num number of carpets\n// let n = floor.length;\n// // let dp = Array.from({ length: 1001 }, () => new Uint32Array(1001));\n// let dp=Array.from({length:floor.length},()=>Array(numCarpets+1).fill(0));\n\n// let all = 0;\n// let sum = 0;\n// for (let i = 0; i < n; i++) {\n// all += floor.charCodeAt(i) & 1;\n// sum += floor.charCodeAt(i) & 1;\n// if (i >= carpetLen) sum -= floor.charCodeAt(i - carpetLen) & 1;\n\n// for (let j = 0; j <= numCarpets; ++j) {\n// if (!j) {\n// dp[i][j] = 0;\n// continue;\n// }\n// if (i < carpetLen) {\n// dp[i][j] =(pfix[i]);\n// continue;\n// }\n // dp[i][j] = Math.max(dp[i - 1][j], dp[i - carpetLen][j - 1] + (pfix[i]-pfix[i-carpetLen]));\n// }\n// }\n\n// return cnt - dp[floor.length - 1][numCarpets];\n}\n```
0
0
['JavaScript']
0
minimum-white-tiles-after-covering-with-carpets
easy c++ solution using prefix sum and dynamic programming
easy-c-solution-using-prefix-sum-and-dyn-7wau
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
Amanr_nitw
NORMAL
2024-05-24T06:38:32.341577+00:00
2024-05-24T06:38:32.341612+00:00
11
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int f(int i,string &floor,int numCarpets,int carpetLen,vector<vector<int>> &dp,vector<int> &suff_sum)\n {\n if(i>=floor.size())return 0;\n if(numCarpets==0)\n {\n // int count=0;\n // for(int j=i;j<floor.size();j++){if(floor[j]==\'1\')count++;}\n return suff_sum[i];\n }\n if(dp[i][numCarpets]!=-1)return dp[i][numCarpets];\n int take=f(i+carpetLen,floor,numCarpets-1,carpetLen,dp,suff_sum);\n int not_take=0;\n if(floor[i]==\'1\')not_take=1+f(i+1,floor,numCarpets,carpetLen,dp,suff_sum);\n else not_take=f(i+1,floor,numCarpets,carpetLen,dp,suff_sum);\n return dp[i][numCarpets]=min(take,not_take);\n }\n int minimumWhiteTiles(string floor, int numCarpets, int carpetLen) {\n int n=floor.size();\n vector<vector<int>> dp(n,vector<int>(numCarpets+1,-1));\n vector<int> suff_sum(n,0);\n suff_sum[n-1]+=(floor[n-1]==\'1\');\n for(int i=n-2;i>=0;i--)\n {\n if(floor[i]==\'1\')suff_sum[i]++;\n suff_sum[i]+=suff_sum[i+1];\n }\n return f(0,floor,numCarpets,carpetLen,dp,suff_sum);\n }\n};\n```
0
0
['C++']
0
minimum-white-tiles-after-covering-with-carpets
Dp with prefix sum
dp-with-prefix-sum-by-maxorgus-n5nm
i, where we are\nj, carpets we have left\n\n# Code\n\nclass Solution:\n def minimumWhiteTiles(self, floor: str, numCarpets: int, carpetLen: int) -> int:\n
MaxOrgus
NORMAL
2024-05-24T02:49:41.197074+00:00
2024-05-24T02:49:41.197103+00:00
9
false
i, where we are\nj, carpets we have left\n\n# Code\n```\nclass Solution:\n def minimumWhiteTiles(self, floor: str, numCarpets: int, carpetLen: int) -> int:\n n = len(floor)\n psum = [0]\n for a in floor:\n if a == \'1\':\n psum.append(psum[-1]+1)\n else:\n psum.append(psum[-1])\n @cache\n def dp(i,j):\n if i >= n:\n return 0\n if j == 0:\n return psum[-1] - psum[i]\n res = int(floor[i]==\'1\')+dp(i+1,j)\n res = min(res,dp(i+carpetLen,j-1))\n return res\n return dp(0,numCarpets)\n\n \n```
0
0
['Dynamic Programming', 'Prefix Sum', 'Python3']
0
minimum-white-tiles-after-covering-with-carpets
Shortest DP
shortest-dp-by-yoongyeom-ieaf
Code\n\nclass Solution:\n def minimumWhiteTiles(self, floor: str, numCarpets: int, carpetLen: int) -> int:\n @cache\n def dp(i, car):\n
YoonGyeom
NORMAL
2024-05-18T08:08:31.411272+00:00
2024-05-18T08:08:31.411319+00:00
5
false
# Code\n```\nclass Solution:\n def minimumWhiteTiles(self, floor: str, numCarpets: int, carpetLen: int) -> int:\n @cache\n def dp(i, car):\n if i >= len(floor): return 0\n if car == 0: return dp(i+1, car)+int(floor[i]==\'1\')\n return min(dp(i+1, car)+int(floor[i]==\'1\'), dp(i+carpetLen, car-1))\n return dp(0, numCarpets)\n```
0
0
['Python3']
0
minimum-white-tiles-after-covering-with-carpets
C# solution beats 100%??
c-solution-beats-100-by-obose-q3cp
Intuition\n Describe your first thoughts on how to solve this problem. \nMy first thought on how to solve this problem is to use dynamic programming (DP) to fin
Obose
NORMAL
2024-05-14T04:22:33.343551+00:00
2024-05-14T04:22:33.343595+00:00
3
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nMy first thought on how to solve this problem is to use dynamic programming (DP) to find the minimum number of white tiles that need to be painted black. The problem seems to be a classic example of a DP problem, where we need to make decisions based on previous states.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nMy approach is to create a 2D DP array, where the state dp[i, j] represents the minimum number of white tiles that need to be painted black for the first i tiles and j carpets. We iterate through the floor and carpets, and for each state, we consider two options: either paint the current tile black or use a carpet to cover it. We choose the option that results in the minimum number of white tiles painted black.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(n\\*numCarpets)$$, where n is the length of the floor and numCarpets is the number of carpets. This is because we iterate through the floor and carpets in a nested manner.\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(n\\*numCarpets)$$, as we need to store the DP array of size n x numCarpets.\n\n# Code\n```\npublic class Solution {\n public int MinimumWhiteTiles(string floor, int numCarpets, int carpetLen) {\n int n = floor.Length;\n int[,] dp = new int[n + 1, numCarpets + 1];\n\n // Initialize the dp array\n for (int i = 0; i <= n; i++) {\n for (int j = 0; j <= numCarpets; j++) {\n dp[i, j] = int.MaxValue / 2; \n }\n }\n dp[0, 0] = 0;\n\n // Fill the dp array\n for (int i = 1; i <= n; i++) {\n for (int j = 0; j <= numCarpets; j++) {\n if (j > 0 && i >= carpetLen) {\n dp[i, j] = Math.Min(dp[i, j], dp[i - carpetLen, j - 1]);\n }\n if (j > 0 && i < carpetLen) {\n dp[i, j] = Math.Min(dp[i, j], dp[0, j - 1]);\n }\n dp[i, j] = Math.Min(dp[i, j], dp[i - 1, j] + (floor[i - 1] == \'1\' ? 1 : 0));\n }\n }\n\n int minWhiteTiles = int.MaxValue;\n for (int j = 0; j <= numCarpets; j++) {\n minWhiteTiles = Math.Min(minWhiteTiles, dp[n, j]);\n }\n\n return minWhiteTiles;\n }\n}\n\n```
0
0
['C#']
0
minimum-white-tiles-after-covering-with-carpets
rust 17ms solution with explaination
rust-17ms-solution-with-explaination-by-yvpwu
\n\n# Approach\nTo get the min exposed is to get the max covered;\n\nLet dp[n][i] be the max_covered with n carpets, let m be the length of carpets.\n\ndp[n][i]
sovlynn
NORMAL
2024-04-10T18:41:46.512553+00:00
2024-04-10T18:41:46.512573+00:00
0
false
![image.png](https://assets.leetcode.com/users/images/612f5345-e554-4d44-907d-20222a260dd6_1712773598.1896548.png)\n\n# Approach\nTo get the min exposed is to get the max covered;\n\nLet dp[n][i] be the max_covered with n carpets, let m be the length of carpets.\n\ndp[n][i]=max(\ndp[n-1][i-M]+cover[i-M+1] \\\\\\*I choose to cover from i-M+1 to i\\*\\\\,\nmax(dp[n][0 to i-1]) \\\\\\*max so far\\*\\\\)\n\n# Note\nDon\'t consider when the carpets overlap each other, that will not increase the white covered.\n\ndp[n][i] is all whites from 0 to i when i<M. I though when i<M\\*num_carpets is also correct, but this does not decrease the time needed.\n\n# Complexity\n- Time complexity:\n$$O(floor.len()*num\\_carpets)$$\n\n- Space complexity:\n$$O(floor.len())$$\n\n# Code\n```\nuse std::cmp::{min, max};\nuse std::mem::swap;\nimpl Solution {\n pub fn minimum_white_tiles(floor: String, num_carpets: i32, carpet_len: i32) -> i32 {\n if (num_carpets*carpet_len) as usize >= floor.len(){return 0;}\n let carpet_len=carpet_len as usize;\n let mut whites=0i32;\n let floor=floor.as_bytes().iter().map(|&x|if x==b\'1\'{whites+=1;true}else{false}).collect::<Vec<bool>>();\n if carpet_len==1{\n return max(whites-num_carpets, 0);\n }\n if whites==0{return 0;}\n \n let mut cover=vec![0i32; floor.len()-carpet_len+1];\n cover[0]=(0..carpet_len).filter(|x|floor[*x]).count() as i32;\n for i in 1..cover.len(){\n cover[i]=cover[i-1];\n if floor[i+carpet_len-1]{cover[i]+=1;}\n if floor[i-1]{cover[i]-=1;}\n }\n\n let mut sum=vec![0; carpet_len];\n sum[0]=if floor[0]{1}else{0};\n for i in 1..carpet_len{\n sum[i]=sum[i-1];\n if floor[i]{sum[i]+=1;}\n }\n\n let mut res=0;\n let mut prev=vec![0i32; floor.len()];\n let mut cur=vec![0i32; floor.len()];\n for n in 1..=num_carpets{\n let mut max_so_far=0;\n for i in 0..floor.len(){\n let c=if i<carpet_len{\n sum[i]\n }else{\n prev[i-carpet_len]+cover[i-carpet_len+1]\n };\n max_so_far=max(max_so_far, c);\n cur[i]=max_so_far;\n }\n swap(&mut cur,&mut prev);\n }\n whites-prev[floor.len()-1]\n }\n}\n```
0
0
['Dynamic Programming', 'Rust']
0
minimum-white-tiles-after-covering-with-carpets
C++ sliding window + dp memo
c-sliding-window-dp-memo-by-user5976fh-v596
\nclass Solution {\npublic:\n // dp memo based on amount of carpets left and current index\n // first perform a sliding window to determine\n // how ma
user5976fh
NORMAL
2024-03-25T21:28:06.887659+00:00
2024-03-25T21:28:06.887690+00:00
1
false
```\nclass Solution {\npublic:\n // dp memo based on amount of carpets left and current index\n // first perform a sliding window to determine\n // how many tiles we cover\n vector<int> tilesCovered;\n int l = 1;\n string s = "";\n vector<vector<int>> dp;\n int minimumWhiteTiles(string str, int nc, int len) {\n tilesCovered = vector<int>(str.size());\n l = len;\n s = str;\n dp = vector<vector<int>>(s.size(), vector<int>(nc + 1, -1));\n int count = 0;\n for (int i = 0; i < len && i < s.size(); ++i)\n count += s[i] == \'1\';\n tilesCovered[0] = count;\n for (int i = 1; i < s.size(); ++i){\n count -= s[i - 1] == \'1\';\n if (i + len - 1 < s.size())\n count += s[i + len - 1] == \'1\';\n tilesCovered[i] = count;\n }\n int total = 0;\n for (auto& c : s) total += c == \'1\';\n return total - dfs(0, nc);\n }\n \n int dfs(int i, int nc){\n if (i >= s.size() || nc == 0) return 0;\n if (dp[i][nc] != -1) return dp[i][nc];\n dp[i][nc] = max(dfs(i + 1, nc), tilesCovered[i] + dfs(i + l, nc - 1));\n return dp[i][nc];\n }\n};\n```
0
0
[]
0
minimum-white-tiles-after-covering-with-carpets
Minumum White Tiles
minumum-white-tiles-by-user9233o-01nh
\n# Code\n\npublic class Solution {\n public int MinimumWhiteTiles(string floor, int numCarpets, int carpetLen) {\n int n = floor.Length;\n
user9233O
NORMAL
2024-03-12T10:27:48.477753+00:00
2024-03-12T10:27:48.477791+00:00
3
false
\n# Code\n```\npublic class Solution {\n public int MinimumWhiteTiles(string floor, int numCarpets, int carpetLen) {\n int n = floor.Length;\n int[,] dp = new int[n + 1, numCarpets + 1];\n\n for (int i = 1; i <= n; ++i)\n {\n for (int k = 0; k <= numCarpets; ++k)\n {\n int jump = dp[i - 1, k] + (floor[i - 1] - \'0\');\n int cover = k > 0 ? dp[Math.Max(0, i - carpetLen), k - 1] : 1000;\n dp[i, k] = Math.Min(cover, jump);\n }\n }\n return dp[n, numCarpets];\n }\n}\n```
0
0
['C#']
0
minimum-white-tiles-after-covering-with-carpets
Efficient JS solution - DP (Beat 100% time)
efficient-js-solution-dp-beat-100-time-b-u9om
\n\nPro tip: Love lil Xi\xE8 \uD83D\uDC9C \u7231\u5C0F\u8C22 \uD83D\uDC9C\n\n# Complexity\n- let n = floor.length, c = numCarpets\n- Time complexity: O(nc)\n- S
CuteTN
NORMAL
2024-01-18T17:29:57.916997+00:00
2024-01-18T17:29:57.917026+00:00
12
false
![image.png](https://assets.leetcode.com/users/images/197c73b5-11df-4d7f-a64a-0922789cc1b7_1705598883.7087042.png)\n\nPro tip: Love lil Xi\xE8 \uD83D\uDC9C \u7231\u5C0F\u8C22 \uD83D\uDC9C\n\n# Complexity\n- let `n = floor.length`, `c = numCarpets`\n- Time complexity: $$O(nc)$$\n- Space complexity: $$O(nc)$$\n\n# Code\n```js\nlet dp = Array.from({ length: 1001 }, () => new Uint32Array(1001));\n\n/**\n * @param {string} floor\n * @param {number} numCarpets\n * @param {number} carpetLen\n * @return {number}\n */\nvar minimumWhiteTiles = function (floor, numCarpets, carpetLen) {\n let n = floor.length;\n let all = 0;\n let sum = 0;\n for (let i = 0; i < n; ++i) {\n all += floor.charCodeAt(i) & 1;\n sum += floor.charCodeAt(i) & 1;\n if (i >= carpetLen) sum -= floor.charCodeAt(i - carpetLen) & 1;\n\n for (let j = 0; j <= numCarpets; ++j) {\n if (!j) {\n dp[i][j] = 0;\n continue;\n }\n if (i < carpetLen) {\n dp[i][j] = sum;\n continue;\n }\n dp[i][j] = Math.max(dp[i - 1][j], dp[i - carpetLen][j - 1] + sum);\n }\n }\n\n return all - dp[n - 1][numCarpets];\n};\n```
0
0
['Dynamic Programming', 'JavaScript']
0
minimum-white-tiles-after-covering-with-carpets
DP
dp-by-hidanie-hzdl
Intuition\n Describe your first thoughts on how to solve this problem. \nCover the tiles carpet by carpet from end to beginning. for each carpet, choose the the
hidanie
NORMAL
2023-12-19T19:26:27.198180+00:00
2023-12-19T19:26:27.198208+00:00
12
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nCover the tiles carpet by carpet from end to beginning. for each carpet, choose the the place that the sum of the tiles he and his predecessors cover the most.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:O(N*K)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(N*K)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int minimumWhiteTiles(String floor, int numCarpets, int carpetLen) {\n char []arr=floor.toCharArray();\n int[][] mat=new int[numCarpets][arr.length];\n int max=0;\n int[]sums=new int[arr.length];\n for(int i=0;i<numCarpets;i++)\n {\n int sum=0;\n for(int j=arr.length-1;j>-1;j--)\n {\n if(arr[j]==\'1\')\n sum++;\n if(j+carpetLen<arr.length){\n if(arr[j+carpetLen]==\'1\')\n sum--; \n mat[i][j]=sum+sums[j+carpetLen];\n }\n else\n mat[i][j]=sum;\n }\n sums[arr.length-1]=mat[i][arr.length-1];\n for(int j=arr.length-2;j>-1;j--)\n {\n sums[j]=Math.max(mat[i][j],sums[j+1]);\n }\n \n }\n int sum=0;\n for(char ch:arr)\n if(ch==\'1\')\n sum++;\n return sum-sums[0]; \n }\n}\n```
0
0
['Java']
0
minimum-white-tiles-after-covering-with-carpets
Simple Explanation and Solution (Memoization) [Python]
simple-explanation-and-solution-memoizat-say4
Intuition\nBacktracking memoization solution. At every step we either place a carpet or don\'t - we do whatever minimizes the number of exposed white tiles. For
Atjowt
NORMAL
2023-12-18T04:56:38.926026+00:00
2023-12-18T04:56:38.926054+00:00
22
false
# Intuition\nBacktracking memoization solution. At every step we either place a carpet or don\'t - we do whatever minimizes the number of exposed white tiles. For every tile we make a binary choice, which means complexity $O(2^n)$, but with memoization we reduce that to $O(n^2)$.\n\n# Complexity\n- Time complexity: $$\\mathcal{O}(n^2)$$\n- Space complexity: $$\\mathcal{O}(n \\cdot k)$$\n\nWhere $n = nums.length$ and $k = numCarpets$.\n\n# Code\n```\nclass Solution:\n\n def minimumWhiteTiles(self, floor: str, carpets: int, length: int) -> int:\n \n floor = [int(tile) for tile in floor]\n \n @cache # O(floor.length * numCarpets) memory\n def backtrack(i: int, carpets: int) -> int:\n\n # there is no more floor to carpet\n if i >= len(floor):\n return 0\n\n # we have no more carpets to place\n if carpets == 0:\n # this tile and all remaining tiles could be visible\n return floor[i] + backtrack(i + 1, carpets)\n else: \n # we have some carpets to place\n # we can either:\n # 1. place a carpet to hide the tiles under it (ignore them, skip one carpet-length ahead), or\n # 2. keep the carpet, saving one for later but exposing the current tile (which could be white)\n # simply do both and pick whichever one is better\n place = backtrack(i + length, carpets - 1)\n dont = floor[i] + backtrack(i + 1, carpets)\n return min(place, dont)\n \n return backtrack(0, carpets)\n```
0
0
['Dynamic Programming', 'Backtracking', 'Recursion', 'Memoization', 'Python', 'Python3']
0
minimum-white-tiles-after-covering-with-carpets
96% Faster Solution
96-faster-solution-by-priyanshuniranjan-zuad
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
PriyanshuNiranjan
NORMAL
2023-12-15T18:39:06.808666+00:00
2023-12-15T18:39:06.808695+00:00
9
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n/*\nclass Solution {\n\n public int minimumWhiteTiles(String floor, int numCarpets, int carpetLen) {\n int n = floor.length(), dp[][] = new int[n + 1][numCarpets + 1];\n\n for (int i = 1; i <= n; i++) {\n for (int k = 0; k <= numCarpets; k++) {\n int jump = dp[i - 1][k] + floor.charAt(i - 1) - \'0\';\n int cover = k > 0 ? dp[Math.max(i - carpetLen, 0)][k - 1] : 1000;\n dp[i][k] = Math.min(cover, jump);\n }\n }\n return dp[n][numCarpets];\n }\n}\n*/\nclass Solution {\n public int minimumWhiteTiles(String floor, int numCarpets, int carpetLen) {\n int n = floor.length();\n if (numCarpets * carpetLen >= n) return 0;\n int[] dp = new int[n + 1];\n for (int i = n - 1; i >= 0; i--) {\n dp[i] = floor.charAt(i) == \'1\' ? dp[i + 1] + 1 : dp[i + 1];\n }\n int[] temp = new int[n + 1];\n for (int i = 1; i <= numCarpets; i++) {\n temp[n - i * carpetLen] = 0;\n for (int j = n - i * carpetLen - 1; j >= (numCarpets - i) * carpetLen; j--)\n temp[j] = Math.min(dp[j + carpetLen], temp[j + 1] + (floor.charAt(j) == \'1\' ? 1 : 0));\n int[] temp2 = temp;\n temp = dp;\n dp = temp2;\n }\n return dp[0];\n }\n}\n```
0
0
['Java']
0
minimum-white-tiles-after-covering-with-carpets
Easy intuitive Solution Using Recursion and Memoization||Tabulation
easy-intuitive-solution-using-recursion-1nmmf
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
code_plus_plus
NORMAL
2023-11-13T20:16:27.703183+00:00
2023-11-13T20:16:27.703201+00:00
20
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int solve(string s,int numCar,int carLen,int i,vector<vector<int>>&dp)\n {\n \n if(i>=s.size())\n return(0);\n if(dp[i][numCar]!=-1)\n return(dp[i][numCar]);\n int take=1000,notake=1000,notake1=1000;\n if(s[i]==\'1\')\n {\n if(numCar>0)\n take=solve(s,numCar-1,carLen,i+carLen,dp);\n notake=solve(s,numCar,carLen,i+1,dp)+1;\n }\n else\n notake1=solve(s,numCar,carLen,i+1,dp);\n return(dp[i][numCar]=min(take,min(notake,notake1)));\n }\n int solveTab(string s,int numCar,int carLen,vector<vector<int>>dp)\n {\n for(int i=s.size()-1;i>=0;i--)\n {\n for(int j=0;j<=numCar;j++)\n {\n int take=1000,notake=1000,notake1=1000;\n if(s[i]==\'1\')\n {\n if(j>0)\n {\n if((i+carLen)>=s.size())\n take=0;\n else\n take=dp[i+carLen][j-1];\n }\n notake=dp[i+1][j]+1;\n }\n else\n notake1=dp[i+1][j];\n dp[i][j]=min(take,min(notake,notake1));\n }\n }\n return(dp[0][numCar]);\n }\n int minimumWhiteTiles(string floor, int numCarpets, int carpetLen) {\n vector<vector<int>>dp(floor.size()+1,vector<int>(numCarpets+1,0));\n return(solveTab(floor,numCarpets,carpetLen,dp));\n }\n};\n```
0
0
['C++']
0
minimum-white-tiles-after-covering-with-carpets
Thoroughly Explained C++ code
thoroughly-explained-c-code-by-monkey_d_-q27g
Intuition\nDon\'t think about the overlapping of the carpets because it will be taken care at the end because it can be folded from the end side as well.\n\n# A
Monkey_D_Luffy_2002
NORMAL
2023-11-08T09:52:57.473594+00:00
2023-11-08T09:53:34.105266+00:00
16
false
# Intuition\nDon\'t think about the overlapping of the carpets because it will be taken care at the end because it can be folded from the end side as well.\n\n# Approach\nWe will use a array to store the prefix sum and the find the maximum amount of white tiles that can be removed and then subtract the tiles from total number of white tiles that will give us the minimum number of white tiles.\nTo find the number of white tiles that can be removed from placing the carpet starting at index i will be -\nprefix[i + carpetLen - 1] - prefix[n - 1];\nThe above formula gives us the number of white tiles that are placed between index "i" and "i + carpetLen - 1" and that is covered by the carpet.\nWhen the "i + carpetLen - 1" is going out of bound we will use prefix[n - 1] instead of prefix[i + carpetLen - 1] because prefix[n - 1] is the maximum tiles.\n\n# Complexity\n- Time complexity:\n O(N*C) where \n N = Length of floor\n C = Number of Carpets\n\n- Space complexity:\n O(N) + O(N*C) + O(N)\n O(N) for prefix array\n O(N*C) for dp array\n O(N) for stack space\n\n It can be improved by using bottom up DP where we will not use stack space and the DP space can also improve by using two 1D array of size numCarpet instead of using a 2D dp array.\n\n# Code\n```\n\nint solve(vector<int> &prefix, int num, int l, int index, int n, vector<vector<int>> &dp){\n if(index >= n){\n return 0;\n }\n if(dp[index][num] != -1)return dp[index][num];\n int inc = 0;\n if(num > 0){\n if(index + l - 1 >= n){\n inc = (prefix[n - 1] - prefix[index - 1]) + solve(prefix, num - 1, l, index + l, n, dp);\n }\n else{\n inc = (prefix[index + l - 1] - prefix[index - 1]) + solve(prefix, num - 1, l, index + l, n, dp);\n }\n }\n int exc = solve(prefix, num, l, index + 1, n, dp);\n return dp[index][num] = max(inc, exc);\n}\n\nclass Solution {\npublic:\n int minimumWhiteTiles(string floor, int numCarpets, int carpetLen) {\n int n = floor.size();\n vector<int> prefix(n + 1, 1);\n int white = 0, j = 1;\n for(auto i : floor){\n int x = i - \'0\', y = prefix[j - 1];\n if(x == 1)white++;\n prefix[j++] = (x + y);\n }\n vector<vector<int>> dp(n + 1, vector<int>(numCarpets + 1, -1));\n int removedWhite = solve(prefix, numCarpets, carpetLen, 1, n + 1, dp);\n return white - removedWhite;\n }\n};\n```
0
0
['Dynamic Programming', 'Memoization', 'Prefix Sum', 'C++']
0
minimum-white-tiles-after-covering-with-carpets
python3 dp beats 93%
python3-dp-beats-93-by-0icy-u3hz
\n\n# Code\n\nclass Solution:\n def minimumWhiteTiles(self, floor: str, numCarpets: int, carpetLen: int) -> int:\n floor = \'0\'+floor\n dp = [
0icy
NORMAL
2023-11-06T17:03:08.346356+00:00
2023-11-06T17:03:25.341904+00:00
10
false
\n\n# Code\n```\nclass Solution:\n def minimumWhiteTiles(self, floor: str, numCarpets: int, carpetLen: int) -> int:\n floor = \'0\'+floor\n dp = [[inf for x in range(len(floor))] for y in range(numCarpets+1)]\n c = 0\n for i in range(len(floor)):\n if floor[i]==\'1\':\n c+=1\n dp[0][i] = c\n\n \n for r in range(1,numCarpets+1):\n for c in range(len(floor)):\n if c==0:\n dp[r][c]=0\n continue\n if floor[c]==\'0\':\n dp[r][c] = dp[r][c-1]\n else:\n dp[r][c] = min(dp[r][c-1]+1,dp[r-1][max(0,c-carpetLen)])\n\n return dp[-1][-1]\n\n \n```
0
0
['Python3']
0
minimum-white-tiles-after-covering-with-carpets
Dp Super Detailed Explanation and Process
dp-super-detailed-explanation-and-proces-kqvn
\n## Initial thoughts \n\nIt looks like initially, me an others considered a greedy approach to optimize the placement of carpets to cover the most white tiles
srd4
NORMAL
2023-11-01T14:11:33.709504+00:00
2023-11-01T14:11:33.709538+00:00
12
false
\n## Initial thoughts \n\nIt looks like initially, me an others considered a greedy approach to optimize the placement of carpets to cover the most white tiles at each step. With counterexamples It became clear though that the approach didn\'t yield the optimal solution. From the solutions section it seemed was rather necessary to find the optimal solution at each step and sum those together to get the minimum possible white tiles visible at the end.\n\nMy first approach the first time I encountered this problem 6 months ago was likely manipulating arrays somehow. Trying the greedy this second time and finding a couple counter examples, I discarded it quickly.\n\nIt was kind of interesting to see this kind of problem the first time around. Labelled as \'hard\' the difficulty was a bit intimidating.\n\nIf I recall correctly, it was probably the first time I saw the use of diagrams to explain the problem statement.\n\n## Past experiences\n\nI\'ve come across similar problems or topics related to dynamic programming before, but this is likely the first of its kind I tackled. The concept often feels confusing, especially around the pre-computation of values to be reused later. Understanding solutions is complex on its on, but devising my own can and still to this day does feel hellish.\n\nI\'ve seen similar problems with tags strings and prefix sum (another term for cumulative sum). The problem made me recall the latter concept, and [the wikipedia](https://en.wikipedia.org/wiki/Prefix_sum) article I first clarified it with.\n\nThe dynamic programming approach required here keeps a sum of the remaining visible white tiles in a two-dimensional array at each position, which is a bit reminiscent of problems with prefix sum I\'ve encountered before.\n\n## ChatGPT interaction\n\nWith ChatGPT I usually follow a couple prompting patterns for seeking tag explanations and understanding tricky solutions on LeetCode, often times from specific recurrent LeetCode users like Lee215 whose English may be tricky to read but solutions are spot on. I find ChatGPT useful in elaborating on those solutions, explaining the logic and code involved in a structured manner, to enhance understanding\n\n![Dp solution chatgpt convo prompt](https://assets.leetcode.com/users/images/e76cfc09-67ed-4dac-b761-45251328f800_1698847638.5198662.png)\n\nI prefer to ask ChatGPT to clarify existing human made solutions rather than asking it to provide new ones himself, as it can sometimes hallucinate or offer less optimal solutions.\n\nInitially, I thought a greedy approach might work but soon realized it led to suboptimal solutions. \n\nThrough interactions and reviewing different submissions, I explored solutions with different approaches to dynamic programming, learning more about bottom-up and top-down strategies, and when to use dynamic programming.\n\nI didn\'t get to ask all my questions to it due to time constraints. The problem is significantly more difficult to process than others I\'ve written about and confronted before, and in such cases my method\'s cue to move on is placed to the test.\n\nMy experience has been that the quicker I move away from frustration, while actively seeking it through making and testing assumptions, the faster I learn.\n\nI also wondered if the problem could be approached as a sliding window scenario, considering each carpet\'s starting index rather than a greedy placement. Initially, I pursued a wrong route based on this insight. This evolved through discovering a crucial example in the discussion section and self-discovery in isolation, leading me to understand that the problem had a larger search space with more possibilities for carpet placement combinations.\n\nI also used ChatGPT to tweak around a more in-depth second solution compared to user Lee215\'s succinct, Pythonic solution.\n\n## Tricky Parts\n\nAs I said, it was tricky figuring out how to traverse the space of carpet placement combinations. Dynamic programming (DP) is always a bit daunting on its difficulty to grasp and for me it often is the case that it doesn\'t intuitively come to mind as a solution.\n\nAlthough there weren\'t any tricky coding constraints, understanding the DP approach and the problem\'s optimal substructure was challenging still. The goal is to minimize something by finding minima in sub-sequences, which in general is hard to visualize.\n\nWith more learning and a closer look, I might get better at it, but I still don\'t feel strong on this one and for that reason haven\'t been able to mark it as understood on my database just yet.\n\n## Solution\n\n\n```python\nclass Solution:\n def minimumWhiteTiles(self, floor, k, l):\n\n @lru_cache(None)\n def dp(i, k):\n if i <= 0: return 0\n return min(int(floor[i - 1]) + dp(i - 1, k), dp(i - l, k - 1) if k else 1000)\n \n return dp(len(floor), k) \n\n```\n\nAs mentioned, the solution revolves around a DP approach to minimize the number of visible white tiles after placing a given number of carpets on a floor represented by the string `floor`. The core of this solution is the `dp` function, which is memoized using `lru_cache` to improve performance by storing the results of previous computations -that\'s what memoization means.\n\nThe `dp` function takes two arguments: `i`, the current index in the string representing the `floor`, and `k`, the number of carpets left to lay. The function is called recursively, working from right to left across the string, considering two main choices at each step: placing a carpet or not:\n\n1. **Not Placing a Carpet:** If a carpet isn\'t placed at the current index, the function adds `1` to the count if a white tile is present (`int(A[i - 1])` converts the character at the current index to an integer, adding `1` if it\'s a white tile), and then `dp` calls itself recursively with `i - 1`, moving one step to the left, keeping the count of carpets `k` left to place unchanged.\n\n2. **Placing a Carpet:** If a carpet is placed, the function calls itself also with `i - l`, jumping by the length of a carpet (we skip `l` positions because a carpet is there), and `k - 1`, reducing the count of remaining carpets by `1`. However, this choice is only considered if there are carpets left to place (`k` is not zero), otherwise, a large value (`1000`) is used to represent an undesirable choice, effectively ignoring this option, and always going for the other side of `min`. \n\nThe recursion continues until the left end of the string is reached (`i <= 0`), at which point `0` is returned, serving as the base case to terminate the recursion.\n\nThe main method initiates the dynamic programming process by calling `dp` with the initial index set to the length of the string `floor`, and the initial count of carpets `k`, and returns the result, representing the minimum number of visible white tiles after placing all carpets optimally.\n\n## Optimization\n\nJust understanding the actual complexity as described by these guys was initially challenging. With dynamic programming, it seems like the states are built around the indexes or tiles and the number of carpets `k`. So, the states are essentially what happens at a particular index after placing a certain number of carpets.\n\nThe complexity arises as we consider all positions from 0 to n (length of `floor`) and all carpet counts from 0 to k, leading to n times k states.\n\nThere are weird scenarios, like stacking a bunch of carpets at index 0, which feels illogical and calls for optimization to eliminate such considerations. These states seemed to inflate the space complexity and possibly the time complexity too.\n\n## Learned\n\nThis problem dives into the core of dynamic programming and gave me an opportunity to work on its fundamental concepts. I got to grasp, perhaps to an intermediate extent, the essence of recursiveness, tabulation, and memoization, and how the same ideas can be implemented with iterative rather than recursive code, essentially tabulating states.\n\nI got a little bit of an initial handle on optimally solving problems, understanding how tackling larger problems with optimal solutions to smaller sub-problems aligns with dynamic programming.\n\nI was able to expose the inadequacy of a greedy approach, affirming that dynamic programming, is the suitable strategy for such problems that are optimal in structure. I think this was the most significant realization of the session.\n\n## Further\n\nThe resources I used were basically the [convo with ChatGPT](https://chat.openai.com/share/f2df59ac-f8e5-4a2e-85fe-2b41ab8f9615) on this topic that I had today and yesterday. And the couple solutions ([first](https://leetcode.com/problems/minimum-white-tiles-after-covering-with-carpets/solutions/1863955/java-c-python-dp-solution/) and [second](https://leetcode.com/problems/minimum-white-tiles-after-covering-with-carpets/solutions/1872882/python-readable-and-easy-understand-bottom-up-dp-solution-in-python/))from users on LeetCode I feed as context to ChatGPT and drew understanding from.\n
0
0
['Dynamic Programming', 'Recursion', 'Python3']
0
minimum-white-tiles-after-covering-with-carpets
Easy intuitive Solution Using Recursion and Memoization
easy-intuitive-solution-using-recursion-gm699
Intuition\nwe will try to put carpet on every white tile where it exists till\nour number of carpets are over.\n\n# Approach\nif we find a white tile we will pu
hazarika857
NORMAL
2023-07-31T22:52:38.368711+00:00
2023-07-31T22:52:38.368736+00:00
35
false
# Intuition\nwe will try to put carpet on every white tile where it exists till\nour number of carpets are over.\n\n# Approach\nif we find a white tile we will put a carpet based on the length of\nthe carpet and look for more white tile and put carpet over them too,\nif the number of carpet is over we cant do anything at that case we \nhave to count the white tiles. If it is black tile we ignore it.\n\n# Code\n```\nclass Solution {\npublic:\n int minimumWhiteTiles(string floor, int numCarpets, int carpetLen) {\n vector<vector<int>>dp(floor.size(),vector<int>(numCarpets+1,-1));\n return solve(0,floor,numCarpets,carpetLen,dp);\n }\n int solve(int i,string &floor, int numCarpets, int &carpetLen,vector<vector<int>>&dp){\n if(i == floor.size()) return 0;\n if(dp[i][numCarpets] != -1) return dp[i][numCarpets];\n\n if(floor[i] == \'1\'){\n int putCarpet=INT_MAX;\n if(numCarpets!=0) \n {\n int temp= floor.size();\n putCarpet = solve( min(temp,i+carpetLen),floor,numCarpets-1,carpetLen,dp);\n }\n\n int notput=1+solve(i+1,floor,numCarpets,carpetLen,dp);\n\n return dp[i][numCarpets] = min(putCarpet,notput);\n\n }else{\n //ignore black tiles\n return dp[i][numCarpets] =solve(i+1,floor,numCarpets,carpetLen,dp);\n }\n }\n};\n```
0
0
['Recursion', 'Memoization', 'C++']
0
minimum-white-tiles-after-covering-with-carpets
Dp solution(c++ solution)
dp-solutionc-solution-by-jishudip_389-uokf
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
jishudip389
NORMAL
2023-07-31T15:08:55.479260+00:00
2023-07-31T15:08:55.479290+00:00
9
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 int f(int ind,int count,string &s,int carpetlen,vector<vector<int>>&dp){\n if(count<0)return -1e9;\n if(ind >= s.size())return 0;\n\n if(dp[ind][count]!=-1)return dp[ind][count];\n int color = -1e9;\n int notcolor = -1e9;\n if(s[ind] == \'0\'){\n notcolor = 1 + f(ind+1,count,s,carpetlen,dp);//we donot need to color this index as it is laredy black \n }\n else if(s[ind] == \'1\'){\n notcolor = f(ind+1,count,s,carpetlen,dp);\n if(ind+carpetlen >=s.size()){\n color=(s.size() - ind);\n }\n else color=carpetlen;\n color+=f(ind+carpetlen,count-1,s,carpetlen,dp);//color means we are coloring \n }\n\n return dp[ind][count] = max(color,notcolor);\n }\npublic:\n int minimumWhiteTiles(string floor, int numCarpets, int carpetLen) {\n \n int n = floor.size();\n int count = numCarpets;\n vector<vector<int>>dp(n,vector<int>(count+1,-1));\n int k = f(0,count,floor,carpetLen,dp);\n cout<<k<<endl;\n return n - k;\n }\n};\n```
0
0
['C++']
0
minimum-white-tiles-after-covering-with-carpets
0/1 Knapsack || Pick Not pick || Easy to read concise code
01-knapsack-pick-not-pick-easy-to-read-c-2v9s
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
Rutuj_P
NORMAL
2023-07-18T17:23:42.776729+00:00
2023-07-18T17:23:42.776762+00:00
18
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\nint n,l;\nint numCarpets;\nint dp[1000+1][1000+1];\n int solve(string &floor, int ind, int rem){\n if(ind>=n) return 0;\n if(dp[ind][rem] != -1) return dp[ind][rem];\n\n if(floor[ind]==\'1\'){\n int pick=INT_MAX,not_pick=INT_MAX;\n\n if(rem) pick=solve(floor,ind+l,rem-1);\n not_pick=1+solve(floor,ind+1,rem);\n return dp[ind][rem]=min(op1,op2);\n }\n return dp[ind][rem]=solve(floor,ind+1,rem);\n }\n int minimumWhiteTiles(string floor, int numCarpets, int carpetLen) {\n n=floor.size(), l=carpetLen;\n memset(dp,-1,sizeof(dp));\n return solve(floor,0,numCarpets);\n }\n};\n```
0
0
['Dynamic Programming', 'Memoization', 'C++']
0
minimum-white-tiles-after-covering-with-carpets
DP solution || Recursion + Memoization
dp-solution-recursion-memoization-by-eni-9u5j
\nclass Solution {\npublic:\n int solve(int i,string &s,int k,int len,vector<int> &pre,vector<vector<int>> &dp){\n int n = s.size();\n if(i>=n)
enigma79
NORMAL
2023-07-17T05:56:52.678018+00:00
2023-07-17T05:56:52.678036+00:00
4
false
```\nclass Solution {\npublic:\n int solve(int i,string &s,int k,int len,vector<int> &pre,vector<vector<int>> &dp){\n int n = s.size();\n if(i>=n) return 0;\n \n if(dp[i][k]!=-1) return dp[i][k];\n \n int tk=-1e9,ksum=0;\n ksum=(i+len<=n)?(pre[i+len]-pre[i]):(pre[n]-pre[i]);\n \n if(k>0 and s[i]==\'1\') tk = ksum+solve(i+len,s,k-1,len,pre,dp);\n int nottk = 0+solve(i+1,s,k,len,pre,dp);\n \n return dp[i][k]=max(tk,nottk);\n }\n int minimumWhiteTiles(string s, int numCarpets, int carpetLen) {\n int n = s.size();\n vector<int> pre(n+1,0);\n vector<vector<int>> dp(n+1,vector<int>(numCarpets+1,-1));\n for(int i=1;i<=n;i++) {\n pre[i]=pre[i-1];\n if(s[i-1]==\'1\') pre[i]+=1;\n }\n \n return pre[n]-solve(0,s,numCarpets,carpetLen,pre,dp);\n }\n};\n```
0
0
['Dynamic Programming', 'Memoization']
0
minimum-white-tiles-after-covering-with-carpets
My Solution
my-solution-by-hope_ma-ahay
\n/**\n * the dynamic programming solution is employed.\n *\n * `dp[carpets][tiles]` stands for the minimum number of while tiles\n * when `carpets` carpets hav
hope_ma
NORMAL
2023-07-14T09:19:22.704667+00:00
2023-07-14T09:19:22.704694+00:00
2
false
```\n/**\n * the dynamic programming solution is employed.\n *\n * `dp[carpets][tiles]` stands for the minimum number of while tiles\n * when `carpets` carpets have been covered in the tile range [0, tiles),\n * 0 inclusive, `tiles` exclusive.\n * where `carpets` is in the range [0, `numCarpets`], both inclusive\n * `tiles` is in the range [0, `floor.size()`], both inclusive\n *\n * initial:\n * if `carpets` == 0\n * 1. if tiles == 0,\n * dp[carpets][tiles] = 0\n * 2. if tiles > 0,\n * dp[carpets][tiles] = dp[carpets][tiles - 1] + (floor[tiles - 1] == \'1\' ? 1 : 0)\n *\n * induction:\n * 1. if tiles == 0\n * dp[carpets][tiles] = 0\n * 2. otherwise\n * 2.1. let `covered` stand for the minimum number of while tiles\n * if the `tiles - 1`\'th tile is covered by a carpet\n * covered = dp[carpets - 1][max(0, tiles - carpetLen)]\n * 2.2. let `uncovered` stand for the minimum number of while tiles\n * if the `tiles - 1`\'th tile is not covered by a carpet,\n * uncovered = dp[carpets][tiles - 1] + (floor[tiles - 1] == \'1\' ? 1 : 0)\n * dp[carpets][tiles] = min(covered, uncovered)\n *\n * target:\n * dp[numCarpets][floor.size()]\n *\n * Time Complexity: O(numCarpets * n)\n * Space Complexity: O(n)\n * where `n` is the length of the string `floor`\n */\nclass Solution {\n public:\n int minimumWhiteTiles(const string &floor, const int numCarpets, const int carpetLen) {\n constexpr int range = 2;\n constexpr char white = \'1\';\n const int n = static_cast<int>(floor.size());\n int dp[range][n + 1];\n memset(dp, 0, sizeof(dp));\n int previous = 0;\n int current = 1;\n for (int tiles = 1; tiles < n + 1; ++tiles) {\n dp[previous][tiles] = dp[previous][tiles - 1] + (floor[tiles - 1] == white ? 1 : 0);\n }\n \n for (int carpets = 1; carpets < numCarpets + 1; ++carpets) {\n for (int tiles = 1; tiles < n + 1; ++tiles) {\n const int covered = dp[previous][max(0, tiles - carpetLen)];\n const int uncovered = dp[current][tiles - 1] + (floor[tiles - 1] == white ? 1 : 0);\n dp[current][tiles] = min(covered, uncovered);\n }\n \n previous ^= 1;\n current ^= 1;\n memset(dp[current], 0, sizeof(dp[current]));\n }\n \n return dp[previous][n];\n }\n};\n```
0
0
[]
0
minimum-white-tiles-after-covering-with-carpets
[C++/Java] Memoization - Commented
cjava-memoization-commented-by-suren-yea-9oi9
Code\nC++ []\nclass Solution {\npublic:\n\n #define WHITE \'1\'\n \n vector<vector<int>> dp;\n int n, c;\n \n int solve(string &floor, int ind
suren-yeager
NORMAL
2023-07-06T19:49:22.563788+00:00
2023-07-06T19:49:22.563808+00:00
16
false
## Code\n```C++ []\nclass Solution {\npublic:\n\n #define WHITE \'1\'\n \n vector<vector<int>> dp;\n int n, c;\n \n int solve(string &floor, int ind, int rem){\n\n // Reached end - No white tiles visible\n if(ind >= n) return 0;\n\n // Checking cache\n if(dp[ind][rem] != -1) return dp[ind][rem];\n\n int res = 1e8;\n\n // We have 2 options -> Cover this tile or don\'t\n \n // Don\'t cover this tile \n // If its a white tile, one white tile is visible already\n res = (floor[ind] == WHITE) + solve(floor, ind + 1, rem);\n \n // Cover this tile if its a white tile and carpets are still remaining\n if(floor[ind] == WHITE and rem) res = min(res, solve(floor, ind + c, rem - 1));\n \n // Caching\n return dp[ind][rem] = res;\n \n }\n \n int minimumWhiteTiles(string floor, int numCarpets, int carpetLen) {\n n = floor.length(), c = carpetLen;\n\n // 2D DP {index, carpetsRemaining}\n dp = vector<vector<int>> (n + 1, vector<int> (numCarpets + 1, -1));\n\n return solve(floor, 0, numCarpets);\n }\n};\n```\n```Java []\nclass Solution {\n\n private static final char WHITE = \'1\';\n private int[][] dp;\n private int n, c;\n\n public int minimumWhiteTiles(String floor, int numCarpets, int carpetLen) {\n n = floor.length();\n c = carpetLen;\n\n // 2D DP {index, carpetsRemaining}\n dp = new int[n + 1][numCarpets + 1];\n for (int[] row : dp) {\n Arrays.fill(row, -1);\n }\n\n return solve(floor, 0, numCarpets);\n }\n\n private int solve(String floor, int ind, int rem) {\n // Reached end - No white tiles visible\n if (ind >= n) {\n return 0;\n }\n\n // Checking cache\n if (dp[ind][rem] != -1) {\n return dp[ind][rem];\n }\n\n int res = (int) 1e8;\n\n // We have 2 options -> Cover this tile or don\'t\n\n // Don\'t cover this tile\n // If it\'s a white tile, one white tile is visible already\n res = (floor.charAt(ind) == WHITE ? 1 : 0) + solve(floor, ind + 1, rem);\n\n // Cover this tile if it\'s a white tile and carpets are still remaining\n if (floor.charAt(ind) == WHITE && rem > 0) {\n res = Math.min(res, solve(floor, ind + c, rem - 1));\n }\n\n // Caching\n dp[ind][rem] = res;\n return res;\n }\n}\n\n```\n\n## Complexity\n- Time complexity: $$O(n^2)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n^2)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->
0
0
['Memoization', 'C++', 'Java']
0
minimum-white-tiles-after-covering-with-carpets
C++/Python, dynamic programming solution with explanation
cpython-dynamic-programming-solution-wit-tufo
dp[i][j] is minimum number of visible white tiles in the first i tiles ([0, i]) which are coverd by j carpets.\nIf the tile is black, dp[i][j] = dp[i][j-1] + 1.
shun6096tw
NORMAL
2023-07-06T13:50:05.951868+00:00
2023-07-06T13:50:05.951896+00:00
4
false
```dp[i][j]``` is minimum number of visible white tiles in the first ```i``` tiles ([0, i]) which are coverd by ```j``` carpets.\nIf the tile is black, ```dp[i][j] = dp[i][j-1] + 1```.\nIf the tile is white, we have 2 choices,\none is using a carpet to to cover it, ```dp[i][j] = dp[i-1][j-carpetLen]```.\nAnother is not to cover it, ```dp[i][j] = dp[i][j-1] + 1```.\nWe select minimum choice, ```dp[i][j] = min(dp[i][j-1] + (\'1\' == floor[j]), dp[i-1][j-carpetLen])```.\n\nAt first, there is no carpet, so ```dp[0][j]``` is number of white tiles in the first ```j``` tiles.\n\ntc and sc are O(numCarpets * len(floor))\n\n### python\n```python\nclass Solution:\n def minimumWhiteTiles(self, floor: str, numCarpets: int, carpetLen: int) -> int:\n size = len(floor)\n\t\t\n\t\t# floor are covered by carpets entirely\n if numCarpets * carpetLen >= size: return 0\n\t\t\n dp = [[0] * size for _ in range(numCarpets+1)]\n\t\t\n\t\t# At first, there is no carpet\n\t\t# dp[0][j] is number of white tiles in the first j tiles\n dp[0][0] = \'1\' == floor[0]\n for i in range(1, size):\n dp[0][i] = dp[0][i-1] + (\'1\' == floor[i])\n \n for i in range(1, numCarpets+1):\n\t\t\t# there have i carpets, it can covered i * carpetLen tiles, \n\t\t\t# so dp[i][0...i * carpetLen-1] are 0\n\t\t\t\n for j in range(i * carpetLen, size):\n\t\t\t\t\n\t\t\t\t# min(not to cover, use a carpet to cover j-th tile)\n dp[i][j] = min(dp[i][j-1] + (\'1\' == floor[j]), dp[i-1][j-carpetLen])\n return dp[numCarpets][-1]\n```\n\n### c++\n```cpp\nclass Solution {\npublic:\n int minimumWhiteTiles(string floor, int numCarpets, int carpetLen) {\n int size = floor.size();\n if (numCarpets * carpetLen >= size) return 0;\n vector<vector<int>> dp (numCarpets+1, vector<int>(size));\n dp[0][0] = (\'1\' == floor[0]);\n for (int i = 1; i < size; i+=1) \n dp[0][i] = dp[0][i-1] + (\'1\' == floor[i]); \n for (int i = 1; i <= numCarpets; i+=1) {\n for (int j = i * carpetLen; j < size; j+=1) {\n dp[i][j] = min(dp[i][j-1] + (\'1\' == floor[j]), dp[i-1][j-carpetLen]); \n }\n }\n return dp[numCarpets][size-1];\n }\n};\n```\n### space optimization\nuse scrolling array.\n### python\n```python\nclass Solution:\n def minimumWhiteTiles(self, floor: str, numCarpets: int, carpetLen: int) -> int:\n size = len(floor)\n if numCarpets * carpetLen >= size: return 0\n dp = [0] * size\n dp[0] = \'1\' == floor[0]\n for i in range(1, size):\n dp[i] = dp[i-1] + (\'1\' == floor[i])\n for i in range(1, numCarpets+1):\n tmp = dp[:] # dp[i-1][j-carpetLen]\n dp[i * carpetLen - 1] = 0 # notice that dp[j-1]\n for j in range(i * carpetLen, size):\n dp[j] = min(dp[j-1] + (\'1\' == floor[j]), tmp[j-carpetLen])\n return dp[-1]\n```
0
0
['Dynamic Programming', 'C', 'Python']
0
minimum-white-tiles-after-covering-with-carpets
Easy to Understand | C++ | Recursive | Memoization | DP
easy-to-understand-c-recursive-memoizati-336j
Intuition\n Describe your first thoughts on how to solve this problem. \nDynamic Programming take and not take simple intuition.\n\n# Approach\n Describe your a
AmitKumarn22
NORMAL
2023-06-29T14:27:22.487127+00:00
2023-06-29T14:27:22.487146+00:00
13
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nDynamic Programming take and not take simple intuition.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nSolved using Dynamic Programming approach.\nThere are 3 case , starting from the first tile \n1. Black tile : skip and move to next tile\n2. White tile not Take : skip and move to next tile\n3. White tile take : use the carpet to cover and move to (curr tile + carpetLen - 1 )th tile\nthen take the max of all.\nWe are taking max because we have to find min uncovered tile, so max covered tile. \n\n# Complexity\n- Time complexity:\nO(floor.length() * numCarpets)\n\n- Space complexity:\nO(floor.length() * numCarpets)\n\n# Code\n```\nclass Solution {\npublic:\n\n int f(int i, int num, int &len, vector<int> &prefix_floor, string &floor,int &n,vector<vector<int>> &dp){\n if(i>=n || num==0) return 0;\n if(dp[i][num]!=-1) return dp[i][num];\n if(floor[i]==\'0\') return dp[i][num] = f(i+1,num,len,prefix_floor,floor,n,dp);\n int notTake = f(i+1,num,len,prefix_floor,floor,n,dp);\n int bnd = min(i+len-1,n-1);\n int white = prefix_floor[bnd];\n if(i!=0) white = white - prefix_floor[i-1];\n int take = white + f(i+len,num-1,len,prefix_floor,floor,n,dp);\n return dp[i][num] = max(take,notTake);\n }\n\n int minimumWhiteTiles(string floor, int numCarpets, int carpetLen) {\n int n = floor.length();\n vector<int> prefix_floor;\n int count = 0;\n if(floor[0]==\'1\'){\n prefix_floor.push_back(1);\n count++;\n }\n else prefix_floor.push_back(1);\n for(int i=1; i<n; i++){\n if(floor[i]==\'1\'){\n prefix_floor.push_back(1 + prefix_floor[i-1]);\n count++;\n }\n else{\n prefix_floor.push_back(prefix_floor[i-1]);\n }\n }\n vector<vector<int>> dp(n,vector<int>(numCarpets+1,-1));\n return count-f(0,numCarpets,carpetLen,prefix_floor,floor,n,dp);\n }\n};\n```
0
0
['C++']
0
counter
Day2=O(1)>Understanding Closure in easy way and its practical uses!!
day2o1understanding-closure-in-easy-way-pr939
When, Where, What, and How to use closure!!!\nFirst of all closure is not something you create it\'s something that the language has created for itself for appr
Cosmic_Phantom
NORMAL
2023-05-06T02:04:08.894012+00:00
2024-08-23T02:18:00.884791+00:00
113,612
false
# When, Where, What, and How to use closure!!!\nFirst of all closure is not something you create it\'s something that the language has created for itself for appropriate development and we need to crack this code that how the language uses it. \n\n"*To be honest, a good developer\'s greatest fear is discovering that something is working but not knowing how it works.*"\n\n## What is Closure ?\n* A closure is created when a function is defined inside another function, and the **inner function references variables in the outer function\'s scope**. When the inner function is returned from the outer function, it retains a reference to the outer function\'s scope, and can continue to access those variables even after the outer function has finished executing. Vice-Versa is not true!!\n* In simple terms a closure can "**remember" values from its outer function\'s scope and use them later**, even if the outer function has returned and those values would normally be out of scope.\n\n## When to use closure concept ?\nFIrst let\'s summarize the definition as usually the definition gives the answer for when to use..\n* From definition you can see that it\'s used for retrival of values from outer parent function so we can understand that closure can be used for retrival of dead values which have become out of scope. also we can comprehend that it can used for privating some varibles or function. \n* **Thus closures are useful for creating private variables and functions, implementing partial function application, and preserving state in asynchronous code.**\n* While writing the code whenever there is a need for these types of thing try to incorporate this closure concept i.e. In a programmer languge it\'s called `lexical environment`\n\n## Where and How to use closure concept ?\n1. **Private variables and functions:**\n\n```\nconst makeCounter = () => {\n let count = 0;\n \n return () => {\n count++;\n console.log(count);\n }\n}\n\nlet counter = makeCounter();\ncounter(); // logs 1\ncounter(); // logs 2\ncounter(); // logs 3\n```\n* In this example, `makeCounter` is an `arrow function` that returns another `arrow function`. The returned function increments a count variable each time it is called, and logs the new value of `count` to the console.\n* When `makeCounter` is called, it creates a new scope with a `count` variable initialized to `0`. It then returns a **new arrow function that "closes over" this scope and increments the count variable each time it is called.**\n* When we assign the returned arrow function to the counter variable, we create a closure that retains a reference to the count variable. \n* Each time we call `counter()`, it increments the `count` variable and logs the new value to the console, because it is still "closing over" the original `count` variable in the outer function\'s scope.\n* Thus because the `count` variable is not exposed outside of the returned object, it is effectively a private variable that can only be accessed or modified through the `makeCounter()` methods.\n\n2. **Partial function:**\nI was introduced to this concept name during development phase but was shocked that unknowingly I have used it many times. I\'m sure that you all also must have use this:\n```\nfunction add(x) {\n return function(y) {\n return x + y;\n }\n}\n\nlet add5 = add(5);\nconsole.log(add5(3)); // 8\n```\n* In this example, the `add()` function returns another function that takes a single argument and returns the `sum` of that argument and the `x` value from the outer function\'s scope. \n* This allows us to "partially apply" the `add()` function by passing in an `x` value and getting back a new function that always adds that value to its argument. \n* Thuse we can then use the new function like any other function, passing in different `y` values as needed.\n\n3. **For preserving states in asynchronous code:** \nThe below snippet is from my personal project:)\n```\nconst animate = (element, from, to, duration) => {\n let start = performance.now();\n \n const update = () => {\n let time = performance.now() - start;\n let progress = time / duration;\n let value = from + (to - from) * progress;\n \n element.style.left = value + \'px\';\n \n if (progress < 1) {\n requestAnimationFrame(update);\n }\n }\n \n requestAnimationFrame(update);\n}\n\nlet element = document.getElementById(\'my-element\');\nanimate(element, 0, 100, 1000);\n```\n\n* In this example, the `animate()` function creates a closure over the `start` variable, which is used to calculate the elapsed time since the animation started. \n* The `update()` function also "closes over" the element, `from`, `to`, and `duration` arguments, so that it can use them to update the element\'s position over time. \n* Thus by **creating a closure over these values**, we can **preserve their state between animation frames**, even though the `update()` function is called **asynchronously** by `requestAnimationFrame()`.\n\n\n# Answer to todays(#2) JS challenge:\n```\nvar createCounter = function(n) {\n return ()=> n++\n};\n```\n**TIme and Space : O(1)**\n
627
1
['JavaScript']
40
counter
✔️Counter( ) 2620✔️Level up🚀your JavaScript skills with these intuitive implementations󠁓🚀
counter-2620level-upyour-javascript-skil-qy21
Intuition\n Describe your first thoughts on how to solve this problem. \n>The problem asks us to implement a function that returns a counter, which initially re
Vikas-Pathak-123
NORMAL
2023-05-06T09:00:32.251319+00:00
2023-05-06T09:07:00.284840+00:00
41,994
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n>The problem asks us to implement a function that returns a counter, which initially returns the input number, and then returns a number that is one more than the previous value on each subsequent call. To solve this problem, we need to define a function that maintains the state of the current count, and returns a value that is incremented by one on each call.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n>One way to implement this function is to use a closure - we define an outer function that takes the initial count as a parameter, and returns an inner function that increments and returns the count on each call. The inner function has access to the `count` variable of the outer function, and since the outer function has already returned, the inner function\'s closure retains a reference to the `count` variable. This allows the inner function to maintain the state of the count between calls.\n\n\n# Complexity\n>The time and space complexity of this implementation of the counter function are both constant - O(1). The `createCounter` function initializes a single variable `count` to the input `start` value, which takes constant time and space. The inner function returns the current value of `count` and increments it by one, which also takes constant time and space. Since there are no loops or recursive calls in the implementation, the time and space complexity remain constant regardless of the number of calls to the counter function.\n\n\n# Code\n```\nfunction createCounter(start) {\n let count = start;\n return function() {\n return count++;\n }\n}\n```\n\n![image.png](https://assets.leetcode.com/users/images/b427e686-2e5d-469a-8e7a-db5140022a6b_1677715904.0948765.png)\n\n\n# Please Upvote\uD83D\uDC4D\uD83D\uDC4D\n```\nThanks for visiting my solution.\uD83D\uDE0A Keep Learning\nPlease give my solution an upvote! \uD83D\uDC4D\nIt\'s a simple way to show your appreciation and\nkeep me motivated. Thank you! \uD83D\uDE0A\n```\n\n##### Here\'s an implementation of the counter function using a closure:\n>There are multiple ways to implement a counter function in JavaScript. Here are a few examples:\n\n1. Using a closure and a local variable:\n```\nfunction createCounter(start) {\n let count = start;\n return function() {\n return count++;\n }\n}\n\nconst counter = createCounter(10);\nconsole.log(counter()); // 10\nconsole.log(counter()); // 11\nconsole.log(counter()); // 12\nUsing a generator function:\n```\n2. Using a generator function:\n```\nfunction* createCounter(start) {\n let count = start;\n while (true) {\n yield count++;\n }\n}\n\nconst counter = createCounter(10);\nconsole.log(counter.next().value); // 10\nconsole.log(counter.next().value); // 11\nconsole.log(counter.next().value); // 12\nUsing an ES6 class:\n```\n3. Using an ES6 class:\n```\nclass Counter {\n constructor(start) {\n this.count = start;\n }\n next() {\n return this.count++;\n }\n}\n\nconst counter = new Counter(10);\nconsole.log(counter.next()); // 10\nconsole.log(counter.next()); // 11\nconsole.log(counter.next()); // 12\n```\n4. Using arrow function\n```\nvar createCounter = (n) =>{\n return () => n++;\n};\n\n```\nAll of these implementations work in a similar way - they define a variable to keep track of the current count, and return a function or method that increments and returns the count on each call. The first example uses a closure and a local variable, the second uses a generator function, and the third uses an ES6 class with a next() method.\n\n# Important topic to Learn\n```\n1. Closures - As I mentioned earlier, closures are an important\nconcept in JavaScript, and understanding how they work is essential \nfor solving the counter function problem. Closures are \ncreated whenever a function is defined inside another function, and\nthe inner function has access to the variables and parameters of the \nouter function.\n\n2. Higher-order functions - The counter function is an example of a \nhigher-order function, which is a function that takes one or more \nfunctions as arguments or returns a function as its result. In this \ncase, the `createCounter` function takes an initial count as a \nparameter and returns an inner function that increments and returns \nthe count on each call.\n\n3. Function expressions - The implementation of the counter function \nusing a closure involves using a function expression to define the \ninner function. Function expressions are a way to define a function \nas a value that can be assigned to a variable or passed as an \nargument to another function.\n\n4. Arrow functions - Arrow functions are a shorthand syntax for \ndefining functions in JavaScript, and they are commonly used in \nfunctional programming. The counter function can also be implemented \nusing an arrow function, as I showed in one of the previous solutions.\n\n5. Arrays and array methods - In the test cases for the counter \nfunction problem, the function is called multiple times and the \nresults are returned as an array. To implement this, we can use an \narray to store the results and an array method like `map()` to call \nthe function multiple times and add the results to the array.\n```\n\n\n\n# Please Comment\uD83D\uDC4D\uD83D\uDC4D\n```\nThanks for visiting my solution comment below if you like it.\uD83D\uDE0A\n```
510
0
['JavaScript']
37
counter
✅💯🔥Simple Code📌🚀| 🔥✔️Easy to understand🎯 | 🎓🧠Beginner friendly🔥| O(n) Time Complexity💀💯
simple-code-easy-to-understand-beginner-cmuz1
Code\n\n/**\n * @param {number} n\n * @return {Function} counter\n */\nvar createCounter = function(n) {\n return function() {\n return n++;\n }\n}
atishayj4in
NORMAL
2024-08-12T21:39:20.400612+00:00
2024-08-12T21:39:20.400651+00:00
8,388
false
# Code\n```\n/**\n * @param {number} n\n * @return {Function} counter\n */\nvar createCounter = function(n) {\n return function() {\n return n++;\n }\n}\n\n/** \n * const counter = createCounter(10)\n * counter() // 10\n * counter() // 11\n * counter() // 12\n */\n```\n![7be995b4-0cf4-4fa3-b48b-8086738ea4ba_1699897744.9062278.jpeg](https://assets.leetcode.com/users/images/fe5117c9-43b1-4ec8-8979-20c4c7f78d98_1721303757.4674635.jpeg)
60
0
['JavaScript']
7
counter
Day 2 - JavaScript and TypeScript
day-2-javascript-and-typescript-by-racha-58yt
Approach - Postfix Increment Syntax\nJavaScript provides convenient syntax that returns a value and then increments it. This allows us to avoid having to initia
mr_rajeshsingh
NORMAL
2023-05-06T00:22:05.812605+00:00
2023-05-07T04:08:42.046539+00:00
22,532
false
# Approach - Postfix Increment Syntax\nJavaScript provides convenient syntax that returns a value and then increments it. This allows us to avoid having to initially set a variable to n - 1.\n\n# Code\n<iframe src="https://leetcode.com/playground/PgQPK2ds/shared" frameBorder="0" width="700" height="300"></iframe>\n
33
1
['TypeScript', 'JavaScript']
7
counter
Solutions in two different approaches....
solutions-in-two-different-approaches-by-hiq3
Day 2 of JavaScript\n\n## Code 1\njavascript []\n/**\n * @param {number} n\n * @return {Function} counter\n */\nvar createCounter = function(n) {\n let count
Aim_High_212
NORMAL
2024-11-10T13:00:30.285630+00:00
2024-11-10T13:00:30.285664+00:00
5,284
false
# Day 2 of JavaScript\n\n## Code 1\n```javascript []\n/**\n * @param {number} n\n * @return {Function} counter\n */\nvar createCounter = function(n) {\n let count = n;\n return function() {\n return count++;\n };\n};\n```\n## Code 2\n```javascript []\nvar createCounter = function(n) {\n let count = n;\n return function counter() {\n if (count <= n + 2) {\n return count++;\n } else {\n return "Counter limit reached";\n }\n };\n};\n```
26
0
['Recursion', 'JavaScript']
4
counter
➡️➡️ Double Arrow Function || One-Line || Explained
double-arrow-function-one-line-explained-hr6z
Approach\nThis problem involves the concept of a closure.\n\nA closure is the combination of a function and a reference to the function\'s outer scope.\n\nIt\'s
richardm2789
NORMAL
2023-04-11T22:14:19.051331+00:00
2024-08-05T21:14:22.807351+00:00
11,540
false
# Approach\nThis problem involves the concept of a closure.\n\nA closure is the combination of a function and a reference to the function\'s outer scope.\n\nIt\'s the ability of an inner function to access its outer scope even after the outer function has finished executing.\n\nIn this problem, the closure is the pairing of the function being returned inside of createCounter and its access to the outer scope including createCounter\'s variables. \n\nWhen createCounter has finished executing, the inner function is still able to access createCounter\'s variables. \n\nEach time the inner counter function is called, it accesses createCounter\'s parameter n, returns its value, and updates it.\n\nIt\'s important to use post-increment (i++) operator here since the problem specifies that the first call returns n.\n```\nvar createCounter = function(n) {\n return function() {\n return n++\n };\n}\n```\n\nIf closures still confuse you, I\'d recommend looking up "closures javascript" on google. There\'s tons of great resources (ie. YT videos, StackOverflow posts) that explain this concept in more detail.\n### Arrow Function Syntax\nWe can make the syntax more concise by using arrow functions.\n\nArrow functions provide an alternate way of writing functions. They typically follow one of the following formats\n```\n() => expression\nparam => expression\n(param1, param2, ...) => expression\n```\nIn this problem, we can convert both the inner and outer functions into arrow functions.\n\n```\nvar createCounter = n => () => n++\n```\n\nAs mentioned in the comments, there\'s an even shorter version.\n\nWe can use \'_\' to replace the parentheses. We can also omit the var keyword.\n\n```\ncreateCounter = n => _ => n++\n```\nNot sure if there\'s a LC question that you can answer in fewer characters than this lol.
22
0
['JavaScript']
6
counter
Counter : Closure
counter-closure-by-santoshmcode-p9ts
Intuition\nThe code snippet defines a function createCounter that takes an integer n as input and returns another function that increments and returns a counter
santoshmcode
NORMAL
2023-04-12T04:06:55.112421+00:00
2023-04-12T04:06:55.112467+00:00
6,990
false
# Intuition\nThe code snippet defines a function `createCounter` that takes an integer n as input and returns another function that increments and returns a counter variable count every time it is called.\n\n# Approach\nThe inner function returned by `createCounter` uses a `closure` to maintain access to the `count` variable defined in the outer function. When the inner function is called, it increments `count` by 1 and returns its new value.\n\n# Complexity\n- Time complexity: \nThe time complexity of the inner function is `O(1)` because it performs a constant number of operations (incrementing and returning count). The time complexity of the outer function is also `O(1)` because it performs a constant number of operations (defining a variable and returning the inner function).\n\n- Space complexity:\nThe space complexity of the `createCounter` function is `O(1)` because it only defines one variable count. The space complexity of the inner function is also `O(1)` because it does not create any additional variables.\n\n# Code\n```\n/**\n * @param {number} n\n * @return {Function} counter\n */\nvar createCounter = function(n) {\n let count = n - 1\n return function() {\n count++\n return count\n };\n};\n\n/** \n * const counter = createCounter(10)\n * counter() // 10\n * counter() // 11\n * counter() // 12\n */\n```
14
0
['JavaScript']
4
counter
Easy and Straightforward Javascript Solution in O(1) Time And Space Complexity ✔✔.
easy-and-straightforward-javascript-solu-gq7y
Intuition \n Describe your first thoughts on how to solve this problem. \n - n is local to createCounter function.\n - n is global to counter function.\n Since
Boolean_Autocrats
NORMAL
2023-05-06T02:43:37.869869+00:00
2023-05-06T02:45:24.137759+00:00
4,925
false
# Intuition \n<!-- Describe your first thoughts on how to solve this problem. -->\n - n is local to createCounter function.\n - n is global to counter function.\n Since in every call we have to return n and in next call we have to\n return n+1 so what we do is we will first store value of n in temp variable and then we increase value of n by 1 and return temporary value and since n is global to counter so change in value of n will be reflect in next call (In the next call value of n will be curr value+1 and that will be our ans). \n# Approach\n<!-- Describe your approach to solving the problem. -->\n - let temp=n\n - n+=1\n \n# Complexity\n- Time complexity: O(1)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n \n- Space complexity:O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n/**\n * @param {number} n\n * @return {Function} counter\n */\nvar createCounter = function counter(n) {\n return function() {\n let curr=n;\n n+=1;\n return curr;\n };\n};\n\n/** \n * const counter = createCounter(10)\n * counter() // 10\n * counter() // 11\n * counter() // 12\n */\n```
10
0
['JavaScript']
3
counter
Easy iterative example for beginners 🧨. Please Up vote 🫰🏻
easy-iterative-example-for-beginners-ple-fuk4
Approach\nThinking in multiple ways and knowing the fundamentals is Great\n\n# Complexity\n- Time complexity:\no(1)\n\n- Space complexity:\no(1)\n\n# Code\n\n//
Aribaskar_j_b
NORMAL
2023-04-15T09:40:20.900504+00:00
2023-04-15T09:40:20.900534+00:00
3,038
false
# Approach\nThinking in multiple ways and knowing the fundamentals is Great\n\n# Complexity\n- Time complexity:\no(1)\n\n- Space complexity:\no(1)\n\n# Code\n```\n// Expanded version and simple\nvar createCounter = function (n) {\n var count=0;\n var temp=0;\n return function () {\n if(count===0){\n count+=1\n temp=n\n return n\n }\n else{\n temp+=1\n return temp\n }\n }\n};\n\n// For one-liners and functional programmers\n// let createCounter = (n) => () => n++\n\n```
7
0
['JavaScript']
1
counter
Detailed explanation.
detailed-explanation-by-rupdeep-jd2g
Explanation:\n\n1. The createCounter function takes an integer n as input and initializes a counter variable to n.\n2. It then returns an anonymous function tha
Rupdeep
NORMAL
2023-04-11T21:53:41.869482+00:00
2023-04-11T21:59:20.660977+00:00
1,050
false
Explanation:\n\n1. The createCounter function takes an integer n as input and initializes a counter variable to n.\n2. It then returns an anonymous function that takes no arguments.\n3. When the returned function is called, it returns the current value of counter and then increments counter by 1 using the post-increment operator (counter++).\n4. Since counter is a local variable in the scope of the createCounter function, it does not modify the original input n.\n\n\nWe can directly return n++, but it is better not to modify the given input. Hence we store it in another variable and then return.\n\nAlso, if any of you is having difficulty to understand the count++ thing then you can first increment count and then return count - 1. Like this:\ncount++;\nreturn count - 1;\n\n# Code\n```\n/**\n * @param {number} n\n * @return {Function} counter\n */\nvar createCounter = function(n) {\n var count = n;\n return function() {\n return count++;\n };\n};\n\n/** \n * const counter = createCounter(10)\n * counter() // 10\n * counter() // 11\n * counter() // 12\n */\n```\n\nPlease upvote if found helpful. :)
7
0
['JavaScript']
1
counter
1/30 days JAVASCRIPT
130-days-javascript-by-doaaosamak-7uzh
"Hello! Here is a code for a straightforward question. Have a great day, and see you tomorrow."\n\nvar createCounter = function(n) {\n return ()=> n++\n};\n
DoaaOsamaK
NORMAL
2024-03-15T13:03:26.256002+00:00
2024-03-15T13:03:26.256036+00:00
664
false
"Hello! Here is a code for a straightforward question. Have a great day, and see you tomorrow."\n```\nvar createCounter = function(n) {\n return ()=> n++\n};\n```
6
0
['JavaScript']
2
counter
✔💯 DAY 401 | MULTIPLE WAYS | [JAVASCRIPT/TYPESCRIPT] | 100% 0ms | EXPLAINED | Approach 🆙🆙🆙
day-401-multiple-ways-javascripttypescri-5xtb
Please Upvote as it really motivates me \uD83C\uDD99\uD83C\uDD99\uD83C\uDD99\n Describe your approach to solving the problem. \n\n\n\n# Complexity\n- Time compl
ManojKumarPatnaik
NORMAL
2023-05-06T02:59:52.044364+00:00
2023-05-06T03:05:43.808901+00:00
310
false
# Please Upvote as it really motivates me \uD83C\uDD99\uD83C\uDD99\uD83C\uDD99\n<!-- Describe your approach to solving the problem. -->\n![image.png](https://assets.leetcode.com/users/images/1e873636-cdf1-41ef-abbd-caed210b7000_1683342340.5855558.png)\n\n\n# Complexity\n- Time complexity:o(1)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:o(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code Using a function expression assigned to a variable:\n```js []\n/**\n * @param {number} n\n * @return {Function} counter\n */\nvar createCounter = function(n){\n let c=n-1;\n return function(){\n c++;\n return c;\n }\n}\n\n/** \n * const counter = createCounter(10)\n * counter() // 10\n * counter() // 11\n * counter() // 12\n */\n```\n```ts []\nlet createCounter = function(n: number): () => number {\n let c = n - 1;\n return function(): number {\n c++;\n return c;\n }\n};\n```\n# 2nd Using a function declaration:\n```js []\nfunction createCounter(n) {\n let c = n - 1;\n return function() {\n c++;\n return c;\n }\n}\n```\n```ts []\nfunction createCounter(n: number): () => number {\n let c = n - 1;\n return function(): number {\n c++;\n return c;\n }\n}\n```\n# 3rd Using an arrow function assigned to a variable:\n```Js []\nlet createCounter = n => {\n let c = n - 1;\n return () => {\n c++;\n return c;\n }\n};\n```\n```ts []\nlet createCounter = (n: number): (() => number) => {\n let c = n - 1;\n return (): number => {\n c++;\n return c;\n }\n};\n```\n\n\n# Intuition & Approach\nAll three versions of the createCounter function take an integer n as input and return a function that increments and returns a counter value starting from n . The counter value is initialized to n-1 to ensure that the first call to the counter function returns n\n\n\n# one liner \n```js []\nvar createCounter = (n) => () => n++;\n```\n```ts []\nlet createCounter = (n: number): (() => number) => () => n++;\n```\n\n![BREUSELEE.webp](https://assets.leetcode.com/users/images/062630f0-ef80-4e74-abdb-302827b99235_1680054012.5054147.webp)\n![image.png](https://assets.leetcode.com/users/images/303fa18d-281d-49f0-87ef-1a018fc9a488_1681355186.0923774.png)\n\n\n# Please Upvote\uD83D\uDC4D\uD83D\uDC4D\nThanks for visiting my solution.\uD83D\uDE0A Keep Learning\nPlease give my solution an upvote! \uD83D\uDC4D \uD83C\uDD99\uD83C\uDD99\uD83C\uDD99\nIt\'s a simple way to show your appreciation and\nkeep me motivated. Thank you! \uD83D\uDE0A\n.
5
1
['TypeScript', 'JavaScript']
0
counter
Solution
solution-by-antovincent-8ls5
\n\n# Code\n\n/**\n * @param {number} n\n * @return {Function} counter\n */\nvar createCounter = function(n) {\n return function() {\n return n++;\n
antovincent
NORMAL
2023-05-06T02:54:05.848545+00:00
2023-05-06T02:54:05.848573+00:00
8,221
false
\n\n# Code\n```\n/**\n * @param {number} n\n * @return {Function} counter\n */\nvar createCounter = function(n) {\n return function() {\n return n++;\n };\n};\n\n/** \n * const counter = createCounter(10)\n * counter() // 10\n * counter() // 11\n * counter() // 12\n */\n```
5
0
['JavaScript']
2
counter
✅| Hello world😎 | Commented
hello-world-commented-by-drontitan-6q8m
This code defines a function called createCounter that takes a number n as input and returns another function. The returned function acts as a counter that star
DronTitan
NORMAL
2023-05-06T02:47:26.830787+00:00
2023-05-06T09:10:30.900724+00:00
825
false
This code defines a function called `createCounter` that takes a number `n` as input and returns another function. The returned function acts as a counter that starts at `n` and increments by 1 each time it is called.\n\nHere is how the code works:\n\n1. The `createCounter` function takes a number `n` as input and initializes a variable `count` to `n-1`.\n2. It then defines and returns a new function that increments the `count` variable by 1 each time it is called, and returns the updated value of `count`.\n3. The returned function has access to the `count` variable through a closure, which means that the `count` variable persists across multiple calls to the function.\n\nFor example, if you call `createCounter(3)`, it will return a new function that starts counting at 3:\n\n```\nvar counter = createCounter(3);\nconsole.log(counter()); // output: 3\nconsole.log(counter()); // output: 4\nconsole.log(counter()); // output: 5\n```\n\nEach time you call the `counter` function, it increments the `count` variable by 1 and returns its updated value.\n```\nvar counter = createCounter(3);\nconsole.log(counter()); // output: 3\nconsole.log(counter()); // output: 4\nconsole.log(counter()); // output: 5\n\n```\nEach time you call the counter function, it increments the count variable by 1 and returns its updated value.\n\n```\n\nvar createCounter = function(n) {\n var count = n-1;\n return function() {\n count++;\n return count;\n };\n};\n\n\n```\n\nupvote if u like
5
0
['TypeScript', 'JavaScript']
3
counter
EASY 1 line Javascript Solution - Explained Solution
easy-1-line-javascript-solution-explaine-13yb
Intuition\nThe magic of retaining local variables in "memory" of Javascript Closure should come to mind when seeing such problem where we need to return a funct
atiqueahmedziad
NORMAL
2023-04-20T10:35:29.184630+00:00
2023-04-20T11:33:07.311895+00:00
806
false
# Intuition\nThe magic of retaining local variables in "memory" of Javascript Closure should come to mind when seeing such problem where we need to return a function inside another function and recall something from the memory.\n\n# Approach\nWe pass a value of `n` upon calling the `createCounter` method. The value of `n` is **remembered** by the following anonymous function because when the anonymous function is returned, it took the local variable `n` in its **backpack**/**closure**.\n\n*The closure is a collection of all the variables in scope at the time of creation of the function.*\n\n# Code\n```\n/**\n * @param {number} n\n * @return {Function} counter\n */\nvar createCounter = function(n) {\n return function() {\n return n++;\n };\n};\n\n/** \n * const counter = createCounter(10)\n * counter() // 10\n * counter() // 11\n * counter() // 12\n */\n```
5
0
['JavaScript']
0
counter
createCounter
createcounter-by-rinatmambetov-7fhm
# Intuition \n\n\n\n\n\n\n\n\n\n\n\n# Code\n\n/**\n * @param {number} n\n * @return {Function} counter\n */\nvar createCounter = function (n) {\n let counter
RinatMambetov
NORMAL
2023-04-16T16:39:33.658518+00:00
2023-04-16T16:39:33.658547+00:00
3,007
false
<!-- # Intuition -->\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n<!-- # Approach -->\n<!-- Describe your approach to solving the problem. -->\n\n<!-- # Complexity\n- Time complexity: -->\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n<!-- - Space complexity: -->\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n/**\n * @param {number} n\n * @return {Function} counter\n */\nvar createCounter = function (n) {\n let counter = n;\n return function () {\n return counter++;\n };\n};\n\n/** \n * const counter = createCounter(10)\n * counter() // 10\n * counter() // 11\n * counter() // 12\n */\n```
5
0
['JavaScript']
2
counter
Single Line Code || ✨✨✨
single-line-code-by-user9102in-k9dh
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
user9102In
NORMAL
2023-04-12T16:56:15.974224+00:00
2023-04-12T16:56:15.974264+00:00
4,234
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n/**\n * @param {number} n\n * @return {Function} counter\n */\nvar createCounter = function(n) {\n return function() {\n return n++\n };\n};\n\n/** \n * const counter = createCounter(10)\n * counter() // 10\n * counter() // 11\n * counter() // 12\n */\n```
5
0
['JavaScript']
1
counter
Create count variable
create-count-variable-by-dchooyc-pg5x
Edit: Should use let instead of var\nlet: block scope\nvar: function scope\n\n/**\n * @param {number} n\n * @return {Function} counter\n */\nvar createCounter =
dchooyc
NORMAL
2023-04-11T21:35:54.875700+00:00
2023-04-11T22:09:50.662500+00:00
4,988
false
Edit: Should use ```let``` instead of ```var```\n```let```: block scope\n```var```: function scope\n```\n/**\n * @param {number} n\n * @return {Function} counter\n */\nvar createCounter = function(n) {\n let count = n\n return function() {\n count++\n return count - 1\n };\n};\n\n/** \n * const counter = createCounter(10)\n * counter() // 10\n * counter() // 11\n * counter() // 12\n */\n```
5
0
['JavaScript']
5
counter
JS | "Create Counter Function" | Time Complexity O(1) | 33ms Beats 99.69%
js-create-counter-function-time-complexi-tqz9
---\n\n# Intuition\nThe goal is to implement a counter function that begins at an integer n and increments each time it is called.\n\n# Approach\nDefine a count
user4612MW
NORMAL
2024-08-17T12:51:49.866851+00:00
2024-08-17T12:52:27.544428+00:00
156
false
---\n\n# Intuition\nThe goal is to implement a counter function that begins at an integer n and increments each time it is called.\n\n# Approach\nDefine a counter function that uses a variable to track the current count, starting from a given integer **n**. The function returns another function that increments and returns this count each time it\'s called.\n\n# Complexity\n- **Time Complexity** O(1) Each call is handled in constant time.\n- **Space Complexity** O(1) Uses a fixed amount of extra space.\n\n# Code\n```\n/**\n * @param {number} n\n * @return {Function} counter\n */\n\n\nvar createCounter = function(n) {\n let n_ = n;\n return function() {\n return n_++;\n };\n};\n\n\n/** \n * const counter = createCounter(10)\n * counter() // 10\n * counter() // 11\n * counter() // 12\n */\n```\n\n---
4
0
['JavaScript']
0
counter
[Fully Explained] 1 Line Code with Concept Explanation 🔥| Closures | Arrow Functions | Currying
fully-explained-1-line-code-with-concept-j0qu
Intuition \uD83D\uDCA1\n Describe your first thoughts on how to solve this problem. \nThe goal is simple: start at n and return n + 1 every time the function is
poojagera0_0
NORMAL
2023-05-06T05:13:57.854538+00:00
2023-05-06T05:13:57.854579+00:00
408
false
# Intuition \uD83D\uDCA1\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe goal is simple: start at n and return n + 1 every time the function is called. Easy peasy, right?\n\n# Approach \uD83E\uDD14\n<!-- Describe your approach to solving the problem. -->\nAfter a quick brainstorm, it\'s clear that we need to create a function that can remember its previous state. We\'ll need to initialize the function with an input value of n, and then use a *closure* to keep track of a running count. Each time the function is called, we\'ll increase the count by 1 and return the current count value plus n. With a bit of ES6 syntax, we can create this counter function in just one line of code!\n\n# Concepts \uD83D\uDCDA\n\n### What is a Closure? \n\nAh, closures. They may sound like something you would find in a haunted house, but they\'re actually a fundamental concept in programming. In short, a closure is a function that has access to variables in its outer scope, even after that scope has closed. This means that a closure can "remember" values from the parent function or the global scope, even if those values are no longer in memory. Closures are created whenever a function is defined inside another function and that inner function is returned or passed around as an argument.\n\n### What is an Arrow Function?\n\nArrow functions are a way to write functions in JavaScript that are shorter and easier to read. They use a special arrow symbol (=>) to show that they\'re a function. They work just like regular functions, but there are a few important differences.\n\n- The first difference is that arrow functions don\'t have their own "this" value. This means that they use the "this" value from the function that contains them.\n\n- The second difference is that you can\'t create new objects with arrow functions. So, if you need to make a lot of objects that are all the same, you\'ll need to use a regular function instead.\n\n- Finally, arrow functions don\'t have a name. This means that you can\'t refer to them by name, like you can with regular functions.\n\nArrow functions are really useful when you want to write short, simple functions. They\'re also great for working with arrays in JavaScript, which is something you\'ll learn more about as you continue to learn about programming.\n\n### What is Currying? \n\nCurrying is a programming technique where you break down a function that takes multiple arguments into a series of smaller functions, each of which takes only one argument.\n\n# Complexity Analysis \uD83D\uDC7E\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nThe time complexity of our counter function is constant, or O(1). Each time the function is called, we\'re simply incrementing a counter and returning its value, which takes a constant amount of time regardless of the size of n.\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nThe space complexity of our counter function is also constant, or O(1). We\'re not storing any additional data beyond the input value n and the internal counter, both of which take up a constant amount of memory.\n\n# Code\n```\n/**\n * @param {number} n\n * @return {Function} counter\n */\n \nvar createCounter = n => () => n++; \n\n/** \n * const counter = createCounter(10)\n * counter() // 10\n * counter() // 11\n * counter() // 12\n */\n```
4
0
['JavaScript']
2
counter
JavaScript || Day 2 of 30 Days Challange || ✅✅
javascript-day-2-of-30-days-challange-by-e1uw
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
Shubhamjain287
NORMAL
2023-05-06T04:32:38.996028+00:00
2023-05-06T04:32:38.996063+00:00
1,435
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n/**\n * @param {number} n\n * @return {Function} counter\n */\nvar createCounter = function(n) {\n return function() {\n return n++;\n };\n};\n\n/** \n * const counter = createCounter(10)\n * counter() // 10\n * counter() // 11\n * counter() // 12\n */\n```
4
0
['JavaScript']
1
counter
🔥🔥Easy Simple JavaScript Solution 🔥🔥
easy-simple-javascript-solution-by-motah-l03v
\n\n/**\n * @param {number} n\n * @return {Function} counter\n */\nvar createCounter = function(n) {\n let counter=n;\n return function() {\n retur
Motaharozzaman1996
NORMAL
2023-04-18T04:53:40.508021+00:00
2023-04-18T04:53:40.508091+00:00
1,517
false
\n```\n/**\n * @param {number} n\n * @return {Function} counter\n */\nvar createCounter = function(n) {\n let counter=n;\n return function() {\n return counter++;\n \n };\n};\n\n/** \n * const counter = createCounter(10)\n * counter() // 10\n * counter() // 11\n * counter() // 12\n */\n```
4
0
['JavaScript']
0
counter
Single Line Code
single-line-code-by-ankita2905-vb2g
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
Ankita2905
NORMAL
2023-10-24T05:58:10.489522+00:00
2023-10-24T05:58:10.489570+00:00
387
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n/**\n * @param {number} n\n * @return {Function} counter\n */\nvar createCounter = function(n) {\n return function() {\n return n++\n };\n};\n\n/** \n * const counter = createCounter(10)\n * counter() // 10\n * counter() // 11\n * counter() // 12\n */\n```
3
0
['JavaScript']
1
counter
Solution with explanation
solution-with-explanation-by-tmg_bijay-fdqn
Explanation\nThe first time counter is called, it calls the function(n) and just returns the inner function and do nothing. Now after this, everytime the counte
Tmg_Bijay
NORMAL
2023-09-06T12:39:05.469524+00:00
2023-09-06T12:39:05.469543+00:00
370
false
# Explanation\nThe first time counter is called, it calls the `function(n)` and just returns the inner function and do nothing. Now after this, everytime the counter is called, it calls the inner function that was returned from the first call and remembers the argument `n` passed and increments it in every calls.\n\n# Code\n```\n/**\n * @param {number} n\n * @return {Function} counter\n */\nvar createCounter = function(n) {\n\n return function() {\n return n++;\n };\n};\n\n/** \n * const counter = createCounter(10)\n * counter() // 10\n * counter() // 11\n * counter() // 12\n */\n```
3
0
['JavaScript']
1
counter
Easy to understand || JS
easy-to-understand-js-by-yashwardhan24_s-7ml2
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
yashwardhan24_sharma
NORMAL
2023-05-07T04:51:47.354164+00:00
2023-05-07T04:51:47.354189+00:00
655
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n/**\n * @param {number} n\n * @return {Function} counter\n */\nvar createCounter = function(n) {\n return function() {\n return n++;\n };\n};\n\n/** \n * const counter = createCounter(10)\n * counter() // 10\n * counter() // 11\n * counter() // 12\n */\n```
3
0
['JavaScript']
0
counter
✅Day-2 || 30-Days-JS-Challenge || Best Editorial || Everything Explained || Easy to understand ||🔥
day-2-30-days-js-challenge-best-editoria-ygah
Intuition\n1.The createCounter() function is designed to create a counter function that maintains and increments a specific value (n).\n2.By returning a nested
krishna_6431
NORMAL
2023-05-06T17:59:45.792211+00:00
2023-05-06T17:59:45.792241+00:00
82
false
# Intuition\n1.The $$createCounter()$$ function is designed to create a counter function that maintains and increments a specific value $$(n)$$.\n2.By returning a nested function, the $$createCounter()$$ function encapsulates the value $$n$$ within the returned counter function.\n3.Each time the counter function is invoked, it increments $$n$$ by 1 and returns the previous value of $$n$$.\n\n# Approach\n1.The createCounter function takes an initial value $$n$$ as a parameter.\n2.It returns a nested function that acts as the counter function.\n3.The counter function increments n using the post-increment operator $$++$$ and assigns the updated value to the variable $$ans$$.\n4.The counter function returns the previous value of $$n$$, which is stored in $$ans$$. \n\n# Complexity\n- Time complexity:\nThe time complexity of creating the counter function using $$createCounter()$$ is constant, $$O(1)$$, as it simply returns a nested function and does not involve any iterative or recursive operations.\nThe time complexity of invoking the counter function is also constant, $$O(1)$$, as it performs a single operation of incrementing $$n$$ and returning a value.(atmost $$1000$$ calls given in constraint)\n\n- Space complexity:\nThe space complexity of the createCounter function is constant, $$O(1)$$, as it does not create any data structures or variables that scale with the input size.\nThe space complexity of the counter function is also constant, $$O(1)$$, as it only uses a single variable $$(ans)$$ to store the updated value of $$n$$.\n\n# Code\n```\n/**\n * @param {number} n\n * @return {Function} counter\n */\nvar createCounter = function(n) {\n return function() {\n //creating answer variable\n //postincrementing n after assigning to ans variable\n var ans = (n++);\n //return ans\n return ans;\n };\n};\n\n/** \n * const counter = createCounter(10)\n * counter() // 10\n * counter() // 11\n * counter() // 12\n */\n```\n$$Please \\space Upvote \\space My \\space Solution \\space if \\space You \\space Liked \\space it..$$\n![abc.png](https://assets.leetcode.com/users/images/8c23d533-3ba8-4e4f-b081-436f1bd0e5c5_1683395752.0296404.png)\n\n$$Thank \\space you \\space so \\space much$$\n
3
0
['JavaScript']
1
counter
Using post increment
using-post-increment-by-harsh_patell21-6e46
\n\n\n var createCounter = function(n) {\n return function() {\n return n++;\n };\n };
harsh_patell21
NORMAL
2023-05-06T12:01:35.801054+00:00
2023-05-06T12:01:35.801090+00:00
38
false
\n\n\n var createCounter = function(n) {\n return function() {\n return n++;\n };\n };
3
0
['JavaScript']
0
counter
Easy one liner O(1) TC javascript solution!! ✔️✔️
easy-one-liner-o1-tc-javascript-solution-uhcd
Intuition\nBasic implementation\n Describe your first thoughts on how to solve this problem. \n\n# Approach\nBasic post increment n every time when you return i
__AKASH_SINGH___
NORMAL
2023-05-06T07:23:41.727838+00:00
2023-05-06T07:23:41.727873+00:00
367
false
# Intuition\nBasic implementation\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nBasic post increment n every time when you return it\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(1)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n/**\n * @param {number} n\n * @return {Function} counter\n */\nvar createCounter = function(n) {\n return function() {\n return n++;\n };\n};\n//Please upvote if you like the solution!!!\u2714\uFE0F\u2714\uFE0F\n```
3
0
['JavaScript']
1
counter
Java Script Solution for Counter Problem
java-script-solution-for-counter-problem-rpkv
Intuition\n Describe your first thoughts on how to solve this problem. \nThe intuition behind the solution is to create a closure that returns a function that i
Aman_Raj_Sinha
NORMAL
2023-05-06T06:38:06.124458+00:00
2023-05-06T06:38:06.124489+00:00
551
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe intuition behind the solution is to create a closure that returns a function that increments a counter variable n each time it is called.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nThe approach is to define a function createCounter that takes an initial value n as input and returns a function that increments n each time it is called. The returned function is a closure that has access to the n variable defined in the outer function.\nWhen the returned function is called, it increments n by 1 and returns the new value of n. This allows us to create a counter that starts at a given value and increments by 1 each time it is called.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nThe time complexity of the createCounter function is O(1), as it simply returns a function without performing any complex operations.\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nThe space complexity of the createCounter function is O(1), as it only defines a single variable n and returns a function that has access to it.\n\n# Code\n```\n/**\n * @param {number} n\n * @return {Function} counter\n */\nvar createCounter = function(n) {\n return function() {\n return n++;\n };\n};\n\n/** \n * const counter = createCounter(10)\n * counter() // 10\n * counter() // 11\n * counter() // 12\n */\n```
3
0
['JavaScript']
0
counter
simple counter no logic
simple-counter-no-logic-by-nikunjrathod2-05g0
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
NikunjRathod200
NORMAL
2023-05-06T05:27:24.956951+00:00
2023-05-06T05:27:24.956981+00:00
544
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n/**\n * @param {number} n\n * @return {Function} counter\n */\nvar createCounter = function(n) {\n return function() {\n return n++\n };\n};\n\n/** \n * const counter = createCounter(10)\n * counter() // 10\n * counter() // 11\n * counter() // 12\n */\n```
3
0
['JavaScript']
0
counter
Two approaches using count (beats 90.25% in memory) | postfix(beats 100% in time) beginner friendly
two-approaches-using-count-beats-9025-in-1e1y
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
abhishekvallecha20
NORMAL
2023-05-06T04:59:57.034274+00:00
2023-05-29T18:57:27.123720+00:00
1,751
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n/**\n * @param {number} n\n * @return {Function} counter\n */\nvar createCounter = function(n) {\n return function() {\n return n++;\n };\n};\n\n/** \n * const counter = createCounter(10)\n * counter() // 10\n * counter() // 11\n * counter() // 12\n */\n```\n\n# Code\n```\n /**\n * @param {number} n\n * @return {Function} counter\n */\nvar createCounter = function(n) {\n let count = n\n return function() {\n const currCount = count;\n count += 1;\n return currCount;\n };\n};\n\n\n\n/** \n * const counter = createCounter(10)\n * counter() // 10\n * counter() // 11\n * counter() // 12\n */\n```
3
0
['JavaScript']
2
counter
Very simple and easy to understand !!! Just using incrementing
very-simple-and-easy-to-understand-just-qec77
\n# Code\n\n/**\n * @param {number} n\n * @return {Function} counter\n */\nvar createCounter = function(n) {\n return function() {\n return n++\n }
AzamatAbduvohidov
NORMAL
2023-05-06T04:02:45.634556+00:00
2023-05-06T04:02:45.634617+00:00
616
false
\n# Code\n```\n/**\n * @param {number} n\n * @return {Function} counter\n */\nvar createCounter = function(n) {\n return function() {\n return n++\n };\n};\n\n/** \n * const counter = createCounter(10)\n * counter() // 10\n * counter() // 11\n * counter() // 12\n */\n```
3
0
['JavaScript']
3
counter
Simplest code ever
simplest-code-ever-by-deepu_7541-d121
Intuition\nWe just have to return the number that will work as a counter.\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe
deepu_7541
NORMAL
2023-04-13T16:12:10.104232+00:00
2023-04-13T16:12:10.104278+00:00
546
false
# Intuition\nWe just have to return the number that will work as a counter.\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n/**\n * @param {number} n\n * @return {Function} counter\n */\nvar createCounter = function(n) {\n return function() {\n return n++;\n };\n};\n\n/** \n * const counter = createCounter(10)\n * counter() // 10\n * counter() // 11\n * counter() // 12\n */\n```
3
0
['JavaScript']
1