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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
maximum-trailing-zeros-in-a-cornered-path
|
[Python] Self-explain code using Prefix sum
|
python-self-explain-code-using-prefix-su-5gqo
|
Intuition\nSince product of numbers and its trailing zeros will never go down with additional numbers. The problem becomes "for each point (i,j) in the grid, co
|
jimmywzm
|
NORMAL
|
2023-10-11T03:53:45.043680+00:00
|
2023-10-11T03:53:45.043703+00:00
| 12 | false |
# Intuition\nSince product of numbers and its trailing zeros will never go down with additional numbers. The problem becomes "**for each point (i,j) in the grid, compute the max trailling zeros of product of 4 L-shape pathes(till boundary). Then find the max num of trailling zeros over all points**" That\'s definately a prefix sum problem.\n\n# Approach\nTrailing zeros can be calculated by the min count of factor 2 and factor 5. Hence, we can maintain a tup of counts of factor 2 and factor 5 and calculate prefix sum. Than scan over the grid, ultilize the prefix sums to get the max.\n\nThe code below create a class for demostration(though slow down the caculation). It also minimize the memory needed to hold prefix sum. Other parts are self-explianed.\n\n# Complexity\n- Time complexity: O(mn)\n\n- Space complexity: O(n)\n (Ignore the ngrid which cab be transferred on the fly)\n\n# Code\n```\nclass Solution:\n def maxTrailingZeros(self, grid: List[List[int]]) -> int:\n class BaseTup:\n def __init__(self, a=0, b=0):\n self.a, self.b = a, b\n\n @classmethod\n def from_num(cls, n): \n c2 = c5 = 0\n while n and n%2==0:\n c2 += 1\n n = n>>1\n while n and n%5==0:\n c5 += 1\n n //= 5\n return BaseTup(c2, c5)\n\n @classmethod\n def sum(cls, iterable):\n return sum(iterable, start = BaseTup())\n\n def __add__(self, o):\n return BaseTup(self.a + o.a, self.b + o.b)\n\n def __sub__(self, o):\n return BaseTup(self.a - o.a, self.b - o.b)\n\n @property\n def trail_zeros(self):\n return min(self.a, self.b)\n\n \n m,n = len(grid), len(grid[0])\n ngrid = [[ BaseTup.from_num(grid[i][j]) for j in range(n)] for i in range(m)]\n\n up_sum = [BaseTup() for _ in range(n)]\n down_sum = [BaseTup.sum(ngrid[i][j] for i in range(m)) for j in range(n)]\n\n zmax = 0\n for i in range(m):\n rsum = BaseTup.sum(ngrid[i])\n lsum = BaseTup()\n for j in range(n):\n t = ngrid[i][j]\n lsum += t\n down_sum[j] -= t\n\n zmax = max(zmax, \n (lsum+up_sum[j]).trail_zeros,\n (rsum+up_sum[j]).trail_zeros,\n (lsum+down_sum[j]).trail_zeros,\n (rsum+down_sum[j]).trail_zeros)\n\n rsum -= t\n up_sum[j] += t\n \n return zmax\n\n```
| 0 | 0 |
['Python3']
| 0 |
maximum-trailing-zeros-in-a-cornered-path
|
C# Solution (using operators and some tricks)
|
c-solution-using-operators-and-some-tric-ekz7
|
Code\n\npublic class Solution\n{\n public int MaxTrailingZeros(int[][] grid)\n {\n var m = grid.Length;\n var n = grid[0].Length;\n var z = new Zeros
|
BrutalReviewer
|
NORMAL
|
2023-10-07T21:25:01.852552+00:00
|
2023-10-07T21:25:01.852570+00:00
| 8 | false |
# Code\n```\npublic class Solution\n{\n public int MaxTrailingZeros(int[][] grid)\n {\n var m = grid.Length;\n var n = grid[0].Length;\n var z = new Zeros[m, n];\n for (var i = 0; i < m; i++)\n for (var j = 0; j < n; j++)\n z[i, j] = new Zeros(grid[i][j]);\n var rowSum = new Zeros[m, n];\n var colSum = new Zeros[m, n];\n for (var i = 0; i < m; i++)\n {\n rowSum[i, 0] = z[i, 0];\n for (var j = 1; j < n; j++)\n rowSum[i, j] = rowSum[i, j - 1] + z[i, j];\n }\n for (var j = 0; j < n; j++)\n {\n colSum[0, j] = z[0, j];\n for (var i = 1; i < m; i++)\n colSum[i, j] = colSum[i - 1, j] + z[i, j];\n }\n var result = 0;\n for (var i = 0; i < m; i++)\n for (var j = 0; j < n; j++)\n {\n result = Max(result,\n rowSum[i, j] + colSum[i, j] - z[i, j],\n rowSum[i, n - 1] - rowSum[i, j] + colSum[i, j],\n rowSum[i, j] + colSum[m - 1, j] - colSum[i, j],\n rowSum[i, n - 1] - rowSum[i, j] + colSum[m - 1, j] - colSum[i, j] + z[i, j]);\n }\n return result;\n }\n\n private static int Max(params int[] values) => values.Max();\n\n private struct Zeros\n {\n private readonly int _twos;\n private readonly int _fives;\n\n private static int NumCount(int n, int x)\n {\n var count = 0;\n while (n % x == 0)\n {\n count++;\n n /= x;\n }\n return count;\n }\n\n public static Zeros operator +(Zeros x, Zeros y) => new(x._twos + y._twos, x._fives + y._fives);\n public static Zeros operator -(Zeros x, Zeros y) => new(x._twos - y._twos, x._fives - y._fives);\n\n public static implicit operator int(Zeros x) => Math.Min(x._twos, x._fives);\n\n private Zeros(int twos, int fives)\n {\n _twos = twos;\n _fives = fives;\n }\n\n public Zeros(int value)\n : this(NumCount(value, 2), NumCount(value, 5))\n {\n }\n }\n}\n```
| 0 | 0 |
['C#']
| 0 |
maximum-trailing-zeros-in-a-cornered-path
|
Python3 Vectorized Solution
|
python3-vectorized-solution-by-archieger-srax
|
I hope this answer is helpful to those who prefer more formal explanations (like myself).\n___\n# Intuition\n Describe your first thoughts on how to solve this
|
archiegertsman
|
NORMAL
|
2023-07-30T03:56:54.719334+00:00
|
2023-07-30T04:20:54.927500+00:00
| 9 | false |
I hope this answer is helpful to those who prefer more formal explanations (like myself).\n___\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nI made the following two observations:\n1. Let $g(x)$ denote the number of trailing zeros of a number $x$. Then \n$g(x) = \\min_{p\\in\\{2,5\\}} f(x,p),$ \nwhere $f(x, p)$ is the number of times that prime number $p$ appears in the prime factorization of $x$.\n2. The solution can always be represented by a cornered path which extends all the way to the edges of the grid. This is because the entries are non-negative, and so adding more cells can never harm the solution.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nDefine a _leg_ $(i,j,d)$ to be a path of cells from (_excluding_) $(i,j)$ to the edge of the grid, following direction $d\\in\\{{\\rm up,down,left,right}\\}$. WLOG, we only consider cornered paths which extend all the way to the edges of the grid, so that each cornered path can be decomposed into a corner and two legs. We encode each cornered path by a tuple $(i,j,d_1,d_2)$, where $(i,j)$ is the location of the path\'s corner, and $(d_1,d_2)$ are the directions of the its legs, $(i,j,d_1)$ and $(i,j,d_2)$.\n\nDefine the _gain_ $g(\\pi)$ of $\\pi$ to be the number of trailing zeros in the product of the path, i.e. $g(\\pi) = g(\\Pi_{ij\\in\\pi}x_{ij})$, and let $f(\\pi, p) = \\sum_{ij\\in\\pi} f(x_{ij}, p)$ be the number of times prime number $p$ appears along a path $\\pi$. Then,\n$g(\\pi) = g(\\Pi_{ij\\in\\pi}x_{ij}) \\\\ = \\min_{p\\in\\{2,5\\}} f(\\Pi_{ij\\in\\pi}x_{ij}, p) \\\\ = \\min_{p\\in\\{2,5\\}} \\sum_{ij\\in\\pi} f(x_{ij}, p) \\\\ = \\min_{p\\in\\{2,5\\}} f(\\pi, p).$\nOur objective is to find a cornered path $\\pi$ which maximizes $g(\\pi)$. First, we need to compute $f(\\pi, p)$ for all cornered paths $\\pi$ and $p\\in\\{2,5\\}$.\n\nNotice that, for a cornered path, $\\pi=(i,j,d_1,d_2)$, the quantity $f(\\pi,p)$ can be decomposed over $\\pi$\'s corner and two legs:\n$f((i,j,d_1,d_2), p) = f(x_{ij}, p) + f((i,j,d_1), p) + f((i,j,d_2), p).$\n\nThese leg counts, $f((i,j,d), p)$, are our building blocks, so I computed them for each possible leg $(i,j,d)$. Since a leg may be a sub-leg of a longer leg, I stored and reused intermediate results in a dynamic programming style. I then used these leg counts to compute $f(\\pi, 2)$ and $f(\\pi, 5)$ for each possible cornered path $\\pi$, which together yield $g(\\pi)$. Finally, I computed $\\max_\\pi g(\\pi)$ by searching over all cornered paths $\\pi$. Crucially, I vectorized this search over $(i,j)$ using NumPy; without doing so, my solution exceeded the time limit.\n\n# Complexity\n- Time complexity: $O(mn)$, because $O(1)$ visits per cell\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $O(mn)$, because $O(1)$ values stored per cell\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nimport numpy as np\n\n# directions\nU = 0 # Up\nD = 1 # Down\nL = 2 # Left\nR = 3 # Right\nN_dir = 4\n\n# factors\nT = 0 # Two\nF = 1 # Five\nN_fac = 2\n\ndef f(x, p):\n \'\'\'returns the highest power of `p` that divides `x`\'\'\'\n c = 0\n while x % p == 0:\n c += 1\n x //= p\n return c\n\nclass Solution:\n def maxTrailingZeros(self, grid: List[List[int]]) -> int:\n m, n = len(grid), len(grid[0])\n grid = np.array(grid)\n\n # y[i, j, p] = \n # highest power of `p` that divides `grid[i, j]`\n y = np.zeros((m, n, N_fac), dtype=int)\n for i in range(m):\n for j in range(n):\n y[i, j, T] = f(grid[i, j], 2)\n y[i, j, F] = f(grid[i, j], 5)\n\n # x[i, j, d, p] = \n # count of times that `p` appears in leg `(i,j,d)`\n x = np.zeros((m, n, N_dir, N_fac), dtype=int)\n for i in range(m):\n for j in range(n):\n if i > 0:\n x[i, j, U] = y[i-1, j] + x[i-1, j, U]\n x[m-1-i, j, D] = y[m-i, j] + x[m-i, j, D]\n if j > 0:\n x[i, j, L] = y[i, j-1] + x[i, j-1, L]\n x[i, n-1-j, R] = y[i, n-j] + x[i, n-j, R]\n\n # the cornered path\'s legs can be oriented in one of four ways\n path_orientations = [(U,R), (U,L), (D,R), (D,L)]\n\n # for each orientation `(d1, d2)`, \n # for each corner `(i, j)` (vectorized):\n # find the the number of trailing zeros in the product\n # of the path `(i, j, d1, d2)`.\n # max-reduce over corners (vectorized)\n # max-reduce over orientations.\n return max(\n (y + x[:, :, d1] + x[:, :, d2]).min(-1).max()\n for d1, d2 in path_orientations\n )\n```
| 0 | 0 |
['Python3']
| 0 |
maximum-trailing-zeros-in-a-cornered-path
|
[JavaScript] Simple Array
|
javascript-simple-array-by-tmohan-xkz8
|
Complexity\n- Time complexity: O(nn)\n- Space complexity: O(nn)\n\n# Code\n\nvar maxTrailingZeros = function(grid) {\n const n = grid.length, m = grid[0].len
|
tmohan
|
NORMAL
|
2023-04-19T12:22:21.668403+00:00
|
2023-04-19T12:23:53.547508+00:00
| 18 | false |
# Complexity\n- Time complexity: $$O(n*n)$$\n- Space complexity: $$O(n*n)$$\n\n# Code\n```\nvar maxTrailingZeros = function(grid) {\n const n = grid.length, m = grid[0].length;\n const rowWise = Array.from({ length: n }, () => Array(m)),\n columnWise = Array.from({ length: n }, () => Array(m));\n\n for (let i = 0; i < n; i++) {\n for (let j = 0; j < m; j++) {\n grid[i][j] = [getFactorsCount(grid[i][j], 2), getFactorsCount(grid[i][j], 5)];\n rowWise[i][j] = [(j > 0 ? rowWise[i][j - 1][0] : 0) + grid[i][j][0],\n (j > 0 ? rowWise[i][j - 1][1] : 0) + grid[i][j][1]];\n columnWise[i][j] = [(i > 0 ? columnWise[i - 1][j][0] : 0) + grid[i][j][0],\n (i > 0 ? columnWise[i - 1][j][1] : 0) + grid[i][j][1]];\n }\n }\n \n function getFactorsCount(value, factor) {\n let count = 0;\n while(value % factor == 0) count++, value /= factor;\n return count;\n }\n\n let maxTrailingZeros = 0;\n\n for (let i = 0; i < n; i++) {\n for (let j = 0; j < m; j++) {\n const top = columnWise[i - 1]?.[j] ?? [0, 0];\n const left = rowWise[i][j - 1] ?? [0, 0];\n const right = [rowWise[i].at(-1)[0] - rowWise[i][j][0],\n rowWise[i].at(-1)[1] - rowWise[i][j][1]];\n const bottom = [columnWise.at(-1)[j][0] - columnWise[i][j][0],\n columnWise.at(-1)[j][1] - columnWise[i][j][1]];\n\n const allDirections = [top, left, right, bottom]; \n for (let k = 0; k < 4; k++) {\n for (let l = 0; l < 4; l++) {\n if (k == l) continue;\n maxTrailingZeros = Math.max(maxTrailingZeros, \n Math.min(allDirections[k][0] + allDirections[l][0] + grid[i][j][0], \n allDirections[k][1] + allDirections[l][1] + grid[i][j][1]));\n }\n }\n }\n }\n\n return maxTrailingZeros;\n};\n```
| 0 | 0 |
['Array', 'Prefix Sum', 'JavaScript']
| 0 |
maximum-trailing-zeros-in-a-cornered-path
|
C++ | Prefix Sum
|
c-prefix-sum-by-pikachuu-b8bw
|
Code\n\nclass Solution {\n int numOfFact(int n, int x) {\n int count = 0;\n while(n % x == 0) {\n count++;\n n /= x;\n
|
pikachuu
|
NORMAL
|
2023-03-29T16:54:14.971136+00:00
|
2023-03-29T16:54:14.971185+00:00
| 137 | false |
# Code\n```\nclass Solution {\n int numOfFact(int n, int x) {\n int count = 0;\n while(n % x == 0) {\n count++;\n n /= x;\n }\n return count;\n }\npublic:\n int maxTrailingZeros(vector<vector<int>>& grid) {\n int m = grid.size(), n = grid[0].size(), ans = 0;\n vector<vector<pair<int, int>>> h(m + 1, vector<pair<int, int>>(n + 1));\n vector<vector<pair<int, int>>> v(m + 1, vector<pair<int, int>>(n + 1));\n for(int i = 0; i < m; i++) {\n for(int j = 0; j < n; j++) {\n h[i + 1][j + 1].first = h[i + 1][j].first + numOfFact(grid[i][j], 2); \n h[i + 1][j + 1].second = h[i + 1][j].second + numOfFact(grid[i][j], 5); \n v[i + 1][j + 1].first = v[i][j + 1].first + numOfFact(grid[i][j], 2); \n v[i + 1][j + 1].second = v[i][j + 1].second + numOfFact(grid[i][j], 5); \n }\n }\n pair<int, int> h1, h2, v1, v2;\n for(int i = 1; i <= m; i++) {\n for(int j = 1; j <= n; j++) {\n h1 = {h[i][j - 1].first, h[i][j - 1].second};\n h2 = {h[i][n].first - h[i][j].first, h[i][n].second - h[i][j].second};\n v1 = {v[i][j].first, v[i][j].second};\n v2 = {v[m][j].first - v[i - 1][j].first, v[m][j].second - v[i - 1][j].second};\n ans = max(ans, min(v1.first + h1.first, v1.second + h1.second));\n ans = max(ans, min(v1.first + h2.first, v1.second + h2.second));\n ans = max(ans, min(v2.first + h1.first, v2.second + h1.second));\n ans = max(ans, min(v2.first + h2.first, v2.second + h2.second));\n }\n }\n return ans;\n }\n};\n```
| 0 | 0 |
['Matrix', 'Prefix Sum', 'C++']
| 0 |
maximum-trailing-zeros-in-a-cornered-path
|
1464 ms
|
1464-ms-by-0x81-j7uk
|
ruby\ndef max_trailing_zeros v\n y, x = v.size, v[0].size\n m, h = 0, Array.new(y) { [0] * x }\n for i in 0...y\n h2, h5 = 0, 0\n for j i
|
0x81
|
NORMAL
|
2023-03-07T22:17:49.585782+00:00
|
2023-03-07T22:17:49.585828+00:00
| 7 | false |
```ruby\ndef max_trailing_zeros v\n y, x = v.size, v[0].size\n m, h = 0, Array.new(y) { [0] * x }\n for i in 0...y\n h2, h5 = 0, 0\n for j in 0...x\n d = v[i][j]\n x2, x5 = 0, 0\n (d >>= 1; x2 += 1) while (d & 1).zero?\n (d /= 5; x5 += 1) while (d % 5).zero?\n h[i][j] = [h2 += x2, h5 += x5]\n if i > 0\n p2, p5 = *v[i - 1][j]\n x2 += p2; x5 += p5\n end\n v[i][j] = [x2, x5]\n end\n end\n for i in 0...y\n r2, r5 = *h[i][-1]\n for j in 0...x\n v2, v5 = *v[-1][j]\n cv2, cv5 = *v[i][j]\n ch2, ch5 = *h[i][j]\n j > 0 ?\n (lh2, lh5 = *h[i][j - 1]) :\n (lh2, lh5 = 0, 0)\n m = [m,\n [lh2 + cv2,\n lh5 + cv5].min,\n [cv2 + r2 - ch2,\n cv5 + r5 - ch5].min,\n [ch2 + v2 - cv2,\n ch5 + v5 - cv5].min,\n [r2 - lh2 + v2 - cv2,\n r5 - lh5 + v5 - cv5].min\n ].max\n end\n end\n m\nend\n```
| 0 | 0 |
['Ruby']
| 0 |
maximum-trailing-zeros-in-a-cornered-path
|
Python
|
python-by-prem_bio-4c7m
|
\n\nclass Solution:\n def maxTrailingZeros(self, grid) :\n matrix = grid \n self.ans,prefix,suffix = 0,[i[:] for i in matrix ],[i[:] for i in m
|
Prem_Bio
|
NORMAL
|
2023-01-19T18:11:48.789788+00:00
|
2023-01-19T18:11:48.789843+00:00
| 66 | false |
\n```\nclass Solution:\n def maxTrailingZeros(self, grid) :\n matrix = grid \n self.ans,prefix,suffix = 0,[i[:] for i in matrix ],[i[:] for i in matrix ]\n \n def f(n):\n x,y =0,0\n while n%2==0:\n n = n//2\n x+=1\n while n% 5==0:\n n = n // 5\n y+=1\n return x,y\n\n for i in prefix:\n for n,v in enumerate(i):\n if n==0 : i[0] =f(v)\n else:\n x,y = f(v)\n a,b = i[n-1]\n i[n]=x+a,y+b\n\n for i in suffix :\n for n in range(len(i)-1,-1,-1):\n if n == len(i)-1:i[n]=f(i[n])\n else:\n x,y = f(i[n])\n a,b= i[n+1]\n i[n]=x+a,y+b\n\n for j in range(len(matrix[0])):\n two,five =0,0\n for i in range(len(matrix)):\n self.ans = max(self.ans,min(two+prefix[i][j][0],five + prefix[i][j][1]))\n self.ans = max(self.ans , min(two + suffix[i][j][0] , five + suffix[i][j][1]))\n\n x,y = f(matrix[i][j])\n two +=x\n five +=y \n \n two,five = 0,0\n for i in range(len(matrix)-1,-1,-1):\n self.ans = max(self.ans,min(two+prefix[i][j][0],five + prefix[i][j][1]))\n self.ans = max(self.ans , min(two + suffix[i][j][0] , five + suffix[i][j][1]))\n x,y = f(matrix[i][j])\n two +=x\n five +=y \n \n return self.ans \n```
| 0 | 0 |
['Python3']
| 0 |
maximum-trailing-zeros-in-a-cornered-path
|
Simple rust solution
|
simple-rust-solution-by-matthew-ch-mtaj
|
Enumerate corner cells, extend horizontally and vertically. There are four cornered paths to consider for each corner cell. Use prefix sum to quickly calculate
|
matthew-ch
|
NORMAL
|
2022-12-20T12:09:03.673236+00:00
|
2022-12-20T12:09:03.673283+00:00
| 43 | false |
Enumerate corner cells, extend horizontally and vertically. There are four cornered paths to consider for each corner cell. Use prefix sum to quickly calculate zeros for each path.\n\n# Complexity\n- Time complexity:\n$$O(m*n)$$\n\n- Space complexity:\n$$O(m*n)$$\n\n# Code\n```\nimpl Solution {\n pub fn max_trailing_zeros(grid: Vec<Vec<i32>>) -> i32 {\n use std::ops::{Add, Sub};\n\n let m = grid.len();\n let n = grid[0].len();\n\n #[derive(Clone, Copy, Debug, Default)]\n struct Counts {\n count_2: i32,\n count_5: i32,\n }\n\n impl Counts {\n fn zeros(&self) -> i32 {\n self.count_2.min(self.count_5)\n }\n }\n\n impl Add for Counts {\n type Output = Self;\n fn add(self, rhs: Self) -> Self::Output {\n Self {\n count_2: self.count_2 + rhs.count_2,\n count_5: self.count_5 + rhs.count_5,\n }\n }\n }\n\n impl Sub for Counts {\n type Output = Self;\n fn sub(self, rhs: Self) -> Self::Output {\n Self {\n count_2: self.count_2 - rhs.count_2,\n count_5: self.count_5 - rhs.count_5,\n }\n }\n }\n\n let mut prime_count = vec![Counts::default(); 1001];\n for i in 2..=1000 {\n let mut count_2 = 0;\n let mut count_5 = 0;\n let mut k = i;\n while k % 2 == 0 {\n k /= 2;\n count_2 += 1;\n }\n while k % 5 == 0 {\n k /= 5;\n count_5 += 1;\n }\n prime_count[i] = Counts { count_2, count_5 };\n }\n let mut h_acc = vec![vec![Counts::default(); n + 1]; m + 1];\n let mut v_acc = vec![vec![Counts::default(); m + 1]; n + 1];\n\n for row in 0..m {\n for col in 0..n {\n let count = prime_count[grid[row][col] as usize];\n h_acc[row][col + 1] = h_acc[row][col] + count;\n v_acc[col][row + 1] = v_acc[col][row] + count;\n }\n }\n\n let mut res = 0;\n\n for row in 0..m {\n for col in 0..n {\n let top = v_acc[col][row];\n let bottom = v_acc[col][m] - v_acc[col][row + 1];\n let left = h_acc[row][col];\n let right = h_acc[row][n] - h_acc[row][col + 1];\n let current = prime_count[grid[row][col] as usize];\n\n res = res.max(\n (top + left + current).zeros()\n ).max(\n (top + right + current).zeros()\n ).max(\n (bottom + left + current).zeros()\n ).max(\n (bottom + right + current).zeros()\n );\n }\n }\n\n res\n }\n}\n```
| 0 | 0 |
['Rust']
| 0 |
maximum-trailing-zeros-in-a-cornered-path
|
JAVA | Simple Solution
|
java-simple-solution-by-architjain121-4ph1
|
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
|
architjain121
|
NORMAL
|
2022-12-08T16:44:20.668330+00:00
|
2022-12-08T16:44:20.668403+00:00
| 182 | 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: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int maxTrailingZeros(int[][] grid) {\n int[][][] t = new int[grid.length][grid[0].length][8];\n int n = grid.length;\n int m = grid[0].length;\n\n int[][][] tf = new int[n][m][2];\n for(int i = 0; i<n;i++) {\n for(int j = 0 ; j<m ;j++) {\n int two = 0;\n int five = 0;\n int k = grid[i][j];\n while(k%2==0){\n k/=2;\n two++;\n }\n while(k%5==0){\n k/=5;\n five++;\n }\n tf[i][j][0] = two;\n tf[i][j][1] = five;\n }\n }\n for(int i = 0; i<n;i++) {\n int two = 0;\n int five = 0;\n for(int j = 0; j<m;j++) {\n int k = grid[i][j];\n while(k%2 == 0) {\n two++;\n k=k/2;\n }\n while(k%5 == 0) {\n five++;\n k=k/5;\n }\n t[i][j][0] = two;\n t[i][j][1] = five;\n }\n }\n\n\n for(int i = 0; i<n;i++) {\n int two = 0;\n int five = 0;\n for(int j = m-1; j>=0;j--) {\n int k = grid[i][j];\n while(k%2 == 0) {\n two++;\n k=k/2;\n }\n while(k%5 == 0) {\n five++;\n k=k/5;\n }\n t[i][j][2] = two;\n t[i][j][3] = five;\n }\n }\n for(int i = 0; i<m;i++) {\n int two = 0;\n int five = 0;\n for(int j = 0; j<n;j++) {\n int k = grid[j][i];\n while(k%2 == 0) {\n two++;\n k=k/2;\n }\n while(k%5 == 0) {\n five++;\n k=k/5;\n }\n t[j][i][4] = two;\n t[j][i][5] = five;\n }\n }\n for(int i = 0; i<m;i++) {\n int two = 0;\n int five = 0;\n for(int j = n-1; j>=0;j--) {\n int k = grid[j][i];\n while(k%2 == 0) {\n two++;\n k=k/2;\n }\n while(k%5 == 0) {\n five++;\n k=k/5;\n }\n t[j][i][6] = two;\n t[j][i][7] = five;\n }\n }\n int[][] ans = new int[n][m];\n int a = 0;\n for(int i = 0; i<n; i++) {\n for(int j = 0; j<m ;j++) {\n ans[i][j] = Math.max(ans[i][j],Math.min(t[i][j][0] + t[i][j][4] - tf[i][j][0],t[i][j][1] + t[i][j][5] - tf[i][j][1])); //3\n ans[i][j] = Math.max(ans[i][j],Math.min(t[i][j][0] + t[i][j][6]- tf[i][j][0],t[i][j][1] + t[i][j][7]- tf[i][j][1]));\n ans[i][j] = Math.max(ans[i][j],Math.min(t[i][j][2] + t[i][j][4]- tf[i][j][0],t[i][j][3] + t[i][j][5]- tf[i][j][1]));\n ans[i][j] = Math.max(ans[i][j],Math.min(t[i][j][2] + t[i][j][6]- tf[i][j][0],t[i][j][3] + t[i][j][7]- tf[i][j][1]));\n a = Math.max(a,ans[i][j]);\n }\n }\n return a;\n \n }\n}\n```
| 0 | 0 |
['Java']
| 0 |
maximum-trailing-zeros-in-a-cornered-path
|
Java concise and efficient solution; explanation included
|
java-concise-and-efficient-solution-expl-zs0a
|
\nclass Solution {\n \n public int maxTrailingZeros(int[][] grid) {\n \n int rows = grid.length;\n int cols = grid[0].length;\n
|
xychen11214
|
NORMAL
|
2022-10-25T02:55:19.961707+00:00
|
2022-10-25T02:55:19.961750+00:00
| 40 | false |
```\nclass Solution {\n \n public int maxTrailingZeros(int[][] grid) {\n \n int rows = grid.length;\n int cols = grid[0].length;\n \n // twoAndFives[i][j][0] is the number of factor 2 of grid[i][j]\n // twoAndFives[i][j][1] is the number of factor 5 of grid[i][j]\n int[][][] twoAndFives = new int[rows][cols][2];\n \n for (int i = 0; i < rows; i++) {\n for (int j = 0; j < cols; j++) {\n int num = grid[i][j];\n int twos = 0;\n int fives = 0;\n while (num % 2 == 0) {\n num /= 2;\n twos++;\n }\n while (num % 5 == 0) {\n num /= 5;\n fives++;\n }\n twoAndFives[i][j] = new int[] {twos, fives};\n }\n }\n \n int[][] prefixRowTwo = new int[rows][cols+1];\n int[][] prefixRowFive = new int[rows][cols+1];\n \n int[][] prefixColTwo = new int[cols][rows+1];\n int[][] prefixColFive = new int[cols][rows+1];\n\n for (int i = 0; i < rows; i++) {\n for (int j = 0; j < cols; j++) {\n prefixRowTwo[i][j+1] = prefixRowTwo[i][j] + twoAndFives[i][j][0];\n prefixRowFive[i][j+1] = prefixRowFive[i][j] + twoAndFives[i][j][1];\n }\n }\n \n for (int j = 0; j < cols; j++) {\n for (int i = 0; i < rows; i++) {\n prefixColTwo[j][i+1] = prefixColTwo[j][i] + twoAndFives[i][j][0];\n prefixColFive[j][i+1] = prefixColFive[j][i] + twoAndFives[i][j][1];\n }\n }\n \n int max = 0;\n for (int i = 1; i <= rows; i++) {\n for (int j = 1; j <= cols; j++) {\n \n // Path: top-down then turn left\n max = Math.max(max, Math.min(prefixRowTwo[i-1][j] + prefixColTwo[j-1][i-1], prefixRowFive[i-1][j] + prefixColFive[j-1][i-1]));\n \n // Path: bottom-up then turn left\n max = Math.max(max, Math.min(prefixRowTwo[i-1][j] + prefixColTwo[j-1][rows] - prefixColTwo[j-1][i], prefixRowFive[i-1][j] + prefixColFive[j-1][rows] - prefixColFive[j-1][i]));\n \n // Path: top-down then turn right\n max = Math.max(max, Math.min(prefixRowTwo[i-1][cols] - prefixRowTwo[i-1][j] + prefixColTwo[j-1][i], prefixRowFive[i-1][cols] - prefixRowFive[i-1][j] + prefixColFive[j-1][i]));\n \n // Path: bottom-up then turn right\n max = Math.max(max, Math.min(prefixRowTwo[i-1][cols] - prefixRowTwo[i-1][j] + prefixColTwo[j-1][rows] - prefixColTwo[j-1][i-1], prefixRowFive[i-1][cols] -prefixRowFive[i-1][j] + prefixColFive[j-1][rows] - prefixColFive[j-1][i-1]));\n }\n }\n\n return max;\n }\n}\n```
| 0 | 0 |
[]
| 0 |
maximum-trailing-zeros-in-a-cornered-path
|
Efficient Use of Prefix Sums, owing to @votrubac
|
efficient-use-of-prefix-sums-owing-to-vo-lhbd
|
\narray<int, 2> operator+(const array<int, 2> &l, const array<int, 2> &r) { return { l[0] + r[0], l[1] + r[1] }; }\narray<int, 2> operator-(const array<int, 2>
|
OmShivamR24
|
NORMAL
|
2022-10-20T16:39:10.742297+00:00
|
2022-10-20T16:39:10.742344+00:00
| 161 | false |
```\narray<int, 2> operator+(const array<int, 2> &l, const array<int, 2> &r) { return { l[0] + r[0], l[1] + r[1] }; }\narray<int, 2> operator-(const array<int, 2> &l, const array<int, 2> &r) { return { l[0] - r[0], l[1] - r[1] }; }\n\nint pairs(const array<int, 2> &p) { return min(p[0], p[1]); }\n\nclass Solution {\npublic:\n int factors(int i, int f) {\n return i % f ? 0 : 1 + factors(i / f, f);\n }\n \n // https://leetcode.com/problems/maximum-trailing-zeros-in-a-cornered-path/discuss/1955515/Prefix-Sum-of-Factors-2-and-5\n \n int maxTrailingZeros(vector<vector<int>>& grid) {\n \n int m = grid.size(), n = grid[0].size(), res = 0;\n vector<vector<array<int, 2>>> h(m, vector<array<int, 2>>(n + 1)), v(m + 1, vector<array<int, 2>>(n));\n for (int i = 0; i < m; ++i)\n for (int j = 0; j < n; ++j) {\n array<int, 2> f25 = { factors(grid[i][j], 2), factors(grid[i][j], 5) };\n v[i + 1][j] = v[i][j] + f25;\n h[i][j + 1] = h[i][j] + f25;\n }\n for (int i = 0; i < m; ++i)\n for (int j = 0; j < n; ++j) {\n auto v1 = v[i + 1][j], v2 = v[m][j] - v[i][j];\n auto h1 = h[i][j], h2 = h[i][n] - h[i][j + 1];\n res = max({res, pairs(v1 + h1), pairs(v1 + h2), pairs(v2 + h1), pairs(v2 + h2)});\n \n // 4 paths \n // suppose you\'re on (i, j) cell\n // then either you can have vertical_top path + horizantal_right path ( L shaped) OR vertical_top path + horizantal_left path ( mirrored L)\n // OR vertical_down + hori_right OR vertical_down + hori_left\n // \n \n }\n return res;\n }\n};\n```
| 0 | 0 |
['C']
| 0 |
maximum-trailing-zeros-in-a-cornered-path
|
CPP || 99 %faster and 99%memory
|
cpp-99-faster-and-99memory-by-aman77pand-xwit
|
class Solution {\npublic:\n \n pairfind_factor(int n)\n { \n int two=0,five=0;\n while(n%5==0)\n {\n five++;\n
|
aman77pandey
|
NORMAL
|
2022-07-29T09:52:35.375398+00:00
|
2022-07-29T09:52:35.375439+00:00
| 115 | false |
class Solution {\npublic:\n \n pair<int,int>find_factor(int n)\n { \n int two=0,five=0;\n while(n%5==0)\n {\n five++;\n n/=5;\n }\n \n while(n%2==0)\n {\n two++;\n n/=2;\n \n }\n \n return {two,five};\n }\n int maxTrailingZeros(vector<vector<int>>& grid) \n {\n int n=grid.size(),m=grid[0].size();\n \n int factor[n][m][2];\n \n for(int i=0;i<n;i++)\n {\n for(int j=0;j<m;j++)\n { \n pair<int,int>p=find_factor(grid[i][j]);\n factor[i][j][0]=p.first;\n factor[i][j][1]=p.second;\n }\n }\n \n \n int row[n][m][2];\n int col[n][m][2];\n \n for(int i=0;i<n;i++)\n {\n int two=0,five=0;\n \n for(int j=0;j<m;j++)\n {\n row[i][j][0]=two+factor[i][j][0];\n two=row[i][j][0];\n row[i][j][1]=five+factor[i][j][1];\n five=row[i][j][1];\n }\n }\n \n for(int j=0;j<m;j++)\n {\n int two=0,five=0;\n \n for(int i=0;i<n;i++)\n {\n col[i][j][0]=two+factor[i][j][0];\n two=col[i][j][0];\n col[i][j][1]=five+factor[i][j][1];\n five=col[i][j][1];\n }\n }\n \n \n \n \n \n int ans=0;\n \n for(int i=0;i<n;i++)\n {\n for(int j=0;j<m;j++)\n {\n int a=(i>0)?col[i-1][j][0]:0;\n int b=(i!=n-1)?col[n-1][j][0]-col[i][j][0]:0;\n int c=(i>0)?col[i-1][j][1]:0;\n int d=(i!=n-1)?col[n-1][j][1]-col[i][j][1]:0;\n \n int p=(j>0)?row[i][j-1][0]:0;\n int q=(j!=m-1)?row[i][m-1][0]-row[i][j][0]:0;\n int r=(j>0)?row[i][j-1][1]:0;\n int s=(j!=m-1)?row[i][m-1][1]-row[i][j][1]:0;\n \n \n ans=max(ans,min(a+p+factor[i][j][0],c+r+factor[i][j][1]));\n ans=max(ans,min(a+q+factor[i][j][0],c+s+factor[i][j][1]));\n ans=max(ans,min(b+p+factor[i][j][0],d+r+factor[i][j][1]));\n ans=max(ans,min(b+q+factor[i][j][0],d+s+factor[i][j][1]));\n \n \n }\n \n }\n \n \n return ans;\n }\n};
| 0 | 0 |
[]
| 0 |
maximum-trailing-zeros-in-a-cornered-path
|
C++ || EXPLANATION || EASY ||
|
c-explanation-easy-by-ksheersagaragrawal-lov7
|
We can then treat each cell as the elbow point and calculate the largest minimum (sum of 2 exponents, sum of 5 exponents) from the combination of top-left, top-
|
ksheersagaragrawal
|
NORMAL
|
2022-06-28T04:24:51.613959+00:00
|
2022-06-28T04:25:41.624310+00:00
| 130 | false |
**We can then treat each cell as the elbow point and calculate the largest minimum (sum of 2 exponents, sum of 5 exponents) from the combination of top-left, top-right, bottom-left and bottom-right.**\n\n```\nclass Solution {\npublic:\n int pow2(int num)\n { int cnt=0;\n while(num%2==0)\n {\n cnt=cnt+1;\n num=num/2;\n }\n return cnt;\n }\n \n int pow5(int num)\n { int cnt=0;\n while(num%5==0)\n {\n cnt=cnt+1;\n num=num/5;\n }\n return cnt;\n }\n \n int ans=0;\n \n int maxTrailingZeros(vector<vector<int>>& grid) {\n \n vector<pair<int, int>> up (grid[0].size(), std::make_pair(0,0));\n vector<pair<int, int>> dwn (grid[0].size(), std::make_pair(0,0));\n vector<pair<int, int>> rht (grid.size(), std::make_pair(0,0));\n vector<pair<int, int>> lft (grid.size(), std::make_pair(0,0));\n \n for(int i=0;i<grid.size();i=i+1)\n { \n int a=0;\n int b=0;\n for(int j=grid[0].size()-1;j>=0;j=j-1)\n {\n a=a+pow2(grid[i][j]);\n b=b+pow5(grid[i][j]);\n }\n rht[i].first=a;\n rht[i].second=b;\n ans=max(ans,min(a,b));\n }\n \n for(int i=0;i<grid[0].size();i=i+1)\n { \n int a=0;\n int b=0;\n for(int j=grid.size()-1;j>=0;j=j-1)\n {\n a=a+pow2(grid[j][i]);\n b=b+pow5(grid[j][i]);\n }\n dwn[i].first=a;\n dwn[i].second=b; \n ans=max(ans,min(a,b));\n }\n \n \n for(int i=0;i<grid.size();i=i+1)\n {\n for(int j=0;j<grid[0].size();j=j+1)\n {\n \n int a=pow2(grid[i][j]);\n int b=pow5(grid[i][j]);\n rht[i].first=rht[i].first-a;\n rht[i].second=rht[i].second-b;\n dwn[j].first=dwn[j].first-a;\n dwn[j].second=dwn[j].second-b;\n \n ans=max(ans,min(rht[i].first+dwn[j].first+a,rht[i].second+dwn[j].second+b));\n ans=max(ans,min(rht[i].first+up[j].first+a,rht[i].second+up[j].second+b));\n ans=max(ans,min(lft[i].first+dwn[j].first+a,lft[i].second+dwn[j].second+b));\n ans=max(ans,min(lft[i].first+up[j].first+a,lft[i].second+up[j].second+b));\n \n lft[i].first=lft[i].first+a;\n lft[i].second=lft[i].second+b; \n up[j].first=up[j].first+a;\n up[j].second=up[j].second+b;\n }\n }\n return ans;\n }\n};\n```\n\n**If you found it helpful, kindly upvote!!!**
| 0 | 0 |
[]
| 0 |
maximum-trailing-zeros-in-a-cornered-path
|
Best C++ solution TC O(N*M) SC O(min(N,M))
|
best-c-solution-tc-onm-sc-ominnm-by-bobs-hdv5
|
\n\ntemplate \nstd::pair operator+(const std::pair &l, const std::pair &r)\n{\n return {l.first + r.first, l.second + r.second};\n}\n\ntemplate \nstd::pair o
|
bobsingh149
|
NORMAL
|
2022-06-18T15:30:23.098542+00:00
|
2022-06-18T15:41:45.387815+00:00
| 95 | false |
\n\ntemplate <typename T, typename U>\nstd::pair<T, U> operator+(const std::pair<T, U> &l, const std::pair<T, U> &r)\n{\n return {l.first + r.first, l.second + r.second};\n}\n\ntemplate <typename T, typename U>\nstd::pair<T, U> operator-(const std::pair<T, U> &l, const std::pair<T, U> &r)\n{\n return {l.first - r.first, l.second - r.second};\n}\n\ntypedef pair<int, int> p;\n\nclass Solution\n{public:\n\n p decompose(int n)\n {\n int two = 0;\n int five = 0;\n\n while (n % 2 == 0)\n {\n two++;\n n /= 2;\n }\n\n while (n % 5 == 0)\n {\n five++;\n n /= 5;\n }\n\n return make_pair(two, five);\n }\n\n\n int maxTrailingZeros(vector<vector<int>> &grid)\n {\n\n vector<p> rows(grid.size(), make_pair(0, 0));\n vector<p> cols(grid[0].size(), make_pair(0, 0));\n\n for (int i = 0; i < grid.size(); i++)\n\n {\n\n for (int j = 0; j < grid[0].size(); j++)\n {\n auto pr = decompose(grid[i][j]);\n rows[i].first += pr.first;\n rows[i].second += pr.second;\n\n cols[j].first += pr.first;\n cols[j].second += pr.second;\n }\n }\n\n vector<p> colstill(grid[0].size(), make_pair(0, 0));\n\n int max0 = 0;\n\n for (int i = 0; i < grid.size(); i++)\n\n {\n p rowtill = make_pair(0, 0);\n\n for (int j = 0; j < grid[0].size(); j++)\n {\n auto a=decompose(grid[i][j]);\n\n auto r = rows[i] - rowtill;\n\n rowtill.first+=a.first;\n rowtill.second+=a.second;\n\n p l = rowtill;\n \n\n auto t = colstill[j];\n auto b = cols[j] - colstill[j];\n b.first-=a.first;\n b.second-=a.second;\n \n\n int tz1 = min(l.first + t.first, l.second + t.second);\n int tz2 = min(l.first + b.first, l.second + b.second);\n int tz3 = min(r.first + t.first, r.second + t.second);\n int tz4 = min(r.first + b.first, r.second + b.second);\n\n max0 = max(max0, tz1);\n max0 = max(max0, tz2);\n max0 = max(max0, tz3);\n max0 = max(max0, tz4);\n\n colstill[j].first+=a.first;\n colstill[j].second+=a.second;\n }\n }\n\n return max0;\n }\n};\n\n
| 0 | 0 |
[]
| 0 |
maximum-trailing-zeros-in-a-cornered-path
|
C++ solution, faster than 90%, O(m*n), Simple
|
c-solution-faster-than-90-omn-simple-by-wyv2t
|
\nclass Solution {\npublic:\n class data{\n public:\n int up_5, up_2,\n left_5, left_2;\n };\n vector<vector<data>> v;\n
|
MrGamer2801
|
NORMAL
|
2022-05-28T13:09:57.308381+00:00
|
2022-05-28T13:09:57.308420+00:00
| 202 | false |
```\nclass Solution {\npublic:\n class data{\n public:\n int up_5, up_2,\n left_5, left_2;\n };\n vector<vector<data>> v;\n int func2(int n)\n {\n int res=0;\n while(n%2==0){ res++; n/=2;}\n return res;\n }\n int func5(int n)\n {\n int res=0;\n while(n%5==0){ res++; n/=5;}\n return res;\n }\n int sol(int x1, int x2, int y1, int y2, int z1, int z2)\n {\n return min(x1+y1+z1, x2+y2+z2);\n }\n int func(int i, int j, vector<vector<int>> &g, data H, data V)\n {\n int res=0;\n data cur=v[i][j];\n \n int cnt_2=func2(g[i][j]), cnt_5=func5(g[i][j]);\n res=max(res, sol(-cnt_2, -cnt_5, cur.left_2, cur.left_5, cur.up_2, cur.up_5));\n res=max(res, sol(0,0,cur.left_2,cur.left_5,V.up_2-cur.up_2,V.up_5-cur.up_5));\n res=max(res, sol(0,0,cur.up_2,cur.up_5,H.left_2-cur.left_2,H.left_5-cur.left_5));\n res=max(res, sol(cnt_2,cnt_5,V.up_2-cur.up_2,V.up_5-cur.up_5,H.left_2-cur.left_2, H.left_5-cur.left_5));\n return res;\n }\n int maxTrailingZeros(vector<vector<int>>& g) {\n int m=g.size(), n=g[0].size();\n v.assign(m+1, vector<data>(n+1));\n for(int i=0; i<m; i++)\n {\n for(int j=0; j<n; j++)\n {\n if(i==0){\n v[i][j].up_2=func2(g[i][j]); v[i][j].up_5=func5(g[i][j]);\n }else{\n v[i][j].up_2=v[i-1][j].up_2+func2(g[i][j]); \n v[i][j].up_5=v[i-1][j].up_5+func5(g[i][j]);\n }\n if(j==0){\n v[i][j].left_2=func2(g[i][j]); v[i][j].left_5=func5(g[i][j]);\n }else{\n v[i][j].left_2=v[i][j-1].left_2+func2(g[i][j]); \n v[i][j].left_5=v[i][j-1].left_5+func5(g[i][j]);\n }\n }\n }\n \n int res=0;\n for(int i=0; i<m; i++)\n for(int j=0; j<n; j++)\n res=max(res, func(i, j, g, v[i][n-1], v[m-1][j]));\n return res;\n }\n};\n```
| 0 | 0 |
[]
| 0 |
maximum-trailing-zeros-in-a-cornered-path
|
Horizontal & Vertical Prefix sum
|
horizontal-vertical-prefix-sum-by-i_am_c-fbp2
|
For each cell, calculate count of factors of 2 and 5. Then, prepare a horizontal and vertical prefix sum grid. Now, considering each cell as a turning point, ca
|
i_am_chitti
|
NORMAL
|
2022-05-25T03:57:44.498899+00:00
|
2022-05-25T03:57:44.498934+00:00
| 138 | false |
For each cell, calculate count of factors of 2 and 5. Then, prepare a horizontal and vertical prefix sum grid. Now, considering each cell as a turning point, calculate maximum number of trailing zeros from the four paths i.e: left-to-top, left to bottom, top to right, and right to bottom. You got the answer. :)\n```\nclass Solution {\n pair<int,int> getCount(int num) {\n int c2=0, c5=0;\n while(num%2 == 0) {\n num/=2;\n c2++;\n }\n while(num%5 == 0) {\n num/=5;\n c5++;\n }\n return make_pair(c2,c5);\n }\n \npublic:\n int maxTrailingZeros(vector<vector<int>>& grid) {\n vector<vector<pair<int,int>>> aux; // to maintain count of factors of 2 and 5 for each cell element\n int m=grid.size(), n=grid[0].size();\n for(int i=0;i<m;i++) {\n vector<pair<int,int>> temp;\n for(int j=0;j<n;j++) {\n temp.push_back(getCount(grid[i][j]));\n }\n aux.push_back(temp);\n }\n \n int ans=0;\n \n vector<vector<pair<int,int>>> aux1(m, vector<pair<int,int>>(n, {0,0})), aux2(m, vector<pair<int,int>>(n, {0,0})); // array to maintain vertical and horizontal perfix sum\n \n for(int i=0;i<m;i++) {\n aux1[i][0] = aux[i][0];\n }\n \n for(int j=0;j<n;j++) {\n aux2[0][j] = aux[0][j];\n }\n \n for(int i=0;i<m;i++) {\n for(int j=1;j<n;j++) {\n aux1[i][j].first = aux[i][j].first+aux1[i][j-1].first;\n aux1[i][j].second = aux[i][j].second+aux1[i][j-1].second;\n ans=max(ans, min(aux1[i][j].first, aux1[i][j].second));\n }\n }\n \n for(int j=0;j<n;j++) {\n for(int i=1;i<m;i++) {\n aux2[i][j].first = aux[i][j].first+aux2[i-1][j].first;\n aux2[i][j].second = aux[i][j].second+aux2[i-1][j].second;\n ans=max(ans, min(aux2[i][j].first, aux2[i][j].second));\n }\n }\n \n \n for(int i=0;i<m;i++) {\n for(int j=0;j<n;j++) {\n \n int tl=0,tr=0,tt=0,tb=0; // t stands for two, l for left, f for five, r for right and so on.\n int fl=0,fr=0,ft=0,fb=0;\n \n if(j-1>=0) {\n tl=aux1[i][j-1].first;\n fl=aux1[i][j-1].second;\n }\n \n if(i-1>=0) {\n tt=aux2[i-1][j].first;\n ft=aux2[i-1][j].second;\n }\n \n tr=aux1[i][n-1].first-aux1[i][j].first;\n fr=aux1[i][n-1].second-aux1[i][j].second;\n \n tb=aux2[m-1][j].first-aux2[i][j].first;\n fb=aux2[m-1][j].second-aux2[i][j].second;\n \n // top-to-left\n ans = max(ans, min(tl+tt+aux[i][j].first, fl+ft+aux[i][j].second));\n // left-to-bottom\n ans = max(ans, min(tl+tb+aux[i][j].first, fl+fb+aux[i][j].second));\n // top-to-right\n ans = max(ans, min(tt+tr+aux[i][j].first, ft+fr+aux[i][j].second));\n // right-to-bottom\n ans = max(ans, min(tr+tb+aux[i][j].first, fr+fb+aux[i][j].second));\n \n \n }\n }\n \n \n return ans;\n }\n};\n```
| 0 | 0 |
['C']
| 0 |
maximum-trailing-zeros-in-a-cornered-path
|
Simple Brute force using prefix sum of number of factors of 2 and 5
|
simple-brute-force-using-prefix-sum-of-n-vfwn
|
\nclass Solution {\npublic:\n \n int count(int num,int v){\n int cnt=0;\n while(num>0 and num%v==0){\n cnt++;\n num/=v
|
hydrazine
|
NORMAL
|
2022-04-28T11:42:36.376721+00:00
|
2022-04-28T11:43:21.682746+00:00
| 146 | false |
```\nclass Solution {\npublic:\n \n int count(int num,int v){\n int cnt=0;\n while(num>0 and num%v==0){\n cnt++;\n num/=v;\n }\n return cnt;\n }\n \n int maxTrailingZeros(vector<vector<int>>& grid) {\n vector<vector<pair<int,int>>> h,v;\n int n=grid.size(),m=grid[0].size();\n h.resize(n,vector<pair<int,int>>(m));\n v.resize(n,vector<pair<int,int>>(m));\n for(int i=0;i<n;i++){\n int two=0,fv=0;\n for(int j=0;j<m;j++){\n two+=count(grid[i][j],2);\n fv+=count(grid[i][j],5);\n h[i][j]={two,fv};\n }\n }\n for(int j=0;j<m;j++){\n int two=0,fv=0;\n for(int i=0;i<n;i++){\n two+=count(grid[i][j],2);\n fv+=count(grid[i][j],5);\n v[i][j]={two,fv};\n }\n }\n int ans=INT_MIN;\n for(int i=0;i<n;i++){\n for(int j=0;j<m;j++){\n int v12=(v[i][j].first+h[i][j].first)-count(grid[i][j],2);\n int v15=(v[i][j].second+h[i][j].second)-count(grid[i][j],5);\n \n int v21=(v[i][j].first+h[i][m-1].first)-h[i][j].first;\n int v25=(v[i][j].second+h[i][m-1].second)-h[i][j].second;\n\n int v31=(h[i][j].first+v[n-1][j].first)-v[i][j].first;\n int v35=(h[i][j].second+v[n-1][j].second)-v[i][j].second;\n \n int v41=(h[i][m-1].first+v[n-1][j].first)-(v[i][j].first+h[i][j].first)+count(grid[i][j],2);\n int v45=(h[i][m-1].second+v[n-1][j].second)-(v[i][j].second+h[i][j].second)+count(grid[i][j],5);\n int k=max({min(v12,v15),min(v21,v25),min(v31,v35),min(v41,v45)});\n ans=max(ans,k);\n }\n }\n return ans;\n }\n};\n```
| 0 | 0 |
[]
| 0 |
maximum-trailing-zeros-in-a-cornered-path
|
C++ || Easy || Explanation
|
c-easy-explanation-by-theanantdahiya-mle2
|
\nclass Solution {\npublic:\n // Add Pair Utility Function\n pair<int, int> addPair(pair<int, int> a, pair<int, int> b){\n return {a.first + b.firs
|
theanantdahiya
|
NORMAL
|
2022-04-24T11:31:18.199260+00:00
|
2022-04-24T11:31:18.199296+00:00
| 237 | false |
```\nclass Solution {\npublic:\n // Add Pair Utility Function\n pair<int, int> addPair(pair<int, int> a, pair<int, int> b){\n return {a.first + b.first , a.second + b.second};\n }\n // Sub Pair Utility Function\n pair<int, int> subPair(pair<int, int> a, pair<int, int> b){\n return {a.first - b.first , a.second - b.second};\n }\n \n // Find the number of 5s and 2s making factors of the current number\n pair<int, int> factors(int num){\n int fiveCount = 0;\n int twoCount = 0;\n while(num % 5 == 0){\n fiveCount += 1;\n num /= 5;\n }\n while(num % 2 == 0){\n twoCount += 1;\n num /= 2;\n }\n return {fiveCount, twoCount};\n }\n \n int maxTrailingZeros(vector<vector<int>>& grid) {\n int n = grid.size();\n int m = grid[0].size();\n int ans = 0;\n vector<vector<pair<int, int>>> hor(n, vector<pair<int, int>>(m, {0, 0}));\n vector<vector<pair<int, int>>> ver(n, vector<pair<int, int>>(m, {0, 0}));\n vector<vector<pair<int, int>>> fgrid(n, vector<pair<int, int>>(m, {0, 0}));\n // Get count of 5 and 2 factors of each number\n for(int i=0;i<n;i++){\n for(int j=0;j<m;j++){\n fgrid[i][j] = factors(grid[i][j]);\n }\n }\n \n // horizontal prefix array from left to right\n for(int i=0;i<n;i++){\n int fcount = 0;\n int tcount = 0;\n for(int j=0;j<m;j++){\n fcount += fgrid[i][j].first;\n tcount += fgrid[i][j].second;\n hor[i][j] = {fcount, tcount};\n }\n }\n \n // vertical prefix array from top to bottom \n for(int i=0;i<m;i++){\n int fcount = 0;\n int tcount = 0;\n for(int j=0;j<n;j++){\n fcount += fgrid[j][i].first;\n tcount += fgrid[j][i].second;\n ver[j][i] = {fcount, tcount};\n }\n }\n \n /*\n * Iterating each cell. There are 4 ways each cell can contribute to the path\n * top-left, top-right, left-bottom, right-bottom\n * Adding 5s and 2s for all paths and updating ans with min count of 5s ans 2s.\n */\n for(int i=0;i<n;i++){\n for(int j=0;j<m;j++){\n pair<int, int> count = {0, 0};\n count = subPair(addPair(hor[i][j], ver[i][j]), fgrid[i][j]);\n ans = max(ans, min(count.first, count.second));\n \n count = {0, 0};\n count = subPair(addPair(hor[i][m-1], ver[i][j]), hor[i][j]);\n ans = max(ans, min(count.first, count.second));\n\n count = {0, 0};\n count = subPair(addPair(hor[i][j], ver[n-1][j]), ver[i][j]);\n ans = max(ans, min(count.first, count.second));\n \n count = {0, 0};\n count = addPair(subPair(subPair(addPair(hor[i][m-1], ver[n-1][j]), hor[i][j]), ver[i][j]), fgrid[i][j]);\n ans = max(ans, min(count.first, count.second));\n \n }\n }\n \n\n return ans;\n }\n};\n```
| 0 | 0 |
['Matrix']
| 0 |
maximum-trailing-zeros-in-a-cornered-path
|
simple efficient solution
|
simple-efficient-solution-by-maverick09-r9dx
|
\nclass Solution {\npublic:\n typedef long long ll;\n pair<ll, ll> getZeroes(ll n) {\n pair<ll, ll>res{ 0,0 };\n ll m = n;\n while (n
|
maverick09
|
NORMAL
|
2022-04-24T08:38:48.356503+00:00
|
2022-04-24T08:38:48.356535+00:00
| 102 | false |
```\nclass Solution {\npublic:\n typedef long long ll;\n pair<ll, ll> getZeroes(ll n) {\n pair<ll, ll>res{ 0,0 };\n ll m = n;\n while (n && n % 2 == 0) {\n ++res.first;\n n /= 2;\n }\n n = m;\n while (n && n % 5 == 0) {\n ++res.second;\n n /= 5;\n }\n return res;\n }\n int maxTrailingZeros(vector<vector<int>>& v) {\n ll m = v.size(), n = v.front().size(), ans = 0;\n vector<vector<pair<ll, ll>>>preHor(m, vector<pair<ll, ll>>(n)), preVer(m, vector<pair<ll, ll>>(n));//, tmpV(m, vector<ll>(n));\n for (ll i = 0;i < m;++i) {\n for (ll j = 0;j < n;++j) {\n auto tmp = getZeroes(v[i][j]);\n if (j) {\n tmp.first += preHor[i][j - 1].first;\n tmp.second += preHor[i][j - 1].second;\n }\n preHor[i][j] = tmp;\n tmp = getZeroes(v[i][j]);\n if (i) {\n tmp.first += preVer[i - 1][j].first;\n tmp.second += preVer[i - 1][j].second;\n }\n preVer[i][j] = tmp;\n }\n }\n for (ll i = 0;i < m;++i) {\n for (ll j = 0;j < n;++j) {\n pair<ll, ll> top = preVer[i][j], left = preHor[i][j];\n pair<ll, ll>right = preHor[i].back(), down = preVer.back()[j];\n if (j) {\n right.first -= preHor[i][j - 1].first;\n right.second -= preHor[i][j - 1].second;\n }\n if (i) {\n down.first -= preVer[i - 1][j].first;\n down.second -= preVer[i - 1][j].second;\n }\n auto cur = getZeroes(v[i][j]);\n ll res = min(top.first+left.first-cur.first, top.second+left.second-cur.second);\n\n res = max(res, min(top.first+right.first-cur.first, top.second+right.second-cur.second));\n \n res = max(res, min(down.first+right.first-cur.first, down.second+right.second-cur.second));\n \n res = max(res, min(down.first+left.first-cur.first, down.second+left.second-cur.second));\n ans = max(ans, res);\n }\n }\n return ans;\n }\n};\n```
| 0 | 0 |
['Math']
| 0 |
maximum-trailing-zeros-in-a-cornered-path
|
C++ O(n*m) Solution || Prefix Sum Solution
|
c-onm-solution-prefix-sum-solution-by-sh-l1pz
|
cpp\ntypedef pair<int,int> pii;\ntypedef vector<pair<int,int>> vpii;\ntypedef vector<vpii> vvpii;\nclass Solution {\npublic:\n pii get_count(int x,int p=0){\
|
shubham_lohan
|
NORMAL
|
2022-04-23T12:39:17.893628+00:00
|
2022-04-23T12:41:27.035684+00:00
| 209 | false |
```cpp\ntypedef pair<int,int> pii;\ntypedef vector<pair<int,int>> vpii;\ntypedef vector<vpii> vvpii;\nclass Solution {\npublic:\n pii get_count(int x,int p=0){\n int c_2=0,c_5=0;\n while(x%2==0)\n x/=2,c_2+=1;\n while(x%5==0)\n x/=5,c_5+=1;\n if(p==1)\n return {-c_2,-c_5};\n return {c_2,c_5};\n }\n void print(vvpii &arr){\n for(int i=0;i<arr.size();i++){\n for(int j=0;j<arr[0].size();j++){\n cout<<"{"<<arr[i][j].first<<","<<arr[i][j].second<<"}, ";\n }\n cout<<endl;\n }\n cout<<\'\\n\';\n }\n int maxTrailingZeros(vector<vector<int>>& grid) {\n int n=grid.size();\n int m=grid[0].size();\n vvpii horizontal(n,vpii(m)),vertical(n,vpii(m));\n for(int i=0;i<n;i++){\n for(int j=0;j<m;j++){\n auto [a,b]=get_count(grid[i][j]);\n if(j==0){\n horizontal[i][j]={a,b};\n continue;\n }\n horizontal[i][j]=horizontal[i][j-1];\n horizontal[i][j].first+=a;\n horizontal[i][j].second+=b;\n }\n }\n // print(horizontal);\n for(int i=0;i<n;i++){\n for(int j=0;j<m;j++){\n auto [a,b]=get_count(grid[i][j]);\n if(i==0){\n vertical[i][j]={a,b};\n continue;\n }\n vertical[i][j]=vertical[i-1][j];\n vertical[i][j].first+=a;\n vertical[i][j].second+=b;\n }\n }\n // print(vertical);\n int ans=0;\n for(int i=0;i<n;i++){\n for(int j=0;j<m;j++){\n pii h=horizontal[i][j];\n pii v=vertical[i][j];\n pii c=get_count(grid[i][j]);\n// case1: _|\n int a1=h.first+v.first-c.first;\n int b1=h.second+v.second-c.second;\n// case 2: |_\n int a2=v.first+(horizontal[i][m-1].first-horizontal[i][j].first);\n int b2=v.second+(horizontal[i][m-1].second-horizontal[i][j].second);\n// case 3: --\\\n int a3=h.first+vertical[n-1][j].first-vertical[i][j].first;\n int b3=h.second+vertical[n-1][j].second-vertical[i][j].second;\n// case 4: /--\n int a4=(vertical[n-1][j].first-vertical[i][j].first)+(horizontal[i][m-1].first-horizontal[i][j].first)+c.first;\n int b4=(vertical[n-1][j].second-vertical[i][j].second)+(horizontal[i][m-1].second-horizontal[i][j].second)+c.second; \n \n ans=max({ans,min(a1,b1),min(a2,b2),min(a3,b3),min(a4,b4)});\n }\n }\n return ans;\n }\n};\n```
| 0 | 0 |
['Prefix Sum']
| 0 |
maximum-trailing-zeros-in-a-cornered-path
|
Python3 O(mn) Vertical/horizontal Prefix Sum Solution
|
python3-omn-verticalhorizontal-prefix-su-zjyo
|
First step is convert each number to how many 2s and 5s it contains, these are the ingredients of 10. \nThen is just standard counting using prefix array in bot
|
xxhrxx
|
NORMAL
|
2022-04-21T22:39:14.841341+00:00
|
2022-04-21T22:39:14.841368+00:00
| 233 | false |
First step is convert each number to how many 2s and 5s it contains, these are the ingredients of 10. \nThen is just standard counting using prefix array in both vertical and horizontal way. \n```\nclass Solution:\n def maxTrailingZeros(self, grid: List[List[int]]) -> int:\n m, n = len(grid), len(grid[0])\n new_grid = [[[0, 0] for _ in range(n)] for _ in range(m)]\n for i in range(m):\n for j in range(n):\n target = grid[i][j]\n count2, count5 = 0, 0\n while target % 2 == 0:\n count2 += 1\n target = target//2\n while target % 5 == 0:\n count5 += 1\n target = target//5\n new_grid[i][j] = [count2, count5]\n verti_grid = [[[0, 0] for _ in range(n)] for _ in range(m)]\n hori_grid = [[[0, 0] for _ in range(n)] for _ in range(m)]\n \n for i in range(m):\n sum2, sum5 = 0, 0\n for j in range(n):\n sum2 += new_grid[i][j][0]\n sum5 += new_grid[i][j][1]\n hori_grid[i][j] = [sum2, sum5]\n \n for j in range(n):\n sum2, sum5 = 0, 0\n for i in range(m):\n sum2 += new_grid[i][j][0]\n sum5 += new_grid[i][j][1]\n verti_grid[i][j] = [sum2, sum5]\n \n res = -sys.maxsize\n \n for i in range(m):\n for j in range(n):\n start2, start5 = hori_grid[i][j][0], hori_grid[i][j][1]\n start2_up, start5_up = start2 + verti_grid[i][j][0] - new_grid[i][j][0], \\\n start5 + verti_grid[i][j][1] - new_grid[i][j][1]\n start2_down, start5_down = start2 + verti_grid[-1][j][0] - verti_grid[i][j][0], \\\n start5 + verti_grid[-1][j][1] - verti_grid[i][j][1]\n res = max([min(start2_up, start5_up), min(start2_down, start5_down), res])\n\n for i in range(m):\n for j in range(n):\n if j != 0:\n start2, start5 = hori_grid[i][-1][0] - hori_grid[i][j-1][0], \\\n hori_grid[i][-1][1] - hori_grid[i][j-1][1]\n else:\n start2, start5 = hori_grid[i][-1][0], hori_grid[i][-1][1]\n start2_up, start5_up = start2 + verti_grid[i][j][0] - new_grid[i][j][0], \\\n start5 + verti_grid[i][j][1] - new_grid[i][j][1]\n start2_down, start5_down = start2 + verti_grid[-1][j][0] - verti_grid[i][j][0], \\\n start5 + verti_grid[-1][j][1] - verti_grid[i][j][1]\n res = max([min(start2_up, start5_up), min(start2_down, start5_down), res])\n \n return res\n```
| 0 | 0 |
['Prefix Sum', 'Python3']
| 0 |
maximum-trailing-zeros-in-a-cornered-path
|
O(1)-space implementation (except stack space)
|
o1-space-implementation-except-stack-spa-9kg8
|
I am spawning 3-directional (it is interesting to see that they need not be 4-directional i.e; go up, down, left, and right, three directions are sufficient for
|
loxo
|
NORMAL
|
2022-04-21T17:16:05.485766+00:00
|
2022-04-21T17:16:05.485815+00:00
| 87 | false |
I am spawning 3-directional (it is interesting to see that they need not be 4-directional i.e; go up, down, left, and right, three directions are sufficient for spanning the array) crawlers at promising (cells which are already multiples of either 2 or 5) roots.\n\nUsing marking-unmarking technique to avoid a visited array.\n```\n\tvoid rec(vector<vector<int> >& grid, int& ans, int num_twos, int num_fives, int i, int j, bool turned, int dir)\n {\n if(grid[i][j]==-1)\n return;\n // there is a more optimal way but it won\'t matter here since max(grid[i][j]) is 1000. so that\'s a max of 9 iterations for twos and 4 for fives in the following\n int twos = 0, fives = 0, temp = grid[i][j], n = grid[i][j], num_zeroes;\n while(!(n&1))\n {\n ++twos;\n n /= 2;\n }\n num_twos += twos;\n n = grid[i][j];\n while(n%5==0)\n {\n ++fives;\n n /= 5;\n }\n num_fives += fives;\n grid[i][j] = -1;\n num_zeroes = (num_twos<num_fives) ? num_twos : num_fives;\n if(ans<num_zeroes)\n ans = num_zeroes;\n // can proceed virgin\n if(dir==1 && i+1<grid.size())\n rec(grid, ans, num_twos, num_fives, i+1, j, turned, 1);\n else if(dir==2 && i-1>=0)\n rec(grid, ans, num_twos, num_fives, i-1, j, turned, 2);\n //else if(dir==3 && j+1<grid[0].size())\n //rec(grid, ans, num_twos, num_fives, i, j+1, turned, 3);\n else if(dir==4 && j-1>=0)\n rec(grid, ans, num_twos, num_fives, i, j-1, turned, 4);\n // or pivot\n if(!turned)\n {\n if(dir==1 || dir==2)\n {\n //rec(grid, ans, num_twos, num_fives, i, j+1, true, 3);\n if(j-1>=0)\n rec(grid, ans, num_twos, num_fives, i, j-1, true, 4);\n }\n else\n {\n if(i+1<grid.size())\n rec(grid, ans, num_twos, num_fives, i+1, j, true, 1);\n if(i-1>=0)\n rec(grid, ans, num_twos, num_fives, i-1, j, true, 2);\n }\n }\n grid[i][j] = temp;\n }\n \n int maxTrailingZeros(vector<vector<int>>& grid) {\n int ans = 0;\n for(int i=0; i<grid.size(); ++i)\n for(int j=0; j<grid[0].size(); ++j)\n {\n if(!(grid[i][j]&1) || grid[i][j]%5==0) // only non empty roots\n {\n rec(grid, ans, 0, 0, i, j, false, 1); // i+1\n rec(grid, ans, 0, 0, i, j, false, 2); // i-1\n //rec(grid, ans, 0, 0, i, j, false, 3); // j+1\n rec(grid, ans, 0, 0, i, j, false, 4); // j-1 \n }\n }\n return ans;\n }\n```
| 0 | 0 |
['Recursion']
| 0 |
maximum-trailing-zeros-in-a-cornered-path
|
(C++) 2245. Maximum Trailing Zeros in a Cornered Path
|
c-2245-maximum-trailing-zeros-in-a-corne-4vvb
|
\n\nclass Solution {\npublic:\n int maxTrailingZeros(vector<vector<int>>& grid) {\n int m = grid.size(), n = grid[0].size(); \n vector<vector<i
|
qeetcode
|
NORMAL
|
2022-04-20T22:38:46.864224+00:00
|
2022-04-20T22:38:46.864257+00:00
| 178 | false |
\n```\nclass Solution {\npublic:\n int maxTrailingZeros(vector<vector<int>>& grid) {\n int m = grid.size(), n = grid[0].size(); \n vector<vector<int>> f2(m, vector<int>(n)), f5(m, vector<int>(n)); \n for (int i = 0; i < m; ++i) \n for (int j = 0; j < n; ++j) {\n for (int x = grid[i][j]; x % 2 == 0; x /= 2) ++f2[i][j]; \n for (int x = grid[i][j]; x % 5 == 0; x /= 5) ++f5[i][j]; \n }\n vector<vector<array<int, 2>>> h(m+1, vector<array<int, 2>>(n+1)), v = h;\n for (int i = 0; i < m; ++i) \n for (int j = 0; j < n; ++j) {\n h[i][j+1][0] = h[i][j][0] + f2[i][j]; \n h[i][j+1][1] = h[i][j][1] + f5[i][j]; \n v[i+1][j][0] = v[i][j][0] + f2[i][j]; \n v[i+1][j][1] = v[i][j][1] + f5[i][j]; \n }\n int ans = 0; \n for (int i = 0; i < m; ++i) {\n for (int j = 0; j < n; ++j) {\n vector<int> hh = {h[i][n][0] - h[i][j][0], h[i][n][1] - h[i][j][1]}, vv = {v[m][j][0] - v[i][j][0], v[m][j][1] - v[i][j][1]}; \n ans = max(ans, min(h[i][j][0]+v[i][j][0]+f2[i][j], h[i][j][1]+v[i][j][1]+f5[i][j])); \n ans = max(ans, min(hh[0]+v[i][j][0], hh[1]+v[i][j][1])); \n ans = max(ans, min(h[i][j][0]+vv[0], h[i][j][1]+vv[1])); \n ans = max(ans, min(hh[0]+vv[0]-f2[i][j], hh[1]+vv[1]-f5[i][j])); \n }\n }\n return ans; \n }\n};\n```
| 0 | 0 |
['C']
| 0 |
maximum-trailing-zeros-in-a-cornered-path
|
c++ factor 2 and 5 time: O(nm) space: O(m)
|
c-factor-2-and-5-time-onm-space-om-by-do-1fxd
|
\nclass Solution {\n void update(int gridv, vector<int>& c)\n {\n while (gridv != 0 && gridv % 5 == 0) {c[0]++; gridv/=5;}\n while (gridv !=
|
dolaamon2
|
NORMAL
|
2022-04-20T01:27:26.005552+00:00
|
2022-04-20T01:32:45.415061+00:00
| 51 | false |
```\nclass Solution {\n void update(int gridv, vector<int>& c)\n {\n while (gridv != 0 && gridv % 5 == 0) {c[0]++; gridv/=5;}\n while (gridv != 0 && gridv % 2 == 0) {c[1]++; gridv/=2;}\n }\n \n int calculate(vector<vector<int>>& grid, bool updown)\n {\n int n = grid.size(), m = grid[0].size();\n int i=updown?0:n-1;\n int ans = 0;\n vector<vector<int>> count(m,vector<int>(2,0));//count of 2, count of 5\n while(i>=0 && i <n)\n {\n vector<int> hcount = {0,0};\n for(int j=0; j<m; j++)\n {\n update(grid[i][j], count[j]);\n ans = max(ans, min(count[j][0] + hcount[0], count[j][1] + hcount[1]));\n update(grid[i][j], hcount);\n }\n hcount[0] = hcount[1] = 0;\n for(int j=m-1; j>=0; j--)\n {\n ans = max(ans, min(count[j][0] + hcount[0], count[j][1] + hcount[1]));\n update(grid[i][j], hcount);\n }\n i+= updown?1:-1;\n }\n return ans;\n }\n \npublic:\n int maxTrailingZeros(vector<vector<int>>& grid) {\n return max(calculate(grid, true), calculate(grid, false));\n }\n};\n```
| 0 | 0 |
[]
| 0 |
maximum-trailing-zeros-in-a-cornered-path
|
Java | Prefix sums of 10, 5, 2
|
java-prefix-sums-of-10-5-2-by-prezes-v2tj
|
Yes, you can do away with 5 and 2 only.\n```\nclass Solution {\n static int R= 0, L= 1, D= 2, U= 3; // grid iteration direction index\n static int Z= 0, F
|
prezes
|
NORMAL
|
2022-04-18T22:12:16.260058+00:00
|
2022-04-18T22:12:16.260094+00:00
| 68 | false |
Yes, you can do away with 5 and 2 only.\n```\nclass Solution {\n static int R= 0, L= 1, D= 2, U= 3; // grid iteration direction index\n static int Z= 0, F= 1, E= 2; // count of zeros, fives and even numbers\n static int[] EMPTY= {0, 0, 0}; // empty array of factor counts [Z, F, E]\n \n public int maxTrailingZeros(int[][] grid) {\n int m= grid.length, n= grid[0].length;\n \n // calculate 10,5,2 factors for each number in the grid\n int[][][] fs= new int[m][n][3];\n for(int i=0; i<m; i++)\n for(int j=0; j<n; j++)\n fact(fs[i][j], grid[i][j]);\n \n // calculate ps matrices of factors in all directions\n int[][][][] ps= new int[m][n][4][3]; \n for(int i=0; i<m; i++){\n for(int j=0; j<n; j++)\n add(ps[i][j][R], fs[i][j], j==0 ? EMPTY : ps[i][j-1][R]);\n for(int j=n-1; j>-1; j--)\n add(ps[i][j][L], fs[i][j], j==n-1 ? EMPTY : ps[i][j+1][L]);\n }\n for(int j=0; j<n; j++){\n for(int i=0; i<m; i++)\n add(ps[i][j][D], fs[i][j], i==0 ? EMPTY : ps[i-1][j][D]);\n for(int i=m-1; i>-1; i--)\n add(ps[i][j][U], fs[i][j], i==m-1 ? EMPTY : ps[i+1][j][U]); \n }\n\n // use ps matrices to calculate answer \n int ans= 0;\n for(int i=0; i<m; i++){\n for(int j=0; j<n; j++){\n ans= Math.max(ans, calc(ps[i][j][L], i==m-1 ? EMPTY : ps[i+1][j][U]));\n ans= Math.max(ans, calc(ps[i][j][L], i==0 ? EMPTY : ps[i-1][j][D]));\n ans= Math.max(ans, calc(ps[i][j][R], i==m-1 ? EMPTY : ps[i+1][j][U]));\n ans= Math.max(ans, calc(ps[i][j][R], i==0 ? EMPTY : ps[i-1][j][D]));\n }\n }\n return ans;\n }\n\n void fact(int[] fs, int val){\n while(val!=0 && val%10==0){fs[Z]++; val/=10;}\n while(val!=0 && val%5==0){fs[F]++; val/=5;} \n while(val!=0 && val%2==0){fs[E]++; val/=2;}\n }\n \n void add(int[] ans, int[] a, int[] b){\n for(int i=0; i<3; i++) ans[i]= a[i]+b[i];\n }\n \n int calc(int[] a, int[] b){\n return a[Z]+b[Z] + Math.min(a[F]+b[F], a[E]+b[E]);\n }\n}
| 0 | 0 |
[]
| 0 |
maximum-trailing-zeros-in-a-cornered-path
|
Prefix sum vertically and horizontally of factors 2 and 5
|
prefix-sum-vertically-and-horizontally-o-uwrm
|
\nclass Solution {\npublic:\n int maxTrailingZeros(vector<vector<int>>& grid) {\n int n = grid.size();\n int m = grid[0].size();\n int a
|
harshyadav434
|
NORMAL
|
2022-04-18T17:40:23.869235+00:00
|
2022-04-18T17:40:23.869283+00:00
| 56 | false |
```\nclass Solution {\npublic:\n int maxTrailingZeros(vector<vector<int>>& grid) {\n int n = grid.size();\n int m = grid[0].size();\n int ans = 0;\n \n vector<vector<pair<int,int>>> ngrid(n,vector<pair<int,int>>(m,{0,0}));\n vector<vector<pair<int,int>>> vert(n,vector<pair<int,int>>(m,{0,0}));\n vector<vector<pair<int,int>>> hor(n,vector<pair<int,int>>(m,{0,0}));\n \n for(int i=0; i<n; i++){\n for(int j=0; j<m; j++){\n auto x = func(grid[i][j]);\n ngrid[i][j].first = x.first;\n ngrid[i][j].second = x.second;\n }\n }\n \n for(int j=0; j<m; j++){\n vert[0][j] = ngrid[0][j]; \n for(int i=1; i<n; i++){\n vert[i][j].first = vert[i-1][j].first + ngrid[i][j].first;\n vert[i][j].second = vert[i-1][j].second + ngrid[i][j].second;\n \n }\n }\n \n for(int i=0; i<n; i++){\n hor[i][0] = ngrid[i][0]; \n for(int j=1; j<m; j++){\n hor[i][j].first = hor[i][j-1].first+ngrid[i][j].first;\n hor[i][j].second = hor[i][j-1].second+ngrid[i][j].second;\n }\n }\n \n for(int i=0; i<n; i++){\n for(int j=0; j<m; j++){\n vector<pair<int,int> > v(4);\n \n v[0].first = (i-1 >= 0 ? vert[i-1][j].first : 0);\n v[0].second = (i-1 >= 0 ? vert[i-1][j].second : 0);\n \n v[1].first = ( vert[n-1][j].first - vert[i][j].first);\n v[1].second = ( vert[n-1][j].second - vert[i][j].second);\n \n v[2].first = (j-1 >= 0 ? hor[i][j-1].first : 0);\n v[2].second = (j-1 >= 0 ? hor[i][j-1].second : 0);\n \n v[3].first = ( hor[i][m-1].first - hor[i][j].first);\n v[3].second = ( hor[i][m-1].second - hor[i][j].second); \n \n int cmax = 0;\n \n for(int k=0; k<4; k++){\n for(int l = k+1; l<4; l++){\n int sum = min(v[k].first+v[l].first+ngrid[i][j].first, v[k].second+v[l].second+ngrid[i][j].second);\n \n cmax = max(cmax, sum);\n }\n }\n \n ans = max(ans,cmax);\n }\n }\n return ans;\n }\n \n pair<int,int> func(int x){\n int two = 0,five=0;\n while(x>0 && x%2 == 0){\n two++;\n x = x/2;\n }\n \n while(x>0 && x%5 == 0){\n five++;\n x = x/5;\n }\n \n return {two,five};\n }\n};\n```
| 0 | 0 |
['C', 'Prefix Sum']
| 0 |
maximum-trailing-zeros-in-a-cornered-path
|
c++
|
c-by-devwrathvats-t1ub
|
\nclass Solution {\npublic:\n int maxTrailingZeros(vector<vector<int>>& g) {\n \n int col=g[0].size();\n int row=g.size(); \n int a[row][
|
DevwrathVats
|
NORMAL
|
2022-04-18T15:52:17.933806+00:00
|
2022-04-18T15:52:17.933852+00:00
| 32 | false |
```\nclass Solution {\npublic:\n int maxTrailingZeros(vector<vector<int>>& g) {\n \n int col=g[0].size();\n int row=g.size(); \n int a[row][col],b[row][col]; \n for(int i=0;i<row;i++)\n {\n int cnt5=0,cnt2=0;\n for(int j=0;j<col;j++)\n {\n \n int x=g[i][j];\n while(x%5==0)\n {\n cnt5++;\n x/=5;\n }\n while(x%2==0)\n {\n cnt2++;\n x/=2;\n }\n a[i][j]=cnt5;\n b[i][j]=cnt2; \n \n }\n \n }\n \n \n int maxi=0; \n for(int j=0;j<col;j++)\n {\n int cnt5=0,cnt2=0; \n for(int i=0;i<row;i++)\n {\n int val5=cnt5+a[i][j];\n int val2=cnt2+b[i][j];\n int rval5=cnt5+a[i][col-1]-(j==0?0:a[i][j-1]);\n int rval2=cnt2+b[i][col-1]-(j==0?0:b[i][j-1]); \n cout<<a[i][col-1];\n int mini1=min(val2,val5);\n int mini2=min(rval2,rval5);\n \n int maxis=max(mini1,mini2);\n maxi=max(maxi,maxis); \n \n int x=g[i][j];\n while(x%5==0)\n {\n cnt5++;\n x/=5;\n }\n while(x%2==0)\n {\n cnt2++;\n x/=2;\n }\n \n \n }\n \n } \n \n for(int j=0;j<col;j++)\n {\n int cnt5=0,cnt2=0; \n for(int i=row-1;i>=0;i--)\n {\n int x=g[i][j];\n int val5=cnt5+a[i][j];\n int val2=cnt2+b[i][j];\n int rval5=cnt5+a[i][col-1]-(j==0?0:a[i][j-1]);\n int rval2=cnt2+b[i][col-1]-(j==0?0:b[i][j-1]); \n \n int mini1=min(val2,val5);\n int mini2=min(rval2,rval5);\n \n int maxis=max(mini1,mini2);\n maxi=max(maxi,maxis);\n while(x%5==0)\n {\n cnt5++;\n x/=5;\n }\n while(x%2==0)\n {\n cnt2++;\n x/=2;\n }\n \n \n }\n\n }\n \n return maxi; \n \n \n \n }\n};\n```
| 0 | 0 |
[]
| 0 |
maximum-trailing-zeros-in-a-cornered-path
|
C++ 100% Fast
|
c-100-fast-by-retire-drua
|
\nclass Solution {\npublic:\n int maxTrailingZeros(vector<vector<int>>& grid) \n {\n int m=grid.size(),n=grid[0].size();\n vector<vector<pai
|
Retire
|
NORMAL
|
2022-04-18T15:07:02.194170+00:00
|
2022-04-18T15:07:02.194211+00:00
| 38 | false |
```\nclass Solution {\npublic:\n int maxTrailingZeros(vector<vector<int>>& grid) \n {\n int m=grid.size(),n=grid[0].size();\n vector<vector<pair<int,int>>>prefix(m,vector<pair<int,int>>(n,{0,0}));\n for(int i=0;i<m;i++)\n for(int j=0;j<n;j++)\n {\n int cnt1=0,cnt2=0;\n while(grid[i][j]%2==0)cnt1++,grid[i][j]/=2;\n while(grid[i][j]%5==0)cnt2++,grid[i][j]/=5;\n prefix[i][j].first=cnt1;\n prefix[i][j].second=cnt2;\n }\n auto record=prefix;\n for(int i=0;i<m;i++)\n for(int j=1;j<n;j++)\n {\n prefix[i][j].first+=prefix[i][j-1].first;\n prefix[i][j].second+=prefix[i][j-1].second;\n }\n int ans=0;\n for(int i=0;i<n;i++)\n {\n int v1=0,v2=0;\n for(int j=0;j<m;j++)\n {\n ans=max(ans,min(v1+prefix[j][i].first,v2+prefix[j][i].second));\n int v3=prefix[j][n-1].first,v4=prefix[j][n-1].second;\n if(i-1>=0)v3-=prefix[j][i-1].first,v4-=prefix[j][i-1].second;\n ans=max(ans,min(v1+v3,v2+v4));\n v1+=record[j][i].first,v2+=record[j][i].second;\n }\n }\n for(int i=0;i<n;i++)\n {\n int v1=0,v2=0;\n for(int j=m-1;j>=0;j--)\n {\n ans=max(ans,min(v1+prefix[j][i].first,v2+prefix[j][i].second));\n int v3=prefix[j][n-1].first,v4=prefix[j][n-1].second;\n if(i-1>=0)v3-=prefix[j][i-1].first,v4-=prefix[j][i-1].second;\n ans=max(ans,min(v1+v3,v2+v4));\n v1+=record[j][i].first,v2+=record[j][i].second;\n }\n }\n return ans;\n }\n};\n```
| 0 | 0 |
['Prefix Sum']
| 0 |
maximum-trailing-zeros-in-a-cornered-path
|
c++ || 100% fast, easy approach
|
c-100-fast-easy-approach-by-four_707-7xw2
|
calculate powers of 2 and 5 in factors of each grid[i][j] item in a vectorof pairs of int \n2. make 2 matrices v and h, v stores vertical prefix sum (for each c
|
four_707
|
NORMAL
|
2022-04-18T08:49:29.366938+00:00
|
2022-04-18T08:49:29.366969+00:00
| 47 | false |
1. calculate powers of 2 and 5 in factors of each grid[i][j] item in a vectorof pairs of int \n2. make 2 matrices v and h, v stores vertical prefix sum (for each column seprately)of values of fac and h stores horizontal prefix sum (for each row).\n3. now in nother loop calculate ans using h and v\n```\n#define fo(i,s,e) for(int i=s;i<=e;i++)\npair<int,int> operator+(pair<int,int>a,pair<int,int>b){\n return make_pair(a.first+b.first,a.second+b.second);\n } \npair<int,int> operator-(pair<int,int>a,pair<int,int>b){\n return make_pair(a.first-b.first,a.second-b.second);\n } \nint mx(pair<int,int>a){\n return min(a.first,a.second);\n}\nclass Solution {\n pair<int,int>fact25(int val){\n int cnt=0,cnt2=0;\n while(val!=0&&val%2==0)\n {cnt++;val/=2;}\n \n while(val!=0&&val%5==0){\n cnt2++;val/=5;\n }\n return make_pair(cnt,cnt2);\n }\n \npublic:\n int maxTrailingZeros(vector<vector<int>>& grid) {\n int m=grid.size();\n int n=grid[0].size();\n vector<vector<pair<int,int>>>fac(m+1,vector<pair<int,int>>(n+1,make_pair(0,0))),h,v;\n v=h=fac;\n fac.clear();\n fo(i,1,m){\n fo(j,1,n){\n auto x=fact25(grid[i-1][j-1]);\n v[i][j]=v[i-1][j]+x;\n h[i][j]=h[i][j-1]+x;\n }\n }\n \n int ans=0;\n fo(i,1,m){\n fo(j,1,n){\n pair<int,int> hl,hr,vu,vd;\n hl=h[i][j];\n hr=h[i][n]-h[i][j-1];\n vu=v[i-1][j];\n vd=v[m][j]-v[i][j];\n ans=max({ans,mx(vu+hl),mx(vu+hr),mx(vd+hl),mx(vd+hr)});\n }\n } \n return ans;\n }\n};\n```
| 0 | 0 |
['C']
| 0 |
maximum-trailing-zeros-in-a-cornered-path
|
C++ 100% faster (557 ms), 100% less memory (140.6 MB)
|
c-100-faster-557-ms-100-less-memory-1406-gdv3
|
The hints 1-4 basically summarized what this code does.\n\ncpp\nstruct s {\n int five_cnt;\n int two_cnt;\n s(int in_f, int in_t) {\n five_cnt =
|
slothalan
|
NORMAL
|
2022-04-18T08:47:54.725937+00:00
|
2022-04-18T08:47:54.725972+00:00
| 31 | false |
The hints 1-4 basically summarized what this code does.\n\n```cpp\nstruct s {\n int five_cnt;\n int two_cnt;\n s(int in_f, int in_t) {\n five_cnt = in_f;\n two_cnt = in_t;\n }\n s() {}\n};\n\nclass Solution {\npublic:\n vector<vector<s>> C, VC, HC;\n int tmpFive, tmpTwo;\n \n void setT(int in_val) {\n tmpFive = 0;\n tmpTwo = 0;\n if (in_val == 0) {\n return;\n }\n while ((in_val % 5) == 0) {\n tmpFive++;\n in_val /= 5;\n }\n while ((in_val % 2) == 0) {\n tmpTwo++;\n in_val /= 2;\n }\n return;\n }\n \n int maxTrailingZeros(vector<vector<int>>& grid) {\n C.clear();\n int row = grid.size();\n int col = grid[0].size();\n \n for (int i = 0; i < row; i++) {\n vector<s> tmp;\n C.push_back(tmp);\n for (int j = 0; j < col; j++) {\n setT(grid[i][j]);\n C[i].push_back(s(tmpFive, tmpTwo));\n }\n }\n grid.clear();\n VC = C;\n HC = C;\n C.clear();\n for (int i = 0; i < row; i++) {\n for (int j = 1; j < col; j++) {\n HC[i][j].five_cnt += HC[i][j - 1].five_cnt;\n HC[i][j].two_cnt += HC[i][j - 1].two_cnt;\n }\n }\n for (int j = 0; j < col; j++) {\n for (int i = 1; i < row; i++) {\n VC[i][j].five_cnt += VC[i - 1][j].five_cnt;\n VC[i][j].two_cnt += VC[i - 1][j].two_cnt;\n }\n }\n int resmaxcnt = 0;\n for (int i = 0; i < row; i++) {\n for (int j = 0; j < col; j++) {\n // vertical, then left.\n s tmp = VC[i][j];\n if (j - 1 >= 0) {\n tmp.five_cnt += HC[i][j - 1].five_cnt; // correct here.\n tmp.two_cnt += HC[i][j - 1].two_cnt;\n }\n resmaxcnt = max(resmaxcnt, min(tmp.five_cnt, tmp.two_cnt));\n // next, vertical, right.\n tmp = VC[i][j];\n tmp.five_cnt += HC[i][col - 1].five_cnt - HC[i][j].five_cnt; // correct\n tmp.two_cnt += HC[i][col - 1].two_cnt - HC[i][j].two_cnt;\n resmaxcnt = max(resmaxcnt, min(tmp.five_cnt, tmp.two_cnt));\n \n // next, bottom - left.\n // always includes middle in the vertical part.\n tmp = VC[row - 1][j];\n if (i - 1 >= 0) {\n tmp.five_cnt = VC[row - 1][j].five_cnt - VC[i - 1][j].five_cnt; // modified.\n tmp.two_cnt = VC[row - 1][j].two_cnt - VC[i - 1][j].two_cnt;\n }\n if (j - 1 >= 0) {\n tmp.five_cnt += HC[i][j - 1].five_cnt;\n tmp.two_cnt += HC[i][j - 1].two_cnt;\n }\n resmaxcnt = max(resmaxcnt, min(tmp.five_cnt, tmp.two_cnt));\n \n tmp = VC[row - 1][j]; \n if (i - 1 >= 0) {\n tmp.five_cnt = VC[row - 1][j].five_cnt - VC[i - 1][j].five_cnt;\n tmp.two_cnt = VC[row - 1][j].two_cnt - VC[i - 1][j].two_cnt;\n }\n tmp.five_cnt += HC[i][col - 1].five_cnt - HC[i][j].five_cnt;\n tmp.two_cnt += HC[i][col - 1].two_cnt - HC[i][j].two_cnt;\n resmaxcnt = max(resmaxcnt, min(tmp.five_cnt, tmp.two_cnt));\n }\n }\n return resmaxcnt;\n }\n};\n```
| 0 | 0 |
[]
| 0 |
maximum-trailing-zeros-in-a-cornered-path
|
[C++] Prefix Sum of factors 2 and 5 (Used 3D array to make implementation easier)
|
c-prefix-sum-of-factors-2-and-5-used-3d-e466j
|
\n\n#define endl ("\\n")\n#define pi (3.141592653589)\n#define mod 1e9+7\n#define ll long long\n#define float double\n#define pb push_back\n#define pp pair<ll,
|
ujjwalkrishna
|
NORMAL
|
2022-04-18T07:53:31.404302+00:00
|
2022-04-18T07:53:31.404337+00:00
| 50 | false |
```\n\n#define endl ("\\n")\n#define pi (3.141592653589)\n#define mod 1e9+7\n#define ll long long\n#define float double\n#define pb push_back\n#define pp pair<ll, ll>\n#define mp make_pair\n#define ff first\n#define ss second\n#define all(c) cc.begin(), c.end()\n#define mini(a, b, c) min(c, min(a, b))\n#define rrep(i, n) for(int i=n-1;i>=0;i--)\n#define rep(i,n) for(int i=0;i<n;i++)\n#define rep1(i,n) for(int i=1;i<n;i++)\n\nclass Solution {\npublic:\n pp solve(ll ele){\n int temp = ele;\n int twos = 0, fives = 0;\n while(temp%2==0){\n twos++;\n temp/=2;\n }\n temp = ele;\n while(temp%5==0){\n fives++;\n temp/=5;\n }\n return {twos, fives};\n }\n int maxTrailingZeros(vector<vector<int>>& grid) {\n int n = grid.size();\n int m = grid[0].size();\n vector<vector<vector<pp>>> dp(n, vector<vector<pp>>(m, vector<pp>(4)));\n rep(i, n){\n vector<pp> store(m); //{2, 5}\n rep(j, m){\n pp it = solve(grid[i][j]);\n if(j == 0){\n store[j] = it;\n }else{\n store[j] = {it.first+store[j-1].first, it.second+store[j-1].second};\n }\n }\n int t_2 = store[m-1].first, t_5 = store[m-1].second;\n rep(j, m){\n dp[i][j][0].first = store[j].first;\n dp[i][j][0].second = store[j].second;\n dp[i][j][1].first = t_2 - (j >= 1 ? store[j-1].first:0);\n dp[i][j][1].second = t_5 - (j >= 1 ? store[j-1].second:0);\n }\n }\n\n rep(j, m){\n vector<pp> store(n); //{2, 5}\n rep(i, n){\n pp it = solve(grid[i][j]);\n if(i == 0){\n store[i] = it;\n }else{\n store[i] = {it.first+store[i-1].first, it.second+store[i-1].second};\n }\n }\n int t_2 = store[n-1].first, t_5 = store[n-1].second;\n rep(i, n){\n dp[i][j][2].first = store[i].first;\n dp[i][j][2].second = store[i].second;\n dp[i][j][3].first = t_2 - (i >= 1 ? store[i-1].first:0);\n dp[i][j][3].second = t_5 - (i >= 1 ? store[i-1].second:0);\n }\n }\n \n int res = 0;\n rep(i, n){\n rep(j, m){\n int up_max = min(dp[i][j][2].first, dp[i][j][2].second);\n int down_max = min(dp[i][j][3].first, dp[i][j][3].second);\n \n int left_max = min(dp[i][j][0].first, dp[i][j][0].second);\n int right_max = min(dp[i][j][1].first, dp[i][j][1].second);\n \n pp it = solve(grid[i][j]);\n //UP -> RIGHT\n ll twos = dp[i][j][2].first+dp[i][j][1].first-it.first;\n ll fives = dp[i][j][2].second+dp[i][j][1].second-it.second;\n \n ll tu = min(twos, fives);\n res = res < tu ? tu:res;\n \n //UP -> LEFT\n twos = dp[i][j][2].first+dp[i][j][0].first-it.first;\n fives = dp[i][j][2].second+dp[i][j][0].second-it.second;\n \n tu = min(twos, fives);\n res = res < tu ? tu:res;\n \n //LEFT -> DOWN\n twos = dp[i][j][0].first+dp[i][j][3].first-it.first;\n fives = dp[i][j][0].second+dp[i][j][3].second-it.second;\n \n tu = min(twos, fives);\n res = res < tu ? tu:res;\n \n //DOWN -> RIGHT\n twos = dp[i][j][3].first+dp[i][j][1].first-it.first;\n fives = dp[i][j][3].second+dp[i][j][1].second-it.second;\n \n tu = min(twos, fives);\n res = res < tu ? tu:res;\n }\n }\n \n return (int)res;\n }\n};\n\n```
| 0 | 0 |
['C', 'Matrix', 'Prefix Sum']
| 0 |
maximum-trailing-zeros-in-a-cornered-path
|
[Python] Iterative. Prefix Sum + Factor caching Beats 100% 2601 ms
|
python-iterative-prefix-sum-factor-cachi-8cpn
|
\nclass Solution(object):\n def maxTrailingZeros(self, grid):\n m = len(grid)\n n = len(grid[0])\n factors = {}\n for val in rang
|
ayushpatwari
|
NORMAL
|
2022-04-18T07:44:03.937509+00:00
|
2022-04-18T07:45:00.177597+00:00
| 72 | false |
```\nclass Solution(object):\n def maxTrailingZeros(self, grid):\n m = len(grid)\n n = len(grid[0])\n factors = {}\n for val in range(1, 1001):\n num = val\n cnt2, cnt5 = 0, 0\n while num > 0 and num % 2 == 0: \n cnt2 += 1\n num = num / 2\n while num > 0 and num % 5 == 0: \n cnt5 += 1\n num = num / 5\n factors[val] = (cnt2, cnt5)\n row2, row5, col2, col5 = [], [], [], []\n for i in range(m + 1): \n row2.append([0]*(n + 1))\n col2.append([0]*(n + 1))\n row5.append([0]*(n + 1))\n col5.append([0]*(n + 1))\n for i in range(1, m + 1):\n for j in range(1, n + 1):\n cnt2, cnt5 = factors[grid[i - 1][j - 1]]\n row2[i][j] = cnt2 + row2[i][j - 1]\n row5[i][j] = cnt5 + row5[i][j - 1]\n col2[i][j] = cnt2 + col2[i - 1][j]\n col5[i][j] = cnt5 + col5[i - 1][j]\n res = 0\n for i in range(1, m + 1):\n for j in range(1, n + 1):\n cnt2, cnt5 = factors[grid[i - 1][j - 1]]\n top2, top5 = col2[i-1][j], col5[i-1][j]\n bottom2, bottom5 = col2[m][j] - col2[i][j], col5[m][j] - col5[i][j]\n left2, left5 = row2[i][j-1], row5[i][j-1]\n right2, right5 = row2[i][n] - row2[i][j], row5[i][n] - row5[i][j]\n res = max(res, min(top2 + left2 + cnt2, top5 + left5 + cnt5), min(top2 + right2 + cnt2, top5 + right5 + cnt5), min(bottom2 + left2 + cnt2, bottom5 + left5 + cnt5), min(bottom2 + right2 + cnt2, bottom5 + right5 + cnt5))\n return res\n \n \n \n \n \n```
| 0 | 0 |
[]
| 0 |
maximum-trailing-zeros-in-a-cornered-path
|
C++ || Self Explanatory/More Readable Code || Prefix Sum
|
c-self-explanatorymore-readable-code-pre-wtxz
|
\n// Trailing Zeros => Count of 10\'s in a number => 10 = 2*5 => minimum (sum of 2 exponents, sum of 5 exponents)\n// Apporach : Prefix Sum of Count of 2\'s and
|
jkrlr
|
NORMAL
|
2022-04-18T06:55:28.776221+00:00
|
2022-04-18T07:14:58.429523+00:00
| 63 | false |
```\n// Trailing Zeros => Count of 10\'s in a number => 10 = 2*5 => minimum (sum of 2 exponents, sum of 5 exponents)\n// Apporach : Prefix Sum of Count of 2\'s and 5\'s + Suffix Sum of Count of 2\'s and 5\'s | Time - O(4*m*n), Space - O(2*m*n)\n\nclass Pair{\npublic:\n int countOfTwo;\n int countOfFive;\n \n Pair(){\n countOfTwo = 0;\n countOfTwo = 0;\n }\n \n Pair(int two, int five){\n countOfTwo = two;\n countOfFive = five;\n }\n};\n\nclass Solution {\npublic:\n int maxTrailingZeros(vector<vector<int>>& grid) {\n int m = grid.size();\n int n = grid[0].size();\n \n vector<vector<Pair>> prefix(m, vector<Pair>(n));\n vector<vector<Pair>> suffix(m, vector<Pair>(n));\n \n // Find the Prefix Sum of Count of 2\'s and 5\'s \n for(int i=0; i<m; i++){\n for(int j=0; j<n; j++){\n prefix[i][j] = findCountTwoAndFive(grid[i][j]);\n \n if(j!=0){\n prefix[i][j].countOfTwo += prefix[i][j-1].countOfTwo;\n prefix[i][j].countOfFive += prefix[i][j-1].countOfFive;\n }\n }\n }\n \n // Find the Suffix Sum of Count of 2\'s and 5\'s \n for(int i=0; i<m; i++){\n for(int j=n-1; j>=0; j--){\n suffix[i][j] = findCountTwoAndFive(grid[i][j]);\n \n if(j!=n-1){\n suffix[i][j].countOfTwo += suffix[i][j+1].countOfTwo;\n suffix[i][j].countOfFive += suffix[i][j+1].countOfFive;\n }\n }\n }\n \n // __ __\n // Traverse the each valid concerned Path => |__ , __| , | ,| \n // and calculate the trailing zeros and then take max of it\n // We\'re traversing each column and then each row\n \n // First Traverse the concerned Path of type:|__ , __|\n int ans = 0;\n for(int i=0; i<n; i++){\n int count2 = 0, count5 = 0;\n for(int j=0; j<m; j++){\n \n ans = max(ans, min(count2 + prefix[j][i].countOfTwo, count5 + prefix[j][i].countOfFive));\n ans = max(ans, min(count2 + suffix[j][i].countOfTwo, count5 + suffix[j][i].countOfFive));\n \n Pair p = findCountTwoAndFive(grid[j][i]);\n count2 += p.countOfTwo, count5 += p.countOfFive;\n }\n }\n \n // __ __\n // Second Traverse the concerned Path of type: | , | \n for(int i=0; i<n; i++){\n int count2 = 0, count5 = 0;\n for(int j=m-1; j>=0; j--){\n \n ans = max(ans, min(count2 + prefix[j][i].countOfTwo, count5 + prefix[j][i].countOfFive));\n ans = max(ans, min(count2 + suffix[j][i].countOfTwo, count5 + suffix[j][i].countOfFive));\n \n Pair p = findCountTwoAndFive(grid[j][i]);\n count2 += p.countOfTwo, count5 += p.countOfFive;\n }\n }\n \n // Now return ans\n return ans;\n }\nprivate:\n Pair findCountTwoAndFive(int num){\n int two = 0, five = 0;\n while(num%2==0){\n two++;\n num /= 2;\n }\n \n while(num%5==0){\n five++;\n num /= 5;\n }\n \n return Pair(two, five);\n }\n};\n```
| 0 | 0 |
['C']
| 1 |
maximum-trailing-zeros-in-a-cornered-path
|
Can someone help me where I'm going wrong
|
can-someone-help-me-where-im-going-wrong-pmrp
|
\nclass Solution:\n def maxTrailingZeros(self, grid: List[List[int]]) -> int:\n m=len(grid[0])\n n=len(grid)\n def checkZeros(num):\n
|
saisanjith15
|
NORMAL
|
2022-04-18T06:22:17.077583+00:00
|
2022-04-18T06:22:17.077626+00:00
| 33 | false |
```\nclass Solution:\n def maxTrailingZeros(self, grid: List[List[int]]) -> int:\n m=len(grid[0])\n n=len(grid)\n def checkZeros(num):\n count=0\n while num%10 ==0 and num!=0:\n count+=1\n num//=10\n return count\n preRow=[[1 for i in range(len(grid[0]))] for j in range(n)]\n preCol=[[1 for i in range(len(grid[0]))] for j in range(n)]\n totalRow=[1 for i in range(n)]\n totalCol=[1 for i in range(m)]\n for i in range(n):\n pro=1\n for j in range(m):\n pro*=grid[i][j]\n preRow[i][j]=pro\n totalRow[i]=pro\n for i in range(m):\n pro=1\n for j in range(n):\n pro*=grid[j][i]\n preCol[j][i]=pro\n totalCol[i]=pro\n maxx=0\n for i in range(m):\n pro=1\n for j in range(n):\n maxx=max(maxx,checkZeros(pro*preRow[j][i]))\n pro*=grid[j][i]\n maxx=max(maxx,checkZeros(pro*(totalRow[j]//preRow[j][i])))\n for i in range(n):\n pro=1\n for j in range(m):\n maxx=max(maxx,checkZeros(pro*preCol[i][j]))\n pro*=grid[i][j]\n maxx=max(maxx,checkZeros(pro*(totalCol[j]//preCol[i][j])))\n return maxx\n \n```\nwhy is this code failing for this test case\n[[534,575,625,84,20,999,35],[208,318,96,380,819,102,669]]
| 0 | 0 |
[]
| 0 |
maximum-trailing-zeros-in-a-cornered-path
|
[Python3] DP concise recursive 19 lines, + iterative beats 100%
|
python3-dp-concise-recursive-19-lines-it-o2gx
|
Starting from any cell[i][j], we go 4 directions top,left, right, down. Go until meeting boundary. Then pick any 2 directions plus cell[i][j] itself to make a \
|
yuanzhi247012
|
NORMAL
|
2022-04-18T05:56:10.207003+00:00
|
2022-04-18T06:49:14.269139+00:00
| 38 | false |
Starting from any cell[i][j], we go 4 directions top,left, right, down. Go until meeting boundary. Then pick any 2 directions plus cell[i][j] itself to make a \'cornered line\', totally 6 combinations: \'left+cell+top\', \'left+cell+down\', \'left+cell+right\', \'top+cell+right\', \'top+cell+down\', \'right+cell+down\'. Calculating scores for these 6 lines and we will know the highest score that passes cell[i][j]. \nDo the same for all cells and the highest among highest score is the final result. We use 2D prefix sum for 4 directions to achieve O(1) time for each cell.\n\nRecursive: 8274ms beats 50%\n```\n def maxTrailingZeros(self, grid: List[List[int]]) -> int:\n @functools.lru_cache(None)\n def factors(num,factor):\n if num%factor!=0: return 0\n return 1+factors(num//factor,factor)\n @functools.lru_cache(None)\n def dp(i,j,d):\n if 0<=i<m and 0<=j<n:\n tmp2,tmp5 = dp(i+d[0],j+d[1],d)\n return factors(grid[i][j],2)+tmp2,factors(grid[i][j],5)+tmp5\n return 0,0\n combo = [[a,b] for a,b in combinations([(-1,0),(0,-1),(1,0),(0,1)],2) if a[0]+b[0]!=0 or a[1]+b[1]!=0]\n m,n,res=len(grid),len(grid[0]),0\n for i in range(m):\n for j in range(n):\n cur = (factors(grid[i][j],2),factors(grid[i][j],5))\n for dir1, dir2 in combo:\n d1,d2=dp(i,j,dir1),dp(i,j,dir2)\n res = max(res,min(d1[0]+d2[0]-cur[0],d1[1]+d2[1]-cur[1]))\n return res\n```\n\nTo make it even faster\n\t1. We don\'t need to prepare 2D prefix sum for all 4 directions, but only \'up\' and \'left\'. Because \'right\' and \'down\' can be calculated using \'up\' and \'left\'.\n\t2. We don\'t need to go all 6 combinations of 4 directions, but only 4. No need to calculate the 4 \'straight line\' combinations, because for each of them there must exists a \'corner line\' that completely covers it.\n\t3. The function to count factors \'2\' and \'5\' can be cached and put to global to share across test cases\n\nIterative, 4556ms beats 100%\n```\n def maxTrailingZeros(self, grid: List[List[int]]) -> int:\n\t\[email protected]_cache(None)\n def factors(num,factor):\n if num%factor!=0: return 0\n return 1+factors(num//factor,factor)\n m,n=len(grid),len(grid[0])\n up=[[(0,0) for _ in range(n)] for _ in range(m)]\n left=[[(0,0) for _ in range(n)] for _ in range(m)]\n for i in range(m):\n for j in range(n):\n cur = (factors(grid[i][j],2),factors(grid[i][j],5))\n grid[i][j] = cur\n up_prev,left_prev = up[i-1][j], left[i][j-1]\n up[i][j] = [up_prev[0]+cur[0],up_prev[1]+cur[1]]\n left[i][j] = [left_prev[0]+cur[0],left_prev[1]+cur[1]]\n res = 0\n for i in range(m):\n for j in range(n):\n up1,left1,cur = up[i][j], left[i][j], grid[i][j]\n right1 = [left[i][-1][0]-left1[0]+cur[0],left[i][-1][1]-left1[1]+cur[1]]\n down1 = [up[-1][j][0]-up1[0]+cur[0],up[-1][j][1]-up1[1]+cur[1]]\n a = min(left1[0]+up1[0]-cur[0],left1[1]+up1[1]-cur[1])\n b = min(up1[0]+right1[0]-cur[0],up1[1]+right1[1]-cur[1])\n c = min(left1[0]+down1[0]-cur[0],left1[1]+down1[1]-cur[1])\n d = min(right1[0]+down1[0]-cur[0],right1[1]+down1[1]-cur[1])\n res = max(res,a,b,c,d)\n return res\n```\n
| 0 | 0 |
[]
| 0 |
find-the-losers-of-the-circular-game
|
Simulation
|
simulation-by-votrubac-xg06
|
We pre-populate the result array with all numbers, and set a number to zero once visited.\n\nAfter the simulation, we return remaining non-zero numbers.\n\nPyth
|
votrubac
|
NORMAL
|
2023-05-14T04:22:21.811866+00:00
|
2023-05-14T05:22:47.805174+00:00
| 2,904 | false |
We pre-populate the result array with all numbers, and set a number to zero once visited.\n\nAfter the simulation, we return remaining non-zero numbers.\n\n**Python 3**\n```python\nclass Solution:\n def circularGameLosers(self, n: int, k: int) -> List[int]:\n s = set([i for i in range(1, n + 1)])\n for mul in accumulate([i for i in range(n)]):\n if k * mul % n + 1 not in s:\n break\n s.remove(k * mul % n + 1)\n return s\n```\n\n**C++**\n``` cpp\nvector<int> circularGameLosers(int n, int k) {\n vector<int> res(n);\n iota(begin(res), end(res), 1);\n for (int cur = 0, mul = 1; res[cur]; ++mul) {\n res[cur] = 0;\n cur = (cur + mul * k) % n;\n }\n res.erase(remove(begin(res), end(res), 0), end(res));\n return res;\n}\n```
| 27 | 0 |
['C', 'Python3']
| 3 |
find-the-losers-of-the-circular-game
|
Simple || Clean || Java Solution
|
simple-clean-java-solution-by-himanshubh-sd3u
|
\njava []\nclass Solution {\n public int[] circularGameLosers(int n, int k) {\n boolean visited[] = new boolean[n];\n int v = 0, i=0;\n
|
HimanshuBhoir
|
NORMAL
|
2023-05-14T04:01:43.412335+00:00
|
2023-05-14T04:01:43.412363+00:00
| 2,428 | false |
\n```java []\nclass Solution {\n public int[] circularGameLosers(int n, int k) {\n boolean visited[] = new boolean[n];\n int v = 0, i=0;\n while(visited[i%n] == false){\n v++;\n visited[i%n] = true;\n i += v*k;\n }\n int[] res = new int[n-v];\n int j=0;\n for(i=0; i<visited.length; i++){\n if(visited[i] == false) res[j++]=i+1;\n }\n return res;\n }\n}\n```
| 17 | 0 |
['Java']
| 3 |
find-the-losers-of-the-circular-game
|
🔥C++ ✅✅ Best Solution ( 🔥 🔥 ) Easy to Understand💯💯 ⬆⬆⬆
|
c-best-solution-easy-to-understand-by-sa-ahkn
|
Complexity\n- Time complexity: O(n)\n Add your time complexity here, e.g. O(n) \n\n- Space complexity: O(n)\n Add your space complexity here, e.g. O(n) \n\n# Co
|
Sandipan58
|
NORMAL
|
2023-05-14T04:53:25.377024+00:00
|
2023-05-14T04:53:37.963640+00:00
| 2,159 | false |
# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n vector<int> circularGameLosers(int n, int k) {\n vector<int> vis(n, 0);\n int i=0, j=1;\n while(1) {\n if(vis[i] == 1) break;\n vis[i] = 1;\n i = (i + j*k) % n;\n j++;\n }\n vector<int> ans;\n for(int i=0; i<n; i++) {\n if(vis[i] == 0) ans.push_back(i+1);\n }\n \n return ans;\n }\n};\n\n```
| 9 | 0 |
['Array', 'Hash Table', 'Math', 'C++']
| 1 |
find-the-losers-of-the-circular-game
|
Python 3 || 7 lines, w/example || T/S: 92% / 91%
|
python-3-7-lines-wexample-ts-92-91-by-sp-z9ji
|
\nclass Solution:\n def circularGameLosers(self, n, k):\n\n remain, ball, nxt = set(N:=range(1,n)), k,0\n\n for _ in N:
|
Spaulding_
|
NORMAL
|
2023-05-16T16:33:14.780634+00:00
|
2024-06-22T21:27:16.821803+00:00
| 634 | false |
```\nclass Solution:\n def circularGameLosers(self, n, k):\n\n remain, ball, nxt = set(N:=range(1,n)), k,0\n\n for _ in N: # Example: n = 5 k = 2\n\n nxt = (nxt + ball)%n # ball nxt remain\n if nxt not in remain: break # ----- ----- -----\n # 2 0 [1, 2, 3, 4]\n remain.remove(nxt) # 4 2 [1, 3, 4]\n ball+= k # 6 1 [3, 4]\n # 6 2 [3, 4] <-- 2 appears again\n\n return [i+1 for i in remain] # return [3+1, 4+1] --> [4, 5]\n```\n[https://leetcode.com/problems/find-the-losers-of-the-circular-game/submissions/1297107321/](https://leetcode.com/problems/find-the-losers-of-the-circular-game/submissions/1297107321/)\n\nI could be wrong, but I think that time complexity is *O*(*N*) and space complexity is *O*(*N*).\n\n[Edited 7/28/23] See [@almostmonday](/almostmonday) in comments.
| 8 | 0 |
['Python3']
| 1 |
find-the-losers-of-the-circular-game
|
MOST OPTIMISED || C++ || EASY TO UNDERSTNAD
|
most-optimised-c-easy-to-understnad-by-g-689b
|
make an array of size n. initially no one have ball so all are false.\n1st person have ball\nthan 1+i*k person have ball (i = ith step)\nmodulo is use for circu
|
ganeshkumawat8740
|
NORMAL
|
2023-05-14T05:43:54.176392+00:00
|
2023-05-14T05:46:02.266709+00:00
| 1,325 | false |
make an array of size n. initially no one have ball so all are false.\n1st person have ball\nthan 1+i*k person have ball (i = ith step)\nmodulo is use for circular\n\n# Code\n```\nclass Solution {\npublic:\n vector<int> circularGameLosers(int n, int k) {\n int x = 1,y=1;\n vector<int> v(n+1,false);\n // cout<<y<<" ";\n while(!v[y]){\n v[y] = true;\n y = ((y+x*k)%n);\n if(y==0)y = n;\n // cout<<y<<" ";\n x++;\n }\n vector<int> ans;\n for(x = 1; x <= n; x++){\n if(!v[x])ans.push_back(x);\n }\n return ans;\n }\n};\n```
| 8 | 0 |
['Math', 'Game Theory', 'C++']
| 0 |
find-the-losers-of-the-circular-game
|
Simulation Easy Python solution.
|
simulation-easy-python-solution-by-bk244-lpo6
|
\n# Code\n\nclass Solution:\n def circularGameLosers(self, n: int, k: int) -> List[int]:\n start = 0\n sset = set()\n p = 1\n whi
|
bk2444
|
NORMAL
|
2023-05-14T04:10:57.650659+00:00
|
2023-05-14T04:10:57.650701+00:00
| 1,600 | false |
\n# Code\n```\nclass Solution:\n def circularGameLosers(self, n: int, k: int) -> List[int]:\n start = 0\n sset = set()\n p = 1\n while start not in sset:\n sset.add(start)\n start += p*k\n start = start%n\n p += 1\n ans = []\n for i in range(n):\n if i not in sset:\n ans.append(i+1)\n return ans\n \n \n```
| 7 | 0 |
['Python3']
| 1 |
find-the-losers-of-the-circular-game
|
Java | Beats > 99% | 10 lines
|
java-beats-99-10-lines-by-judgementdey-g5ia
|
Intuition\n Describe your first thoughts on how to solve this problem. \n1. Maintain a boolean map of size n.\n2. Simulate the scenario described in the problem
|
judgementdey
|
NORMAL
|
2023-05-15T23:27:33.959894+00:00
|
2023-05-16T23:03:58.183095+00:00
| 736 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n1. Maintain a boolean map of size `n`.\n2. Simulate the scenario described in the problem statement and keep marking each player that receives the ball in the map.\n3. Break the loop once the ball reaches a player that had already got it before.\n4. Parse through the boolean map and extract the indices of the players that didn\'t receive the ball at all.\n\n# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int[] circularGameLosers(int n, int k) {\n var map = new boolean[n];\n int x = 0, i;\n \n for (i=1; !map[x]; i++) {\n map[x] = true;\n x = (x + i*k) % n;\n }\n var ans = new int[n-i+1];\n var j = 0;\n\n for (i=0; i<n; i++)\n if (!map[i])\n ans[j++] = i+1;\n\n return ans;\n }\n}\n```\nIf you like my solution, please upvote it!
| 6 | 0 |
['Simulation', 'Java']
| 0 |
find-the-losers-of-the-circular-game
|
Simple Bruteforce
|
simple-bruteforce-by-kreakemp-j3hx
|
\nUp vote if you like the solution\n\n# Approach \n1. Just take an array and keep tracking its value with bruteforce.\n \n# Code\n\n\nvector<int> circularGam
|
kreakEmp
|
NORMAL
|
2023-05-14T04:02:59.869301+00:00
|
2023-05-14T04:02:59.869333+00:00
| 4,023 | false |
\n<b>Up vote if you like the solution</b>\n\n# Approach \n1. Just take an array and keep tracking its value with bruteforce.\n \n# Code\n\n```\nvector<int> circularGameLosers(int n, int k) {\n vector<int> v(n, 0);\n int i = 1, t = 0; \n while(v[i-1] == 0){\n v[i-1] = 1;\n t = t + k;\n i = (i + t)%n;\n if(i == 0) i = n;\n }\n vector<int> ans;\n for(int i = 0; i < v.size(); ++i){\n if(v[i] == 0) ans.push_back(i+1);\n }\n return ans;\n}\n```\n\n<b>Here is an article of my last interview experience - A Journey to FAANG Company, I recomand you to go through this to know which all resources I have used & how I cracked interview at Amazon:\nhttps://leetcode.com/discuss/interview-experience/3171859/Journey-to-a-FAANG-Company-Amazon-or-SDE2-(L5)-or-Bangalore-or-Oct-2022-Accepted
| 5 | 1 |
['C++']
| 3 |
find-the-losers-of-the-circular-game
|
HashSet JAVA solution || Intuitive
|
hashset-java-solution-intuitive-by-kshit-188q
|
\n# Code\n\nclass Solution {\n public int[] circularGameLosers(int n, int k) {\n int multiplier =1;\n HashSet<Integer> set = new HashSet<>();\n
|
Kshitij_Pandey
|
NORMAL
|
2023-05-15T08:03:35.331026+00:00
|
2023-05-15T08:03:35.331053+00:00
| 63 | false |
\n# Code\n```\nclass Solution {\n public int[] circularGameLosers(int n, int k) {\n int multiplier =1;\n HashSet<Integer> set = new HashSet<>();\n int winner =0;\n \n while(true){\n set.add(winner);\n winner = (winner +multiplier*k) % n;\n multiplier++;\n if(set.contains(winner)){\n break;\n }\n }\n \n int size = n -set.size();\n int[] ans =new int[size];\n int index =0;\n \n for(int i=0; i< n; i++){\n if(!set.contains(i)){\n ans[index++] = i+1;\n }\n }\n return ans;\n }\n}\n```
| 4 | 0 |
['Java']
| 0 |
find-the-losers-of-the-circular-game
|
Poetic Solution || Experimental solution || C++
|
poetic-solution-experimental-solution-c-fam3w
|
Code in Poem\n\nAmidst a circle of players fair,\nA game is played with utmost care.\nEvery kth player must be gone,\nUntil just one is left alone.\n\nTo simula
|
ross8888
|
NORMAL
|
2023-05-14T09:19:32.226045+00:00
|
2023-05-14T09:19:32.226069+00:00
| 737 | false |
# Code in Poem\n\nAmidst a circle of players fair,\nA game is played with utmost care.\nEvery kth player must be gone,\nUntil just one is left alone.\n\nTo simulate this game we\'ll try,\nUsing a map to bid goodbye.\nEliminating till the end,\nKeeping track of all our friends.\n\nWith time complexity of n,\nAnd space complexity of the same yen.\nThe code we\'ll write in just a snap,\nTo solve the problem with a tap.\n\n# Code\n```\nclass Solution {\npublic:\n vector<int> circularGameLosers(int n, int k) {\n vector<int> ans;\n map<int,int> mp;\n int i=1,j=k;\n \n \n while(mp.find(i)==mp.end())\n {\n mp[i]++;\n i = (i+k)%n;\n if(i == 0)\n {\n i = n;\n }\n \n k=k+j;\n \n }\n \n for(int i=1;i<=n;i++)\n {\n if(mp.find(i) == mp.end())\n {\n ans.push_back(i);\n }\n }\n \n return ans;\n }\n};\n```
| 4 | 0 |
['C++']
| 0 |
find-the-losers-of-the-circular-game
|
✅[Python] Simple and Clean, beats 99.99%✅
|
python-simple-and-clean-beats-9999-by-_t-1shc
|
Please upvote if you find this helpful. \u270C\n\n\nThis is an NFT\n\n\n# Intuition\nThe problem asks us to find the losers of a circular game played by n frien
|
_Tanmay
|
NORMAL
|
2023-05-17T15:42:25.127185+00:00
|
2023-05-17T15:42:25.127250+00:00
| 289 | false |
### Please upvote if you find this helpful. \u270C\n<img src="https://assets.leetcode.com/users/images/b8e25620-d320-420a-ae09-94c7453bd033_1678818986.7001078.jpeg" alt="Cute Robot - Stable diffusion" width="200"/>\n\n*This is an NFT*\n\n\n# Intuition\nThe problem asks us to find the losers of a circular game played by n friends sitting in a circle. The game involves passing a ball between friends according to certain rules. The losers of the game are friends who did not receive the ball in the entire game. Our first thought might be to simulate the game and keep track of the friends who have received the ball.\n\n# Approach\n1. We can use an array `visited` of size n to keep track of the friends who have received the ball. We initialize all elements of `visited` to 0.\n2. We then use a while loop to simulate the game. In each iteration of the loop, we calculate the next friend to receive the ball using the formula `pos = (pos+(count*k))%n` where `pos` is the current friend holding the ball, `count` is the turn number, and `k` is the number of steps to move in the clockwise direction.\n3. We increment `visited[pos]` by 1 to indicate that this friend has received the ball. If `visited[pos]` becomes 2, it means that this friend has received the ball for the second time and the game is finished.\n4. After simulating the game, we can iterate over `visited` and add all friends who have not received the ball to a list `res`. We then return `res` which contains the losers of the game.\n\n# Complexity\n- Time complexity: $$O(n)$$ where n is the number of friends. This is because we need to simulate n turns of the game and each turn takes constant time.\n- Space complexity: $$O(n)$$ since we use an array of size n to keep track of the friends who have received the ball.\n\n# Code\n```\nclass Solution:\n def circularGameLosers(self, n: int, k: int) -> List[int]:\n visited = [0] * n\n count = 1\n pos = 0\n visited[pos] = 1\n while (visited[pos]!=2):\n pos = (pos+(count*k))%n\n visited[pos]+=1\n count+=1\n res = []\n for i in range(n):\n if not visited[i]:\n res.append(i+1)\n return res\n```
| 3 | 0 |
['Array', 'Simulation', 'Python', 'Python3']
| 1 |
find-the-losers-of-the-circular-game
|
✅[Python] Simple and Clean, beats 93.99%✅
|
python-simple-and-clean-beats-9399-by-_t-svf9
|
Intuition\nThe problem asks us to find the losers of a circular game played by n friends sitting in a circle. The game involves passing a ball between friends a
|
_Tanmay
|
NORMAL
|
2023-05-17T14:10:38.544186+00:00
|
2023-05-17T14:10:38.544235+00:00
| 113 | false |
# Intuition\nThe problem asks us to find the losers of a circular game played by n friends sitting in a circle. The game involves passing a ball between friends according to certain rules. The losers of the game are friends who did not receive the ball in the entire game. Our first thought might be to simulate the game and keep track of the friends who have not received the ball yet.\n\n# Approach\n1. We can use a list `res` to keep track of the friends who have not received the ball yet. We initialize `res` with all the friends from 1 to n and remove the first friend since they receive the ball first.\n2. We then use a while loop to simulate the game. In each iteration of the loop, we calculate the next friend to receive the ball using the formula `curr = (curr+(count*k))%n` where `curr` is the current friend holding the ball, `count` is the turn number, and `k` is the number of steps to move in the clockwise direction.\n3. If `curr` is not in `res`, it means that this friend has already received the ball and the game is finished. In this case, we return `res` which contains the losers of the game. Otherwise, we remove `curr` from `res` and increment `count`.\n\n# Complexity\n- Time complexity: $$O(n^2)$$ where n is the number of friends. This is because in the worst case, we need to remove n-1 elements from `res`, and removing an element from a list takes $$O(n)$$ time.\n- Space complexity: $$O(n)$$ since we use a list of size n to keep track of the friends who have not received the ball yet.\n\n# Code\n```\nclass Solution:\n def circularGameLosers(self, n: int, k: int) -> List[int]:\n res = [i for i in range(1,n+1)]\n res.remove(1)\n curr = 1\n count = 1\n while True:\n curr = (curr+(count*k))%n\n if curr == 0:\n curr = n\n if curr not in res:\n return res\n else:\n res.remove(curr)\n count+=1 \n```
| 3 | 0 |
['Math', 'Simulation', 'Python3']
| 0 |
find-the-losers-of-the-circular-game
|
Easy | Brute Force
|
easy-brute-force-by-sourasb-7w5u
|
Code\n\nclass Solution {\n public int[] circularGameLosers(int n, int k) {\n Set<Integer> gotBall = new HashSet<>();\n \n for(int i=1,mu
|
sourasb
|
NORMAL
|
2023-05-14T07:39:28.274673+00:00
|
2023-05-14T07:39:28.274706+00:00
| 1,537 | false |
# Code\n```\nclass Solution {\n public int[] circularGameLosers(int n, int k) {\n Set<Integer> gotBall = new HashSet<>();\n \n for(int i=1,mul=1;!gotBall.contains(i); i = (i+(k*mul))%n,mul++){\n gotBall.add(i);\n }\n if(gotBall.contains(0)){\n gotBall.add(n);\n gotBall.remove(0);\n }\n int[] ans = new int[n-gotBall.size()];\n int index = 0;\n for(int i=1;i<=n;i++) if(!gotBall.contains(i)) ans[index++] = i;\n return ans;\n }\n}\n```
| 3 | 0 |
['Java']
| 0 |
find-the-losers-of-the-circular-game
|
Loser Of Circular Game O(n) time with 100% beats🚀🚀
|
loser-of-circular-game-on-time-with-100-4id7o
|
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
|
sumitkumar-
|
NORMAL
|
2024-10-09T07:03:24.741368+00:00
|
2024-10-09T07:03:24.741404+00:00
| 85 | 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$$O(n)$$\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(n)$$\n\n# Code\n```cpp []\nclass Solution {\npublic:\n vector<int> circularGameLosers(int n, int k) {\n int it=1,hold=1;\n vector<int> arr(n+1,0);\n\n while(arr[hold]!=1){\n arr[hold]++;\n hold=((hold+it*k)%n);\n if(hold==0)\n hold=n;\n it++;\n }\n vector<int> res;\n for(int it=1;it<=n;it++){\n if(arr[it]==0)\n res.push_back(it);\n }\n return res;\n }\n};\n```
| 2 | 0 |
['Array', 'Hash Table', 'Math', 'Two Pointers', 'Simulation', 'C++']
| 0 |
find-the-losers-of-the-circular-game
|
Java HashSet
|
java-hashset-by-hobiter-isga
|
Intuition\n Describe your first thoughts on how to solve this problem. \nEach time it goes to the Remaider\'s friend. Use hashMap to cache all the friend (remai
|
hobiter
|
NORMAL
|
2023-05-15T04:08:26.393647+00:00
|
2023-05-15T04:13:59.482616+00:00
| 856 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nEach time it goes to the Remaider\'s friend. Use hashMap to cache all the friend (remainder) caught the ball.\n\nNote it is 1 indexed, so has to transform to 0 indexed for easy to adop remaineder.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(N)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(N)\n# Code\n```\npublic int[] circularGameLosers(int n, int k) {\n Set<Integer> vis = new HashSet<>();\n int i = 0, rem = 0;\n while(true) {\n rem = (rem + k * i++) % n;\n if (!vis.add(rem)) break; //rem has been visited\n }\n int j = 0, res[] = new int[n - vis.size()];\n for (i = 0; i < n; i++) {\n if (!vis.contains(i)) res[j++] = i + 1;\n }\n return res;\n}\n```
| 2 | 0 |
['Java']
| 0 |
find-the-losers-of-the-circular-game
|
C++|| Easy To Understand || Hashing || Brute Force Approach ✔✔
|
c-easy-to-understand-hashing-brute-force-bapr
|
Code\n\nclass Solution {\npublic:\n vector<int> circularGameLosers(int n, int k) {\n map<int,int> mp;\n int i=1; int turn=1;\n while (mp
|
akanksha984
|
NORMAL
|
2023-05-14T04:07:52.894637+00:00
|
2023-05-14T04:08:05.328873+00:00
| 184 | false |
## Code\n```\nclass Solution {\npublic:\n vector<int> circularGameLosers(int n, int k) {\n map<int,int> mp;\n int i=1; int turn=1;\n while (mp[i]!=1){\n mp[i]++;\n int addy= (i+(turn*k));\n if (addy%n==0)i=n;\n else i= addy%n;\n turn++;\n }\n vector<int> ans;\n for (int i=1; i<=n; i++){\n if (mp[i]==0)ans.push_back(i);\n }\n return ans;\n }\n};\n```
| 2 | 0 |
['Array', 'Hash Table', 'Math', 'Ordered Map', 'C++']
| 0 |
find-the-losers-of-the-circular-game
|
🔥Java || Easy to Understand
|
java-easy-to-understand-by-neel_diyora-hdwd
|
Code\n\nclass Solution {\n public int[] circularGameLosers(int n, int k) {\n boolean[] visited = new boolean[n];\n visited[0] = true;\n
|
anjan_diyora
|
NORMAL
|
2023-05-14T04:02:08.298922+00:00
|
2023-05-14T04:09:36.302177+00:00
| 962 | false |
# Code\n```\nclass Solution {\n public int[] circularGameLosers(int n, int k) {\n boolean[] visited = new boolean[n];\n visited[0] = true;\n \n int i = 0;\n int x = 1; \n while(!visited[(i + (x*k)) % n]) {\n visited[(i + (x*k)) % n] = true;\n i = (i + (x*k)) % n;\n x++;\n }\n \n int count = 0; \n for(boolean b : visited) {\n if(!b) {\n count++;\n }\n }\n \n int[]ans = new int[count];\n int index = 0;\n for(int j = 0; j < visited.length; j++) {\n if(!visited[j]) {\n ans[index++] = j+1;\n }\n }\n return ans;\n }\n}\n```
| 2 | 0 |
['Java']
| 0 |
find-the-losers-of-the-circular-game
|
✔💯 DAY 409 | EASY | 100% | | [PYTHON/JAVA/C++] | EXPLAINED 🆙🆙🆙
|
day-409-easy-100-pythonjavac-explained-u-yow5
|
Please Upvote as it really motivates me \uD83C\uDD99\uD83C\uDD99\uD83C\uDD99\n# Intuition & Approach\n Describe your approach to solving the problem. \ncreate a
|
ManojKumarPatnaik
|
NORMAL
|
2023-05-14T04:01:15.482697+00:00
|
2023-05-14T04:10:53.050525+00:00
| 774 | false |
# Please Upvote as it really motivates me \uD83C\uDD99\uD83C\uDD99\uD83C\uDD99\n# Intuition & Approach\n<!-- Describe your approach to solving the problem. -->\ncreate an array vis of the same size as n and fill it with zeros. Then they iterate over the array and update the value of p using the given formula. They also check if p has already been visited before and break the loop if it has. Finally, they create a list of all the elements that have not been visited and return it.\n\n# Complexity\n- Time complexity:o(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:o(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```java []\npublic int[] circularGameLosers(int n, int k) {\n int vis[] = new int[n+1];\n vis[1]=1;\n int p = 1;\n for(int i=1;i<=n;i++){\n p=(p+(k*i) )%(n);\n if(p==0) p=n;\n if(vis[p]==1) break;\n vis[p]=1;\n \n }\n var list = new ArrayList<Integer>();\n for(int i=1;i<=n;i++){\n if(vis[i]==0){\n list.add(i);\n }\n }return list.stream().mapToInt(i->i).toArray();\n}\n```\n\n```python []\ndef circularGameLosers(self, n: int, k: int) -> List[int]:\n vis = [0] * (n + 1)\n vis[1] = 1\n p = 1\n for i in range(1, n + 1):\n p = (p + k * i) % n\n if p == 0:\n p = n\n if vis[p] == 1:\n break\n vis[p] = 1\n return [i for i in range(1, n + 1) if vis[i] == 0]\n```\n```c++ []\nvector<int> circularGameLosers(int n, int k) {\n vector<int> vis(n + 1, 0);\n vis[1] = 1;\n int p = 1;\n for (int i = 1; i <= n; i++) {\n p = (p + k * i) % n;\n if (p == 0) {\n p = n;\n }\n if (vis[p] == 1) {\n break;\n }\n vis[p] = 1;\n }\n vector<int> res;\n for (int i = 1; i <= n; i++) {\n if (vis[i] == 0) {\n res.push_back(i);\n }\n }\n return res;\n }\n
| 2 | 1 |
['Python', 'C++', 'Java', 'Python3']
| 0 |
find-the-losers-of-the-circular-game
|
Просто лучший
|
prosto-luchshii-by-danisdeveloper-6cqs
|
Code
|
DanisDeveloper
|
NORMAL
|
2025-01-08T11:58:25.545723+00:00
|
2025-01-08T11:58:25.545723+00:00
| 14 | false |

# Code
```kotlin []
class Solution {
fun circularGameLosers(n: Int, k: Int): IntArray {
val used = BooleanArray(n)
var index = 0
var coef = 1
while(!used[index]){
used[index] = true
index = (index + k * coef++) % used.size
}
val result = IntArray(used.count { !it })
var pointer = 0
used.forEachIndexed{ i, value ->
if(!value)
result[pointer++] = i + 1
}
return result
}
}
```
| 1 | 0 |
['Kotlin']
| 0 |
find-the-losers-of-the-circular-game
|
Simple java code 1 ms beats 100 %
|
simple-java-code-1-ms-beats-100-by-arobh-gloz
|
\n# Complexity\n- \n\n# Code\n\nclass Solution {\n public int[] circularGameLosers(int n, int k) {\n int arr[]=new int[n];\n int i=0;\n
|
Arobh
|
NORMAL
|
2023-12-25T10:28:06.149072+00:00
|
2023-12-25T10:28:06.149102+00:00
| 14 | false |
\n# Complexity\n- \n\n# Code\n```\nclass Solution {\n public int[] circularGameLosers(int n, int k) {\n int arr[]=new int[n];\n int i=0;\n int j=k;\n int c=0;\n while(true){\n if(arr[i]==1){\n break;\n }\n c++;\n arr[i]=1;\n i=(i+j)%n;\n j=j+k;\n }\n c=n-c;\n int arr2[]=new int[c];\n j=0;\n for(i=0;i<n;i++){\n if(arr[i]==0){\n arr2[j++]=i+1;\n }\n }\n return arr2;\n }\n}\n```
| 1 | 0 |
['Java']
| 0 |
find-the-losers-of-the-circular-game
|
C# HashSet
|
c-hashset-by-chuletsva-x4v5
|
\npublic class Solution {\n public int[] CircularGameLosers(int n, int k)\n {\n var losers = new HashSet<int>(Enumerable.Range(1, n));\n\n f
|
chuletsva
|
NORMAL
|
2023-08-28T09:49:36.476371+00:00
|
2024-11-02T20:20:01.796658+00:00
| 22 | false |
```\npublic class Solution {\n public int[] CircularGameLosers(int n, int k)\n {\n var losers = new HashSet<int>(Enumerable.Range(1, n));\n\n for (int i = 0, j = 0; losers.Contains(i + 1); i = (i + ++j * k) % n)\n {\n losers.Remove(i + 1);\n }\n\n return losers.ToArray();\n }\n}\n```
| 1 | 0 |
['C#']
| 0 |
find-the-losers-of-the-circular-game
|
Java clean code solution
|
java-clean-code-solution-by-coffeeminato-87md
|
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
|
coffeeminator
|
NORMAL
|
2023-06-27T07:34:55.888468+00:00
|
2023-06-27T07:34:55.888487+00:00
| 118 | 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: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int[] circularGameLosers(int n, int k) {\n\n // the game simulation\n final boolean[] friends = new boolean[n];\n int index = 0;\n int counter = 0;\n int loosersAmount = n;\n\n // the game is finished when some friend receives the ball for the second time\n while (!friends[index]) {\n friends[index] = true;\n --loosersAmount;\n\n index = (index + ++counter * k) % n;\n }\n\n // let\'s gather the loosers\n final int[] loosers = new int[loosersAmount];\n int loosersCount = 0;\n for (int i = 0; i < n; i++) {\n if (!friends[i]) {\n loosers[loosersCount++] = i + 1;\n }\n }\n\n return loosers;\n }\n}\n```
| 1 | 0 |
['Java']
| 0 |
find-the-losers-of-the-circular-game
|
Java Solution
|
java-solution-by-devadharshini-j3n3
|
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
|
Devadharshini_
|
NORMAL
|
2023-06-17T04:08:41.791343+00:00
|
2023-06-17T04:08:41.791371+00:00
| 42 | 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 public int[] circularGameLosers(int n, int k) {\n int i=0,rem=0;\n ArrayList<Integer> set=new ArrayList<>();\n while(true){\n rem=(rem+(k*i))%n;\n if(set.contains(rem+1)){\n break;\n }\n else{\n set.add(rem+1);\n }\n i++;\n }\n ArrayList<Integer> list=new ArrayList<>();\n for(i=1;i<=n;i++){\n if(!set.contains(i)){\n list.add(i);\n }\n }\n int ans[]=new int[list.size()];\n for( i=0;i<list.size();i++){\n ans[i]=list.get(i);\n }\n return ans;\n \n }\n}\n```
| 1 | 0 |
['Java']
| 0 |
find-the-losers-of-the-circular-game
|
C++ Solution || frequency vector
|
c-solution-frequency-vector-by-kunal-bha-fhfk
|
Intuition\nfrequency vector\n\n# Approach\nCreate a vector of length n with initial values 0, Simulate whole process and increment the corresponding index value
|
Kunal-bhamoriya
|
NORMAL
|
2023-05-23T16:43:20.196487+00:00
|
2023-05-23T16:43:20.196523+00:00
| 39 | false |
# Intuition\nfrequency vector\n\n# Approach\nCreate a vector of length n with initial values 0, Simulate whole process and increment the corresponding index value in vector till frequency of any index reaches 2,\n\nfinally Return indexes whose value is 0.\n\n# Complexity\n- Time complexity:\n\n- Space complexity:\n\n# Code\n```\nclass Solution {\npublic:\n vector<int> circularGameLosers(int n, int k) {\n vector<int> v(n,0);\n vector<int> ans;\n int i = 1;\n int index = 0;\n v[index]=1;\n\n while(1){\n if(v[index]>1){\n break;\n }\n index=(index+(i*k))%n;\n v[index]++;\n i++;\n }\n for(int j=0;j<n;j++){\n if(v[j]==0){\n ans.push_back(j+1);\n }\n }\n return ans;\n }\n};\n```
| 1 | 0 |
['C++']
| 0 |
find-the-losers-of-the-circular-game
|
C++ Solution Using Set and Vector
|
c-solution-using-set-and-vector-by-codin-ebe0
|
\n\n# Complexity\n- Time complexity:O(N)\n Add your time complexity here, e.g. O(n) \n\n- Space complexity:O(N)\n Add your space complexity here, e.g. O(n) \n\n
|
coding_girl
|
NORMAL
|
2023-05-23T07:20:53.001710+00:00
|
2023-05-23T07:20:53.001749+00:00
| 19 | false |
\n\n# Complexity\n- Time complexity:O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(N)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code using Set\n```\nclass Solution {\npublic:\n vector<int> circularGameLosers(int n, int k) {\n vector<int> ans;\n unordered_set<int> s;\n int turn=1;\n int curr=1;\n while(1){\n s.insert(curr);\n curr+=turn*k;\n if(curr>n) curr%=n;\n if(curr==0) curr=n;\n turn++;\n if(s.find(curr)!=s.end())\n break;\n \n }\n for(int i=1;i<=n;i++){\n if(s.find(i)==s.end())\n ans.push_back(i);\n \n }\n return ans;\n \n }\n};\n```\n\n\n# Code using Vector\n```\nclass Solution {\npublic:\n vector<int> circularGameLosers(int n, int k) {\n vector<int> v(n+1,0);\n int curr=1,turn=1;\n while(v[curr]==0){\n v[curr]++;\n curr=(curr+turn*k)%n;\n if(curr==0) curr=n;\n turn++;\n }\n vector<int> ans;\n for(int i=1;i<=n;i++){\n if(v[i]==0)\n ans.push_back(i);\n }\n return ans;\n }\n};\n```
| 1 | 0 |
['C++']
| 1 |
find-the-losers-of-the-circular-game
|
java Simple Solution using HashSet
|
java-simple-solution-using-hashset-by-ka-w6xj
|
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
|
Kashi_27
|
NORMAL
|
2023-05-20T08:52:18.739079+00:00
|
2023-05-20T08:52:18.739290+00:00
| 21 | 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 public int[] circularGameLosers(int n, int k) {\n HashSet<Integer> set = new HashSet<>();\n\n int i=0;\n int count=0;\n while(true)\n {\n \n i=i+k*count++;\n i=i%n;\n if(set.contains(i)) break;\n else set.add(i);\n \n }\n int[] result = new int[n-set.size()];\n int j=0;\n for( i=0;i<n;i++)\n {\n if(!set.contains(i))\n {\n result[j++]=i+1;\n }\n }\n return result;\n }\n}\n```
| 1 | 0 |
['Java']
| 0 |
find-the-losers-of-the-circular-game
|
C++ - Iterative
|
c-iterative-by-jay0411-hiop
|
\nclass Solution {\npublic:\n vector<int> circularGameLosers(int n, int k) {\n\t\t// Here I\'ve used 0 based indexing, so range will be [0, ..., n-1].\n\t\t\
|
jay0411
|
NORMAL
|
2023-05-15T13:06:40.094571+00:00
|
2023-05-15T13:16:35.404896+00:00
| 514 | false |
```\nclass Solution {\npublic:\n vector<int> circularGameLosers(int n, int k) {\n\t\t// Here I\'ve used 0 based indexing, so range will be [0, ..., n-1].\n\t\t\n\t\t// Assign the ball count for all friends to 0.\n vector<int> count(n, 0), res;\n\t\t\n\t\t// We start from the first friend, \n\t\t// so assign starting value for first friend to 1.\n int start = 0, i = 1;\n count[start] = 1;\n \n\t\t// Loop until we found the friend which got 2nd time ball\n while(count[start] != 2)\n {\n start = (start + (i * k)) % n;\n count[start]++;\n i++;\n }\n \n for(int i = 0; i < n; i++)\n {\n if(count[i] == 0)\n res.push_back(i + 1);\n }\n return res;\n }\n};\n```
| 1 | 0 |
['C']
| 0 |
find-the-losers-of-the-circular-game
|
🔥C++ ✅ Best Solution ( 🔥 🔥 ) Easy to Understand💯💯 ⬆⬆⬆
|
c-best-solution-easy-to-understand-by-7m-d4kg
|
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
|
7mm
|
NORMAL
|
2023-05-14T18:08:04.884904+00:00
|
2023-05-14T18:08:04.884948+00:00
| 943 | 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 vector<int> circularGameLosers(int n, int k) {\n vector<int>ans(n,1);\n vector<int>ans2;\n int i=2;\n ans[0]=0;\n int first=0,temp=k;\n \n while(true)\n {\n \n first=(first+temp)%n;\n if(ans[first]==0) break;\n else\n {\n\n ans[first]=0;\n temp=k*i;\n i++;\n }\n }\n for(int j=0;j<ans.size();j++)\n {\n if(ans[j]==1) {ans2.push_back(j+1);}\n }\n return ans2;\n \n }\n};\n\n\n```
| 1 | 0 |
['C++']
| 0 |
find-the-losers-of-the-circular-game
|
C++ || Easy || Set solution
|
c-easy-set-solution-by-vinayak_sahu-nldv
|
\n vector circularGameLosers(int n, int k)\n {\n unordered_set s;\n \n int curr = 1, i = 1;\n \n
|
vinayak_sahu
|
NORMAL
|
2023-05-14T09:51:34.337531+00:00
|
2023-05-14T09:51:34.337570+00:00
| 57 | false |
\n vector<int> circularGameLosers(int n, int k)\n {\n unordered_set<int> s;\n \n int curr = 1, i = 1;\n \n while (s.find(curr) == s.end())//stopping condition\n {\n s.insert(curr);//mask as visited\n curr = (curr + i *k ) % n;\n if (curr == 0) curr = n;\n i++;\n }\n vector<int> ans;\n for (int i = 1; i <= n; i++)//check which are not visited\n {\n if (s.find(i) == s.end())\n ans.push_back(i);\n }\n return ans;\n }\n
| 1 | 0 |
['C', 'Ordered Set', 'C++']
| 0 |
find-the-losers-of-the-circular-game
|
python3 Solution
|
python3-solution-by-motaharozzaman1996-bdxl
|
\n\nclass Solution:\n def circularGameLosers(self, n: int, k: int) -> List[int]:\n ans=[0]\n m=k\n while True:\n if (ans[-1]+
|
Motaharozzaman1996
|
NORMAL
|
2023-05-14T09:23:30.815938+00:00
|
2023-05-14T09:23:30.815977+00:00
| 769 | false |
\n```\nclass Solution:\n def circularGameLosers(self, n: int, k: int) -> List[int]:\n ans=[0]\n m=k\n while True:\n if (ans[-1]+m)%n not in ans:\n ans.append((ans[-1]+m)%n)\n m=m+k\n\n else:\n break\n\n\n return [i+1 for i in range(n) if i not in ans] \n```
| 1 | 0 |
['Python', 'Python3']
| 0 |
find-the-losers-of-the-circular-game
|
Implementation
|
implementation-by-_kitish-kmlv
|
Code\n\nclass Solution {\npublic:\n vector<int> circularGameLosers(int n, int k) {\n unordered_map<int,bool> mp;\n vector<int> ans;\n lo
|
_kitish
|
NORMAL
|
2023-05-14T08:05:41.956916+00:00
|
2023-05-14T08:05:41.956960+00:00
| 26 | false |
# Code\n```\nclass Solution {\npublic:\n vector<int> circularGameLosers(int n, int k) {\n unordered_map<int,bool> mp;\n vector<int> ans;\n long long st = 0, i = 1;\n while(!mp.count(st)){\n mp[st] = true;\n st += i*k;\n st %= n;\n i++;\n }\n for(int i=0; i<n; ++i)\n if(!mp.count(i)) ans.push_back(i+1);\n return ans;\n }\n};\n```
| 1 | 0 |
['Simulation', 'C++']
| 0 |
find-the-losers-of-the-circular-game
|
Simple Short C++ Solution | TC : O(N) | SC : O(N)
|
simple-short-c-solution-tc-on-sc-on-by-v-x0cm
|
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
|
vedant_rawale
|
NORMAL
|
2023-05-14T06:12:39.685453+00:00
|
2023-05-14T06:12:39.685501+00:00
| 22 | 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:O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(N)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n vector<int> circularGameLosers(int n, int k) {\n vector<int> v(n+1,0);\n int j = 1;\n vector<int> ans;\n for(int i =1;i<=n;i++){\n if((j%n==0 && v[n]==1)||(v[j%n]==1)) break;\n else{\n if(j%n==0) v[n]=1;\n else v[j%n]=1; \n j+=(i*k)%n;\n }\n }\n for(int i =1;i<n+1;i++){\n if(v[i]==0) ans.push_back(i);\n }\n return ans;\n }\n};\n```
| 1 | 0 |
['C++']
| 0 |
find-the-losers-of-the-circular-game
|
Easy to read simulation solution
|
easy-to-read-simulation-solution-by-efor-vk7u
|
Code\n\n/**\n * @param {number} n\n * @param {number} k\n * @return {number[]}\n */\nvar circularGameLosers = function(n, k) {\n const players = new Array(n)
|
eforce
|
NORMAL
|
2023-05-14T05:43:19.280231+00:00
|
2023-05-14T05:43:19.280261+00:00
| 311 | false |
# Code\n```\n/**\n * @param {number} n\n * @param {number} k\n * @return {number[]}\n */\nvar circularGameLosers = function(n, k) {\n const players = new Array(n).fill(0);\n let index = 0;\n let turn = 1;\n \n while (true) {\n ++players[index];\n if (players[index] === 2) break;\n index += turn++ * k;\n index %= n;\n }\n\n const result = [];\n\n for (let i = 1; i < n; ++i) {\n if (players[i] === 0) result.push(i + 1);\n }\n\n return result;\n};\n```
| 1 | 0 |
['JavaScript']
| 0 |
find-the-losers-of-the-circular-game
|
C++ || Easy approach
|
c-easy-approach-by-mrigank_2003-b5az
|
Here is my c++ code for this problem.\n\n# Complexity\n- Time complexity:O(n)\n\n- Space complexity:O(n)\n\n# Code\n\nclass Solution {\npublic:\n vector<int>
|
mrigank_2003
|
NORMAL
|
2023-05-14T04:49:24.086209+00:00
|
2023-05-14T04:49:24.086268+00:00
| 822 | false |
Here is my c++ code for this problem.\n\n# Complexity\n- Time complexity:$$O(n)$$\n\n- Space complexity:$$O(n)$$\n\n# Code\n```\nclass Solution {\npublic:\n vector<int> circularGameLosers(int n, int k) {\n vector<int>v(n, 0), ans;\n int i=0, turn=1;\n while(v[i]!=1){\n v[i]=1;\n cout<<i<<" "<<(turn*k)%n<<endl;\n i=(i+(turn*k)%n)%n;\n turn++;\n }\n for(int k=0; k<n; k++){\n if(!v[k]){\n ans.push_back(k+1);\n }\n }\n return ans;\n }\n};\n```
| 1 | 0 |
['C++']
| 0 |
find-the-losers-of-the-circular-game
|
CPP EASY SOLUTION
|
cpp-easy-solution-by-ankit_kumar12345-eeww
|
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
|
ankit_kumar12345
|
NORMAL
|
2023-05-14T04:46:23.222760+00:00
|
2023-05-14T04:46:23.222798+00:00
| 410 | 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\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n vector<int> circularGameLosers(int n, int k) {\n vector<int>frq(n+1,0);\n vector<int>ans;\n int i = 0;\n int round = 1;\n while(true){\n frq[i]++;\n if(frq[i] >= 2) break;\n i = (i + ( round++ * k))%n;\n }\n for(int i = 0 ; i<n ; i++)\n if( frq[i] == 0) ans.push_back(i+1);\n\n return ans;\n }\n};\n```
| 1 | 0 |
['C++']
| 0 |
find-the-losers-of-the-circular-game
|
✅🚀 || Steps Explained || Beginner friendly || JAVA ||
|
steps-explained-beginner-friendly-java-b-uofq
|
Approach\n Describe your approach to solving the problem. \nSince, the index of an array starts from 0 there will be a huge confusion during the circular traver
|
aeroabrar_31
|
NORMAL
|
2023-05-14T04:45:21.836559+00:00
|
2023-05-14T04:45:21.836585+00:00
| 244 | false |
# Approach\n<!-- Describe your approach to solving the problem. -->\nSince, the index of an array starts from 0 there will be a huge confusion during the circular traversal.\nThe cicular traversal of an array is always a hectic process until or unless you don\'t know how to handle the edge cases.\n\nHere, by following the gven above conditions:\n\nOur Solution includes 3 steps\n1. Passing the ball and marking the **visited** friends in visited array.\n2. Finding the no of losers(unvisited) from visited array.\n3. Adding the losers(unvisited) to the resultant array and returning it.\n\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(N)$$\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(N)$$\n\n# Code\n\n\n```java []\nclass Solution {\n public int[] circularGameLosers(int n, int k) {\n \n boolean[] vis=new boolean[n+1];\n \n //Step - 1\n int curr_friend=1,i=1;\n do\n {\n vis[curr_friend]=true;\n curr_friend=(curr_friend+i*k)%n;\n if(curr_friend==0)\n {\n curr_friend=n;\n }\n i++;\n }while(vis[curr_friend]==false);\n \n \n //Step-2\n int size=0;\n for( i=1;i<=n;i++)\n {\n if(!vis[i])\n size++;\n }\n\n //Step-3\n int[] res=new int[size];\n int j=0;\n for( i=1;i<=n;i++)\n {\n if(!vis[i])\n res[j++]=i;\n }\n \n return res;\n }\n}\n\n\n```
| 1 | 0 |
['Array', 'Game Theory', 'Java']
| 0 |
find-the-losers-of-the-circular-game
|
[JAVA] Easy - Simulation✅Fully Explained
|
java-easy-simulationfully-explained-by-_-cq5t
|
Feel free to suggest any improvements, corrections\uD83D\uDC4D\uD83C\uDFFB\nDo UPVOTE\uD83D\uDD3A\n\nclass Solution {\n public int[] circularGameLosers(int n
|
_krishna_Singh
|
NORMAL
|
2023-05-14T04:35:37.668617+00:00
|
2023-05-14T04:35:37.668639+00:00
| 327 | false |
Feel free to suggest any improvements, corrections\uD83D\uDC4D\uD83C\uDFFB\nDo **UPVOTE**\uD83D\uDD3A\n```\nclass Solution {\n public int[] circularGameLosers(int n, int k) {\n int[] map = new int[n];\n\t\t//map[i] tracks the number of times ith member recieves the ball\n \n int i = 0, cnt = 1;\n while(true){\n map[i]++;\n if(map[i] == 2) break; //break out of the loop whenever any member recieves the ball 2nd time, i.e. GAME_OVER\n i = (i + (cnt * k)) % n;\n cnt++; //to increase the multiple of k: k, 2*k, 3*k, 4*k, etc\n }\n \n int len = 0; //For storing how many members are the losers, i.e. did not recieve the ball even once\n for(int num : map) if(num == 0) len++;\n \n \n int index = 0, ans[] = new int[len];\n for(int j=0;j<n;j++){\n if(map[j] == 0) ans[index++] = j+1; \n }\n return ans;\n }\n}\n```
| 1 | 0 |
['Simulation', 'Java']
| 1 |
find-the-losers-of-the-circular-game
|
hashing c++ solution
|
hashing-c-solution-by-kumarsankalp-d0zt
|
Intuition\n we will decleare a hash array of size n+1 intially marked with zero . freind will start 1 to n . we will mark hash(i)=1 as we get the ball pass to
|
kumarSankalp
|
NORMAL
|
2023-05-14T04:31:45.045738+00:00
|
2023-05-14T04:31:45.045787+00:00
| 369 | false |
# Intuition\n we will decleare a hash array of size n+1 intially marked with zero . freind will start 1 to n . we will mark hash(i)=1 as we get the ball pass to freind . before marking we will check that wether it is previously marked or not , if it is marked as 1 then that freind is geeting ball second time and the game end by break out of loop \n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:O(n)+O(n) = O(2n) ; \n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n) for hash array \n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n vector<int> circularGameLosers(int n, int k) {\n \n vector<int>hash(n+1,0) ; \n hash[1]=1 ; \n vector<int>ans ; \n \n int prev = 1 ; \n int i =1 ; \n while(1) \n {\n int nextstep = i*k ; \n int move = (prev+nextstep)%n ; \n if (move%n==0)move=n;\n \n if(hash[move]==0) \n {\n hash[move] =1 ; \n prev = move ;\n \n }\n else \n {\n break ; \n } \n i++ ; \n \n }\n for( int i = 1 ; i<=n ; i++) \n {\n if(hash[i]==0) \n ans.push_back(i) ; \n }\n \n \n return ans ; \n }\n};\n```
| 1 | 0 |
['C++']
| 1 |
find-the-losers-of-the-circular-game
|
ONLY MAP:EXPLAINED EASY TO UNDERSTAND
|
only-mapexplained-easy-to-understand-by-bndex
|
Intuition\nuse map to mark the friend that received the ball\n\n# Approach\nbe carefull when your next friends value come to zero then you make that value equal
|
ajayadhikari
|
NORMAL
|
2023-05-14T04:05:53.416221+00:00
|
2023-05-14T04:05:53.416265+00:00
| 55 | false |
# Intuition\nuse map to mark the friend that received the ball\n\n# Approach\nbe carefull when your next friends value come to zero then you make that value equal to n because 0 is not a friend and for finding the next value of friend simply int** **nf=(currf + (i+1)*k) % n;**** and make your current friend cf equal to newfriend nf, \n\n1.Also store the number of friend at vector or any datastructure to keep track of marked one and lastly return the unmarked one\n\n# Complexity\n- Time complexity:\n appx O(N)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n vector<int> circularGameLosers(int n, int k) {\n if(k>n) return {};\n vector<int> ans;\n vector<int> temp;\n for(int i=0;i<n;i++)\n {\n temp.push_back(i+1);\n }\n map<int , int> mp;\n mp[1]=1;\n int currf=1;\n for(int i=0;i<1000;i++)\n {\n \n int nf=(currf + (i+1)*k) % n;\n if (nf == 0) {\n nf = n;\n }\n if(mp[nf]==1) break;\n mp[nf]=1;\n currf=nf; \n }\n for(auto i:temp)\n {\n if(mp[i]==0)\n {\n ans.push_back(i);\n }\n }\n return ans;\n \n }\n};\n```
| 1 | 0 |
['C++']
| 0 |
find-the-losers-of-the-circular-game
|
Easy JAVA Solution || 100 Faster
|
easy-java-solution-100-faster-by-mayur01-q97v
|
\n\nclass Solution {\n public int[] circularGameLosers(int n, int k) {\n \n Set<Integer> set=new HashSet<>();\n set.add(1);\n int
|
mayur0106
|
NORMAL
|
2023-05-14T04:05:03.787480+00:00
|
2023-05-14T04:05:03.787522+00:00
| 61 | false |
\n```\nclass Solution {\n public int[] circularGameLosers(int n, int k) {\n \n Set<Integer> set=new HashSet<>();\n set.add(1);\n int i=1;\n int m=1;\n while(true)\n {\n int cal=m*k;\n m++;\n int current = cal+i;\n i=current%n;\n if(i==0) i=n;\n if(set.contains(i))\n {\n break;\n }\n set.add(i); \n }\n int []arr=new int[n-set.size()];\n int j=0;\n for(i=2;i<=n;i++)\n {\n if(!set.contains(i)) arr[j++]=i;\n }\n return arr;\n }\n}\n```
| 1 | 1 |
['Java']
| 0 |
find-the-losers-of-the-circular-game
|
c++ O(n) solution Beats 95.24%
|
c-on-solution-beats-9524-by-augus7-c1vn
|
\n# Complexity\n- Time complexity: O(n)\n Add your time complexity here, e.g. O(n) \n\n- Space complexity: O(n)\n Add your space complexity here, e.g. O(n) \n\n
|
Augus7
|
NORMAL
|
2023-05-14T04:04:11.312280+00:00
|
2023-05-14T04:04:11.312317+00:00
| 408 | false |
\n# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n vector<int> circularGameLosers(int n, int k) {\n int turn = 2;\n vector<int> vec, vis(n);\n int i = k;\n while(i >= n) i -= n;\n vis[0] = 1;\n\n while(true) {\n if(vis[i]) break;\n vis[i] = 1;\n i += (k * turn);\n while(i >= n) i = i - n;\n turn++;\n }\n\n for(int i = 0; i < n; i++) {\n if(!vis[i]) vec.push_back(i + 1);\n }\n return vec;\n }\n};\n```
| 1 | 0 |
['C++']
| 0 |
find-the-losers-of-the-circular-game
|
Rust/Python. Linear. Track people who have been selected
|
rustpython-linear-track-people-who-have-3p4kv
|
Intuition\nStore all positions of people who has already been selected. Then iterate over all jumps (there will be at most n of them) until you will see a selec
|
salvadordali
|
NORMAL
|
2023-05-14T04:02:52.403603+00:00
|
2023-05-14T04:02:52.403634+00:00
| 160 | false |
# Intuition\nStore all positions of people who has already been selected. Then iterate over all jumps (there will be at most n of them) until you will see a selected person. \n\nThen return all people who has not been selected.\n\n\n# Complexity\n- Time complexity: $O(n)$\n- Space complexity: $O(n)$\n\n# Code\n\n\n\n```Python []\nclass Solution:\n def circularGameLosers(self, n: int, k: int) -> List[int]:\n seen = [0] * n\n seen[0] = 1\n \n pos, jump = 0, k\n while True:\n pos = (pos + jump) % n\n if seen[pos]:\n break\n \n seen[pos] = 1\n jump += k\n \n return [i + 1 for i in range(n) if seen[i] == 0]\n```\n```Rust []\nimpl Solution {\n pub fn circular_game_losers(n: i32, k: i32) -> Vec<i32> {\n let mut seen = vec![false; n as usize];\n seen[0] = true;\n\n let (mut pos, mut jump) = (0, k);\n loop {\n pos = (pos + jump) % n;\n if seen[pos as usize] {\n break;\n }\n \n seen[pos as usize] = true;\n jump += k;\n }\n \n let mut res = vec![];\n for i in 0 .. n {\n if !seen[i as usize] {\n res.push(i + 1);\n }\n }\n \n return res;\n }\n}\n```\n
| 1 | 0 |
['Python', 'Rust']
| 0 |
find-the-losers-of-the-circular-game
|
2682. Find the Losers of the Circular Game - JAVA SOL
|
2682-find-the-losers-of-the-circular-gam-13bw
|
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
|
Ayu10x
|
NORMAL
|
2023-05-14T04:01:04.895131+00:00
|
2023-05-14T04:01:04.895169+00:00
| 207 | 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 public int[] circularGameLosers(int n, int k) {\n int[] result = new int[n];\n int[] p = new int[n + 1];\n int i = 1, j = 1, count = 0; \n while (p[i] == 0) {\n p[i] = -1;\n i = (i + (j * k));\n while (i > n)\n i -= n;\n j++;\n }\n for (i = 1; i <= n; i++) {\n if (p[i] != -1) {\n result[count++] = i;\n }\n }\n return Arrays.copyOf(result, count);\n }\n}\n```
| 1 | 0 |
['Java']
| 0 |
find-the-losers-of-the-circular-game
|
Python Using Mod Beginners
|
python-using-mod-beginners-by-shtanriver-t7ij
|
\nclass Solution:\n def circularGameLosers(self, n: int, k: int) -> List[int]:\n losers = [0]*n\n losers[0] = 1\n index = 0\n tur
|
shtanriverdi
|
NORMAL
|
2023-05-14T04:01:00.186535+00:00
|
2023-05-14T04:01:00.186575+00:00
| 106 | false |
```\nclass Solution:\n def circularGameLosers(self, n: int, k: int) -> List[int]:\n losers = [0]*n\n losers[0] = 1\n index = 0\n turn = 1\n while losers[index] != 2:\n index = ((turn * k) + index) % n\n losers[index] += 1\n turn += 1\n \n answer = []\n for index, loser in enumerate(losers):\n if loser == 0:\n answer.append(index + 1)\n \n return answer\n```
| 1 | 0 |
['Python']
| 0 |
find-the-losers-of-the-circular-game
|
Python3: Simulate + adjust index for modulo
|
python3-simulate-adjust-index-for-modulo-2wha
|
IntuitionApproachComplexity
Time complexity: O(n)
Space complexity: O(n) (using set)
Code
|
tfwre342
|
NORMAL
|
2025-03-22T09:45:53.845878+00:00
|
2025-03-22T09:45:53.845878+00:00
| 2 | false |
# Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity: O(n)
- Space complexity: O(n) (using set)
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```python3 []
class Solution:
def circularGameLosers(self, n: int, k: int) -> List[int]:
# Base Case: 1st friend wins
if k == n:
return list(range(2,n+1))
frens = set() # Contain winners
count = 1
i = 1 # First friend
while i not in frens:
frens.add(i)
steps = count * k
# Adjust 1-indexed frens to 0 for modulo
adjust_frens = (i + steps - 1)
# Adjust back to 1-indexed
i = (adjust_frens % n) + 1 # Forward circular
count += 1
# Extract losers
losers = [i for i in range(1, n+1) if i not in frens]
return losers
```
| 0 | 0 |
['Python3']
| 0 |
find-the-losers-of-the-circular-game
|
🔥✅✅ Dart Solution 📌📌 || with Explanation 👌👌
|
dart-solution-with-explanation-by-nosar-nb7c
|
Solution
Initialization: We create a list received of size n + 1 to keep track of which friends have received the ball. The +1 is to match the friend numbering
|
NosaR
|
NORMAL
|
2025-03-21T07:54:38.412756+00:00
|
2025-03-21T07:54:38.412756+00:00
| 2 | false |
# Solution
- **Initialization**: We create a list `received` of size `n + 1` to keep track of which friends have received the ball. The `+1` is to match the friend numbering (1-based indexing).
- **Simulation**: We start with the 1st friend and simulate the passing of the ball. The next friend is calculated using modulo arithmetic to handle the circular nature of the friends.
- **Termination**: The game ends when a friend receives the ball for the second time.
- **Losers**: After the game ends, we iterate through the `received` list to find friends who never received the ball and add them to the `losers` list.
### Time Complexity:
- The time complexity is `O(n)` in the worst case because we might have to pass the ball to all `n` friends before a friend receives the ball for the second time.
- The space complexity is `O(n)` due to the storage of the `received` array.
```dart
class Solution {
List<int> circularGameLosers(int n, int k) {
List<bool> received = List.filled(n + 1, false);
int currentFriend = 1;
received[currentFriend] = true;
int turn = 1;
while (true) {
int steps = turn * k;
int nextFriend = (currentFriend + steps - 1) % n + 1;
if (received[nextFriend]) {
break;
}
received[nextFriend] = true;
currentFriend = nextFriend;
turn++;
}
List<int> losers = [];
for (int i = 1; i <= n; i++) {
if (!received[i]) {
losers.add(i);
}
}
return losers;
}
}
```
| 0 | 0 |
['Dart']
| 0 |
find-the-losers-of-the-circular-game
|
C++ | O(N) efficient solution but ugly code
|
c-on-efficient-solution-but-ugly-code-by-ntgj
|
IntuitionThere are 2 parts to this problem:
Simulate the game and keep track of who received the ball
Find everyone who lost the game and sort them in ascending
|
serrabassaoriol
|
NORMAL
|
2025-03-20T22:32:19.144506+00:00
|
2025-03-20T22:36:18.930299+00:00
| 1 | false |
# Intuition
There are 2 parts to this problem:
- Simulate the game and keep track of who received the ball
- Find everyone who lost the game and sort them in ascending order
## *unordered_set*
Originally, I thought about using 2 *unordered_set* to keep track of all the players that received the ball and those who did not. That way, I could easily check if a player received the ball for the second time and be able to know when the game should end.
The reason why an *unordered_set* approach is not the most efficient solution for this problem is that there is no practical way to retrieve the players that lost the game and have them in ascending order.
The only method to achieve that would be to iterate the *unordered_set* of players that never received the ball while creating and filling the output vector. However, that alone would not be enough, since *unordered_set*, as the name implies, does not preserve any order. Therefore, to guarantee that the output vector is in ascending order, a sort is required and that takes O(N * log(N)).
I have not tested if such approach would be accepted in this problem, but considering the problem's constraint, it should be perfectly fine.
## *set*
As using an *unordered_set* was out of the question, I wondered how using a *set* instead would make things different.
On one hand, using a *set* avoids having to sort the output vector which means we can avoid an O(N * log(N)) operation. On the other hand, the insert and find operation in a *set* have a O(log(N)) time complexity.
After each game turn, we could end up having to perform a delete operation on the *set* in order to remove a player that never received a ball until that moment. So, in other words, we are still stuck with a time complexity of O(N * log(N)).
In the worst case, a game can have 0 losers, meaning that all the players received the ball once and we had to perform N delete operations on the *set*.
## *vector<bool>*
Neither an *unordered_set* and a *set* allows us to reach the best time complexity for this problem which would be O(N). Then, how can we achieve that?
There were 2 main roadblocks that prevented us from getting that O(N) time complexity:
- Sort the output solution (O(N * log(N)))
- Inefficient insertion, deletion and search operations (O(log(N)))
Knowing that, which data structure can we use to overcome those issues? Thanks to how this problem works, the best data structure that fits these needs and requirements is a *vector*, array or similar.
A *vector* has amortized constant time complexity for its insertion and delete operations. Although, for the solution that I have come up with, we do not need to perform any insertion or deletion operation.
Technically, finding a specific element in a *vector* is an O(N) operation as you would need to traverse the whole *vector*. However, since all the players are numbered from 1 to N, we can map each player's number to a valid vector index position by simply subtracting 1 from the player number and achieve a constant O(1) operation.
- Player 1 = 0 index position in *vector*
- Player N = N - 1 index position in *vector*
This allows us to have a *vector* which pretty much behaves like an *unordered_set*. I am specifically going to use a *vector* that stores *bool* values to indicate if a player has received or not received the ball yet.
# Approach
There are 2 parts to this problem:
- Simulate the game and keep track of who received the ball
- Create a *vector<bool>* data structure to track the players who have received the ball
- Create a loop that will continue simulating the game until you get to a player which has already previously received the ball
- Inside the loop, update the ball's pass distance and set to *true* the player that received the ball on that particular game turn
- (Optional) Keep track of the number of players that have not received the ball
- Find everyone who lost the game and sort them in ascending order
- To know which players lost the game, iterate the *vector<bool>* and check for any player who has its *bool* value set to *false*
- No need to specifically sort the output in ascending order because by iterating the *vector<bool>* we are already doing so
- (Optional) If you kept track of the number of players that have not received the ball, you can exit early this *vector<bool>* loop whenever the ouput vector size matches with the number of players that do not have received the ball. This optimization can improve efficiency considerably in the cases where all the game losers are the initial players.
# Complexity
- Time complexity: O(2N) = O(N)
- O(N) for simulating the game
- O(N) for creating the output solution
- Space complexity: O(N)
- O(N) for a helper data structure to keep track of which players have received or not received a ball
- I do not count the space required to return the problem solution
# Code
```cpp []
#include <vector>
#include <cstdint>
class Solution {
public:
std::vector<int> circularGameLosers(int n, int k) {
uint8_t players_ball_counter = 0;
std::vector<bool> players_who_received_ball = std::vector<bool>(n, false);
for (
uint16_t player_index = 0,
turn = 1,
distance = turn * k;
!players_who_received_ball[player_index];
(
player_index = (player_index + distance) % n,
turn++,
distance = turn * k
)
) {
players_who_received_ball[player_index] = true;
players_ball_counter++;
}
std::vector<int32_t> players_who_never_received_ball = std::vector<int32_t>(n - players_ball_counter);
for (
uint8_t iterator_index = 0,
result_index = 0;
result_index != players_who_never_received_ball.size();
iterator_index++
) {
if (!players_who_received_ball[iterator_index]) {
players_who_never_received_ball[result_index] = iterator_index + 1;
result_index++;
}
}
return players_who_never_received_ball;
}
};
```
| 0 | 0 |
['C++']
| 0 |
find-the-losers-of-the-circular-game
|
Find the Players Who Never Receive the Ball in a Circular Game
|
find-the-players-who-never-receive-the-b-1795
|
IntuitionThe game follows a circular sequence where each step size increases by k after each move. Players who are never visited are the "losers." We need an ef
|
Koda_O
|
NORMAL
|
2025-03-11T14:36:54.434013+00:00
|
2025-03-11T14:36:54.434013+00:00
| 0 | false |
# **Intuition**
The game follows a **circular sequence** where each step size increases by `k` after each move. Players who are never visited are the "losers." We need an efficient way to track visited players while ensuring we correctly handle the circular movement.
# **Approach**
- Use a **Boolean list (`visited`)** to track players who have received the ball.
- Start from player **1 (index 0)** and move by `k` steps, incrementing the step size by `k` after each move.
- Stop when a player is **visited twice**, indicating a loop.
- Return the list of players who were **never visited**.
# **Complexity**
- **Time complexity:**
$$O(n)$$ – Each player is visited at most once.
- **Space complexity:**
$$O(n)$$ – We use a Boolean list of size `n`.
# **Code**
```python
from typing import List
class Solution:
def circularGameLosers(self, n: int, k: int) -> List[int]:
visited = [False] * n
i, step = 0, k
while not visited[i]:
visited[i] = True
i = (i + step) % n
step += k
return [j + 1 for j in range(n) if not visited[j]]
```
This approach ensures an **efficient and optimized** solution.
| 0 | 0 |
['Array', 'Hash Table', 'Math', 'Ordered Map', 'Simulation', 'Python3']
| 0 |
find-the-losers-of-the-circular-game
|
Find the Players Who Never Receive the Ball in a Circular Game
|
find-the-players-who-never-receive-the-b-3q8z
|
IntuitionThe game follows a circular sequence where each step size increases by k after each move. Players who are never visited are the "losers." We need an ef
|
Koda_O
|
NORMAL
|
2025-03-11T14:36:51.504117+00:00
|
2025-03-11T14:36:51.504117+00:00
| 2 | false |
# **Intuition**
The game follows a **circular sequence** where each step size increases by `k` after each move. Players who are never visited are the "losers." We need an efficient way to track visited players while ensuring we correctly handle the circular movement.
# **Approach**
- Use a **Boolean list (`visited`)** to track players who have received the ball.
- Start from player **1 (index 0)** and move by `k` steps, incrementing the step size by `k` after each move.
- Stop when a player is **visited twice**, indicating a loop.
- Return the list of players who were **never visited**.
# **Complexity**
- **Time complexity:**
$$O(n)$$ – Each player is visited at most once.
- **Space complexity:**
$$O(n)$$ – We use a Boolean list of size `n`.
# **Code**
```python
from typing import List
class Solution:
def circularGameLosers(self, n: int, k: int) -> List[int]:
visited = [False] * n
i, step = 0, k
while not visited[i]:
visited[i] = True
i = (i + step) % n
step += k
return [j + 1 for j in range(n) if not visited[j]]
```
This approach ensures an **efficient and optimized** solution.
| 0 | 0 |
['Array', 'Hash Table', 'Math', 'Ordered Map', 'Simulation', 'Python3']
| 0 |
find-the-losers-of-the-circular-game
|
simple dict solution
|
simple-dict-solution-by-js8nlxv9hy-k2pz
|
IntuitionApproachComplexity
Time complexity:
Space complexity:
Code
|
JS8nlXv9hy
|
NORMAL
|
2025-02-26T09:04:01.105862+00:00
|
2025-02-26T09:04:01.105862+00:00
| 3 | 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 circularGameLosers(self, n: int, k: int) -> List[int]:
d = defaultdict(bool)
i = 0
c = 0
x = 0
res = []
while True:
x = (i + c *k) % (n)
#print("x",x,d)
if x in d:
break
else:
d[x] = True
i = x
c +=1
#print(x,i)
for i in range(1,n+1):
if i-1 not in d:
res.append(i)
return res
```
| 0 | 0 |
['Array', 'Hash Table', 'Simulation', 'Python3']
| 0 |
find-the-losers-of-the-circular-game
|
c++(0ms) iterative
|
c0ms-iterative-by-zx007pi-j9vw
|
IntuitionApproachComplexity
Time complexity:
Space complexity:
Code
|
zx007pi
|
NORMAL
|
2025-02-01T07:27:28.975607+00:00
|
2025-02-01T07:27:28.975607+00:00
| 4 | 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:
vector<int> circularGameLosers(int n, int k) {
vector<int> t(n,0), ans;
t[0] = 1;
for(int i = 1, id = 0; ;++i){
id += k*i%n;
if(id >= n) id -= n;
if(t[id]++) break;
}
for(int i = 0; i != n; ++i)
if(t[i] == 0) ans.push_back(i+1);
return ans;
}
};
```
| 0 | 0 |
['C++']
| 0 |
find-the-losers-of-the-circular-game
|
[C++] Simple Solution
|
c-simple-solution-by-samuel3shin-0nvp
|
Code
|
Samuel3Shin
|
NORMAL
|
2025-01-27T15:54:03.067916+00:00
|
2025-01-27T15:54:03.067916+00:00
| 4 | false |
# Code
```cpp []
class Solution {
public:
vector<int> circularGameLosers(int n, int k) {
vector<int> v(n, 0);
int mult = 1;
int idx = 0;
v[0] = 1;
while(true) {
v[(idx+k*mult)%n]++;
if(v[(idx+k*mult)%n] > 1) break;
idx = (idx+k*mult)%n;
mult++;
}
vector<int> ans;
for(int i=0; i<n; i++) {
if(v[i] == 0) {
ans.push_back(i+1);
}
}
return ans;
}
};
```
| 0 | 0 |
['C++']
| 0 |
find-the-losers-of-the-circular-game
|
circularGameLosers: easy O(n) solution. ✅
|
circulargamelosers-easy-on-solution-by-r-nqx4
|
IntuitionThe problem requires identifying players who lose in a circular game. By keeping track of which friends have been chosen in each round, we can determin
|
rTIvQYSHLp
|
NORMAL
|
2025-01-24T14:36:58.803056+00:00
|
2025-01-24T14:36:58.803056+00:00
| 4 | false |
# Intuition
The problem requires identifying players who lose in a circular game. By keeping track of which friends have been chosen in each round, we can determine which friends are not chosen by the end of the game.
# Approach
1. Initialize an array to keep track of which friends have been chosen.
2. Use a loop to simulate the game, updating the chosen friend's status in each round.
3. Calculate the next friend to be chosen based on the current index and step size (k).
4. Continue the loop until a friend is chosen twice, indicating the end of the game.
5. Iterate through the array to identify friends who were not chosen and add them to the result list.
# Complexity
- Time complexity:
O(n)
- Space complexity:
O(n)
# Code
```python3 []
class Solution:
def circularGameLosers(self, n: int, k: int) -> List[int]:
friends=[False]*n
i=k
temp=0
while(friends[temp]==False):
friends[temp]=True
temp=(temp+i)%n
i+=k
answer=[]
for i in range(n):
if friends[i]==False:
answer.append(i+1)
return answer
```
| 0 | 0 |
['Array', 'Hash Table', 'Simulation', 'Python3']
| 0 |
find-the-losers-of-the-circular-game
|
Elegant array modification solution
|
elegant-array-modification-solution-by-a-tgqv
|
IntuitionAt first I thought about deleting the element of the array once it passed through, but then the values of the array will not match the indexes.Therefor
|
Alexitoo00
|
NORMAL
|
2025-01-10T00:48:56.785583+00:00
|
2025-01-10T00:48:56.785583+00:00
| 2 | false |
# Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
At first I thought about deleting the element of the array once it passed through, but then the values of the array will not match the indexes.
Therefore, my approach consists in changing the value to None, and if the None value is reached, stop the loop and clean the output.
I think the way of preparing the output with `[x + 1 for x in rest if x is not None]` is quite elegant, but a bit too specific.
In the same line I also increase the number by one because the indexes start at 0 but the numbers of the positions of the people start at 1.
# Code
```python []
class Solution(object):
def circularGameLosers(self, n, k):
"""
:type n: int
:type k: int
:rtype: List[int]
"""
rest = range(n)
index = 0
rest[0] = None
turn = 1
new_output = []
while True:
index = index + turn * k
index %= n
if rest[index] != None:
rest[index] = None
turn += 1
continue
break
return [x + 1 for x in rest if x is not None]
```
| 0 | 0 |
['Array', 'Python']
| 0 |
find-the-losers-of-the-circular-game
|
2682. Find the Losers of the Circular Game
|
2682-find-the-losers-of-the-circular-gam-skvm
|
IntuitionApproachComplexity
Time complexity:
Space complexity:
Code
|
G8xd0QPqTy
|
NORMAL
|
2025-01-06T17:18:37.277907+00:00
|
2025-01-06T17:18:37.277907+00:00
| 10 | 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
```javascript []
/**
* @param {number} n
* @param {number} k
* @return {number[]}
*/
var circularGameLosers = function(n, k) {
let visited = new Array(n).fill(false); // To keep track of friends who received the ball
let current = 0; // Start at the 1st friend, which is index 0 in 0-based indexing
let turn = 1; // First turn is passing k steps
// Loop until the ball is passed to the same friend again
while (!visited[current]) {
visited[current] = true;
current = (current + turn * k) % n; // Move k steps (scaled by the turn number) in a circular fashion
turn++;
}
// Collect all friends who never received the ball
let losers = [];
for (let i = 0; i < n; i++) {
if (!visited[i]) {
losers.push(i + 1); // Add 1 because the friends are numbered starting from 1
}
}
return losers;
};
```
| 0 | 0 |
['JavaScript']
| 0 |
find-the-losers-of-the-circular-game
|
2682. Find the Losers of the Circular Game
|
2682-find-the-losers-of-the-circular-gam-vyoo
|
Code
|
Adarshjha
|
NORMAL
|
2024-12-31T10:51:56.101060+00:00
|
2024-12-31T10:51:56.101060+00:00
| 4 | false |
# Code
```c []
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* circularGameLosers(int n, int k, int* returnSize) {
int *H, *ans, count = 0, i, t = k;
H = (int *)malloc(sizeof(int)*(n));
for(int i = 0; i < n; i++){
H[i] = 1;
}
i = 0;
while(H[i]){
H[i] = 0;
i = (i + k) % n;
k += t;
}
for(int i = 0; i < n; i++){
if(H[i])
count++;
}
ans = (int *)malloc(sizeof(int) * (count));
i = 0;
for(int j = 0; j < n; j++){
if(H[j])
ans[i++] = j + 1;
}
*returnSize = count;
return ans;
}
```
| 0 | 0 |
['C']
| 0 |
find-the-losers-of-the-circular-game
|
100% beats soln || Logic based
|
100-beats-soln-logic-based-by-mamthanaga-lmws
|
IntuitionApproachSet seen : To keep track of players who recived the ball.
Vector loser: To return the players who didnt recived the ball.passball+i*k-1)%n +1 t
|
mamthanagaraju1
|
NORMAL
|
2024-12-27T07:01:43.540975+00:00
|
2024-12-27T07:01:43.540975+00:00
| 2 | false |
# Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
Set seen : To keep track of players who recived the ball.
Vector loser: To return the players who didnt recived the ball.
passball+i*k-1)%n +1 to make sure value doesnt go beyond 5 and stays in a circular fashion.
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
If u like my sol, upvote me.
# Code
```cpp []
class Solution {
public:
vector<int> circularGameLosers(int n, int k) {
unordered_set<int>seen;
vector<int> losers;
int passball=1;
int i=1;
while(seen.find(passball)==seen.end()){
seen.insert(passball);
passball = (passball+i*k-1)%n+1;
i++;
}
for(int j=1;j<=n;++j){
if(seen.find(j)==seen.end()){
losers.push_back(j);
}
}
return losers;
}
};
```

| 0 | 0 |
['C++']
| 0 |
find-the-losers-of-the-circular-game
|
2682. Find the Losers of the Circular Game | Dart Solution | Time O(n) | Space O(n)
|
2682-find-the-losers-of-the-circular-gam-jhjc
|
ApproachThe solution simulates the ball-passing game by tracking winners and losers:
Initialize data structures:
losers: List of all players except player 1 (
|
user4343mG
|
NORMAL
|
2024-12-20T11:41:01.322384+00:00
|
2024-12-20T11:41:01.322384+00:00
| 2 | false |
## Approach
The solution simulates the ball-passing game by tracking winners and losers:
1. Initialize data structures:
- `losers`: List of all players except player 1 (initially assumed all are losers)
- `winners`: List starting with player 1
- `players`: List of all player numbers from 1 to n
2. Game simulation:
- Track current position and move multiplier
- Calculate next position using modulo for circular movement
- If current player is already a winner, end game
- Otherwise:
- Add current player to winners
- Remove current player from losers
3. Position calculation:
- Use formula: `(position + move * k) % players.length`
- Increment move counter after each turn
The solution efficiently handles the circular nature of the game while maintaining separate lists for winners and losers.
## Complexity
- Time complexity: $$O(n)$$
The solution iterates through players until a repeat occurs, which in worst case is O(n). The `contains` and `removeWhere` operations are also O(n), making the overall complexity linear.
- Space complexity: $$O(n)$$
The solution maintains three lists (`losers`, `winners`, `players`) each potentially containing up to n elements, resulting in linear space complexity.
# Code
```dart []
class Solution {
List<int> circularGameLosers(int n, int k) {
List<int> losers = List.generate(n - 1, (int index) => index + 2);
List<int> winners = [1];
List<int> players = List.generate(n, (int index) => index + 1);
int position = 0;
int move = 1;
while (true) {
position = position + move * k >= players.length
? (position + move * k) % players.length
: position + move * k;
move++;
if (winners.contains(players[position])) {
break;
} else {
winners.add(players[position]);
losers.removeWhere((player) => player == players[position]);
}
}
return losers;
}
}
```
| 0 | 0 |
['Dart']
| 0 |
find-the-losers-of-the-circular-game
|
Circular Array
|
circular-array-by-paulocesarvasco-5t75
| null |
paulocesarvasco
|
NORMAL
|
2024-12-10T21:00:33.808600+00:00
|
2024-12-10T21:00:33.808600+00:00
| 4 | false |
# Complexity\n- Time complexity:\n$$O(n)$$\n\n- Space complexity:\n$$O(n)$$\n\n# Code\n```golang []\nfunc circularGameLosers(n int, k int) []int {\n // if game[i] == 0 -> doesn\'t play yet\n\t// if game[i] == 1 -> already played\n\tgamers := make([]int, n)\n\tvar j int\n\tfor i := 1; gamers[j] == 0; i++ {\n\t\tgamers[j] = 1\n\t\tj = (j + (i * k)) % n\n\t}\n\tlosers := []int{}\n\tfor i := range gamers {\n\t\tif gamers[i] == 0 {\n\t\t\tlosers = append(losers, i+1)\n\t\t}\n\t}\n\treturn losers \n}\n```
| 0 | 0 |
['Go']
| 0 |
find-the-losers-of-the-circular-game
|
Python3 Imperative Approach
|
python3-imperative-approach-by-curenosm-ixk6
|
Code\npython3 []\nclass Solution:\n def circularGameLosers(self, n: int, k: int) -> List[int]:\n visited = [False for _ in range(n)]\n position, turn = 0
|
curenosm
|
NORMAL
|
2024-11-30T20:20:45.854089+00:00
|
2024-11-30T20:20:45.854117+00:00
| 5 | false |
# Code\n```python3 []\nclass Solution:\n def circularGameLosers(self, n: int, k: int) -> List[int]:\n visited = [False for _ in range(n)]\n position, turn = 0, 1\n while True:\n if not visited[position]:\n visited[position] = True\n position = (position + turn * k) % n\n turn += 1\n else:\n break\n return [i + 1 for i in range(n) if not visited[i]]\n```
| 0 | 0 |
['Python3']
| 0 |
find-the-losers-of-the-circular-game
|
Easy to understand
|
easy-to-understand-by-zorroo6903-344o
|
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
|
zorroo6903
|
NORMAL
|
2024-11-05T14:14:11.811277+00:00
|
2024-11-05T14:14:11.811309+00:00
| 1 | 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```cpp []\nclass Solution {\npublic:\n vector<int> circularGameLosers(int n, int k) {\n vector<int> ans;\n map<int,int> mpp;\n int start=1;int i=1;\n while(mpp[start]!=1){\n mpp[start]=1;\n start=(start+i*k)%n;\n if(start==0) start=n;\n i++;\n }\n\n for(int i=1;i<=n;i++){\n if(mpp[i]==0){\n ans.push_back(i);\n }\n }\n return ans;\n \n }\n};\n```
| 0 | 0 |
['C++']
| 0 |
find-the-losers-of-the-circular-game
|
Java&JS&TS Solution (JW)
|
javajsts-solution-jw-by-specter01wj-h08n
|
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
|
specter01wj
|
NORMAL
|
2024-10-24T06:11:15.498769+00:00
|
2024-10-24T06:11:22.910666+00:00
| 7 | 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```java []\npublic int[] circularGameLosers(int n, int k) {\n // Set to track the friends who have received the ball\n Set<Integer> received = new HashSet<>();\n int[] result;\n \n int currentFriend = 1; // The game starts with the 1st friend\n int steps = 1; // Initial steps to pass the ball\n \n // Continue the game until a friend receives the ball twice\n while (!received.contains(currentFriend)) {\n received.add(currentFriend); // Mark the current friend as having received the ball\n currentFriend = (currentFriend + steps * k - 1) % n + 1; // Move to the next friend\n steps++; // Increase the steps (i * k for the next friend)\n }\n\n // Create a list of friends who did not receive the ball\n List<Integer> losers = new ArrayList<>();\n for (int i = 1; i <= n; i++) {\n if (!received.contains(i)) {\n losers.add(i);\n }\n }\n\n // Convert the list of losers to an array\n result = new int[losers.size()];\n for (int i = 0; i < losers.size(); i++) {\n result[i] = losers.get(i);\n }\n\n return result;\n}\n```\n```javascript []\nvar circularGameLosers = function(n, k) {\n const received = new Set(); // Set to track friends who have received the ball\n let currentFriend = 1; // The game starts with the 1st friend\n let steps = 1; // Initial steps to pass the ball\n \n // Continue the game until a friend receives the ball twice\n while (!received.has(currentFriend)) {\n received.add(currentFriend); // Mark current friend as having received the ball\n currentFriend = (currentFriend + steps * k - 1) % n + 1; // Move to the next friend\n steps++; // Increase the steps (i * k for the next friend)\n }\n \n // Collect friends who did not receive the ball\n const losers = [];\n for (let i = 1; i <= n; i++) {\n if (!received.has(i)) {\n losers.push(i);\n }\n }\n \n return losers;\n};\n```\n```typescript []\nfunction circularGameLosers(n: number, k: number): number[] {\n const received = new Set<number>(); // Set to track friends who have received the ball\n let currentFriend = 1; // The game starts with the 1st friend\n let steps = 1; // Initial steps to pass the ball\n \n // Continue the game until a friend receives the ball twice\n while (!received.has(currentFriend)) {\n received.add(currentFriend); // Mark current friend as having received the ball\n currentFriend = (currentFriend + steps * k - 1) % n + 1; // Move to the next friend\n steps++; // Increase the steps (i * k for the next friend)\n }\n \n // Collect friends who did not receive the ball\n const losers: number[] = [];\n for (let i = 1; i <= n; i++) {\n if (!received.has(i)) {\n losers.push(i);\n }\n }\n \n return losers;\n};\n```
| 0 | 0 |
['Array', 'Java', 'TypeScript', 'JavaScript']
| 0 |
find-the-losers-of-the-circular-game
|
&% runtime performance, with my own brute force solution
|
runtime-performance-with-my-own-brute-fo-yhuy
|
Code\npython3 []\nclass Solution:\n def circularGameLosers(self, n: int, k: int) -> List[int]:\n # add losers - which never increased during a game\n
|
parvizmalik
|
NORMAL
|
2024-09-22T11:14:04.385858+00:00
|
2024-09-22T11:14:04.385891+00:00
| 2 | false |
# Code\n```python3 []\nclass Solution:\n def circularGameLosers(self, n: int, k: int) -> List[int]:\n # add losers - which never increased during a game\n # create object and increase the numbers of its players\n # if any element\'s count reached 3 the game will be ended\n obj = {}\n res = []\n for i in range(1, n+1):\n res.append(i)\n obj[i] = obj.get(i, 0)+1\n a = 0\n n=1\n while True:\n if a>len(res) -1:\n while a>=len(res):\n a -= len(res)\n obj[res[a]] += 1\n if obj[res[a]] == 3:\n break\n a+=n*k\n n+=1\n return [x for x in obj if obj[x] == 1]\n\n\n```
| 0 | 0 |
['Python3']
| 0 |
find-the-losers-of-the-circular-game
|
bitvector + modual arithmetic
|
bitvector-modual-arithmetic-by-user5285z-x1c8
|
rust []\nimpl Solution {\n pub fn circular_game_losers(n: i32, k: i32) -> Vec<i32> {\n let n = n as usize;\n let k = k as usize;\n let m
|
user5285Zn
|
NORMAL
|
2024-09-20T09:12:07.818423+00:00
|
2024-09-20T09:12:07.818456+00:00
| 1 | false |
```rust []\nimpl Solution {\n pub fn circular_game_losers(n: i32, k: i32) -> Vec<i32> {\n let n = n as usize;\n let k = k as usize;\n let mut seen = vec![false; n];\n let mut p = 0;\n seen[p] = true;\n for i in 1.. {\n p = (p + i*k).rem_euclid(n);\n if seen[p] {\n return (0..n).filter_map(|i|(!seen[i]).then_some((i+1) as i32)).collect()\n } else {\n seen[p] = true;\n }\n }\n unreachable!()\n }\n}\n```
| 0 | 0 |
['Rust']
| 0 |
find-the-losers-of-the-circular-game
|
train
|
train-by-gpivusev-xybn
|
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
|
gpivusev
|
NORMAL
|
2024-08-31T16:18:32.990770+00:00
|
2024-08-31T16:18:32.990793+00:00
| 1 | 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```cpp []\nclass Solution {\npublic:\n vector<int> circularGameLosers(int n, int k) {\n vector<int> test; //\u043C\u0430\u0441\u0441\u0438\u0432 \u0434\u043B\u044F \u043E\u0431\u043E\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u044F \u043F\u043E \u043A\u0430\u043A\u0438\u043C \u0438\u0433\u0440\u043E\u043A\u0430\u043C \u0437\u0430\u0448\u043B\u0438 \u043F\u043E \u043A\u0430\u043A\u0438\u043C \u043D\u0435\u0442 1 - \u0431\u044B\u043B, 0 - \u043D\u0435 \u0431\u044B\u043B\n for (int i = 0; i < n; i++){\n test.push_back(0);\n }\n int index = 0;\n test[index] = 1;\n\n for (int loop = 1; ;loop++){\n int step = loop * k;\n for (int i = 0; i < step; i++){\n if (index == n-1){ //\u043A\u0430\u043A \u0434\u043E\u0448\u043B\u0438 \u0434\u043E \u043A\u043E\u043D\u0446\u0430 \u0438\u0434\u0435\u043C \u0441\u043D\u043E\u0432\u0430 \u043F\u043E \u043A\u0440\u0443\u0433\u0443\n index = 0;\n }\n else{\n index++;\n }\n }\n if (test[index] == 0){ //\u0435\u0441\u043B\u0438 \u0443 \u0438\u0433\u0440\u043E\u043A\u0430 \u043D\u0435 \u0431\u044B\u043B\u043E \u043C\u044F\u0447\u0430\n test[index] = 1;\n }\n else{\n break; //\u0435\u0441\u043B\u0438 \u0431\u044B\u043B - \u0432\u044B\u0445\u043E\u0434\u0438\u043C\n }\n }\n vector<int> res;\n for (int i = 0; i < n; i++){\n if (test[i] == 0){\n res.push_back(i+1); //\u0437\u0430\u0441\u043E\u0432\u044B\u0432\u0430\u0435\u043C \u0432 \u043E\u0442\u0432\u0435\u0442 \u0442\u0435\u0445 \u0443 \u043A\u043E\u0433\u043E \u043D\u0435 \u0431\u044B\u043B\u043E \u043C\u044F\u0447\u0430\n }\n }\n \n return res;\n }\n};\n
| 0 | 0 |
['C++']
| 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.