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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
construct-the-minimum-bitwise-array-ii | Python3. O( n ). Backtracking, Update SET bits | python3-o-n-backtracking-update-set-bits-hy2c | 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 \nSwitch bits one | srptv | NORMAL | 2024-10-12T16:05:54.754059+00:00 | 2024-10-13T01:37:19.831418+00:00 | 67 | 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 \nSwitch **bits** one by one and **check** if it\'s valid \n \n Ex: 10111\n\n 10110 check ( 10110 | (10110 - 1) == 10111?) no? go next, else return\n 10101 check \n 10011 check \n so on. \n\n##### Logic:\n\n Any string can be a 32 bit number\n \n Go bit by bit removing only one bit and check if update `number OR number + 1` can give the target *\n\nhope helps.\n\n#### UPDATED:\n\nWe can modify string manipulation with bit manipulation:\n\n```\n tmp = 0\n while i >= (1 << tmp):\n # print(tmp, i, 1 << tmp, 1 & (1 << tmp))\n if i & (1 << tmp) :\n tm = i ^ (1 << tmp)\n if tm | (tm + 1) == i:\n\n mn = min(mn, tm)\n tmp = tmp + 1\n```\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```python3 []\nclass Solution:\n def minBitwiseArray(self, nums: List[int]) -> List[int]:\n \n # 1.\n ans = []\n for i in nums:\n tmp = bin(i).replace("0b", "")\n mn = inf\n for j in range(len(tmp)):\n\n if tmp[j] == "1":\n\n tm = int(tmp[:j] + "0" + tmp[j + 1:], 2)\n \n if tm | (tm + 1) == i:\n\n mn = min(mn, tm)\n\n ans.append(mn if mn != inf else -1)\n\n return ans \n```\n\n # UPDATED. Same logic but with bits: Check if bit is set:\n\n # 2.\n ans = []\n for i in nums:\n mn = inf\n tmp = 0\n while i >= (1 << tmp):\n\n if i & (1 << tmp) :\n\n tm = i ^ (1 << tmp)\n\n if tm | (tm + 1) == i:\n\n mn = min(mn, tm)\n \n tmp = tmp + 1\n\n ans.append(mn if mn != inf else -1)\n\n return ans\n\nTLE:\n``` \n # ans = []\n # for n in nums:\n # flag = True\n # for i in range((n // 2) - 1, n, 1):\n # if i | i + 1 == n:\n # ans.append(i)\n # flag = False\n # break\n # if flag:\n # ans.append(-1)\n\n # # print(ans)\n # return ans\n \n \n``` | 1 | 0 | ['Python3'] | 0 |
construct-the-minimum-bitwise-array-ii | bitmask solution explain | bitmask-solution-explain-by-_dharamvir-z7xo | 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 | _dharamvir__ | NORMAL | 2024-10-12T16:05:03.287342+00:00 | 2024-10-12T16:10:35.955887+00:00 | 249 | 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*32)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n vector<int> minBitwiseArray(vector<int>& nums) {\n int n=nums.size();\n\n vector<int>ans(n,-1);\n\n for(int i=0;i<nums.size();i++){\n int num=nums[i];\n\n if(num<=2)continue;\n\n vector<int>bit(32,0);//used for calculating bits of num\n\n for(int j=0;j<31;j++){\n\n int digit=(num>>j)&1;\n\n bit[j]=digit;\n\n }\n\n int tempans=num-1; //always num-1 answer is possible as num is prime number so it is always odd if we neglect one then tempans is equal to num-1\n\n int sum=num;//total sum\n\n\n\n //below loop is traversing and neglect the bit which has bit[j]=1; and calculate the currsum that is check . if check is possible ans then we update tempans \n for(int j=0;j<31;j++){\n\n if(bit[j]){\n\n int check=sum-(1<<j);\n\n if((check|(check+1))==num){tempans=min(tempans,check);}\n }\n\n }\n \n ans[i]=tempans; //minimum of all \n\n }\n\n return ans;\n }\n};\n``` | 1 | 0 | ['Array', 'Bitmask', 'C++'] | 3 |
construct-the-minimum-bitwise-array-ii | [Java] O(n) Look at the last block of ones | java-on-look-at-the-last-block-of-ones-b-90ej | Intuition\nWe have prime numbers only. They all are odd except 2. For 2 we always return -1. For all the others answer exists.\nWhen we add 1 to the number what | whoawhoawhoa | NORMAL | 2024-10-12T16:01:26.233035+00:00 | 2024-10-12T16:15:36.581443+00:00 | 118 | false | # Intuition\nWe have prime numbers only. They all are odd except 2. For 2 we always return -1. For all the others answer exists.\nWhen we add 1 to the number what happens bitwise?\nThe last block of ones shifts by 1 position to the left.\nWe know that each number is odd - the last block always starts at the last position in bit representation. If we shift the last block by 1 to the right - after addition we\'re going to have bitwise OR equal to target and the minimal number achieving that.\n\n# Approach\nTraverse the array. For each value traverse the bit representation right to left, when we see 0 - flip the previous 1. Last value in representation is always 1, except number 2. Handle it separately.\n\n# Complexity\n- Time complexity:\n$$O(32 * n)$$\n\n- Space complexity:\n$$O(1)$$\n\n# Code\n```java []\nclass Solution {\n public int[] minBitwiseArray(List<Integer> nums) {\n int[] res = new int[nums.size()];\n for (int i = 0; i < nums.size(); i++) {\n int x = nums.get(i);\n if (x == 2) {\n res[i] = -1;\n continue;\n }\n for (int j = 0; j < 32; j++) {\n if (((x >> j) & 1) == 0) {\n res[i] = x ^ (1 << (j - 1));\n break;\n }\n }\n }\n return res;\n }\n}\n``` | 1 | 0 | ['Bit Manipulation', 'Java'] | 0 |
construct-the-minimum-bitwise-array-ii | Java | Time 100% | Space 100% | java-time-100-space-100-by-viraj_modi-rtsx | 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 | viraj_modi | NORMAL | 2024-10-12T16:01:00.845944+00:00 | 2024-10-12T16:02:20.709860+00:00 | 120 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```java []\nclass Solution {\n public int[] minBitwiseArray(List<Integer> nums) {\n int n = nums.size(), index = 0;\n\t\tint[] res = new int[n];\n\t\tfor (int num : nums) {\n\t\t\tif (num % 2 != 0) {\n\t\t\t\tint ans = -1, max = (int) (Math.log(num) / Math.log(2));\n\t\t\t\tfor (int i = max; i >= 0; i--) {\n\t\t\t\t\tint newN = num - (1 << i);\n\t\t\t\t\tif ((newN | (newN + 1)) == num) {\n\t\t\t\t\t\tans = newN;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tres[index++] = ans;\n\t\t\t} else\n\t\t\t\tres[index++] = -1;\n\t\t}\n\t\treturn res;\n }\n}\n``` | 1 | 0 | ['Math', 'Java'] | 0 |
construct-the-minimum-bitwise-array-ii | Easy to understand solution in c++ | easy-to-understand-solution-in-c-by-code-idhl | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | coderkrishna07mishra | NORMAL | 2025-03-19T09:54:10.763434+00:00 | 2025-03-19T09:54:10.763434+00:00 | 2 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- 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 solve(int value,string &st){
string str = "";
int temp = value;
while(temp>0){
str += to_string(temp&1);
temp >>=1;
}
str += '0';
reverse(str.begin(),str.end());
int i = str.length()-1;
bool flag = false;
while(i>0){
if(str[i-1] == '0' && flag == false){
str[i] = '0';
flag = true;
}
i--;
}
long long s = 1;
long long j = str.length()-1;
long long val = 0;
while(j>=0){
val += (str[j]-'0')*s;
j--;
s = s*2;
}
st = str;
return val;
}
vector<int> minBitwiseArray(vector<int>& nums) {
int n = nums.size();
vector<int> ans(n);
for(int i = 0; i<nums.size(); i++){
int val = nums[i];
if(val == 2){
ans[i] = -1;
}
else{
string st = "";
ans[i] = solve(val,st);
cout<<st<<endl;
}
}
return ans;
}
};
``` | 0 | 0 | ['Array', 'Bit Manipulation', 'C++'] | 0 |
construct-the-minimum-bitwise-array-ii | Bit operation | bit-operation-by-wondertx-tsq0 | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | wondertx | NORMAL | 2025-01-31T03:15:59.001341+00:00 | 2025-01-31T03:15:59.001341+00:00 | 3 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```cpp []
class Solution {
public:
int MinBitwise(int n) const {
int ones_right = 0;
int flag = 1;
while (n & flag) {
++ones_right;
flag <<= 1;
}
if (!ones_right) {
return -1;
}
flag = ~(1 << (ones_right - 1));
return n & flag;
}
std::vector<int> minBitwiseArray(std::vector<int>& nums) const {
std::vector<int> res;
res.reserve(nums.size());
for (int num : nums) {
res.push_back(MinBitwise(num));
}
return res;
}
};
``` | 0 | 0 | ['C++'] | 0 |
construct-the-minimum-bitwise-array-ii | one pass bitwise-2. | one-pass-bitwise-2-by-rishiinsane-k8xn | IntuitionApproachComplexity
Time complexity:
O(n)
Space complexity:
O(n)
Code | RishiINSANE | NORMAL | 2025-01-26T09:45:06.737326+00:00 | 2025-01-26T09:45:06.737326+00:00 | 7 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
O(n)
- Space complexity:
O(n)
# Code
```cpp []
class Solution {
public:
vector<int> minBitwiseArray(vector<int>& nums) {
int n = nums.size();
vector<int> ans;
for (auto it : nums) {
if (it == 2)
ans.push_back(-1);
else {
int temp = it, val = 0;
while (temp > 0) {
if (allSetBits(temp)) {
val += temp / 2;
temp = 0;
} else {
int x = largestPowerOfTwoLessThan(temp);
temp -= x;
val += x;
}
}
ans.push_back(val);
}
}
return ans;
}
bool allSetBits(int n) { return ((n & (n + 1)) == 0); }
int largestPowerOfTwoLessThan(int n) {
if (n <= 1)
return 0;
int power = floor(log2(n));
return 1 << power;
}
};
``` | 0 | 0 | ['C++'] | 0 |
construct-the-minimum-bitwise-array-ii | Simple Bitmask & Greedy | simple-bitmask-greedy-by-eskandar1-e8et | Complexity
Time complexity:
O(31*n) = O(n)
Space complexity:
cpp -> O(1)
java -> O(n)Code | Eskandar1 | NORMAL | 2025-01-26T00:05:48.288234+00:00 | 2025-01-26T00:10:59.525188+00:00 | 1 | false |
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
O(31*n) = O(n)
---
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
cpp -> O(1)
java -> O(n)
----
# Code
```cpp []
class Solution {
public:
vector<int> minBitwiseArray(vector<int>& nums) {
for(int i=0; i<nums.size(); i++){
if((nums[i]&1) == 0) {
nums[i] = -1; continue;
}
int k=1;
while((nums[i]& 1<<k) !=0) k++;
nums[i] = nums[i]^(1<<(k-1));
}
return nums;
}
};
```
```java []
class Solution {
public int[] minBitwiseArray(List<Integer> nums) {
int[] ans = new int [nums.size()];
for(int i=0; i<nums.size(); i++){
if((nums.get(i)&1) == 0) {
ans[i] = -1; continue;
}
int k=1;
while((nums.get(i)& 1<<k) != 0) k++;
ans[i] = nums.get(i)^(1<<(k-1));
}
return ans;
}
}
``` | 0 | 0 | ['Array', 'Greedy', 'Bit Manipulation', 'Bitmask', 'C++', 'Java'] | 0 |
construct-the-minimum-bitwise-array-ii | Track lowest continuous 1s | track-lowest-continuous-1s-by-linda2024-vjc8 | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | linda2024 | NORMAL | 2025-01-12T04:56:21.920909+00:00 | 2025-01-12T04:56:21.920909+00:00 | 5 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```csharp []
public class Solution {
private int GetValue(int num)
{
int idx = 0;
while((1<<idx & num) != 0)
{
idx++;
}
if(idx == 0) // even number?
return -1;
return num - (int)Math.Pow(2, idx-1); // *1111 -> *0111
}
public int[] MinBitwiseArray(IList<int> nums) {
int len = nums.Count;
List<int> res = new();
foreach(int num in nums)
{
res.Add(GetValue(num));
}
return res.ToArray();
}
}
``` | 0 | 0 | ['C#'] | 0 |
construct-the-minimum-bitwise-array-ii | BIT MANIPULATION | bit-manipulation-by-prachikumari-w5dw | Intuition2 Special Cases to Cater , while obseriving Binary Number behaviuorLSB:
nums.get(i)%2 == 1 (01) ending in binary so to make LSB(trainling zeroes) just | PrachiKumari | NORMAL | 2024-12-30T10:11:02.660525+00:00 | 2024-12-30T10:11:02.660525+00:00 | 4 | false | # Intuition
2 Special Cases to Cater , while obseriving Binary Number behaviuor
LSB:
nums.get(i)%2 == 1 (01) ending in binary so to make LSB(trainling zeroes) just subtract 1(power of 2 at LSB ie 1) ans[i] = nums.get(i)-1
nums.get(i)%2 == 3 (11) ending in binary so to make LSB
trailing zeroes just get to the rightMost 0 position (left Shift 1 upto that and subtract that to get you the minimum posible number satifying ans[i] OR ans[i]+1 = nums[i])
for endings 10, 00 are already trailing no need to be taken care of hence other that these cases , ans[i]=-1
BINARY BEHAVIOUR IS TO BE FOCUSED on
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:O(N)
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:O(N)
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```java []
class Solution {
public int[] minBitwiseArray(List<Integer> nums) {
int n = nums.size();
int[] ans = new int[n];
for (int i = 0; i <n ; i++){
if (nums.get(i)%4 == 1){
ans[i] = nums.get(i)-1;
} else if (nums.get(i)%4 == 3){
int temp = nums.get(i);
int pos = 0;
while (temp >0){
temp >>= 1;
if (temp%2 == 0) break;
pos ++;
}
ans[i] = nums.get(i) - (1<<pos);
}else {
ans[i]= -1;
}
}
return ans;
}
}
``` | 0 | 0 | ['Java'] | 0 |
construct-the-minimum-bitwise-array-ii | C++ | Beats 100% | T.C. O (N * 32), S.C. O (1) | c-beats-100-tc-o-n-32-sc-o-1-by-aman786-bpty | \nclass Solution {\npublic:\n vector<int> minBitwiseArray(vector<int>& nums) {\n vector<int> ans;\n \n for(int i=0;i<nums.size(); i++){\ | Aman786 | NORMAL | 2024-12-20T16:32:25.400487+00:00 | 2024-12-20T16:32:25.400566+00:00 | 2 | false | ```\nclass Solution {\npublic:\n vector<int> minBitwiseArray(vector<int>& nums) {\n vector<int> ans;\n \n for(int i=0;i<nums.size(); i++){\n \n if(nums[i]==2){\n ans.push_back(-1);\n continue;\n }\n \n int last_bit_pos = -1;\n \n for(int j=0; j<31; j++){\n if(nums[i] & (1<<j))\n last_bit_pos = j;\n \n else break;\n }\n \n int mask = 1<<last_bit_pos;\n \n mask = ~mask;\n \n ans.push_back(nums[i]&mask);\n \n }\n \n return ans;\n \n }\n};\n``` | 0 | 0 | ['Bit Manipulation', 'C'] | 0 |
construct-the-minimum-bitwise-array-ii | converting the first '1' before the first '0' | converting-the-first-1-before-the-first-kzq2b | IntuitionBy analyzing the examples provided, you can notice a pattern: converting the first '1' before the first '0' gives you the answer.Code | J22qIDYZa7 | NORMAL | 2024-12-23T05:25:47.776358+00:00 | 2024-12-23T05:25:47.776358+00:00 | 1 | false | # Intuition
By analyzing the examples provided, you can notice a pattern: converting the first '1' before the first '0' gives you the answer.
# Code
```php []
class Solution
{
public function minBitwiseArray($nums)
{
$ans = [];
foreach ($nums as $num) {
if ($num == 2) {
$ans[] = -1;
continue;
}
$i = $num;
$mask = 1;
// Find first 0
while ($i & 1) {
$mask <<= 1;
$i >>= 1;
}
// Convert previous 1 from first 0 to 0
$ans[] = $num ^ ($mask >> 1);
}
return $ans;
}
}
``` | 0 | 0 | ['PHP'] | 0 |
construct-the-minimum-bitwise-array-ii | From Brute Force to optimized | from-brute-force-to-optimized-by-rknice1-b268 | Brute Force Approach\nTime: O(NMax(nums))\nSpce: O(N)\n\n\nans=[-1]*len(nums)\nfor num in nums:\n for i in range(0,num):\n\t\t\t\t if (i) | (i+1)==nu | rknice16 | NORMAL | 2024-12-04T12:26:48.150582+00:00 | 2024-12-04T12:26:48.150619+00:00 | 2 | false | **Brute Force Approach**\nTime: O(N*Max(nums))\nSpce: O(N)\n\n```\nans=[-1]*len(nums)\nfor num in nums:\n for i in range(0,num):\n\t\t\t\t if (i) | (i+1)==nums:\n\t\t\t\t\t\t ans[i]=i\n\t\t\t\t\t\t\t\t\t\tbreak\nreturn ans\n```\n**Optimized Approach**\nfor every nums[i]:\n unset a bit and try\n\t\tfor example:\n\t\t to get 111:\n\t\t\t\t the possible values are:\n 011--->011|100=111\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t101---->101|110=111\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t110 ----> 110|111=111\n\t\tso for each value we need to unset bits and try\n\nHow can we do that?\n \n How to know ith bit is 1 or 0? -- we need do an AND operation with `1<<i`\n\t\t\t\t\t\t\t\tHow to make a bit 0? Do a AND operation with ~(1<<i)\n\n\nSo our optimized code will be:\n ```\n ```\n max_len=len(1000000000)\n ans=[-1]*len(nums)\n\t\t\t\t\t\t\tfor n in range(len(nums)):\n\t\t\t\t\t\t\t\t\tnum=nums[n]\n\t\t\t\t\t\t\t\t\tvalues=[]\n\t\t\t\t\t\t\t\t\tfor i in range(max_len):\n\t\t\t\t\t\t\t\t\t\t\tif num& 1<<i!=0 and (num& ~(1<<i))|(num& ~(1<<i))+1==num:\n\t\t\t\t\t\t\t\t\t\t\t\t\tvalues.append(num& ~(1<<i))\n\t\t\t\t\t\t\t\t\tif values:\n\t\t\t\t\t\t\t\t\t\t\t ans[n]=min(values) \n\t\t\t\t\t\t\treturn ans\n```\n```\n\t\t\t\t\t\t \n \n\n\n\n\n | 0 | 0 | ['Array', 'Bit Manipulation', 'Python'] | 0 |
construct-the-minimum-bitwise-array-ii | Rust/Python. Real linear solution with full explanation | rustpython-real-linear-solution-with-ful-kar4 | Intuition\n\nFirst we need to understand that the question asks to solve equation:\n\nx OR (x + 1) = y\n\nfor x. Here they have a strange requirement of y being | salvadordali | NORMAL | 2024-11-22T08:39:01.355465+00:00 | 2024-11-22T08:42:53.561872+00:00 | 3 | false | # Intuition\n\nFirst we need to understand that the question asks to solve equation:\n\n`x OR (x + 1) = y`\n\nfor `x`. Here they have a strange requirement of `y` being prime, but we later we will see that it is irrelevant. On top of this the `x` should be as small as possible.\n\n\nLets look at some number `10111001111` and after trying multiple numbers you can see that all you need is to find how many consequitive ones from the right do you have (in our case it is 4: `1111`) and remove the top one -> `0111`. So your number will be:\n\n```\n10111001111\n= \n10111000111 \nOR\n10111001000\n```\nIt is easily to see that this will work (when you have some ones at the end) as `1...1` or `1..1 + 1` will give you `11...1`.\n\nAs you see here it will work for any number and for even you never can find the solution.\n\n------\nSo we have the solution. Now we can easily implement this with a loop:\n\n```\n def find_x(self, y):\n if y % 2 == 0:\n return -1\n\n count, temp = 0, y\n while temp & 1:\n count += 1\n temp >>= 1\n\n mask = 1 << (count - 1)\n return y & ~mask\n```\n\nBut we do not want a loop. We need efficient binary operation. And you can achieve it with `x & ((x | ~(x + 1)) >> 1)`. This will work because:\n\n - `x + 1` changes your `1..1` to `10..0`\n - `!(x + 1)` inverts bits of that value\n - `(x | !(x + 1))` all trailing ones are still ones then zero and then once again\n - prev expression >> 2 just shifts one value to the right\n - x & prev expression gets you the number you want\n \n# Complexity\n- Time complexity: $O(n)$\n- Space complexity: $O(n)$\n\n# Code\n```python []\nclass Solution:\n\n def find_x(self, x):\n if x % 2 == 0:\n return -1\n return x & ((x | ~(x+1)) >> 1)\n\n def minBitwiseArray(self, nums: List[int]) -> List[int]:\n return [self.find_x(v) for v in nums] \n```\n```rust []\nimpl Solution {\n fn find_x(x: i32) -> i32 {\n if x % 2 == 0 {\n return -1;\n }\n x & ((x | !(x + 1)) >> 1)\n }\n\n fn min_bitwise_array(nums: Vec<i32>) -> Vec<i32> {\n nums.into_iter().map(|v| Self::find_x(v)).collect()\n }\n}\n```\n\n**BTW, rust has** `trailing_ones()` function so you can just do:\n\n`x & !(1 << (x.trailing_ones() - 1))`. But I am not sure what ASM code will it generate. So if Rust experts are here, can you tell if it gives an efficient implementation. | 0 | 0 | ['Python3', 'Rust'] | 0 |
construct-the-minimum-bitwise-array-ii | C++ 100% | c-100-by-soundsoflife-in8j | 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 | soundsoflife | NORMAL | 2024-11-13T16:57:39.068699+00:00 | 2024-11-13T16:57:39.068743+00:00 | 2 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n int solve(int num) {\n if (num == 2) return -1;\n long long tmp = 1;\n while(tmp < num) {\n if ((num & tmp) == 0) {\n num = num - (tmp / 2);\n return num;\n }\n tmp = tmp * 2;\n }\n return num / 2;\n }\n\n vector<int> minBitwiseArray(vector<int>& nums) {\n vector<int> ans;\n for (auto &it : nums) {\n ans.push_back(solve(it));\n }\n return ans;\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
construct-the-minimum-bitwise-array-ii | Easy to UnderStand Beginner Friendly | easy-to-understand-beginner-friendly-by-mxp7b | To address this problem, here\u2019s the breakdown:\n\n# Intuition\nThe goal is to transform each element of the array v by minimizing its binary representation | tinku_tries | NORMAL | 2024-11-11T09:51:37.425549+00:00 | 2024-11-11T09:51:37.425589+00:00 | 4 | false | To address this problem, here\u2019s the breakdown:\n\n# Intuition\nThe goal is to transform each element of the array `v` by minimizing its binary representation. For each element `v[i]`, if it is odd, we attempt to adjust it such that the resulting value retains as few high-value bits as possible while being slightly modified if necessary. This may involve clearing specific bits in a controlled way to achieve the minimal required configuration.\n\n# Approach\n1. **Helper Function `f`**: \n - This function minimizes a given integer `n` by selectively clearing one of the bits to create the smallest possible number that still closely resembles `n` in its binary structure.\n - We iterate through each bit of `n`. When we encounter the first unset bit (`0`), we adjust the last set bit (`1`) we added, which helps minimize the integer.\n \n2. **Main Transformation in `minBitwiseArray`**:\n - **Check Each Element**:\n - If `v[i]` is even, we skip it, as we only want to modify odd numbers.\n - For odd numbers:\n - If `v[i]` is a power of two minus one (e.g., `1, 3, 7, 15...`), its minimized value should be half of `v[i]` minus one (a straightforward case).\n - Otherwise, we use the `f` function to get a minimized version.\n - **Store Result**: We create an array `ans` to store the minimized results for each `v[i]`.\n\n# Complexity\n- **Time Complexity**: \n - Let `n` be the length of the input array `v`. For each odd element, we process its bits (approximately `O(log k)` for integer `k`).\n - Overall complexity is `O(nlog k)` in the worst case.\n\n- **Space Complexity**: \n - `O(n)` for storing the resulting minimized array.\n\n# Beats\n\n\n\n# Code\n```cpp\n#include <vector>\nusing namespace std;\n\nclass Solution {\npublic:\n // Helper function to minimize binary form of odd number `n`\n int f(int n) {\n int ans = 0, i = 0;\n bool flag = true;\n \n // Iterate through bits of `n` to minimize its value\n while(n) {\n if(n % 2) ans += 1 << i; // If bit is set, add it to `ans`\n else if(flag) {\n ans -= 1 << (i - 1); // Clear the last added bit to minimize\n flag = false;\n }\n i++;\n n /= 2;\n }\n return ans;\n }\n \n // Main function to transform array based on minimization rules\n vector<int> minBitwiseArray(vector<int>& v) {\n int n = v.size();\n vector<int> ans(n, -1); // Initialize results with `-1`\n \n // Process each element in the input vector\n for(int i = 0; i < n; i++) {\n if(v[i] % 2 == 0) continue; // Skip even numbers\n else if(((v[i] + 1) & (v[i])) == 0) // Special case for `2^k - 1`\n ans[i] = (v[i] - 1) / 2;\n else ans[i] = f(v[i]); // Use helper function for other odd numbers\n }\n return ans;\n }\n};\n``` | 0 | 0 | ['Array', 'Bit Manipulation', 'C++'] | 0 |
construct-the-minimum-bitwise-array-ii | Simple C++ Solution Beats 100% , O(N) | simple-c-solution-beats-100-on-by-samart-a24m | Code\ncpp []\nvector<int> minBitwiseArray(vector<int>& nums) {\n int n=nums.size();\n vector<int> ans(n);\n for(int i=0;i<n;++i){\n | samarth_verma_007 | NORMAL | 2024-11-04T18:12:41.151895+00:00 | 2024-11-04T18:12:41.151925+00:00 | 5 | false | # Code\n```cpp []\nvector<int> minBitwiseArray(vector<int>& nums) {\n int n=nums.size();\n vector<int> ans(n);\n for(int i=0;i<n;++i){\n if(nums[i]&1){\n int j=0;\n while(nums[i] & (1<<j)){\n ++j;\n }\n\n --j;\n ans[i]=(nums[i] & (~(1<<j)));\n }\n else{\n ans[i]=-1;\n }\n }\n\n return ans;\n}\n``` | 0 | 0 | ['C++'] | 0 |
construct-the-minimum-bitwise-array-ii | Bit Manipulation | bit-manipulation-by-djverma5-32xg | 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 | Djverma5 | NORMAL | 2024-10-29T08:03:34.865491+00:00 | 2024-10-29T08:03:34.865518+00:00 | 1 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n$$O(n Log(max(nums[i])))$$\n\n- Space complexity:\n$$O(1)$$\n\n# Code\n```cpp []\nclass Solution {\npublic:\n vector<int> minBitwiseArray(vector<int>& nums) {\n int n = nums.size();\n vector<int> res(n , -1);\n for(int i = 0 ; i < n ; i++){\n if(nums[i] == 2) continue;\n int num = nums[i];\n int a = 1;\n while((num & a) != 0){\n a = a << 1;\n }\n a = a >> 1;\n num = num - a;\n res[i] = num;\n }\n return res;\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
construct-the-minimum-bitwise-array-ii | beating 100% c++ solution (no explanation) | beating-100-c-solution-no-explanation-by-0bpq | \n\n# Code\ncpp []\nclass Solution {\npublic:\n vector<int> minBitwiseArray(vector<int>& nums) {\n vector<int> res;\n for(int ele: nums) | lcq_dev | NORMAL | 2024-10-26T15:45:04.001871+00:00 | 2024-10-26T15:45:04.001895+00:00 | 1 | false | \n\n# Code\n```cpp []\nclass Solution {\npublic:\n vector<int> minBitwiseArray(vector<int>& nums) {\n vector<int> res;\n for(int ele: nums) {\n int a = 0;\n int temp = 0;\n\n int count = 0;\n while(ele!=0) {\n if(((ele>>count)&1) == 0) {\n break;\n \n }else{\n temp <<= 1;\n temp |= 1;\n }\n\n count++;\n }\n\n a = (ele^temp);\n a = (a|(temp>>1));\n\n if((a|(a+1)) == ele) {\n res.push_back(a);\n }else{\n res.push_back(-1);\n }\n } \n\n return res;\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
construct-the-minimum-bitwise-array-ii | Simple Python3 Solution | simple-python3-solution-by-xxhrxx-5m9n | Basically what we need to do is to find the where the consecutive 1 ends from the end of the binary presentation of the target and then construct the number\n\n | xxhrxx | NORMAL | 2024-10-24T18:30:10.269513+00:00 | 2024-10-24T18:30:10.269544+00:00 | 2 | false | Basically what we need to do is to find the where the consecutive 1 ends from the end of the binary presentation of the target and then construct the number\n\nFor example:\ntarget = 11111000111111\nres ~~= 11111000011111\n\nas adding 1 in res yield to 11111000100000 which contributes to the only missing 1 in the target\n\n# Code\n```python3 []\nclass Solution:\n def minBitwiseArray(self, nums: List[int]) -> List[int]:\n res = []\n for element in nums:\n if element == 2:\n res.append(-1)\n else:\n bin_rep = bin(element)[2:]\n if bin_rep[-2] == \'0\':\n res.append(int(bin_rep[:-1] + \'0\',2))\n else:\n index = None\n for i in range(len(bin_rep)-2, -1, -1):\n if bin_rep[i] == \'0\':\n break\n else:\n index = i\n res.append(int(bin_rep[:index] + \'0\' + \'1\'*(len(bin_rep) - index - 1),2))\n return res\n \n``` | 0 | 0 | ['Python3'] | 0 |
construct-the-minimum-bitwise-array-ii | C++ Solution | c-solution-by-tlexceeded-o0to | Intuition\n Describe your first thoughts on how to solve this problem. \n\nLet num is any number in array.\n\n1) if num is in the form of x0 -> even -> -1(not p | TLExceeded | NORMAL | 2024-10-23T05:20:22.391761+00:00 | 2024-10-23T05:20:22.391814+00:00 | 10 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\nLet num is any number in array.\n\n1) if num is in the form of x0 -> even -> -1(not possible use pen and paper to check since adding 1 is always a odd number).\n2) only even prime number is 2 thus -1 for 2\n3) odd prime have 2 form\n4) form 1 -> x01 , form 2 xA\'1\n \n x -> any bits 0/1\n A -> count of continous bits , in above case count of conti. 1 bit\n\n5) for form 1 easy -> num - 1 (use pen and paper to check)\n6) for form 2 medium -> x111 - > x011 (again use pen and paper to check)\n7) Do lot\'s of dry run to check then see my code for building correct mask to solve.\n\nGood Luck :) \nIf any doubt pin me on "partharora3350@gmail.com" for discussion on google meet.\n\n\n# Code\n```cpp []\nclass Solution\n{\npublic:\n vector<int> minBitwiseArray(vector<int> &a)\n {\n int n = a.size();\n vector<int> res(n);\n for(int i = 0 ; i < n; i++){\n int num = a[i];\n if(num == 2) res[i] = -1;\n else if((num & 3) == 1) res[i] = num - 1;\n else{\n int mask = 1;\n while((mask & num)){\n mask <<= 1;\n }\n mask >>= 1;\n mask = ~mask;\n num &= mask;\n res[i] = num;\n }\n }\n return res;\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
construct-the-minimum-bitwise-array-ii | Python3 | 0ms | Beats 100% | python3-0ms-beats-100-by-padth-8xay | 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 | padth | NORMAL | 2024-10-23T04:13:33.664760+00:00 | 2024-10-23T04:13:33.664783+00:00 | 2 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```python3 []\nclass Solution:\n def minBitwiseArray(self, nums: List[int]) -> List[int]:\n result = []\n\n for n in nums:\n if n % 2 == 0:\n result.append(-1)\n continue\n\n i = 0\n while n & (1 << i) != 0:\n i += 1\n\n result.append((1 << (i - 1)) ^ n)\n\n return result\n``` | 0 | 0 | ['Python3'] | 0 |
construct-the-minimum-bitwise-array-ii | C Solution || Beats 100% || Bit Manipulation Approach || With Explanations | c-solution-beats-100-bit-manipulation-ap-unwt | Intuition\nThe goal is to modify each number in the array such that for odd numbers, we find the minimum bitwise transformation that satisfies a given condition | Heber_Alturria | NORMAL | 2024-10-22T21:57:43.455366+00:00 | 2024-10-22T21:57:43.455398+00:00 | 1 | false | # Intuition\nThe goal is to modify each number in the array such that for odd numbers, we find the minimum bitwise transformation that satisfies a given condition. For even numbers, a predetermined result is returned. The key observation is that for odd numbers, we can use bitwise operations to manipulate individual bits in a controlled manner.\n\n# Approach\n\nWe need to modify each number in the input array based on specific rules. If the number is even, we simply set the result for that number to `-1`. If the number is odd, we need to find the smallest number that can be created using a bitwise XOR (`^`) operation with a bitmask.\n\nThe approach can be broken down into the following steps:\n\n1. **Even Numbers**: If the current number is even, the result is automatically set to `-1`. This simplifies handling for even numbers and avoids unnecessary computation.\n\n2. **Odd Numbers**: For odd numbers, we need to find the smallest possible result by applying a bitwise operation. We do this by:\n - Starting with a bitmask of `1` (which corresponds to the lowest bit).\n - For each bitmask, we calculate the result of XOR between the number and the bitmask (`num ^ mask`).\n - After that, we check if the condition `(val | (val + 1)) == num` is satisfied. This condition ensures that the transformed number still retains a valid bit structure similar to the original odd number.\n - We repeat this process by shifting the bitmask to the left (doubling it) and checking different bits of the number until we find a valid result.\n\n# Code\n```c []\n/**\n * Note: The returned array must be malloced, assume caller calls free().\n */\nint* minBitwiseArray(int* nums, int numsSize, int* returnSize) {\n int *result = calloc(numsSize, sizeof(int));\n *returnSize = numsSize;\n\n for (int i = 0; i < numsSize; i++) {\n int num = nums[i];\n\n if (num % 2 == 0) {\n result[i] = -1;\n continue;\n }\n\n int mask = 1;\n\n while (mask <= num) {\n int val = mask ^ num;\n\n if ((val | (val + 1)) == num) result[i] = val;\n\n mask <<= 1;\n }\n }\n\n return result;\n}\n``` | 0 | 0 | ['Array', 'Bit Manipulation', 'C'] | 0 |
construct-the-minimum-bitwise-array-ii | C++ | Bit Manipulation | Beats 100% | c-bit-manipulation-beats-100-by-rajharsh-huqk | 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 | rajharsh_24 | NORMAL | 2024-10-22T18:32:04.181802+00:00 | 2024-10-22T18:32:04.181841+00:00 | 6 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\n int harsh(int n){\n int m=log2(n)+1;\n\n if(n==2) return -1;\n int flag=0;\n int x=0;\n\n for(int i=0; i<m; i++){\n if((n&(1<<i))==0){\n flag=1;\n x=i-1;\n break;\n }\n }\n\n int ans=0;\n\n if(!flag){\n ans=n>>1;\n }\n else ans=(n^(1<<x));\n\n return ans;\n }\npublic:\n vector<int> minBitwiseArray(vector<int>& nums) {\n int n=nums.size();\n vector<int> ans(n);\n\n for(int i=0; i<n; i++){\n ans[i]=harsh(nums[i]);\n }\n\n return ans;\n }\n};\n``` | 0 | 0 | ['Bit Manipulation', 'C++'] | 0 |
construct-the-minimum-bitwise-array-ii | C & Python || 1ms || Beats 100% || Bit manipulation | c-python-1ms-beats-100-bit-manipulation-h0zve | Intuition\nIf the original is 1110010101001111\nThen best value is 1110010101000111\ni.e. make the leftmost 1 in the rightmost block of 1\'s a 0.\n\nThe C and P | i_have_no_biscuits | NORMAL | 2024-10-21T17:20:19.099319+00:00 | 2024-10-21T17:20:19.099351+00:00 | 2 | false | # Intuition\nIf the original is 1110010101001111\nThen best value is 1110010101000111\ni.e. make the leftmost 1 in the rightmost block of 1\'s a 0.\n\nThe C and Python code are basically identical (ignoring the messing around you have to do with dynamic memory in C)!\n\n# Code\n```c []\nint value(int n) {\n if (n % 2 == 0) {\n return -1;\n }\n int offset = 1;\n while (n & (offset<<1)) {\n offset <<= 1;\n }\n return n - offset;\n}\n\nint* minBitwiseArray(int* nums, int numsSize, int* returnSize) {\n int* vals = malloc(numsSize*sizeof(int));\n *returnSize = numsSize;\n \n for (int i=0; i<numsSize; ++i) {\n vals[i] = value(nums[i]);\n }\n return vals;\n}\n```\n```Python []\nclass Solution:\n def minBitwiseArray(self, nums: List[int]) -> List[int]:\n def value(n):\n if n % 2 == 0:\n return -1\n offset = 1\n while n & (offset<<1):\n offset <<= 1\n return n - offset\n\n return [value(n) for n in nums]\n```\n | 0 | 0 | ['C'] | 0 |
construct-the-minimum-bitwise-array-ii | Beats 100% solutions | beats-100-solutions-by-0056harshit_gupta-opgd | Complexity\n- Time complexity:O(N)\n Add your time complexity here, e.g. O(n) \n\n- Space complexity:O(N)\n Add your space complexity here, e.g. O(n) \n\n# Code | 0056harshit_gupta | NORMAL | 2024-10-20T13:08:46.640860+00:00 | 2024-10-20T13:08:46.640902+00:00 | 3 | false | # Complexity\n- Time complexity:O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(N)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n vector<int> minBitwiseArray(vector<int>& nums) {\n vector<int> ans;\n for(int i=0;i<nums.size();i++){\n int num=nums[i];\n int curr=0;\n if(num==2)\n {\n ans.push_back(-1);\n continue;\n }\n int check=1;\n for(int i=0;i<31;i++){\n if((num & (1 << (i+1)))==0 && check==1){\n check=0;\n }else{\n curr=curr + ((num & (1 << i))?pow(2,i):0);\n }\n }\n\n ans.push_back(curr);\n }\n return ans;\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
construct-the-minimum-bitwise-array-ii | Beats 95% solutions | beats-95-solutions-by-0056harshit_gupta-68qf | Complexity\n- Time complexity:O(N)\n Add your time complexity here, e.g. O(n) \n\n- Space complexity:O(N)\n Add your space complexity here, e.g. O(n) \n\n# Code | 0056harshit_gupta | NORMAL | 2024-10-20T13:00:57.208928+00:00 | 2024-10-20T13:00:57.208957+00:00 | 3 | false | # Complexity\n- Time complexity:O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(N)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n vector<int> minBitwiseArray(vector<int>& nums) {\n vector<int> ans;\n for(int i=0;i<nums.size();i++){\n int num=nums[i];\n int curr=0;\n if(num==2)\n {\n ans.push_back(-1);\n continue;\n }\n int check = 1;\n for(int i = 0; i < 31; i++) {\n if(((num & (1 << (i + 1))) == 0) && check == 1) {\n check = 0; \n } else {\n curr = curr + ((num & (1 << i)) ? (1 << i) : 0);\n }\n }\n\n ans.push_back(curr);\n }\n return ans;\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
construct-the-minimum-bitwise-array-ii | Simple Java Solution | simple-java-solution-by-prince_kumar1-khda | 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 | prince_kumar1 | NORMAL | 2024-10-20T11:04:09.482988+00:00 | 2024-10-20T11:04:09.483013+00:00 | 2 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```java []\nclass Solution {\n public int[] minBitwiseArray(List<Integer> nums) {\n \n int []ans=new int[nums.size()];\n\n for(int i=0;i<nums.size();i++){\n if(nums.get(i)==2)ans[i]=-1;\n else{\n int x=nums.get(i);\n int p=Integer.lowestOneBit(x+1);\n x=x-(p>>1);\n ans[i]=x;\n }\n }\n\n return ans;\n }\n}\n``` | 0 | 0 | ['Java'] | 0 |
construct-the-minimum-bitwise-array-ii | scala solution. lowest unset bit | scala-solution-lowest-unset-bit-by-vitit-0e4o | scala []\nobject Solution {\n def minBitwiseArray(nums: List[Int]): Array[Int] = {\n nums.map(BigInt(_)).map(bigInt => (Option.when((bigInt&1) != 0) {\n | vititov | NORMAL | 2024-10-19T17:05:13.000528+00:00 | 2024-10-19T17:05:13.000551+00:00 | 0 | false | ```scala []\nobject Solution {\n def minBitwiseArray(nums: List[Int]): Array[Int] = {\n nums.map(BigInt(_)).map(bigInt => (Option.when((bigInt&1) != 0) {\n lazy val lowestUnSetBit = (~bigInt).lowestSetBit\n lazy val hiBits = bigInt & ~((1<<lowestUnSetBit)-1)\n lazy val loBits = (1<<(lowestUnSetBit-1))-1\n (hiBits | loBits).toInt\n }).getOrElse(-1)).to(Array)\n }\n}\n``` | 0 | 0 | ['Scala'] | 0 |
construct-the-minimum-bitwise-array-ii | Beats 100% | Easy C++ Solution | beats-100-easy-c-solution-by-krishiiitp-5w76 | Code\ncpp []\nclass Solution {\npublic:\n vector<int> minBitwiseArray(vector<int>& nums) {\n int n=nums.size();\n vector<int> ans(n),v;\n | krishiiitp | NORMAL | 2024-10-19T16:44:45.809006+00:00 | 2024-10-19T16:44:45.809030+00:00 | 3 | false | # Code\n```cpp []\nclass Solution {\npublic:\n vector<int> minBitwiseArray(vector<int>& nums) {\n int n=nums.size();\n vector<int> ans(n),v;\n for(int i=0;i<n;i++){\n if(nums[i]==2){\n ans[i]=-1;\n }else{\n int some=nums[i];\n while(some>0){\n if(some%2){\n v.push_back(1);\n }else{\n v.push_back(0);\n }\n some/=2;\n }\n int val=nums[i],sub=1;\n for(int i=0;i<v.size();i++){\n if(v[i]==0){\n break;\n }\n sub=sub*2;\n }\n sub/=2;\n ans[i]=val-sub;\n v.clear();\n }\n }\n return ans;\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
construct-the-minimum-bitwise-array-ii | Easy Solution with Bit Manipulation | easy-solution-with-bit-manipulation-by-s-4nsp | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \nBit manipulation\n\n# C | Shayan704 | NORMAL | 2024-10-19T07:09:50.413162+00:00 | 2024-10-19T07:09:50.413207+00:00 | 5 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nBit manipulation\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(N*31)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(N)\n\n# Code\n```java []\nclass Solution {\n public int[] minBitwiseArray(List<Integer> nums) {\n int ans[]= new int[nums.size()];\n for(int i=0; i<nums.size(); i++)\n {\n int temp = nums.get(i);\n if(temp == 2)\n {\n ans[i] = -1;\n continue;\n }\n for(int j=1; j<31; j++)\n {\n if((temp & (1<<j))>0)\n continue;\n ans[i] = temp ^ (1<<(j-1));\n break;\n }\n\n }\n return ans;\n }\n}\n``` | 0 | 0 | ['Bit Manipulation', 'Java'] | 0 |
construct-the-minimum-bitwise-array-ii | Beats 100% | beats-100-by-dhyey_24-812k | 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# Cod | dhyey_24 | NORMAL | 2024-10-19T07:01:22.824432+00:00 | 2024-10-19T07:01:22.824469+00:00 | 4 | false | # 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```cpp []\nclass Solution {\npublic:\n vector<int> minBitwiseArray(vector<int>& arr) {\n int n = arr.size() ;\n vector<int> ans ;\n\n for(int i = 0;i<n;i++){\n if(arr[i] == 2){\n ans.push_back(-1);\n }\n else{\n for(int j = 1;j<31;j++){\n if((arr[i] & (1<<j)) == 0){\n ans.push_back(arr[i] ^ (1 << (j-1)));\n break;\n }\n }\n }\n }\n\n return ans;\n }\n};\n``` | 0 | 0 | ['Array', 'Bit Manipulation', 'C++'] | 0 |
construct-the-minimum-bitwise-array-ii | One line solution. Bit manipulation. O(n) | one-line-solution-bit-manipulation-on-by-0cin | \nclass Solution:\n def minBitwiseArray(self, nums: List[int]) -> List[int]:\n return [(n&(n+1)) | ((~n&(n+1))//2-1) for n in nums]\n | xxxxkav | NORMAL | 2024-10-18T22:14:25.402374+00:00 | 2024-10-18T22:14:33.674104+00:00 | 2 | false | ```\nclass Solution:\n def minBitwiseArray(self, nums: List[int]) -> List[int]:\n return [(n&(n+1)) | ((~n&(n+1))//2-1) for n in nums]\n``` | 0 | 0 | ['Bit Manipulation', 'Python3'] | 0 |
construct-the-minimum-bitwise-array-ii | why leftmost works | what happens when we add 1 to a number | Proof | why-leftmost-works-what-happens-when-we-jxdnd | In binary addition, adding 1 to a number follows rules very similar to how addition works in decimal, but with only two digits (0 and 1). Let\'s take a deeper l | byp8as | NORMAL | 2024-10-18T19:26:01.879495+00:00 | 2024-10-18T19:26:01.879524+00:00 | 4 | false | In binary addition, adding `1` to a number follows rules very similar to how addition works in decimal, but with only two digits (`0` and `1`). Let\'s take a deeper look at what happens bit by bit when we add `1` to a binary number.\n\n#### Binary addition works with the following basic rules:\n\n- 0 + 0 = 0\n- 0 + 1 = 1\n- 1 + 0 = 1\n- 1 + 1 = 10 (This results in 0 and carries over 1 to the next higher bit) So adding 1 in a 1 gives 2 in decimal format and 10 in binary.\n\nNow Lets see how does this help us,\n\nTake Example of `47` = `101111` there is always a number n-1, here `46` to give answer ,as `46` is even and even number has last bit always `0` ,`46` = `101110` so when you `or` both the numbers, last bit gets set and you get `47` and `46` becomes your answer.\n\nBut can we do better,\nYes by using the binary addition trick we discussed above, we want answer to be minimum so what if we set the `1` which is just after the leftmost `0` to `0`. If we do this in `47` = `101111` then the binary will change to `100111`=`39` now if you add `1` to `39` then it bits will change with the last `1` to `0` then second last `1` to `0` then third last`1` to `0` and finally fourth last `0` will become `1` due to carry finally making `101000` = `40` and if you or `39` with `40` you will get `47` \n\nbelow is just the implementation of this\n\n# Code\n```cpp []\nclass Solution {\npublic:\n int number(int n){\n int mask = 1;\n for(int i=1;i<=31;i++){\n mask = mask << 1;\n if((n&mask) == 0){\n mask = mask >> 1;\n return n & ~(mask); \n }\n }\n return 0;\n }\n\n vector<int> minBitwiseArray(vector<int>& nums) {\n vector<int> ans;\n for(auto& it: nums){\n if(it == 2){\n ans.push_back(-1);\n }else{\n ans.push_back(number(it));\n }\n }\n return ans;\n }\n};\n``` | 0 | 0 | ['Math', 'Bit Manipulation', 'C++'] | 0 |
construct-the-minimum-bitwise-array-ii | Java, Easy And Optimized Solution using bitwise Operator | java-easy-and-optimized-solution-using-b-ujrv | 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 | vipin_121 | NORMAL | 2024-10-18T09:45:16.052687+00:00 | 2024-10-18T09:45:16.052711+00:00 | 2 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```java []\nclass Solution {\n public int[] minBitwiseArray(List<Integer> nums) {\n int[] ans=new int[nums.size()];\n for(int i=0;i<nums.size();i++){\n int sf=1;\n if(nums.get(i)==2){\n ans[i]=-1;\n continue;\n }\n while((nums.get(i)&sf)!=0){\n sf=sf<<1;\n }\n sf=sf>>1;\n ans[i]=nums.get(i)&~(sf);\n\n }\n return ans;\n }\n}\n``` | 0 | 0 | ['Java'] | 0 |
construct-the-minimum-bitwise-array-ii | C++, Easy and Optimized Using Bitwise Operator | c-easy-and-optimized-using-bitwise-opera-hq5h | 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 | Ashutosh_2002 | NORMAL | 2024-10-18T09:44:41.550820+00:00 | 2024-10-18T09:44:41.550855+00:00 | 2 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n vector<int> minBitwiseArray(vector<int>& nums) {\n int n = nums.size();\n vector<int>ans;\n\n for(int i = 0;i<n;i++){\n if(nums[i]==2){\n ans.push_back(-1);\n continue;\n } \n int temp = 1;\n\n while(nums[i] & temp){\n temp = temp<<1;\n }\n\n temp = temp>>1;\n nums[i] = nums[i] & (~temp);\n ans.push_back(nums[i]);\n\n }\n\n return ans;\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
construct-the-minimum-bitwise-array-ii | Beats 100% solutions | beats-100-solutions-by-rupesh5129-jxm2 | Intuition\n- Find the position of the first unset bit from LSB.\n- Now toggle the next bit to the right.\n\n# Complexity\n- Time complexity: O(n)\n\n- Space com | rupesh5129 | NORMAL | 2024-10-18T07:56:08.881231+00:00 | 2024-10-18T07:56:08.881254+00:00 | 1 | false | # Intuition\n- Find the position of the first unset bit from LSB.\n- Now toggle the next bit to the right.\n\n# Complexity\n- Time complexity: O(n)\n\n- Space complexity: O(1)\n\n# Code\n```cpp []\nclass Solution {\npublic:\n vector<int> minBitwiseArray(vector<int>& nums) {\n int n = nums.size();\n for (int i=0; i<n; i++) {\n int pos = 0;\n int temp = nums[i];\n while (temp != 0) {\n if((temp&1) == 1) {\n pos++;\n temp = temp >> 1;\n } else {\n break;\n }\n }\n if (pos != 0) {\n nums[i] = nums[i] ^ (1 << (pos-1));\n } else {\n nums[i] = -1;\n }\n }\n return nums;\n }\n}; \n``` | 0 | 0 | ['Bitmask', 'C++'] | 0 |
construct-the-minimum-bitwise-array-ii | Flip farthest 1 in right to left continuous sequence | flip-farthest-1-in-right-to-left-continu-ery6 | \nclass Solution {\npublic:\n vector<int> minBitwiseArray(vector<int>& nums) {\n vector <int> ans;\n for(auto & it : nums){\n if(it | xelladze | NORMAL | 2024-10-17T22:27:15.376044+00:00 | 2024-10-17T22:30:29.174215+00:00 | 2 | false | ```\nclass Solution {\npublic:\n vector<int> minBitwiseArray(vector<int>& nums) {\n vector <int> ans;\n for(auto & it : nums){\n if(it == 2)\n ans.push_back(-1);\n else{\n for(int i = 0; i < 32; i++){\n if((it & 1 << i) <= 0){\n ans.push_back(it ^ (1 << (i-1)));\n break;\n }\n }\n }\n }\n return ans;\n }\n};\n``` | 0 | 0 | [] | 0 |
construct-the-minimum-bitwise-array-ii | C++ || O(n) || Easy & Simple | c-on-easy-simple-by-ajay_makvana-x28e | Complexity\n- Time complexity: O(n * K)\n Add your time complexity here, e.g. O(n) \n\n- Space complexity: O(K)\n Add your space complexity here, e.g. O(n) \n\n | AJAY_MAKVANA | NORMAL | 2024-10-17T19:22:46.311713+00:00 | 2024-10-17T19:22:46.311737+00:00 | 8 | false | # Complexity\n- Time complexity: O(n * K)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(K)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n vector<int> minBitwiseArray(vector<int>& nums) {\n int n = nums.size();\n vector<int> ans(n, 0);\n vector<int> bits;\n for (int i = 0; i < n; i++) {\n if (!(nums[i] % 2)) {\n // even no.\n ans[i] = -1;\n continue;\n }\n bits.clear();\n while (nums[i]) {\n bits.push_back(nums[i] % 2);\n nums[i] /= 2;\n }\n bits.push_back(0);\n for (int j = 1; j < bits.size(); j++) {\n if (!bits[j]) {\n bits[j - 1] = 0;\n break;\n }\n }\n for (int j = 0; j < bits.size(); j++) {\n ans[i] += (bits[j] * pow(2, j));\n }\n }\n return ans;\n }\n};\n\n``` | 0 | 0 | ['C++'] | 0 |
construct-the-minimum-bitwise-array-ii | Few lines of code | few-lines-of-code-by-leeetforce-8lk7 | \n# Complexity\n- Time complexity:O(n)\n\n- Space complexity:O(n)\n\n# Code\ncpp []\nclass Solution {\npublic:\n vector<int> minBitwiseArray(vector<int>& num | Leeetforce | NORMAL | 2024-10-17T17:42:43.754093+00:00 | 2024-10-17T17:42:43.754134+00:00 | 1 | false | \n# Complexity\n- Time complexity:$$O(n)$$\n\n- Space complexity:$$O(n)$$\n\n# Code\n```cpp []\nclass Solution {\npublic:\n vector<int> minBitwiseArray(vector<int>& nums) {\n vector<int> ans;\n for(int&num:nums){\n if(num==2) ans.push_back(-1);\n else{\n int i=0;\n while(num&(1<<i)){\n i++;\n }\n ans.push_back(num&(~(1<<(i-1))));\n }\n }\n return ans;\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
construct-the-minimum-bitwise-array-ii | [C] | c-by-zhang_jiabo-50av | C []\nint * minBitwiseArray(\n\tconst int * const nums,\n\tconst int numsLen,\n\n\tint * const pRetsLen //out\n){\n\t*pRetsLen = numsLen;\n\tint * const rets = | zhang_jiabo | NORMAL | 2024-10-17T07:50:31.294287+00:00 | 2024-10-17T07:50:31.294322+00:00 | 2 | false | ```C []\nint * minBitwiseArray(\n\tconst int * const nums,\n\tconst int numsLen,\n\n\tint * const pRetsLen //out\n){\n\t*pRetsLen = numsLen;\n\tint * const rets = (int *)malloc(sizeof (int) * *pRetsLen);\n\n\tfor (int i = 0; i < numsLen; i += 1){\n\t\tif (nums[i] % 2 == 0){\n\t\t\trets[i] = -1;\n\t\t\tcontinue;\n\t\t}\n\n\t\tint mask = 1;\n\t\twhile ( (nums[i] & (mask << 1)) != 0 ){\n\t\t\tmask <<= 1;\n\t\t}\n\n\t\trets[i] = nums[i] & ~mask;\n\t}\n\n\treturn rets;\n}\n``` | 0 | 0 | ['C'] | 0 |
construct-the-minimum-bitwise-array-ii | || BIT MANIPULATION, IN ONE PASS O(N)|| | bit-manipulation-in-one-pass-on-by-anmol-lsgo | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \nSo , for even numbers t | anmol_050 | NORMAL | 2024-10-16T12:11:07.054492+00:00 | 2024-10-16T12:11:07.054530+00:00 | 6 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nSo , for even numbers those num has 0th bit not set so cannot find any ans[i] for them always -1 for them , as only prime numbers here so for 2 ans[i] has to be -1\n\n\nFor ODD numbers - if we have something like 23 - 10111 , so here we have possibilities to get this number from(10110 , 10101 , 10011) just make 0 for 1s who is in continuation from start point , now to choose the smallest one we have to make 0 to the farthest one , one with higher value .\nso for 23 - we choose 10011=>19\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n)\nbasically one traversal with 32 bit num so - 32*n\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n vector<int> minBitwiseArray(vector<int>& nums) {\n vector<int>ans;\n for(int i=0 ; i<nums.size() ; i++){\n int step=0;\n int temp=nums[i];\n if(temp==2){\n ans.push_back(-1);\n continue;\n }\n while(temp>0){\n if(temp&1){\n step++;\n temp>>=1;\n }\n else{break;}\n }\n int a= 1;\n a<<=(step-1);\n nums[i]^=a;\n ans.push_back(nums[i]);\n\n\n }\n return ans;\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
construct-the-minimum-bitwise-array-ii | Bitwise Greedy | bitwise-greedy-by-parteek_coder-kkol | Code\ncpp []\nclass Solution {\npublic:\n vector<int> minBitwiseArray(vector<int>& nums) {\n int n = nums.size();\n vector<int>ans(n,-1);\n | parteek_coder | NORMAL | 2024-10-16T08:11:28.049264+00:00 | 2024-10-16T08:11:28.049299+00:00 | 6 | false | # Code\n```cpp []\nclass Solution {\npublic:\n vector<int> minBitwiseArray(vector<int>& nums) {\n int n = nums.size();\n vector<int>ans(n,-1);\n for(int i=0;i<n;i++){\n if(nums[i]==2) ans[i]=-1;\n else {\n int j=1;\n while(j<32 && ((1<<j)&nums[i])) j++;\n ans[i] = nums[i]^(1<<(j-1));\n }\n }\n return ans;\n }\n};\n``` | 0 | 0 | ['Greedy', 'Bit Manipulation', 'C++'] | 0 |
construct-the-minimum-bitwise-array-ii | BEAT 100% ULTRA SHORT, EASY BRUTE - FORCE APPROACH ✅✅ | beat-100-ultra-short-easy-brute-force-ap-w3ik | BEAT 100%\n\n\n# Code\ncpp []\nclass Solution {\npublic:\n vector<int> minBitwiseArray(vector<int>& nums) {\n for (int i = 0; i < nums.size(); i++) {\ | Nitansh_Koshta | NORMAL | 2024-10-15T14:04:57.462604+00:00 | 2024-10-15T14:04:57.462638+00:00 | 0 | false | # BEAT 100%\n\n\n# Code\n```cpp []\nclass Solution {\npublic:\n vector<int> minBitwiseArray(vector<int>& nums) {\n for (int i = 0; i < nums.size(); i++) {\n if (nums[i] % 2 == 0)\n nums[i] = -1;\n else\n nums[i] = nums[i] - ((nums[i] + 1) & (-nums[i] - 1)) / 2;\n }\n return nums;\n }\n};\n```\n\n# --- PLEASE UPVOTE SIR ---\n\n | 0 | 0 | ['C++'] | 0 |
construct-the-minimum-bitwise-array-ii | Beats 100.00% on time & 100.00% on memory | 1-liner | beats-10000-on-time-10000-on-memory-1-li-49u9 | \n\ntypescript []\nfunction minBitwiseArray(nums: number[]): number[] {\n return nums.map((num) => (num === 2 ? -1 : (((-num - 2) ^ num) >> 2) + num))\n}\n | NicholasGreenwood | NORMAL | 2024-10-15T12:53:25.900768+00:00 | 2024-10-15T12:53:25.900791+00:00 | 1 | false | \n\n```typescript []\nfunction minBitwiseArray(nums: number[]): number[] {\n return nums.map((num) => (num === 2 ? -1 : (((-num - 2) ^ num) >> 2) + num))\n}\n``` | 0 | 0 | ['TypeScript'] | 0 |
construct-the-minimum-bitwise-array-ii | ✅FINDING RIGHTMOST UNSET BIT🔥🔥 | finding-rightmost-unset-bit-by-amarnatht-nbxk | Intuition\n Describe your first thoughts on how to solve this problem. \nThe goal of this function is to modify each element in the given array nums \nbased on | amarnathtripathy | NORMAL | 2024-10-15T11:50:27.581991+00:00 | 2024-10-15T11:50:27.582017+00:00 | 2 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe goal of this function is to modify each element in the given array `nums` \nbased on certain bitwise operations. The modification is aimed at finding a \nsmaller number by flipping the rightmost unset bit. The function handles a \nspecial case where the number is 2, returning -1. For other numbers, it searches \nfor the lowest unset bit (starting from the least significant bit) and flips \nthe bit just before it. \n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Create a vector `ans` to store the results.\n2. Loop through each element `i` in the input vector `nums`:\n - If `i` is 2, push -1 to the result vector `ans`.\n - Otherwise, loop from bit position 1 to 30:\n - Check if the bit at position `j` is unset in `i` using `(i & (1 << j))`.\n - If the bit is set, continue to the next position.\n - If the bit is unset, flip the bit at position `j-1` using `i ^ (1 << (j-1))`\n and push the modified value to `ans`. Break out of the loop.\n3. Return the vector `ans` containing the modified values.\n# Complexity\n- Time complexity:O(N * 31)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(N)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n vector<int> minBitwiseArray(vector<int>& nums) {\n vector<int> ans;\n for(int i:nums){\n if(i==2){\n ans.push_back(-1);\n }else{\n for(int j=1;j<31;j++){\n if(i&(1<<j)){\n continue;\n }else{\n ans.push_back(i^(1<<(j-1)));\n break;\n }\n }\n }\n }\n return ans;\n }\n};\n``` | 0 | 0 | ['Array', 'Bit Manipulation', 'C++'] | 0 |
construct-the-minimum-bitwise-array-ii | VERY EASY SOLUTION||C++||BIT_MANIPULATION | very-easy-solutioncbit_manipulation-by-s-z46q | 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 | spidee180 | NORMAL | 2024-10-15T10:55:28.405031+00:00 | 2024-10-15T10:55:28.405055+00:00 | 5 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n vector<int> minBitwiseArray(vector<int>& nums) {\n //when we do nums|nums + 1 example 10100111 + 10101111 = 10101111\n // we observe that it sets till leftmost 0 bit \n // if nums[i] leftmost bit is 0 then there will be no ans[i]\n // because if ans[i] has leftmost bit 0 then it will be set after\n // ans[i] | ans[i+1] if leftmost bit is 1 then also ans[i]|ans[i+1]\n // will give 1 as leftmost bit\n // if nums[i] has trailing ones then ans could be formed by converting \n // any of them to 0 , so we need to set leftmost trailing 1 to 0 to get\n // least value of ans\n vector<int>ans;\n for(int num : nums)\n {\n if(num%2 == 0)\n {\n ans.push_back(-1);\n continue;\n }\n int i;\n cout<<num<<endl;\n for( i = 0; i < 31; i++)\n {\n // to get ith bit num &( 1 << i)\n if(!(num & (1 << i))) break;\n }\n // cout<<"I "<<i<<endl;\n // to invert i-1 th bit we use xor ^ operation\n ans.push_back(num ^ (1 << (i-1)));\n \n }\n return ans;\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
construct-the-minimum-bitwise-array-ii | Java - simple - unset each bit - approach | java-simple-unset-each-bit-approach-by-t-ulfk | 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 | tanmayrsm | NORMAL | 2024-10-15T10:48:44.762878+00:00 | 2024-10-15T10:48:44.762899+00:00 | 3 | 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(nlogB)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```java []\nclass Solution {\n public int[] minBitwiseArray(List<Integer> nums) {\n int n = nums.size(), k = 0;\n int[] ans = new int[n];\n for(Integer num : nums)\n ans[k++] = getBitwiseItem(num);\n return ans;\n }\n private int getBitwiseItem(int no) {\n char[] binStr = Integer.toBinaryString(no).toCharArray();\n int n = binStr.length;\n if(binStr[n - 1] == \'0\') return -1; // even no\n for(int i = 0; i < n; i++) {\n if(binStr[i] == \'1\') {\n char[] newer = new char[n];\n for(int j = 0; j < n; j++)\n if(j == i)\n newer[j] = \'0\';\n else newer[j] = binStr[j];\n int newNo = Integer.parseInt(new String(newer), 2);\n if((newNo | newNo + 1) == no) return newNo;\n }\n }\n return no / 2;\n }\n}\n``` | 0 | 0 | ['Java'] | 0 |
construct-the-minimum-bitwise-array-ii | Easy solution but hard to come up with | easy-solution-but-hard-to-come-up-with-b-w8cn | Intuition\nThe goal of this solution is to unset (toggle) the last consecutive set bit (the rightmost sequence of 1s) in each number of the given array using XO | Aarav_vaish | NORMAL | 2024-10-15T06:47:05.083700+00:00 | 2024-10-15T06:47:05.083745+00:00 | 4 | false | # Intuition\nThe goal of this solution is to unset (toggle) the last consecutive set bit (the rightmost sequence of 1s) in each number of the given array using XOR. \n\nThe last consecutive 1 bit is the rightmost bit in a sequence of 1s. Unsetting this bit (changing it from 1 to 0) often results in the smallest possible reduction in the number\'s value, because this bit represents the smallest power of two in that sequence.\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n vector<int> minBitwiseArray(vector<int>& nums) {\n int n = nums.size();\n vector<int> ans;\n for (int i = 0; i < n; i++) {\n int num = nums[i];\n int j = 0;\n if(nums[i]==2){\n ans.push_back(-1);\n continue;\n }\n while (num & (1 << j)) {\n j++;\n }\n num = (num ^ (1 << j-1));\n ans.push_back(num);\n }\n return ans;\n }\n};\n\n``` | 0 | 0 | ['C++'] | 0 |
construct-the-minimum-bitwise-array-ii | [C++] Set the bit before the rightmost zero to zero with xor. | c-set-the-bit-before-the-rightmost-zero-cc72u | \ncpp []\nclass Solution {\npublic:\n vector<int> minBitwiseArray(vector<int>& nums) {\n int n = nums.size();\n vector<int> ans;\n\n for | lovebaonvwu | NORMAL | 2024-10-15T01:11:54.012481+00:00 | 2024-10-15T01:11:54.012507+00:00 | 4 | false | \n```cpp []\nclass Solution {\npublic:\n vector<int> minBitwiseArray(vector<int>& nums) {\n int n = nums.size();\n vector<int> ans;\n\n for (auto p : nums) {\n if (p % 2 == 0) {\n ans.push_back(-1);\n } else {\n for (int i = 1; i < 31; ++i) {\n if ((p & (1 << i)) == 0) {\n p = p ^ (1 << (i - 1));\n break;\n }\n }\n ans.push_back(p);\n }\n }\n\n return ans;\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
construct-the-minimum-bitwise-array-ii | JAVA 1ms(100%) with O(N*logV) | java-1ms100-with-onlogv-by-meringueee-0o17 | 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 | meringueee | NORMAL | 2024-10-15T00:04:01.194975+00:00 | 2024-10-15T00:04:01.195003+00:00 | 4 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```java []\nclass Solution {\n public int[] minBitwiseArray(List<Integer> n) {\n int[] a = new int[n.size()];\n for(int i=0; i<a.length; i++){\n if(n.get(i)==2)a[i]=-1;\n else a[i]=n.get(i)-find(n.get(i));\n }\n return a;\n }\n private int find(int x){\n int y=1;\n while((x&y)>0)y<<=1;\n return y>>1;\n }\n}\n``` | 0 | 0 | ['Java'] | 0 |
construct-the-minimum-bitwise-array-ii | Easy C++ || Bitwise Operations || Beats 100% | easy-c-bitwise-operations-beats-100-by-y-ulm7 | Code\ncpp []\nclass Solution {\npublic:\n vector<int> minBitwiseArray(vector<int>& a) {\n int n = a.size();\n vector<int> ans(n, -1);\n | yoyobuzz | NORMAL | 2024-10-14T20:20:17.489901+00:00 | 2024-10-14T20:20:17.489929+00:00 | 21 | false | # Code\n```cpp []\nclass Solution {\npublic:\n vector<int> minBitwiseArray(vector<int>& a) {\n int n = a.size();\n vector<int> ans(n, -1);\n for(int i=0; i<n; i++){\n if(a[i] == 2) continue;\n int last = -1;\n for(int j = 0; j <=30; j++){\n if( ((a[i]>>j) & (1)) == 0) break;\n else last++;\n }\n // cout<<last<<" ";\n ans[i] = ((a[i]^(1<<last)));\n }\n return ans;\n }\n};\n\n#pragma GCC optimize("O3", "unroll-loops")\n\nauto init = [](){\n std::ios::sync_with_stdio(0);\n cin.tie(0);\n cout.tie(0);\n return 0;\n}();\n``` | 0 | 0 | ['C++'] | 1 |
construct-the-minimum-bitwise-array-ii | pro c++ code || time complexity O(N) || space complexity O(1)||simple bitmask observation | pro-c-code-time-complexity-on-space-comp-nnq5 | Intuition\njust observe and try to visualise every testcases given at start point\nby changing them into bits\n\n# Approach\n Describe your approach to solving | Md_Imtiyaz | NORMAL | 2024-10-14T16:28:56.344149+00:00 | 2024-10-14T16:28:56.344181+00:00 | 6 | false | # Intuition\njust observe and try to visualise every testcases given at start point\nby changing them into bits\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n- O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n- O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\n\nprivate:\n int findOperation(int n) {\n int k = n;\n int m = 1;\n int i = 0;\n while (k & 1) {\n if (i >= 1) {\n m = m << 1;\n }\n k = k >> 1;\n i++;\n }\n return n ^ m;\n }\n\npublic:\n vector<int> minBitwiseArray(vector<int>& nums) {\n vector<int> ans;\n int n = nums.size();\n for (int i = 0; i < n; i++) {\n if (nums[i] == 2)\n ans.push_back(-1);\n else {\n int m = findOperation(nums[i]);\n ans.push_back(m);\n }\n }\n\n return ans;\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
construct-the-minimum-bitwise-array-ii | [C++][Bit manipulation] | cbit-manipulation-by-mumrocks-u0q4 | \n\n# Code\ncpp []\nclass Solution {\n inline int minBitwise(const int n){\n if (n==2) return -1;\n\n int idx=0;\n while ((n & (1<<idx)) | MumRocks | NORMAL | 2024-10-14T15:49:51.749608+00:00 | 2024-10-14T15:49:51.749629+00:00 | 0 | false | \n\n# Code\n```cpp []\nclass Solution {\n inline int minBitwise(const int n){\n if (n==2) return -1;\n\n int idx=0;\n while ((n & (1<<idx))!=0) idx++;\n idx--;\n\n int mask = ~(1<<idx);\n return (n&mask);\n }\npublic:\n vector<int> minBitwiseArray(vector<int>& nums) {\n vector<int> ans;\n for (const auto n: nums) ans.push_back(minBitwise(n));\n return ans;\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
construct-the-minimum-bitwise-array-ii | O(32N) PrefixBit | python-brute-force-o32n-prefixbit-beats-oge0x | IntuitionWant: ans[i] OR (ans[i] + 1) == nums[i]Prime means all odd, except 2
So at least (p-1)|p==p (trivial root)We brute force all possible prefix|prefix-1 a | justinleung0204 | NORMAL | 2024-10-14T14:40:10.525469+00:00 | 2025-02-15T18:15:22.831437+00:00 | 7 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
Want: ans[i] OR (ans[i] + 1) == nums[i]
Prime means all odd, except 2
So at least (p-1)|p==p (trivial root)
We brute force all possible prefix|prefix-1 and return the smallest
101101
prefix|(prefix-1)
100000|011111 smallest prefix
101000|100111
101100|101011
101101|101100 largest prefix (trivial match)
TC: O(NlogMAX) = O(32N)
# Code
```python3 []
class Solution:
def minBitwiseArray(self, nums: List[int]) -> List[int]:
N=len(nums)
ans=[]
B=32
def get(i):#get smallest j s.t. j|j+1==i
prefix = 0
for b in range(B-1,-1,-1):
prefix|= i&(1<<b)
if prefix>0 and prefix|(prefix-1)==i:
return prefix-1
return -1
for i in range(N):
ans.append(get(nums[i]))
return ans
``` | 0 | 0 | ['Bit Manipulation', 'Prefix Sum', 'Python3'] | 0 |
construct-the-minimum-bitwise-array-ii | C++ Solution (Simple and easy to understand) | c-solution-simple-and-easy-to-understand-dak8 | Intuition\n Describe your first thoughts on how to solve this problem. \nThis problem follow a specific pattern.\n# Approach\n Describe your approach to solving | hazemkhairat4 | NORMAL | 2024-10-14T12:10:44.110925+00:00 | 2024-10-14T12:10:44.110948+00:00 | 8 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThis problem follow a specific pattern.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nThe pattern is to continue shifting the number until you find 0 to the right, and you must have a counter to count how much you have done this operation, then subtract 1 after shifting it to the left count - 1 times, example (1 << (count - 1) from the original number, example (11 - (1 << (count - 1)), then push this into your answer array.\n# Complexity\n- Time complexity: O(NlogK)\n> Where K is the largest number in nums.\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n> We do not need additional space to the answer array.\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n vector<int> minBitwiseArray(vector<int>& nums) {\n vector<int> ans;\n\n for (auto num : nums) {\n int count = 0;\n\n while ((num & (1 << count))) {\n count++;\n }\n\n num == 2 ? ans.push_back(-1)\n : ans.push_back(num - (1 << (count - 1)));\n }\n\n return ans;\n }\n};\n``` | 0 | 0 | ['Bit Manipulation', 'C++'] | 0 |
construct-the-minimum-bitwise-array-ii | Python 3 fast solution | python-3-fast-solution-by-fm2alexei-vunm | 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 | fm2alexei | NORMAL | 2024-10-14T10:24:03.422259+00:00 | 2024-10-14T10:24:03.422282+00:00 | 4 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```python3 []\nclass Solution:\n\n\tdef _xor(self, n: int) -> int:\n\t\tif n&1:\n\t\t\tm = (n>>1) + 1\n\t\t\treturn n - (m&-m)\n\t\telse:\n\t\t\treturn -1\n\n\tdef minBitwiseArray(self, nums: list[int]) -> list[int]:\n\t\treturn map(self._xor, nums)\n\n``` | 0 | 0 | ['Bit Manipulation', 'Python3'] | 0 |
construct-the-minimum-bitwise-array-ii | One of the Easiest solution With explanation | C++| Beats 100% | one-of-the-easiest-solution-with-explana-c01t | 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 | Rohit_Kumar_Srivastava | NORMAL | 2024-10-14T09:29:10.938921+00:00 | 2024-10-14T09:29:10.938989+00:00 | 8 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\n\n\n/*\n LOGIC: \n 1). First to find the first unset bit of nums[i]. eg 0101 ,2nd position is the first unset bit i:e 0\n ^\n |\n 2). simply change that bit which are present just before the first unset bit. eg: 0 1 0 1\n index: 3 2 1 0 ,simply change the zero index bit\n*/\n\nclass Solution {\npublic:\n vector<int> minBitwiseArray(vector<int>& nums) {\n vector<int> ans;\n for(int i=0;i<nums.size();i++)\n {\n if(nums[i]==2)\n ans.push_back(-1);\n\n \n else{\n int j=0;\n int n=nums[i];\n while(n!=0)\n {\n if(((n)&(1))==0)\n {\n break;\n }\n n= n>>1;\n j++;\n }\n j--;\n int k=1;\n ans.push_back(((nums[i])&(~(k<<j))));\n } \n }\n return ans;\n }\n};\n\n// 47 101111\n// 45 101101\n// 39 100111\n\n// 0010 0011 0101 0111\n\n// 0001\n// 0100\n\n// 0011\n\n// 11\n// 1011\n// 0010\n// 1101\n\n// 9\n// 1001\n\n// 13\n// 1101\n\n// 0111\n\n\n// 17\n// 10001\n\n// 19\n// 10011\n\n// 15\n\n\n\n\n``` | 0 | 0 | ['C++'] | 0 |
construct-the-minimum-bitwise-array-ii | easy c++ solution | easy-c-solution-by-zachisworking-802n | Intuition\neverything written in code\n\n# Code\ncpp []\n#include <vector>\nusing namespace std;\n\nclass Solution {\npublic:\n vector<int> minBitwiseArray(v | ZAChisworking | NORMAL | 2024-10-13T17:27:36.184943+00:00 | 2024-10-13T17:27:36.184976+00:00 | 11 | false | # Intuition\neverything written in code\n\n# Code\n```cpp []\n#include <vector>\nusing namespace std;\n\nclass Solution {\npublic:\n vector<int> minBitwiseArray(vector<int>& nums) {\n vector<int> ans;\n int n = nums.size();\n\n for (int i = 0; i < n; i++) {\n if (nums[i] % 2 == 0) {\n ans.push_back(-1); // Handle even numbers\n } else {\n int num = nums[i];\n\n for (int j = 0; j < 64; j++) {\n // Check if the current bit is set\n if (num & (1 << j)) {\n // If the next bit is 0 or this is the last bit, clear the current bit\n if (!(num & (1 << (j + 1)))) {\n num &= ~(1 << j); // Clear the current bit\n break; // Exit after clearing the bit\n }\n } else {\n // If we encounter a 0 after starting the sequence, stop the loop\n break;\n }\n }\n\n ans.push_back(num); // Store the modified number\n }\n }\n \n return ans;\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
construct-the-minimum-bitwise-array-ii | C++ solution bit manipulation | c-solution-bit-manipulation-by-oleksam-e653 | \n// Please, upvote if you like it. Thanks :-)\nvector<int> minBitwiseArray(vector<int>& nums) {\n\tint n = nums.size();\n\tvector<int> res(n, 10e8);\n\tfor (in | oleksam | NORMAL | 2024-10-13T16:12:58.110768+00:00 | 2024-10-13T16:12:58.110803+00:00 | 0 | false | ```\n// Please, upvote if you like it. Thanks :-)\nvector<int> minBitwiseArray(vector<int>& nums) {\n\tint n = nums.size();\n\tvector<int> res(n, 10e8);\n\tfor (int i = 0; i < n; i++) {\n\t\tif (nums[i] & 1) {\n\t\t\tbitset<32> bs(nums[i]);\n\t\t\tfor (int j = 0; j < 31; j++) {\n\t\t\t\tauto copy = bs;\n\t\t\t\tcopy.set(j, false);\n\t\t\t\tif (((int)copy.to_ulong() | ((int)copy.to_ulong() + 1)) == nums[i])\n\t\t\t\t\tres[i] = min(res[i], (int)copy.to_ulong());\n\t\t\t}\n\t\t}\n\t\telse\n\t\t\tres[i] = -1;\n\t}\n\treturn res;\n}\n``` | 0 | 0 | ['Array', 'Bit Manipulation', 'C', 'Bitmask', 'C++'] | 0 |
construct-the-minimum-bitwise-array-ii | C++ bitwise solution | c-bitwise-solution-by-nguyenchiemminhvu-od3f | \nstatic bool fastIO = []()\n{\n std::cin.tie(0)->sync_with_stdio(false);\n return true;\n}();\n\nclass Solution\n{\npublic:\n vector<int> minBitwiseAr | nguyenchiemminhvu | NORMAL | 2024-10-13T15:02:40.017944+00:00 | 2024-10-13T15:02:40.017969+00:00 | 5 | false | ```\nstatic bool fastIO = []()\n{\n std::cin.tie(0)->sync_with_stdio(false);\n return true;\n}();\n\nclass Solution\n{\npublic:\n vector<int> minBitwiseArray(vector<int>& nums)\n {\n std::vector<int> res(nums.size(), -1);\n for (int i = 0; i < nums.size(); i++)\n {\n int count_trailing_1 = countTrailingZerosUntilBit0(nums[i]);\n if (count_trailing_1 == 0)\n {\n continue;\n }\n\n res[i] = nums[i] & (~(1 << count_trailing_1 - 1));\n }\n\n return res;\n }\nprivate:\n int countTrailingZerosUntilBit0(int num)\n {\n int count = 0;\n while (num & 1)\n {\n count++;\n num >>= 1;\n }\n return count;\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
construct-the-minimum-bitwise-array-ii | Time complexity : 31 times O(N) | 2 ms Beats 100.00% | time-complexity-31-times-on-2-ms-beats-1-98sy | Intuition\n for value = 7 \n we can find a number such that : num | (num + 1) = value\nby setting any one bit of value\'s binary representation from 1 to 0.\nT | AddDeepanshuVerma | NORMAL | 2024-10-13T14:08:52.320654+00:00 | 2024-10-13T14:08:52.320713+00:00 | 8 | false | # Intuition\n for value = 7 \n we can find a number such that : num | (num + 1) = value\nby setting any one bit of value\'s binary representation from 1 to 0.\nTo find the minimum, start from 31st bit and which ever number we get after turning any one bit from 1 to 0, does prove our given condition is the answer\nHence for any number we just need at max 31 comparision to find desired value.\n\n\n\n\n\n# Code\n```java []\nclass Solution {\n public int[] minBitwiseArray(List<Integer> nums) {\n int[] ans = new int[nums.size()];\n int i = 0;\n for (int num : nums) {\n ans[i++] = getMinValue(num);\n }\n return ans;\n }\n\n private int getMinValue(int num) {\n int ans = -1;\n for (int i = 31; i >= 0; i--) {\n if (((num >> i) & 1) == 1) {\n // this bit is 1, now change this bit to 0 and check if update number is valid or not\n int temp = (1 << i) ^ num;\n if (isValid(temp, num)) {\n return temp;\n }\n }\n }\n return ans;\n }\n\n private boolean isValid(int temp, int num) {\n return (temp | (temp + 1)) == num;\n }\n}\n``` | 0 | 0 | ['Math', 'Bit Manipulation', 'Java'] | 0 |
construct-the-minimum-bitwise-array-ii | Easy Solution using Bit Manipulation | easy-solution-using-bit-manipulation-by-7u399 | 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 | J_P_11 | NORMAL | 2024-10-13T13:49:10.982171+00:00 | 2024-10-13T13:50:04.802993+00:00 | 7 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\n#define isBit1(x,i) ((x >> i) & 1)\nclass Solution {\npublic:\ninline int setBit1(int x, int i) {\n return (x | (1 << i));\n }\n inline int setBit0(int x, int i) {\n return (x & ~(1 << i));\n }\n\n int fun(int n)\n {\n if(n==2) return -1;\n int i=0,a=n,b=n;\n\n for(i=0;i<32;i++)\n {\n if(!isBit1(n,i)) break;\n }\n bool x=true;\n for(int j=i-1;j>=0;j--)\n {\n if(x)\n {\n a=setBit0(a,j);\n x=false;\n }\n else\n {\n b=setBit0(b,j);\n }\n }\n return min(a,b);\n }\n\n vector<int> minBitwiseArray(vector<int>& n) {\n vector<int> v;\n for(int i=0;i<n.size();i++)\n {\n v.push_back(fun(n[i]));\n }\n return v;\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
construct-the-minimum-bitwise-array-ii | c++ solution | c-solution-by-dilipsuthar60-ez2n | \nclass Solution {\npublic:\n vector<int> minBitwiseArray(vector<int>& nums) {\n int n=nums.size();\n vector<int>ans(n,0);\n for(int i=0 | dilipsuthar17 | NORMAL | 2024-10-13T12:46:20.940715+00:00 | 2024-10-13T12:58:34.660460+00:00 | 13 | false | ```\nclass Solution {\npublic:\n vector<int> minBitwiseArray(vector<int>& nums) {\n int n=nums.size();\n vector<int>ans(n,0);\n for(int i=0;i<n;i++){\n int result=1e9;\n for(int j=0;j<31;j++){\n if(nums[i]&(1<<j)){\n int k=nums[i]-(1<<j);\n if((k|(k+1))==nums[i]){\n result=min(result,k);\n }\n }\n }\n ans[i]=(result==1e9)?-1:result;\n }\n return ans;\n }\n};\n``` | 0 | 0 | ['C', 'C++'] | 0 |
construct-the-minimum-bitwise-array-ii | BEST PYTHON SOLUTION WITH 59MS OF RUNTIME ! | best-python-solution-with-59ms-of-runtim-fmi9 | \n# Code\npython3 []\nclass Solution:\n def minBitwiseArray(self, nums: List[int]) -> List[int]:\n ans = [0] * len(nums) # Initialize ans array\n | rishabnotfound | NORMAL | 2024-10-13T10:33:21.482275+00:00 | 2024-10-13T10:33:21.482310+00:00 | 7 | false | \n# Code\n```python3 []\nclass Solution:\n def minBitwiseArray(self, nums: List[int]) -> List[int]:\n ans = [0] * len(nums) # Initialize ans array\n for i, num in enumerate(nums):\n # Convert the number to binary (without the \'0b\' prefix)\n b = bin(num)[2:]\n \n # If the number ends with \'0\', it is impossible to find such x\n if b[-1] == \'0\':\n ans[i] = -1\n continue\n \n # Count consecutive trailing \'1\'s in the binary representation\n count = 0\n for k in range(-1, -len(b) - 1, -1):\n if b[k] == \'1\':\n count += 1\n else:\n break\n \n # The index of the first bit that is not part of the trailing \'1\'s\n front = len(b) - count\n \n # Form the result by turning the last \'1\' into a \'0\' and keeping other bits the same\n ans[i] = int(b[:front] + \'0\' + (\'1\' * (count - 1)), 2)\n \n return ans\n\n``` | 0 | 0 | ['Python3'] | 0 |
construct-the-minimum-bitwise-array-ii | 📌 C++ || 7 Lines || Faster 96% | c-7-lines-faster-96-by-t86-z771 | Intuition\n- Basically, the problem is broken down to for only even number\n\t- If we have the 01 pattern in binary, then convert it to 00\n\t- Example, 11111 - | t86 | NORMAL | 2024-10-13T10:12:48.137445+00:00 | 2024-10-13T10:12:48.137484+00:00 | 11 | false | **Intuition**\n- Basically, the problem is broken down to for only `even` number\n\t- If we have the `01` pattern in binary, then convert it to `00`\n\t- Example, `11111` -> `01111`, `1010101` -> `1010100`, `10111` -> `10011`\n\n**Code**\n```c++\nvector<int> minBitwiseArray(vector<int>& nums) {\n vector<int> res;\n auto solve = [](int& i) {\n auto str = bitset<64>(i).to_string();\n for (int i = str.size() - 1; i > 0; i--) \n if (str[i - 1] == \'0\' && str[i] == \'1\') {\n str[i] = \'0\';\n return stoi(str, nullptr, 2);\n }\n throw "error";\n };\n \n for (auto num: nums) \n if (num & 1) res.push_back( solve(num) ); \n else res.push_back(-1);\n return res;\n}\n```\n\n**Complexity**\n`Time`: O(n)\n`Space`: O(n)\n\n**For more solutions and concepts, check out this \uD83D\uDCD6 [BLOG](https://github.com/MuhtasimTanmoy/notebook) and \uD83C\uDFC6 [GITHUB REPOSITORY](https://github.com/MuhtasimTanmoy/playground) with over 2000+ solutions.** | 0 | 0 | ['C'] | 0 |
construct-the-minimum-bitwise-array-ii | Fast and simple O(n) solution | fast-and-simple-on-solution-by-waxm-mx1z | Intuition\nThe key to understanding the solution is the realize that for a given number the answer will vary only by a single set bit if at all such a number ex | waxm | NORMAL | 2024-10-13T09:53:22.598366+00:00 | 2024-10-13T09:53:22.598390+00:00 | 4 | false | # Intuition\nThe key to understanding the solution is the realize that for a given number the answer will vary only by a single set bit if at all such a number exists. \n\n# Approach\nLet\'s consider the number 13 for which we want to find the answer.\n\nThe number 13 in binary is 1101.\n\nWe can find variations for the binary representation of 13 by unsetting each set bit in 1101.\n\nThe possible variations include:\n1100 - 12\n1001 - 9\n0101 - 5\n\nWe can find if a bit is set at a position `x` for a number `num` by using: `((num >> x) & 1) == 1` \n\nWe can unset a bit at a position `x` for a number `num` by using: `(1 << x) ^ num` \n\nFor each of these numbers, we can OR with itself +1 and if it results to the original number 13, then we have found a possible answer. We will then pick the minimum of all possible answers. \n\n# Complexity\n- Time complexity:\nO(n)\n\nAlthought for each iteration of n, we loop 32 times to check each position in the binary representation of `nums[i]`, this is not included in the time complexity because it is constant. \n\n- Space complexity:\nO(1)\n\nWe are not including the space we use for creating the answer array.\n\n# Code\n```typescript []\nfunction minBitwiseArray(nums: number[]): number[] {\n const ans: number[] = [];\n for (const num of nums) {\n let min = Infinity;\n for (let i = 0; i < 32; ++i) {\n if (((num >> i) & 1) === 1) {\n const mask = 1 << i;\n const n = mask ^ num;\n if ((n | (n + 1)) === num) {\n min = Math.min(n, min);\n }\n }\n }\n\n ans.push(min === Infinity ? -1 : min);\n }\n\n return ans;\n};\n``` | 0 | 0 | ['TypeScript'] | 0 |
construct-the-minimum-bitwise-array-ii | Simple bit manipulation | O(n) | simple-bit-manipulation-on-by-kavishgupt-xcbe | 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 | kavishgupta2011 | NORMAL | 2024-10-13T09:51:04.091435+00:00 | 2024-10-13T09:51:04.091467+00:00 | 14 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n vector<int> minBitwiseArray(vector<int>& nums) {\n int n=nums.size();\n vector<int>ans;\n for(int i=0;i<n;i++){\n if(nums[i]==2){\n ans.push_back(-1);\n }\n else{\n int cnt=0;\n //cout<<nums[i];\n int em=nums[i];\n while(nums[i]>0 &&nums[i]%2==1){\n nums[i]/=2;\n cnt++;\n }\n cnt--;\n //cout<<" "<<cnt<<" "<<(1<<cnt)<<endl;\n ans.push_back(em- (1<<cnt));\n }\n }\n return ans;\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
construct-the-minimum-bitwise-array-ii | Simple Observation Using Bit Manipulation | simple-observation-using-bit-manipulatio-c2b1 | 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 | catchme999 | NORMAL | 2024-10-13T09:14:20.191749+00:00 | 2024-10-13T09:14:20.191773+00:00 | 5 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n vector<int> minBitwiseArray(vector<int>& nums) {\n vector<int> ans;\n for (auto i : nums) {\n if (i == 2) {\n ans.push_back(-1);\n continue;\n }\n for (int j = 1; j < 32; j++) {\n if ((i>>j)&1==1)\n continue;\n ans.push_back(i ^ (1 << (j - 1)));\n break;\n }\n }\n return ans;\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
construct-the-minimum-bitwise-array-ii | Easy to understand code!!! | easy-to-understand-code-by-daminrido139-whsc | Intuition\n Describe your first thoughts on how to solve this problem. \nObserving pattern for various inputs is the key to solve this problem.\n# Approach\n De | chicken_strips | NORMAL | 2024-10-13T08:58:17.674351+00:00 | 2024-10-13T08:58:17.674370+00:00 | 0 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nObserving pattern for various inputs is the key to solve this problem.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n.................Input............ Answer.............\n.................1111...............111..................\n.................101................100..................\n................1011...............1001................\n................10111..............10011..............\n..........1010101111.......1010100111........\n# Complexity\n- Time complexity:$$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:$$O(n)$$ for storing result\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```python3 []\nclass Solution:\n def minBitwiseArray(self, nums: List[int]) -> List[int]:\n ans = []\n for x in nums:\n if x==2:\n ans.append(-1)\n else:\n val = bin(x)[2:]\n ind = val.rfind("0")\n if ind == -1:\n ans.append(int(val[1:],2))\n else:\n ans.append(int(val[:ind+1]+"0"+val[ind+2:],2))\n\n return ans\n\n \n``` | 0 | 0 | ['Python3'] | 0 |
construct-the-minimum-bitwise-array-ii | bit manipulation | bit-manipulation-by-swatilohiya0343-cait | 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 | swatilohiya0343 | NORMAL | 2024-10-13T08:37:39.394397+00:00 | 2024-10-13T08:37:39.394424+00:00 | 5 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```python3 []\nclass Solution:\n def minBitwiseArray(self, nums: List[int]) -> List[int]:\n n=len(nums)\n ans=[]\n for i in range(n):\n mini=float("inf")\n for j in range(32):\n temp=nums[i] & ~(1 << (j))\n if temp |(temp+1)==nums[i]:\n mini=min(mini,temp)\n if mini==float("inf"):\n mini=-1\n ans.append(mini)\n return ans\n \n``` | 0 | 0 | ['Bit Manipulation', 'Python3'] | 0 |
construct-the-minimum-bitwise-array-ii | Python || Simple solution | python-simple-solution-by-vilaparthibhas-i2hh | 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 | vilaparthibhaskar | NORMAL | 2024-10-13T07:45:02.058738+00:00 | 2024-10-13T07:45:02.058786+00:00 | 6 | 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)$$ -->\no(n)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\no(n)\n\n# Code\n```python3 []\nclass Solution:\n def minBitwiseArray(self, nums: List[int]) -> List[int]:\n ans = [0] * len(nums)\n for i, j in enumerate(nums):\n b = bin(j)[2:]\n if b[-1] == \'0\':\n ans[i] = -1\n continue\n count = 0\n for k in range(-1, -len(b) - 1, -1):\n if b[k] == \'1\':\n count += 1\n else:\n break\n front = len(b) - count\n ans[i] = int(b[:front] + \'0\' + (\'1\' * (count - 1)), 2)\n return ans\n \n``` | 0 | 0 | ['Bit Manipulation', 'Python3'] | 0 |
construct-the-minimum-bitwise-array-ii | c++(0ms) only bit manipulations | c0ms-only-bit-manipulations-by-zx007pi-26cg | 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 | zx007pi | NORMAL | 2024-10-13T07:36:52.530029+00:00 | 2024-10-13T07:36:52.530057+00:00 | 5 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n vector<int> minBitwiseArray(vector<int>& nums) {\n vector<int> ans(nums.size());\n\n for(int i = 0; i != nums.size(); i++){\n long n = nums[i], x = 1;\n ans[i] = -1;\n while(x <= n) x <<= 1;\n \n long mask = (x >>= 1);\n for(; x; x >>= 1)\n if( (x & n) ){\n mask |= x;\n if( (mask | (mask -1)) == n){\n ans[i] = mask - 1;\n break;\n } \n } \n }\n\n return ans; \n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
transform-to-chessboard | [C++/Java/Python] Solution with Explanation | cjavapython-solution-with-explanation-by-pp3w | Intuition:\nTwo conditions to help solve this problem:\n1. In a valid chess board, there are 2 and only 2 kinds of rows and one is inverse to the other.\nFor ex | lee215 | NORMAL | 2018-02-11T17:45:15.784000+00:00 | 2021-01-29T07:05:55.721440+00:00 | 18,742 | false | # **Intuition**:\nTwo conditions to help solve this problem:\n1. In a valid chess board, there are 2 and only 2 kinds of rows and one is inverse to the other.\nFor example if there is a row 01010011 in the board, any other row must be either 01010011 or 10101100.\nThe same for columns\nA corollary is that, any rectangle inside the board with corners top left, top right, bottom left, bottom right must be 4 zeros or 2 ones 2 zeros or 4 zeros.\n\n2. Another important property is that every row and column has half ones. Assume the board is ```N * N```:\nIf ```N = 2*K```, every row and every column has K ones and K zeros.\nIf ```N = 2*K + 1```, every row and every column has K ones and K + 1 zeros or K + 1 ones and K zeros.\n<br>\n\n# **Explanation**:\n**Since the swap process does not break this property, for a given board to be valid, this property must hold.\nThese two conditions are necessary and sufficient condition for a valid chessboard.**\n\nOnce we know it is a valid cheese board, we start to count swaps.\nBasic on the property above, when we arange the first row, we are actually moving all columns.\n\nI try to arrange one row into ```01010``` and ```10101``` and I count the number of swaps.\n1. In case of N even, I take the minimum swaps, because both are possible.\n2. In case of N odd, I take the even swaps.\nBecause when we make a swap, we move 2 columns or 2 rows at the same time.\nSo col swaps and row swaps should be same here.\n<br>\n\n# **Time Complexity**:\n`O(N^2)` to check the whole board.\n\n<br>\n\n**C++**\n```cpp\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 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 }\n else {\n colSwap = min(N - colSwap, colSwap);\n rowSwap = min(N - rowSwap, rowSwap);\n }\n return (colSwap + rowSwap) / 2;\n }\n```\n\n**Java:**\n```java\n public int movesToChessboard(int[][] b) {\n int N = b.length, 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]) == 1) return -1;\n for (int i = 0; i < N; ++i) {\n rowSum += b[0][i];\n colSum += b[i][0];\n if (b[i][0] == i % 2) rowSwap ++;\n if (b[0][i] == i % 2) colSwap ++ ;\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 == 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**Python:**\n```py\n def movesToChessboard(self, b):\n N = len(b)\n if any(b[0][0] ^ b[i][0] ^ b[0][j] ^ b[i][j] for i in range(N) for j in range(N)): return -1\n if not N / 2 <= sum(b[0]) <= (N + 1) / 2: return -1\n if not N / 2 <= sum(b[i][0] for i in range(N)) <= (N + 1) / 2: return -1\n col = sum(b[0][i] == i % 2 for i in range(N))\n row = sum(b[i][0] == i % 2 for i in range(N))\n if N % 2:\n if col % 2: col = N - col\n if row % 2: row = N - row\n else:\n col = min(N - col, col)\n row = min(N - row, row)\n return (col + row) / 2\n```\n\n# **Update**\n**Q: why just check the first row and col?**\nA: We have checked that ```b[0][0] ^ b[i][0] ^ b[0][j] ^ b[i][j]) == 0``` for all `i` and `j`.\nSo if we well arrange the first row and the first col, all board will be well set up.\n\n | 191 | 6 | [] | 38 |
transform-to-chessboard | Python, detailed explanation | python-detailed-explanation-by-yuanzhi24-pa97 | How to check impossible board?\n1. Each row in the board must either equal to the first row or equal to the reverse of the first row. \nThe same apply to column | yuanzhi247012 | NORMAL | 2019-11-29T14:38:14.862074+00:00 | 2019-11-29T14:44:08.245552+00:00 | 2,984 | false | How to check impossible board?\n1. Each row in the board must either equal to the first row or equal to the reverse of the first row. \nThe same apply to column, but you don\'t need to check column, because if all rows complies with this rule, all columns automatically comply with this rule by themselves. Only need to check rows.\n2. Count of "1" in each row must equal to the count of "0", or at most differ by 1.\nSince rule #1 is already passed, you don\'t need to check every row this time. Checking only the 1st row is enough. But you need to check both 1st row and 1st column in this case. Can\'t skip column this time\n\nWhen both #1 and #2 passed, it means the board can be tranformed to chessboard.\n\nHow to count number of swaps to transform?\nOnly need to count 1st row and 1st column. When the 1st row and 1st column becomes valid, the rest must be valid by themselves according to rule #1.\n\nTaking 1st row for example.\n1. We don\'t know whether the first cell should be "0" or "1". Assume it to be "0" first, then we know the expected values of all cells in 1st row. \n2. Count the difference against actual values. The number of swap should be diffCnt/2. If the diffCnt is an odd number, that means the first cell cannot be "0", we should choose "1" as the first cell. \n3. If both choosing "0" and choosing "1" makes even diffCount, then we choose the one with smallest number of swaps.\n\nSame applies to column.\n\n```\nclass Solution:\n def movesToChessboard(self, board: List[List[int]]) -> int:\n n=len(board)\n if n<=1:\n return 0\n rows=[\'\'.join(str(c) for c in r) for r in board]\n counter=collections.Counter(rows)\n keys=list(counter)\n if len(keys)!=2 or abs(counter[keys[0]]-counter[keys[1]])>1 \\\n or abs(keys[0].count(\'1\')-keys[0].count(\'0\'))>1 \\\n or any(a==b for a,b in zip(*keys)):\n return -1\n rowdiff=sum(board[0][i]!=(i%2) for i in range(n))\n coldiff=sum(board[i][0]!=(i%2) for i in range(n))\n rowdiff=n-rowdiff if rowdiff%2!=0 or (n%2==0 and (n-rowdiff)<rowdiff) else rowdiff\n coldiff=n-coldiff if coldiff%2!=0 or (n%2==0 and (n-coldiff)<coldiff) else coldiff\n return (rowdiff+coldiff)//2\n``` | 72 | 1 | [] | 4 |
transform-to-chessboard | C++ solution with Image explanation | c-solution-with-image-explanation-by-luc-q8d2 | Logic of how check if it a valid board \nTo understand if a board can be a chess board (so if it is valid) we can think in opposite way (so from the chess board | lucayan0506 | NORMAL | 2021-09-26T13:30:06.050973+00:00 | 2021-09-26T13:33:38.085295+00:00 | 3,125 | false | ## Logic of how check if it a valid board \nTo understand if a board can be a chess board (so if it is valid) we can think in opposite way (so from the chess board and get the rules that a chess board **must have.**\n\nThis is our chess board and let we focus on the first row and ignore others (image that other cell just follow the first row).\n\nYou can notice that however we move these cells (when we move some cells we move the entire column but for now we don\'t need to care about them) we will always have 2 cells with value `1` and 2 cells with value `0`, \n\nNow we come back to the entire board and we notice that ***cells below the first row*** (so columns) form 2 particular pattern (one equal to the first column and another one completely opposite than first column). So ,from these points we can get the **rules that a chess board has**:\n1. **Half of columns have the first pattern and rest have the second pattern**\n\t* with an exception which is when the board size is equal to an odd number, with this exception **patter1 - patter2 = 1 or -1** (in this case we have 3 column with the first patter and 2 second patter with the second pattern) \t\n2. A chess board has only 2 patterns of column \n\t* \t**first** one equal to the first column \n\t* \t**second** one completely opposite to the first column\n\n\t\nThese rules are the same for rows (just rotate the board and apply the same concept)\n\n##### E.g. of a valid board (board that can be a chess board)\n \nThis is valid because if we look column by column we notice that:\n* we have only 2 patters (respect the second rule).\n* `N. of pattern1 = 2` `N. of patter2 = 3` (the size of the board is an odd number so `pattern1- pattern2 = -1` and this respect the first rule)\n* When we rotate it and apply the same concept we notice that it is still valid.\n\n\n##### E.g. of a invalid board (board that cannot be a chess board)\n\nThis is invalid because it has 3 pattern (break the first rule)\n\nThis is invalid because `pattern1 = 3` `pattern2=1` (breaks the second rule)\n \nThis is invalid because when we rotate it it breaks the first rule\n\n## Calculate how many steps we need to do to get the chess board\n* Scan the board(horizontally and vertically\n* Image that the board start from 0\n\n* check if first cell is equal to 0 (in this case it isn\'t so countRow and countCol +1)\n\n* check next ones, now should be `1` (in this case countCor +1 )\n\n* Check next ones, now should be `0` (in this case countRow +1)\n* and so on,\n* Do the same thing imaging that the board start from 1 (there is a faster way to find out that which is `countRow2 = n - countRow` `countCol2 = n - countCol` \n* if `countRow` or `countRow2` is an odd number choose the another one (it will be even) because if `countRow` or `countRow2` is odd means that it can\'t be a chess board however you move (because each step you move 2 rows or 2 columns and if `countRow` is odd means that it will be a column that you can\'t move)\n* same for `countCol` and `countCol2`\n* `result = (min(countRow,countRow2) + min(countCol,countCol2) ) /2 ` divided by 2 because each step you move 2 columns/rows\n\n```\nclass Solution {\npublic:\n int movesToChessboard(vector<vector<int>>& board) {\n int n = board.size();\n \n\t\t//////////////////////////////////////////////////////////////////////////////\n\t\t//Secon rule\n\t\t//////////////////////////////////////////////////////////////////////////////\n //count how many columns we have for type1(column equal to the first column) and type2(column that have each cell different than the first column)\n int countCol_type1 = 1; //this is equal to 1 because we already count the first column\n int countCol_type2 =0;\n\n //count how many rows we have for type1(rows equal to the first row) and type2(rows that have each cell different than the first row)\n int countRow_type1 = 1; //this is equal to 1 because we already count the first row\n int countRow_type2 = 0;\n\n //check if the board is a valid board (by valid I mean that it can be a chess board. Scroll above to know the how to know if it\'s valid)\n for (int j = 1; j < n; j++) {\n\n //check horizontaly (each columns of the horizontal lane)\n if (board[0][j] == board[0][0]) {\n countCol_type1++;\n\n //check if all cell of the j column is equal to the first column (if not means that it is a invalid board, so return -1)\n for (int i = 1; i < n; i++) {\n if (board[i][j] != board[i][0])return -1;\n }\n }\n else {\n countCol_type2++;\n\n //check if all cell of the j column is different to the first column (if not means that it is a invalid board, so return -1)\n for (int i = 1; i < n; i++) {\n if (board[i][j] == board[i][0])return -1;\n }\n }\n\n //check vertically (each rows of the vertical lane)\n if (board[j][0] == board[0][0]) {\n countRow_type1++;\n\n //check if all cell of the j row is equal to the first row (if not means that it is a invalid board, so return -1)\n for (int i = 1; i < n; i++) {\n if (board[j][i] != board[0][i])return -1;\n }\n }\n else {\n countRow_type2++;\n\n //check if all cell of the j row is different to the first row (if not means that it is a invalid board, so return -1)\n for (int i = 1; i < n; i++) {\n if (board[j][i] == board[0][i])return -1;\n }\n }\n }\n\n\n\t\t//////////////////////////////////////////////////////////////////////////////\n\t\t//first rule\n\t\t//////////////////////////////////////////////////////////////////////////////\n //we have to make sure that n. of type1 is equal to type2 of only with 1 of difference (when n = odd number)\n //if it isn\'t means that the board is invalid) \n if (abs(countCol_type1 - countCol_type2) > 1) return -1; // if type1 - type2 != -1,0,1 then return -1\n if (abs(countRow_type1 - countRow_type2) > 1) return -1;\n\t\t\n\t\t\n\t\t//////////////////////////////////////////////////////////////////////////////\n\t\t//Calculate how many steps we need to do to get the chess board\n\t\t//////////////////////////////////////////////////////////////////////////////\n int countRow = 0;\n int countCol = 0;\n //count how many moves need to make the board as a chessboard that start with 0 \n for (int j = 0; j < n; j++) {\n if (board[0][j] != j % 2)countCol++;\n if (board[j][0] != j % 2)countRow++;\n }\n\n //count how many moves need to make the board as a chessboard (horizontally) that start with 1 \n int countRow2 = n - countRow;\n int countCol2 = n - countCol;\n\n int res = 0;\n //if countRow2 is an odd number return countRow/2\n if (countRow2 % 2)res+= countRow / 2;\n //if countRow is an odd number return countRow2/2\n else if (countRow % 2)res+= countRow2 / 2;\n //if countRow and countRow2 are even numbers return the smaller one\n else res += min(countRow, countRow2) / 2;\n\n //if countCol2 is an odd number return countCol/2\n if (countCol2 % 2)res += countCol / 2;\n //if countCol is an odd number return countCol2/2\n else if (countCol % 2)res += countCol2 / 2;\n //if countCol and countCol2 are even numbers return the smaller one\n else res += min(countCol, countCol2) / 2;\n\n return res;\n }\n};\n``` | 53 | 0 | ['C'] | 5 |
transform-to-chessboard | Java Clear Code with Detailed Explanations | java-clear-code-with-detailed-explanatio-cswj | Thanks @lee215 for the original post.\n\nMy thinking process :\n How do we check if it is possible to transform the board into the chessboard?\n1. Only 2 kinds | gracemeng | NORMAL | 2018-05-19T02:58:13.293632+00:00 | 2018-05-19T02:58:13.293632+00:00 | 3,850 | false | Thanks @lee215 for the original post.\n\nMy thinking process :\n* How do we check if it is possible to transform the board into the chessboard?\n1. Only 2 kinds of rows + one should be inverse to the other, e.g., one is 0110, another one is 0110 or 1001\n2. Assume the board N * N,\nif N is even, rowOneCnt = N / 2, colOneCnt = N / 2.\nif N is odd, rowOneCnt = N / 2, colOneCnt = N / 2 + 1 or rowOneCnt = N / 2 + 1, colOneCnt = N / 2\n* How do we count the swaps if it is possible to transform the board into the chessboard?\nWe count colToMove and rowToMove, (colToMove + rowToMove) / 2 will be the number of swaps in total for **each swap will move either two columns or two rows**.\n* How do we count colToMove and rowToMove?\n1. if elements on top edge or left edge == i % 2, they need to be changed\n2. we can change either colToMove or N - colToMove, similarly, either rowToMove or N - rowToMove\nif N is even, choose the smaller one\nif N is odd, we must choose the even one between ToMove or N - ToMove, for **each swap will move either two columns or two rows** \n\nThe complete code is as below :\n```\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``` | 32 | 1 | [] | 4 |
transform-to-chessboard | [Python] math solution, explained | python-math-solution-explained-by-dbabic-jnzx | We can find some invariants of our board:\n\n1. There will be 2 unique types of row and if n is even, there should be n/2 of each type; if n is odd, there shoul | dbabichev | NORMAL | 2021-09-26T07:31:32.210516+00:00 | 2021-09-27T10:13:10.730236+00:00 | 2,407 | false | We can find some invariants of our board:\n\n1. There will be `2` unique types of row and if `n` is even, there should be `n/2` of each type; if `n` is odd, there should be `(n+1)//2` and `(n-1)//2`.\n2. The same is for columns.\n3. Number of `1` in all board should be `n*n//2` if `n` is even and `(n*n +- 1)//2` if n is odd. \n\nIt can be shown, that these two conditions are sufficient and enough. Then for the first row, if `n` is odd, we have one option: `10101...01` we need to transform to, if `n` is even, there are two options: `1010...10` and `0101...01` we need to check. The same is for columns.\n\nLine `x1 = sum(i == j for i, j in zip(Cnt_r[0][0], patt1))` will check how many not equal elements we have between our pattern and one of our two types of columns, similar logic is for `patt2`. Then we have two options: try to make it `patt1` or `patt2`. Sometimes it is not possble to converge to one of them: in fact we can converge only if number of not equal elements is `even`, because on each step we can reduct number of not-equal elements by `2`. Imagine example `1000001111` which we try to make equal to `1010101010`. Then we enough to make only `2` steps to transform one to another!\n\n#### Complexity\nFinal time complexity is `O(n^2)`, space is also `O(n^2)`, because I keep transposed grid and count rows and columns.\n\n#### Code\n```python\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(sum(map(sum, board)) * 2 - n*n) > 1: 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```\n\n#### Remark\nWe can also notice, that all feasible boards will have the following property:\n1. If `n` is even, first column and row should have `n//2` ones, if `n` is odd, both of them should have `(n+1)//2` or `(n-1)//2` ones.\n2. For each rectangle with sides parallel to grid, it has even number of zeroes: it means that all elements uniquely defined by first column and first row. | 28 | 4 | ['Math'] | 7 |
transform-to-chessboard | C++ solution with very detailed comments, especially the swap counting part | c-solution-with-very-detailed-comments-e-j9tb | Inspired by this and this posts, but use a different approach to count swap number, IMHO, which is more intuitive.\nC++\n int movesToChessboard(vector<vector | bwv988 | NORMAL | 2019-02-10T21:58:22.163132+00:00 | 2019-07-24T13:12:31.561408+00:00 | 1,725 | 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``` C++\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 }\n``` | 17 | 0 | [] | 1 |
transform-to-chessboard | Short Python Solution; Beat 100%; with line-by-line explanation | short-python-solution-beat-100-with-line-4y5l | Beat 100%\n(Inspired by Maozi Chen\'s observations; he/she is a genius!)\nMy understanding:\nKey observation: A solvable board iff it satisfies the following re | yuxiong | NORMAL | 2018-09-12T05:38:04.096985+00:00 | 2018-09-12T05:38:04.097033+00:00 | 1,189 | false | Beat 100%\n(Inspired by Maozi Chen\'s observations; he/she is a genius!)\nMy understanding:\nKey observation: A solvable board iff it satisfies the following requirements:\n 1) Each row/column either the same as the first row/column or exactly cell-by-cell reversed color of the first row/column.\n Example1: If the first row is: 011010, then the other rows must be either 011010 (same) or 100101(inverted).\n Example2: If the first column is: 101, then the other columns must be either 101 or 010.\n 2) Let\'s make two definitions:\n Positive: A row/col is positive if it\'s same as the first row/col.\n Negative: A row/col is negative if it\'s the invertion of the first row/col.\n If N is Even: there must be equal numbers of positive rows/cols and negative rows/cols\n If N is Odd: they must differ by 1. Examples: len(pos_rows) = len(neg_rows) + 1\nThese two observations can be proven by drawing a generic final chessboard, then prove by contradiction or enumeration.\n\nNow as long as it satisfies the requirements, we can definitely reach \'chessboard\', what left is to calculate the min steps needed.\nI use P to represent a positive row/col, and N to represent a negative row/col. There are only two possible results:\nPattern A: P N P N P ... or Pattern B: N P N P N ...\nFor a given problem, its rows are in the format X X X X X ...\nWe check if pattern A and/or pattern B are possible, if both are possible then we use the min steps.\nHow to check if a pattern is possible for the given problem?\n For a given problem and a pattern, we compare them digit by digit, each time they differ we increment errors/mismatches: errs+=1\n If the final errs is odd, then this pattern is impossible. In other words, there must be even number of errors/mismatches.\n Example: n=5, problem = N N P P N, \n Pattern = P N P N P (pattern A)\n Errors = E _ _ E E errs = 3\n So pattern A is impossible.\n Example: n=5, problem = N N P P N, \n Pattern = N P N P N (pattern B)\n Errors = _ E E _ _ errs = 2\n So pattern B is possible.\n Example: n=3, problem = N N N, you can prove that neither of the patterns are possible. But this example should\'ve exited at requirement 2)\n\nSo the algorithm is as following:\n Line <1> and <2>: save positive and negative rows/cols. \n Line <3>: The function core will be called once for rows once for columns.\n Lines < A>: the default pattern used is pattern A (lines < A>), then the errs of matching pattern B can be calculated: N-errs\n Line < 4>: we keep tracking the count of positive rows/cols.\n Line <5>: checks requirement 1)\n Line <6>: checks requirement 2) using the count at line <4>\n Lines < B>: check if pattern A or pattern B is possible.\n```\nclass Solution:\n def movesToChessboard(self, board):\n N = len(board)\n rp, cp = board[0], [x[0] for x in board] #<1>\n rn, cn = [(x+1)%2 for x in rp], [(x+1)%2 for x in cp] #<2>\n \n def core(is_row): # <3>\n count = errs = 0\n for i in range(N):\n if is_row: line, pos, neg = board[i], rp, rn\n else: line, pos, neg = [x[i] for x in board], cp, cn\n \n if line == pos:\n count+=1 # <4>\n if i%2==1: errs+=1 # <A>\n elif line == neg:\n if i%2==0: errs+=1 # <A>\n else: return -1 # <5>\n if count > math.ceil(N/2) or count < math.floor(N/2): return -1 # <6>\n cand1 = math.inf if errs%2==1 else errs//2 # <B>\n cand2 = math.inf if (N-errs)%2==1 else (N-errs)//2 # <B>\n return min(cand1, cand2)# if min(cand1, cand2) != math.inf else -1\n \n row_ans = core(True)\n if row_ans == -1: return -1\n col_ans = core(False)\n if col_ans == -1: return -1\n return row_ans + col_ans\n``` | 14 | 1 | [] | 1 |
transform-to-chessboard | ⚡C# | Beats runtime AND memory 100% [EXPLAINED IN DETAILS] | c-beats-runtime-and-memory-100-explained-7knw | Intuition\nWhen I looked at this problem, it was clear that I needed to transform a grid of 0s and 1s into a chessboard pattern, where no two adjacent cells are | r9n | NORMAL | 2024-09-05T21:30:46.369438+00:00 | 2024-09-05T21:30:46.369462+00:00 | 118 | false | # Intuition\nWhen I looked at this problem, it was clear that I needed to transform a grid of 0s and 1s into a chessboard pattern, where no two adjacent cells are the same. Essentially, I want the board to look like a checkerboard, alternating between 0 and 1.\n\nTo solve this, I realized I could only swap rows and columns. So, the rows and columns in a valid chessboard pattern have to either be exactly the same as or the opposite of each other. My task is to see if I can rearrange the grid to meet this pattern and, if so, figure out the minimum number of swaps needed.\n\n\n# Approach\nCheck if It\u2019s Possible: First, I need to check if it\'s even possible to turn the grid into a chessboard. I do this by comparing the rows and columns to the first row and column. For a valid chessboard:\n\nEvery row should be either the same as or the reverse of the first row.\n\nEvery column should be either the same as or the reverse of the first column.\n\nIf any row or column doesn\u2019t match this pattern, I know it\u2019s impossible to form a chessboard and return -1.\n\nCount 1s and 0s: If the board looks like it can be turned into a chessboard, I check how many 1s and 0s are in the first row and first column. For a proper chessboard, these counts should be balanced. If they\u2019re not, it\u2019s impossible to make a chessboard pattern, so I return -1.\n\nCalculate the Swaps:\n If the board is valid, I count how many rows and columns are out of place compared to the chessboard pattern. Then, I figure out how many swaps are needed to fix them.\n\nDepending on whether the board size n is even or odd, there might be two valid patterns (for even n) or just one (for odd n). I calculate the minimum number of swaps required to align the board with one of these patterns and return that number.\n\n\n# Complexity\n- Time complexity:\nO(n\xB2). I have to check every cell in the grid to see if it fits the chessboard pattern and count how many swaps are needed. So, the time it takes grows with the square of the size of the board.\n\n\n- Space complexity:\nO(1). I only use a few extra variables to keep track of counts and swaps, so the amount of extra space I need doesn\u2019t depend on the size of the board.\n\n# Code\n```csharp []\npublic class Solution {\n public int MovesToChessboard(int[][] board) {\n int n = board.Length;\n \n // Check for the validity of rows and columns\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]) != 0)\n return -1; // Invalid chessboard pattern\n }\n }\n\n // Count how many rows and columns we need to swap\n int rowSum = 0, colSum = 0, rowSwap = 0, colSwap = 0;\n \n // Analyze the first row and first column for patterns\n for (int i = 0; i < n; ++i) {\n rowSum += board[0][i]; // Count 1\'s in the first row\n colSum += board[i][0]; // Count 1\'s in the first column\n rowSwap += (board[0][i] == i % 2) ? 1 : 0; // How many need to be swapped in rows\n colSwap += (board[i][0] == i % 2) ? 1 : 0; // How many need to be swapped in columns\n }\n \n // Check if the sum of 1s in row and column is valid for a chessboard pattern\n if (rowSum < n / 2 || rowSum > (n + 1) / 2) return -1;\n if (colSum < n / 2 || colSum > (n + 1) / 2) return -1;\n \n // Calculate the minimum number of swaps\n if (n % 2 == 1) {\n if (rowSwap % 2 != 0) rowSwap = n - rowSwap;\n if (colSwap % 2 != 0) colSwap = n - colSwap;\n } else {\n rowSwap = Math.Min(rowSwap, n - rowSwap);\n colSwap = Math.Min(colSwap, n - colSwap);\n }\n \n return (rowSwap + colSwap) / 2;\n }\n}\n\n``` | 11 | 0 | ['C#'] | 0 |
transform-to-chessboard | Short C++ solution, no swaps, 9ms, O(n^2) time, O(1) space | short-c-solution-no-swaps-9ms-on2-time-o-9rqr | 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 | mzchen | NORMAL | 2018-02-11T05:27:35.814000+00:00 | 2018-09-12T00:26:54.186892+00:00 | 2,417 | 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}\n``` | 11 | 1 | [] | 0 |
transform-to-chessboard | [Python3] alternating numbers | python3-alternating-numbers-by-ye15-uqsu | \n\nclass Solution:\n def movesToChessboard(self, board: List[List[int]]) -> int:\n n = len(board)\n \n def fn(vals): \n """R | ye15 | NORMAL | 2021-06-29T21:21:48.074875+00:00 | 2021-06-29T21:40:34.684378+00:00 | 944 | false | \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 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: return inf\n ans = inf \n if len(vals) <= 2*total <= len(vals)+1: ans = min(ans, odd)\n if len(vals)-1 <= 2*total <= len(vals): ans = min(ans, total - odd)\n return ans \n \n rows, cols = [0]*n, [0]*n\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 ans = fn(rows) + fn(cols)\n return ans if ans < inf else -1 \n``` | 8 | 0 | ['Python3'] | 1 |
transform-to-chessboard | JavaScript easy to read solution | javascript-easy-to-read-solution-by-elle-725o | \n/**\n * @param {number[][]} board\n * @return {number}\n */\nvar movesToChessboard = function(board) {\n const boardSize = board.length;\n const boardSi | elleuz | NORMAL | 2021-09-26T11:25:34.312618+00:00 | 2021-09-26T11:51:00.768728+00:00 | 519 | false | ```\n/**\n * @param {number[][]} board\n * @return {number}\n */\nvar movesToChessboard = function(board) {\n const boardSize = board.length;\n const boardSizeIsEven = boardSize % 2 === 0;\n \n if(!canBeTransformed(board)) return -1;\n \n // to convert to 010101\n let rowSwap = 0;\n let colSwap = 0;\n \n // to convert to 101010\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 \n // no need to swap anything\n if((rowSwap + colSwap) === 0 || (rowSwap2 + colSwap2) === 0) return 0; \n \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 // number of 0 and 1 should be equal\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 // each row should be equal to first or opposite\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 // for even board, two types of rows should be equal\n if(boardSizeIsEven) {\n return counter[0] == counter[1];\n }\n return Math.abs(counter[0] - counter[1]) === 1\n }\n};\n``` | 6 | 0 | ['JavaScript'] | 0 |
transform-to-chessboard | Transform to Chessboard || [C++/Java/Python] | transform-to-chessboard-cjavapython-by-r-6wy0 | Intuition:\nTwo conditions to help solve this problem:\n\n1. In a valid chess board, there are 2 and only 2 kinds of rows and one is inverse to the other.\nFor | rishabhsarang200 | NORMAL | 2021-09-26T08:45:14.361605+00:00 | 2021-09-27T07:52:38.893953+00:00 | 711 | false | **Intuition**:\nTwo conditions to help solve this problem:\n\n1. In a valid chess board, there are 2 and only 2 kinds of rows and one is inverse to the other.\nFor example if there is a row 01010011 in the board, any other row must be either 01010011 or 10101100.\nThe same for columns\nA corollary is that, any rectangle inside the board with corners top left, top right, bottom left, bottom right must be 4 zeros or 2 ones 2 zeros or 4 zeros.\n\n2. Another important property is that every row and column has half ones. Assume the board is N * N:\nIf N = 2*K, every row and every column has K ones and K zeros.\nIf N = 2*K + 1, every row and every column has K ones and K + 1 zeros or K + 1 ones and K zeros.\n\n\n**Explanation**:\nSince the swap process does not break this property, for a given board to be valid, this property must hold.\nThese two conditions are necessary and sufficient condition for a valid chessboard.\n\nOnce we know it is a valid cheese board, we start to count swaps.\nBasic on the property above, when we arange the first row, we are actually moving all columns.\n\nI try to arrange one row into 01010 and 10101 and I count the number of swaps.\n\nIn case of N even, I take the minimum swaps, because both are possible.\nIn case of N odd, I take the even swaps.\nBecause when we make a swap, we move 2 columns or 2 rows at the same time.\nSo col swaps and row swaps should be same here.\n\nC++\n``` \nint 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 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 }\n else {\n colSwap = min(N - colSwap, colSwap);\n rowSwap = min(N - rowSwap, rowSwap);\n }\n return (colSwap + rowSwap) / 2;\n }\n```\n\t\n\tJava \n```\n\t public int movesToChessboard(int[][] b) {\n int N = b.length, 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]) == 1) return -1;\n for (int i = 0; i < N; ++i) {\n rowSum += b[0][i];\n colSum += b[i][0];\n if (b[i][0] == i % 2) rowSwap ++;\n if (b[0][i] == i % 2) colSwap ++ ;\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 == 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\tPython:\n```\n\t def movesToChessboard(self, b):\n N = len(b)\n if any(b[0][0] ^ b[i][0] ^ b[0][j] ^ b[i][j] for i in range(N) for j in range(N)): return -1\n if not N / 2 <= sum(b[0]) <= (N + 1) / 2: return -1\n if not N / 2 <= sum(b[i][0] for i in range(N)) <= (N + 1) / 2: return -1\n col = sum(b[0][i] == i % 2 for i in range(N))\n row = sum(b[i][0] == i % 2 for i in range(N))\n if N % 2:\n if col % 2: col = N - col\n if row % 2: row = N - row\n else:\n col = min(N - col, col)\n row = min(N - row, row)\n return (col + row) / 2\n``` | 6 | 4 | [] | 2 |
transform-to-chessboard | C++ little longer | c-little-longer-by-khacker-6vis | \nint 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; + | khacker | NORMAL | 2021-09-26T07:04:37.032510+00:00 | 2021-09-26T07:04:37.032556+00:00 | 162 | false | ```\nint 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 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 }\n else {\n colSwap = min(N - colSwap, colSwap);\n rowSwap = min(N - rowSwap, rowSwap);\n }\n return (colSwap + rowSwap) / 2;\n }\n```\n | 6 | 5 | [] | 0 |
transform-to-chessboard | JavaScript solution | javascript-solution-by-yyoon-shev | My code is ugly but at least it passed all the test cases.\nThe main idea is the following:\n\n1. rows and columns can be fixed independantly, because they don\ | yyoon | NORMAL | 2021-04-21T22:13:07.187137+00:00 | 2021-04-21T22:22:07.954757+00:00 | 313 | false | My code is ugly but at least it passed all the test cases.\nThe main idea is the following:\n\n1. rows and columns can be fixed **independantly**, because they don\'t affect eachother.\n2. If the size is odd, first position and last position in the row and column is **decided**. If one has three, zero has two in the first row, first column and last column must have one. It is same as the column calculation.\n3. If the size is even, check which one has more correct position and try to fix the wrong position to minimize the move.\n4. If you see the code below, column fix logic and row fix logic is **identical** except the posion in the board\n\n\n```\n/**\n * @param {number[][]} board\n * @return {number}\n */\n var movesToChessboard = function(board) {\n let cnt = 0;\n let one = 0;\n let zero = 0;\n for (let r of board) {\n for (let c of r) {\n if (c === 0) {\n zero++;\n } else {\n one++;\n }\n }\n }\n\t\n\t// start column fix\n let missedOne = [];\n let missedZero = [];\n let cur = 0;\n if (one !== zero) {\n cur = one > zero ? 1 : 0;\n } else {\n let zeroCorrect = 0;\n let oneCorrect = 0;\n for (let i = 0; i < board.length; i += 2) {\n if (board[0][i] == 0) {\n zeroCorrect++;\n } else {\n oneCorrect++;\n }\n }\n cur = oneCorrect > zeroCorrect ? 1 : 0;\n }\n \n let r = 0;\n if (one != zero) {\n while (r < board.length) {\n o = 0;\n z = 0;\n for(let c = 0; c < board.length; c++) {\n o = board[r][c] === 1 ? o + 1 : o;\n z = board[r][c] === 0 ? z + 1 : z;\n }\n if (cur === 1 && o > z || cur == 0 && z > o) break;\n r++;\n }\n }\n for(let c = 0; c < board.length; c++) {\n if (board[r][c] !== cur) {\n if (cur === 1) {\n missedOne.push(c);\n } else {\n missedZero.push(c);\n }\n }\n cur = cur === 1 ? 0 : 1;\n }\n if (missedOne.length != missedZero.length) {\n return -1;\n }\n for (let i = 0; i < missedZero.length; i++) {\n for (let rr = 0; rr < board.length; rr++) {\n [board[rr][missedZero[i]], board[rr][missedOne[i]]] = [board[rr][missedOne[i]], board[rr][missedZero[i]]];\n }\n cnt++;\n }\n\n // start row fix\n missedOne = [];\n missedZero = [];\n cur = 0;\n if (one !== zero) {\n cur = one > zero ? 1 : 0;\n } else {\n let zeroCorrect = 0;\n let oneCorrect = 0;\n for (let i = 0; i < board.length; i += 2) {\n if (board[i][0] == 0) {\n zeroCorrect++;\n } else {\n oneCorrect++;\n }\n }\n cur = oneCorrect > zeroCorrect ? 1 : 0;\n }\n \n let c = 0;\n if (one != zero) {\n while (c < board.length) {\n o = 0;\n z = 0;\n for(let r = 0; r < board.length; r++) {\n o = board[r][c] === 1 ? o + 1 : o;\n z = board[r][c] === 0 ? z + 1 : z;\n }\n if (cur === 1 && o > z || cur == 0 && z > o) break;\n c++;\n }\n }\n for(let r = 0; r < board.length; r++) {\n if (board[r][c] !== cur) {\n if (cur === 1) {\n missedOne.push(r);\n } else {\n missedZero.push(r);\n }\n }\n cur = cur === 1 ? 0 : 1;\n }\n if (missedOne.length != missedZero.length) {\n return -1;\n }\n for (let i = 0; i < missedZero.length; i++) {\n [board[missedOne[i]], board[missedZero[i]]] = [board[missedZero[i]], board[missedOne[i]]];\n cnt++;\n }\n\n for (let r = 1; r < board.length; r++) {\n for (let c = 1; c < board.length; c++) {\n if (board[r][c] == board[r][c-1] || board[r-1][c] == board[r][c]) {\n return -1;\n }\n }\n }\n \n return cnt;\n}; | 5 | 0 | [] | 1 |
transform-to-chessboard | C++ Solution with proof | c-solution-with-proof-by-matecompufrj-0wbk | The key idea is:\nIf the grid has a solution, we can arrive at the solution by looking only at the first row and the first column. This happens because each sol | matecompufrj | NORMAL | 2021-10-15T20:16:22.214232+00:00 | 2021-10-15T20:16:22.214270+00:00 | 580 | false | **The key idea is:**\nIf the grid has a solution, we can arrive at the solution by looking only at the first row and the first column. This happens because each solution step moves the entire row or entire column.\n\n**How to know if the table has a solution?**\nThe dimensions are dependent, so we need to check that when correcting the first row or first column, the values in the middle of the table are resolved too.\n\nThe code below shows how we analyze this:\n```c++\nfor (int i=1; i<board.size(); i++) {\n for (int j=1; j<board[i].size(); j++) {\n if (((board[0][0] ^ board[i][0]) ^ (board[i][j] ^ board[0][j])) == 1) {\n return -1;\n }\n }\n}\n```\n\nThis code compares whether the middle value has the same parity with the edge values.\n\n[](https://gyazo.com/1dc9dbe67d99ded468cd73efb0a2a03e)\n\n- if the blue cells have different values, the green cells must also have different values.\n- if blue cells have equal values, green cells must also have equal values.\n\nIf neither of the above two conditions are true, we have a table that is impossible to solve. \nThis looks like magic right? Let\'s look at the solved table:\n<p>\n<img src="https://i.gyazo.com/f3e3ee7360a38024e12ef928fef72cc9.png" width="30%">\n</p>\n\nBetween two adjacent lines, one is the conjugate of the other and the same applies for columns. When we swap a row or a column from an solved table, we have two scenarios:\n\n1. Swap identical row or collumn\n2. Swap conjugated row or collumn\n\nNo matter how many operations you do, we will always fall into these two scenarios. In summary, the code above checks if the current table has this property.\n\nBefore calculating the number of steps to reach the solution. We need to do one more validation, this one is much simpler.\n\nThis validation consists of counting the number of 1s and 0s in the first row and in the first column:\n```c++\nfor (int i=0; i<N; i++) {\n\tif (board[0][i]) onesInFirstRow++;\n\telse zerosInFirstRow++;\n\n\tif (board[i][0]) onesInFirstCol++;\n\telse zerosInFirstCol++;\n}\n\nif (abs(onesInFirstRow - zerosInFirstRow) > 1) return -1;\nif (abs(onesInFirstCol - zerosInFirstCol) > 1) return -1;\n```\n\n- If the difference between zeros and ones is greater than 1, it\'s impossible solve this table.\n\n\nNow to calculate the minimum number of steps, we need to solve the first column and the first row individually and sum each result.\n\n**Solving to first row and column**\n\nTo solve this, we have two scenarios:\n1. N even\n2. N odd\n\nWhen N is even, we have two solutions:\n\n- **[0,1,...,0,1]** (starting with 0)\n- **[1,0,...,1,0]** (starting with 1)\n\n\nWe know that each swap can fix two elements as we can see in the example below:\n\n- **[0,0,1,1]** --> **[0,1,0,1]** (swap second with third item)\n\nSo, the number of moviments needed to transform a row or a collumn to any two possible solution is:\n\n- number of wrong elements divided by 2\n\nAs one solution is the inverse of the other, we can say that:\n\n- **solution_start_one** = N - **solution_start_zero**\n\nTherefore, when N is even, the answer will be the smallest value between the two possible solutions.\n\n```c++\n// This for compare the first row and column \n// with the solution that starts with one\nfor (int i=0; i<N; i++) {\n\tif (board[0][i] == i%2) rowMovesNeeded++;\n\tif (board[i][0] == i%2) colMovesNeeded++;\n} \n\nif (N % 2 == 0) {\n\tcolMovesNeeded = min(colMovesNeeded, N-colMovesNeeded);\n\trowMovesNeeded = min(rowMovesNeeded, N-rowMovesNeeded);\n\t\n\treturn (colMovesNeeded + rowMovesNeeded) / 2;\n} \n\n// solve when N is odd\n```\n\nWhen N is odd, we have only one solution:\n\n- **[1,0,..,0,1]** (when the row or column has more ones)\n- **[0,1,..,1,0]** (when the row or column has more zeros)\n\nIf we have more zeros, we only use the value to solution that begin with zero. So with odd N we need analyze the number of zeros and use the correct solution to each case.\n\n```c++\nif (onesInFirstCol < zerosInFirstCol) {\n\tcolMovesNeeded = N - colMovesNeeded;\n}\n\nif (onesInFirstRow < zerosInFirstRow) {\n\trowMovesNeeded = N - rowMovesNeeded;\n}\n\nreturn (colMovesNeeded + rowMovesNeeded) / 2;\n```\n\nThe code for this question is quite simple, but the idea behind it is quite complex. I really enjoyed the insights that this problem required.\n\nThe final code is:\n```c++\nclass Solution {\npublic:\n\n int movesToChessboard(vector<vector<int>>& board) {\n int N = board.size();\n int colMovesNeeded = 0, rowMovesNeeded = 0;\n int onesInFirstCol = 0, onesInFirstRow = 0;\n int zerosInFirstCol = 0, zerosInFirstRow = 0;\n\n for (int i=1; i<board.size(); i++) {\n for (int j=1; j<board[i].size(); j++) {\n if (((board[0][0] ^ board[i][0]) ^ (board[i][j] ^ board[0][j])) == 1) {\n return -1;\n }\n }\n }\n \n for (int i=0; i<N; i++) {\n if (board[0][i]) onesInFirstRow++;\n else zerosInFirstRow++;\n \n if (board[i][0]) onesInFirstCol++;\n else zerosInFirstCol++;\n }\n \n if (abs(onesInFirstRow - zerosInFirstRow) > 1) return -1;\n if (abs(onesInFirstCol - zerosInFirstCol) > 1) return -1;\n \n for (int i=0; i<N; i++) {\n if (board[0][i] == i%2) rowMovesNeeded++;\n if (board[i][0] == i%2) colMovesNeeded++;\n } \n \n \n if (N % 2 == 1) {\n \n if (onesInFirstCol < zerosInFirstCol) {\n colMovesNeeded = N - colMovesNeeded;\n }\n \n if (onesInFirstRow < zerosInFirstRow) {\n rowMovesNeeded = N - rowMovesNeeded;\n }\n \n } else {\n colMovesNeeded = min(colMovesNeeded, N-colMovesNeeded);\n rowMovesNeeded = min(rowMovesNeeded, N-rowMovesNeeded);\n }\n \n\n \n return (colMovesNeeded + rowMovesNeeded) / 2;\n }\n};\n```\nI am sorry for my english. I\'m just a young brazilian boy trying to help this community. | 4 | 0 | ['C'] | 0 |
transform-to-chessboard | c++ Solution | c-solution-by-saurabhvikastekam-jtiq | \nclass Solution \n{\npublic:\n int movesToChessboard(vector<vector<int>>& board) \n {\n int n = board.size();\n int cnt1 = 1, cnt2 = 0;\n | SaurabhVikasTekam | NORMAL | 2021-09-27T07:26:46.969248+00:00 | 2021-09-27T07:26:46.969317+00:00 | 663 | false | ```\nclass Solution \n{\npublic:\n int movesToChessboard(vector<vector<int>>& board) \n {\n int n = board.size();\n int cnt1 = 1, cnt2 = 0;\n for (int i = 1; i < n; ++i) \n {\n if (board[0][0] == board[i][0]) \n {\n ++cnt1;\n for (int j = 0; j < n; ++j) \n {\n if (board[0][j] != board[i][j]) \n {\n return -1;\n } \n }\n } \n else \n {\n ++cnt2;\n for (int j = 0; j < n; ++j) \n {\n if (board[0][j] == board[i][j]) \n {\n return -1;\n }\n }\n }\n }\n if (abs(cnt1 - cnt2) > 1) \n {\n return -1;\n }\n cnt1 = 1, cnt2 = 0;\n for (int j = 1; j < n; ++j) \n {\n if (board[0][0] == board[0][j]) \n {\n ++cnt1;\n for (int i = 0; i < n; ++i) \n {\n if (board[i][0] != board[i][j]) \n {\n return -1;\n }\n }\n } \n else \n {\n ++cnt2;\n for (int i = 0; i < n; ++i) \n { \n if (board[i][0] == board[i][j]) \n {\n return -1;\n }\n }\n }\n }\n if (abs(cnt1 - cnt2) > 1) \n {\n return -1;\n }\n int swapRow = 0, swapCol = 0;\n for (int i = 0; i < n; ++i)\n {\n if (board[i][0] != i % 2) \n {\n ++swapRow;\n }\n }\n for (int j = 0; j < n; ++j) \n {\n if (board[0][j] != j % 2) \n {\n ++swapCol;\n }\n }\n int ans = 0;\n if (n & 1) \n {\n if (swapRow & 1) \n {\n swapRow = n - swapRow;\n }\n if (swapCol & 1) \n {\n swapCol = n - swapCol;\n }\n ans += swapRow / 2;\n ans += swapCol / 2;\n } \n else \n {\n ans += min(swapRow, n - swapRow) / 2;\n ans += min(swapCol, n - swapCol) / 2;\n }\n return ans;\n }\n};\n``` | 4 | 0 | ['C', 'C++'] | 0 |
transform-to-chessboard | [JavaScript] Check number of 1s and 0s | javascript-check-number-of-1s-and-0s-by-zr5wo | ```\nvar movesToChessboard = function(board) {\n const n = board.length;\n\n for (let i = 0; i < n; i++)\n for (let j = 0; j < n; j++)\n | tmohan | NORMAL | 2021-09-04T11:14:52.281157+00:00 | 2021-09-04T11:14:52.281185+00:00 | 222 | false | ```\nvar movesToChessboard = function(board) {\n const n = board.length;\n\n for (let i = 0; i < n; i++)\n for (let j = 0; j < n; j++)\n if (board[0][0] ^ board[i][0] ^ board[0][j] ^ board[i][j]) \n return -1;\n\n let rowSwaps = 0, colSwaps = 0, rowSum = 0, colSum = 0;\n\n for (let i = 0; i < n; i++) {\n rowSum += board[0][i] ? 1 : -1\n colSum += board[i][0] ? 1 : -1;\n rowSwaps += board[0][i] === i % 2;\n colSwaps += board[i][0] === i % 2;\n }\n \n if (Math.abs(rowSum) > 1 || Math.abs(colSum) > 1)\n return -1;\n\n if (n % 2) {\n if (rowSwaps % 2) rowSwaps = n - rowSwaps;\n if (colSwaps % 2) colSwaps = n - colSwaps;\n } else {\n colSwaps = Math.min(colSwaps, n - colSwaps);\n rowSwaps = Math.min(rowSwaps, n - rowSwaps);\n }\n\n return (colSwaps + rowSwaps) / 2;\n}; | 4 | 0 | [] | 1 |
transform-to-chessboard | C++ solution with comments | c-solution-with-comments-by-sup6yj3a8-9mil | \nint isRawSame(const vector<vector<int>> &vec, const int &a, const int &b){\n for (int col=0; col<vec[a].size(); ++col) {\n if (vec[a][col] != vec[b] | sup6yj3a8 | NORMAL | 2021-07-27T11:09:28.100095+00:00 | 2021-07-27T11:10:22.830676+00:00 | 456 | false | ```\nint isRawSame(const vector<vector<int>> &vec, const int &a, const int &b){\n for (int col=0; col<vec[a].size(); ++col) {\n if (vec[a][col] != vec[b][col]) {return false;}\n }\n return true;\n}\n\n// Find the min number of swaping of vec to fit ans1 {0, 1, 0, 1, .....} or ans2 {1, 0, 1, 0, .....}.\nint minSwap(const vector<int> &vec){\n int ans1 = 0;\n int ans2 = 0;\n for (int i=0; i<vec.size(); ++i) {\n if (vec[i] != i % 2) {++ans1;} // {0, 1, 0, 1, .....}\n if (vec[i] != (i + 1) % 2) {++ans2;} // {1, 0, 1, 0, .....}\n }\n \n // If ans1 and ans2 are valid, they must be EVEN.\n if (ans1 % 2 != 0) {\n return ans2 / 2;\n }else if (ans2 % 2 != 0) {\n return ans1 / 2;\n }else{\n return min(ans1 / 2, ans2 / 2);\n }\n \n}\n\n// The size of difference of vec is smaller 1, the vec is valid.\n// The value of vec must be 0 or 1\nint isValid(const vector<int> &vec){\n int c1 = 0;\n int c2 = 0;\n for (const auto &v : vec) {\n v == 0 ? ++c1 : ++c2;\n }\n return abs(c1 - c2) <= 1;\n}\n\nint findRawDiff(const vector<vector<int>> &board, vector<int> &diffRaw, vector<int> &raw){\n diffRaw.push_back(0);\n for (int i=1; i<board.size(); ++i) {\n int d = 0;\n \n for (d=0; d<diffRaw.size(); ++d) {\n if ( isRawSame(board, i, diffRaw[d]) ){break;}\n }\n \n // If d > 1, d is not valid.\n if (d > 1) {\n return -1;\n }else if (d == diffRaw.size()) {\n diffRaw.push_back(i);\n }\n \n raw[i] = d;\n }\n \n return 1;\n}\n\nint movesToChessboard(vector<vector<int>>& board) {\n const int size = static_cast<int>(board.size());\n \n // 1. Check if the raw and col of board is same and record corresponding index to diff.\n vector<int> raw(size, 0);\n vector<int> col(size, 0);\n vector<int> diffRaw;\n vector<int> diffCol;\n \n // 1.1 Find the difference of raw\n if (findRawDiff(board, diffRaw, raw) == -1) {return -1;}\n \n // 1.2 Transpose (raw <-> col)\n vector<vector<int>> tBoard(size, vector<int>(size));\n for (int i = 0; i < board.size(); ++i) {\n for (int j = 0; j < board.size(); ++j) {\n tBoard[j][i] = board[i][j];\n }\n }\n \n // 1.3 Find the difference of col\n if (findRawDiff(tBoard, diffCol, col) == -1) {return -1;}\n \n // 1.4 If the size of the difference type is 2 or the size of difference of raws / cols is smaller than 1, the vector is valid.\n if (diffRaw.size() != 2 || diffCol.size() != 2 || !isValid(raw) || !isValid(col)) {return -1;}\n \n // 2. Return min number of swapping\n return minSwap(raw) + minSwap(col);\n}\n``` | 4 | 2 | ['C'] | 1 |
transform-to-chessboard | Java beats 100% | java-beats-100-by-deleted_user-p31v | Java beats 100%\n\n\n\n# Code\n\nclass Solution {\n public int movesToChessboard(int[][] board) {\n int N = board.length, rowSum = 0, colSum = 0, rowS | deleted_user | NORMAL | 2024-05-25T04:46:24.324690+00:00 | 2024-05-25T04:46:24.324710+00:00 | 153 | false | Java beats 100%\n\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``` | 3 | 0 | ['Java'] | 0 |
transform-to-chessboard | 782: Beats 98.8%, Solution with step by step explanation | 782-beats-988-solution-with-step-by-step-0qck | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n\n n = len(board)\n\n\nGet the size of the board.\n\n\n for | Marlen09 | NORMAL | 2023-10-28T07:03:19.602139+00:00 | 2023-10-28T07:03:19.602169+00:00 | 210 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n```\n n = len(board)\n```\n\nGet the size of the board.\n\n```\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]:\n return -1\n```\n\nFor every possible 2x2 square in the board (formed by picking cells (0, 0), (i, 0), (0, j), (i, j)), if the four cells are neither all the same nor all different, we instantly return -1 because it\'s impossible to form a chessboard in this situation. The ^ operator is a bitwise XOR operation that will return 1 if two bits are different and 0 if they\'re the same.\n\n```\n row_sum = sum(board[0])\n```\n\nCount the number of ones in the first row.\n\n```\n col_sum = sum(board[i][0] for i in range(n))\n```\n\nCount the number of ones in the first column.\n\n```\n if not n//2 <= row_sum <= (n+1)//2:\n return -1\n if not n//2 <= col_sum <= (n+1)//2:\n return -1\n```\n\nCheck if the number of ones in the first row and column is valid. A valid chessboard will have almost equal number of ones and zeros in the first row and column. Depending on whether the board size n is even or odd, we ensure that the number of ones lies in the acceptable range.\n\n```\n row_swaps = sum(board[i][0] == i % 2 for i in range(n))\n```\n\nCalculate how many rows in the board have their starting bit different from their row index modulo 2. This will help determine how many rows we need to swap to get the desired alternating pattern.\n\n```\n col_swaps = sum(board[0][i] == i % 2 for i in range(n))\n```\n\nSimilarly, calculate how many columns have their starting bit different from their column index modulo 2.\n\n```\n if n % 2:\n```\n\nIf the size of the board n is odd\n\n```\n if row_swaps % 2:\n row_swaps = n - row_swaps\n```\n\nIf the number of row swaps is odd, you adjust it because you can\'t make an odd number of swaps to achieve the desired configuration. It becomes the complement, i.e., the difference from the total number of rows.\n\n```\n if col_swaps % 2:\n col_swaps = n - col_swaps\n```\n\nSimilarly, adjust column swaps if it\'s odd.\n\n```\n else:\n row_swaps = min(row_swaps, n - row_swaps)\n col_swaps = min(col_swaps, n - col_swaps)\n```\n\nIf n is even, for both rows and columns, choose the minimum between the calculated swaps and its complement. This ensures you always take the minimum number of swaps required.\n\n```\n return (row_swaps + col_swaps) // 2\n```\n\nFinally, return the total number of swaps required. We divide by 2 because for every two moves, we fix one position in both rows and columns.\n\n# Complexity\n- Time complexity:\nO(n^2)\n\n- Space complexity:\nO(1)\n\n# Code\n```\nclass Solution:\n def movesToChessboard(self, board: List[List[int]]) -> int:\n n = len(board)\n \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]:\n return -1\n \n row_sum = sum(board[0])\n col_sum = sum(board[i][0] for i in range(n))\n\n if not n//2 <= row_sum <= (n+1)//2:\n return -1\n if not n//2 <= col_sum <= (n+1)//2:\n return -1\n\n row_swaps = sum(board[i][0] == i % 2 for i in range(n))\n col_swaps = sum(board[0][i] == i % 2 for i in range(n))\n\n if n % 2:\n if row_swaps % 2:\n row_swaps = n - row_swaps\n if col_swaps % 2:\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``` | 3 | 0 | ['Array', 'Math', 'Bit Manipulation', 'Matrix', 'Python', 'Python3'] | 0 |
transform-to-chessboard | Python (Bipartite graph) | python-bipartite-graph-by-404akhan-ehlh | Consider bipartite graph of rows and columns. If row and column intersection has 1, then connect with an edge corresponding vertices in the graph. Swaping rows | 404akhan | NORMAL | 2021-11-10T11:57:18.353424+00:00 | 2021-11-10T11:59:35.807275+00:00 | 456 | false | Consider bipartite graph of rows and columns. If row and column intersection has `1`, then connect with an edge corresponding vertices in the graph. Swaping rows or columns correspond to swapping vertices in the graph. At the end we want to have chessboard construction, which implies that we have connected component of odd rows connected to all odd columns or to all even columns. And all even rows connected to other half of columns. So we will get two complete subgraphs which do not intersect with each other in our initial bipartite graph, and it is very intuitive that this is actually necessary and sufficient condition. So after understanding whether you have two such complete subgraphs, it is easy to compute number of swaps required to move all rows and columns inside the same subgraph to odd or even indexes. Done.\n\n```\nfrom collections import defaultdict\n\nclass Solution:\n def movesToChessboard(self, board):\n n = len(board)\n gr = defaultdict(set)\n\n for i in range(n):\n for j in range(n):\n if board[i][j]:\n gr[i].add(j + 2 * n)\n gr[j + 2 * n].add(i)\n\n def assign(base = 0):\n len_base, deg = len(gr[base]), n // 2\n if n % 2 == 0 and len_base != deg: return -1\n if n % 2 == 1 and not (0 <= len_base - deg <= 1): return -1\n\n first = {base}\n second = set()\n\n for j in range(base, base + n):\n intersection = gr[base] & gr[j]\n if len(intersection) == 0 and len(gr[j]) == n - len_base:\n second.add(j)\n elif len(intersection) == len_base and len(gr[j]) == len_base:\n first.add(j)\n else:\n return -1\n\n v1, v2 = sum(f % 2 for f in first), sum((f + 1) % 2 for f in first)\n\n if n % 2 == 1:\n return v2 if len(first) == deg else v1\n\n return min(v1, v2)\n\n v1, v2 = assign(), assign(2 * n)\n if v1 == -1 or v2 == -1: return -1\n return v1 + v2\n``` | 3 | 0 | [] | 1 |
transform-to-chessboard | using bit manipulation | using-bit-manipulation-by-mittal582-d5f1 | ```\nclass Solution {\npublic:\n int movesToChessboard(vector>& board) {\n set s;\n int n = board.size();\n \n for(auto& row : bo | mittal582 | NORMAL | 2021-09-26T10:32:14.744221+00:00 | 2021-09-27T13:14:38.486051+00:00 | 370 | false | ```\nclass Solution {\npublic:\n int movesToChessboard(vector<vector<int>>& board) {\n set<int> s;\n int n = board.size();\n \n for(auto& row : board) {\n int code = 0;\n for(int& num : row) {\n code = code*2 + num;\n }\n s.insert(code);\n }\n \n int r = check(s, n);\n if(r == -1) return -1;\n \n s.clear();\n for(int i = 0; i < n; i++) {\n int code = 0;\n for(int j = 0; j < n; j++) {\n code = code*2 + board[j][i];\n }\n s.insert(code);\n }\n \n int c = check(s, n);\n if(c == -1) return -1;\n \n return r+c;\n }\n \nprivate:\n int check(set<int>& s, int n){\n if(s.size() != 2) return -1;\n int k1 = *s.begin();\n \n int one = __builtin_popcount(k1);//count set bits\n if(one != n/2 && one != (n+1)/2) return -1;\n \n int none = (1 << n) -1;\n int k2 = *(++s.begin());\n k2 = k1^k2;\n if(k2 != none) return -1;\n one <<= 1;\n \n int c = INT_MAX; //count of swap\n \n if(one >= n)//if count of one in k1 is greater than equal to n/2. eg n = 5 and one = 3.\n c = min(c, __builtin_popcount(k1^(0x55555555 & none))/2);\n \n if(one <= n)//if count of one in k1 is equal to n/2. eg n = 5 and one = 2.\n c = min(c, __builtin_popcount(k1^(0xAAAAAAAA & none))/2);\n \n return c;\n }\n}; | 3 | 0 | [] | 2 |
transform-to-chessboard | C++ (ADDED EXPLANATION IN COMMENTS) | c-added-explanation-in-comments-by-sum_i-odel | \nclass Solution {\npublic:\n enum{COL,ROW};\n int addedXOR(vector<vector<int>>& board,int orientation,int index)\n {\n int res=0;\n if(o | sum_it_zzz | NORMAL | 2021-09-26T10:06:17.872113+00:00 | 2021-09-26T16:26:14.289040+00:00 | 306 | false | ```\nclass Solution {\npublic:\n enum{COL,ROW};\n int addedXOR(vector<vector<int>>& board,int orientation,int index)\n {\n int res=0;\n if(orientation==COL)\n for(int i=0;i<board.size();i++)\n res+=board[i][index]^board[i][index+1];\n else if(orientation==ROW)\n for(int i=0;i<board.size();i++)\n res+=board[index][i]^board[index+1][i];\n return res;\n }\n \n \n int movesToChessboard(vector<vector<int>>& board) \n {\n int totalMoves;\n int RequiredConfig1[board.size()],RequiredConfig2[board.size()];\n //generate 2 possible config of size N(ex:N=5 RequiredConfig1=01010 RequiredConfig2=10101)\n RequiredConfig1[0]=0;RequiredConfig2[0]=1;\n for(int i=1;i<board.size();i++)\n {\n RequiredConfig1[i]= RequiredConfig1[i-1]^1;\n RequiredConfig2[i]= RequiredConfig2[i-1]^1;\n }\n //check if valid(ADAJCENT ROWS AND COLUMNS SHOULD BE ALL SAME OR ALL DIFFERENT)\n for(int i=0;i<board.size()-1;i++)\n {\n int res=addedXOR(board,COL,i);\n if(res!=0&&res!=board.size())\n return -1;\n \n res=addedXOR(board,ROW,i);\n if(res!=0&&res!=board.size())\n return -1; \n }\n //get for 1st row and 1stcolumn(no of 1s,total diffs with 1st and 2nd RequiredConfig)\n int sumConfig1=0,sumConfig2=0,diff1=0,diff2=0,diff3=0,diff4=0;\n for(int i=0;i<board.size();i++)\n {\n sumConfig1+=board[0][i];\n diff1+=RequiredConfig1[i]^board[0][i];\n diff2+=RequiredConfig2[i]^board[0][i];\n sumConfig2+=board[i][0]; \n diff3+=RequiredConfig1[i]^board[i][0];\n diff4+=RequiredConfig2[i]^board[i][0]; \n }\n //handle saperately for even size and odd size\n if(!(board.size()%2))//even size\n {\n //calc no of required column swaps\n if(sumConfig1!=board.size()/2)//no of 1s should be exactly half of size\n return -1;\n totalMoves=min(diff1,diff2)/2;//half of min of total diffs from either Requiredconfig\n\t\t\t\n //calc no of required row swaps (similar to column swaps)\n if(sumConfig2!=board.size()/2)\n return -1;\n totalMoves+=min(diff3,diff4)/2; \n }\n else //odd size\n { \n //calc no of required column swaps\n //no of 1s should be exactly half of size or 1 greater\n if(sumConfig1!=board.size()/2&&sumConfig1!=board.size()/2+1)\n return -1;\n //if(no of 0s greater thann no of 1s) required swaps =half of diffs from RequiredConfig1\n if(sumConfig1==board.size()/2)\n totalMoves=diff1/2;\n else //else half of diffs from RequiredConfig2\n totalMoves=diff2/2;\n\t\t\t \n //calc no of required row swaps (similar to row swaps)\n if(sumConfig2!=board.size()/2&&sumConfig2!=board.size()/2+1)\n return -1;\n if(sumConfig2==board.size()/2)\n totalMoves+=diff3/2;\n else\n totalMoves+=diff4/2;\n }\n return totalMoves; \n }\n};\n``` | 3 | 0 | [] | 0 |
transform-to-chessboard | C++ O(N*N) solution | c-onn-solution-by-tt89-i8ab | \tclass Solution {\n\tpublic:\n\t\tint n;\n\t\tvector> arr;\n\n\t\tint getRow(vector &v,int x) {\n\t\t\tint ans=0;\n\t\t\tfor(int i=0;i<n;i++) {\n\t\t\t\tif(v[i | tt89 | NORMAL | 2021-09-26T10:02:08.394645+00:00 | 2021-09-26T10:02:08.394688+00:00 | 406 | false | \tclass Solution {\n\tpublic:\n\t\tint n;\n\t\tvector<vector<int>> arr;\n\n\t\tint getRow(vector<int> &v,int x) {\n\t\t\tint ans=0;\n\t\t\tfor(int i=0;i<n;i++) {\n\t\t\t\tif(v[i]!=x) ans++;\n\t\t\t\tx^=1;\n\t\t\t}\n\t\t\treturn ans;\n\t\t}\n\n\t\tint calc(vector<vector<int>> &v) {\n\t\t\tint ans1=0, x=0;\n\t\t\tfor(int i=0;i<n;i++) if(v[0][i]) x++;\n\t\t\tif(n%2) {\n\t\t\t\tif(x>n/2) x=1; else x=0;\n\t\t\t\tans1= getRow(v[0],x);\n\t\t\t}else ans1= min(getRow(v[0],0),getRow(v[0],1));\n\n\t\t\tint ans=0;\n\t\t\tfor(int i=0;i<n;i++) {\n\t\t\t\tbool b0= arr[i]==v[0];\n\t\t\t\tbool b1= arr[i]==v[1];\n\t\t\t\tif(!b0 && !b1) return -1;\n\n\t\t\t\tif(i%2 && b0) ans++;\n\t\t\t\telse if(i%2==0 && b1) ans++;\n\t\t\t}\n\n\t\t\tif(ans%2) return -1;\n\t\t\treturn ans/2+ans1/2;\n\n\t\t}\n\n\t\tint chk() {\n\t\t\tint c0=0,c1=0;\n\t\t\tfor(int i=0;i<n;i++) {\n\t\t\t\tif(arr[0][i]) c1++;\n\t\t\t\telse c0++;\n\t\t\t}\n\t\t\tif(n%2==0) {\n\t\t\t\tif(c0!=c1) return -1;\n\t\t\t}else {\n\t\t\t\tif(abs(c0-c1)!=1) return -1;\n\t\t\t}\n\n\t\t\tvector<vector<int>> v;\n\t\t\tvector<int> temp=arr[0];\n\t\t\tfor(int &i: temp) i^=1;\n\t\t\tv.push_back(arr[0]);\n\t\t\tv.push_back(temp);\n\t\t\tint x= calc(v);\n\t\t\tswap(v[0],v[1]);\n\t\t\tint y= calc(v);\n\n\t\t\tif(x==-1 && y==-1) return -1;\n\t\t\tif(x==-1) return y;\n\t\t\tif(y==-1) return x;\n\t\t\treturn min(x,y);\n\n\t\t}\n\n\t\tint movesToChessboard(vector<vector<int>>& arr) {\n\t\t\tn= arr.size();\n\t\t\tthis->arr= arr;\n\t\t\treturn chk();\n\t\t}\n\t}; | 3 | 1 | ['C'] | 0 |
transform-to-chessboard | Java XOR check | java-xor-check-by-hobiter-wm9w | Ref:https://leetcode.com/problems/transform-to-chessboard/discuss/114847/C%2B%2BJavaPython-Solution-with-Explanation\n\npublic int movesToChessboard(int[][] bd) | hobiter | NORMAL | 2020-06-07T16:42:10.026989+00:00 | 2020-06-07T16:42:54.380007+00:00 | 912 | false | Ref:https://leetcode.com/problems/transform-to-chessboard/discuss/114847/C%2B%2BJavaPython-Solution-with-Explanation\n```\npublic int movesToChessboard(int[][] bd) {\n int n = bd.length, rs = 0, cs = 0, ro = 0, co = 0;;\n for (int i = 0; i < n; i++) {\n co += bd[0][i];\n ro += bd[i][0];\n if (bd[0][i] != i % 2) cs++;\n if (bd[i][0] != i % 2) rs++;\n for (int j = 0; j < n; j++) {\n if ((bd[0][0] ^ bd[i][0] ^ bd[0][j] ^ bd[i][j]) > 0) return -1; //must be 4 zeros or 2 ones 2 zeros or 4 ones.\n }\n }\n if (co != n / 2 && co != (n + 1) / 2 ) return - 1;\n if (ro != n / 2 && ro != (n + 1) / 2 ) return - 1;\n if (n % 2 == 1) {\n if (rs % 2 == 1) rs = n - rs;\n if (cs % 2 == 1) cs = n - cs;\n } else {\n rs = Math.min(rs, n - rs);\n cs = Math.min(cs, n - cs);\n }\n return (rs + cs) / 2;\n }\n``` | 3 | 0 | [] | 1 |
transform-to-chessboard | C++ O(N^2) time solution with explantion | c-on2-time-solution-with-explantion-by-i-risb | Two rows are either the same or have opposite contents. This is equivalent to each 2x2 square has xor sum equal to zero. Then we need to move rows so that two r | imrusty | NORMAL | 2018-02-18T21:13:05.477693+00:00 | 2018-10-11T01:57:04.429779+00:00 | 1,086 | false | Two rows are either the same or have opposite contents. This is equivalent to each 2x2 square has xor sum equal to zero. Then we need to move rows so that two rows that are the same either occupie all even positions or all odd positions. Do the same for columns.
```
class Solution {
public:
int cal(vector<int> &v) {
int n = v.size();
int odd = 0, even = 0;
for (int i = 0; i < v.size(); ++i) if (v[i]) {
if (i & 1) ++odd;
else ++even;
}
if (abs(odd*2 + even*2 - n) > 1) return -n;
if (n & 1) {
if (odd + even > n/2) return odd;
return even;
}
return min(odd,even);
}
int movesToChessboard(vector<vector<int>>& b) {
int n = b.size();
for (int i = 1; i < n; ++i) {
for (int j = 1; j < n; ++j)
if (b[i][j] ^ b[i-1][j] ^ b[i][j-1] ^ b[i-1][j-1]) return -1;
}
vector<int> c;
for (int i = 0; i < n;++i) c.push_back(b[i][0]);
return max(cal(b[0]) + cal(c),-1);
}
};
``` | 3 | 1 | [] | 1 |
transform-to-chessboard | [Python3] Four rounds of check before counting min number of swaps | python3-four-rounds-of-check-before-coun-ws2u | \nclass Solution:\n def build_pat(self, lst: List[int]) -> int:\n """Build a pattern out of a given list of 1s and 0s"""\n n = len(lst)\n | fanchenbao | NORMAL | 2021-09-27T01:34:27.779311+00:00 | 2021-10-01T18:17:43.009868+00:00 | 212 | false | ```\nclass Solution:\n def build_pat(self, lst: List[int]) -> int:\n """Build a pattern out of a given list of 1s and 0s"""\n n = len(lst)\n pat = 0\n for i in range(n):\n pat |= (lst[i] << (n - i - 1))\n return pat\n\n def count_swap(self, pat: int, val1: int, val2: int) -> int:\n """Count the min number of swaps to go from pat to either val1 or val2.\n\n Note that the number of 1s in the result of XOR must be even for swap\n to be possible\n\n :param pat: The current pattern.\n :param val1: One of the valid final pattern on the chessboard.\n :param val2: The other valid final pattern on the chessboard.\n """\n swap1 = bin(pat ^ val1).count(\'1\')\n swap2 = bin(pat ^ val2).count(\'1\')\n return min(\n swap1 if swap1 % 2 == 0 else math.inf,\n swap2 if swap2 % 2 == 0 else math.inf,\n ) // 2\n\n def movesToChessboard(self, board: List[List[int]]) -> int:\n """LeetCode 782\n\n This problem is not difficult in terms of using some smart algorithm.\n But it is complex because there are a lot of tricks to go through to\n help one realize that this problem does not require smart algorithm.\n\n First, we identify that to make a chessboard possible, each row must\n have equal number of 1s and 0s or the number of one value only one larger.\n If this requirement is not satisfied, we can return -1 immediately.\n\n Second, among all the rows, there must only be two patterns. This is\n because in the final chessboard, there are only two patterns for all the\n rows. Since swapping columns do not add or minus row patterns, we must\n start with two row patterns.\n\n Third, the two row patterns must complement each other. Otherwise, there\n must exist some swap on one row that will have no effect on the other\n row. e.g. pat1 = 0110, pat2 = 0010. Swapping the first two element of\n pat1 will not change pat2, which means we cannot make both patterns\n correct at the same time. This requirement can translate to pat1 ^ pat2\n == (1 << n) - 1\n\n Fourth, the number of each row pattern must be equal or differ only by\n one.\n\n Interestingly, once the rows satisfy the above-mentioned four requirements\n the cols automatically also become valid. Then, we just need to find\n the min number of moves to swap the rows and the cols. Add them together,\n and we have the result. To find the min number of swaps, we create masks\n for the two valid final state val1, val2. We only need to check for one\n of the row and col pattern. We use XOR and then count the number of 1s\n in the result. The number of 1s indicate the number of mismatches\n between the current pattern and the valid pattern. Also, the number of\n 1s must be even, because each pair of 1s indicate a swap. Odd number of\n 1s doesn\'t work.\n\n O(N^2) time complexity. 76 ms, 88% ranking.\n """\n n = len(board)\n counter = Counter()\n mask = (1 << n) - 1\n for row in board:\n one_count = row.count(1)\n if abs(one_count - (n - one_count)) > 1:\n return -1\n counter[self.build_pat(row)] += 1\n if len(counter) != 2:\n return -1\n pat1, pat2 = counter.keys()\n if pat1 ^ pat2 != mask:\n return -1\n if abs(counter[pat1] - counter[pat2]) > 1:\n return -1\n # At this point, we are certain that the chessboard can be created.\n \n # Obtain the two valid states for each row and col\n val1 = 0\n for i in range(n - 1, -1, -2):\n val1 |= (1 << i)\n val2 = val1 ^ mask\n return self.count_swap(pat1, val1, val2) + self.count_swap(\n self.build_pat([board[i][0] for i in range(n)]),\n val1,\n val2,\n )\n``` | 2 | 0 | [] | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.