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
transform-to-chessboard
Transform to Chessboard | JS | just check bro | beat 100%
transform-to-chessboard-js-just-check-br-fbxd
The key here is realizing that since you cannot move individual cells, but only rows and columns, what started off in a column/row will always remain there. \nE
junyanbill
NORMAL
2021-09-26T19:19:14.288578+00:00
2021-09-26T19:19:14.288619+00:00
252
false
The key here is realizing that since you cannot move individual cells, but only rows and columns, what started off in a column/row will always remain there. \nE.g. in the first example case, you can view it as:\n * col 0 and col 1 swap places\n * row 1 and row 2 swap places\nAnd you can see none of the zeros and ones actually left their original column/row. \nMoreover, the actions of swapping rows/columns can be done independent of each other.\n\nThe algorithm for swapping into a chessboard is therefore the following:\n* swap the rows until the first column is in either "0101" or "1010" configuration.\n* swap the columns until the first row is in either "0101" or "1010" configuration.\n* done.\n\nBut this is based on the assumption that a chessboard can be formed.\n\nHow can we be sure a chessboard can never be formed?\nSince anytime you move a column to attempt to align a certain row into the correct configuration, you are changing the configuration of all other rows. Therefore all the rows must be either the same, or the opposite of one another.\nThen it follows that the number of opposite rows must be the same as the number of same rows if the board size is even, or 1 off if the board size is odd.\n\nAdd this all together, what we are doing is:\n * check if a chessboard can be formed\n * for row get number of moves to get into "0101" or "1010" configuration\n * for col get number of moves to get into "0101" or "1010" configuration\n * combination of lowest number of moves (must each be even) is optimal.\n * return the combination/2 to get number of swaps.\n```\n/**\n * @param {number[][]} board\n * @return {number}\n */\nvar movesToChessboard = function(board) {\n const boardSz = board.length;\n const evenBoard = boardSz%2===0;\n \n const possible=()=>{\n //number of 0 and 1 must be equal in the case of even size board\n //or have a difference of 1 in the case of odd size board\n let numOne = 0, numZero = 0;\n\n //each subsequent row must be either equal to first or opposite of first\n let same = "", oppo = "";\n board[0].forEach(item=>{\n if (item === 1) {\n numOne++;\n same+="1";\n oppo+="0";\n }\n else {\n numZero++;\n same+="0";\n oppo+="1";\n }\n });\n \n //checking for zeros and ones in first row\n if (evenBoard)\n if (numOne != numZero)\n return false;\n else if (!evenBoard)\n if (Math.abs(numOne-numZero) != 1)\n return false;\n \n let sameRow = 0, oppoRow = 0;\n \n for (const row of board) {\n const joinedRow = row.join("");\n if (joinedRow === same){\n sameRow++;\n }\n else if (joinedRow === oppo){\n oppoRow++;\n }\n else {\n return false;\n }\n }\n\n if (evenBoard)\n return sameRow === oppoRow;\n \n return Math.abs(sameRow-oppoRow) === 1;\n \n };\n \n if (!possible()){\n return -1;\n }\n \n //convert to 0101\n let rowMove1 = 0;\n let colMove1 = 0;\n \n //convert to 1010\n let rowMove2 = 0;\n let colMove2 = 0;\n \n for(let i=0; i<boardSz; i++) {\n //checking rows\n //1010\n if(board[i][0] === i % 2) {\n rowMove1++;\n //0101\n } else {\n rowMove2++;\n }\n \n //checking cols\n //1010\n if(board[0][i] === i % 2) {\n colMove1++;\n //0101\n } else {\n colMove2++;\n }\n }\n \n if(rowMove1 + colMove1 === 0 || rowMove2 + colMove2 === 0) \n return 0; \n \n //if the board size is even, number of optimal moves is the minimum\n\t//no need to check if even since by default it will be\n if(evenBoard) {\n rowMove1 = Math.min(rowMove1, rowMove2);\n colMove1 = Math.min(colMove1, colMove2);\n //number of optimal moves must be even (each swap is two moves)\n } else {\n rowMove1 = rowMove1 % 2 === 0 ? rowMove1 : rowMove2;\n colMove1 = colMove1 % 2 === 0 ? colMove1 : colMove2;\n }\n \n return (rowMove1 + colMove1) / 2;\n};\n```
2
1
['JavaScript']
1
transform-to-chessboard
Python Solutions
python-solutions-by-anmol957-xlaw
\nclass Solution:\n def movesToChessboard(self, board):\n n = len(board)\n patt1 = ([0, 1]*(n//2+1))[:n]\n patt2 = ([1, 0]*(n//2+1))[:n]
anmol957
NORMAL
2021-09-26T17:07:09.435683+00:00
2021-09-26T17:07:09.435715+00:00
93
false
```\nclass Solution:\n def movesToChessboard(self, board):\n n = len(board)\n patt1 = ([0, 1]*(n//2+1))[:n]\n patt2 = ([1, 0]*(n//2+1))[:n]\n \n board_t = map(list, zip(*board))\n Cnt_r = list(Counter(tuple(row) for row in board).items())\n Cnt_c = list(Counter(tuple(row) for row in board_t).items())\n if len(Cnt_r) != 2 or len(Cnt_c) != 2: return -1\n if abs(Cnt_r[0][1] - Cnt_r[1][1]) > 1: return -1\n if abs(Cnt_c[0][1] - Cnt_c[1][1]) > 1: return -1\n \n x1 = sum(i != j for i,j in zip(Cnt_r[0][0], patt1))\n y1 = sum(i != j for i,j in zip(Cnt_c[0][0], patt1))\n \n x2 = sum(i != j for i,j in zip(Cnt_r[0][0], patt2))\n y2 = sum(i != j for i,j in zip(Cnt_c[0][0], patt2))\n \n cands_x = [x for x in [x1, x2] if x % 2 == 0]\n cands_y = [y for y in [y1, y2] if y % 2 == 0]\n \n return min(cands_x)//2 + min(cands_y)//2\n```
2
2
[]
0
transform-to-chessboard
[C++]Every Step Explained
cevery-step-explained-by-rajneelesh473-poqn
This isn\'t easy to get for me and I hope my code and comment is clear. I think this is a better code readability practice that algo practice.\nPlease let me kn
rajneelesh473
NORMAL
2021-09-26T15:42:42.633997+00:00
2021-09-26T15:42:42.634026+00:00
310
false
This isn\'t easy to get for me and I hope my code and comment is clear. I think this is a better code readability practice that algo practice.\nPlease let me know the confusing parts :P\n```\nclass Solution {\npublic:\n // Both the column and row swap satisfies the following\n // property:\n // All the numbers in a row will always be in the same row\n // however swapped. The reasoning is simple: row swap will \n // keep the positions of the numbers in the same row unchanged\n // and column swap will move the number in a same row within\n // the row.\n // Similarly all the numbers in a same column will always be \n // in the same column, however swapped.\n // Let\'s call it "group-invariant property" which is vital for\n // an efficient solution.\n int movesToChessboard(vector<vector<int>>& board) {\n int n = board.size();\n // If a board is transformable, there can only be two kind\n // of rows: 1. the number order in the row are extactly same\n // as in the first row; 2. the number in the row are exactly\n // complimentary of the nubmer in the first row at the same\n // position. Similar rules also apply to columns. This will\n // be notd as the "complimentary" property.\n // This can be proved by contradictory. Assume there are two\n // rows, r1 and r2, in the board where exits two positions p1\n // and p2. The numbers in r1 and r2 at position p1 are 1 and 0\n // correspondingly and the numbers at position p2 are both 1.\n // If the board is transformable, numbers at p2 needs to be\n // swapped without affecting the nubmers at p1. And it is not \n\t\t// possible for the elements to move out from r1 or r2 due to \n\t\t// the "group-invariant property". Since there are\n // only two operations column swap and row swap, they can be\n // tried exhaustively. Row swap won\'t change relative positions\n // within two rows so it won\'t work. Column swap will move numbers\n // at p1 togather, so it also cannot be done. If one want to \n // swap numbers at position p1 without affecting number at p2,\n // similary reasoning can be applied. Thus complimentary property\n // is proved.\n for (int i = 0; i < n; ++i) {\n // If ith row and first row are exactly the same, \n // rowComplimentary will be 0, otherwise 1.\n int rowComplimentary = board[i][0] ^ board[0][0];\n // If ith column and first column are exactly the same, \n // colComplimentary will be 0, otherwise 1.\n int colComplimentary = board[0][i] ^ board[0][0];\n for (int j = 0; j < n; ++j) {\n // Check the complimentary property on ith rows.\n if ((board[i][j] ^ board[0][j]) != rowComplimentary) {\n return -1;\n }\n // Check the complimentary property on ith columns.\n if ((board[j][i] ^ board[j][0]) != colComplimentary) {\n return -1;\n }\n }\n }\n\n // There are two properties\n // that will be helpful here:\n // 1. row and column are moved independently so the moves need \n // to be added.\n // 2. If there are n rows/columns that are mis-placed, each swap\n // can put two of them back to right place, thus the move number\n // will be mis-placed numbers divided by 2.\n // 3. Assume all 0s should be put on even position and all 1s\n // should be put on odd positions, the acutual misplaced number\n // will be the smaller one between misplaced-number and\n // N - misplaced-number.\n // This section be combined into the first for loop where the complimentary\n // property is verified.\n int misplacedRowCount = 0;\n int misplacedColCount = 0;\n int rowComplimentartyCount = 0;\n int colComplimentartyCount = 0;\n for (int i = 0; i < n; ++i) {\n // Count misplaced digit for first row.\n int complimentaryRow = board[0][i] ^ board[0][0];\n rowComplimentartyCount += complimentaryRow;\n misplacedRowCount += complimentaryRow ^ !(i & 1);\n // Count misplaced digit for first column.\n int complimentaryCol = board[i][0] ^ board[0][0];\n colComplimentartyCount += complimentaryCol;\n misplacedColCount += complimentaryCol ^ !(i & 1);\n }\n\n // When n is even, the move complimentary counts needs to be n/2 and the\n // move is easy to count.\n if (n % 2 == 0) {\n if (rowComplimentartyCount != n/2 || colComplimentartyCount != n/2) {\n return -1;\n }\n return (min(misplacedRowCount, n - misplacedRowCount) / 2 +\n min(misplacedColCount, n - misplacedColCount) / 2);\n }\n // cout << n << endl << rowComplimentartyCount << " " << colComplimentartyCount << "\\n"\n // << misplacedRowCount << " " << misplacedColCount << endl << endl;\n int move = 0;\n if (rowComplimentartyCount == n/2) {\n move += (n - misplacedRowCount) / 2;\n } else if (rowComplimentartyCount == n/2 + 1) {\n move += misplacedRowCount / 2;\n } else {\n return -1;\n }\n // cout << "row " << move;\n if (colComplimentartyCount == n/2) {\n move += (n - misplacedColCount) / 2;\n } else if (colComplimentartyCount == n/2 + 1) {\n move += misplacedColCount / 2;\n } else {\n return -1;\n }\n // cout << ". col " << move << endl;\n return move;\n }\n \n};
2
0
[]
0
transform-to-chessboard
Java | Counting repeating parts
java-counting-repeating-parts-by-samoyle-f2dx
It is somewhat differrent from the other solutions here. We can count repeating parts in rows and columns, like this 0111001: countOnes=3, countZeros=2 (so, min
SamoylenkoDmitry
NORMAL
2021-09-26T11:45:33.443278+00:00
2021-09-26T17:23:10.179932+00:00
469
false
It is somewhat differrent from the other solutions here. We can count repeating parts in rows and columns, like this `0111001`: countOnes=3, countZeros=2 (so, min=2, max=3). And we expect that `min` and `max` repeating parts are constant between the rows and the columns.\n\nAfter we proved that board is correct, we simple count incorrect positions in the first row and the first column. \n\n```java\nclass Solution {\n int n;\n int[][] board;\n int countInRow(int r,int what){\n int count=0;\n for(int i =0;i<n;i++)if(board[r][i]==what)count++;\n\n return count;\n }\n int countInCol(int c,int what){\n int count=0;\n for(int i =0;i<n;i++)if(board[i][c]==what)count++;\n\n return count;\n }\n\n public int movesToChessboard(int[][] board) {\n n = board.length;\n this.board = board;\n\n int sameMinRowF = -1;\n int sameMaxRowF = -1;\n int sameMinColF = -1;\n int sameMaxColF = -1;\n for (int i = 0; i < n; i++) {\n int newCountOnesRow = countInRow(i, 1);\n int newCountZerosRow = countInRow(i, 0);\n if(Math.abs(newCountOnesRow-newCountZerosRow)>1)return -1;\n int newCountZerosCol = countInCol(i, 0);\n int newCountOnesCol = countInCol(i, 1);\n if(Math.abs(newCountZerosCol-newCountOnesCol)>1)return -1;\n int[]row=board[i];\n int same0Row = countSameInRow(row, 0);\n int same1Row = countSameInRow(row, 1);\n int sameMinRow = Math.min(same0Row,same1Row);\n int sameMaxRow = Math.max(same0Row, same1Row);\n if(sameMinRowF==-1)sameMinRowF = sameMinRow;\n if(sameMaxRowF==-1)sameMaxRowF=sameMaxRow;\n if(sameMinRowF!=sameMinRow)return -1;\n if(sameMaxRowF!=sameMaxRow)return -1;\n\n int same0Col=countSameInCol(i, 0); \n int same1Col=countSameInCol(i, 1); \n int sameMinCol = Math.min(same0Col,same1Col);\n int sameMaxCol = Math.max(same0Col, same1Col);\n if(sameMinColF==-1)sameMinColF = sameMinCol;\n if(sameMaxColF==-1)sameMaxColF=sameMaxCol;\n if(sameMinColF!=sameMinCol)return -1;\n if(sameMaxColF!=sameMaxCol)return -1;\n }\n int count=0;\n boolean isEven =n%2==0;\n if(isEven){\n //101010 nz=3,no=3\n //010101\n int nz = countInRow(0,0);\n int no = countInRow(0,1);\n if(nz!=no)throw new Error("can\'t");\n nz = countInCol(0,0);\n no = countInCol(0,1);\n if(nz!=no)throw new Error("can\'t");\n //00111100\n //1001\n //0110\n int c1=0;int c0=0;\n for(int i=0;i<n;i+=2){if(board[0][i]!=1)c1++;if(board[0][i]!=0)c0++;}\n count+=Math.min(c1,c0);\n c1=0;c0=0;\n for(int i=0;i<n;i+=2){if(board[i][0]!=1)c1++;if(board[i][0]!=0)c0++;}\n count+=Math.min(c1,c0);\n }else{\n //1010101 nz=3, no=4\n //0101010 nz=4, no=3\n\n //1100100100111\n int nz = countInRow(0,0);\n int no = countInRow(0,1);\n if(nz==no+1){\n //0101010\n for(int i =1;i<n;i+=2)if(board[0][i]!=1)count++;\n }else if(no==nz+1){\n //101\n for(int i =1;i<n;i+=2)if(board[0][i]!=0)count++;\n\n }else throw new Error("can\'t");\n nz = countInCol(0,0);\n no = countInCol(0,1);\n if(nz==no+1){\n //0101010\n for(int i =1;i<n;i+=2)if(board[i][0]!=1)count++;\n }else if(no==nz+1){\n //101\n for(int i =1;i<n;i+=2)if(board[i][0]!=0)count++;\n\n }else throw new Error("can\'t");\n\n }\n \n return count;\n }\n int countSameInRow(int[]row, int what){\n int count=0;\n int prev=row[0];\n int len=1;\n for(int i =1;i<n;i++){\n int curr=row[i];\n if(curr==what&&curr==prev){\n len++;\n }else{\n count+=len-1;\n len=1;\n }\n prev=curr;\n }\n count+=len-1;\n return count;\n }\n int countSameInCol(int c, int what){ \n int count=0;\n int prev=board[0][c];\n int len=1;\n for(int i =1;i<n;i++){\n int curr=board[i][c];\n if(curr==what&&curr==prev){\n len++;\n }else{\n count+=len-1;\n len=1;\n }\n prev=curr;\n }\n count+=len-1;\n return count; \n } \n} \n```\nI think this problem is a one big `corner-case`.
2
1
['Java']
3
transform-to-chessboard
[C++] first check if we can transform, then count the miss match row and col.
c-first-check-if-we-can-transform-then-c-yaa2
\nclass Solution {\npublic:\n int movesToChessboard(vector<vector<int>>& board) {\n int n = board.size();\n \n int cnt1 = 1, cnt2 = 0;\n
lovebaonvwu
NORMAL
2021-09-26T08:31:12.524472+00:00
2021-09-26T08:31:12.524511+00:00
414
false
```\nclass Solution {\npublic:\n int movesToChessboard(vector<vector<int>>& board) {\n int n = board.size();\n \n int cnt1 = 1, cnt2 = 0;\n \n for (int i = 1; i < n; ++i) {\n \n if (board[0][0] == board[i][0]) {\n ++cnt1;\n \n for (int j = 0; j < n; ++j) {\n if (board[0][j] != board[i][j]) {\n return -1;\n } \n }\n } else {\n ++cnt2;\n \n for (int j = 0; j < n; ++j) {\n if (board[0][j] == board[i][j]) {\n return -1;\n }\n }\n }\n }\n\n if (abs(cnt1 - cnt2) > 1) {\n return -1;\n }\n \n cnt1 = 1, cnt2 = 0;\n for (int j = 1; j < n; ++j) {\n \n if (board[0][0] == board[0][j]) {\n ++cnt1;\n \n for (int i = 0; i < n; ++i) {\n if (board[i][0] != board[i][j]) {\n return -1;\n }\n }\n } else {\n ++cnt2;\n \n for (int i = 0; i < n; ++i) { \n if (board[i][0] == board[i][j]) {\n return -1;\n }\n }\n }\n }\n \n if (abs(cnt1 - cnt2) > 1) {\n return -1;\n }\n \n int swapRow = 0, swapCol = 0;\n \n for (int i = 0; i < n; ++i) {\n if (board[i][0] != i % 2) {\n ++swapRow;\n }\n }\n \n for (int j = 0; j < n; ++j) {\n if (board[0][j] != j % 2) {\n ++swapCol;\n }\n }\n \n int ans = 0;\n if (n & 1) {\n if (swapRow & 1) {\n swapRow = n - swapRow;\n }\n \n if (swapCol & 1) {\n swapCol = n - swapCol;\n }\n \n ans += swapRow / 2;\n ans += swapCol / 2;\n } else {\n ans += min(swapRow, n - swapRow) / 2;\n ans += min(swapCol, n - swapCol) / 2;\n }\n \n return ans;\n }\n};\n```
2
0
[]
0
transform-to-chessboard
Compress rows/columns
compress-rowscolumns-by-madno-i37t
Since bounds are small, the rows/columns can be compressed into vectors.\n\nEach of the two vectors should contain exactly two type of values, \none with cardin
madno
NORMAL
2020-12-29T14:52:43.487950+00:00
2021-02-06T18:03:14.377756+00:00
509
false
Since bounds are small, the rows/columns can be compressed into vectors.\n\nEach of the two vectors should contain exactly two type of values, \none with cardinality n/2, the other with n-n/2. And each value has\nn/2 or n-n/2 bit set.\n\nThe rows and columns can be manipulated independently: a swap in a row\ndoesn\'t affect the column order (the column values are affected, but the\npattern/ordering and the cardinality stays the same).\nSo we can check the vectors individually for mismatches against the expected ordering.\n\n```\nclass Solution {\n public int movesToChessboard(int[][] board) {\n int n = board.length, ans = 0;\n var pats = new long[2][n];\n for(int i = 0; i < n; ++i){\n for(int j = 0; j < n; ++j){\n pats[0][i] = pats[0][i]*2+board[i][j];\n pats[1][j] = pats[1][j]*2+board[i][j];\n }\n }\n for(var pat : pats){\n var tiles = new Long[]{-1L,-1L};\n long cntMax = 0;\n for(long v : pat){\n if (tiles[1] == -1 || tiles[1] == v){\n ++cntMax;\n tiles[1] = v;\n } else {\n if (!(tiles[0] == -1 || tiles[0] == v)) return -1;\n tiles[0] = v;\n }\n }\n if (cntMax < n-cntMax) {\n Collections.swap(Arrays.asList(tiles),0,1);\n cntMax = n-cntMax;\n }\n if (cntMax != n-n/2) return -1;\n int mism = 0;\n for(int a = 1, i = 0; i < n; ++i, a^=1){\n mism += tiles[a] == pat[i] ? 0 : 1;\n }\n ans += (n%2 == 1 ? mism : Math.min((n-mism),mism))/2;\n }\n return ans;\n }\n}\n```
2
0
['Bit Manipulation', 'Java']
0
transform-to-chessboard
Accepted C# Solution
accepted-c-solution-by-maxpushkarev-7m7v
\n public class Solution\n {\n private int Helper(int[] rows, int[] rowPatterns, int[] columnPatterns, int n, int m)\n {\n int ro
maxpushkarev
NORMAL
2020-04-04T09:22:17.869344+00:00
2020-04-04T09:22:17.869379+00:00
205
false
```\n public class Solution\n {\n private int Helper(int[] rows, int[] rowPatterns, int[] columnPatterns, int n, int m)\n {\n int rowSwaps = 0;\n\n for (int i = 0; i < n; i++)\n {\n if (rows[i] != rowPatterns[i & 1])\n {\n rowSwaps++;\n }\n }\n\n if ((rowSwaps & 1) == 1)\n {\n return int.MaxValue;\n }\n\n int colSwaps = 0;\n for (int j = 0; j < m; j++)\n {\n var bit = (rowPatterns[0] & (1 << j)) >> j;\n if (bit != columnPatterns[j & 1])\n {\n colSwaps++;\n }\n }\n\n if ((colSwaps & 1) == 1)\n {\n return int.MaxValue;\n }\n\n rowSwaps /= 2;\n colSwaps /= 2;\n\n return rowSwaps + colSwaps;\n }\n\n public int MovesToChessboard(int[][] board)\n {\n int n = board.Length;\n int m = board[0].Length;\n\n int[] rows = new int[n];\n IDictionary<int, int> row2Count = new Dictionary<int, int>();\n\n for (int i = 0; i < n; i++)\n {\n int row = 0;\n for (int j = 0; j < m; j++)\n {\n row |= (board[i][j] << j);\n }\n\n if (!row2Count.ContainsKey(row))\n {\n row2Count[row] = 0;\n }\n\n row2Count[row]++;\n rows[i] = row;\n }\n\n if (row2Count.Count != 2)\n {\n return -1;\n }\n\n int[] rowPatterns = new int[2];\n rowPatterns[0] = row2Count.First().Key;\n rowPatterns[1] = rowPatterns[0];\n\n for (int j = 0; j < m; j++)\n {\n rowPatterns[1] ^= (1 << j);\n }\n\n if (!row2Count.ContainsKey(rowPatterns[1]))\n {\n return -1;\n }\n\n if ((n & 1) == 1 && Math.Abs(row2Count[rowPatterns[0]] - row2Count[rowPatterns[1]]) != 1)\n {\n return -1;\n }\n\n if ((n & 1) == 0 && row2Count[rowPatterns[0]] != row2Count[rowPatterns[1]])\n {\n return -1;\n }\n \n int[] bitsCount = new int[2];\n\n for (int j = 0; j < m; j++)\n {\n var bit = (rowPatterns[0] & (1 << j)) >> j;\n bitsCount[bit]++;\n }\n\n if ((m & 1) == 1 && Math.Abs(bitsCount[0] - bitsCount[1]) != 1)\n {\n return -1;\n }\n\n if ((m & 1) == 0 && bitsCount[0] != bitsCount[1])\n {\n return -1;\n }\n\n\n int res = int.MaxValue;\n\n res = Math.Min(res, Helper(rows, rowPatterns, new[] {0, 1}, n, m));\n res = Math.Min(res, Helper(rows, rowPatterns, new[] { 1, 0 }, n, m));\n\n var tmp = rowPatterns[0];\n rowPatterns[0] = rowPatterns[1];\n rowPatterns[1] = tmp;\n\n res = Math.Min(res, Helper(rows, rowPatterns, new[] { 0, 1 }, n, m));\n res = Math.Min(res, Helper(rows, rowPatterns, new[] { 1, 0 }, n, m));\n\n return res;\n }\n }\n```
2
0
[]
0
transform-to-chessboard
[JAVA] a lot of bit operations
java-a-lot-of-bit-operations-by-tyuan73-ylru
int n = 0, mask = 0, p0 = 0xAAAAAAAA, p1 = 0x55555555;\n public int movesToChessboard(int[][] board) {\n n = board.length; // the size\n mask =
tyuan73
NORMAL
2018-02-12T05:08:12.303000+00:00
2018-02-12T05:08:12.303000+00:00
812
false
int n = 0, mask = 0, p0 = 0xAAAAAAAA, p1 = 0x55555555;\n public int movesToChessboard(int[][] board) {\n n = board.length; // the size\n mask = (1 << n) - 1; // the mask, for example: 11111 for n = 5\n p0 &= mask; // the chessboard line ending with 0, for example: 01010 for n = 5\n p1 &= mask; // the chessboard line ending with 1, for example: 10101 for n = 5\n \n int[] rows = new int[n], cols = new int[n];\n for(int i = 0; i < n; i++) {\n for(int j = 0; j < n; j++)\n if (board[i][j] == 1) {\n rows[i] |= 1 << j;\n cols[j] |= 1 << i;\n }\n }\n int m1 = minSwap(rows), m2 = minSwap(cols);\n return m1 == -1 || m2 == -1 ? -1 : m1 + m2;\n }\n \n private int minSwap(int[] nums) {\n int first = nums[0];\n for(int x : nums)\n if (x != first && (x + first) != mask)\n return -1;\n \n int m = Integer.bitCount(first);\n if ((n % 2) == 0) {\n if (m == n/2)\n return Math.min(Integer.bitCount(first ^ p0), Integer.bitCount(first ^ p1)) / 2;\n } else {\n if (m == n/2)\n return Integer.bitCount(first ^ p0) / 2;\n else if (m == n/2 + 1)\n return Integer.bitCount(first ^ p1) / 2;\n }\n return -1;\n }
2
0
[]
0
transform-to-chessboard
[C++] Swapping rows and cols while fixing the color of first element
c-swapping-rows-and-cols-while-fixing-th-r4fs
We see that we can swap column and rows independently. So we can make sure first row and first column are in the correct order and then just verify whether the
facelessvoid
NORMAL
2018-02-11T04:10:19.108000+00:00
2018-02-11T04:10:19.108000+00:00
775
false
We see that we can swap column and rows independently. So we can make sure first row and first column are in the correct order and then just ```verify``` whether the rest of the board is valid. While doing this we can count minimum possible swaps in rows and cols to achieve this state.\nThe only thing that can vary is the definition of ```black``` which can either be ```0``` or ```1```.\n\n```\nvoid swap_cols(vector<vector<int>> &board, int c1, int c2){\n int n = board.size();\n for(int i=0;i<n;i++){\n swap(board[i][c1], board[i][c2]);\n }\n }\n \n void swap_rows(vector<vector<int>> &board, int r1, int r2){\n int n = board.size();\n for(int i=0;i<n;i++){\n swap(board[r1][i], board[r2][i]);\n }\n }\n \n bool verify(vector<vector<int>> &board){\n int n = board.size();\n int b = board[0][0];\n \n for(int i=0;i<n;i++){\n for(int j=0;j<n;j++){\n if((i+j)%2 == 0 && board[i][j] != b) return false;\n if((i+j)%2 != 0 && board[i][j] == b) return false;\n }\n }\n \n return true;\n }\n \n int can_cols_swap(vector<vector<int>> board, int black){\n int n = board.size();\n vector<int> blks, whites;\n int moves = 0;\n for(int i=0;i<n;i++){\n if(board[0][i] == black && i%2 != 0) blks.push_back(i);\n if(board[0][i] != black && i%2 == 0) whites.push_back(i);\n }\n\n if(blks.size() == whites.size()){\n moves += blks.size();\n\n for(int i=0;i<blks.size();i++){\n swap_cols(board, blks[i], whites[i]);\n }\n if(!verify(board)) moves = INT_MAX;\n }else moves = INT_MAX;\n \n return moves;\n }\n \n int can_rows_swap(vector<vector<int>> board, int black){\n int moves = 0, n=board.size();\n vector<int> blks, whites;\n for(int i=0;i<n;i++){\n if(board[i][0]==black && i%2 != 0) blks.push_back(i);\n if(board[i][0] != black && i%2 == 0) whites.push_back(i);\n }\n \n if(blks.size() == whites.size()){\n moves += blks.size();\n\n for(int i=0;i<blks.size();i++){\n swap_rows(board, blks[i], whites[i]);\n }\n\n int col_moves = min(can_cols_swap(board, 0), can_cols_swap(board, 1));\n if(col_moves == INT_MAX) moves = INT_MAX;\n else moves += col_moves;\n }else moves = INT_MAX;\n \n return moves;\n }\n \n int movesToChessboard(vector<vector<int>>& board) {\n int ans = min(can_rows_swap(board, 0), can_rows_swap(board, 1));\n return ans == INT_MAX ? -1 : ans;\n }\n```
2
0
[]
0
transform-to-chessboard
Solution
solution-by-deleted_user-21as
C++ []\nclass Solution {\npublic:\n int movesToChessboard(vector<vector<int>>& board) {\n int n = board.size();\n int row_counter = 0, col
deleted_user
NORMAL
2023-04-29T08:53:19.004876+00:00
2023-04-29T09:09:24.322764+00:00
988
false
```C++ []\nclass Solution {\npublic:\n int movesToChessboard(vector<vector<int>>& board) {\n int n = board.size();\n int row_counter = 0, col_counter = 0;\n for(int r = 0; r < n; r++){\n row_counter += board[r][0] ? 1 : -1;\n for(int c = 0; c < n; c++){\n if(r == 0) col_counter += board[r][c] ? 1 : -1;\n if((board[r][0] ^ board[0][0]) ^ (board[r][c] ^ board[0][c])) return -1; \n }\n }\n if(abs(row_counter) > 1 || abs(col_counter) > 1) return -1;\n int row_swap_count = 0, col_swap_count = 0, row_0_count = 0, col_0_count = 0;\n for(int i = 0; i < n; i++){\n if(i & 1){\n row_swap_count += board[i][0];\n col_swap_count += board[0][i];\n }\n row_0_count += board[i][0] == 0, col_0_count += board[0][i] == 0; \n }\n int odd_position_count = n/2; \n if(n & 1){ \n row_swap_count = row_0_count == odd_position_count ? row_swap_count : (odd_position_count - row_swap_count);\n col_swap_count = col_0_count == odd_position_count ? col_swap_count : (odd_position_count - col_swap_count);\n }\n else{\n row_swap_count = min(row_swap_count, odd_position_count - row_swap_count);\n col_swap_count = min(col_swap_count, odd_position_count - col_swap_count); \n }\n return row_swap_count + col_swap_count;\n } \n};\n```\n\n```Python3 []\nclass Solution:\n def check_even(self, count) : \n if len(count) != 2 or sorted(count.values()) != self.balanced : \n return -1 \n return 1\n\n def all_opposite(self, line1, line2) : \n if not all (line1_value ^ line2_value for line1_value, line2_value in zip(line1, line2)) : \n return -1 \n return 1 \n \n def set_sums_of_lists_of_values(self) : \n self.sums_of_lists_of_values = [sum(list_of_values) for list_of_values in self.lists_of_values]\n\n def update_number_of_swaps(self) : \n self.number_of_swaps += min(self.sums_of_lists_of_values) // 2\n\n def set_lists_of_values(self, line1) : \n self.lists_of_values = []\n for start in self.starts : \n new_list = []\n for index, value in enumerate(line1, start) : \n new_list.append((index-value) % 2)\n self.lists_of_values.append(new_list)\n\n def set_starting_values(self, line1) : \n self.starts = [+(line1.count(1) * 2 > self.n)] if self.n & 1 else [0, 1]\n\n def process_line(self, line1) : \n self.set_starting_values(line1)\n self.set_lists_of_values(line1) \n self.set_sums_of_lists_of_values()\n self.update_number_of_swaps()\n\n def process_board(self, board) : \n for count in (collections.Counter(map(tuple, board)), collections.Counter(zip(*board))) : \n if self.check_even(count) == -1 : \n return -1 \n line1, line2 = count\n if self.all_opposite(line1, line2) == -1 : \n return -1 \n self.process_line(line1)\n return self.number_of_swaps\n\n def set_up_for_processing_board(self, n) : \n self.n = n \n self.number_of_swaps = 0\n self.balanced = [n//2, (n+1)//2]\n \n def movesToChessboard(self, board: List[List[int]]) -> int:\n self.set_up_for_processing_board(len(board))\n return self.process_board(board)\n```\n\n```Java []\nclass Solution {\n public int movesToChessboard(int[][] board) {\n int N = board.length, rowSum = 0, colSum = 0, rowSwap = 0, colSwap = 0;\n for (int r = 0; r < N; ++r)\n for (int c = 0; c < N; ++c) {\n if ((board[0][0] ^ board[r][0] ^ board[0][c] ^ board[r][c]) == 1)\n return -1;\n }\n for (int i = 0; i < N; ++i) {\n rowSum += board[0][i];\n colSum += board[i][0];\n rowSwap += board[i][0] == i % 2 ? 1 : 0;\n colSwap += board[0][i] == i % 2 ? 1 : 0;\n }\n if (N / 2 > rowSum || rowSum > (N + 1) / 2) return -1;\n if (N / 2 > colSum || colSum > (N + 1) / 2) return -1;\n if (N % 2 == 1) {\n if (colSwap % 2 == 1) colSwap = N - colSwap;\n if (rowSwap % 2 == 1) rowSwap = N - rowSwap;\n } else {\n colSwap = Math.min(N - colSwap, colSwap);\n rowSwap = Math.min(N - rowSwap, rowSwap);\n }\n return (colSwap + rowSwap) / 2;\n }\n}\n```\n
1
0
['C++', 'Java', 'Python3']
0
transform-to-chessboard
JAVA Easy & Concise
java-easy-concise-by-rohitkumarsingh369-h904
\nclass Solution {\n public int movesToChessboard(int[][] board) {\n int N = board.length, colToMove = 0, rowToMove = 0, rowOneCnt = 0, colOneCnt = 0;
rohitkumarsingh369
NORMAL
2021-09-27T06:39:23.283954+00:00
2021-09-27T06:39:23.283998+00:00
445
false
```\nclass Solution {\n public int movesToChessboard(int[][] board) {\n int N = board.length, colToMove = 0, rowToMove = 0, rowOneCnt = 0, colOneCnt = 0;\n for (int i = 0; i < N; i++) {\n for (int j = 0; j < N; j++) {\n if (((board[0][0] ^ board[i][0]) ^ (board[i][j] ^ board[0][j])) == 1) {\n return -1;\n }\n }\n }\n for (int i = 0; i < N; i++) {\n rowOneCnt += board[0][i];\n colOneCnt += board[i][0];\n if (board[i][0] == i % 2) {\n rowToMove++;\n }\n if (board[0][i] == i % 2) {\n colToMove++;\n }\n }\n if (rowOneCnt < N / 2 || rowOneCnt > (N + 1) / 2) {\n return -1;\n }\n if (colOneCnt < N / 2 || colOneCnt > (N + 1) / 2) {\n return -1;\n }\n if (N % 2 == 1) {\n // we cannot make it when ..ToMove is odd\n if (colToMove % 2 == 1) {\n colToMove = N - colToMove;\n }\n if (rowToMove % 2 == 1) {\n rowToMove = N - rowToMove;\n }\n } else {\n colToMove = Math.min(colToMove, N - colToMove);\n rowToMove = Math.min(rowToMove, N - rowToMove);\n }\n return (colToMove + rowToMove) / 2;\n }\n\n}\n```
1
0
['Java']
0
transform-to-chessboard
Rust bit based solution (for fun)
rust-bit-based-solution-for-fun-by-michi-wslw
I had a lot of fun with this one. Part of this relies on the fact that n <= 30. This means that the rows and columns will fit into an i32.\n\nThe hardest part
michielbaird
NORMAL
2021-09-26T19:00:33.105060+00:00
2021-09-26T19:00:33.105090+00:00
138
false
I had a lot of fun with this one. Part of this relies on the fact that `n <= 30`. This means that the rows and columns will fit into an `i32`.\n\nThe hardest part in my opinion is figuring out whether a given board is solvable. Going to leave out how I prove this but a solvable board has the following properties:\n\n- You can have a maximum of 2 values in the rows and a maximum on 2 values columns, let\'s call this value `a` and `b`\n\t- `count(a)` and `count(b)` cannot differ by more than one\n\t- `a & b == 0`\n\t- `a | b == (1 << n)-1`\n\t- The bit count of `a` and the bitcount of `b` cannot differ by more than one\n\nOnce this is determined we can now find how many swaps we need. rows and columns can be operated on independently. For every swap that we do we can put 2 \nvalues in the correct position. For a chess board either 1010.... or 0101... are valid. For an odd `n`, only one of these configurations is valid. We can used a test_mask to see how far we are\noff from a valid configuration. This mask is basically 01010 or 10101 repeating. This is `0x2AAAAAAA` and `0x55555555`. If we XOR this value with the numbers we obtained, the count of the set bits\nis equal to this number of rows or columns that are out of place. Since a swap fixes 2 of these value so we can divide the result by 2. If the result is odd though that is an invalid configuration.\n\n\n```rust\nimpl Solution {\n fn get_number(arr: &Vec<i32>) -> Option<i32> {\n let mask = (1 << arr.len()) -1;\n let test:i32 = 0x2AAAAAAA & mask;\n \n arr.iter().fold(Some((-1, -1, 0i32, 0i32)), |s, &n| {\n match s {\n Some((-1, -1, c, d)) => Some((n, -1, c + 1, d)),\n Some((f, b, c, d)) if f == n => Some((f, b, c + 1, d)),\n Some((f, -1, c, d)) => Some((f, n, c, d + 1)),\n Some((f, b, c, d)) if b == n => Some((f, b, c, d + 1)),\n Some(_) => None,\n None => None\n }\n }).filter(|(a, b, _, _)| \n a & b == 0 && (a|b) == mask && \n (a.count_ones() as i32 - b.count_ones() as i32).abs() <= 1\n ).filter(|(_, _, c1, c2)|\n (c1 - c2).abs() <= 1\n ).map(|(a, b, _,_)| {\n vec![a^test, a^test^mask].into_iter()\n .map(|v|v.count_ones() as i32)\n .map(|v| (v>>1) | (v&1)<<6)\n .min().unwrap()\n })\n }\n pub fn moves_to_chessboard(board: Vec<Vec<i32>>) -> i32 {\n let n = board.len();\n let transform = |v: i32, i:i32| (v<<1)|i;\n let rows = board.iter().map(|row| row.iter().copied().fold(0, transform)).collect::<Vec<_>>();\n let cols = (0..n).map(|i| board.iter().map(|r|r[i]).fold(0, transform)).collect::<Vec<_>>();\n\n match (Self::get_number(&rows), Self::get_number(&cols)) {\n (Some(r), Some(c)) => (r + c),\n _ => -1\n }\n }\n}\n```
1
0
['Bit Manipulation', 'Rust']
0
transform-to-chessboard
My C++ Solution
my-c-solution-by-muskiajbhave-sk2c
```\nint movesToChessboard(vector>& board) {\n int n = board.size();\n int maxR = 0, maxC = 0, ones = 0, zeros = 0;\n for (int i = 0; i < n
muskiajbhave
NORMAL
2021-09-26T16:07:23.159244+00:00
2021-09-26T16:07:23.159296+00:00
124
false
```\nint movesToChessboard(vector<vector<int>>& board) {\n int n = board.size();\n int maxR = 0, maxC = 0, ones = 0, zeros = 0;\n for (int i = 0; i < n; i++) {\n int rzero = 0, rone = 0, czero = 0, cone = 0;\n maxR = max(maxR, helper(-1, i, board, rzero, rone, n));\n if (maxR == INT_MAX) return -1;\n maxC = max(maxC, helper(i, -1, board, czero, cone, n));\n if (maxC == INT_MAX) return -1;\n ones = ones + rone + cone;\n zeros = zeros + rzero + czero;\n }\n if (ones - zeros > 2 || zeros - ones > 2) return -1;\n return maxR + maxC;\n }\n \n int helper(int r, int c, vector<vector<int>>& board, int& zero, int& one, int n) {\n zero = 0, one = 0;\n int oneodd = 0, oneeven = 0;\n int result = 0;\n for (int i = 0; i < n; i ++) {\n int b = r == -1 ? board[i][c] : board[r][i];\n if (b == 0) {\n zero++;\n }\n else {\n one++;\n if (i % 2 == 0) oneeven++;\n else oneodd++;\n }\n }\n if (one - zero > 1 || zero - one > 1) return INT_MAX;\n if (one > zero) result = oneodd;\n else if (one < zero) result = oneeven;\n else result = min(oneodd, oneeven);\n return result;\n }
1
1
[]
0
transform-to-chessboard
Simple C solution
simple-c-solution-by-linhbk93-w6k2
\nnt movesToChessboard(int** board, int boardSize, int* boardColSize){\n int rowSum = 0, colSum = 0, row = 0, col = 0;\n for (int i = 0; i < boardSize; ++
linhbk93
NORMAL
2021-09-26T08:45:45.545222+00:00
2021-09-26T08:45:45.545257+00:00
233
false
```\nnt movesToChessboard(int** board, int boardSize, int* boardColSize){\n int rowSum = 0, colSum = 0, row = 0, col = 0;\n for (int i = 0; i < boardSize; ++i) \n for (int j = 0; j < boardSize; ++j)\n if (board[0][0] ^ board[i][0] ^ board[0][j] ^ board[i][j]) return -1;\n for (int i = 0; i < boardSize; ++i) \n {\n rowSum += board[0][i];\n colSum += board[i][0];\n if((i % 2) == board[i][0]) row++;\n if((i % 2) == board[0][i]) col++;\n }\n if (boardSize / 2 > rowSum || rowSum > (boardSize + 1) / 2) return -1;\n if (boardSize / 2 > colSum || colSum > (boardSize + 1) / 2) return -1;\n if (boardSize % 2)\n {\n if (row % 2) row = boardSize - row;\n if (col % 2) col = boardSize - col;\n }\n else \n {\n row = boardSize - row < row ? boardSize - row : row;\n col = boardSize - col < col ? boardSize - col : col;\n }\n return (row + col) / 2;\n}\n```
1
0
['C']
0
transform-to-chessboard
(C++) 782. Transform to Chessboard
c-782-transform-to-chessboard-by-qeetcod-yls8
\n\nclass Solution {\npublic:\n int movesToChessboard(vector<vector<int>>& board) {\n int n = size(board); \n \n auto fn = [&](vector<in
qeetcode
NORMAL
2021-06-29T21:33:15.805163+00:00
2021-06-29T21:33:15.805195+00:00
223
false
\n```\nclass Solution {\npublic:\n int movesToChessboard(vector<vector<int>>& board) {\n int n = size(board); \n \n auto fn = [&](vector<int>& vals) {\n int total = 0, odd = 0; \n for (int i = 0; i < size(vals); ++i) {\n if (vals[0] == vals[i]) {\n ++total; \n if (i&1) ++odd; \n } else if ((vals[0] ^ vals[i]) != (1 << n) - 1) return 100; \n }\n int ans = 100; \n if (size(vals) <= 2*total && 2*total <= size(vals)+1) ans = min(ans, odd); \n if (size(vals)-1 <= 2*total && 2*total <= size(vals)) ans = min(ans, total - odd); \n return ans; \n }; \n \n vector<int> rows(n), cols(n); \n for (int i = 0; i < n; ++i) \n for (int j = 0; j < n; ++j) \n if (board[i][j]) {\n rows[i] ^= 1 << j; \n cols[j] ^= 1 << i; \n }\n int ans = fn(rows) + fn(cols); \n return ans < 100 ? ans : -1; \n }\n};\n```
1
0
['C']
0
transform-to-chessboard
Python Solution
python-solution-by-0105cs161104-cpr6
\nclass Solution:\n def movesToChessboard(self, board: List[List[int]]) -> int:\n n=len(board)\n for i in range(0,n):\n for j in ran
0105CS161104
NORMAL
2021-06-04T09:10:59.396475+00:00
2021-06-04T09:10:59.396519+00:00
233
false
```\nclass Solution:\n def movesToChessboard(self, board: List[List[int]]) -> int:\n n=len(board)\n for i in range(0,n):\n for j in range(0,n):\n if(board[0][0] ^ board[0][j] ^ board[i][0] ^ board[i][j]!=0):\n return -1\n rowSum=0\n colSum= 0\n rowSwap=0\n colSwap= 0\n for i in range(0,n):\n rowSum= rowSum + board[i][0]\n colSum = colSum +board[0][i]\n rowSwap += board[i][0] == i % 2\n colSwap += board[0][i] == i % 2\n if(rowSum != n//2 and rowSum != (n + 1)//2):\n return -1\n if(colSum != n//2 and colSum != (n + 1)//2):\n return -1\n if(n % 2 == 1):\n if(colSwap % 2):\n colSwap = n - colSwap\n if(rowSwap % 2):\n rowSwap = n - rowSwap\n else:\n colSwap = min(colSwap, n - colSwap)\n rowSwap = min(rowSwap, n - rowSwap)\n return (rowSwap + colSwap)//2;\n \n```
1
0
[]
0
transform-to-chessboard
C++ Easy to Understand Solution
c-easy-to-understand-solution-by-xiaopin-wqg4
This solution is based on an observation by mzchen: After the moving, all rows with even numbers are the same and so are the rows with odd numbers. \nFor calcul
xiaoping3418
NORMAL
2021-04-22T11:52:46.409567+00:00
2021-04-24T23:57:43.070617+00:00
331
false
This solution is based on an observation by mzchen: After the moving, all rows with even numbers are the same and so are the rows with odd numbers. \nFor calculating the moves on rows, we use a mapping table to record the index of the rows:\n1) return -1 if the mapping size is not two.\n2) return -1 if the counts of the two rows are not balanced, or the counts differ by more than one.\n3) Pick the row with potential more appearances to calculate the answer\n\nRotate the matrix to use the same row count function to calculate the moves on columns.\n~~~\nclass Solution {\n int rowCount(vector<vector<int>> &board) {\n map<vector<int>, vector<int>> mp;\n for (int i = 0; i < board.size(); ++i) {\n mp[board[i]].push_back(i);\n }\n // after the moving, all even numbered rows are the same\n // so ar the odd numbered rows\n if (mp.size() != 2) return -1;\n \n // their numbers shoud not differ by more than one\n auto it = mp.begin();\n int count1 = it->second.size();\n ++it;\n int count2 = it->second.size();\n if (abs(count1 - count2) > 1) return -1;\n \n // look at the row with potential more appearances \n it = mp.begin();\n if (count2 > count1) ++it;\n int even = 0, odd = 0;\n for (int &i : it->second) {\n if (i % 2 == 0) ++even;\n else ++odd;\n }\n if (board.size() % 2 == 0) return min(even, odd); \n else return odd;\n }\npublic:\n int movesToChessboard(vector<vector<int>> &board) {\n int n = board.size(), ret1 = rowCount(board);\n if (ret1 == -1) return -1;\n \n vector<vector<int>> a(n, vector<int>(n));\n for (int i = 0; i < board.size(); ++i) {\n for (int j = 0; j < board.size(); ++j) {\n a[j][i] = board[i][j];\n }\n }\n int ret2 = rowCount(a);\n if (ret2 == -1) return -1;\n return ret1 + ret2;\n }\n};\n~~~
1
0
[]
1
transform-to-chessboard
[C++] Bit operations and explanation in comments
c-bit-operations-and-explanation-in-comm-dbsl
\nbool debug = false;\n\n/*\ntest cases\n[[0,1,1,0],[0,1,1,0],[1,0,0,1],[1,0,0,1]]\n[[0, 1], [1, 0]]\n[[1, 0], [1, 0]]\n[[0,1,0],[1,0,1],[0,1,0]]\n[[0,1,0],[1,0
genxium
NORMAL
2021-02-16T06:07:43.220289+00:00
2021-02-16T06:08:30.192583+00:00
273
false
```\nbool debug = false;\n\n/*\ntest cases\n[[0,1,1,0],[0,1,1,0],[1,0,0,1],[1,0,0,1]]\n[[0, 1], [1, 0]]\n[[1, 0], [1, 0]]\n[[0,1,0],[1,0,1],[0,1,0]]\n[[0,1,0],[1,0,1],[1,0,1]]\n[[1,1,0],[0,0,1],[0,0,1]]\n*/\nclass Solution {\npublic:\n int movesToChessboard(vector<vector<int>>& board) {\n /*\n [Lemma#1] ActionSequences "swapRows(ri, rj) -> swapCols(ci, cj)" and "swapRows(ci, cj) -> swapCols(ri, rj)" have the SAME result on a "01-board". Draw the 4 intersections (ri, ci), (ri, cj), (rj, ci), (rj, cj) and follow their moves to see why. Moreover, an ActionSequence of "swapRows" and "swapCols" can arbitrarily permute the actions to get the same result on a "01-board".\n \n [Lemma#2] If transformed from a ChessBoard, there\'d be EXACTLY 2 types of rows in the input.\n */\n int N = board.size();\n int valsForLeadingDigits[2];\n valsForLeadingDigits[0] = 0; // a row or col "0,1,0,1,0,1,..."\n for (int i = 1; i < N; ++i) {\n valsForLeadingDigits[0] *= 2;\n valsForLeadingDigits[0] += (i & 1) ? 1 : 0;\n }\n \n valsForLeadingDigits[1] = 1; // a row or col "1,0,1,0,1,0,..."\n for (int i = 1; i < N; ++i) {\n valsForLeadingDigits[1] *= 2;\n valsForLeadingDigits[1] += (i & 1) ? 0 : 1;\n }\n \n map<int, int> rowRepVals; // row representatives\n for (int y = 0; y < N; ++y) {\n int rowVal = 0;\n vector<int> row;\n for (int x = 0; x < N; ++x) {\n rowVal *= 2;\n rowVal += board[y][x];\n }\n if (rowRepVals.size() == 2 && !rowRepVals.count(rowVal)) return -1;\n ++rowRepVals[rowVal];\n }\n \n map<int, int> colRepVals; // col representatives\n for (int x = 0; x < N; ++x) {\n int colVal = 0;\n vector<int> col;\n for (int y = 0; y < N; ++y) {\n colVal *= 2;\n colVal += board[y][x];\n }\n if (colRepVals.size() == 2 && !colRepVals.count(colVal)) return -1;\n ++colRepVals[colVal];\n }\n \n if (colRepVals.size() != 2 || rowRepVals.size() != 2) return -1;\n \n vector<int> rowRepValsList = {rowRepVals.begin()->first, rowRepVals.rbegin()->first};\n vector<int> colRepValsList = {colRepVals.begin()->first, colRepVals.rbegin()->first};\n \n int ans = INT_MAX;\n // Note that to transform a "01-row" into another "01-row" with the same 0\'s count & 1\'s count by "swapping any pair of digits", we just have to count how many of the digits are different and take the half.\n\n if (N%2 == 0) {\n int halfN = N/2;\n if (colRepVals.begin()->second != colRepVals.rbegin()->second) return -1;\n if (rowRepVals.begin()->second != rowRepVals.rbegin()->second) return -1;\n if (__builtin_popcount(colRepValsList[0]) != halfN || __builtin_popcount(colRepValsList[1]) != halfN) return -1;\n if (__builtin_popcount(rowRepValsList[0]) != halfN || __builtin_popcount(rowRepValsList[1]) != halfN) return -1;\n \n // Traverse the matching options, \n for (int a = 0; a < 2; ++a) {\n for (int b = 0; b < 2; ++b) {\n int rowCost = (__builtin_popcount(rowRepValsList[0]^valsForLeadingDigits[a]))/2; \n int colCost = (__builtin_popcount(colRepValsList[0]^valsForLeadingDigits[b]))/2; \n ans = min(ans, rowCost+colCost);\n }\n }\n } else {\n int majorityEle = -1;\n int majorityEleTotCount = (N*N+1)/2;\n int minorityEleTotCount = (N*N-1)/2;\n int oneTotCount = 0;\n for (auto &it : rowRepVals) oneTotCount += it.second*__builtin_popcount(it.first);\n \n if (oneTotCount == majorityEleTotCount) {\n majorityEle = 1;\n } else if (oneTotCount == minorityEleTotCount) {\n majorityEle = 0;\n } else {\n return -1;\n }\n \n int localMajorityCount = (N+1)/2, localMinorityCount = (N-1)/2;\n int rowCost = INT_MAX, colCost = INT_MAX;\n if (__builtin_popcount(rowRepValsList[0]) == (1 == majorityEle ? localMajorityCount : localMinorityCount)) {\n if (debug) printf("rowRepVal:%d holds localMajorityCount:%d of the majorityEle:%d\\n", rowRepValsList[0], localMajorityCount, majorityEle);\n rowCost = (__builtin_popcount(rowRepValsList[0]^valsForLeadingDigits[majorityEle]))/2;\n } else {\n if (debug) printf("rowRepVal:%d holds localMajorityCount:%d of the majorityEle:%d\\n", rowRepValsList[1], localMajorityCount, majorityEle);\n rowCost = (__builtin_popcount(rowRepValsList[1]^valsForLeadingDigits[majorityEle]))/2;\n }\n\n if (__builtin_popcount(colRepValsList[0]) == (1 == majorityEle ? localMajorityCount : localMinorityCount)) {\n if (debug) printf("colRepVal:%d holds localMajorityCount:%d of the majorityEle:%d\\n", colRepValsList[0], localMajorityCount, majorityEle);\n colCost = (__builtin_popcount(colRepValsList[0]^valsForLeadingDigits[majorityEle]))/2;\n } else {\n if (debug) printf("colRepVal:%d holds localMajorityCount:%d of the majorityEle:%d\\n", colRepValsList[1], localMajorityCount, majorityEle);\n colCost = (__builtin_popcount(colRepValsList[1]^valsForLeadingDigits[majorityEle]))/2;\n }\n \n if (debug) printf("N:%d is even, majorityEle is %d, rowCost:%d, colCost:%d\\n", N, majorityEle, rowCost, colCost);\n \n ans = min(ans, rowCost+colCost);\n }\n \n return (INT_MAX == ans ? -1 : ans);\n }\n};\n```
1
0
[]
0
transform-to-chessboard
C++ Straightly and Ugly code,But, AC Solution
c-straightly-and-ugly-codebut-ac-solutio-f18f
\nclass Solution {\npublic:\n int movesToChessboard(vector<vector<int>>& board) {\n int res = min(helper(board, 0), helper(board, 1));\n return
woshiyuanlei
NORMAL
2021-01-13T03:37:25.386361+00:00
2021-01-13T03:37:25.386408+00:00
171
false
```\nclass Solution {\npublic:\n int movesToChessboard(vector<vector<int>>& board) {\n int res = min(helper(board, 0), helper(board, 1));\n return res == INT_MAX ? -1 : res;\n }\n int helper(vector<vector<int>> board, int begin) {\n int res1 = movesToChessboardForRow(board, begin);\n vector<vector<int>> b1 = board;\n int res2 = movesToChessboardForCol(board, 0);\n int res3 = movesToChessboardForCol(b1, 1);\n res1 = res1 == INT_MAX || (res2 == INT_MAX && res3 == INT_MAX) ? INT_MAX : res1 + min(res2, res3);\n return res1;\n }\n int check(vector<vector<int>>& board) {\n for(int i = 1; i < board.size(); i++)\n if(board[i][0] == board[i - 1][0])\n return INT_MAX;\n for(int i = 0; i < board.size(); i++) {\n for(int j = 1; j < board.size(); j++) {\n if(board[i][j] == board[i][j - 1])\n return INT_MAX;\n }\n }\n return 1;\n }\n int movesToChessboardForRow(vector<vector<int>>& board, int begin) {\n int n = board.size(), res = 0;\n for(int i = begin; i < n; i++) {\n if((i & 1) && board[i][0] != board[0][0]) continue;\n if(i > 0 && !(i & 1) && board[i][0] == board[0][0]) continue;\n int j = i + 1;\n while(j < n && board[j][0] == board[i][0]) j += 2;\n if(j >= n) return INT_MAX;\n res++;\n swapRow(board, i, j);\n }\n return res;\n }\n int movesToChessboardForCol(vector<vector<int>>& board, int begin) {\n int n = board.size(), res = 0;\n for(int i = begin; i < n; i++) {\n if((i & 1) && board[0][i] != board[0][0]) continue;\n if(i > 0 && !(i & 1) && board[0][i] == board[0][0]) continue;\n int j = i + 1;\n while(j < n && board[0][j] == board[0][i]) j += 2;\n if(j >= n) return INT_MAX;\n res++;\n swapCol(board, i, j);\n }\n return check(board) == INT_MAX ? INT_MAX : res;\n }\n void swapRow(vector<vector<int>>& board, int i, int j) {\n for(int col = 0; col < board.size(); col++)\n swap(board[i][col], board[j][col]);\n }\n void swapCol(vector<vector<int>>& board, int i, int j) {\n for(int row = 0; row < board.size(); row++)\n swap(board[row][i], board[row][j]);\n }\n};\n```
1
0
[]
0
transform-to-chessboard
Simple C++ solution
simple-c-solution-by-caspar-chen-hku-dvth
\nclass Solution {\npublic:\n int movesToChessboard(vector<vector<int>>& b) {\n int N = b.size(), rowSum = 0, colSum = 0, rowSwap = 0, colSwap = 0;\n
caspar-chen-hku
NORMAL
2020-05-18T12:51:33.290131+00:00
2020-05-18T12:51:33.290168+00:00
497
false
```\nclass Solution {\npublic:\n int movesToChessboard(vector<vector<int>>& b) {\n int N = b.size(), rowSum = 0, colSum = 0, rowSwap = 0, colSwap = 0;\n for (int i = 0; i < N; ++i) for (int j = 0; j < N; ++j){\n if (b[0][0]^b[i][0]^b[0][j]^b[i][j]) return -1; \n }\n for (int i = 0; i < N; ++i) {\n rowSum += b[0][i];\n colSum += b[i][0];\n rowSwap += b[i][0] == i % 2;\n colSwap += b[0][i] == i % 2;\n }\n if (rowSum != N / 2 && rowSum != (N + 1) / 2) return -1;\n if (colSum != N / 2 && colSum != (N + 1) / 2) return -1;\n if (N % 2) {\n if (colSwap % 2) colSwap = N - colSwap;\n if (rowSwap % 2) rowSwap = N - rowSwap;\n } else {\n colSwap = min(N - colSwap, colSwap);\n rowSwap = min(N - rowSwap, rowSwap);\n }\n return (colSwap + rowSwap) / 2;\n }\n};\n```
1
1
[]
1
transform-to-chessboard
java brute force...... code is very tedious and long
java-brute-force-code-is-very-tedious-an-8nj6
\nclass Solution {\n int n;\n public int movesToChessboard(int[][] board) {\n n=board.length;int ans=-1;\n if(n%2==0){\n StringBu
CUNY-66brother
NORMAL
2020-02-12T07:02:39.114065+00:00
2020-02-12T07:05:20.353516+00:00
495
false
```\nclass Solution {\n int n;\n public int movesToChessboard(int[][] board) {\n n=board.length;int ans=-1;\n if(n%2==0){\n StringBuilder s2=new StringBuilder();\n String s1=coltos(board,0);\n for(int i=0;i<s1.length();i++){\n if(s1.charAt(i)==\'0\'){\n s2.append("1");\n }else{\n s2.append("0");\n }\n }\n int copy1[][]=copy(board);\n int copy2[][]=copy(board);\n ans=Math.min(evencase(copy1,s1),evencase(copy2,s2.toString()));\n }else{\n ans=oddcase(board);\n }\n return ans;\n }\n public int evencase(int board[][],String start){\n int res=0;\n int copyboard[][]=copy(board);\n String s=start;\n for(int c=0;c<n;c++){\n StringBuilder next=new StringBuilder();\n for(int i=0;i<s.length();i++){\n if(s.charAt(i)==\'0\'){\n next.append("1");\n }else{\n next.append("0");\n }\n }\n boolean found=false;\n for(int i=c;i<n;i++){\n String cur=coltos(board,i);\n if(cur.equals(next.toString())){\n if(i==c){\n found=true;\n s=next.toString();\n break; \n }\n if((i-c)%2==0)continue;\n found=true;\n res++;\n s=next.toString();\n swapcol(board,c,i);\n break;\n }\n }\n if(!found){\n return -1;\n }\n }//swap col\n\n int copy1[][]=copy(board);\n int copy2[][]=copy(board);\n s=rowtos(board,0);\n StringBuilder s2=new StringBuilder();\n for(int i=0;i<s.length();i++){\n if(s.charAt(i)==\'0\'){\n s2.append("1");\n }else{\n s2.append("0");\n }\n }\n int val1=subeven(copy1,s);\n int val2=subeven(copy2,s2.toString());\n if(val1==-1&&val2==-1)return -1;\n res+=Math.min(val1,val2);\n return res;\n }\n \n \n public int subeven(int board[][],String start){\n String s=start;\n int res=0;\n for(int r=0;r<n;r++){\n StringBuilder next=new StringBuilder();\n for(int i=0;i<s.length();i++){\n if(s.charAt(i)==\'0\'){\n next.append("1");\n }else{\n next.append("0");\n }\n }\n boolean found=false;\n for(int i=r;i<n;i++){\n String cur=rowtos(board,i);\n if(cur.equals(next.toString())){\n if(i==r){\n found=true;\n s=next.toString();\n break;\n }\n if((i-r)%2==0)continue;\n found=true;\n res++;\n s=next.toString();\n swaprow(board,r,i);\n break;\n }\n }\n if(!found){\n return -1;\n }\n }//swap row\n return res;\n }\n \n \n public int oddcase(int board[][]){\n int res=0;int target=n/2+1;\n StringBuilder str=new StringBuilder();\n String s="";\n for(int r=0;r<n;r++){\n int counter=0;\n for(int c=0;c<n;c++){\n if(board[r][c]==1)counter++;\n }\n if(counter==target){\n str.append("0"); //diao guo lai\n }else{\n str.append("1");\n }\n }\n s=str.toString();\n \n for(int c=0;c<n;c++){\n StringBuilder next=new StringBuilder();\n for(int i=0;i<s.length();i++){\n if(s.charAt(i)==\'0\'){\n next.append("1");\n }else{\n next.append("0");\n }\n }\n boolean found=false;\n for(int i=c;i<n;i++){\n String cur=coltos(board,i);\n if(cur.equals(next.toString())){\n if(i==c){\n found=true;\n s=next.toString();\n break; \n }\n if((i-c)%2==0)continue;\n found=true;\n res++;\n s=next.toString();\n swapcol(board,c,i);\n break;\n }\n }\n if(!found){\n return -1;\n }\n }//swap col\n \n str=new StringBuilder();\n \n for(int c=0;c<n;c++){\n int counter=0;\n for(int r=0;r<n;r++){\n if(board[r][c]==1)counter++;\n }\n if(counter==target){\n str.append("0"); //diao guo lai\n }else{\n str.append("1");\n }\n }\n s=str.toString();\n \n for(int r=0;r<n;r++){\n StringBuilder next=new StringBuilder();\n for(int i=0;i<s.length();i++){\n if(s.charAt(i)==\'0\'){\n next.append("1");\n }else{\n next.append("0");\n }\n }\n boolean found=false;\n for(int i=r;i<n;i++){\n String cur=rowtos(board,i);\n if(cur.equals(next.toString())){\n if(i==r){\n found=true;\n s=next.toString();\n break;\n }\n if((i-r)%2==0)continue;\n res++;found=true;\n s=next.toString();\n swaprow(board,r,i);\n break;\n }\n }\n if(!found){\n return -1;\n }\n }//swap row\n \n return res;\n }\n\n public String rowtos(int board[][], int row){\n StringBuilder str=new StringBuilder();\n for(int i=0;i<board.length;i++){\n str.append(""+board[row][i]);\n }\n return str.toString();\n }\n \n public int[][] copy(int board[][]){\n int res[][]=new int[n][n];\n for(int r=0;r<n;r++){\n for(int c=0;c<n;c++){\n res[r][c]=board[r][c];\n }\n }\n return res;\n }\n \n public String coltos(int board[][], int col){\n StringBuilder str=new StringBuilder();\n for(int i=0;i<board.length;i++){\n str.append(""+board[i][col]);\n }\n return str.toString();\n }\n \n public void swaprow(int array[][], int rowA, int rowB) {\n int tmpRow[] = array[rowA];\n array[rowA] = array[rowB];\n array[rowB] = tmpRow;\n }\n \n public void swapcol(int board[][], int colA, int colB){\n List<Integer>list=new ArrayList<>(); \n for(int r=0;r<board.length;r++){\n list.add(board[r][colA]);\n board[r][colA]=board[r][colB];\n }\n for(int i=0;i<list.size();i++){\n board[i][colB]=list.get(i);\n }\n } \n}\n```
1
0
[]
1
transform-to-chessboard
Java - 1 ms, faster than 100.00% - 43.6 MB, less than 88.89%
java-1-ms-faster-than-10000-436-mb-less-5c4k8
\nclass Solution {\n public int movesToChessboard(int[][] board) {\n if (board == null || board.length == 0 || board[0].length == 0) {\n re
woshilxd912
NORMAL
2019-06-16T18:03:10.107762+00:00
2019-06-16T18:03:10.107809+00:00
807
false
```\nclass Solution {\n public int movesToChessboard(int[][] board) {\n if (board == null || board.length == 0 || board[0].length == 0) {\n return -1;\n }\n int N = board.length;\n for (int i = 0; i < N; ++i) {\n for (int j = 0; j < N; ++j) {\n if ((board[0][0] ^ board[i][0] ^ board[0][j] ^ board[i][j]) == 1) {\n return -1;\n }\n }\n }\n int rowSum = 0;\n int colSum = 0;\n int rowSwap = 0;\n int colSwap = 0;\n for (int i = 0; i < N; ++i) {\n rowSum += board[0][i];\n colSum += board[i][0];\n if (board[i][0] == i % 2) {\n ++rowSwap;\n }\n if (board[0][i] == i % 2) {\n ++colSwap;\n }\n }\n if (N / 2 > rowSum || N / 2 > (N - rowSum) || \n N / 2 > colSum || N / 2 > (N - colSum)) {\n return -1;\n }\n if (N % 2 == 0) {\n rowSwap = Math.min(rowSwap, N - rowSwap);\n colSwap = Math.min(colSwap, N - colSwap);\n } else {\n if (colSwap % 2 == 1) {\n colSwap = N - colSwap;\n }\n if (rowSwap % 2 == 1) {\n rowSwap = N - rowSwap;\n }\n }\n return (rowSwap + colSwap) / 2;\n }\n}\n```
1
0
[]
1
transform-to-chessboard
A detailed and easy to understand C++ version.
a-detailed-and-easy-to-understand-c-vers-3mk4
//Feb 13 2018 //A problem that costs me a long time //Property: //1. To tranform columns, you must exchange rows and vice versa //2. The beginning board contai
debiluz
NORMAL
2018-02-14T04:35:33.962747+00:00
2018-02-14T04:35:33.962747+00:00
599
false
//Feb 13 2018 //A problem that costs me a long time //Property: //1. To tranform columns, you must exchange rows and vice versa //2. The beginning board contains only two different kinds of rows(columns), and the two kinds are 0/1 reversed //This is correct because after a swap of rows, columns that are the same remains the same, different remains the different //and final board has only two kinds of rows(columns), so the beginning must be also //As for why they are 0/1 reversed, prove by contradiction. If there are two different rows like these: [0, ....., 1] and [0, ....., 0] //Then no matter how you swap rows and columns, there must be a rectangular whose four corners are 0,1,0,1, it cannot be a chessboard!!! //3.A row swap followed by a column swap is the same as the opposite. So we can swap rows first, then columns //If the minimum swaps consists of a sequence like RCCR....(R for row swap, C for column swap) //4. If this chessboard can be tranformed (We can check that first), then if the first row and column is legal, the whole will also be legal. //To check, verify the property 2. //If we first perform row swaps and make the first column legal, then according to 2(two different columns remain 0/1 reversed after row swaps), //every column is equal to the first or 0/1 reversal, then all columns are legal, then we can perform column swaps and make the first row legal. //So we can write code like this: //1) verify property 2 //2) swap columns and swap rows //count the number num of displaced 0/1, the number of swap is num/2 //3) add column swaps and row swaps ``` class Solution { public: bool check(vector<vector<int>>& board) { int s = board.size(); vector<int> row0, row1; vector<int> col0, col1; //两种不同的行和列 row0 = board[0]; for(int i = 0; i < s; i++) row1.push_back(row0[i]^1); for(int i = 0; i < s; i++) { col0.push_back(board[i][0]); col1.push_back(board[i][0] ^ 1); } if(!checkSingle(row0) || !checkSingle(col0)) return false; for(int i = 0; i < s; i++) { vector<int> col; for(int j = 0; j < s; j++) col.push_back(board[j][i]); if(!checkSingle(col, col0) && !checkSingle(col, col1)) return false; if(!checkSingle(board[i], row0) && !checkSingle(board[i], row1)) return false; } return true; } bool checkSingle(vector<int>& v, vector<int>& formal) { for(int i = 0; i < v.size(); i++) if(v[i] != formal[i]) return false; return true; } bool checkSingle(vector<int>& board) { int n0 = 0, n1 = 0; for(int i = 0; i < board.size(); i++) { if(board[i] == 0) n0 += 1; else n1 += 1; } if(abs(n0 - n1) > 1) return false; return true; } int getRes(vector<int>& board) //Assume in final state board[0][0] = 0 { int ans = INT_MAX, mismatch = 0; int s = board.size(); int cnt1 = 0, cnt2 = 0; for(int i = 0; i < s; i++) { int need = i % 2; if(board[i] != need) mismatch++; if(board[i] == 0) cnt1++; if(need == 0) cnt2++; } if(cnt1 == cnt2) ans = mismatch / 2; return ans; } int movesToChessboard(vector<vector<int>>& board) { if(check(board)) { vector<int> row0 = board[0]; vector<int> col0; for(int i = 0; i < board.size(); i++) col0.push_back(board[i][0]); int row, col; row = getRes(row0); col = getRes(col0); for(int i = 0; i < board.size(); i++) { row0[i] ^= 1; col0[i] ^= 1; } //xor, final state board[0][0] = 1 row = min(row, getRes(row0)); //find the min between board[0][0] = 0 and board[0][0] = 1 col = min(col, getRes(col0)); if(row != INT_MAX && col != INT_MAX) return row + col; else return -1; } return -1; } }; ```
1
1
[]
0
transform-to-chessboard
9ms short C++ solution, easy to understand
9ms-short-c-solution-easy-to-understand-n00e5
``` class Solution { public: int movesToChessboard(vector>& board) { int N=board.size(),row_bal=0,col_bal=0,c=0,d=0; for(int i=0;i1||row_bal
ztc254
NORMAL
2018-02-14T01:30:54.169772+00:00
2018-02-14T01:30:54.169772+00:00
616
false
``` class Solution { public: int movesToChessboard(vector<vector<int>>& board) { int N=board.size(),row_bal=0,col_bal=0,c=0,d=0; for(int i=0;i<N;++i){ row_bal+=board[0][i]?1:-1; col_bal+=board[i][0]?1:-1; if(i&1){ c+=board[0][i]; d+=board[i][0]; } } if(row_bal>1||row_bal<-1||col_bal>1||col_bal<-1) return -1; for(int i=1;i<N;++i) for(int j=1;j<N;++j) if(board[i][j]^board[i][0]^board[0][j]^board[0][0]) return -1; if(!row_bal) return min(N/2-c,c) + min(N/2-d,d); else return (row_bal>0?c:N/2-c) + (col_bal>0?d:N/2-d); } }; ```
1
0
[]
0
transform-to-chessboard
✅✅ Dimension Independence || C++ || Beats 100% 🔥🔥
dimension-independence-c-beats-100-by-an-xp26
Code
AntonioMalloc
NORMAL
2025-01-24T01:30:24.195063+00:00
2025-01-24T01:30:24.195063+00:00
15
false
# Code ```cpp [] class Solution { public: int movesToChessboard(vector<vector<int>>& board) { int N = board.size(); // The size of the board (N x N) // Count the frequency of each unique row in the board unordered_map<int, int> count; for (const auto& row : board) { int code = 0; for (int x : row) { code = (code << 1) + x; // Construct binary representation of the row } count[code]++; } int k1 = analyzeCount(count, N); if (k1 == -1) return -1; // Count the frequency of each unique column in the board count.clear(); for (int c = 0; c < N; ++c) { int code = 0; for (int r = 0; r < N; ++r) { code = (code << 1) + board[r][c]; // Construct binary representation of the column } count[code]++; } int k2 = analyzeCount(count, N); return k2 >= 0 ? k1 + k2 : -1; } private: int analyzeCount(unordered_map<int, int>& count, int N) { // If the map doesn't contain exactly 2 different keys, it's invalid if (count.size() != 2) return -1; auto it = count.begin(); int k1 = it->first, v1 = it->second; ++it; int k2 = it->first, v2 = it->second; // Check if the counts of the two keys are valid if (!((v1 == N / 2 && v2 == (N + 1) / 2) || (v2 == N / 2 && v1 == (N + 1) / 2))) { return -1; } // Check if the two keys are bitwise opposites (XOR == all 1s) if ((k1 ^ k2) != (1 << N) - 1) return -1; // Calculate the number of swaps needed int mask = (1 << N) - 1; // N bits set to 1 int ones = __builtin_popcount(k1 & mask); // Count the number of 1s in k1 int cand = INT_MAX; // Check swaps for "zero start" and "ones start" if (N % 2 == 0 || ones * 2 < N) { // "Zero start" cand = min(cand, __builtin_popcount(k1 ^ 0xAAAAAAAA & mask) / 2); } if (N % 2 == 0 || ones * 2 > N) { // "Ones start" cand = min(cand, __builtin_popcount(k1 ^ 0x55555555 & mask) / 2); } return cand; } }; ```
0
0
['Array', 'Math', 'Bit Manipulation', 'Matrix', 'C++']
0
transform-to-chessboard
782. Transform to Chessboard
782-transform-to-chessboard-by-g8xd0qpqt-ouqu
IntuitionApproachComplexity Time complexity: Space complexity: Code
G8xd0QPqTy
NORMAL
2025-01-01T16:26:36.857660+00:00
2025-01-01T16:26:36.857660+00:00
16
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```cpp [] class Solution { public: int movesToChessboard(vector<vector<int>>& board) { int n = board.size(); int firstRowMatch = 1, secondRowMatch = 0, firstColMatch = 1, secondColMatch = 0; for (int i = 1; i < n; i++) { if (board[0][i] == board[0][0]) { firstRowMatch++; for (int j = 1; j < n; j++) { if (board[j][i] != board[j][0]) return -1; } } else { secondRowMatch++; for (int j = 1; j < n; j++) { if (board[j][i] == board[j][0]) return -1; } } if (board[i][0] == board[0][0]) { firstColMatch++; for (int j = 1; j < n; j++) { if (board[i][j] != board[0][j]) return -1; } } else { secondColMatch++; for (int j = 1; j < n; j++) { if (board[i][j] == board[0][j]) return -1; } } } if (abs(firstRowMatch - secondRowMatch) > 1 || abs(firstColMatch - secondColMatch) > 1) return -1; int rowMismatch = 0, colMismatch = 0; for (int i = 0; i < n; i++) { if (board[0][i] != i % 2) rowMismatch++; if (board[i][0] != i % 2) colMismatch++; } int rowMismatch2 = n - rowMismatch, colMismatch2 = n - colMismatch; int totalMoves = 0; if (rowMismatch2 % 2) totalMoves += rowMismatch / 2; else if (rowMismatch % 2) totalMoves += rowMismatch2 / 2; else totalMoves += min(rowMismatch, rowMismatch2) / 2; if (colMismatch2 % 2) totalMoves += colMismatch / 2; else if (colMismatch % 2) totalMoves += colMismatch2 / 2; else totalMoves += min(colMismatch, colMismatch2) / 2; return totalMoves; } }; ```
0
0
['C++']
0
transform-to-chessboard
generate zebra pattern
generate-zebra-pattern-by-user5285zn-ed4l
There is no interference between row an column operation. Hence, we need to count how many operations are needed to make the first row and the first column to z
user5285Zn
NORMAL
2024-09-05T16:08:59.248794+00:00
2024-09-05T16:08:59.248817+00:00
0
false
There is no interference between row an column operation. Hence, we need to count how many operations are needed to make the first row and the first column to zebra pattern.\n\nIn addition, we need to check whether the whole matrix follows the same pattern as prescribed by leading row and column.\n\n\n```rust []\nfn zebra(r: &Vec<i32>) -> Option<i32> {\n let n = r.len();\n let (k0, k1) = r.iter().fold((0,0), |(k0, k1),x| match x {\n 0 => (k0+1,k1),\n _ => (k0, k1+1)\n });\n \n if k0 > k1 {\n let z = r.iter().step_by(2).filter(|x|**x!=0).count() as i32;\n return if k1 + 1 != k0 {None} else {Some(z)};\n }\n if k0 < k1 {\n let z = r.iter().step_by(2).filter(|x|**x!=1).count() as i32;\n return if k0 +1 != k1 {None} else {Some(z)}\n }\n\n let a = r.iter().step_by(2).filter(|x|**x!=r[0]).count();\n Some(a.min(n/2 - a) as _)\n}\n\nimpl Solution {\n pub fn moves_to_chessboard(b: Vec<Vec<i32>>) -> i32 {\n let n = b.len();\n let row = b[0].clone();\n let col = (0..n).map(|i|b[i][0]).collect::<Vec<_>>();\n \n for i in 0..n {\n for j in 0..n {\n if b[i][j] == (1 + b[0][0] + row[j] + col[i]) % 2 {return -1}\n }\n }\n if let (Some(a), Some(b)) = (zebra(&row), zebra(&col)) {\n a+b\n } else {\n -1\n }\n }\n}\n```
0
0
['Rust']
0
transform-to-chessboard
BFS and Mismatch Counting
bfs-and-mismatch-counting-by-orel12-hnnf
Intuition\nTransforming a board into a chessboard pattern involves strict conditions: alternating 0s and 1s across rows and columns. The challenge is to determi
orel12
NORMAL
2024-09-03T21:24:37.464827+00:00
2024-09-03T21:24:37.464850+00:00
11
false
# Intuition\nTransforming a board into a chessboard pattern involves strict conditions: alternating `0`s and `1`s across rows and columns. The challenge is to determine if a given board can be rearranged to meet these conditions by swapping elements. Key considerations include ensuring equal or near-equal distribution of `0`s and `1`s in rows and columns, and that the connected components of `1`s or `0`s form valid rectangular shapes. If these conditions are met, the number of swaps needed to achieve the chessboard pattern is calculated.\n\n\n# Approach\n1. **Pattern Generation**: Two patterns are generated for comparison: one starting with `0` and the other with `1`. These patterns represent valid chessboard rows and columns.\n \n2. **Validity Checks**: \n - **Connected Components**: The code checks if connected components of `1`s or `0`s form rectangles, as required for a valid transformation.\n - **Row/Column Count**: Each row and column should contain an equal number of `1`s and `0`s (or near-equal if the size is odd). This ensures the board can be rearranged into a valid chessboard.\n \n3. **Mismatch Calculation**: For the first row and column, calculate the minimum swaps required to match either of the generated patterns.\n\n4. **Final Validation**: If any validation fails, the function returns `-1`; otherwise, it returns the total number of swaps needed.\n\n# Complexity\n- **Time complexity**: $$O(n^2)$$, due to traversing each cell in the grid to check for validity and potential swaps.\n- **Space complexity**: $$O(n^2)$$, for the `visited` boolean matrix used to track checked cells.\n\n\n# Code\n```python3 []\nclass Solution:\n def movesToChessboard(self, board):\n n = len(board)\n pat1, pat2 = [i % 2 for i in range(n)], [(i + 1) % 2 for i in range(n)]\n visited = [[False] * n for _ in range(n)]\n rowSwaps = colSwaps = 0\n \n for i in range(n):\n rowCount = colCount = 0\n for j in range(n):\n rowCount += board[i][j]\n colCount += board[j][i]\n if not visited[i][j]:\n queue = [(i, j)]\n visited[i][j] = True\n val = board[i][j]\n minRow = maxRow = i\n minCol = maxCol = j\n cells = 0\n while queue:\n x, y = queue.pop()\n cells += 1\n minRow, maxRow = min(minRow, x), max(maxRow, x)\n minCol, maxCol = min(minCol, y), max(maxCol, y)\n for dx, dy in [(-1, 0), (1, 0), (0, -1), (0, 1)]:\n newX, newY = x + dx, y + dy\n if 0 <= newX < n and 0 <= newY < n and not visited[newX][newY] and board[newX][newY] == val:\n visited[newX][newY] = True\n queue.append((newX, newY))\n if (maxRow - minRow + 1) * (maxCol - minCol + 1) != cells:\n return -1\n\n if n % 2 == 0:\n if rowCount != n // 2 or colCount != n // 2:\n return -1\n else:\n if not (rowCount in {n // 2, n // 2 + 1}) or not (colCount in {n // 2, n // 2 + 1}):\n return -1\n\n if i == 0:\n rowSwaps = self.countSwaps(board[0], pat1, pat2)\n colSwaps = self.countSwaps([board[k][0] for k in range(n)], pat1, pat2)\n if rowSwaps == float(\'inf\') or colSwaps == float(\'inf\'):\n return -1\n\n return rowSwaps + colSwaps\n\n def countSwaps(self, row, pat1, pat2):\n n = len(row)\n mismatch1 = sum(1 for i in range(n) if row[i] != pat1[i])\n mismatch2 = sum(1 for i in range(n) if row[i] != pat2[i])\n return min(mismatch1 // 2 if mismatch1 % 2 == 0 else float(\'inf\'),\n mismatch2 // 2 if mismatch2 % 2 == 0 else float(\'inf\'))\n\n```
0
0
['Matrix', 'Python3']
0
transform-to-chessboard
[Python] Detailed Intuition + Easy To Understand Code - Beats 98%
python-detailed-intuition-easy-to-unders-ywhg
Breakdown\n Describe your first thoughts on how to solve this problem. \n1. Check whether a solution is possible\n2. Calculate number of moves\n\n## Is a soluti
raayc
NORMAL
2024-07-15T02:16:30.640042+00:00
2024-07-15T02:36:17.070448+00:00
36
false
# Breakdown\n<!-- Describe your first thoughts on how to solve this problem. -->\n1. Check whether a solution is possible\n2. Calculate number of moves\n\n## Is a solution possible?\n\nFirst, we check if it is possible to turn the board into a chessboard. To do this, let\'s look at a chessboard:\n![image.png](https://assets.leetcode.com/users/images/7d83ba14-bfce-4f39-9eaf-722645842bd5_1721008633.4652224.png)\n\nWe can consider white squares to be 0, and black to be 1 OR vice-versa.\n\nWhile looking at the chessboard, you can realize some important properties of a chessboard:\n\n\n### Requirements\n1. Chessboards only have `2 types of rows`: `row_type_1` and `row_type_2`\n2. Chessboards only have `2 types of cols`: `col_type_1` and `col_type_2`\n3. The 2 row types MUST be an inverse of each other:\n `row_type_1` must have a white square for every index that there is a black square in `row_type_2` and vice-versa\n4. The 2 col types MUST be an inverse of each other\n `col_type_1` must have a white square for every index that there is a black square in `col_type_2` and vice-versa\n5. `count(row_type_1)` must be equal to `count(row_type_2)` (both must be `n/2, n/2`) - or if n is odd near equal `(n - 1) / 2, (n + 1) / 2`\n6. `count(col_type_1)` must be equal to `count(col_type_2)` (both must be `n/2, n/2`) - or if n is odd near equal `(n - 1) / 2, (n + 1) / 2`\n\nAll of these properties also apply as requirements for a board, if it can be converted to a chessboard\n\n## Solution IS possible, so now what?\n\n### More insights\n1. If we fix either of the 2 row types, we also fix the rest of row types\n2. If we fix either of the 2 col types, we also fix the rest of col types\n3. Each move affects 2 rows (or 2 cols). Optimally, one move will fix 2 incorrections. Therefore, moves = differences / 2.\n\nCombining the 3 insights, we can calculate the minimum number of moves to convert the board to chessboard\n\n# Code\n```python []\nclass Solution:\n def movesToChessboard(self, board: List[List[int]]) -> int:\n n = len(board)\n\n # calculate counts for each rows type and col type\n row_count = defaultdict(int)\n col_count = defaultdict(int)\n\n for row in board:\n row_count[tuple(row)] += 1\n \n for col in zip(*board):\n col_count[tuple(col)] += 1\n \n # Check requirements 1 and 2\n if len(row_count) != 2 or len(col_count) != 2:\n return -1\n\n # Check requirements 3 and 4\n row1, row2 = row_count.keys()\n for n1, n2 in zip(row1, row2):\n if sorted([n1, n2]) != [0, 1]:\n return -1\n\n # Check requirements 5 and 6\n expected_counts = [n // 2, (n + 1) // 2] \n if sorted(row_count.values()) != expected_counts or sorted(col_count.values()) != expected_counts:\n return -1\n\n # We have checked all requirements, there is an answer\n ans = 0\n\n # This loop will run once for rows and once for keys\n for (line1, line2) in (row_count.keys(), col_count.keys()):\n # For rows and cols, there\'s only 2 possible types: line1 and line2\n # By default, assume line1 can start with either 0 or 1\n starts = [0, 1]\n\n # If n is odd, we need to see whether 1 is more common or 0 in line1\n # and the start value for that line HAS to be the more common number\n if n % 2 == 1:\n starts = [1] if line1.count(1) > line1.count(0) else [0]\n ans += self.count_moves(line1, starts)\n \n return ans\n\n # Number of moves needed to convert line to the correct value\n def count_moves(self, line, starts):\n min_moves = float(\'inf\')\n inverse = [1, 0]\n\n for start in starts:\n differences = 0\n\n for i, val in enumerate(line):\n if i % 2 == 1:\n differences += 0 if val == inverse[start] else 1\n else:\n differences += 0 if val == start else 1\n\n # If there are 6 differences, we can fix the line\n # In 3 moves (since each move affects two lines)\n min_moves = min(min_moves, differences // 2)\n return min_moves\n\n```
0
0
['Matrix', 'Python', 'Python3']
1
transform-to-chessboard
782. Transform to Chessboard-easy python3 solution
782-transform-to-chessboard-easy-python3-g1cj
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
Chandvanibharat
NORMAL
2024-06-02T22:58:09.714387+00:00
2024-06-02T22:58:09.714404+00:00
27
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def movesToChessboard(self, board: List[List[int]]) -> int:\n n = len(board)\n row_swaps, col_swaps = 0, 0\n\n # Check Board Validity\n for i in range(n):\n for j in range(n):\n if board[0][0] ^ board[i][0] ^ board[0][j] ^ board[i][j] == 1:\n return -1\n if not (n // 2 <= sum(board[0]) <= (n + 1) // 2):\n return -1\n if not (n // 2 <= sum(board[i][0] for i in range(n)) <= (n + 1) // 2):\n return -1\n\n # Count Swaps\n for i in range(n):\n if board[i][0] == i % 2:\n row_swaps += 1\n if board[0][i] == i % 2:\n col_swaps += 1\n\n # Calculate Minimum Swaps\n if n % 2 == 1:\n if row_swaps % 2 == 1:\n row_swaps = n - row_swaps\n if col_swaps % 2 == 1:\n col_swaps = n - col_swaps\n else:\n row_swaps = min(row_swaps, n - row_swaps)\n col_swaps = min(col_swaps, n - col_swaps)\n\n return (row_swaps + col_swaps) // 2\n\n```
0
0
['Python3']
0
transform-to-chessboard
cpp
cpp-by-pankajkumar101-u6qh
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
PankajKumar101
NORMAL
2024-05-17T00:18:35.987980+00:00
2024-05-17T00:18:35.988010+00:00
28
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int movesToChessboard(vector<vector<int>>& board) {\n int n = board.size();\n int row_counter = 0, col_counter = 0;\n for(int r = 0; r < n; r++){\n row_counter += board[r][0] ? 1 : -1;\n for(int c = 0; c < n; c++){\n if(r == 0) col_counter += board[r][c] ? 1 : -1;\n if((board[r][0] ^ board[0][0]) ^ (board[r][c] ^ board[0][c])) return -1; \n }\n }\n if(abs(row_counter) > 1 || abs(col_counter) > 1) return -1;\n int row_swap_count = 0, col_swap_count = 0, row_0_count = 0, col_0_count = 0;\n for(int i = 0; i < n; i++){\n if(i & 1){\n row_swap_count += board[i][0];\n col_swap_count += board[0][i];\n }\n row_0_count += board[i][0] == 0, col_0_count += board[0][i] == 0; \n }\n int odd_position_count = n/2; \n if(n & 1){ \n row_swap_count = row_0_count == odd_position_count ? row_swap_count : (odd_position_count - row_swap_count);\n col_swap_count = col_0_count == odd_position_count ? col_swap_count : (odd_position_count - col_swap_count);\n }\n else{\n row_swap_count = min(row_swap_count, odd_position_count - row_swap_count);\n col_swap_count = min(col_swap_count, odd_position_count - col_swap_count); \n }\n return row_swap_count + col_swap_count;\n } \n};\n```
0
0
['C++']
0
transform-to-chessboard
Kotlin with explanation
kotlin-with-explanation-by-arista_agarwa-5m2d
Approach\nValidity Check: The code starts by checking the validity of the chessboard by comparing each cell in the first row and first column with the top-left
Arista_agarwal
NORMAL
2024-03-31T13:55:49.043171+00:00
2024-03-31T13:55:49.043203+00:00
5
false
# Approach\nValidity Check: The code starts by checking the validity of the chessboard by comparing each cell in the first row and first column with the top-left cell (b[0][0]). It checks if the XOR of these cells equals 1. If it does, it means the chessboard cannot be formed, and -1 is returned.\nCounting Row and Column Sums:\n\nNext, the code iterates through the first row and first column to count the number of 1s. This count is stored in rowSum and colSum.\nAdditionally, it counts the number of rows and columns that need to be swapped (rowSwap and colSwap). If a row or column needs to be swapped, it increments the respective swap counter.\nChecking Row and Column Sums Validity:\n\nAfter counting, it checks if the row and column sums are valid for forming a chessboard. If the sums are not equal to N / 2 or (N + 1) / 2, where N is the size of the board, it means the chessboard cannot be formed, and -1 is returned.\nAdjusting Swap Counts for Even and Odd Board Sizes:\n\nIf the board size N is odd, the code ensures that the number of swaps for rows and columns is even. If it\'s odd, it adjusts it to make it even.\nIf the board size is even, the code takes the minimum of the original swap count and its complement to N.\nCalculating the Minimum Number of Swaps:\n\nFinally, the code calculates the minimum number of swaps needed by adding the row and column swap counts and dividing by 2. This is because each swap operation fixes two cells (one in a row and one in a column) of the chessboard.\n\n# Code\n```\nclass Solution {\n fun movesToChessboard(board: Array<IntArray>): Int {\n val n = board.size\n var rowSum = 0\n var colSum = 0\n var rowSwap = 0\n var colSwap = 0\n\n for (i in 0 until n) {\n for (j in 0 until n) {\n if ((board[0][0] xor board[i][0] xor board[0][j] xor board[i][j]) == 1) return -1\n }\n }\n\n for (i in 0 until n) {\n rowSum += board[0][i]\n colSum += board[i][0]\n if (board[i][0] == i % 2) rowSwap++\n if (board[0][i] == i % 2) colSwap++\n }\n\n if (rowSum != n / 2 && rowSum != (n + 1) / 2) return -1\n if (colSum != n / 2 && colSum != (n + 1) / 2) return -1\n\n if (n % 2 == 1) {\n if (colSwap % 2 == 1) colSwap = n - colSwap\n if (rowSwap % 2 == 1) rowSwap = n - rowSwap\n } else {\n colSwap = minOf(n - colSwap, colSwap)\n rowSwap = minOf(n - rowSwap, rowSwap)\n }\n\n return (colSwap + rowSwap) / 2\n }\n\n}\n```
0
0
['Kotlin']
0
transform-to-chessboard
Clean & Clear & Easy to understand solution
clean-clear-easy-to-understand-solution-dl0bz
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
joelwangusa
NORMAL
2024-02-26T02:55:51.893508+00:00
2024-02-26T02:55:51.893543+00:00
46
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def movesToChessboard(self, board: List[List[int]]) -> int:\n n = len(board)\n \n rowCnt = Counter(map(tuple, board))\n colCnt = Counter(zip(*board))\n\n # check number of patterns, the number of patterns should only be 2\n if len(rowCnt) != 2 or len(colCnt) != 2: return -1\n\n # check number of each pattern should have only 1 differ\n cr1, cr2 = rowCnt.values()\n cc1, cc2 = colCnt.values()\n if abs(cr1-cr2) > 1 or abs(cc1-cc2) > 1: return -1\n\n\n # two patterns should be complimentary to each other\n r1, r2 = rowCnt\n c1, c2 = colCnt\n \n if not all(r1[i]^r2[i] for i in range(n)):\n return -1\n \n if not all(c1[i]^c2[i] for i in range(n)):\n return -1\n \n # match with the final stage, calculate number of moves\n pattern1 = list([0, 1] * (n//2+1))[:n]\n pattern2 = list([1, 0] * (n//2+1))[:n]\n\n x1 = sum([r1[i] ^ pattern1[i] for i in range(n)])\n x2 = sum([r1[i] ^ pattern2[i] for i in range(n)])\n y1 = sum([c1[i] ^ pattern1[i] for i in range(n)])\n y2 = sum([c1[i] ^ pattern2[i] for i in range(n)])\n\n x = [x for x in [x1, x2] if x % 2 == 0]\n y = [y for y in [y1, y2] if y % 2 == 0]\n\n return min(x)//2 + min(y)//2\n\n```
0
0
['Python3']
0
transform-to-chessboard
consider only the first row & col
consider-only-the-first-row-col-by-maxor-9ypt
Code\n\nclass Solution:\n def movesToChessboard(self, board: List[List[int]]) -> int:\n n = len(board)\n for i in range(n):\n for j
MaxOrgus
NORMAL
2024-02-18T02:54:14.683133+00:00
2024-02-18T02:54:14.683155+00:00
14
false
# Code\n```\nclass Solution:\n def movesToChessboard(self, board: List[List[int]]) -> int:\n n = len(board)\n for i in range(n):\n for j in range(n):\n for k in range(i+1,n):\n for l in range(j+1,n):\n if board[i][j] ^ board[i][l] != board[k][j] ^ board[k][l]:\n return -1\n firstrow = board[0]\n if abs(firstrow.count(0) - firstrow.count(1))>1:\n return -1\n firstcol = [board[i][0] for i in range(n)]\n if abs(firstcol.count(0) - firstcol.count(1))>1:\n return -1\n res = 0\n n1 = 0\n n2 = 0\n for i in range(n):\n if i % 2 != board[0][i]:\n n1 += 1\n if (i + 1) % 2 != board[0][i]:\n n2 += 1\n #print(n1,n2)\n if n1%2 ==1:n1 = float(\'inf\')\n if n2%2 ==1:n2 = float(\'inf\')\n res += min(n1,n2) // 2\n n1 = 0\n n2 = 0\n for i in range(n):\n if i % 2 != board[i][0]:\n n1 += 1\n if (i + 1) % 2 != board[i][0]:\n n2 += 1\n #print(n1,n2)\n if n1%2 ==1:n1 = float(\'inf\')\n if n2%2 ==1:n2 = float(\'inf\')\n res += min(n1,n2) // 2\n return res\n \n```
0
0
['Python3']
0
transform-to-chessboard
JS || Solution by Bharadwaj
js-solution-by-bharadwaj-by-manu-bharadw-3kst
Code\n\nvar movesToChessboard = function (board) {\n let boardSize = board.length;\n let boardSizeIsEven = boardSize % 2 === 0;\n if (!canBeTransformed
Manu-Bharadwaj-BN
NORMAL
2024-02-08T07:24:11.406842+00:00
2024-02-08T07:24:11.406867+00:00
64
false
# Code\n```\nvar movesToChessboard = function (board) {\n let boardSize = board.length;\n let boardSizeIsEven = boardSize % 2 === 0;\n if (!canBeTransformed(board)) return -1;\n let rowSwap = 0;\n let colSwap = 0;\n let rowSwap2 = 0;\n let colSwap2 = 0;\n\n for (let i = 0; i < boardSize; i++) {\n if (board[i][0] === i % 2) {\n rowSwap++;\n } else {\n rowSwap2++;\n }\n if (board[0][i] === i % 2) {\n colSwap++;\n } else {\n colSwap2++;\n }\n }\n if ((rowSwap + colSwap) === 0 || (rowSwap2 + colSwap2) === 0) return 0;\n if (boardSizeIsEven) {\n rowSwap = Math.min(rowSwap, rowSwap2);\n colSwap = Math.min(colSwap, colSwap2);\n } else {\n rowSwap = rowSwap % 2 === 0 ? rowSwap : rowSwap2;\n colSwap = colSwap % 2 === 0 ? colSwap : colSwap2;\n }\n\n return (rowSwap + colSwap) / 2;\n\n function canBeTransformed(board) {\n let sum = board[0].reduce((a, b) => a + b);\n if (boardSizeIsEven && sum != boardSize / 2) return false;\n if (!boardSizeIsEven && sum > ((boardSize + 1) / 2)) return false;\n\n let first = board[0].join(\'\');\n let opposite = board[0].map((item) => item === 1 ? 0 : 1).join(\'\');\n let counter = [0, 0];\n for (let i = 0; i < boardSize; i++) {\n let str = board[i].join(\'\');\n if (str == first) {\n counter[0]++;\n } else if (str == opposite) {\n counter[1]++;\n } else {\n return false;\n }\n }\n if (boardSizeIsEven) {\n return counter[0] == counter[1];\n }\n return Math.abs(counter[0] - counter[1]) === 1\n }\n}; \n```
0
0
['JavaScript']
1
transform-to-chessboard
solution full comented PY3
solution-full-comented-py3-by-borkiss-b6gk
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
borkiss
NORMAL
2024-01-28T15:30:54.728551+00:00
2024-01-28T15:30:54.728582+00:00
16
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def movesToChessboard(self, board: List[List[int]]) -> int:\n n = len(board)\n \n def fn(vals):\n """Return min moves to transform to chessboard."""\n total = odd = 0 \n # Iterate through values in vals and count total and odd occurrences\n for i, x in enumerate(vals): \n if vals[0] == x: \n total += 1\n if i & 1: odd += 1\n elif vals[0] ^ x != (1 << n) - 1: \n return inf\n ans = inf \n # Check conditions for valid configurations and update ans accordingly\n if len(vals) <= 2 * total <= len(vals) + 1: \n ans = min(ans, odd)\n if len(vals) - 1 <= 2 * total <= len(vals): \n ans = min(ans, total - odd)\n return ans \n \n # Initialize lists to store rows and columns\n rows, cols = [0] * n, [0] * n\n # Update rows and columns based on the input board\n for i in range(n): \n for j in range(n): \n if board[i][j]: \n rows[i] ^= 1 << j \n cols[j] ^= 1 << i\n # Calculate the minimum moves for rows and columns and sum them up\n ans = fn(rows) + fn(cols)\n # Return ans if it is less than inf, otherwise return -1\n return ans if ans < inf else -1 \n\n```
0
0
['Python3']
0
transform-to-chessboard
Proper Explanation and easy code. Time - O(N^2)
proper-explanation-and-easy-code-time-on-f04p
Intuition\n Describe your first thoughts on how to solve this problem. \nanswer = Maximum(operations required for each row) + Maximum(operations required for ea
Jatin1358
NORMAL
2024-01-20T16:26:16.164187+00:00
2024-01-20T16:26:16.164209+00:00
40
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nanswer = Maximum(operations required for each row) + Maximum(operations required for each col)\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Check the matrix is proper or not -\n a. In each row, count of one\'s should be equal to count of zero, or can have a diff of 1, in case of n = odd\n b. There can be atmost two different kind of patterns of all the rows. And count of those two patterns should be equal or Can have a difference of 1 in case of n = odd\n\n2. Then we\'ll count max operations required in rows as well as column.\n a. In case of n = odd, row/col should start with max(countOfZero,countOfOne) of that particular row/col. Using that strategy we\'ll check how many digits are not in place.\n b. In case of n = even, we\'ll compute how many digits are not in place, by taking both parameters that it should start with 0 and 1. Whatever is minium will be the max operations required.\n c. After computing the operations required for each row/col, we\'ll return max of operations required for both row and col individually.\n\n3. When we get operations, we\'ll add both the sum and divide by two as swap will always happen between two entites, and one operation will make two entites(row/col) in place.\n\n# Complexity\n- Time complexity: O(N^2)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public static int movesToChessboard(int[][] board) {\n boolean isValid = checkData(board);\n if (!isValid) {\n return -1;\n }\n int n = board.length;\n int maxContRow = operations(board, n, true);\n int maxContCol = operations(board, n, false);\n return (maxContCol / 2) + (maxContRow / 2);\n }\n\n private static int operations(int[][] board, int n, boolean rowWise) {\n int maxOperations = 0;\n for (int i = 0; i < n; i++) {\n int countOfOne = 0;\n for (int j = 0; j < n; j++) {\n int val = rowWise ? board[i][j] : board[j][i];\n if (val == 1) {\n countOfOne++;\n }\n }\n if (n % 2 != 0) {\n int countOfZero = n - countOfOne;\n if (countOfZero > countOfOne) {\n int count = getCount(board, false, rowWise, i);\n maxOperations = Math.max(count, maxOperations);\n } else {\n int count = getCount(board, true, rowWise, i);\n maxOperations = Math.max(count, maxOperations);\n }\n } else {\n int count1 = getCount(board, true, rowWise, i);\n int count2 = getCount(board, false, rowWise, i);\n maxOperations = Math.max(Math.min(count1, count2), maxOperations);\n }\n }\n return maxOperations;\n }\n\n public static int getCount(int[][] board, boolean start, boolean rowWise, int i) {\n int operations = 0;\n int n = board.length;\n for (int j = 0; j < n; j++) {\n int val = rowWise ? board[i][j] : board[j][i];\n if (start) {\n if (val != 1) {\n operations++;\n }\n start = false;\n } else {\n if (val != 0) {\n operations++;\n }\n start = true;\n }\n }\n return operations;\n }\n\n private static boolean checkData(int[][] board) {\n int countOfSimilar = 1;\n int countOfOpposite = 0;\n int n = board.length;\n int count = 0;\n for (int i = 0; i < n; i++) {\n if (board[0][i] == 1) {\n count++;\n }\n }\n if ((n % 2 == 0 && count > n / 2) || (n % 2 != 0 && count - 1 > n / 2)) {\n return false;\n }\n\n for (int i = 1; i < n; i++) {\n boolean checkSame = board[i][0] == board[0][0];\n if (checkSame) {\n countOfSimilar++;\n } else {\n countOfOpposite++;\n }\n for (int j = 0; j < n; j++) {\n if (checkSame) {\n if (board[i][j] != board[0][j]) {\n return false;\n }\n } else {\n if (board[i][j] == board[0][j]) {\n return false;\n }\n }\n }\n }\n return countOfOpposite == countOfSimilar || countOfOpposite - 1 == countOfSimilar || countOfOpposite == countOfSimilar - 1;\n }\n}\n```
0
0
['Java']
0
transform-to-chessboard
Python numpy solution
python-numpy-solution-by-dkoshman-6wv8
Code\n\nimport numpy as np\n\ndef min_even_number(nums):\n return min(i for i in nums if not i & 1)\n\nclass Solution:\n def movesToChessboard(self, board
dkoshman
NORMAL
2024-01-19T19:05:28.006867+00:00
2024-01-19T19:05:28.006898+00:00
9
false
# Code\n```\nimport numpy as np\n\ndef min_even_number(nums):\n return min(i for i in nums if not i & 1)\n\nclass Solution:\n def movesToChessboard(self, board: List[List[int]]) -> int:\n board = np.array(board, dtype=bool)\n n = len(board)\n can_first_row_be_chessified = n // 2 <= board[0].sum() <= (n + 1) // 2\n n_rows_equal_to_first = (board == board[0]).all(1).sum()\n n_rows_inverse_to_first = (board != board[0]).all(1).sum()\n if (\n not can_first_row_be_chessified\n or {n_rows_equal_to_first, n_rows_inverse_to_first} != {n // 2, (n + 1) // 2}\n ):\n return -1\n\n chess_line = np.ones(n, dtype=bool)\n chess_line[::2] = False\n row_chess_cells = (board[0] == chess_line).sum()\n col_chess_cells = (board[:, 0] == chess_line).sum()\n min_row_moves = min_even_number([row_chess_cells, n - row_chess_cells]) // 2\n min_col_moves = min_even_number([col_chess_cells, n - col_chess_cells]) // 2\n return min_row_moves + min_col_moves\n\n\n```
0
0
['Python3']
0
transform-to-chessboard
Scala
scala-by-heavenwatcher-ee86
scala\nobject Solution {\n def movesToChessboard(board: Array[Array[Int]]): Int = {\n def half(x: Int) = x == board.length / 2 || x == (board.length + 1) /
heavenwatcher
NORMAL
2023-12-01T20:14:37.560997+00:00
2023-12-01T20:14:37.561031+00:00
2
false
```scala\nobject Solution {\n def movesToChessboard(board: Array[Array[Int]]): Int = {\n def half(x: Int) = x == board.length / 2 || x == (board.length + 1) / 2\n val vec_board = board.map(_.toVector)\n val patterns = vec_board.toSet\n Option\n .when(patterns.size == 2)(patterns.head, patterns.last)\n .filter { case (p1, p2) =>\n p1.zip(p2).forall(t => t._1 != t._2) && half(vec_board.count(_ == p1)) && half(p1.count(_ == 0))\n }\n .map { case (p1, p2) =>\n val d = Seq(0, 1).maxBy(x => p1.count(_ == x))\n val p = Seq(p1, p2).maxBy(x => vec_board.count(_ == x))\n val bad_cols = p1.zipWithIndex.count { case (x, i) => (i % 2 == 0) ^ (x == d) }\n val bad_rows = vec_board.zipWithIndex.count { case (row, i) => (i % 2 == 0) ^ (row == p) }\n Seq(bad_cols, bad_rows).map { x =>\n if (board.size % 2 != 0) x else x min (board.size - x)\n }.sum / 2\n }\n .getOrElse(-1)\n }\n}\n```
0
0
['Scala']
0
transform-to-chessboard
Scala solution
scala-solution-by-malovig-ltcp
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
malovig
NORMAL
2023-06-25T19:15:10.598551+00:00
2023-06-25T19:15:10.598574+00:00
13
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^2)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n^1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nobject Solution {\n def movesToChessboard(board: Array[Array[Int]]): Int = {\n val n = board.length\n var rowSum = 0\n var colSum = 0\n var rowSwap = 0\n var colSwap = 0\n for (r <- 0 until n; c <- 0 until n)\n if ((board(0)(0) ^ board(r)(0) ^ board(0)(c) ^ board(r)(c)) == 1)\n return -1\n for (i <- 0 until n) {\n rowSum += board(0)(i)\n colSum += board(i)(0)\n rowSwap += (if (board(i)(0) == i % 2) 1 else 0)\n colSwap += (if (board(0)(i) == i % 2) 1 else 0)\n }\n if (n / 2 > rowSum || rowSum > (n + 1) / 2 || n / 2 > colSum || colSum > (n + 1) / 2) -1\n else {\n if (n % 2 == 1) {\n if (colSwap % 2 == 1) colSwap = n - colSwap\n if (rowSwap % 2 == 1) rowSwap = n - rowSwap\n } else {\n colSwap = math.min(n - colSwap, colSwap)\n rowSwap = math.min(n - rowSwap, rowSwap)\n }\n (colSwap + rowSwap) / 2\n }\n }\n}\n```
0
0
['Scala']
0
transform-to-chessboard
Swift Solution with Explanations and Dry Run.
swift-solution-with-explanations-and-dry-j5dr
Approach\nThe movesToChessboard function takes a 2D array (board) representing the chessboard configuration as input and returns an integer representing the min
aayushkumar20
NORMAL
2023-06-09T05:55:14.571259+00:00
2023-06-09T05:55:14.571307+00:00
10
false
# Approach\nThe `movesToChessboard` function takes a 2D array (`board`) representing the chessboard configuration as input and returns an integer representing the minimum number of moves required. The code uses a dry run of the algorithm to explain the steps.\n\nHere\'s a step-by-step explanation of the code:\n\n1. Initialize variables `rowSum`, `colSum`, `rowSwap`, and `colSwap` to keep track of row and column sums, as well as the number of row and column swaps.\n\n2. Iterate over each element of the chessboard using nested loops.\n\n3. Check if the current element\'s XOR operation with the top-left element (`board[0][0]`), top element (`board[r][0]`), and left element (`board[0][c]`) is equal to 1. If true, it means there is an invalid configuration, and the function returns -1.\n\n4. Calculate the sum of the first row (`rowSum`) and the sum of the first column (`colSum`).\n\n5. Determine the number of row swaps (`rowSwap`) and column swaps (`colSwap`) needed. For each row and column, if the current element matches the expected pattern (`i % 2`), increment the respective swap counter.\n\n6. Check if the rowSum is within the valid range (`N / 2` to `(N + 1) / 2`). If not, return -1.\n\n7. Check if the colSum is within the valid range (`N / 2` to `(N + 1) / 2`). If not, return -1.\n\n8. If the size of the chessboard (`N`) is odd, adjust the rowSwap and colSwap counts to minimize the number of swaps.\n\n9. If the size of the chessboard is even, take the minimum value between the current swap count and the complement of the swap count (N - swapCount) for both rowSwap and colSwap.\n\n10. Calculate the total number of swaps needed by adding rowSwap and colSwap and dividing it by 2.\n\n11. Return the minimum number of swaps as the result.\n\n\n# Dry Run\n```\nlet board: [[Int]] = [\n [0, 1, 1, 0],\n [1, 0, 0, 1],\n [1, 0, 0, 1],\n [0, 1, 1, 0]\n]\n\nlet solution = Solution()\nlet minMoves = solution.movesToChessboard(board)\nprint(minMoves)\n```\n\nLet\'s perform a sample check on the given code with a sample chessboard configuration.\n\nIn this example, we have a 4x4 chessboard represented by the `board` array. The elements of the array are either 0 or 1, indicating different pieces on the chessboard.\n\nThe provided code will be executed to find the minimum number of moves required to transform this chessboard configuration.\n\nStep-by-step execution:\n1. The code initializes variables `rowSum`, `colSum`, `rowSwap`, and `colSwap` to 0.\n2. The first nested loop iterates over each element of the chessboard.\n3. The XOR operation is performed to check the validity of the configuration. In this case, all XOR operations evaluate to 0, indicating a valid configuration.\n4. The code calculates the row and column sums (`rowSum` and `colSum`) and the number of row and column swaps (`rowSwap` and `colSwap`).\n - `rowSum` = 4, `colSum` = 2, `rowSwap` = 2, `colSwap` = 2\n5. Since the rowSum and colSum are within the valid range, no further checks are required.\n6. The code checks if the size of the chessboard is odd or even. In this case, it is even.\n7. The number of swaps needed is calculated by taking the minimum value between the current swap count and its complement for both rowSwap and colSwap. In this case, `rowSwap` and `colSwap` remain unchanged.\n8. The total number of swaps needed is calculated by adding rowSwap and colSwap and dividing by 2. In this case, it is 2.\n9. The result, `minMoves`, is set to 2.\n10. The result, 2, is printed to the console.\n\n# Complexity\n- Time complexity: O(N^2)\n- Space complexity: O(1)\n\n# Code\n```\nclass Solution\n{\n func movesToChessboard(_ board: [[Int]]) -> Int\n {\n let N = board.count\n var rowSum = 0, colSum = 0, rowSwap = 0, colSwap = 0\n for r in 0..<N\n {\n for c in 0..<N\n {\n if (board[0][0] ^ board[r][0] ^ board[0][c] ^ board[r][c]) == 1\n {\n return -1\n }\n }\n }\n for i in 0..<N\n {\n rowSum += board[0][i]\n colSum += board[i][0]\n rowSwap += board[i][0] == i % 2 ? 1 : 0\n colSwap += board[0][i] == i % 2 ? 1 : 0\n }\n if N / 2 > rowSum || rowSum > (N + 1) / 2\n {\n return -1\n }\n if N / 2 > colSum || colSum > (N + 1) / 2\n {\n return -1\n }\n if N % 2 == 1\n {\n if colSwap % 2 == 1\n {\n colSwap = N - colSwap\n }\n if rowSwap % 2 == 1\n {\n rowSwap = N - rowSwap\n }\n }\n else\n {\n colSwap = min(N - colSwap, colSwap)\n rowSwap = min(N - rowSwap, rowSwap)\n }\n return (colSwap + rowSwap) / 2\n }\n}\n```
0
0
['Swift']
0
transform-to-chessboard
Time: O(n2)O(n2) Space: O(1)O(1)
time-on2on2-space-o1o1-by-mdarafatuddin4-iepo
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
mdarafatuddin481
NORMAL
2023-04-08T19:24:24.259260+00:00
2023-04-08T19:24:24.259290+00:00
50
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def movesToChessboard(self, board: List[List[int]]) -> int:\n n = len(board)\n\n if any(board[0][0] ^ board[i][0] ^ board[0][j] ^ board[i][j] for i in range(n) for j in range(n)):\n return -1\n\n rowSum = sum(board[0])\n colSum = sum(board[i][0] for i in range(n))\n\n if rowSum != n // 2 and rowSum != (n + 1) // 2:\n return -1\n if colSum != n // 2 and colSum != (n + 1) // 2:\n return -1\n\n rowSwaps = sum(board[i][0] == (i & 1) for i in range(n))\n colSwaps = sum(board[0][i] == (i & 1) for i in range(n))\n\n if n & 1:\n if rowSwaps & 1:\n rowSwaps = n - rowSwaps\n if colSwaps & 1:\n colSwaps = n - colSwaps\n else:\n rowSwaps = min(rowSwaps, n - rowSwaps)\n colSwaps = min(colSwaps, n - colSwaps)\n\n return (rowSwaps + colSwaps) // 2\n\n```
0
0
['Python3']
0
transform-to-chessboard
Solid Principles | Dimension Independence | Commented and Explained
solid-principles-dimension-independence-h195o
Intuition\n Describe your first thoughts on how to solve this problem. \nOur main insight into the problem is that there must be a balance of either exactly the
laichbr
NORMAL
2023-04-03T19:37:53.844797+00:00
2023-04-03T19:37:53.844838+00:00
49
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nOur main insight into the problem is that there must be a balance of either exactly the same or alternating by 1 number of chess piece locations in two rows based on the idea that we have two rows next to each other (think of a 2 by 2 grid as the easiest case, then a 3 x 3, and so on), which you can convince yourself of by building up by 2 x 2 to 3 x 3 to 4 x 4 to 5 x 5 chess grids. \n\nThis implies two stopping early conditions we can exploit. These are that there are more than two types of lines based on the frequencies of values between the two rows, or if there are not a balanced valuation of frequencies for the two rows. If we encounter any case with this, we will never be able to swap our chess board (until someone out there decides to invent a fiendish version where we can swap items on one row with items far away on another! That\'d be horrid!). Similarly, if in our our processing of the two rows, we find that there are not exactly xor sequences when placed on top of each other and doing an xor summation, then we also know that this is not possible for our consideration at all. \n\nOnce we have these two cases, we need to figure out what to do in the meantime if we find two rows that are compatabile at some point. \n\nTo do so, we will need to determine what the line can start with. \nIn the case of an even number of items, we obviously need to only start with 0 and 1. But on the case of an odd length row (5 x 5 grid for example) we will need to start with some amalgatation of the count of line1\'s 1s being 2 times greater than our length of n. This will place us as either 0 and 1 or 1 and 0 depending on the row indice we currently occupy. \n\nOnce we know what we can start with, we want the sum of the lists of values that we currently have, namely the value of index - value mod 2 for each index in our row and value in our row depending on if we start with index 0 or index 1. \n\nThese then are summed up as two separate valuations in our list of sums of lists of values\n\nWe take the minimal account of these by half, and that is our update to our number of swaps. We can do this by half, since we will be swapping two items positions in a maximally advantageous way, and we only need to get the minimal number in order, since once they are in order the maximal are as well. \n\nTo process our board then, we need to first set up a bit. We will need of course a size of the board dimensions, n, a number of swaps holder, 0, and a way to know if wwe are balanced, a list of [n//2 and (n+1)//2] \n\nWhen we process we then want to take the counter of the map of the tuples of the board with the counter of the zipped board columns \nThis necessarily gives us row and column independent comparisons\nIn such a case, \n- For count in our independent spaces \n - if our count is not even (2 types of lines and sorted version of the line values are the balanced ones) we can return -1 \n - if our two lines do not form up an alternating pair (xor of one and the others values all the way across) we can return -1 \n - otherwise, we need to process a line, including updating our number of swaps accordingly \nWhen done, if we never returned, we now return our number of swaps \n\nTo calculate our moves to chessboard then, we simply call set up for processing board, passing the length of the board and then return the value of the call to process board passing the board. \n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nAn object oriented approach using solid design principles was the focus of this work. The goal was to limit responsibility of each function to a singular purpose within the problem space. \n\n# Complexity\n- Time complexity: O(N * N) \n - We end up exploring the entire board, so it is the size of the board as the limit on time \n\n- Space complexity: O(N) \n - Count ends up storing N items for line1 and N items for line2, so total is 2N which reduces to N \n\n# Code\n```\nclass Solution:\n # check if there are two types of lines or that the sorted values are not the balanced form \n # on fail, return -1 \n # on pass, return 1 \n def check_even(self, count) : \n if len(count) != 2 or sorted(count.values()) != self.balanced : \n return -1 \n return 1\n\n # check if all are alternating row by row \n # if so, alternate is good, if not, not possible, return -1 \n def all_opposite(self, line1, line2) : \n if not all (line1_value ^ line2_value for line1_value, line2_value in zip(line1, line2)) : \n return -1 \n return 1 \n \n # set your sums of lists of values based on your current lists of values \n def set_sums_of_lists_of_values(self) : \n self.sums_of_lists_of_values = [sum(list_of_values) for list_of_values in self.lists_of_values]\n\n # update your number of swaps using your current sums of lists of values \n def update_number_of_swaps(self) : \n self.number_of_swaps += min(self.sums_of_lists_of_values) // 2\n\n def set_lists_of_values(self, line1) : \n self.lists_of_values = []\n for start in self.starts : \n new_list = []\n for index, value in enumerate(line1, start) : \n new_list.append((index-value) % 2)\n self.lists_of_values.append(new_list)\n\n def set_starting_values(self, line1) : \n self.starts = [+(line1.count(1) * 2 > self.n)] if self.n & 1 else [0, 1]\n\n def process_line(self, line1) : \n # starts is the starting value of line 1 \n # starts gets added to an empty list the value of \n # the number of 1s found multipled by 2 is greater than n if n is odd \n # this is to deal with the one off 1 factor on odd boards alternating \n # otherwise, it gets only 0 and 1 \n self.set_starting_values(line1)\n # use starts and line1 to build the list \n self.set_lists_of_values(line1) \n # use the lists of values to build the sums of lists of values \n self.set_sums_of_lists_of_values()\n # use those to update the number of swaps \n self.update_number_of_swaps()\n\n def process_board(self, board) : \n # get the count as the pair of tuples of the board as frequencies with the zip of the rows \n for count in (collections.Counter(map(tuple, board)), collections.Counter(zip(*board))) : \n # if there are more than 2 kinds of lines or they are not balanced \n if self.check_even(count) == -1 : \n return -1 \n line1, line2 = count\n # if the values of the two lines when zipped are not always alternating, also false\n # this can be checked with exclusive or of the values in line1 and line 2 as l1v and l2v\n if self.all_opposite(line1, line2) == -1 : \n return -1 \n # pass the line which is the first item in count \n self.process_line(line1)\n # if you haven\'t returned yet, return now \n return self.number_of_swaps\n\n def set_up_for_processing_board(self, n) : \n # n by n board \n self.n = n \n # number of swaps needed \n self.number_of_swaps = 0\n # balanced form for chess board \n self.balanced = [n//2, (n+1)//2]\n \n def movesToChessboard(self, board: List[List[int]]) -> int:\n # set up for processing \n self.set_up_for_processing_board(len(board))\n # then process it \n return self.process_board(board)\n\n```
0
0
['Python3']
0
transform-to-chessboard
[c++] Clean and Simple | O(n*n)
c-clean-and-simple-onn-by-projectcoder-csz5
\nclass Solution {\npublic:\n int solve(int s, int h, int n) {\n int ans = 0;\n for (int i = 0; i < n; i++) ans += (((s>>i&1)==h) != (i%2==0));
projectcoder
NORMAL
2023-02-22T05:42:40.082688+00:00
2023-02-22T05:42:40.082744+00:00
39
false
```\nclass Solution {\npublic:\n int solve(int s, int h, int n) {\n int ans = 0;\n for (int i = 0; i < n; i++) ans += (((s>>i&1)==h) != (i%2==0)); \n return ans / 2;\n }\n \n \n int movesToChessboard(vector<vector<int>>& arr) { int n = arr.size();\n int row[110] = {0};\n int col[110] = {0};\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < n; j++) {\n row[i] |= (arr[i][j]==arr[i][0])<<j; // get row mode\n col[j] |= (arr[i][j]==arr[0][j])<<i;\n }\n }\n for (int i = 1; i < n; i++) {\n if (row[i]!=row[0]) return -1; // all the rows have the same row mode\n if (col[i]!=col[0]) return -1; \n }\n \n int a = __builtin_popcount(row[0]), b = n-a;\n int c = __builtin_popcount(col[0]), d = n-c;\n if (abs(a-b) > 1 || abs(c-d) > 1) return -1; \n \n // rows and columns do not affect each other\n int u = min(a>=b?solve(row[0],1,n):INT_MAX,b>=a?solve(row[0],0,n):INT_MAX);\n int v = min(c>=d?solve(col[0],1,n):INT_MAX,d>=c?solve(col[0],0,n):INT_MAX);\n return u + v;\n }\n};\n```
0
0
[]
0
transform-to-chessboard
Java working wit explanation
java-working-wit-explanation-by-obose-eudz
Intuition\n Describe your first thoughts on how to solve this problem. \nWe want to find the minimum number of swaps required to transform the given board into
Obose
NORMAL
2023-01-26T19:06:32.603252+00:00
2023-01-26T19:06:32.603284+00:00
120
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe want to find the minimum number of swaps required to transform the given board into a "chessboard". A chessboard is defined as having alternating 1s and 0s row-wise and column-wise. For example: \n\n```\n[0, 1, 0, 1]\n[1, 0, 1, 0]\n[0, 1, 0, 1]\n[1, 0, 1, 0]\n```\n\nTo achieve this, we can take the following steps: \n1. First, check if it\'s even possible to transform the board into a chessboard. If not, return -1. \n2. Check if the number of 1s and 0s on each row and column are within valid range (i.e. if they\'re both either greater than "N/2" or less than "(N+1)/2"). If not, then return -1. \n3. Then we can count the number of row and column swaps required, and return the sum/2 of both these values, as each swap fixes 2 cells (1 row and 1 column). \n# Approach\n<!-- Describe your approach to solving the problem. -->\nThe algorithm we can use is as follows: \n1. Iterate through the board and check if it is possible to transform it into a chessboard, as defined above. \n2. Iterate again, this time counting the number of 1s and 0s in each row and column. \n3. Calculate the row and column swaps needed and return the sum/2 of both these values. \n# Complexity\n- Time complexity: $$O(N^2)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nwhere N is the number of cells in each row or column of the board \n- Space complexity: $$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int movesToChessboard(int[][] board) {\n int N = board.length, rowSum = 0, colSum = 0, rowSwap = 0, colSwap = 0;\n for (int r = 0; r < N; ++r)\n for (int c = 0; c < N; ++c) {\n if ((board[0][0] ^ board[r][0] ^ board[0][c] ^ board[r][c]) == 1)\n return -1;\n }\n for (int i = 0; i < N; ++i) {\n rowSum += board[0][i];\n colSum += board[i][0];\n rowSwap += board[i][0] == i % 2 ? 1 : 0;\n colSwap += board[0][i] == i % 2 ? 1 : 0;\n }\n if (N / 2 > rowSum || rowSum > (N + 1) / 2) return -1;\n if (N / 2 > colSum || colSum > (N + 1) / 2) return -1;\n if (N % 2 == 1) {\n if (colSwap % 2 == 1) colSwap = N - colSwap;\n if (rowSwap % 2 == 1) rowSwap = N - rowSwap;\n } else {\n colSwap = Math.min(N - colSwap, colSwap);\n rowSwap = Math.min(N - rowSwap, rowSwap);\n }\n return (colSwap + rowSwap) / 2;\n }\n}\n```
0
0
['Java']
0
transform-to-chessboard
Just a runnable solution
just-a-runnable-solution-by-ssrlive-8fqr
Code\n\nimpl Solution {\n pub fn moves_to_chessboard(board: Vec<Vec<i32>>) -> i32 {\n let n = board.len();\n let mut row = 0;\n let mut
ssrlive
NORMAL
2022-12-16T11:14:33.753148+00:00
2022-12-16T11:14:33.753190+00:00
51
false
# Code\n```\nimpl Solution {\n pub fn moves_to_chessboard(board: Vec<Vec<i32>>) -> i32 {\n let n = board.len();\n let mut row = 0;\n let mut col = 0;\n let mut row_diff = 0;\n let mut col_diff = 0;\n for i in 0..n {\n for j in 0..n {\n if board[0][0] ^ board[0][j] ^ board[i][0] ^ board[i][j] == 1 {\n return -1;\n }\n }\n }\n for i in 0..n {\n row += board[0][i];\n col += board[i][0];\n if board[i][0] == i as i32 % 2 {\n row_diff += 1;\n }\n if board[0][i] == i as i32 % 2 {\n col_diff += 1;\n }\n }\n if row < n as i32 / 2 || row > (n as i32 + 1) / 2 {\n return -1;\n }\n if col < n as i32 / 2 || col > (n as i32 + 1) / 2 {\n return -1;\n }\n if n % 2 == 1 {\n if row_diff % 2 == 1 {\n row_diff = n - row_diff;\n }\n if col_diff % 2 == 1 {\n col_diff = n - col_diff;\n }\n } else {\n row_diff = std::cmp::min(row_diff, n - row_diff);\n col_diff = std::cmp::min(col_diff, n - col_diff);\n }\n ((row_diff + col_diff) / 2) as i32\n }\n}\n```
0
0
['Rust']
0
transform-to-chessboard
python3
python3-by-swastik1712-ev4m
class Solution:\n\n def movesToChessboard(self, board: List[List[int]]) -> int:\n n = len(board)\n res = 0\n rowCnt = Counter(map(tuple,
swastik1712
NORMAL
2022-09-11T18:22:31.965020+00:00
2022-09-11T18:22:31.965067+00:00
45
false
class Solution:\n\n def movesToChessboard(self, board: List[List[int]]) -> int:\n n = len(board)\n res = 0\n rowCnt = Counter(map(tuple,board))\n colCnt = Counter(zip(*board))\n \n for count in (rowCnt,colCnt):\n if len(count)!=2:\n return -1\n \n if sorted(count.values())!=[n//2,(n+1)//2]:\n return -1\n \n for key in count:\n cnt = Counter(key)\n if sorted(cnt.values())!=[n//2,(n+1)//2]:\n return -1\n \n line1,line2 = count\n if not all(x^y for x,y in zip(line1,line2)):\n return -1\n \n if n%2:\n expect = 1 if line1.count(1)>line1.count(0) else 0\n moves = 0\n for x in line1:\n moves+=x^expect\n expect^=1\n res+=moves//2\n else:\n moves = float(\'inf\')\n for expect in (0,1):\n currMove = 0\n for x in line1:\n currMove+=x^expect\n expect^=1\n moves = min(moves,currMove)\n res+=moves//2\n \n return res
0
0
[]
0
transform-to-chessboard
✔️Python O(n) solution, O(n^2) check for possibility. With comments. No graphs.
python-on-solution-on2-check-for-possibi-gxdx
\n\tdef movesToChessboard(self, board: List[List[int]]) -> int:\n n = len(board)\n \n # check that there are half zeroes and half ones in t
Veanules
NORMAL
2022-04-18T15:14:53.632036+00:00
2022-04-18T15:18:54.023745+00:00
254
false
\n\tdef movesToChessboard(self, board: List[List[int]]) -> int:\n n = len(board)\n \n # check that there are half zeroes and half ones in the first row and column\n ones = sum(board[0])\n if ones != n//2 and ones != (n+1)//2:\n return -1\n ones = sum(board[i][0] for i in range(n))\n if ones != n//2 and ones != (n+1)//2:\n return -1\n \n # check that all the rows are either exactly the same as first or exactly inverted\n inv = 0\n for i in range(1,n): \n if all(board[i][j] == board[0][j] for j in range(n)):\n pass\n elif all(board[i][j] != board[0][j] for j in range(n)):\n inv += 1\n else:\n return -1\n \n # the number of inversions should be half of n\n if inv != n//2 and inv != (n+1)//2:\n return -1\n \n # same for columns\n inv = 0\n for j in range(1,n): \n if all(board[i][j] == board[i][0] for i in range(n)):\n pass\n elif all(board[i][j] != board[i][0] for i in range(n)):\n inv += 1\n else:\n return -1\n \n if inv != n//2 and inv != (n+1)//2:\n return -1\n \n # now we know the transformation is possible\n # count the difference from "01010..." in the first row and column\n diff_h = sum(1 for j in range(n) if board[0][j] == j%2)\n diff_v = sum(1 for i in range(n) if board[i][0] == i%2)\n if n%2:\n #for odd n: the right order is when diff is even\n return (diff_h if diff_h%2==0 else n-diff_h)//2 + \\\n (diff_v if diff_v%2==0 else n-diff_v)//2\n else:\n #for even n: any order is fine\n return min(diff_h,n-diff_h)//2 + \\\n min(diff_v,n-diff_v)//2\n
0
0
['Python']
0
transform-to-chessboard
C++ O(n^2) | Reduce 2d problem to 2 1d problems
c-on2-reduce-2d-problem-to-2-1d-problems-zsyr
Rows and columns are orthogonal. You can make columns alternating and then make rows alternating or vice versa.\nThere can only be two unique rows and columns i
megatron10
NORMAL
2022-04-10T16:24:18.278269+00:00
2022-04-10T16:24:18.278318+00:00
247
false
Rows and columns are orthogonal. You can make columns alternating and then make rows alternating or vice versa.\nThere can only be two unique rows and columns in a solvable board. Then this problem is reduced to 1d problems. Given a sequeune of the type of row/column, find steps required to make all it an alternating sequence.\n```\nclass Solution {\n const int inf = 1e9;\n void transpose(vector<vector<int>>& board) {\n const int n = board.size();\n for (int i = 0; i < n; i++)\n for (int j = 0; j < i; j++)\n swap(board[i][j], board[j][i]);\n }\n \n bool isSame(vector<int> &r1, vector<int>& r2) {\n const int n = r1.size();\n for (int i = 0; i < n; i++)\n if (r1[i] != r2[i])\n return false;\n return true;\n }\n \n bool isOpposite(vector<int> &r1, vector<int>& r2) {\n const int n = r1.size();\n for (int i = 0; i < n; i++)\n if (r1[i] == r2[i])\n return false;\n return true;\n }\n \n int getSteps(vector<vector<int>> &&confusionMatrix) {\n int steps = inf;\n \n if (confusionMatrix[0][1] == confusionMatrix[1][0])\n steps = confusionMatrix[0][1];\n \n if (confusionMatrix[0][0] == confusionMatrix[1][1])\n steps = min(steps, confusionMatrix[0][0]);\n \n return steps;\n }\n \n vector<vector<int>> getConfusionMatrix(vector<int>& rowType) {\n const int n = rowType.size();\n vector<vector<int>> confusionMatrix(2, vector<int>(2, 0));\n for (int i = 0; i < n; i++)\n confusionMatrix[rowType[i]][i & 1]++;\n return confusionMatrix;\n }\n \n int solve1d(vector<int> &arr) {\n return getSteps(getConfusionMatrix(arr));\n }\n \n int makeColumnsAlternating(vector<vector<int>>& board) {\n const int n = board.size();\n vector<int> rowType(n, 0);\n for (int i = 1; i < n; i++)\n if (isOpposite(board[0], board[i]))\n rowType[i] = 1;\n else if (!isSame(board[0], board[i]))\n return inf;\n return solve1d(rowType);\n }\npublic:\n int movesToChessboard(vector<vector<int>>& board) {\n int steps = makeColumnsAlternating(board);\n transpose(board);\n steps += makeColumnsAlternating(board);\n if (steps >= inf)\n return -1;\n return steps;\n }\n};\n```
0
0
['C']
0
transform-to-chessboard
Java BFS + DFS but TLE
java-bfs-dfs-but-tle-by-catshaoshao-oy2b
\nHope anyone can improve my solution.\n\n...\npublic int movesToChessboard(int[][] board) {\n if (board == null || board.length == 0 || board[0] == null
catshaoshao
NORMAL
2021-11-30T00:43:10.491833+00:00
2021-11-30T00:43:10.491865+00:00
260
false
\nHope anyone can improve my solution.\n\n...\npublic int movesToChessboard(int[][] board) {\n if (board == null || board.length == 0 || board[0] == null || board[0].length == 0) return -1;\n \n int row = board.length;\n int col = board[0].length;\n HashSet<String> visited = new HashSet<>(); // hashvalue, the board status\n visited.add(getHash(board));\n Queue<int[][]> q = new LinkedList<>();\n q.offer(board);\n int res = 0;\n \n while (!q.isEmpty()) {\n int size = q.size();\n while (size-- > 0) {\n int[][] cur = q.poll();\n if (isValid(cur)) {\n return res;\n }\n // changes rows\n for (int i = 0; i < row; i++) {\n for (int j = i + 1; j < row; j++) {\n int[][] newBoard = getNewRow(cur, i, j);\n if (!visited.contains(getHash(newBoard))) {\n q.offer(newBoard);\n visited.add(getHash(newBoard));\n }\n }\n }\n // changes cols\n for (int i = 0; i < col; i++) {\n for (int j = i + 1; j < col; j++) {\n int[][] newBoard = getNewCol(cur, i, j);\n if (!visited.contains(getHash(newBoard))) {\n q.offer(newBoard);\n visited.add(getHash(newBoard));\n }\n }\n }\n }\n res++;\n }\n return -1;\n }\n \n private int[][] getNewCol(int[][] board, int i, int j) {\n int row = board.length;\n int col = board[0].length;\n int[][] newBoard = new int[row][col];\n for (int ii = 0; ii < row; ii++) {\n for (int jj = 0; jj < col; jj++) {\n newBoard[ii][jj] = board[ii][jj];\n }\n }\n \n for (int t = 0; t < row; t++) {\n int cur = newBoard[t][i];\n newBoard[t][i] = newBoard[t][j];\n newBoard[t][j] = cur;\n }\n return newBoard;\n }\n \n private int[][] getNewRow(int[][] board, int i, int j) {\n int row = board.length;\n int col = board[0].length;\n int[][] newBoard = new int[row][col];\n for (int ii = 0; ii < row; ii++) {\n for (int jj = 0; jj < col; jj++) {\n newBoard[ii][jj] = board[ii][jj];\n }\n }\n \n for (int t = 0; t < col; t++) {\n int cur = newBoard[i][t];\n newBoard[i][t] = newBoard[j][t];\n newBoard[j][t] = cur;\n }\n return newBoard;\n }\n \n private boolean isValid(int[][] cur) {\n int[][] visited = new int[cur.length][cur[0].length];\n if (cur[0][0] == 1) {\n if (dfs(cur, 0, 0, 0, visited)) return true;\n } else {\n if (dfs(cur, 0, 0, 1, visited)) return true;\n }\n return false;\n }\n \n private boolean dfs(int[][] cur, int i, int j, int value, int[][] visited) {\n if (i < 0 || j < 0 || i >= cur.length || j >= cur[0].length) return true;\n if (cur[i][j] == value) return false;\n if (visited[i][j] == 1) return true;\n \n int curVal = cur[i][j];\n visited[i][j] = 1;\n if (dfs(cur, i + 1, j, curVal, visited) && dfs(cur, i - 1, j, curVal, visited) &&\n dfs(cur, i, j + 1, curVal, visited) && dfs(cur, i, j - 1, curVal, visited)) {\n return true;\n }\n return false;\n }\n \n private String getHash(int[][] board) {\n StringBuilder sb = new StringBuilder();\n for (int i = 0; i < board.length; i++) {\n for (int j = 0; j < board[0].length; j++) {\n sb.append(board[i][j]);\n }\n }\n return sb.toString();\n }\n\t\n\t...
0
0
['Depth-First Search', 'Breadth-First Search']
0
transform-to-chessboard
[Java] exclude impossible cases, then calculate diff row/col
java-exclude-impossible-cases-then-calcu-3ook
\njava\n public int movesToChessboard(int[][] board) {\n // count how many ones in the first row and first col\n int rowOneCount = 0;\n
magiciendecode
NORMAL
2021-09-29T18:17:41.953083+00:00
2021-09-29T18:17:41.953131+00:00
304
false
![image](https://assets.leetcode.com/users/images/124fae9f-d31a-4775-b694-da2f690526bc_1632939415.3491814.png)\n```java\n public int movesToChessboard(int[][] board) {\n // count how many ones in the first row and first col\n int rowOneCount = 0;\n int colOneCount = 0;\n for (int[] ints : board) {\n if (ints[0] == 1) {\n ++rowOneCount;\n }\n }\n for (int i : board[0]) {\n if (i == 1) {\n ++colOneCount;\n }\n }\n final int half = board.length >> 1;\n\n if (board.length % 2 == 0) {\n // if N is even, count of one must equal to half of N\n if (half != rowOneCount || half != colOneCount) {\n return -1;\n }\n } else {\n // if N is odd, count of one could be half or half+1\n if ((half != rowOneCount) && (half + 1 != rowOneCount)) {\n return -1;\n }\n if ((half != colOneCount) && (half + 1 != colOneCount)) {\n return -1;\n }\n }\n // if two adjacent row/col are same at the first row/col, they must be all 1 or all 0\n for (int i = 1; i < board.length; i++) {\n final boolean rowSame = board[i][0] == board[i - 1][0];\n final boolean colSame = board[0][i] == board[0][i - 1];\n for (int j = 1; j < board.length; j++) {\n if (rowSame && board[i - 1][j] != board[i][j]) {\n return -1;\n }\n if (!rowSame && board[i - 1][j] == board[i][j]) {\n return -1;\n }\n if (colSame && board[j][i - 1] != board[j][i]) {\n return -1;\n }\n if (!colSame && board[j][i - 1] == board[j][i]) {\n return -1;\n }\n }\n }\n int row = 0;\n int col = 0;\n if (board.length % 2 == 0) {\n // if N is even, suppose the first element is 0, calculate diff of row/col\n int rowDiff = 0;\n int colDiff = 0;\n for (int i = 0; i < board.length; i++) {\n if (board[i][0] != row) {\n rowDiff++;\n }\n if (board[0][i] != col) {\n colDiff++;\n }\n row = 1 - row;\n col = 1 - col;\n }\n // (N - diff) suppose the first element is 1\n // swap two different row/cols only need 1 transform, so diff / 2\n return Math.min(rowDiff, board.length - rowDiff) / 2 + Math.min(colDiff, board.length - colDiff) / 2;\n } else {\n // if N is odd, determine the first element based on the count of one\n row = rowOneCount == half + 1 ? 1 : 0;\n col = colOneCount == half + 1 ? 1 : 0;\n int diff = 0;\n for (int i = 0; i < board.length; i++) {\n if (board[i][0] != row) {\n diff++;\n }\n if (board[0][i] != col) {\n diff++;\n }\n row = 1 - row;\n col = 1 - col;\n }\n // since the first element is fixed, return diff / 2\n return diff >> 1;\n }\n }\n```
0
0
['Java']
0
transform-to-chessboard
Java beats 98%: Long, but simple
java-beats-98-long-but-simple-by-jttux-r72k
Consider we\'re given the initial board\n\n1 1 0 0\n0 0 1 1\n1 1 0 0\n0 0 1 1\n\nThis algorithm begins by creating two lists: \n\nAdjustedRows = [1, 2, 1, 2]\nA
jttux
NORMAL
2021-09-28T23:14:17.320555+00:00
2021-09-28T23:17:39.346022+00:00
275
false
Consider we\'re given the initial board\n\n1 1 0 0\n0 0 1 1\n1 1 0 0\n0 0 1 1\n\nThis algorithm begins by creating two lists: \n\nAdjustedRows = [1, 2, 1, 2]\nAdjustedCols = [1, 1, 2, 2]\n\nIt then processes these lists to determine the number of swaps necessary to get into chessboard formation. Chessboard formation for the Adjusted arrays just corresponds to both being [1, 2, 1, 2].\n\nTo see how many swaps are necessary, it compares every other index of AdjustedRows and AdjustedCols to the solution board. Any entries that are different than the solution mean that a swap for that position is required.\n\n```\nclass Solution {\n public int movesToChessboard(int[][] board) {\n int[] boardValue = {-1, 1};\n int size = board.length;\n \n short[] adjustedRows = new short[size], adjustedCols = new short[size];\n int[] uniqueRows = new int[2], uniqueCols = new int[2];\n \n int rowCount = 0, colCount = 0;\n \n // Iterate over col and row.\n int colDifferential, rowDifferential, colCurrent, rowCurrent;\n for(int i = 0; i < size; i++){\n colDifferential = 0;\n rowDifferential = 0;\n \n colCurrent = 0;\n rowCurrent = 0;\n \n // Collect column, row into ints\n for(int j = 0; j < size; j++){\n int colEntry = board[j][i];\n int rowEntry = board[i][j];\n\n colCurrent = colCurrent << 1;\n rowCurrent = rowCurrent << 1;\n \n colCurrent |= colEntry;\n rowCurrent |= rowEntry;\n \n colDifferential += boardValue[colEntry];\n rowDifferential += boardValue[rowEntry];\n }\n \n // Count row\n if(uniqueRows[0] == rowCurrent || uniqueRows[0] == 0){\n uniqueRows[0] = rowCurrent;\n rowCount += 1;\n adjustedRows[i] = 1;\n } else if(uniqueRows[1] == rowCurrent || uniqueRows[1] == 0){\n uniqueRows[1] = rowCurrent;\n rowCount -= 1;\n adjustedRows[i] = 2;\n } else {\n // This is a third unique row, which is impossible to solve.\n return -1;\n }\n \n // Count col\n if(uniqueCols[0] == colCurrent || uniqueCols[0] == 0){\n uniqueCols[0] = colCurrent;\n colCount += 1;\n adjustedCols[i] = 1;\n } else if(uniqueCols[1] == colCurrent || uniqueCols[1] == 0){\n uniqueCols[1] = colCurrent;\n colCount -= 1;\n adjustedCols[i] = 2;\n } else {\n // This is a third unique col, which is impossible to solve.\n return -1;\n }\n \n // If this row had too many of a single digit, it\'s impossible to solve.\n if(Math.abs(rowDifferential) > 1 || Math.abs(colDifferential) > 1){\n return -1;\n }\n }\n \n // We didn\'t get enough unique rows.\n if(uniqueRows[1] == 0){\n return -1;\n }\n \n // We got too many of one type of row\n if(Math.abs(rowCount) > 1){\n return -1;\n }\n \n // If we had two types of rows in the same quantity, then try starting with both rows and \n // just consider the one that took less swaps to create a chessboard.\n boolean tryBothRows = rowCount == 0;\n int mostCommonRow = (rowCount >= 1) ? 1 : 2;\n \n int minRowSwaps = size;\n if(tryBothRows){\n for(short row : new short[]{1, 2}){\n int candidateSwaps = 0;\n for(int i = 0; i < size; i += 2){\n if(adjustedRows[i] != row){\n candidateSwaps += 1;\n }\n }\n \n minRowSwaps = Math.min(minRowSwaps, candidateSwaps);\n }\n } else {\n // Otherwise, just start with the more common row.\n minRowSwaps = 0;\n for(int i = 0; i < size; i += 2){\n if(adjustedRows[i] != mostCommonRow){\n minRowSwaps += 1;\n }\n }\n }\n \n \n boolean tryBothCols = colCount == 0;\n int mostCommonCol = (colCount >= 1) ? 1 : 2;\n \n int minColSwaps = size;\n if(tryBothCols){\n for(short col : new short[]{1, 2}){\n int candidateSwaps = 0;\n for(int i = 0; i < size; i += 2){\n if(adjustedCols[i] != col){\n candidateSwaps += 1;\n }\n }\n \n minColSwaps = Math.min(minColSwaps, candidateSwaps);\n }\n } else {\n minColSwaps = 0;\n for(int i = 0; i < size; i += 2){\n if(adjustedCols[i] != mostCommonCol){\n minColSwaps += 1;\n }\n }\n }\n \n return minRowSwaps + minColSwaps;\n }\n}\n```
0
0
[]
0
transform-to-chessboard
Remember it is a 1D problem (C++)
remember-it-is-a-1d-problem-c-by-tlj77-f67e
You just need to do two things:\n1. Make sure it\'s doable.\n2. find the minimum step to flip first row/column.\n\nWe can transpose the matrix, so do row equals
tlj77
NORMAL
2021-09-27T05:09:42.440081+00:00
2021-09-27T05:12:11.192193+00:00
103
false
You just need to do two things:\n1. Make sure it\'s doable.\n2. find the minimum step to flip first row/column.\n\nWe can transpose the matrix, so do row equals do column.\n```\nclass Solution {\npublic:\n int movesToChessboard(vector<vector<int>>& board) {\n int row = row_min_step(board);\n if(row == -1) return -1;\n transpose(board);\n int col = row_min_step(board);\n if(col == -1) return -1;\n return row + col;\n }\nprivate:\n int row_min_step(vector<vector<int>>& board) {\n int n = board.size();\n vector<int> row(board[0]);\n\t\t// below to make sure it\'s doable.\n bool twoRow = false;\n for(int i = 0; i < n; i++) {\n bool op = false;\n for(int j = 0; j < n; j++) {\n if(op && board[i][j] == row[j]){\n return -1;\n }\n if(!op && board[i][j] != row[j]){\n twoRow = true;\n if(j == 0){\n op = !op;\n } else {\n return -1;\n }\n }\n }\n }\n if(!twoRow) return -1;\n\t\t\n return min_step_1D(row);\n }\n int min_step_1D(vector<int>& row){\n int n = row.size();\n int sum = 0;\n for(int i : row) sum+=i;\n if(abs(sum * 2 - n) > 1) return -1;\n bool zero = true;\n int diff = 0;\n for(int i = 0; i < n; i++){\n if(row[i] != (zero?0:1)) diff++;\n zero = !zero;\n }\n if(diff%2 != 0) return (n - diff) / 2;\n if((n - diff) % 2 != 0) return diff / 2;\n return min(diff, n - diff) / 2;\n }\n void transpose(vector<vector<int>>& board) {\n for(int i = 0; i < board.size(); i++) {\n for(int j = i; j < board.size(); j++){\n int tmp = board[i][j];\n board[i][j] = board[j][i];\n board[j][i] = tmp;\n }\n }\n }\n};\n```
0
0
[]
0
transform-to-chessboard
C# 100%. 100%
c-100-100-by-igor0-vhft
\npublic int MovesToChessboard(int[][] board) {\n\tif (IsBadChessboard(board)) return -1;\n\tif (IsBadChessboard2(board)) return -1;\n\tvar shiftsHor = 0;\n\tfo
igor0
NORMAL
2021-09-26T23:41:01.928034+00:00
2021-09-26T23:41:01.928066+00:00
65
false
```\npublic int MovesToChessboard(int[][] board) {\n\tif (IsBadChessboard(board)) return -1;\n\tif (IsBadChessboard2(board)) return -1;\n\tvar shiftsHor = 0;\n\tfor (int i = 0; i < board.Length; i++)\n\t{\n\t\tvar shiftsHor2 = GetShiftsHor(i, board);\n\t\tif (shiftsHor < shiftsHor2) shiftsHor = shiftsHor2;\n\t}\n\tvar shiftsVer = 0;\n\tfor (int i = 0; i < board[0].Length; i++)\n\t{\n\t\tvar shiftsVer2 = GetShiftsVer(i, board);\n\t\tif (shiftsVer < shiftsVer2) shiftsVer = shiftsVer2;\n\t}\n\tvar rs = shiftsHor / 2 + shiftsVer / 2;\n\treturn rs;\n}\nprivate int GetShiftsVer(int col, int[][] board)\n{\n\tif (board.Length % 2 == 0)\n\t{\n\t\tvar errors0 = 0;\n\t\tvar errors1 = 0;\n\t\tfor (int i = 0; i < board.Length; i++)\n\t\t{\n\t\t\tif (i % 2 == 0)\n\t\t\t{\n\t\t\t\tif (board[i][col] == 0)\n\t\t\t\t{\n\t\t\t\t\terrors1++;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\terrors0++;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tif (board[i][col] == 0)\n\t\t\t\t{\n\t\t\t\t\terrors0++;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\terrors1++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tvar rs = Math.Min(errors0, errors1);\n\t\treturn rs;\n\t}\n\telse\n\t{\n\t\tvar countOne = 0;\n\t\tfor (int i = 0; i < board.Length; i++)\n\t\t{\n\t\t\tcountOne += board[i][col];\n\t\t}\n\t\tvar onesIsMore = countOne == (board.Length + 1) / 2;\n\t\tvar errors = 0;\n\t\tfor (int i = 0; i < board.Length; i++)\n\t\t{\n\t\t\tif (i % 2 == 0)\n\t\t\t{\n\t\t\t\tif (!onesIsMore)\n\t\t\t\t{\n\t\t\t\t\tif (board[i][col] == 1) errors++;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tif (board[i][col] == 0) errors++;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tif (!onesIsMore)\n\t\t\t\t{\n\t\t\t\t\tif (board[i][col] == 0) errors++;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tif (board[i][col] == 1) errors++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn errors;\n\t}\n}\nprivate int GetShiftsHor(int row, int[][] board)\n{\n\tif (board[row].Length % 2 == 0)\n\t{\n\t\tvar errors0 = 0;\n\t\tvar errors1 = 0;\n\t\tfor (int i = 0; i < board[row].Length; i++)\n\t\t{\n\t\t\tif (i % 2 == 0)\n\t\t\t{\n\t\t\t\tif (board[row][i] == 0)\n\t\t\t\t{\n\t\t\t\t\terrors1++;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\terrors0++;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tif (board[row][i] == 0)\n\t\t\t\t{\n\t\t\t\t\terrors0++;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\terrors1++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tvar rs = Math.Min(errors0, errors1);\n\t\treturn rs;\n\t}\n\telse\n\t{\n\t\tvar countOne = board[row].Sum();\n\t\tvar onesIsMore = countOne == (board[row].Length + 1) / 2;\n\t\tvar errors = 0;\n\t\tfor (int i = 0; i < board[row].Length; i++)\n\t\t{\n\t\t\tif (i % 2 == 0)\n\t\t\t{\n\t\t\t\tif (!onesIsMore)\n\t\t\t\t{\n\t\t\t\t\tif (board[row][i] == 1) errors++;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tif (board[row][i] == 0) errors++;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tif (!onesIsMore)\n\t\t\t\t{\n\t\t\t\t\tif (board[row][i] == 0) errors++;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tif (board[row][i] == 1) errors++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn errors;\n\t}\n}\nprivate bool IsBadChessboard2(int[][] board)\n{\n\tvar rows = new[] { -1, -1 };\n\tfor (int i = 0; i < board.Length; i++)\n\t{\n\t\tif (board[i][0] == 0)\n\t\t{\n\t\t\tif (rows[0] == -1)\n\t\t\t{\n\t\t\t\trows[0] = i;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tfor (int j = 0; j < board[i].Length; j++)\n\t\t\t\t{\n\t\t\t\t\tif (board[rows[0]][j] != board[i][j]) return true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif (rows[1] == -1)\n\t\t\t{\n\t\t\t\trows[1] = i;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tfor (int j = 0; j < board[i].Length; j++)\n\t\t\t\t{\n\t\t\t\t\tif (board[rows[1]][j] != board[i][j]) return true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tvar cols = new[] { -1, -1 };\n\tfor (int i = 0; i < board[0].Length; i++)\n\t{\n\t\tif (board[0][i] == 0)\n\t\t{\n\t\t\tif (cols[0] == -1)\n\t\t\t{\n\t\t\t\tcols[0] = i;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tfor (int j = 0; j < board.Length; j++)\n\t\t\t\t{\n\t\t\t\t\tif (board[j][cols[0]] != board[j][i]) return true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif (cols[1] == -1)\n\t\t\t{\n\t\t\t\tcols[1] = i;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tfor (int j = 0; j < board.Length; j++)\n\t\t\t\t{\n\t\t\t\t\tif (board[j][cols[1]] != board[j][i]) return true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn false;\n}\nprivate bool IsBadChessboard(int[][] board)\n{\n\tif (board.Length % 2 == 0)\n\t{\n\t\tfor (int i = 0; i < board.Length; i++)\n\t\t{\n\t\t\tvar countZero = 0;\n\t\t\tfor (int j = 0; j < board[i].Length; j++)\n\t\t\t{\n\t\t\t\tif (board[i][j] == 0) countZero++;\n\t\t\t}\n\t\t\tif (countZero != board[i].Length / 2) return true;\n\t\t}\n\t\tfor (int j = 0; j < board[0].Length; j++)\n\t\t{\n\t\t\tvar countZero = 0;\n\t\t\tfor (int i = 0; i < board.Length; i++)\n\t\t\t{\n\t\t\t\tif (board[i][j] == 0) countZero++;\n\t\t\t}\n\t\t\tif (countZero != board.Length / 2) return true;\n\t\t}\n\t\treturn false;\n\t}\n\telse\n\t{\n\t\tvar diff = 0;\n\t\tfor (int i = 0; i < board.Length; i++)\n\t\t{\n\t\t\tvar countZero = 0;\n\t\t\tvar countOne = 0;\n\t\t\tfor (int j = 0; j < board[i].Length; j++)\n\t\t\t{\n\t\t\t\tif (board[i][j] == 0)\n\t\t\t\t{\n\t\t\t\t\tcountZero++;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tcountOne++;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (Math.Abs(countZero - countOne) != 1) return true;\n\t\t\tif (countZero > countOne)\n\t\t\t{\n\t\t\t\tdiff++;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tdiff--;\n\t\t\t}\n\t\t}\n\t\tif (Math.Abs(diff) != 1) return true;\n\t\tdiff = 0;\n\t\tfor (int j = 0; j < board[0].Length; j++)\n\t\t{\n\t\t\tvar countZero = 0;\n\t\t\tvar countOne = 0;\n\t\t\tfor (int i = 0; i < board.Length; i++)\n\t\t\t{\n\t\t\t\tif (board[i][j] == 0)\n\t\t\t\t{\n\t\t\t\t\tcountZero++;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tcountOne++;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (Math.Abs(countZero - countOne) != 1) return true;\n\t\t\tif (countZero > countOne)\n\t\t\t{\n\t\t\t\tdiff++;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tdiff--;\n\t\t\t}\n\t\t}\n\t\tif (Math.Abs(diff) != 1) return true;\n\t\treturn false;\n\t}\n}\n```
0
0
[]
0
transform-to-chessboard
Python, short, invariants tracked
python-short-invariants-tracked-by-agaki-q19x
The invariants to check in this problem are:\n1. There should be only 2 unique rows\n2. They sum in every column must be 1\n3. Number od 1s and 0s in every row
agakishy
NORMAL
2021-09-26T23:04:05.327987+00:00
2021-09-26T23:04:05.328020+00:00
114
false
The invariants to check in this problem are:\n1. There should be only 2 unique rows\n2. They sum in every column must be 1\n3. Number od 1s and 0s in every row shouldn\'t be less then n//2\n4a. For odd n: if 3 above statements are true - there is only one posible solution ruled by most frequent row\n4b. For even n: there exist 2 possibilities: either some of 2 rows can start from 1 or 0. For every of those possibility we find min among being on even or odd position in board.\n\n\n\n```\nclass Solution:\n def movesToChessboard(self, board: List[List[int]]) -> int:\n n = len(board)\n c = defaultdict(Counter)\n for i in range(n):\n c[tuple(board[i])][i%2] += 1 # count even and odd positions for every unique row\n c[tuple(board[i])][1-(i%2)] += 0 # activate other\n if board[i].count(0) < n//2 or board[i].count(1) < n//2: return -1\n if len(c) != 2: return -1 # there should be only 2 unique rows\n if min(sum(cntr.values()) for cntr in c.values()) < n//2: return -1 \n for a, b in zip(*c.keys()):\n if a+b != 1: return -1\n rows = list(c.keys())\n if n % 2 == 1:\n frequent = 0 if sum(c[rows[1]].values()) == n//2 else 1\n pivot = 0 if rows[frequent].count(1) == n//2 else 1\n return c[rows[frequent]][1] + rows[frequent][::2].count(1-pivot)\n # pivot is either 0 and it is in [0s row or in 1st row] or it is 1 in [0s row or 1st row]\n variants = [rows[i][0::2].count(j)+min(c[rows[i]].values()) for i in range(2) for j in range(2)]\n\n return min(variants)\n```
0
0
[]
0
transform-to-chessboard
Go solution
go-solution-by-ganesh-i1p8
https://github.com/ganeshskudva/Leetcode-Golang\n\nInspired by this solution\n\nfunc movesToChessboard(board [][]int) int {\n\tn := len(board)\n\tfor i := 0; i
ganesh
NORMAL
2021-09-26T21:08:16.348483+00:00
2021-09-26T21:08:16.348529+00:00
31
false
ERROR: type should be string, got "https://github.com/ganeshskudva/Leetcode-Golang\\n\\nInspired by [this](https://leetcode.com/problems/transform-to-chessboard/discuss/114847/C%2B%2BJavaPython-Solution-with-Explanation) solution\\n```\\nfunc movesToChessboard(board [][]int) int {\\n\\tn := len(board)\\n\\tfor i := 0; i < n; i++ {\\n\\t\\tfor j := 0; j < n; j++ {\\n\\t\\t\\tif (board[0][0] ^ board[i][0] ^ board[0][j] ^ board[i][j]) == 1 {\\n\\t\\t\\t\\treturn -1\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\n\\trowSum, colSum, rowMisplaced, colMisplaced := 0, 0, 0, 0\\n\\tfor i := 0; i < n; i++ {\\n\\t\\trowSum += board[0][i]\\n\\t\\tcolSum += board[i][0]\\n\\t\\tif board[i][0] == i%2 {\\n\\t\\t\\trowMisplaced++\\n\\t\\t}\\n\\t\\tif board[0][i] == i%2 {\\n\\t\\t\\tcolMisplaced++\\n\\t\\t}\\n\\t}\\n\\n\\tif rowSum != n/2 && rowSum != (n+1)/2 {\\n\\t\\treturn -1\\n\\t}\\n\\tif colSum != n/2 && colSum != (n+1)/2 {\\n\\t\\treturn -1\\n\\t}\\n\\n\\tif n%2 == 1 {\\n\\t\\tif colMisplaced%2 == 1 {\\n\\t\\t\\tcolMisplaced = n - colMisplaced\\n\\t\\t}\\n\\t\\tif rowMisplaced%2 == 1 {\\n\\t\\t\\trowMisplaced = n - rowMisplaced\\n\\t\\t}\\n\\t} else {\\n\\t\\tcolMisplaced = min(n-colMisplaced, colMisplaced)\\n\\t\\trowMisplaced = min(n-rowMisplaced, rowMisplaced)\\n\\t}\\n\\n\\treturn (colMisplaced + rowMisplaced) / 2\\n}\\n\\nfunc min(a, b int) int {\\n\\tif a < b {\\n\\t\\treturn a\\n\\t}\\n\\n\\treturn b\\n}\\n```"
0
0
[]
0
transform-to-chessboard
{Python} Dimension independence + 2-building block for row and column
python-dimension-independence-2-building-cmxf
Approach 1[1]: Dimension independence + 2-building block for row and column\nTime/Space Complexity: O(N)\n\n\nclass Solution(object):\n def movesToChessboard
codedayday
NORMAL
2021-09-26T20:22:23.258452+00:00
2021-09-26T22:41:31.031137+00:00
154
false
Approach 1[1]: Dimension independence + 2-building block for row and column\nTime/Space Complexity: O(N)\n\n```\nclass Solution(object):\n def movesToChessboard(self, board):\n N = len(board)\n ans = 0\n # For each count of lines from {rows, columns}...\n for count in (collections.Counter(map(tuple, board)), # get row\n collections.Counter(zip(*board))): #get column\n\n # If there are more than 2 kinds of lines,\n # or if the number of kinds is not appropriate ...\n if len(count) != 2 or sorted(count.values()) != [N/2, (N+1)/2]:\n return -1\n\n # If the lines are not opposite each other, impossible\n line1, line2 = count\n if not all(x ^ y for x, y in zip(line1, line2)):\n return -1\n\n # starts = what could be the starting value of line1\n # If N is odd, then we have to start with the more\n # frequent element\n starts = [int(line1.count(1) * 2 > N)] if N%2 else [0, 1]\n\n # To transform line1 into the ideal line [i%2 for i ...],\n # we take the number of differences and divide by two\n ans += min(sum((x-i) % 2 for i, x in enumerate(line1, start))\n for start in starts) / 2 \n\n return ans\n```\n\nReference:\n[1] https://leetcode.com/problems/transform-to-chessboard/solution/
0
0
['Divide and Conquer', 'Python']
0
transform-to-chessboard
Go solution | Beats 100%
go-solution-beats-100-by-evleria-z3yf
\nfunc movesToChessboard(board [][]int) int {\n\tn, rowSum, colSum, rowSwap, colSwap := len(board), 0, 0, 0, 0\n\n\tfor i := 0; i < n; i++ {\n\t\tfor j := 0; j
evleria
NORMAL
2021-09-26T17:57:48.895913+00:00
2021-09-26T17:58:38.543524+00:00
83
false
```\nfunc movesToChessboard(board [][]int) int {\n\tn, rowSum, colSum, rowSwap, colSwap := len(board), 0, 0, 0, 0\n\n\tfor i := 0; i < n; i++ {\n\t\tfor j := 0; j < n; j++ {\n\t\t\tif board[0][0]^board[i][0]^board[0][j]^board[i][j] == 1 {\n\t\t\t\treturn -1\n\t\t\t}\n\t\t}\n\t}\n\n\tfor i := 0; i < n; i++ {\n\t\trowSum += board[0][i]\n\t\tcolSum += board[i][0]\n\t\tif board[i][0] == i%2 {\n\t\t\trowSwap++\n\t\t}\n\t\tif board[0][i] == i%2 {\n\t\t\tcolSwap++\n\t\t}\n\t}\n\n\tif rowSum != n/2 && rowSum != (n+1)/2 {\n\t\treturn -1\n\t}\n\tif colSum != n/2 && colSum != (n+1)/2 {\n\t\treturn -1\n\t}\n\tif n%2 == 1 {\n\t\tif colSwap%2 == 1 {\n\t\t\tcolSwap = n - colSwap\n\t\t}\n\t\tif rowSwap%2 == 1 {\n\t\t\trowSwap = n - rowSwap\n\t\t}\n\t} else {\n\t\tcolSwap = min(n-colSwap, colSwap)\n\t\trowSwap = min(n-rowSwap, rowSwap)\n\t}\n\treturn (colSwap + rowSwap) / 2\n}\n\nfunc min(a, b int) int {\n\tif a < b {\n\t\treturn a\n\t}\n\treturn b\n}\n```
0
0
['Go']
0
transform-to-chessboard
Java, 95%/92%, validate then calculate, with explanation
java-9592-validate-then-calculate-with-e-226z
There are 3 necessary conditions that need to be validated. Taken together, they are sufficient to confirm that the grid is solvable.\n1. In the first row, the
mnorby26
NORMAL
2021-09-26T17:42:50.385745+00:00
2021-09-26T17:44:08.215077+00:00
136
false
There are 3 necessary conditions that need to be validated. Taken together, they are sufficient to confirm that the grid is solvable.\n1. In the first row, the number of ones and zeroes must be the same, or different by one.\n2. In the first column, the number of ones and zeroes must be the same, or different by one.\n3. Every row after the first must be either identical to the first row, or binary opposite. By "binary opposite", I mean that every digit is different (e.g. for [1,0,1,1,0], the binary opposite is [0,1,0,0,1]).\n\nTo understand #3, consider two rows in the grid. If they are identical before swapping two columns, they will be identical to one another afterward. The same is true when considering two columns and swapping two rows. Therefore, the rows must start as identical, or binary opposite, when given in the grid. Otherwise, there is no solution.\n\nOnce we have validated the above conditions, if the number of rows/columns is even, the answer is simple to calculate. Add the number of column swaps (to move zeroes to even columns or odd columns in the first row, whichever is less) to the number of row swaps (to move all zeroes in even rows or odd rows in the first column, whichever is less).\n\nIf there is an odd number of rows in the grid, we have to be more careful. There are an odd number of grid entries, meaning one value is more common than the other. That is the value that must go in the even rows and columns. Also, this algorithm starts with row swaps, to make the first column alternate zeroes and ones. If those row swaps change the first row, it must recalculate the zero counts for the first row so that the column swaps are calculated correctly.\n\nTC: O(n^2) to visit every cell, to validate condition #3 above\nSC: O(1)\n\n```\nclass Solution {\n public int movesToChessboard(int[][] board) {\n final int n = board.length;\n\n // Count zeroes in the first row, and in even columns in the first row.\n // Also count zeroes in the first column, and in even rows in the first column.\n int zeroesRow1 = 0;\n int zeroesCol1 = 0;\n int zeroesEvenCols = 0;\n int zeroesEvenRows = 0;\n for (int i = 0; i < n; i++) {\n if (board[i][0] == 0) {\n zeroesCol1++;\n if (i % 2 == 0) zeroesEvenRows++;\n }\n if (board[0][i] == 0) {\n zeroesRow1++;\n if (i % 2 == 0) zeroesEvenCols++;\n }\n }\n\n // Validate that the board is solvable.\n // Half of the rows and columns (to within 1) must be zeroes.\n if (Math.abs(n - 2 * zeroesRow1) > 1) return -1;\n if (Math.abs(n - 2 * zeroesCol1) > 1) return -1;\n\n // All rows must be either identical or binary opposite to the first row.\n for (int i = 1; i < n; i++)\n for (int j = 1; j < n; j++)\n if ((board[0][0] == board[i][0]) ^ (board[0][j] == board[i][j])) return -1;\n\n // Now we know that the problem is solvable.\n // If there are an even number of rows, the answer is easy to calculate.\n if (n % 2 == 0)\n return Math.min(zeroesEvenRows, n/2 - zeroesEvenRows)\n + Math.min(zeroesEvenCols, n/2 - zeroesEvenCols);\n \n // Odd number of rows. Calculate the total number of zeroes in the grid.\n int totalZeroes;\n if (board[0][0] == 0) totalZeroes = zeroesRow1 * zeroesCol1 + (n - zeroesRow1) * (n - zeroesCol1);\n else totalZeroes = zeroesRow1 * (n - zeroesCol1) + (n - zeroesRow1) * zeroesCol1;\n \n // Goal for row-swapping is to get the rows alternating by first column value.\n // If the first row changes as the result of swapping, recalculate zeroes in the first row.\n int rowSwaps;\n if (zeroesCol1 * 2 > n) {\n // More zeroes than ones in the first column. Move zeroes from odd rows to even.\n rowSwaps = (n + 1)/2 - zeroesEvenRows;\n if (board[0][0] == 1) {\n zeroesRow1 = n - zeroesRow1;\n zeroesEvenCols = (n + 1)/2 - zeroesEvenCols;\n }\n } else {\n // More ones than zeroes in the first column. Move zeroes from even rows to odd.\n rowSwaps = zeroesEvenRows;\n if (board[0][0] == 0) {\n zeroesRow1 = n - zeroesRow1;\n zeroesEvenCols = (n + 1)/2 - zeroesEvenCols;\n }\n }\n \n // Goal for column-swapping is to get the more common number in the first column,\n // and alternate columns by first row value.\n return rowSwaps + (totalZeroes * 2 > n * n ? (n + 1)/2 - zeroesEvenCols : zeroesEvenCols);\n }\n}\n```
0
0
[]
0
transform-to-chessboard
[C++] Check bitmask signature of rows and columns
c-check-bitmask-signature-of-rows-and-co-p3ol
\nclass Solution {\n using sig_t = std::bitset<30>;\npublic: \n int movesToChessboard(std::vector<std::vector<int>> &board) {\n const int num_ro
phi9t
NORMAL
2021-09-26T17:36:46.800474+00:00
2021-09-26T17:36:46.800526+00:00
77
false
```\nclass Solution {\n using sig_t = std::bitset<30>;\npublic: \n int movesToChessboard(std::vector<std::vector<int>> &board) {\n const int num_rows = board.size(), num_cols = board[0].size();\n if (num_rows != num_cols) {\n return -1;\n }\n\n const auto get_signature = \n [&](std::unordered_map<sig_t, int> &sig_to_cnts) -> std::optional<sig_t> {\n std::vector<std::pair<sig_t, int>> items; \n if (sig_to_cnts.size() != 2) {\n return std::nullopt;\n } \n for (auto &&kv : sig_to_cnts) {\n items.emplace_back(kv);\n }\n const int lhs = items[0].second;\n const int rhs = items[1].second;\n if (std::abs(lhs - rhs) > 1) {\n return std::nullopt;\n }\n return items[0].first;\n };\n \n sig_t row_sig;\n {\n std::unordered_map<sig_t, int> sig_to_cnts;\n for (int row = 0; row < num_rows; ++row) {\n sig_t sig;\n for (int col = 0; col < num_cols; ++col) {\n sig[col] = (board[row][col] == 1);\n }\n ++sig_to_cnts[sig];\n }\n if (auto res = get_signature(sig_to_cnts)) {\n row_sig = *res;\n } else {\n return -1;\n }\n } \n \n sig_t col_sig;\n {\n std::unordered_map<sig_t, int> sig_to_cnts;\n for (int col = 0; col < num_cols; ++col) {\n sig_t sig;\n for (int row = 0; row < num_rows; ++row) {\n sig[row] = (board[row][col] == 1);\n }\n ++sig_to_cnts[sig]; \n }\n if (auto res = get_signature(sig_to_cnts)) {\n col_sig = *res;\n } else {\n return -1;\n }\n } \n \n const auto diff_signature = [&](const sig_t &ref, const sig_t &tgt) -> int {\n int diff_cnts = 0;\n for (int i = 0; i < num_cols; ++i) {\n if (ref[i] != tgt[i]) {\n ++diff_cnts;\n }\n }\n return diff_cnts;\n };\n \n sig_t ref01, ref10;\n for (int i = 0; i < num_cols; ++i) {\n ref01[i] = (i % 2 == 1);\n ref10[i] = (i % 2 == 0);\n } \n const auto get_min_ops = [&](const sig_t &tgt) -> int {\n int lhs_diff = INT_MAX;\n if (ref01.count() == tgt.count()) {\n lhs_diff = diff_signature(ref01, tgt);\n }\n int rhs_diff = INT_MAX;\n if (ref10.count() == tgt.count()) {\n rhs_diff = diff_signature(ref10, tgt);\n }\n return std::min(lhs_diff, rhs_diff) / 2;\n };\n \n return get_min_ops(row_sig) + get_min_ops(col_sig);\n }\n};\n```
0
0
[]
0
transform-to-chessboard
Rust translated
rust-translated-by-sugyan-6s65
rust\nimpl Solution {\n pub fn moves_to_chessboard(board: Vec<Vec<i32>>) -> i32 {\n let n = board.len();\n for i in 1..n {\n if (1..
sugyan
NORMAL
2021-09-26T16:43:23.061215+00:00
2021-09-26T16:43:23.061247+00:00
69
false
```rust\nimpl Solution {\n pub fn moves_to_chessboard(board: Vec<Vec<i32>>) -> i32 {\n let n = board.len();\n for i in 1..n {\n if (1..n as i32).contains(&(0..n).map(|j| board[i][j] ^ board[0][j]).sum::<i32>()) {\n return -1;\n }\n if (1..n as i32).contains(&(0..n).map(|j| board[j][i] ^ board[j][0]).sum::<i32>()) {\n return -1;\n }\n }\n if ((0..n).map(|i| board[0][i]).sum::<i32>() * 2 - n as i32).abs() > 1 {\n return -1;\n }\n if ((0..n).map(|i| board[i][0]).sum::<i32>() * 2 - n as i32).abs() > 1 {\n return -1;\n }\n let mut rowdiff = (0..n).filter(|&i| board[0][i] == i as i32 % 2).count();\n if rowdiff % 2 != 0 || (n % 2 == 0 && rowdiff * 2 > n) {\n rowdiff = n - rowdiff;\n }\n let mut coldiff = (0..n).filter(|&i| board[i][0] == i as i32 % 2).count();\n if coldiff % 2 != 0 || (n % 2 == 0 && coldiff * 2 > n) {\n coldiff = n - coldiff;\n }\n (rowdiff + coldiff) as i32 / 2\n }\n}\n```
0
0
['Rust']
0
transform-to-chessboard
Super Helpful Explanation
super-helpful-explanation-by-manu2710aro-0pmq
Inspired by this and this posts, but use a different approach to count swap number, IMHO, which is more intuitive.\n```\n int movesToChessboard(vector>& bo
manu2710arora
NORMAL
2021-09-26T16:15:46.815264+00:00
2021-09-26T16:15:46.815333+00:00
86
false
Inspired by [this](https://leetcode.com/problems/transform-to-chessboard/discuss/114847/Easy-and-Concise-Solution-with-Explanation-C%2B%2BJavaPython) and [this](https://leetcode.com/problems/transform-to-chessboard/discuss/132113/Java-Clear-Code-with-Detailed-Explanations) posts, but use a different approach to count swap number, IMHO, which is more intuitive.\n```\n int movesToChessboard(vector<vector<int>>& board) {\n /**** An Important Fact ****\n Take any 2 rows r1 and r2, then take 2 items in the same column c from the 2 rows, e.g. b[r1][c], b[r2][c], \n no matter how the rows or columns swap, the relationship between the 2 items never changes:\n if they are the same, they will always be the same, if they are inverted, they will always be inverted.\n Hence for a chess board, any two rows (or two columns) are either the same, or inverted.\n ***************************/\n // Hence we have:\n // Rule 1. If the board can be transformed to a chess board, for any two rows in the board, the cells between them must be either all the same, \n // or all inverted, if some items are inverted and some items are the same, they can\'t form a chess board by swapping.\n // On the other hand:\n // Rule 2. The difference of two types of rows/columns cannot > 1, otherwise there must be >= 2 same type of rows/columns arranged together.\n\t\t\n // Now, validate our board by these 2 rules.\n int n = board.size();\n int row_counter = 0, col_counter = 0;\n for(int r = 0; r < n; r++){\n row_counter += board[r][0] ? 1 : -1;\n for(int c = 0; c < n; c++){\n if(r == 0) col_counter += board[r][c] ? 1 : -1;\n // Check rule 1.\n // The relationship of items in current column between current row and first row should be consistent with the relationship of first items between current row and first row (i.e. the 2 pair of items should be either both the same or both inverted). Hence we compare the first cell of current row and first cell of first row, \nthen compare the current cell with the cell in the cell in the same column in first row, the result should be the same.\n // Since XOR operator is associative and commutative, we don\'t have to verify columns again (i.e. (board[0][c] ^ board[0][0]) ^ (board[r][c] ^ board[r][0]) )\n if((board[r][0] ^ board[0][0]) ^ (board[r][c] ^ board[0][c])) return -1; \n }\n }\n \n // Check rule 2.\n if(abs(row_counter) > 1 || abs(col_counter) > 1) return -1;\n \n // Count possible swap count, we only need care about the swap count of odd positions, since when we swap, we always swap an odd position with an even position.\n int row_swap_count = 0, col_swap_count = 0, row_0_count = 0, col_0_count = 0;\n // When n is odd, we need fit the item whose count is larger into even positions because even position is more than odd position.\n // E.g. \n // 0,1,0,1,1, then 0s must stay on odd positions so that 1s stay on even positions: 1,0,1,0,1.\n // 1,0,1,0,0, then 1s must stay on odd positions so that 0s stay on even positions: 0,1,0,1,0.\n for(int i = 0; i < n; i++){\n if(i & 1){ // When i is odd\n // Assume 0 is less and should stay on odd position, so we swap 1 away from odd position.\n row_swap_count += board[i][0];\n col_swap_count += board[0][i];\n }\n // Count 0.\n row_0_count += board[i][0] == 0, col_0_count += board[0][i] == 0; \n }\n \n int odd_position_count = n/2; // Odd position count is always less than or equal with even position count.\n if(n & 1){ // When n is odd.\n // Count of 0 == odd_position_count means 0 is less, so we\'re right on swapping 1 away, the current swap count is correct. \n\t\t\t// Otherwise we should keep 1 on the odd position and swap 0 away, so the swap count becomes odd_position_count - row_swap_count.\n row_swap_count = row_0_count == odd_position_count ? row_swap_count : (odd_position_count - row_swap_count);\n col_swap_count = col_0_count == odd_position_count ? col_swap_count : (odd_position_count - col_swap_count);\n }\n else{\n // If n is even, odd position\'s count is the same with even position\'s count, choose whichever swap count is smaller.\n row_swap_count = min(row_swap_count, odd_position_count - row_swap_count);\n col_swap_count = min(col_swap_count, odd_position_count - col_swap_count); \n }\n \n return row_swap_count + col_swap_count;\n }
0
0
[]
0
transform-to-chessboard
Refer this Post
refer-this-post-by-sruti08patak-vj95
https://leetcode.com/problems/transform-to-chessboard/discuss/114847/C%2B%2BJavaPython-Solution-with-Explanation\n\nAlso follow the comments for your learning.
sruti08patak
NORMAL
2021-09-26T15:48:59.271965+00:00
2021-09-26T15:48:59.272022+00:00
61
false
https://leetcode.com/problems/transform-to-chessboard/discuss/114847/C%2B%2BJavaPython-Solution-with-Explanation\n\nAlso follow the comments for your learning.
0
0
[]
0
transform-to-chessboard
[Python]StraightForward Approach
pythonstraightforward-approach-by-rjvish-rzjp
```\nfrom operator import xor\nclass Solution(object):\n def movesToChessboard(self, board):\n """\n :type board: List[List[int]]\n :rty
rjvishwa21
NORMAL
2021-09-26T15:40:01.470897+00:00
2021-09-26T15:40:13.536447+00:00
76
false
```\nfrom operator import xor\nclass Solution(object):\n def movesToChessboard(self, board):\n """\n :type board: List[List[int]]\n :rtype: int\n """\n m,n=len(board),len(board[0])\n\n # check single row\n def valid_s(r):\n n=len(r)\n rowSum=sum(r)\n if n%2: # odd number\n if rowSum not in [n/2,n/2+1]: return False\n else: # even number\n if rowSum!=n/2: return False\n return True\n\n # compare each adjacent row\n def valid(r1,r2):\n if r1==r2 or all(map(xor,r1,r2)): return True\n return False\n\n # check rows\n if not valid_s(board[0]): return -1\n for i in xrange(m-1):\n if not valid(board[i],board[i+1]):\n return -1\n\n # check columns\n boardT=map(list,zip(*board)) # transform for simplicity\n if not valid_s(boardT[0]): return -1\n for i in xrange(n-1):\n if not valid(boardT[i],boardT[i+1]):\n return -1\n\n # calculate swap\n def cal(r):\n n=len(r)\n rowsum=sum(r)\n if n%2: # odd number\n if rowsum>n/2: # 1 dominates\n r1=[1,0]*(n/2)+[1]\n else: # 0 dominates\n r1=[0,1]*(n/2)+[0]\n return sum(map(xor,r,r1))/2\n else: # even number\n r1=[1,0]*(n/2)\n r2=[0,1]*(n/2)\n swap1=sum(map(xor,r,r1))\n swap2=sum(map(xor,r,r2))\n return min(swap1,swap2)/2\n\n return cal(board[0])+cal(boardT[0])
0
0
[]
0
transform-to-chessboard
Easy Explanation
easy-explanation-by-psnoy00001111-ayrg
The algorithm is based on counting. A solvable board has each row/column either the same as the first row/column or exactly cell-by-cell reversed color of the f
psnoy00001111
NORMAL
2021-09-26T15:36:15.347068+00:00
2021-09-26T15:36:15.347107+00:00
100
false
The algorithm is based on counting. A solvable board has each row/column either the same as the first row/column or exactly cell-by-cell reversed color of the first row/column.\n\nIn the loop we count for rs and cs, the number of rows/columns being the same as the first row/column, and rm and cm, the number of misplaced rows/columns in the view of the first row/column. If any row/column is found to be neither the same nor reversed color then returns -1 immediately.\n\nThen, for even number n there are two final forms of the first row/column. We compute the minimum swaps of the two cases. For odd number n there is only one final form of the board so we compute the swaps based on the fact that whether the first row/column is in the less or the greater half.\n```\nint movesToChessboard(vector<vector<int>>& b) {\n int n = b.size();\n int rs = 0, cs = 0, rm = 0, cm = 0;\n\n for (int i = 0; i < n; i++) {\n bool rf = b[0][0] == b[i][0], cf = b[0][0] == b[0][i];\n rs += rf, cs += cf;\n rm += rf ^ !(i & 1), cm += cf ^ !(i & 1);\n for (int j = 0; j < n; j++)\n if ((b[0][j] == b[i][j]) ^ rf || (b[j][0] == b[j][i]) ^ cf)\n return -1;\n }\n\n if (n % 2 == 0) {\n if (rs == n / 2 && cs == n / 2)\n return min(rm, n - rm) / 2 + min(cm, n - cm) / 2;\n return -1;\n }\n\n int res = 0;\n if (rs == n / 2)\n res += (n - rm) / 2;\n else if (rs == n / 2 + 1)\n res += rm / 2;\n else\n return -1;\n\n if (cs == n / 2)\n res += (n - cm) / 2;\n else if (cs == n / 2 + 1)\n res += cm / 2;\n else\n return -1;\n\n return res;\n}
0
0
['C']
0
transform-to-chessboard
Python3
python3-by-isissifeng-wiqq
\n
isissifeng
NORMAL
2021-09-26T15:06:25.284236+00:00
2021-09-26T15:06:25.284287+00:00
113
false
![image](https://assets.leetcode.com/users/images/dd2a3966-be6c-485c-8303-54fa1233d588_1632668777.2564044.png)\n
0
0
[]
0
transform-to-chessboard
O(N^2) c++ code with proof of mzchen's observation in comments.
on2-c-code-with-proof-of-mzchens-observa-ypuj
This isn\'t easy to get for me and I hope my code and comment is clear. I think this is a better code readability practice that algo practice.\nPlease let me kn
consciousgaze
NORMAL
2021-01-01T10:42:20.711946+00:00
2021-01-01T10:45:39.169110+00:00
195
false
This isn\'t easy to get for me and I hope my code and comment is clear. I think this is a better code readability practice that algo practice.\nPlease let me know the confusing parts :P\n```\nclass Solution {\npublic:\n // Both the column and row swap satisfies the following\n // property:\n // All the numbers in a row will always be in the same row\n // however swapped. The reasoning is simple: row swap will \n // keep the positions of the numbers in the same row unchanged\n // and column swap will move the number in a same row within\n // the row.\n // Similarly all the numbers in a same column will always be \n // in the same column, however swapped.\n // Let\'s call it "group-invariant property" which is vital for\n // an efficient solution.\n int movesToChessboard(vector<vector<int>>& board) {\n int n = board.size();\n // If a board is transformable, there can only be two kind\n // of rows: 1. the number order in the row are extactly same\n // as in the first row; 2. the number in the row are exactly\n // complimentary of the nubmer in the first row at the same\n // position. Similar rules also apply to columns. This will\n // be notd as the "complimentary" property.\n // This can be proved by contradictory. Assume there are two\n // rows, r1 and r2, in the board where exits two positions p1\n // and p2. The numbers in r1 and r2 at position p1 are 1 and 0\n // correspondingly and the numbers at position p2 are both 1.\n // If the board is transformable, numbers at p2 needs to be\n // swapped without affecting the nubmers at p1. And it is not \n\t\t// possible for the elements to move out from r1 or r2 due to \n\t\t// the "group-invariant property". Since there are\n // only two operations column swap and row swap, they can be\n // tried exhaustively. Row swap won\'t change relative positions\n // within two rows so it won\'t work. Column swap will move numbers\n // at p1 togather, so it also cannot be done. If one want to \n // swap numbers at position p1 without affecting number at p2,\n // similary reasoning can be applied. Thus complimentary property\n // is proved.\n for (int i = 0; i < n; ++i) {\n // If ith row and first row are exactly the same, \n // rowComplimentary will be 0, otherwise 1.\n int rowComplimentary = board[i][0] ^ board[0][0];\n // If ith column and first column are exactly the same, \n // colComplimentary will be 0, otherwise 1.\n int colComplimentary = board[0][i] ^ board[0][0];\n for (int j = 0; j < n; ++j) {\n // Check the complimentary property on ith rows.\n if ((board[i][j] ^ board[0][j]) != rowComplimentary) {\n return -1;\n }\n // Check the complimentary property on ith columns.\n if ((board[j][i] ^ board[j][0]) != colComplimentary) {\n return -1;\n }\n }\n }\n\n // There are two properties\n // that will be helpful here:\n // 1. row and column are moved independently so the moves need \n // to be added.\n // 2. If there are n rows/columns that are mis-placed, each swap\n // can put two of them back to right place, thus the move number\n // will be mis-placed numbers divided by 2.\n // 3. Assume all 0s should be put on even position and all 1s\n // should be put on odd positions, the acutual misplaced number\n // will be the smaller one between misplaced-number and\n // N - misplaced-number.\n // This section be combined into the first for loop where the complimentary\n // property is verified.\n int misplacedRowCount = 0;\n int misplacedColCount = 0;\n int rowComplimentartyCount = 0;\n int colComplimentartyCount = 0;\n for (int i = 0; i < n; ++i) {\n // Count misplaced digit for first row.\n int complimentaryRow = board[0][i] ^ board[0][0];\n rowComplimentartyCount += complimentaryRow;\n misplacedRowCount += complimentaryRow ^ !(i & 1);\n // Count misplaced digit for first column.\n int complimentaryCol = board[i][0] ^ board[0][0];\n colComplimentartyCount += complimentaryCol;\n misplacedColCount += complimentaryCol ^ !(i & 1);\n }\n\n // When n is even, the move complimentary counts needs to be n/2 and the\n // move is easy to count.\n if (n % 2 == 0) {\n if (rowComplimentartyCount != n/2 || colComplimentartyCount != n/2) {\n return -1;\n }\n return (min(misplacedRowCount, n - misplacedRowCount) / 2 +\n min(misplacedColCount, n - misplacedColCount) / 2);\n }\n // cout << n << endl << rowComplimentartyCount << " " << colComplimentartyCount << "\\n"\n // << misplacedRowCount << " " << misplacedColCount << endl << endl;\n int move = 0;\n if (rowComplimentartyCount == n/2) {\n move += (n - misplacedRowCount) / 2;\n } else if (rowComplimentartyCount == n/2 + 1) {\n move += misplacedRowCount / 2;\n } else {\n return -1;\n }\n // cout << "row " << move;\n if (colComplimentartyCount == n/2) {\n move += (n - misplacedColCount) / 2;\n } else if (colComplimentartyCount == n/2 + 1) {\n move += misplacedColCount / 2;\n } else {\n return -1;\n }\n // cout << ". col " << move << endl;\n return move;\n }\n \n};\n```
0
0
[]
0
transform-to-chessboard
c++ sol
c-sol-by-66brother-xm67
\nclass Solution {\npublic:\n int movesToChessboard(vector<vector<int>>& grid) {\n int N=grid.size();\n //2 cases, N==odd || N==even\n /
66brother
NORMAL
2020-06-06T17:04:23.192365+00:00
2020-06-06T17:04:42.740137+00:00
291
false
```\nclass Solution {\npublic:\n int movesToChessboard(vector<vector<int>>& grid) {\n int N=grid.size();\n //2 cases, N==odd || N==even\n //Even:0101,1010 odd: 10101 01010\n for(int i=0;i<N;i++){//basic check\n int col=0,row=0; //one\n for(int j=0;j<N;j++){\n row+=grid[i][j];\n col+=grid[j][i];\n }\n if(abs(N-2*row)>1||abs(N-2*col)>1)return -1;\n }\n int res=-1;\n if(N%2==0){\n res=even(grid);\n }else{\n res=odd(grid);\n }\n return res;\n }\n int absv(int i){\n if(i<0)return -i;\n return i;\n }\n \n int even(vector<vector<int>>& grid){\n int N=grid.size();\n int sum=0;\n unordered_map<int,vector<int>>rmap;\n unordered_map<int,vector<int>>cmap;\n for(int i=0;i<grid.size();i++){\n int rbit=0,cbit=0;\n for(int j=0;j<grid.size();j++){\n rbit=rbit|(grid[i][j]<<j);\n cbit=cbit|(grid[j][i]<<j);\n }\n if(rmap.count(rbit)==0){\n vector<int>v;\n rmap[rbit]=v;\n }\n if(cmap.count(cbit)==0){\n vector<int>v;\n cmap[cbit]=v;\n }\n rmap[rbit].push_back(i);\n cmap[cbit].push_back(i);\n }\n if(cmap.size()!=2||rmap.size()!=2)return -1;\n if(rmap.begin()->second.size()!=N/2||cmap.begin()->second.size()!=N/2){\n return -1;\n }\n vector<int>r=rmap.begin()->second;\n vector<int>c=cmap.begin()->second;\n int rcount=0,ccount=0;\n for(int i:r){\n if(i%2==0)rcount++;\n }\n for(int i:c){\n if(i%2==0)ccount++;\n }\n sum=sum+min(rcount,N/2-rcount)+min(ccount,N/2-ccount);\n return sum;\n }\n \n \n int odd(vector<vector<int>>& grid){\n int N=grid.size();\n int sum=0;\n unordered_map<int,vector<int>>rmap;\n unordered_map<int,vector<int>>cmap;\n for(int i=0;i<grid.size();i++){\n int rbit=0,cbit=0;\n for(int j=0;j<grid.size();j++){\n rbit=rbit|(grid[i][j]<<j);\n cbit=cbit|(grid[j][i]<<j);\n }\n if(rmap.count(rbit)==0){\n vector<int>v;\n rmap[rbit]=v;\n }\n if(cmap.count(cbit)==0){\n vector<int>v;\n cmap[cbit]=v;\n }\n rmap[rbit].push_back(i);\n cmap[cbit].push_back(i);\n }\n if(cmap.size()!=2||rmap.size()!=2)return -1;\n if(absv(rmap.begin()->second.size()-N/2)>1||absv(cmap.begin()->second.size()-N/2)>1)return -1;\n \n vector<int>r=rmap.begin()->second;\n vector<int>c=cmap.begin()->second;\n int rcount=0,ccount=0;\n for(int i:r){\n if(i%2==0)rcount++;\n }\n for(int i:c){\n if(i%2==0)ccount++;\n }\n int rsize=r.size(),csize=c.size();\n if(rsize==N/2+1){//odd index\n sum+=(rsize-rcount);\n }else{//odd\n sum+=(rcount);\n }\n if(csize==N/2+1){//even\n sum+=(csize-ccount);\n }else{//odd\n sum+=(ccount);\n }\n return sum;\n }\n};\n\n\n\n\n\n\n```
0
0
[]
0
transform-to-chessboard
cpp ~0-4ms 9M bits manipulation
cpp-0-4ms-9m-bits-manipulation-by-ptache-1y7j
There are 2 properties which are invariant under transpositions of rows/columns:\n1. The set { c(i), i \u2208 {0,1,...,n-1} }, where c(i) is the count of 1s in
ptacher
NORMAL
2019-11-27T13:25:11.729721+00:00
2019-11-28T11:12:56.718392+00:00
322
false
There are 2 properties which are invariant under transpositions of rows/columns:\n1. The set { c(i), i \u2208 {0,1,...,n-1} }, where c(i) is the count of 1s in column *i*, as well as the counts of columns for each value *c* in the set: #{ i \u2208 {0,1,...,n-1} | c(i)=c }. Same for rows.\n2. each pair of columns are either equal or are mutual n-bits binary complements. Same for rows.\n\nFrom these observations we can construct a necessary and sufficient condition for any binary matrix to be transformable to a chessboard.\n\nI use this to check whether or not a solution exists, then compute the optimal solution.\n```\n\nclass Solution {\npublic:\n int movesToChessboard(vector<vector<int>>& board) {\n \n uint n = board.size();\n uint m = (1<<n)-1;\n \n\t\t// check if a solution exists.\n uint x(0),y(0);\n uint sum(0);uint sum1(0);\n for(int j=0; j<n; ++j){\n sum += board[0][j];\n sum1 += board[j][0];\n x ^= (board[0][j] << j);\n y ^= (board[j][0] << j);\n }\n if(sum!=n/2 && (n%2==0 ||sum!=n/2+1) ||\n sum1!=n/2 && (n%2==0 ||sum1!=n/2+1)){\n return -1;\n }\n \n for (int i = 1; i < n; ++i){\n uint t(0);\n for(int j=0; j<n; ++j){\n t ^= (board[i][j] << j);\n }\n if(x!=t && t!=m-x){ // every row must be equal to either x or x\'s n-bits binary complement.\n return -1;\n }\n }\n \n\t\t// From this point we know a solution exists: compute the optimal solution.\n uint p[2] = {m/3,m-m/3}; // {01010..., 10101...} on n bits.\n uint c[2] = {0,0}; // c[i]: 2 times the minimal # of transpositions from x to p[i]. \n \n for(int i=0; i<2; ++i){\n uint t = x^p[i];\n while(t){\n c[i] += t&1;\n t>>=1;\n }\n if(c[i]%2==1){ // invalid choice: cannot find permutation from x to p[i].\n c[i]=n;\n }\n }\n int count = std::min(c[0],c[1])/2; // minimal # columns transpositions.\n \n c[0]=0;c[1]=0;\n for(int i=0; i<2; ++i){\n uint t = y^p[i];\n while(t){\n c[i] += t&1;\n t>>=1;\n } \n if(c[i]%2==1){\n c[i]=n;\n }\n }\n \n count += std::min(c[0],c[1])/2; // adding minimal # rows transpositions.\n return count;\n \n }\n};\n\n```\nWe can also try these for counting bits instead of the naive way, for large *n* (cf. https://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel ): \n\n\n```\n\nclass Solution {\npublic:\n int movesToChessboard(vector<vector<int>>& board) {\n \n uint n = board.size();\n uint m = (1<<n)-1;\n \n uint x(0),y(0);\n uint sum(0);uint sum1(0);\n for(int j=0; j<n; ++j){\n sum += board[0][j];\n sum1 += board[j][0];\n x ^= (board[0][j] << j);\n y ^= (board[j][0] << j);\n }\n if(sum!=n/2 && (n%2==0 ||sum!=n/2+1) ||\n sum1!=n/2 && (n%2==0 ||sum1!=n/2+1)){\n return -1;\n }\n \n for (int i = 1; i < n; ++i){\n uint t(0);\n for(int j=0; j<n; ++j){\n t ^= (board[i][j] << j);\n }\n if(x!=t && t!=m-x){ // every row must be equal to either x or x\'s n-bits binary complement.\n return -1;\n }\n }\n \n uint p[2] = {m/3,m-m/3}; // {01010..., 10101...}\n uint c[2] = {0,0};\n \n for(int i=0; i<2; ++i){\n uint t = x^p[i];\n \n if(n<12){\n while(t){\n c[i] += t&1;\n t>>=1;\n }\n }\n else{\n t -= ((t >> 1) & 0x55555555); // count 1s by groups of two and store the results on 2 bits. 10-01=01, 11-01=10, 00-00=00, 01-00=01.\n t = (t & 0x33333333) + ((t >> 2) & 0x33333333);// count 1s by groups of 4 and store the results on 4 bits.\n c[i] = (((t + (t >> 4)) & 0x0F0F0F0F) * 0x01010101) >> 24;// count 1s by groups of 8 and store the results on 8 bits, sums the 4 groups and store the result in the most significant 8 bits.\n \n //c[i] = __builtin_popcount(t);\n }\n \n \n if(c[i]%2==1){ // invalid choice: cannot find permutation from x to p[i].\n c[i]=n;\n }\n }\n int count = std::min(c[0],c[1])/2; // minimal # columns transpositions.\n \n c[0]=0;c[1]=0;\n for(int i=0; i<2; ++i){\n uint32_t t = y^p[i];\n \n if(n<12){\n while(t){\n c[i] += t&1;\n t>>=1;\n } \n }\n else{\n t = t - ((t >> 1) & 0x55555555);\n t = (t & 0x33333333) + ((t >> 2) & 0x33333333);\n c[i] = (((t + (t >> 4)) & 0x0F0F0F0F) * 0x01010101) >> 24;\n \n \n /*t = t - ((t >> 1) & 0x55555555);\n t = (t & 0x33333333) + ((t >> 2) & 0x33333333);\n t = (t + (t >> 4)) & 0x0f0f0f0f;\n t = t + (t >> 8);\n t = t + (t >> 16);\n c[i] = t&0x3f;*/\n \n //c[i] = __builtin_popcount(t); \n\t\t\t}\n \n if(c[i]%2==1){\n c[i]=n;\n }\n }\n \n count += std::min(c[0],c[1])/2; // adding minimal # rows transpositions.\n return count;\n \n }\n};\n\n\n```\nWe can parallelize more the loops using 64 bits integers:\n```\n\n\nclass Solution {\npublic:\n int movesToChessboard(vector<vector<int>>& board) {\n \n uint n = board.size();\n uint m = (1<<n)-1;\n \n uint x(0),y(0);\n uint sum(0);uint sum1(0);\n for(int j=0; j<n; ++j){\n sum += board[0][j];\n sum1 += board[j][0];\n x ^= (board[0][j] << j);\n y ^= (board[j][0] << j);\n }\n if(sum!=n/2 && (n%2==0 ||sum!=n/2+1) ||\n sum1!=n/2 && (n%2==0 ||sum1!=n/2+1)){\n return -1;\n }\n \n for (int i = 1; i < n; ++i){\n uint t(0);\n for(int j=0; j<n; ++j){\n t ^= (board[i][j] << j);\n }\n if(x!=t && t!=m-x){ // every row must be equal to either x or x\'s n-bits binary complement.\n return -1;\n }\n }\n \n const uint p[2] = {m/3,m-m/3}; // {01010..., 10101...}\n uint c[2] = {0,0}; // c[i]: 2 times the minimal # of transpositions from x to p[i]. \n const uint shifts[2] = {24,32};\n int count(0);\n \n for(auto const& z: {x,y}){\n uint64_t t = z^p[0]+ (static_cast<uint64_t>(z^p[1])<<32);\n //printf("%#018" PRIx64 "\\n", t);\n\n t -= ((t >> 1) & 0x5555555555555555);\n t = (t & 0x3333333333333333) + ((t >> 2) & 0x3333333333333333);\n t = (((t + (t >> 4)) & 0x0F0F0F0F0F0F0F0F) * 0x01010101);\n \n for(int i=0; i<2; ++i){\n t >>= shifts[i];\n c[i] = t & 0xFF;\n if(c[i]%2==1){\n c[i]=m;\n }\n }\n count += std::min(c[0],c[1])/2;\n c[0]=0;c[1]=0;\n }\n \n return count;\n \n }\n};\n\n
0
0
[]
0
transform-to-chessboard
O(N) Scala solution
on-scala-solution-by-gorokhovsky-seqo
\nimport java.lang.Integer.bitCount\n\nobject Solution {\n def movesToChessboard(board: Array[Array[Int]]): Int = {\n val N = board.size\n val mask = (1<
gorokhovsky
NORMAL
2018-09-10T18:33:43.318794+00:00
2018-09-10T18:33:43.318847+00:00
372
false
```\nimport java.lang.Integer.bitCount\n\nobject Solution {\n def movesToChessboard(board: Array[Array[Int]]): Int = {\n val N = board.size\n val mask = (1<<N)-1\n val templOl = 0x55555555 & mask// 0101010101\n val templLo = ~templOl & mask;// 1010101010\n val rows = board.map(_.reduceLeft((a: Int, r: Int) => (a << 1) | r))// rows to int\n val count = bitCount(rows(0)) // 1\'s in the first row\n if((count<<1) == N || (count<<1) + 1 == N || (count<<1) - 1 == N){ \n rows.foldLeft(Map.empty[Int,Int])((m, r) => m + (r -> (m.getOrElse(r, 0)+1))).toSeq match { // values counter\n case Seq((r1:Int, q1: Int), (r2:Int, q2: Int)) if (r1^r2)==mask && q1>=N/2 && q2>=N/2 => { // if there are only 2 bit-inversive values with equal(+-1) counters\n val col = rows.foldRight(0)((r, c) => (c<<1)|(r&1)) //the last col to int\n (if((N&1)==0) // if N is even - we are free to choose any template\n Seq(templOl, templLo).map(templ => bitCount(templ ^ rows(0))).min +\n Seq(templOl, templLo).map(templ => bitCount(templ ^ col)).min\n else{ // if odd - we have to choose template respond to the value\n val tR = if(count > N/2) templOl else templLo // we have more 1\'s then 0\'s\n val aR = bitCount(tR ^ rows(0))\n val cR = bitCount(col)\n val tC = if(cR > N/2) templOl else templLo\n val aC = bitCount(tC ^ col)\n aR + aC\n }) / 2 // the swaps count = count of distinctive bits / 2 \n }\n case _ => -1\n }\n }\n else\n -1\n }\n}\n```
0
0
[]
0
transform-to-chessboard
\u301048ms Straightforward Python\u3011
u301048ms-straightforward-pythonu3011-by-wjwr
```\nfrom operator import xor\nclass Solution(object):\n def movesToChessboard(self, board):\n """\n :type board: List[List[int]]\n :rty
weidairpi
NORMAL
2018-02-11T20:55:58.233000+00:00
2018-02-11T20:55:58.233000+00:00
386
false
```\nfrom operator import xor\nclass Solution(object):\n def movesToChessboard(self, board):\n """\n :type board: List[List[int]]\n :rtype: int\n """\n m,n=len(board),len(board[0])\n\n # check single row\n def valid_s(r):\n n=len(r)\n rowSum=sum(r)\n if n%2: # odd number\n if rowSum not in [n/2,n/2+1]: return False\n else: # even number\n if rowSum!=n/2: return False\n return True\n\n # compare each adjacent row\n def valid(r1,r2):\n if r1==r2 or all(map(xor,r1,r2)): return True\n return False\n\n # check rows\n if not valid_s(board[0]): return -1\n for i in xrange(m-1):\n if not valid(board[i],board[i+1]):\n return -1\n\n # check columns\n boardT=map(list,zip(*board)) # transform for simplicity\n if not valid_s(boardT[0]): return -1\n for i in xrange(n-1):\n if not valid(boardT[i],boardT[i+1]):\n return -1\n\n # calculate swap\n def cal(r):\n n=len(r)\n rowsum=sum(r)\n if n%2: # odd number\n if rowsum>n/2: # 1 dominates\n r1=[1,0]*(n/2)+[1]\n else: # 0 dominates\n r1=[0,1]*(n/2)+[0]\n return sum(map(xor,r,r1))/2\n else: # even number\n r1=[1,0]*(n/2)\n r2=[0,1]*(n/2)\n swap1=sum(map(xor,r,r1))\n swap2=sum(map(xor,r,r2))\n return min(swap1,swap2)/2\n\n return cal(board[0])+cal(boardT[0])
0
0
[]
0
transform-to-chessboard
My Java Solution
my-java-solution-by-xuhuiwang-52kb
Only use two arrays to represent rows and columns, since they are independent, only rearrange them s.t. \n\nfor i = 1 : (N - 1)\n (states[i] & states[i +
xuhuiwang
NORMAL
2018-02-11T19:19:22.077000+00:00
2018-02-11T19:19:22.077000+00:00
569
false
Only use two arrays to represent rows and columns, since they are independent, only rearrange them s.t. \n\nfor i = 1 : (N - 1)\n (states[i] & states[i + 1]) == 0;\n```\npublic class Solution {\n// process independently for rows and cols, time O(N), space O(N)\n\tint N;\n\tint solve(int[] states) {\n\t\tint bm = states[0];\n\t\tint cnt1 = 0, cnt2 = 0;\n\t\tfor (int i = 0; i < states.length; ++i) {\n\t\t\tif (states[i] == bm)\n\t\t\t\tcnt1++;\n\t\t\telse if ((states[i] & bm) == 0)\n\t\t\t\tcnt2++;\n\t\t\telse\n\t\t\t\treturn -1;\n\t\t}\n\t\tif (Math.abs(cnt1 - cnt2) > 1)\n\t\t\treturn -1;\n\t\tif (cnt2 > cnt1) {\n\t\t\tbm = ((1 << N) - 1) & (~bm);\n\t\t}\n\t\tint mismatches[] = new int[2];\n\t\tfor (int i = 0; i < N; i++) {\n\t\t\tif (i % 2 == 0 && states[i] != bm)\n\t\t\t\tmismatches[0]++;\n\t\t\telse if (i % 2 == 1 && states[i] != bm)\n\t\t\t\tmismatches[1]++;\n\t\t}\n\t\treturn cnt1 == cnt2 ? Math.min(mismatches[0], mismatches[1]) : mismatches[0];\n\t}\n\tpublic int movesToChessboard(int[][] board) {\n\t\t// first check if it's possible\n\t\tN = board.length;\n\t\tint rows[] = new int[N], cols[] = new int[N];\n\t\tfor (int i = 0; i < N; ++i) {\n\t\t\tfor (int j = 0; j < N; ++j) {\n\t\t\t\tint bit = board[i][j];\n\t\t\t\trows[i] |= bit << j;\n\t\t\t\tcols[j] |= bit << i;\n\t\t\t}\n\t\t}\n\t\tint res1 = solve(rows), res2 = solve(cols);\n\t\tif (res1 < 0 || res2 < 0)\n\t\t\treturn -1;\n\t\treturn res1 + res2;\n\t}\n}\n```
0
1
[]
0
maximum-xor-after-operations
Thought process explained || Basic intuition to optimise
thought-process-explained-basic-intuitio-imjf
So during the contest, Initialy I thought about using tries(a most famous based on xor) but here doesn\'t make sense. So let\'s understand the problem first :\n
faltu_admi
NORMAL
2022-06-25T16:24:06.612148+00:00
2022-06-26T02:28:09.233701+00:00
4,386
false
So during the contest, Initialy I thought about using tries(a most famous based on xor) but here doesn\'t make sense. So let\'s understand the problem first :\n\nSo what we\'re going to do in each step :\n1. pick any i-th element let\'s say y\n2. pick any x\n3. make x^y\n4. and put (x&y) at i-th position \n\nSo let\'s know more about & :\n* x&y will never add extra set bit in the result. Suppose x has n bit than after doing & operation on x you can\'t get n+1 bits ***but we can reduct the set bit from n to any number [0...n]***\n* Ok! So what\'s the use of above things in this question :\n\n**Since you\'re main aim to get maximum xor of elements**\n\nSo suppose after doing xor [3,2,4,6] we\'re getting 1\n\n3 => 0 0 1 1\n2 => 0 0 1 0\n4 => 0 1 0 0\n6 => 0 1 1 0\n---------\nxor => 0 0 1 1\n---------\nok so what thinks are reducing the xor? i.e. number of bit\'s position which comes even times from all elements?\nRight? So what if I reduce that bit and make it unset using &(yeah we\'re now using & to reduce that bit) so that it\'ll contribute in the result.\n\nSo finally :\n* find the frequency of all set bit from array :\n* if bit\'s frequency is 0 than you can\'t do any things because that bit\'s are absent and there is not way to add using &.\n\n```\nclass Solution {\npublic:\n int maximumXOR(vector<int>& nums) {\n vector<int> bits(32,0);\n for(int &i:nums) {\n for(int j=31;j>=0;j--) {\n if((i>>j)&1) {\n bits[j]++;\n }\n }\n }\n int res = 0;\n for(int i=0;i<32;i++) {\n if(bits[i]) {\n res = res | 1<<i;\n }\n }\n return res;\n }\n};\n```\n\nBut after contest and reading some discuss I found that I am just including all set bits no matter it comes even times and odd times, I am including. How?\nI know if frequency comes even times than we can reduce it by & and make it odd so that it\'ll be consider into xor.\nSo let\'s refactor the code.\n```\nclass Solution {\npublic:\n int maximumXOR(vector<int>& nums) {\n int res = 0;\n for(int &i:nums) res |= i;\n return res;\n }\n};\n```\n***Please upvote if you it help you.***\n***Thanks for reading.***\n***Happy Coding!***
103
0
[]
19
maximum-xor-after-operations
[Java/C++/Python] 1-Line Solution, OR of All Elements
javacpython-1-line-solution-or-of-all-el-ev9m
Explanation\nThe maximum possible result is res = A[0] || A[1] || A[2] ... and it\'s realisiable.\n\n# Prove\nNow we approve it\'s realisiable.\nAssume result i
lee215
NORMAL
2022-06-25T16:02:18.333723+00:00
2022-06-25T16:16:26.558999+00:00
8,708
false
# **Explanation**\nThe maximum possible result is `res = A[0] || A[1] || A[2] ... ` and it\'s realisiable.\n\n# **Prove**\nNow we approve it\'s realisiable.\nAssume result is `best = XOR(A[i])` and `best < res` above.\nThere is at least one bit difference between `best` and `res`, assume it\'s `x = 1 << k`.\n\nWe can find at least a `A[i]` that `A[i] & x = x`.\n\nwe apply `x` on `A[i]`, `A[i]` is updated to `A[i] & (A[i] ^ x) = A[i] ^ x`.\nWe had `best = XOR(A[i])` as said above,\nnow we have `best2 = XOR(A[i]) ^ x`,\nso we get a better `best2 > best`, where we prove by contradiction.\n<br>\n\n# **Complexity**\nTime `O(n)`\nSpace `O(1)`\n<br>\n\n**Java**\n```java\n public int maximumXOR(int[] nums) {\n int res = 0;\n for (int a: nums)\n res |= a;\n return res;\n }\n```\n**C++**\n```cpp\n int maximumXOR(vector<int>& nums) {\n int res = 0;\n for (int a : nums)\n res |= a;\n return res;\n }\n```\n**C++**\n```cpp\n int maximumXOR(vector<int>& nums) {\n return reduce(nums.begin(), nums.end(), 0, bit_or());\n }\n```\n**Python**\n```py\n def maximumXOR(self, nums):\n return reduce(ior, nums)\n```\n
98
0
['C', 'Python', 'Java']
24
maximum-xor-after-operations
Simplest O(N) solution [WITH EXPLANATION]
simplest-on-solution-with-explanation-by-3209
nums[i] AND (nums[i] XOR x) where x is ANY integer, basically means you can decrease that element into any number but can\'t increase it.\nReread the above stat
stardust23
NORMAL
2022-06-25T16:03:56.369779+00:00
2022-06-25T18:44:57.756539+00:00
2,550
false
`nums[i] AND (nums[i] XOR x)` where *x is ANY integer*, basically means you can decrease that element into any number but can\'t increase it.\n*Reread the above statement. That\'s the key to solving the problem!*\n* AND operation can only allow a 1 to be 0 but not a 0 to become 1.\n* XOR of elements is maximised by getting distinct combination of a 0 and 1.\n* So bascially in the answer you get a 0 where all numbers in array have the bit place values 0, as there is no way to make it into a 1 .\n* Rest can be made into a 1, as atleast one number in the array has a bit place value 1.\n* And obviously you can check if atleast one of the element has a place value 1 by doing a cumulative OR.\n\nSketch out the given TCs in binary bits and do a dry run, I bet you will understand this completely! \nComment if you have any doubts.\n```\nclass Solution {\n public int maximumXOR(int[] nums) {\n int res=0;\n for(int i=0; i<nums.length; i++) res |= nums[i];\n return res;\n }\n}\n```\nDo upvote if this helps and what was your approach?
66
0
[]
8
maximum-xor-after-operations
3 lines of CODE with EXPLANATION !! | C + +
3-lines-of-code-with-explanation-c-by-me-xly7
nums[i] & (nums[i]^x) cannot be more than nums[i] because we are taking AND.\nSo this implies that for any number we can set the bits OFF (only the bits which a
megamind_
NORMAL
2022-06-25T16:01:45.512202+00:00
2022-06-30T11:10:15.373346+00:00
2,304
false
`nums[i] & (nums[i]^x)` cannot be more than `nums[i]` because we are taking **AND.**\nSo this implies that for any number we can set the bits `OFF` ***(only the bits which are already `ON` (1))*** .\n**BUT** we cannot set any bit` ON `if it were `OFF `already .\n\nTherefore , we can say that we will set bits ON and OFF for all numbers in such a way that `XOR` of all the numbers is equal to `OR` of all numbers. Because if a bit is not on in any of the numbers ,there is no way we can get it on in our ans.\n\n```\nint y = 0;\nfor(int x :nums)y = y|x;\nreturn y;\n```
31
0
[]
2
maximum-xor-after-operations
One Liner
one-liner-by-votrubac-3kh8
An operation can remove a bit, but cannot add one.\n \nSo, the maximum result would contain bits from all elements in the input array.\n\nPython 3\npython\nc
votrubac
NORMAL
2022-06-25T16:00:52.601789+00:00
2023-09-11T18:46:08.969017+00:00
2,079
false
An operation can remove a bit, but cannot add one.\n \nSo, the maximum result would contain bits from all elements in the input array.\n\n**Python 3**\n```python\nclass Solution:\n def maximumXOR(self, nums: List[int]) -> int:\n return reduce(or_, nums)\n```\n\n**C++**\n```cpp\nint maximumXOR(vector<int>& nums) {\n return accumulate(begin(nums), end(nums), 0, bit_or<int>());\n}\n```
29
3
['C']
7
maximum-xor-after-operations
✔️ EXPLAiNED || C++ || PYTHON || JAVA
explained-c-python-java-by-karan_8082-elon
UPVOTE IF HELPFuul\n\nEvery once in a while try using paper-pen. -> useful for finding pattern, cant just think about these.\n\nUpon converting to binary, there
karan_8082
NORMAL
2022-06-30T09:19:22.050745+00:00
2022-06-30T09:19:22.050771+00:00
1,104
false
**UPVOTE IF HELPFuul**\n\nEvery once in a while try using paper-pen. -> useful for finding pattern, cant just think about these.\n\nUpon converting to binary, there will be a pattern.\nResult is **OR of all elements** .\n\n**OBSERvATION=>** ```nums[i] AND (nums[i] XOR x)``` \nWith this operation, we can modify each element and adjust it to provide max XOR.\n\nBut with **AND** operation applied to ```nums[i]``` , it can be positively said that none of bits of nums[i] can be converted from **0** to **1**. \nBut the converse could be done, Bit can be changed from 1 -> 0.\n\nHence if all **i**th bits for all nums are```0```, XOR for that bit will also be zero. ```[ 0 XOR 0 = 1 ]```\nBut if atleast single bit at **i**th position is ```1```, we can have a combination of other bits to give ```XOR =1``` for that bit\n\n\n```\nnums = [ 3, 2, 4, 6 ] nums = [ 9, 64, 25, 19 ]\n\n3 -> 0 | 1 | 1 9 -> 0 | 0 | 0 | 1 | 0 | 0 | 1\n2 -> 0 | 1 | 0 64 -> 1 | 0 | 0 | 0 | 0 | 0 | 0\n4 -> 1 | 0 | 0 25 -> 0 | 0 | 1 | 1 | 0 | 0 | 1\n6 -> 1 | 1 | 0 19 -> 0 | 0 | 1 | 0 | 0 | 1 | 1\n ---------- -------------------------\nres -> 1 | 1 | 1 res -> 1 | 0 | 1 | 1 | 0 | 1 | 1\nres = 7 res = 91\n\n\nnums = [ 1, 2, 3, 9, 2 ]\n\n1 -> 0 | 0 | 0 | 1\n2 -> 0 | 0 | 1 | 0\n3 -> 0 | 0 | 1 | 1\n9 -> 1 | 0 | 0 | 1\n2 -> 0 | 0 | 1 | 0\n -------------\nres -> 1 | 0 | 1 | 1\nres = 11\n```\n\nA few Dry runs to show the result is **OR** operation applied on the array.\n\n**C++**\n```\nclass Solution {\npublic:\n int maximumXOR(vector<int>& nums) {\n int res = 0;\n for (int i=0; i<nums.size() ; i++){\n res |= nums[i];\n }\n return res;\n }\n};\n```\n**PYTHON**\n```\nclass Solution:\n def maximumXOR(self, nums: List[int]) -> int:\n res=0\n for i in nums:\n res |= i\n return res\n```\n**JAVA**\n```\nclass Solution {\n public int maximumXOR(int[] nums) {\n int res = 0;\n for (int i=0; i<nums.length; i++){\n res |= nums[i];\n }\n return res;\n }\n}\n```\n![image](https://assets.leetcode.com/users/images/a3c40fd5-21ac-4ad0-9fb1-491bead205ae_1656579946.7431452.jpeg)\n
21
2
['Bit Manipulation', 'C', 'Python', 'Java']
3
maximum-xor-after-operations
Clear and Lucid Explanation along with Dry Runs | O(n) |
clear-and-lucid-explanation-along-with-d-o8k4
Intuition\n\nWe can\'t increase nums[i] since we use AND operator with it because AND operator can\'t make \'0\' to \'1\' but it can make \'1\' to \'0\'. Did yo
KanishYathraRaj
NORMAL
2024-01-01T09:35:00.938215+00:00
2024-01-01T09:35:00.938253+00:00
334
false
# Intuition\n\nWe can\'t increase nums[i] since we use AND operator with it because AND operator can\'t make \'0\' to \'1\' but it can make \'1\' to \'0\'. Did you find the hint behind it? if not , don\'t worry I am here to help you!\n\nlets take first example,\n\n`nums = [ 3 , 2 , 4 , 6 ] `\n\nEvery integers has 32 bits\n```\n3 -> 0 ........ 0 0 1 1\n2 -> 0 ........ 0 0 1 0\n4 -> 0 ........ 0 1 0 0\n6 -> 0 ........ 0 1 1 0\n```\nYou can see that after 3rd bit (right to left) in every elemet , there is no \'1\' in the bits. \n\nSince we need to find the maximum xor value of all element , the maximum "possible" answer can be , "1 1 1" after some required operations( don\'t worry about the operation we need to do)\n\n(because after 3rd bit , all bits in every elemet is \'0\' since we use AND operator to change the value of nums[i] , it can only change bit \'1\' to \'0\' , not \'0\' to \'1\' )\n\n`0 ........ 0 1 1 1 which is 7 (Maximum Possible Answer)`\n\nSo we need to some how try to reach the "Maximum Possible Answer".\n\nLets take a look at the XOR property , it return 1 when bits differ and it return 0 when same bits encounter.\n\nif I take the XOR for the above example without nessary operations we get,\n\n```\n3 -> 0 1 1\n2 -> 0 1 0\n4 -> 1 0 0\n6 -> 1 1 0\n ---------\n 0 1 1 -> xor value\n 2 3 1 -> no of set bits(\'1\') in each coloumn.\n```\n\nYou can see that when there is ODD no of set bits it gives \'1\' in xor\n\nwhen there is EVEN no of set bits it gives \'0\' in xor beause same bits in xor return \'0\' so all odd bits cancel out each other.\n\nSo if we avoid Even no of set bits , then we can reach the Maximum Possible Answer.\n\nwhy not try convert "even no of set bits into odd no of set bits"\nAs we discussed earlier we can\'t convert "0" to "1" so we are going to convert the existing "1" bit to "0" bit hence no of bits in that column becomes ODD. \n\nIf you don\'t understand try read it once more or see the dry run below.\n\n```\nfrom the example we have taken , we can convert\n\n4 -> 1 0 0 to 0 0 0 which is 0\nor\n6 -> 1 1 0 to 0 1 0 which is 2\n\n-----------\n3 -> 0 1 1 \n2 -> 0 1 0\n0 -> 0 0 0 \n6 -> 1 1 0\n -------\n 1 1 1\n------------\n\nor\n\n------------\n3 -> 0 1 1\n2 -> 0 1 0\n4 -> 1 0 0\n2 -> 0 1 0\n -------\n 1 1 1\n------------\n\nso reducing even set bits by one gives odd bits\nwhich can maximize the xor value.\n```\n\nLets take the 2nd example.\n\n```\nnums = [ 1 , 2 , 3 , 9 , 2 ]\n\n1 -> 0 0 0 1\n2 -> 0 0 1 0\n3 -> 0 0 1 1\n9 -> 1 0 0 1\n-------------\n 1 0 2 3 -> no of set bits in each column.\n-------------\n\nSo the Maximum Possible Answer can be 1 1 1 1 which is 15\n\nWe can see that 2nd and 3rd column have even no of set bits \nas 2 and 0 \n\nwe can reduce 2 to 1 \nbut we can\'t reduce 0 to -1\n\nbecause there is no existing \'1\' bit in that column \nso we can\'t do the operation \'1\' to \'0\'.\n(as there there is no set bits)\n\nHence the Answer is 1 0 1 1 which is 11.\n\n\n1 -> 0 0 0 1\n2 -> 0 0 1 0\n1 -> 0 0 0 1 3 (0 0 1 1) converted to 1 (0 0 0 1)\n9 -> 1 0 0 1\n-------------\n 1 0 1 1\n 1 0 1 3 -> no of set bits.\n-------------\n\nor\n\n1 -> 0 0 0 1\n0 -> 0 0 0 0 2 (0 0 1 0) converted to 0 (0 0 0 0)\n3 -> 0 0 1 1 \n9 -> 1 0 0 1\n-------------\n 1 0 1 1\n 1 0 1 3 -> no of set bits.\n-------------\n\nAnswer is 1 0 1 1 which 11.\n```\n# Approach\n \nwhy not try cumulative OR operatoion on the every element.\n\nso if set bit exist in any of the column it returns "1" and\nif set bit not exist in the their coumn it return "0" \n\n```\n3 -> 0 1 1\n2 -> 0 1 0\n4 -> 1 0 0\n6 -> 1 1 0\n ---------\n 1 1 1 -> OR value\n ---------\n\n1 -> 0 0 0 1\n2 -> 0 0 1 0\n3 -> 0 0 1 1\n9 -> 1 0 0 1\n ---------\n 1 0 1 1 -> OR value\n ---------\n\nHope you all understood my Explanation\n```\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int maximumXOR(vector<int>& nums) {\n\n int ans = 0 ;\n\n for(int x : nums) ans |= x ;\n\n return ans;\n }\n};\n```\n\n# PLEASE UP VOTE!\n
18
0
['C++']
3
maximum-xor-after-operations
Python3 || 1 line, bit operations, w/ explanation || T/S: 98% / 80%
python3-1-line-bit-operations-w-explanat-egsl
Points to consider:\n\n The problem calls for choosing an integer x, selecting an element n of the list, applying the compound operator op(n,x) = (x&n)^n, and
Spaulding_
NORMAL
2022-08-01T20:41:28.901062+00:00
2024-06-13T04:46:48.741495+00:00
669
false
Points to consider:\n\n* The problem calls for choosing an integer x, selecting an element n of the list, applying the compound operator op(n,x) = (x&n)^n, and taking the bit-intersection of the modified set. Because of the associative and commutative properties of the XOR operator, it does not matter which n we choose in nums. \n\n* Below is the truth table for op(num,x)\n![image](https://assets.leetcode.com/users/images/3d54169a-85a0-466e-829c-08d2ff436128_1659383847.6181347.png)\n The end result is that the op leaves num\'s bit unchanged unless x and num are both 1, in which case that bit of num becomes 0. It follows that by choosing x wisely, we can erase any bits in any of the elements of nums. \n\n* For example:\n _ _ _ _ _ _ _ _ _ 3 = 0x4 + 1x2 + 1x1 = 011 (base2)\n\t\t\t _ _ _ _ _ _ _ _ _ 2 = 0x4 + 1x2 + 0x1 = 010 (base2)\n\t\t\t _ _ _ _ _ _ _ _ _ 4 = 1x4 + 0x2 + 0x1 = 100 (base2)\n _ _ _ _ _ _ _ _ _ 6 = 1x4 + 1x2 + 0x1 = 110 (base2)\n\t\t\t \n_ _ _ _ _ _ XOR (3,2,4,6)\t= 0x4 + 1x2 + 1x1 = 011 (base2) = 3\n\nIn the base 2 representation of the XOR, the 4s digit is 0 because the bit-XOR of the 4s digits in nums,\nXOR(0,0,1,1) = 0 because there\'s an even number of 1s. And:\n 2s digits: XOR(1,1,0,1) => 2s digit of XOR(nums) = 1 because #of 1s is odd\n 1s digits: XOR(1,0,0,0) => 1s digit of XOR(nums) = 1 because #of 1s is odd\n \n* After applying Op(4,6) = 2 to nums[3]:\n _ _ _ _ _ _ _ _ _ 3 = 0x4 + 1x2 + 1x1 = 011 (base2)\n\t\t\t _ _ _ _ _ _ _ _ _ 2 = 0x4 + 1x2 + 0x1 = 010 (base2)\n\t\t\t _ _ _ _ _ _ _ _ _ 4 = 1x4 + 0x2 + 0x1 = 100 (base2)\n _ _ _ _ _ _ _ _ _ 2 = 0x4 + 1x2 + 0x1 = 110 (base2)\n\t\t\t \n_ _ _ _ _ XOR (3,2,4,2)\t= 1x4 + 1x2 + 1x1 = 111 (base2) = 7\n\n* The bottom line: choosing a value of x that will reduce columns with even 1s by one will maximize the value of XOR(nums). The only columns that cannot be changed are those with no 1s initially. Thus we can solve the problem by determining OR(nums).\n\nThree short solutions:\n \n ```\n class Solution:\n def maximumXOR(self, nums: List[int]) -> int:\n return reduce(lambda x,y: x|y, nums)\n\nclass Solution:\n def maximumXOR(self, nums: List[int]) -> int:\n return reduce(or_, nums)\n\nclass Solution:\n def maximumXOR(self, nums: List[int]) -> int:\n \n ans = 0\n for n in nums:\n ans |= n \n return ans\n```\n\n[https://leetcode.com/problems/maximum-xor-after-operations/submissions/1286630818/](https://leetcode.com/problems/maximum-xor-after-operations/submissions/1286630818/)\n\nI could be wrong, but I think that time complexity is *O*(*N*) and space complexity is *O*(1), in which *N* ~ `len(nums)`.\n\n
13
1
['Python', 'Python3']
1
maximum-xor-after-operations
[C++] | BIT MANIPULATION | Time-O(NlogN) | Explaination Added
c-bit-manipulation-time-onlogn-explainat-np7w
Concept- If we XOR odd number of ones then we\nget 1 and if we XOR even number of ones then\nwe will get 0.\n1^1^1^.....^1(odd number of times)=1\n1^1^1^.....^1
niks07
NORMAL
2022-06-25T16:04:57.849422+00:00
2022-06-25T16:26:53.199151+00:00
937
false
**Concept- If we XOR odd number of ones then we\nget 1 and if we XOR even number of ones then\nwe will get 0.**\n**1^1^1^.....^1(odd number of times)=1\n1^1^1^.....^1(even number of times)=0**\n**Steps-**\n* Each number has bits when we convert it into\nbinary. Eg. 4 has 3 bits which are 100.\nSo First we will find the maximum number of bits\nfrom numbers present in nums.\n* Count zeroes and ones at each bit position.\n* If bits are the number of bits then we iterate at each bit\nposition and check if it ones are odd at this \nposition, if it is then we will store one \nand if it is not then is ones are not zero then\nwe can get 1 as we can convert a 1 to 0 not 0\nto 1 because of AND opertion.\n* Calculate the answer.\n\n\n**Better Understaing**\n**Eg.\nnums:[3,2,4,6]\nWRITING BITS FOR EACH NUMBER-**\n**3-011\n2-010\n4-100\n6-110**\n\nTHERE ARE 3 BITS LETS WRITE THE NUMBER OF ONES AND ZEROES FOR EACH POSITION.\nOnes-[2,3,1]\nZeroes-[2,1,3]\nAt index 2, there are 1 ones which is odd so we can get one at this bit position. Similarly for \nindex 1, ones are odd, but for index 0 ones are even which is 2. In what condition we can get \none at this bits position? We have to make a 1 to 0 or a zero to 1 to convert ones to odd.\nIf we convert a 0 to 1 it will not work because when we AND with the same number it will \nagain yield a zero at this position. So we will convert a 1 to 0 so make ones odd. It is only \npossible when count of ones are not zero.\nI hope you got it!!\n\n\n\n```\nclass Solution {\npublic:\n int maximumXOR(vector<int>& nums) {\n int n=nums.size();\n sort(nums.begin(),nums.end());\n int num=nums[n-1]; //maximum number of bits will be present in the largest number\n int bits=0; //counting the bits for the maximum number of bits among all the numbers\n while(num>0){\n num=num>>1;\n bits++;\n }\n vector<int> ones(bits,0), zeroes(bits,0); //ones will store number of ones at this bit position in every number\n for(int i=0;i<n;i++){\n num=nums[i];\n int idx=0;\n while(num>0){\n int bit=num&1;//checking current bit is 1 or 0\n if(bit){\n ones[idx]++;\n }else{\n zeroes[idx]++;\n }\n num=num>>1;\n idx++;\n }\n \n \n //if idx is less then maximum number of bits then increasing the zeroes for those position\n while(idx<bits){\n zeroes[idx]++;\n idx++;\n }\n }\n \n \n //If number of ones is odd then we can get 1 bit at this position or if one is even then count of ones at this position must not be zero otherwise this position we will put 0\n vector<int> v;\n for(int i=0;i<bits;i++){\n if(ones[i]%2!=0){\n v.push_back(1);\n }else if(ones[i]>0){\n v.push_back(1);\n }else{\n v.push_back(0);\n }\n }\n \n //Calculating the final answer\n int res=0;\n for(int i=0;i<bits;i++){\n res=res+pow(2,i)*v[i];\n }\n\n \n return res;\n }\n};\n\n\n```
11
0
['Bit Manipulation', 'C']
2
maximum-xor-after-operations
C++ | Simple Or Operation
c-simple-or-operation-by-slow_code-l6t7
\nlet take some example\nsuppose arr = {1,2,3,9}\nnow we will find have bit of all these\n1 -> 0001\n2 -> 0010\n3 -> 0011\n9 -> 1001\nnow to get maximum answer
Slow_code
NORMAL
2022-06-25T16:01:24.777434+00:00
2022-06-25T16:25:34.142028+00:00
829
false
```\nlet take some example\nsuppose arr = {1,2,3,9}\nnow we will find have bit of all these\n1 -> 0001\n2 -> 0010\n3 -> 0011\n9 -> 1001\nnow to get maximum answer we should have as many as 1 bits possible in \nanswer so for that we need to use OR operation, \nso that we get maximum of 1 bits in every place of answer\n\n1011 as answer which is equal to 11.\n```\n\t\n\tclass Solution {\n\tpublic:\n\t\tint maximumXOR(vector<int>& nums) {\n\t\t\tint res = 0;\n\t\t\tfor(auto x:nums) res|=x;\n\t\t\treturn res;\n\t\t}\n\t};
10
2
[]
3
maximum-xor-after-operations
C++ Beginner Friendly Explanation
c-beginner-friendly-explanation-by-anis2-1537
Approach:\n\n nums[i] AND (nums[i] XOR x)\n with the above operation we can modify any nums[i] right\n as we are taking AND, we can say that none of the bits of
anis23
NORMAL
2022-08-03T10:35:50.844315+00:00
2022-08-03T10:36:59.340462+00:00
670
false
**Approach:**\n\n* ```nums[i] AND (nums[i] XOR x)```\n* with the above operation we can modify any nums[i] right\n* as we are taking ```AND```, we can say that none of the bits of nums[i] can be converted from 0 to 1 \n* on the other hand, we can convert a bit from 1 to 0\n\t* as we can choose x such that nums[i]^x = 0 at that ith bit then its & with nums[i] will result in 0\n\t* 1&0 = 0\n* now to maximize the final answer we want as many 1 as possible in the final value\n* So, if there exist atleast a single bit at ith position whose value is 1, we can have a combination of other bits to give XOR =1 for that bit\n\t* how?\n\t\t* we can make all the other elements ith bit = 0 then the xor of all the elements at this ith bit will be\n\t\t* 1^0^0...^0 = 1\n* So, in conclusion if the ith bit of any element is 1 then the ith bit of our final answer will be 1 too and if all the elements has their ith bit =0 then the ith bit of our answer will be 0\n* you can clearly guess from the above statement that we just want the OR of all the elements\n\n**Code:**\n\n```\nclass Solution\n{\npublic:\n int maximumXOR(vector<int> &nums)\n {\n int n = nums.size();\n int ans = 0;\n for (int i = 0; i < n; i++)\n ans |= nums[i];\n return ans;\n }\n};\n```
9
0
['Math', 'Bit Manipulation', 'C', 'C++']
2
maximum-xor-after-operations
[Java/Python 3] Bit manipulations w/ brief explanation and analysis.
javapython-3-bit-manipulations-w-brief-e-pk74
Key observation: nums[i] & (nums[i] ^ x) <= nums[i]. Therefoe, we can only set off the 1 bits of each number if necessary, in order to make greatest of the xor
rock
NORMAL
2022-06-25T16:07:38.440914+00:00
2022-06-25T17:52:19.226541+00:00
1,224
false
**Key observation: `nums[i] & (nums[i] ^ x) <= nums[i]`**. Therefoe, we can only set off the `1` bits of each number if necessary, in order to make greatest of the xor all numbers after operations.\n\nSince 2<sup>27</sup> > 10<sup>8</sup>, we can traverse the left-most `28` bits to count how many `1`\'s on each bits.\n1. Count each set bit (`1` bit) on the `0th`, `1st`, `2nd`, ..., `27th` bit; if greater than `0`, we can make it odd so that the xor of all elements on that bit will be `1`;\n2. For each bit, add it (use `|=`) to the result.\n\n```java\n public int maximumXOR(int[] nums) {\n int[] cnt = new int[28];\n int maxXor = 0;\n for (int i = 0; i < 28; ++i) {\n for (int num : nums) {\n if (((num >> i) & 1) != 0) {\n ++cnt[i];\n }\n }\n if (cnt[i] > 0) {\n maxXor |= 1 << i; \n }\n }\n return maxXor;\n }\n```\n\n```python\n def maximumXOR(self, nums: List[int]) -> int:\n cnt = [0] * 28\n maxXor = 0 \n for i in range(28):\n for num in nums:\n if (num & (1 << i)) > 0:\n cnt[i] += 1\n if cnt[i] > 0: \n maxXor |= (1 << i)\n return maxXor\n```\n\n-----\n\nBased from the above explanation, as long as there are at least `1` set bit on a certain bit (say `ith` bit) , we can set that bit (`ith` bit) `1`. Therefore, that is bitwise or `|` operation. Therefore, we can simplify the above codes as follows:\n\n```java\n public int maximumXOR(int[] nums) {\n return IntStream.of(nums).reduce(0, (a, b) -> a | b);\n }\n```\n```python\n def maximumXOR(self, nums: List[int]) -> int:\n return functools.reduce(operator.ior, nums, 0)\n```\n\n**Analysis:**\n\nTime: `O(n)`, space: `O(1)`, where `n = nums.length`.
8
0
['Bit Manipulation', 'Java', 'Python3']
3
maximum-xor-after-operations
C++ | Simple Solution | O(N) Solution | Easy to understand with Comments | Bit Manipulation
c-simple-solution-on-solution-easy-to-un-ll5h
\nclass Solution {\npublic:\n int maximumXOR(vector<int>& nums) {\n int n = nums.size();\n int ans=0;\n // for every bit check the cnt o
gargp1065
NORMAL
2022-06-26T05:47:41.665336+00:00
2022-06-26T05:47:41.665384+00:00
139
false
```\nclass Solution {\npublic:\n int maximumXOR(vector<int>& nums) {\n int n = nums.size();\n int ans=0;\n // for every bit check the cnt of the times 1 appears in the array. If the cnt is great than 1, then we can consider that bit in our ans.\n // this is becuase the given op can unset any bit of the number in nums[i].\n //so if the cntOne is odd we dont have to change that bit in any of the nums[i] because the xor of odd number of one is 1.\n // but if the cntOne if even we must unset any one nums[i] bit in the array and consider that bit in our answer.\n // So it can be conculded that even if a single 1 occurs in that position in any nums[i], we can consider that bit in our ans.\n for(int i=31;i>=0;i--) {\n int cntOne = 0;\n for(int j=0;j<n;j++) {\n cntOne += ((nums[j]>>i)&1);\n }\n if(cntOne == 0)\n continue;\n ans += (1<<i);\n }\n return ans;\n }\n}; \n```
5
0
['Bit Manipulation']
0
maximum-xor-after-operations
[C++] Only Bit Count
c-only-bit-count-by-badhansen-u24m
Approach:\n1. Count number of bits in each positions\n2. Now if the position bit count is zero then we can\'t take this bit otherwise we can take this bit in ma
badhansen
NORMAL
2022-06-25T16:08:19.436454+00:00
2022-06-25T16:08:28.910061+00:00
772
false
**Approach:**\n1. Count number of bits in each positions\n2. Now if the position bit count is zero then we can\'t take this bit otherwise we can take this bit in mask.\n\nNow return the number \n\n**Time:** `O(N), N = Length of nums`\n**Space:** `O(32) ~ O(1)`\n```\nclass Solution {\npublic:\n int maximumXOR(vector<int>& nums) {\n vector<int> bits(32, 0);\n int mask = 0;\n for(auto &num : nums){\n for(int i = 0; i < 31; i++){\n if(num & (1 << i)) bits[i]++;\n }\n }\n for(int i = 0; i < 31; i++){\n if(bits[i] == 0) continue; \n else{\n mask |= (1 << i);\n }\n }\n return mask;\n }\n};\n```
5
0
['C', 'C++']
2
maximum-xor-after-operations
100%FASTER || 3LINE || BITWISE-OR-ALL-ELEMENTS||C++||SHORT & SWEET CODE
100faster-3line-bitwise-or-all-elementsc-e441
\nint maximumXOR(vector<int>& nums) {\n int ans = 0;\n for(auto &i: nums)ans |= i;\n return ans;\n }\n
yash___sharma_
NORMAL
2023-03-28T12:17:09.276906+00:00
2023-03-28T12:17:09.276941+00:00
406
false
````\nint maximumXOR(vector<int>& nums) {\n int ans = 0;\n for(auto &i: nums)ans |= i;\n return ans;\n }\n````
4
0
['Bit Manipulation', 'C', 'C++']
0
maximum-xor-after-operations
Simple Solution(3 lines) ✅ || Runtime - 100% beats💥 || Memory - 100% beats💥 || With Explanation ✅
simple-solution3-lines-runtime-100-beats-ytkq
Approach\n\nThe goal is to find the maximum possible bitwise XOR of all elements in the nums array after applying the given operation any number of times. To ac
akobirswe
NORMAL
2023-07-30T11:54:19.774896+00:00
2023-07-30T11:54:19.774928+00:00
121
false
# Approach\n\nThe goal is to find the maximum possible bitwise XOR of all elements in the `nums` array after applying the given operation any number of times. To achieve this, we can use the properties of the bitwise XOR operation.\n\n**Logic:**\n1. Initialize a variable `res` to 0. This variable will store the final result, which is the maximum possible bitwise XOR of all elements in the `nums` array.\n2. Loop through each element `a` in the `nums` array.\n3. For each element `a`, perform a bitwise OR operation with the current value of `res` and store the result back in `res`. This effectively combines all the elements in the `nums` array using bitwise OR.\n4. After the loop, `res` will contain the result of combining all elements in the `nums` array using bitwise OR, which is equivalent to the maximum bitwise XOR possible for all elements in the `nums` array.\n\n**Explanation:**\nThe given solution uses a simple logic to find the maximum possible bitwise XOR of all elements in the `nums` array without explicitly using XOR operators.\n\nFor each element in the `nums` array, it performs a bitwise OR operation with the current value of `res`. This operation combines the binary representation of the current element with the binary representation of the accumulated result so far (`res`). The OR operation sets the bits in the result to 1 if either of the corresponding bits in the operands is 1.\n\nBy doing this for all elements in the `nums` array, the `res` variable will eventually contain the maximum possible bitwise XOR of all elements.\n\nIt\'s important to note that this solution does not perform the actual XOR operation between the elements in the array. Instead, it leverages the properties of bitwise OR to find the maximum possible XOR efficiently.\n\n# Complexity\n- Time complexity: $$O(n)$$\n\n- Space complexity: $$O(1)$$\n\n# Code\n```\nclass Solution {\n public int maximumXOR(int[] nums) {\n int res = 0;\n for (int a: nums)\n res |= a;\n return res;\n }\n}\n```
3
0
['Array', 'Math', 'Bit Manipulation', 'Java', 'C#']
0
maximum-xor-after-operations
100% BEATS || OR ALL ELEMENTS || C++
100-beats-or-all-elements-c-by-ganeshkum-5gqh
Code\n\nclass Solution {\npublic:\n int maximumXOR(vector<int>& nums) {\n int ans = 0;;\n for(auto &i: nums){\n ans |= i;\n }
ganeshkumawat8740
NORMAL
2023-06-19T11:25:03.136281+00:00
2023-06-19T11:25:03.136330+00:00
594
false
# Code\n```\nclass Solution {\npublic:\n int maximumXOR(vector<int>& nums) {\n int ans = 0;;\n for(auto &i: nums){\n ans |= i;\n }\n return ans;\n }\n};\n```
3
1
['Math', 'Bit Manipulation', 'C++']
0
maximum-xor-after-operations
C++ || Short Simple Solution || O(N) Time Complexity
c-short-simple-solution-on-time-complexi-364l
Simple check the bit is set or not in nums[i]\nOR is the best option to maximize the ans set bits will be set for ans\n\nclass Solution {\npublic:\n int maxi
shrey0811
NORMAL
2023-02-13T11:44:50.665809+00:00
2023-02-13T11:44:50.665847+00:00
803
false
**Simple check the bit is set or not in nums[i]**\n**OR is the best option to maximize the ans set bits will be set for ans**\n```\nclass Solution {\npublic:\n int maximumXOR(vector<int>& nums)\n {\n int ans = 0;\n for(auto it : nums)\n {\n ans |=it;\n }\n return ans;\n }\n};\n```
3
0
['Bit Manipulation', 'C', 'C++']
0
maximum-xor-after-operations
Explained with Comments | Beginner Friendly | C++ | O(n) Time O(1) Space
explained-with-comments-beginner-friendl-srzq
Explanation\nFor each bit position (0 to 31), we count the number of 1 bits for all elements in the nums array.\nWe store this in bitCounts.\n\nNow, if we take
AbhilakshSinghReen
NORMAL
2022-08-11T14:31:52.034139+00:00
2022-08-11T14:31:52.034170+00:00
187
false
**Explanation**\nFor each bit position (0 to 31), we count the number of 1 bits for all elements in the nums array.\nWe store this in bitCounts.\n\nNow, if we take the XOR of the entire array. In the XOR output, the bits at the positions for which the bit count is even will be 0 and for which the bit count is odd will be 1.\n\nIf we could somehow perform the operation to change the even bit counts into odd ones, we would get the maximum XOR output.\n\nWe can do that.\nFor a number, we can perform the operation such that a 1 bit becomes 0.\n**Note: we can select any non-negative integer x, i.e. x does not have to be from within the array.**\n\nSo we can make any 1 bit 0, but we can\'t make a 0 bit 1.\nWe cannot set a 0 bit to 1 using the operation as we are taking the bitwise AND with nums[i].\n\nWe can always select such an x that we can change any 1 bit to 0.\n\nHence, for every bit position in the bit count which has a non-zero value, we can have that bit to be 1 in the answer. For the positions for which the bit count is 0, those bits in the answer will be 0.\n\n\n**Method 1.1: finding the bit counts for every bit position and then computing the answer**\nCheck Method 1.2 for O(1) Space.\n```\nclass Solution {\npublic:\n int maximumXOR(vector<int>& nums) {\n vector<int> bitCounts(32, 0);\n \n for (int& num : nums) {\n for (int i = 0; i < 32; i++) {\n // Increment bitCounts[i] if the (i)th bit of nums is 1\n bitCounts[i] += (num >> i) & 1;\n }\n }\n \n // Compute the answer from the bit counts as given in the explanation.\n int ans = 0;\n for (int i = 0; i < 32; i++) {\n if (bitCounts[i] > 0) {\n ans += pow(2, i); // you could probably do some bit manipulation here instead of \n // using pow, but that\'s when I got the inspiration for \n // Method 1.2\n }\n }\n \n return ans;\n }\n};\n```\n\n\n**Method 1.2: just take the bitwise OR of all numbers to get the answer**\nIn the answer, we want all bits with non-zero bit counts to be 1 and the remaining bits to be 0. We can compute this answer by taking the bitwise OR of all the elements in the array.\n```\nclass Solution {\npublic:\n int maximumXOR(vector<int>& nums) {\n int ans = 0;\n \n for (int& num : nums) {\n ans |= num;\n }\n \n return ans;\n }\n};\n```\n\nThank you for reading.
3
0
['C']
1
maximum-xor-after-operations
💥One Liner
one-liner-by-adityabhate-eh4t
C++\n\nint maximumXOR(vector<int>& nums) {\n return accumulate(begin(nums), end(nums), 0, bit_or<int>()); //O(n)\n}\n\n\nclass Solution {\npublic: \
AdityaBhate
NORMAL
2022-07-29T04:10:30.295152+00:00
2022-11-17T02:58:39.972166+00:00
678
false
# **C++**\n```\nint maximumXOR(vector<int>& nums) {\n return accumulate(begin(nums), end(nums), 0, bit_or<int>()); //O(n)\n}\n```\n```\nclass Solution {\npublic: \n int maximumXOR(vector<int>& nums) {\n int max_XOR=nums[0];\n for(int i=1;i<nums.size();i++){ //O(n) \n max_XOR|=nums[i];\n }\n return max_XOR;\n }\n};\n```\n# **UPVOTE \uD83D\uDE4F**
3
0
['Array', 'Math', 'Bit Manipulation', 'C++', 'Java']
2
maximum-xor-after-operations
✅ O(n) | Easy Explanation. Why?
on-easy-explanation-why-by-shivamsingla-gwwt
Solution : Maximize XOR\nInitially, the question seems to be very brainstorming but when you closely look at the table below, you can actually find the solution
shivamsingla
NORMAL
2022-06-25T16:11:41.752386+00:00
2022-07-12T18:53:30.544432+00:00
570
false
**Solution : Maximize XOR**\nInitially, the question seems to be very brainstorming but when you closely look at the table below, you can actually find the solution like anybody:\n\n![image](https://assets.leetcode.com/users/images/896b6e8b-afcb-4308-870b-10690f15f4ff_1656173293.3394425.png)\n\n**The Real Trick:**\nSo, we know that we need to maximize the XOR of all elements of the array.\nIn order to do so, we must try to include as many as odd 1\u2019s possible in the sequence at every place.\nIncase there are even 1\'s at any position they can be made odd. (by making that position 0 of any one number, see the table.) \nBut incase there are no 1s at a position it can\'t be generated. \nTo check if any position contains 1 or not, OR is the answer.\n\n**Java Version:**\n```\nclass Solution {\n public int maximumXOR(int[] nums) {\n int ans=0;\n for(int i=0; i<nums.length; i++){\n ans=ans|nums[i];\n }\n return ans;\n }\n}\n```\n\n**CPP Version :**\n```\nclass Solution {\npublic:\n int maximumXOR(vector<int>& nums) {\n int ans=0;\n for(auto it:nums){\n ans|=it;\n }\n return ans;\n }\n};\n```\n\n**Python Version:**\n```\ndef maximumXOR(self, nums):\n return reduce(ior, nums)\n```\n*Hope you liked it!*
3
0
['Bit Manipulation', 'C', 'C++', 'Java']
0
maximum-xor-after-operations
[Python] ATK++ | AGL++ | INT++
python-atk-agl-int-by-siizoo333-kzhq
At the first glance, I really don\'t know what number should we choose at any step for nums[i] AND (nums[i] XOR x).\nHowever, recalling the theorem of XOR, if w
siizoo333
NORMAL
2022-06-25T16:08:33.314287+00:00
2022-07-23T09:57:55.242064+00:00
277
false
At the first glance, I really don\'t know what number should we choose at any step for `nums[i] AND (nums[i] XOR x)`.\nHowever, recalling the theorem of XOR, if we wanna get the largest outcome by XOR-ing the array of numbers, we need odd number of 1\'s in each bit.\n\nThen, how about this `nums[i] AND (nums[i] XOR x)`? If you look at it closer, you realise that no matter how you XOR on the right side, you are gonna keep 1\'s with the left side, which is your original number. Hence, this is kinda a 1-bit deletion operation for you. You can definitely delete any 1-bit for `nums[i]` since you can choose any number.\n\nTherefore, what you are gonna do is just to count the 1s at each bit and construct the final binary string before turning it into decimal.\n\nNote: you can only delete 1s at any bit for each number but you are not allowed to add 1s to the `nums[i]` since `nums[i] AND xxx` forced you to keep whatever 1s you have\n\nUpvote if you find it useful\n\nPS: my first article\n\nTC: O(32N) = O(N) where N is the number of `nums[i]`\nSC: O(32) = O(1)\n\nedited: should not include frequency count into title, frequency count is just to see if there is at least one 1s at a certain bit.\n```\nclass Solution:\n def maximumXOR(self, nums: List[int]) -> int:\n nums = list(map(lambda x: format(x, \'032b\'), nums))\n freqs = [0]*32\n for num in nums:\n for i, bit in enumerate(num):\n if bit == \'1\':\n freqs[i] += 1\n \n s = \'\'\n for cnt in freqs:\n if cnt > 0:\n s += \'1\'\n else:\n s += \'0\'\n return int(s, 2)\n```
3
0
['Python']
0
maximum-xor-after-operations
[Python3] bit operation
python3-bit-operation-by-ye15-he8a
Please pull this commit for solutions of biweekly 81. \n\n\nclass Solution:\n def maximumXOR(self, nums: List[int]) -> int:\n return reduce(or_, nums)
ye15
NORMAL
2022-06-25T16:02:14.657431+00:00
2022-06-25T16:19:38.997391+00:00
105
false
Please pull this [commit](https://github.com/gaosanyong/leetcode/commit/7a67de4e975be771355e048bf8dde4cf0906e360) for solutions of biweekly 81. \n\n```\nclass Solution:\n def maximumXOR(self, nums: List[int]) -> int:\n return reduce(or_, nums)\n```
3
0
['Python3']
0
maximum-xor-after-operations
c++ | OR of all elements
c-or-of-all-elements-by-aman282571-6tpv
Observation:-\n1.For any nums[i] you can\'t get more set bits then it already has because of the "and" operation in condition.\n2.So wherever you see ith bit on
aman282571
NORMAL
2022-06-25T16:01:16.471841+00:00
2022-06-25T16:01:16.471889+00:00
197
false
**Observation:-**\n1.For any nums[i] you can\'t get more set bits then it already has because of the "and" operation in condition.\n2.So wherever you see ```ith``` bit on set the ith bit of answer on because you can add this bit to final answer.\n\n \n``` \nclass Solution {\npublic:\n int maximumXOR(vector<int>& nums) {\n int ans=0,sz=nums.size();\n for(int i=0;i<sz;i++)\n ans|=nums[i];\n return ans;\n \n }\n};\n```\nDo **Upvote** if it helps :)
3
0
[]
0
maximum-xor-after-operations
C++ | O(n*31) time | O(1) space
c-on31-time-o1-space-by-vaibhavshekhawat-lwm7
```\nint maximumXOR(vector& nums) {\n int ans=0;\n for(int i=0;i<31;i++){\n int mask=(1<<i);\n bool f=0;\n for(au
vaibhavshekhawat
NORMAL
2022-06-25T16:00:44.208725+00:00
2022-06-25T16:00:44.208764+00:00
340
false
```\nint maximumXOR(vector<int>& nums) {\n int ans=0;\n for(int i=0;i<31;i++){\n int mask=(1<<i);\n bool f=0;\n for(auto& j:nums){\n if((mask&j)!=0){f=1;break;} // break if a bit is 1 in any nums\n }\n if(f==1) ans|=mask; \n }\n return ans;\n }
3
0
['C']
0
maximum-xor-after-operations
[C++] 3 lines, Bitwise OR of all elements
c-3-lines-bitwise-or-of-all-elements-by-8ih2i
\nclass Solution {\npublic:\n int maximumXOR(vector<int>& nums) {\n int ans = nums[0];\n for(int i = 1; i < nums.size(); ++i) ans |= nums[i];\n
aniket_jain_
NORMAL
2022-06-25T16:00:39.260747+00:00
2022-06-25T16:00:39.260790+00:00
233
false
```\nclass Solution {\npublic:\n int maximumXOR(vector<int>& nums) {\n int ans = nums[0];\n for(int i = 1; i < nums.size(); ++i) ans |= nums[i];\n return ans;\n }\n};\n```
3
0
[]
0
maximum-xor-after-operations
C++ || 100% Beats || Easy Solution
c-100-beats-easy-solution-by-ankit_jha_6-2kyt
IntuitionApproachComplexity Time complexity: Space complexity: Code
ankit_jha_6
NORMAL
2025-01-22T05:31:59.635496+00:00
2025-01-22T05:31:59.635496+00:00
67
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> AND operation can only clear bits (change 1 to 0) but never set bits (change 0 to 1). The OR operation ensures that any bit that is 1 in any number in the array remains 1 in the final result. XOR is maximized when the maximum number of bits in the final result are 1 # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> O(n) - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> O(1) # Code ```cpp [] class Solution { public: int maximumXOR(vector<int>& nums) { int res=0; int n=nums.size(); for(int i=0;i<n;i++) { res|=nums[i]; } return res; } }; ```
2
0
['Bit Manipulation', 'C++']
0
maximum-xor-after-operations
Python. few lines code but a bit more explanation provided.
python-few-lines-code-but-a-bit-more-exp-71lh
IntuitionAll bit manupulations tasks with XOR requeres a bit attention. In this particular, key in in R = "nums[i] AND (nums[i] XOR x)" lets' dissolve this expr
dev_lvl_80
NORMAL
2025-01-16T02:09:08.645469+00:00
2025-01-16T02:09:25.346321+00:00
41
false
# Intuition All bit manupulations tasks with XOR requeres a bit attention. In this particular, key in in R = "nums[i] AND (nums[i] XOR x)" lets' dissolve this expression 1. R cannot be more than nums[i], because of AND 2. nums[i] XOR x, can result in any number Looking at 2 we can clarify 1 as R can be any number where bit set (=1) on only those positions where nums[1] has them too. All this lead to solution, XOR between all possible R, is just combination of all numbers where bits set to 1, where combination is logical OR. # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: O(N) - Space complexity: O(1) # Code ```python3 [] class Solution: def maximumXOR(self, nums: List[int]) -> int: r = 0 for n in nums: r|=n return r ```
2
0
['Python3']
0