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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
array-reduce-transformation
|
Easy to understand, less memory consuming solution
|
easy-to-understand-less-memory-consuming-mtso
|
Intuition\nGiven an integer array nums, a reducer function fn, and an initial value init, return a reduced array.\n\nA reduced array is created by applying the
|
krish2213
|
NORMAL
|
2023-05-10T15:46:42.345959+00:00
|
2023-05-10T15:46:42.345983+00:00
| 11 | false |
# Intuition\nGiven an integer array nums, a reducer function fn, and an initial value init, return a reduced array.\n\nA reduced array is created by applying the following operation: val = fn(init, nums[0]), val = fn(val, nums[1]), val = fn(val, nums[2]), ... until every element in the array has been processed. The final value of val is returned\n\n# Code\n```\n/**\n * @param {number[]} nums\n * @param {Function} fn\n * @param {number} init\n * @return {number}\n */\nvar reduce = function(nums, fn, init) {\n for(i = 0;i<nums.length;i++){\n init = fn(init,nums[i]);\n \n }\n return init;\n};\n```
| 1 | 0 |
['JavaScript']
| 0 |
array-reduce-transformation
|
Simple || Easy || JS
|
simple-easy-js-by-rajat-ds-r4lh
|
/*\n * @param {number[]} nums\n * @param {Function} fn\n * @param {number} init\n * @return {number}\n /\n\nvar reduce = function(nums, fn, init) {\n let val
|
rajat-ds
|
NORMAL
|
2023-05-10T13:53:25.447547+00:00
|
2023-05-10T13:53:25.447587+00:00
| 379 | false |
/**\n * @param {number[]} nums\n * @param {Function} fn\n * @param {number} init\n * @return {number}\n */\n```\nvar reduce = function(nums, fn, init) {\n let val = init \n for( let i = 0 ; i < nums.length ; i++ ){\n val =fn(val,nums[i])\n }\n return val\n};\n```
| 1 | 0 |
[]
| 0 |
array-reduce-transformation
|
Array Reduce Transformation
|
array-reduce-transformation-by-agrawalni-fz4d
|
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
|
agrawalnishant90
|
NORMAL
|
2023-05-10T13:01:47.366533+00:00
|
2023-05-10T13:01:47.366581+00:00
| 21 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n/**\n * @param {number[]} nums\n * @param {Function} fn\n * @param {number} init\n * @return {number}\n */\nvar reduce = function(nums, fn, init) {\n if (nums.length==0){ //if length of array is 0\n return init;\n }\n let res = init;\n\n for(let i=0; i<nums.length;i++){\n res = fn(res, nums[i])\n }\n return res;\n};\n```
| 1 | 0 |
['Array', 'JavaScript']
| 0 |
array-reduce-transformation
|
4 different methods
|
4-different-methods-by-__shruti-2zfd
|
\n/*\n * @param {number[]} nums\n * @param {Function} fn\n * @param {number} init\n * @return {number}\n /\n\n //Method 1\n\n// var reduce = function(nums, fn,
|
__shruti__
|
NORMAL
|
2023-05-10T05:46:17.228620+00:00
|
2023-05-10T05:46:17.228653+00:00
| 263 | false |
\n/**\n * @param {number[]} nums\n * @param {Function} fn\n * @param {number} init\n * @return {number}\n */\n\n //Method 1\n\n// var reduce = function(nums, fn, init) {\n// let val=init;\n// for(let i=0;i<nums.length;i++){\n// val=fn(val,nums[i]);\n// }\n// return val;\n// };\n\n// METHOD 2\n// var reduce = function(nums, fn, init) {\n// let val=init;\n// for(const i of nums){ //used \'of\' as we are accessing directly values\n// val=fn(val,i);\n// }\n// return val;\n// };\n\n//METHOD 3\n// var reduce=function(nums,fn,init){\n// let val=init;\n// nums.forEach((n)=> val=fn(val,n));\n// return val;\n// }\n\n//METHOD 4 directly use reduce function\nvar reduce =function(nums,fn,init){\n return nums.reduce(fn,init)\n \n}\n```
| 1 | 0 |
['JavaScript']
| 0 |
array-reduce-transformation
|
Simple Javascript solution using for-of loop
|
simple-javascript-solution-using-for-of-i7qtn
|
\nvar reduce = function(nums, fn, init) {\n for(let i of nums)\n {\n init=fn(init,i)\n }\n return init;\n};\n
|
sh183215---
|
NORMAL
|
2023-05-06T13:52:50.622786+00:00
|
2023-05-06T13:53:08.976836+00:00
| 16 | false |
```\nvar reduce = function(nums, fn, init) {\n for(let i of nums)\n {\n init=fn(init,i)\n }\n return init;\n};\n```
| 1 | 0 |
['JavaScript']
| 0 |
array-reduce-transformation
|
My javaScript solution
|
my-javascript-solution-by-pravesh2892-49nf
|
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
|
Pravesh2892
|
NORMAL
|
2023-04-22T03:03:23.107735+00:00
|
2023-04-22T03:03:23.107769+00:00
| 88 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n/**\n * @param {number[]} nums\n * @param {Function} fn\n * @param {number} init\n * @return {number}\n */\nvar reduce = function(nums, fn, init) {\n if(!nums.length){\n return init;\n } \n let sum=init;\n for(let value of nums){\n sum = fn(sum, value);\n }\n return sum;\n};\n```
| 1 | 0 |
['JavaScript']
| 0 |
array-reduce-transformation
|
✅ Simple Easy 🔥JavaScript || 🔥TypeScript Solution || Begineer Friendly ✅
|
simple-easy-javascript-typescript-soluti-mg1r
|
Code\nTypeScript []\ntype Fn = (accum: number, curr: number) => number\n\nfunction reduce(nums: number[], fn: Fn, init: number): number {\n for (let i of num
|
0xsonu
|
NORMAL
|
2023-04-13T04:02:27.641696+00:00
|
2023-04-13T04:02:43.110852+00:00
| 42 | false |
# Code\n```TypeScript []\ntype Fn = (accum: number, curr: number) => number\n\nfunction reduce(nums: number[], fn: Fn, init: number): number {\n for (let i of nums)\n init = fn(init, i);\n return init;\n};\n```\n```JavaScript []\n/**\n * @param {number[]} nums\n * @param {Function} fn\n * @param {number} init\n * @return {number}\n */\nvar reduce = function(nums, fn, init) {\n for (let i of nums)\n init = fn(init, i);\n return init;\n};\n```
| 1 | 0 |
['TypeScript', 'JavaScript']
| 0 |
array-reduce-transformation
|
Custom "Array.reduce()" Method
|
custom-arrayreduce-method-by-masuten11-nwhn
|
IntuitionSo, this is basically how the Array.prototype.reduce() method works. It takes an initial value (set up to first value of the array if not added), and a
|
masuten11
|
NORMAL
|
2025-04-11T17:38:12.863597+00:00
|
2025-04-11T17:38:12.863597+00:00
| 1 | false |
# Intuition
So, this is basically how the Array.prototype.reduce() method works. It takes an initial value (set up to first value of the array if not added), and applies a function to each element in the array, updating an accumulator along the way.
# Approach
Loop through the array and update the accumulator using the given function on each element. Making sure to reassign acccumulator with the updated value on each iteration.
# Complexity
- Time complexity:
𝑂
(
𝑛
)
O(n)
- Space complexity:
𝑂
(
1
)
O(1)
****Bold****
# Code
```javascript []
/**
* @param {number[]} nums
* @param {Function} fn
* @param {number} init
* @return {number}
*/
var reduce = function(nums, fn, init) {
let reducedVal = init;
for (let i = 0; i < nums.length; i++) {
reducedVal = fn(reducedVal, nums[i])
}
return reducedVal;
};
```
| 0 | 0 |
['JavaScript']
| 0 |
array-reduce-transformation
|
Simple solution
|
simple-solution-by-aandresantos-lb03
|
Approach
Check if has values
Create the accumulator based in initial value (init)
Traverse all nums (array) using a for loop - you can use a forEach too
If res
|
aandresantos
|
NORMAL
|
2025-04-09T13:39:40.278641+00:00
|
2025-04-09T13:39:40.278641+00:00
| 1 | false |
# Approach
1. Check if has values
2. Create the accumulator based in initial value (init)
3. Traverse all nums (array) using a for loop - you can use a forEach too
4. If res accumulator is equal zero, return zero
# Code
```typescript []
type Fn = (accum: number, curr: number) => number
function reduce(nums: number[], fn: Fn, init: number): number {
if(!nums.length) return init
let res = init
for(let i = 0; i < nums.length; i++) {
res = fn(res, nums[i])
}
if(res === 0) return 0
return res
};
```
| 0 | 0 |
['TypeScript']
| 0 |
array-reduce-transformation
|
Solution in Typescript. Works fast :3
|
solution-in-typescript-works-fast-3-by-s-ght4
|
IntuitionThink of it like stacking blocks on top of one another, where each block is an element of the array.ApproachSteps
Created a variable named res
Added in
|
suvrat_bhatta
|
NORMAL
|
2025-04-08T16:49:12.620709+00:00
|
2025-04-08T16:49:12.620709+00:00
| 1 | false |
# Intuition
Think of it like stacking blocks on top of one another, where each block is an element of the array.
# Approach
## Steps
1. Created a variable named `res`
2. Added `init` to `res`
3. Looped through the length of array (`nums.length`) and ran each element of array through the function.
4. Returned `res`
## Important detail
- `accum`: Accumulated result throughout the iteration
- `curr`: The current value being passed to the function. First element in first iteration, second in second iteration, etc.
# Complexity
- Time complexity: O(N)
- Space complexity: O(1)
# Code
```typescript []
type Fn = (accum: number, curr: number) => number
function reduce(nums: number[], fn: Fn, init: number): number {
let res: number = init
for(let i: number = 0; i < nums.length; i++){
res = fn(res, nums[i])
}
return res;
};
```
| 0 | 0 |
['TypeScript']
| 0 |
array-reduce-transformation
|
Easy solution using forEach!!
|
easy-solution-using-foreach-by-jeromejam-t0f9
|
IntuitionApproachComplexity
Time complexity:
Space complexity:
Code
|
JeromeJames
|
NORMAL
|
2025-04-06T08:09:52.053336+00:00
|
2025-04-06T08:09:52.053336+00:00
| 1 | false |
# Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```javascript []
/**
* @param {number[]} nums
* @param {Function} fn
* @param {number} init
* @return {number}
*/
var reduce = function(nums, fn, init) {
nums.forEach((num) => {
init = fn(init, num);
});
return init;
};
```
| 0 | 0 |
['JavaScript']
| 0 |
array-reduce-transformation
|
Easy solution !!
|
easy-solution-by-jeromejames-578y
|
IntuitionApproachComplexity
Time complexity:
Space complexity:
Code
|
JeromeJames
|
NORMAL
|
2025-04-06T08:08:34.248320+00:00
|
2025-04-06T08:08:34.248320+00:00
| 0 | false |
# Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```javascript []
/**
* @param {number[]} nums
* @param {Function} fn
* @param {number} init
* @return {number}
*/
var reduce = function(nums, fn, init) {
nums.forEach((num) => {
init = fn(init, num);
});
return init;
};
```
| 0 | 0 |
['JavaScript']
| 0 |
array-reduce-transformation
|
Easy solution !!
|
easy-solution-by-jeromejames-wkeq
|
IntuitionApproachComplexity
Time complexity:
Space complexity:
Code
|
JeromeJames
|
NORMAL
|
2025-04-06T08:08:31.655764+00:00
|
2025-04-06T08:08:31.655764+00:00
| 1 | false |
# Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```javascript []
/**
* @param {number[]} nums
* @param {Function} fn
* @param {number} init
* @return {number}
*/
var reduce = function(nums, fn, init) {
nums.forEach((num) => {
init = fn(init, num);
});
return init;
};
```
| 0 | 0 |
['JavaScript']
| 0 |
array-reduce-transformation
|
Javascript Beats 93.29%, using forEach method
|
javascript-beats-9329-using-foreach-meth-7z96
|
IntuitionApproachComplexity
Time complexity:
Space complexity:
Code
|
amitrathee729
|
NORMAL
|
2025-04-03T11:46:09.561006+00:00
|
2025-04-03T11:46:09.561006+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
```javascript []
/**
* @param {number[]} nums
* @param {Function} fn
* @param {number} init
* @return {number}
*/
var reduce = function(nums, fn, init) {
let acc = init;
nums.forEach((e, i) => {
acc = fn(acc, nums[i])
})
return acc;
};
```
| 0 | 0 |
['JavaScript']
| 0 |
array-reduce-transformation
|
Array Reduction Transformation
|
array-reduction-transformation-by-aikiii-vfma
|
IntuitionApproachComplexity
Time complexity:
Space complexity:
Code
|
aikiii
|
NORMAL
|
2025-04-02T05:47:27.233523+00:00
|
2025-04-02T05:47:27.233523+00:00
| 1 | false |
# Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```javascript []
/**
* @param {number[]} nums
* @param {Function} fn
* @param {number} init
* @return {number}
*/
var reduce = function(nums, fn, init)
{
let answer=init;
for(let i=0;i<nums.length;i++)
answer=fn(answer,nums[i]);
return answer;
};
```
| 0 | 0 |
['JavaScript']
| 0 |
array-reduce-transformation
|
44 ms Beats 69.74%
|
44-ms-beats-6974-by-gunanshu_joshi-bjko
|
IntuitionThe problem requires applying a function cumulatively to each element of an array, starting with an initial value. This is essentially a reduction oper
|
gunanshu_joshi
|
NORMAL
|
2025-03-31T13:30:10.738716+00:00
|
2025-03-31T13:30:10.738716+00:00
| 2 | false |
# Intuition
The problem requires applying a function cumulatively to each element of an array, starting with an initial value. This is essentially a reduction operation, where we "reduce" the array to a single value.
# Approach
We can iterate through the `nums` array and apply the provided function `fn` to the current accumulated value (`ans`) and the current element. We initialize the accumulated value with `init`. In each iteration, we update `ans` with the result of `fn(ans, nums[i])`. Finally, we return the accumulated value `ans`.
# Complexity
- Time complexity:
$$O(n)$$
where *n* is the length of the `nums` array. We iterate through the array once.
- Space complexity:
$$O(1)$$
We use a constant amount of extra space, regardless of the input size.
# Code
```javascript []
/**
* @param {number[]} nums
* @param {Function} fn
* @param {number} init
* @return {number}
*/
var reduce = function(nums, fn, init) {
let ans = init;
for(let i = 0;i<nums.length;i++){
ans = fn(ans, nums[i]);
}
return ans;
};
| 0 | 0 |
['JavaScript']
| 0 |
array-reduce-transformation
|
myAnswer
|
myanswer-by-rwc8cinz7h-p572
|
IntuitionApproachComplexity
Time complexity:
Space complexity:
Code
|
RwC8cINz7h
|
NORMAL
|
2025-03-29T20:19:42.203573+00:00
|
2025-03-29T20:19:42.203573+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
```javascript []
/**
* @param {number[]} nums
* @param {Function} fn
* @param {number} init
* @return {number}
*/
var reduce = function(nums, fn, init) {
return nums.reduce(fn,init)
};
```
| 0 | 0 |
['Java', 'JavaScript']
| 0 |
array-reduce-transformation
|
Array Reduce Transformation
|
array-reduce-transformation-by-ossine-ce28
|
IntuitionHere we can use javascript reduce method to solve the questionApproachFirst define the output variable and assign it to 0.
Next applying the reduce met
|
Ossine
|
NORMAL
|
2025-03-27T06:44:59.722695+00:00
|
2025-03-27T06:44:59.722695+00:00
| 4 | false |
# Intuition
Here we can use javascript reduce method to solve the question
# Approach
First define the output variable and assign it to 0.
Next applying the reduce method to nums array with two parameters accum and curr, and called the fn funtion with passing those arguments as fn(accum,curr) and assign the reduced result to output variable and return it.
Next creating the sum function and returning the aggregate result.
Now calling the reduce function with given arguments such nums,sum and 0 as
reduce(nums,sum,0)
# Complexity
- Time complexity: O(n)
- Space complexity: O(n)
# Code
```javascript []
/**
* @param {number[]} nums
* @param {Function} fn
* @param {number} init
* @return {number}
*/
var reduce = function (nums, fn, init) {
let output = 0;
output = nums.reduce((accum, curr) => fn(accum, curr), init)
return output;
};
const nums = [1, 2, 3, 4];
const sum = (accum, curr) => {
return accum + curr
}
reduce(nums, sum, 0);
```
Output:

| 0 | 0 |
['JavaScript']
| 0 |
array-reduce-transformation
|
Array Reduce Transformation
|
array-reduce-transformation-by-naeem_abd-3zoi
|
IntuitionApproachComplexity
Time complexity:
Space complexity:
Code
|
Naeem_ABD
|
NORMAL
|
2025-03-26T13:06:09.765312+00:00
|
2025-03-26T13:06:09.765312+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
```javascript []
var reduce = function(nums, fn, init) {
let val = init;
for (let i = 0; i < nums.length; i++) {
val = fn(val, nums[i]);
}
return val;
};
```
| 0 | 0 |
['JavaScript']
| 0 |
array-reduce-transformation
|
Array Reduce Transformation
|
array-reduce-transformation-by-shalinipa-kpd3
|
IntuitionApproachComplexity
Time complexity:
Space complexity:
Code
|
ShaliniPaidimuddala
|
NORMAL
|
2025-03-25T08:36:20.346701+00:00
|
2025-03-25T08:36:20.346701+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
```javascript []
/**
* @param {number[]} nums
* @param {Function} fn
* @param {number} init
* @return {number}
*/
var reduce = function(nums, fn, init) {
var val=0;
if(nums.length>0) val=fn(init, nums[0]);
else return init;
for(var i=1;i<nums.length;i++)
{
val=fn(val, nums[i]);
}
return val;
};
```
| 0 | 0 |
['JavaScript']
| 0 |
array-reduce-transformation
|
JavaScript Solution - Array Reduce Transformation
|
javascript-solution-array-reduce-transfo-jysi
|
IntuitionTo iterate each element in the given nums array and updating val on every iteration with the new value is returned by fn method.Approach
Create the new
|
user9264Uv
|
NORMAL
|
2025-03-25T07:45:42.191669+00:00
|
2025-03-25T07:45:42.191669+00:00
| 3 | false |
# Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
To iterate each element in the given `nums` array and updating `val` on every iteration with the new value is returned by `fn` method.
# Approach
<!-- Describe your approach to solving the problem. -->
1. Create the new variable `val` and assign the `init` value into that variable.
2. Iterate the each element of the `nums` array using `for` loop.
3. Execute the `fn(val, nums[i])` and updating the return value into the existing variable `val`.
4. return the accumulated `val`
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```javascript []
/**
* @param {number[]} nums
* @param {Function} fn
* @param {number} init
* @return {number}
*/
var reduce = function(nums, fn, init) {
let val = init
for (let i = 0; i < nums.length; i++) {
val = fn(val, nums[i])
}
return val
};
```
| 0 | 0 |
['JavaScript']
| 0 |
array-reduce-transformation
|
EASIEST! solution
|
easiest-solution-by-rohandwivedi2005-vizb
|
IntuitionApproachComplexity
Time complexity:
Space complexity:
Code
|
RohanDwivedi2005
|
NORMAL
|
2025-03-25T06:52:08.504379+00:00
|
2025-03-25T06:52:08.504379+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
```javascript []
/**
* @param {number[]} nums
* @param {Function} fn
* @param {number} init
* @return {number}
*/
var reduce = function(nums, fn, init) {
let num = init;
for(let i=0;i<nums.length;i++){
num = fn(num , nums[i] )
}
return num;
};
```
| 0 | 0 |
['JavaScript']
| 0 |
array-reduce-transformation
|
Beats 99.61% on speed.
|
beats-9961-on-speed-by-mtrafto-ynhl
|
Code
|
mtrafto
|
NORMAL
|
2025-03-24T10:34:28.826311+00:00
|
2025-03-24T10:34:28.826311+00:00
| 3 | false |
# Code
```typescript []
type Fn = (accum: number, curr: number) => number
function reduce(nums: number[], fn: Fn, init: number): number {
let res: number = init;
for (let i = 0; i < nums.length; i++) {
res = fn(res, nums[i])
}
return res
};
```
| 0 | 0 |
['TypeScript']
| 0 |
array-reduce-transformation
|
Custom Reduce Function
|
custom-reduce-function-by-abhikhatri67-91lz
|
IntuitionThe problem requires us to implement a custom reduce function that mimics the behavior of the built-in Array.prototype.reduce. The key idea is to itera
|
abhikhatri67
|
NORMAL
|
2025-03-22T16:35:48.825116+00:00
|
2025-03-22T16:35:48.825116+00:00
| 4 | false |
# Intuition
The problem requires us to implement a custom reduce function that mimics the behavior of the built-in Array.prototype.reduce. The key idea is to iteratively apply a callback function (fn) to an accumulator (init) and each element of the array, updating the accumulator at every step. If the input array is empty, the function should simply return the initial value (init).
# Approach
1. Check if the input array nums is empty:
If nums.length === 0, directly return the initial value (init).
2. Iterate through the elements of the nums array using a for loop.
3. In each iteration, update the init value by applying the callback function (fn) with the current accumulator (init) and the current element (nums[i]).
4. After the loop completes, return the final value of the accumulator (init).
This approach simulates the behavior of the built-in reduce function without relying on built-in methods.
# Complexity
- Time complexity:
O(n) - Where n is the number of elements in the array. We iterate through the array once.
- Space complexity:
O(1) - No additional space is used apart from a few variables to store the accumulator and loop index.
# Code
```javascript []
/**
* @param {number[]} nums
* @param {Function} fn
* @param {number} init
* @return {number}
*/
var reduce = function(nums, fn, init) {
if (nums.length === 0) return init;
for (let i=0; i<nums.length; i++) {
init = fn(init, nums[i]);
}
return init;
};
```
| 0 | 0 |
['JavaScript']
| 0 |
array-reduce-transformation
|
2626:- Array Reduce Transformation - LeetCode Solution
|
2626-array-reduce-transformation-leetcod-v6m5
|
IntuitionThe problem requires us to apply a reducer function to an array and return a single accumulated value. This is similar to JavaScript's built-in reduce(
|
runl4AVDwJ
|
NORMAL
|
2025-03-21T07:54:33.354334+00:00
|
2025-03-21T07:54:33.354334+00:00
| 3 | false |
# **Intuition**
The problem requires us to apply a reducer function to an array and return a single accumulated value. This is similar to JavaScript's built-in `reduce()` method, where we iterate through the array, applying the function at each step while keeping track of an intermediate value.
# **Approach**
I explored **three different approaches** to implement this:
---
# 🔹 **Approach 1: Using `for` Loop**
```js
var reduce = function (nums, fn, init) {
let val = init;
for (let i = 0; i < nums.length; i++) {
val = fn(val, nums[i]);
}
return val;
};
```
📌 **Explanation:**
- We initialize `val` with `init`.
- The `for` loop iterates over each element, updating `val` by applying the function `fn(val, nums[i])`.
- Finally, we return `val` after all iterations.
- **This is a straightforward and readable approach.**
---
# 🔹 **Approach 2: Using `for` Loop with Direct Assignment**
```js
var reduce = (nums, fn, init) => {
for (let i = 0; i < nums.length; i++) {
init = fn(init, nums[i]);
}
return init;
};
```
📌 **Why is this different?**
- Instead of using an extra variable `val`, we directly update `init`.
- This makes the code **more concise** while maintaining efficiency.
---
# 🔹 **Approach 3: Using `forEach()` (Best & Optimized)**
```js
var reduce = (nums, fn, init) => {
nums.forEach((val) => {
init = fn(init, val);
});
return init;
};
```
📌 **Why is this better?**
- Uses **JavaScript’s built-in `forEach()` method**, which makes it more **readable**.
- Eliminates the need for manual index handling.
- **Cleaner and more maintainable code**.
---
# **Complexity Analysis**
- **Time Complexity:**
- $$O(n)$$ → We iterate through the array once, applying the function to each element.
- **Space Complexity:**
- $$O(1)$$ → We use only a constant amount of extra space for the accumulator.
---
# **Code**
```js
/**
* @param {number[]} nums
* @param {Function} fn
* @param {number} init
* @return {number}
*/
var reduce = (nums, fn, init) => {
nums.forEach((val) => {
init = fn(init, val);
});
return init;
};
```
---
# **Important Topics to Learn 📚**
- **Higher-Order Functions**: Functions that take other functions as arguments (like `reduce`).
- **Iteration Methods**: Understanding `forEach()`, `reduce()`, `map()`, and `filter()` in JavaScript.
- **Callback Functions**: How functions can be passed as arguments and executed dynamically.
---
# 🚀 **Support & Feedback**
✅ If you found this helpful, **please upvote & comment** on my solution!
💬 Let’s discuss alternative solutions & improvements! 🚀
| 0 | 0 |
['JavaScript']
| 0 |
array-reduce-transformation
|
Best Solution
|
best-solution-by-dheeraj0522-y1bt
|
IntuitionApproachComplexity
Time complexity:
Space complexity:
Code
|
Dheeraj0522
|
NORMAL
|
2025-03-19T15:03:27.820188+00:00
|
2025-03-19T15:03:27.820188+00:00
| 1 | false |
# Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```javascript []
/**
* @param {number[]} nums
* @param {Function} fn
* @param {number} init
* @return {number}
*/
var reduce = function(nums, fn, init)
/* Function reduce banaya jo:
nums → Array lega.
fn → Function jo har element pe apply hoga.
init → Shuruaati value jo result me store hoga.
*/
{
let result = init;
// result variable ko init se initialize kiya, jo computation start karega.
for(let i=0; i < nums.length; i++)
/* Loop chalaya jo array ke har element pe chalega.
i → Index ko represent karega.
nums[i] → Current element ko represent karega.
*/
{
result = fn(result, nums[i]);
/* Har step pe function apply hoga:
fn(result, nums[i]) → Function ko current result aur current element ke saath call kar rahe hain.
result = ... → Jo bhi function return karega, woh result me store ho jayega.
*/
}
return result;
};
```
| 0 | 0 |
['JavaScript']
| 0 |
array-reduce-transformation
|
Typescript O(N) Solution with reduce (93.88% Runtime)
|
typescript-on-solution-with-reduce-9388-p81s4
|
IntuitionApproach
Apply the given function (fn) inside the given array's reduce function.
(I'm a typescript newbie so there should be more good solutions)
Compl
|
missingdlls
|
NORMAL
|
2025-03-17T14:37:12.334212+00:00
|
2025-03-17T14:37:12.334212+00:00
| 1 | false |
# Intuition
<!-- Describe your first thoughts on how to solve this problem. -->

# Approach
<!-- Describe your approach to solving the problem. -->
- Apply the given function (fn) inside the given array's reduce function.
- (I'm a typescript newbie so there should be more good solutions)
# Complexity
- Time complexity: O(N)
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity: O(1)
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
If this solution is similar to yours or helpful, upvote me if you don't mind
```typescript []
type Fn = (accum: number, curr: number) => number
function reduce(nums: number[], fn: Fn, init: number): number {
return nums.reduce((n, acc) => fn(n, acc), init)
};
```
| 0 | 0 |
['Array', 'Math', 'Iterator', 'TypeScript', 'JavaScript']
| 0 |
array-reduce-transformation
|
Simple Reduce
|
simple-reduce-by-ronitbl-xaqd
|
IntuitionApproachComplexity
Time complexity:
Space complexity:
Code
|
RonitBL
|
NORMAL
|
2025-03-14T23:11:27.779006+00:00
|
2025-03-14T23:11:27.779006+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
```javascript []
/**
* @param {number[]} nums
* @param {Function} fn
* @param {number} init
* @return {number}
*/
var reduce = function (nums, fn, init) {
var len = nums.length;
var val = 0;
if (len === 0) return init;
val = fn(init, nums[0]);
for (var i = 1; i <= len - 1; i++) {
val = fn(val, nums[i]);
}
return val;
};
```
| 0 | 0 |
['JavaScript']
| 0 |
array-reduce-transformation
|
For beginner's
|
for-beginners-by-yogi122005-mj8j
|
IntuitionApproachComplexity
Time complexity:
Space complexity:
Code
|
yogi122005
|
NORMAL
|
2025-03-13T13:02:55.425018+00:00
|
2025-03-13T13:02:55.425018+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
```javascript []
var reduce = function(nums, fn, init) {
let result = init;
for(let i=0;i<nums.length;i++){
result = fn(result,nums[i]);
}
return result;
};
```
| 0 | 0 |
['JavaScript']
| 0 |
array-reduce-transformation
|
Time complexity:
|
time-complexity-by-shahidkhanwazirstan-np6q
|
IntuitionApproachComplexity
Time complexity:
Space complexity:
Code
|
shahidkhanwazirstan
|
NORMAL
|
2025-03-13T10:52:18.847238+00:00
|
2025-03-13T10:52:18.847238+00:00
| 1 | false |
# Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```javascript []
/**
* @param {number[]} nums
* @param {Function} fn
* @param {number} init
* @return {number}
*/
var reduce = function(nums, fn, init) {
let val = init;
for (let i = 0; i < nums.length; i++){
val = fn(val, nums[i])
}
return val
};
```
| 0 | 0 |
['JavaScript']
| 0 |
split-array-into-maximum-number-of-subarrays
|
Zero Score
|
zero-score-by-votrubac-8zjd
|
We can split the array only if the score of all subarrays is zero.\n\nIf the score of the entire array is not zero but m, then the score of any subarray cannot
|
votrubac
|
NORMAL
|
2023-09-30T16:00:34.284924+00:00
|
2023-09-30T22:13:37.546670+00:00
| 2,821 | false |
We can split the array only if the score of all subarrays is zero.\n\nIf the score of the entire array is not zero but `m`, then the score of any subarray cannot be less than `m`. Therefore, any split will add at least `m` to the sum.\n \nSo, we count subarrays with the zero score.\n\n**C++**\n```cpp \nint maxSubarrays(vector<int>& nums) {\n int res = 0, cur = 0;\n for (int n : nums) {\n cur = cur == 0 ? n : cur & n;\n res += cur == 0;\n }\n return max(1, res);\n}\n```
| 65 | 0 |
[]
| 16 |
split-array-into-maximum-number-of-subarrays
|
[Java/C++/Python] One Pass, Count Zero Score
|
javacpython-one-pass-count-zero-score-by-t8xm
|
Intuition\nBecause (x & y) <= x and (x & y) <= y,\nso the score(array) <= score(subarray).\n\nIf the score of A is x,\nthen the score of each subarray of A bigg
|
lee215
|
NORMAL
|
2023-09-30T16:01:40.435953+00:00
|
2023-09-30T16:09:39.237093+00:00
| 2,595 | false |
# **Intuition**\nBecause `(x & y) <= x` and `(x & y) <= y`,\nso the `score(array) <= score(subarray)`.\n\nIf the score of `A` is `x`,\nthen the score of each subarray of `A` bigger or equal to `x`.\n\nIf `x > 0`,\n`2x > x`,\nso we won\'t split `A`,\nreturn 1.\n\nIf `x == 0`,\nso we may split `A`,\ninto multiple subarray with score `0`.\n\nSo the real problem is,\nsplit `A` into as many subarray as possbile,\nwith socre `0`\n<br>\n\n# **Explanation**\nCalculate the prefix score of `A`,\nif score is `0`,\nwe can split out the prefix as a subarray with socre `0`,\nthen continue the above process.\n<br>\n\n# Tips 1: -1\nWe initialize the prefix score with `-1`,\nwhose all bits are `1`,\nmaximum integer also works.\n<br>\n\n# Tips 2: no zero score\nIn case that score of `A` is positive,\nthere is no `0` score array,\nstill at least one array of `A`,\nso we return `max(1, res)`.\n<br>\n\n# Tips 3: Greedy\nI have greedily split the subarray with score `0`.\nUsually people like a prove all all greedy ideas,\nI leave for you to have a try.\n<br>\n\n# **Complexity**\nTime `O(n)`\nSpace `O(1)`\n<br>\n\n**Java**\n```java\n public int maxSubarrays(int[] A) {\n int v = -1, res = 0;\n for (int a: A) {\n v &= a;\n if (v == 0) {\n v = -1;\n res += 1;\n }\n }\n return Math.max(1, res);\n }\n```\n\n**C++**\n```cpp\n int maxSubarrays(vector<int>& A) {\n int v = -1, res = 0;\n for (int a: A)\n if ((v &= a) == 0)\n v--, res++;\n return max(1, res);\n }\n```\n\n**Python**\n```py\n def maxSubarrays(self, A: List[int]) -> int:\n v = -1\n res = 0\n for a in A:\n v &= a\n if v == 0:\n v = -1\n res += 1\n return max(1, res)\n```\n
| 41 | 0 |
['C', 'Python', 'Java']
| 10 |
split-array-into-maximum-number-of-subarrays
|
LeetCode Explained ✅☑[C++] || Beats 100% || EXPLAINED🔥
|
leetcode-explained-c-beats-100-explained-rhjy
|
Intuition\n Describe your first thoughts on how to solve this problem. \n\n- We know the result of a bitwise AND operation between two binary numbers can only b
|
coder_kashif
|
NORMAL
|
2023-09-30T16:02:21.740760+00:00
|
2023-09-30T16:43:07.261869+00:00
| 1,778 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n- We know the result of a bitwise AND operation between two binary numbers can only be 0 or 1. \n- We initialize a variable a to INT_MAX. This is because the bitwise AND of the maximum possible value (INT_MAX) and any number will give us that number itself. (Note: INT_MAX in binary is 01111111111111111111111111111111)\n\n- Next, we calculate the bitwise AND of all the elements in the nums array. If this result is not equal to 0, it means that there is at least one subarray where the bitwise AND equal to one. In this case, the minimum possible answer is 1.\n\n- If the result from step 3 is 0, it implies that there exists at least one subarray with a bitwise AND equal to 0. In this scenario, we proceed to find other subarrays that can also have a bitwise AND equal to 0.\n\n- We count and track the subarrays that meet this condition and return the count as our final answer.\n\n\n\n\n# Code\n```\nclass Solution {\npublic:\n int maxSubarrays(vector<int>& nums) {\n int a=INT_MAX;\n for(auto it:nums)a&=it;\n if(a!=0)return 1;\n int b=INT_MAX;\n int count=0;\n for(auto it:nums){\n b&=it;\n if(b==0){\n count++;\n b=INT_MAX;\n }\n }\n return count;\n }\n};\n```
| 21 | 0 |
['Bit Manipulation', 'Bitmask', 'C++']
| 6 |
split-array-into-maximum-number-of-subarrays
|
Easy Video Solution(C++,JAVA,Python)🔥 || Bit Manipulation 🔥
|
easy-video-solutioncjavapython-bit-manip-9yik
|
Intuition\n Describe your first thoughts on how to solve this problem. \nThink in terms of bitwise AND Operator\n\n# Detailed and easy Video Solution\n\nhttps:/
|
ayushnemmaniwar12
|
NORMAL
|
2023-09-30T16:36:25.232571+00:00
|
2023-09-30T16:36:25.232600+00:00
| 964 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThink in terms of bitwise AND Operator\n\n# ***Detailed and easy Video Solution***\n\nhttps://youtu.be/iN7jRGQtVAE\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nOur code aims to find the maximum number of contiguous subarrays in an array that have the same bitwise AND value. It first calculates the common bitwise AND value for the entire array and then iterates through the array to count the number of subarrays with the same AND value, returning this count as the result.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n O(N)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n O(1)\n\n```C++ []\nclass Solution {\npublic:\n int maxSubarrays(vector<int>& v) {\n int m=33554431;\n int n=v.size();\n for(int i=0;i<n;i++)\n m=m&v[i];\n int s=33554431;\n int c=0;\n if(m==0)\n {\n for(int i=0;i<n;i++)\n {\n s=s&v[i];\n if(i==n-1 && s!=m)\n return c;\n if(s==m)\n {\n s=33554431;\n c++;\n } \n }\n return c;\n }\n return 1;\n }\n};\n```\n```python []\nclass Solution:\n def maxSubarrays(self, v):\n m = 33554431\n n = len(v)\n \n for i in range(n):\n m = m & v[i]\n \n s = 33554431\n c = 0\n \n if m == 0:\n for i in range(n):\n s = s & v[i]\n if i == n - 1 and s != m:\n return c\n if s == m:\n s = 33554431\n c += 1\n return c\n \n return 1\n\n```\n```java []\nclass Solution {\n public int maxSubarrays(int[] v) {\n int m = 33554431;\n int n = v.length;\n \n for (int i = 0; i < n; i++) {\n m = m & v[i];\n }\n \n int s = 33554431;\n int c = 0;\n \n if (m == 0) {\n for (int i = 0; i < n; i++) {\n s = s & v[i];\n if (i == n - 1 && s != m)\n return c;\n if (s == m) {\n s = 33554431;\n c++;\n } \n }\n return c;\n }\n \n return 1;\n }\n}\n```\n# ***If you like the solution Please Upvote and subscribe to my youtube channel***\n***It Motivates me to record more videos***\n\n***Thank you*** \uD83D\uDE00\n
| 11 | 1 |
['Bit Manipulation', 'C++', 'Java', 'Python3']
| 0 |
split-array-into-maximum-number-of-subarrays
|
Simple java solution
|
simple-java-solution-by-siddhant_1602-zozf
|
Complexity\n- Time complexity: O(n)\n\n- Space complexity: O(1)\n\n# Code\n\nclass Solution {\n public int maxSubarrays(int[] nums) {\n int val=-1,ans
|
Siddhant_1602
|
NORMAL
|
2023-09-30T16:06:26.291126+00:00
|
2023-09-30T16:23:03.722297+00:00
| 361 | false |
# Complexity\n- Time complexity: $$O(n)$$\n\n- Space complexity: $$O(1)$$\n\n# Code\n```\nclass Solution {\n public int maxSubarrays(int[] nums) {\n int val=-1,ans=0;\n for(int i:nums)\n {\n val=val&i;\n if(val==0)\n {\n ans++;\n val=-1;\n }\n }\n return ans==0 ? 1 : ans;\n }\n}\n```
| 11 | 0 |
['Java']
| 2 |
split-array-into-maximum-number-of-subarrays
|
Python 3 || 8 lines, one-pass || T/S: 99% / 100%
|
python-3-8-lines-one-pass-ts-99-100-by-s-4eoy
|
\nmx = 1048575 # <-- which is 11111111111111111111 base 2\n\nclass Solution:\n def maxSubarrays(self, nums: List[int]) -> int:\n\n ans, acc = 0, mx\
|
Spaulding_
|
NORMAL
|
2023-09-30T20:09:31.541434+00:00
|
2024-05-31T02:58:33.784973+00:00
| 97 | false |
```\nmx = 1048575 # <-- which is 11111111111111111111 base 2\n\nclass Solution:\n def maxSubarrays(self, nums: List[int]) -> int:\n\n ans, acc = 0, mx\n\n for num in nums:\n acc&= num\n \n if acc == 0 :\n ans+= 1 \n acc = mx\n\n return 1 if ans == 0 else ans \n\n```\n[https://leetcode.com/problems/split-array-into-maximum-number-of-subarrays/submissions/1063411734/](https://leetcode.com/problems/split-array-into-maximum-number-of-subarrays/submissions/1063411734/)\n\nI could be wrong, but I think that time complexity is *O*(*N*) and space complexity is *O*(1), in which *N* ~ `len(nums)`.
| 9 | 0 |
['Python3']
| 0 |
split-array-into-maximum-number-of-subarrays
|
✅ [Python] greedy O(n)
|
python-greedy-on-by-stanislav-iablokov-1rgi
|
If the cumulative AND-value of the whole array is non-zero then only one subarray is possible, i.e., the whole array. Otherwise, we use a greedy approach and se
|
stanislav-iablokov
|
NORMAL
|
2023-09-30T16:02:32.187145+00:00
|
2023-09-30T16:02:32.187176+00:00
| 624 | false |
If the cumulative AND-value of the whole array is non-zero then only one subarray is possible, i.e., the whole array. Otherwise, we use a greedy approach and separate subarrays once they reach the point of having zero cumulative AND-value.\n\n```python\nclass Solution:\n def maxSubarrays(self, nums: List[int]) -> int:\n min_and = reduce(and_, nums)\n \n if min_and > 0 : return 1\n \n count, mask = 0, 2**32-1\n\n for n in nums:\n mask &= n\n if mask == 0:\n count += 1\n mask = 2**32-1\n\n return count\n```
| 9 | 0 |
['Python3']
| 3 |
split-array-into-maximum-number-of-subarrays
|
C++
|
c-by-baibhavkr143-1g43
|
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
|
baibhavkr143
|
NORMAL
|
2023-09-30T16:00:43.700432+00:00
|
2023-09-30T16:01:22.283414+00:00
| 478 | 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```\nclass Solution {\npublic:\n int maxSubarrays(vector<int>& nums) {\n int bit=INT_MAX;\n int ans=1;\n for(int i=0;i<nums.size();i++)\n {\n bit=nums[i]&bit;\n if(bit==0)\n {\n ans++;\n bit=INT_MAX;\n }\n }\n if(bit==INT_MAX||bit>0)ans--;\n \n \n return max(1,ans);\n }\n};\n```
| 7 | 0 |
['C++']
| 0 |
split-array-into-maximum-number-of-subarrays
|
Bit Manipulation| Easy to understand
|
bit-manipulation-easy-to-understand-by-m-zcbq
|
Intuition\nintuition is that smallest AND will be equal to AND of whole array \n there cannot be any subarray whose AND is less than AND od array\n
|
Md_Rafiq
|
NORMAL
|
2023-09-30T16:08:52.404304+00:00
|
2023-09-30T16:08:52.404330+00:00
| 227 | false |
# Intuition\nintuition is that smallest AND will be equal to AND of whole array \n there cannot be any subarray whose AND is less than AND od array\n so if array AND is >0 then ans ==1\n else we can count ans\n\n\n\n# Complexity\n- Time complexity:O(n)\n\n- Space complexity:O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int maxSubarrays(vector<int>& nums) {\n int sub_and=nums[0];\n int n=nums.size();\n for(int i=1;i<n;i++){\n sub_and=sub_and&nums[i];\n }\n \n if(sub_and) return 1;\n \n // to set all one in x like x=111111....\n int cnt=0;\n int x=(1<<20)-1;\n for(int i=0;i<n;i++){\n x=x&nums[i];\n if(x==sub_and){\n cnt++;\n x=(1<<20)-1;\n }\n }\n \n return cnt;\n }\n};\n```
| 6 | 0 |
['Bit Manipulation', 'C++']
| 0 |
split-array-into-maximum-number-of-subarrays
|
Video Explanation (Step by step solution with all proofs)
|
video-explanation-step-by-step-solution-qc2i1
|
Explanation\n\nClick here for the video\n\n# Code\n\nclass Solution {\npublic:\n int maxSubarrays(vector<int>& nums) {\n int ands = nums[0];\n
|
codingmohan
|
NORMAL
|
2023-09-30T18:50:31.631512+00:00
|
2023-09-30T18:50:31.631542+00:00
| 61 | false |
# Explanation\n\n[Click here for the video](https://youtu.be/2NExS_6bLP4)\n\n# Code\n```\nclass Solution {\npublic:\n int maxSubarrays(vector<int>& nums) {\n int ands = nums[0];\n for (auto i : nums) ands &= i;\n \n if (ands != 0) return 1;\n \n int n = nums.size();\n int result = 0;\n \n for (int j = 0; j < n; j ++) {\n int currentAnd = nums[j];\n while (j+1 < n && currentAnd != 0) {\n j ++;\n currentAnd &= nums[j];\n }\n if (currentAnd == 0) result ++;\n }\n return result;\n }\n};\n```
| 4 | 0 |
['C++']
| 0 |
split-array-into-maximum-number-of-subarrays
|
Beats 100% time and space || O(n) Java Solution || Bits manipulation || In-depth Explanation
|
beats-100-time-and-space-on-java-solutio-a2za
|
Intuition\nIt looked like dp problem to me so I couldn\'t went in depth of bits during the contest and wasn\'t able to do this in contest cause conversion of gr
|
viratt15081990
|
NORMAL
|
2023-09-30T18:06:41.181231+00:00
|
2023-09-30T18:09:56.328238+00:00
| 73 | false |
# Intuition\nIt looked like dp problem to me so I couldn\'t went in depth of bits during the contest and wasn\'t able to do this in contest cause conversion of greedy recursion to dp was hard task. This problem is completely based on understanding of bits behaviour under the constraint of given problem\n\n# Approach\n=> **we check total array AND value and if its greater then 0. Then we return 1**\nREASON: if total And is greater than 0. Its means its positive number which have some bits set.\nWhich also means, all the element of the array have those bit set. So any partition we make, all partition will have those bits set for sure. Therefore sum of partitions will be sure greater than equal to noOfPartiton*totalAnd.\nSo having one complete partition is the only way of getting less score. Any other partiton will increases the score.\n\n**=> totalAnd is 0.**\nhere totalAns is 0. so least score we can make is 0 only.\nnow we need to check all partiton having score 0 to increase the no.of partition while mainting the score of each partition 0. so that the total score shouldn\'t increase more than 0.\n\nwe traverse left to right we check all the partiton who have score 0. and inrease our partition count.\nnow lets say, we have made 3 partition after the loop is done. having come till 3rd partition bydefault says that we have found 2 partition whose score are 0. But there can be 2 possibilty for 3rd or last partition. \n1st possibilty => last partition score is 0. in this case we return count which is 3\n\t2ND POSSIBILITY = > last partion score is not 0. so what we do is merge last partition with 2nd last partition because 2nd last partition have score 0 and we do AND operation. so 0 AND lastpartition score is also 0.\n\tAnd by merging last 2 partition we have kept the score of all partition 0. and also created max number of partition we can make. so we just do count--, to reduce the partition count. and return it.\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(1)\n\n# Code\n```\nclass Solution {\n public int maxSubarrays(int[] nums) {\n int totalAnd = nums[0];\n int n = nums.length;\n for(int num:nums){\n totalAnd = totalAnd & num;\n }\n if(totalAnd>0){\n return 1;\n }\n int currAnd = 0;\n int split = 0;\n for(int i=0;i<n;i++){\n if(currAnd==0){\n currAnd = nums[i];\n split++;\n }else {\n currAnd = currAnd & nums[i];\n }\n }\n if(currAnd>0){\n split--;\n }\n return split;\n } \n}\n```
| 4 | 0 |
['Array', 'Bit Manipulation', 'Java']
| 2 |
split-array-into-maximum-number-of-subarrays
|
Without zero intuition
|
without-zero-intuition-by-loveshverma-v9d9
|
Intuition\nMinimum AND will be the AND of whole array\nIncrease size of subarray will decrease AND value\n\n\n# Approach\nWe can try to make splits such that cu
|
loveshverma_
|
NORMAL
|
2023-09-30T20:52:10.684490+00:00
|
2023-09-30T20:57:20.027380+00:00
| 440 | false |
# Intuition\nMinimum AND will be the AND of whole array\nIncrease size of subarray will decrease AND value\n\n\n# Approach\nWe can try to make splits such that currSplitAND + RestSplitAND = MinAND\nIf it is > MinAND, we can increase current split length\n\nIf (currSplitAND + RestSplitAND = MinAND) is satisfied, we should now find min splits in RestSplit with new MinAND as (MinAND - currSplitAND)\n\nRestSplitAND is suffix AND\n\nEg: MinAND = 7\n| 2 | 5 |\nWe found currSplit AND with 2 and restsplit AND as 5 which satisfies the minimum. Now we can solve subproblem to split restsplit with minAND 5\n\n# Complexity\n- Time complexity:\n$$O(n)$$\n\n- Space complexity:\n$$O(n)$$\n\n# Code\n```\nclass Solution {\npublic:\n int maxSubarrays(vector<int>& nums) {\n int n = nums.size();\n\n if(n == 1 && nums[0] == 0) return 1;\n\n int minAND = nums[0];\n for(int x: nums) minAND = minAND&x;\n\n int suffAND[n+1];\n suffAND[n] = 0;\n suffAND[n-1] = nums[n-1];\n\n for(int i=n-2; i>=0; i--) suffAND[i] = suffAND[i+1] & nums[i];\n\n int res = 0;\n\n function<void(int, int, int)>solve = [&](int i, int j, int need) {\n if(i>j) return;\n res++;\n int curr = (1<<30)-1;\n int a=i;\n for(a;a<=j; a++) {\n curr &= nums[a];\n if(curr + suffAND[a+1] == need) break;\n }\n solve(a+1,j, need-curr);\n };\n\n solve(0, n-1, minAND);\n return res;\n }\n};\n```
| 3 | 0 |
['C++']
| 3 |
split-array-into-maximum-number-of-subarrays
|
✅☑[C++] || Beats 100% || EXPLAINED🔥
|
c-beats-100-explained-by-marksphilip31-dnnm
|
\n# PLEASE UPVOTE IF IT HELPED\n\n---\n\n\n# Approach\n(Also explained in the code)\n\n1. The maxSubarrays function takes a vector nums as input.\n\n1. It start
|
MarkSPhilip31
|
NORMAL
|
2023-09-30T16:15:09.584066+00:00
|
2023-09-30T16:15:09.584083+00:00
| 288 | false |
\n# *PLEASE UPVOTE IF IT HELPED*\n\n---\n\n\n# Approach\n***(Also explained in the code)***\n\n1. The `maxSubarrays` function takes a vector `nums` as input.\n\n1. It starts by calculating the bitwise AND of all elements in `nums` and stores the result in `a_`.\n\n1. If `a_` is not zero, it means there is at least one element in `nums` with all bits set to 1. In this case, it returns 1.\n\n1. If `a_` is zero, it initializes `size` to 1 and `a_` as a 20-bit mask of all 1s.\n\n1. It then iterates through the elements of `nums`, calculating the bitwise AND of `a_` and each element.\n\n1. When `a_` becomes zero during this iteration, it increments the `size` and resets `a_` to the 20-bit mask of all 1s.\n\n1. After the loop, if a_ is not zero, it decrements the `size`.\n\n1. Finally, it returns the `size` as the result.\n\n\n---\n\n\n# Complexity\n- **Time complexity:**\n$$O(n)$$\n\n- **Space complexity:**\n$$O(1)$$\n\n---\n\n\n# Code\n```\nclass Solution {\npublic:\n int maxSubarrays(vector<int>& nums) {\n int a_ = nums[0]; // Initialize a_ with the first element of nums.\n \n // Calculate bitwise AND of all elements in nums.\n for(int num:nums) {\n a_ &= num;\n }\n \n if(a_) {\n return 1; // If a_ is not zero, return 1.\n }\n \n int size = 1; // Initialize the size to 1.\n a_ = (1 << 20) - 1; // Initialize a_ as a 20-bit mask of all 1s.\n \n for(int num:nums) {\n a_ &= num; // Calculate bitwise AND of a_ and the current element.\n \n if(a_ == 0) {\n size++; // If a_ becomes zero, increment the size.\n a_ = (1 << 20) - 1; // Reset a_ to the 20-bit mask of all 1s.\n }\n }\n \n if(a_) {\n size--; // If a_ is not zero at the end, decrement the size.\n }\n \n return size; // Return the final size.\n }\n};\n\n```\n\n# *PLEASE UPVOTE IF IT HELPED*\n\n---\n\n---\n\n
| 3 | 0 |
['Array', 'Bit Manipulation', 'C++']
| 0 |
split-array-into-maximum-number-of-subarrays
|
C++ | Easy Solution | Logic explained
|
c-easy-solution-logic-explained-by-pajju-gl1w
|
Approach-\n\n## Fact:\n> Bitwise AND on the complete array is the minimum bitwise AND value you can get between all subarrays.\n\n## Case 1: Bitwise AND of the
|
Pajju_0330
|
NORMAL
|
2023-09-30T16:07:27.924151+00:00
|
2023-09-30T16:07:27.924177+00:00
| 213 | false |
# Approach-\n\n## Fact:\n> Bitwise AND on the complete array is the minimum bitwise AND value you can get between all subarrays.\n\n## Case 1: Bitwise AND of the Array is Greater Than 0\nIn this case, you cannot achieve *****"The sum of scores of the subarrays is the minimum possible,"***** because no subarray will give you a smaller AND value than the entire array itself. Therefore, the answer is directly 1, meaning you cannot divide the array into subarrays.\n\n## Case 2: Bitwise AND of the Array is 0\nIn this scenario, count how many subarrays have a bitwise AND value of 0. This count represents your answer.\n\nHappy Coding!\nPlease upvote\uD83E\uDD79\n\n\n\n# Code\n```\nclass Solution {\npublic:\n int maxSubarrays(vector<int>& nums) {\n int minAnd = 1;\n int zeros = 0;\n for(int i = 0;i < nums.size(); ++i){\n minAnd = (minAnd & nums[i]);\n zeros += (nums[i] == 0);\n }\n int ans = 0;\n int andd = INT_MAX;\n for(int i = 0; i < nums.size(); ++i){\n andd = andd & nums[i];\n if(andd == minAnd){\n ans++;\n andd = INT_MAX;\n }\n }\n return zeros == nums.size()? nums.size():minAnd>0?1:max(ans,1);\n }\n};\n```
| 3 | 0 |
['C++']
| 1 |
split-array-into-maximum-number-of-subarrays
|
Simple solution to Bekar Question
|
simple-solution-to-bekar-question-by-lil-vfiz
|
Java []\nclass Solution {\n public int maxSubarrays(int[] nums) {\n int all1=(1<<29)-1, minScore=all1, v=all1, cnt=0;\n for(int num: nums) minS
|
Lil_ToeTurtle
|
NORMAL
|
2023-10-03T04:45:57.173495+00:00
|
2023-10-03T04:45:57.173518+00:00
| 115 | false |
```Java []\nclass Solution {\n public int maxSubarrays(int[] nums) {\n int all1=(1<<29)-1, minScore=all1, v=all1, cnt=0;\n for(int num: nums) minScore&=num;\n if(minScore!=0) return 1;\n for(int num: nums) {\n v&=num;\n if(v==0) {\n cnt++;\n v=all1;\n }\n }\n return cnt;\n }\n}\n```
| 2 | 0 |
['Java']
| 1 |
split-array-into-maximum-number-of-subarrays
|
Proof of zero count
|
proof-of-zero-count-by-nacoward-vd3h
|
Intuition\nThis is a mathematical question.\n\nFirstly, let\'s review AND operator:\n0 & 1 = 0\n1 & 0 = 0\n0 & 0 = 0\n1 & 1 = 1\nAnd for number A=3 and B=5,\nA&
|
nacoward
|
NORMAL
|
2023-10-01T17:03:06.528286+00:00
|
2023-10-01T17:03:06.528313+00:00
| 16 | false |
# Intuition\nThis is a mathematical question.\n\nFirstly, let\'s review `AND` operator:\n0 & 1 = 0\n1 & 0 = 0\n0 & 0 = 0\n1 & 1 = 1\nAnd for number `A=3` and `B=5`,\nA&B = 3 & 5 = 011b & 101b = (0&1)*2^2 + (1&0)*2^1 + (1&1)&2^0 = 1\nIt can be deduced that:\n**A & B <= A,\nA & B <= B**\n\nThen let\'s look at the second condition described by the subject:\n> The sum of scores of the subarrays is the minimum possible.\n\nImagine `Z` is the value of all elem\'s `AND` in the array nums, \nZ = nums[0] & nums[1] & ... & nums[n-1]\nSo **Z must be the minimum score**\n\nImagine the array can be splited to two subarrays, which is Z1 and Z2,\nZ = Z1 & Z2, so Z <= Z1, Z<=Z2\nAnd if Z = Z1 + Z2,\nIt can be deduced that Z==0, Z1==0, Z2==0\nAnd it is the same with if Z can be splited into three subarrays, or more, it will be Z==0, Z1 == Z2 == ... == Zn == 0 \n\nSo the problem became:\n1, if the minimum score Z != 0, there can be only one array can get the minimum socre, which is the whole array;\n\n2, if the minimum score Z == 0, it is equal to count how many subarray\'s `AND` is zero\n\n# Code\n```\nfunc maxSubarrays(nums []int) int {\n ans, val := 0, 0\n for _, num := range nums {\n if val == 0 {\n val = num\n } else {\n val &= num\n }\n if val == 0 {ans++}\n }\n if ans == 0 {return 1}\n return ans\n}\n```
| 2 | 0 |
['Go']
| 0 |
split-array-into-maximum-number-of-subarrays
|
Easy explained solution, just 7 lines | Beats 70% | c++
|
easy-explained-solution-just-7-lines-bea-ar1k
|
Intuition\nThe minimum \'AND\' can only be 0. So count all the subarrays with 0 \'AND\' separetly.\n\n# Approach\n1. Let\'s start with defining variables for co
|
Piyush077
|
NORMAL
|
2023-09-30T22:09:52.227976+00:00
|
2023-09-30T22:09:52.228003+00:00
| 72 | false |
# Intuition\nThe minimum \'AND\' can only be 0. So count all the subarrays with 0 \'AND\' separetly.\n\n# Approach\n1. Let\'s start with defining variables for counting total subarrays (total) and to check the current subarray\'s \'AND\' (curr)\n2. We iterate through the elements as to count all the subarrays with 0 \'AND\' as it is the minimumm that can occur. Let\'s not forget the condition in the question that the sum should be minimumm and the elements should be part of only one array (hence iterating once).\n3. We can greedily filter out the subarrays with 0 \'AND\' because that is the minimum contribution a subarray can make.\n4. Count the zeros and increment the total subarray count.\n5. For returning the answer. We should consider a few conditions:\n 1. 1 is the minimum split you can make (full array).\n 2. if curr == 0, you can take total as it is (minimum sum condition)\n 3. if curr != 0, it has to be taken as a separate sub-array.\n\n# Complexity\n- Time complexity:\nO(N)\n\n- Space complexity:\nO(1)\n\n# Code\n```\nclass Solution {\npublic:\n int maxSubarrays(vector<int>& nums) {\n int total = 0;\n int curr = 0;\n for (int i: nums) {\n if (curr) {\n curr &= i;\n } else {\n curr = i;\n total++;\n }\n }\n return max(1, total - (curr != 0));\n }\n};\n```
| 2 | 0 |
['Math', 'Bit Manipulation', 'C++']
| 1 |
split-array-into-maximum-number-of-subarrays
|
Just Brute Force || C++
|
just-brute-force-c-by-aman91k-5f8v
|
\'\'\'\n\nINTUTUION:-\nIt is optimal to put all the elements in a single subarray until we didn\'t find any subarray having \'AND\' is \'ZERO\' , by doing this
|
aman91k
|
NORMAL
|
2023-09-30T19:56:29.694838+00:00
|
2024-02-22T05:44:39.906720+00:00
| 160 | false |
\'\'\'\n\nINTUTUION:-\nIt is optimal to put all the elements in a single subarray until we didn\'t find any subarray having \'AND\' is \'ZERO\' , by doing this it minimizes the total score.\n\n\n class Solution {\n public:\n \n int maxSubarrays(vector<int>& nums) {\n int n=nums.size();\n int cnt=0, andd=nums[0]; \n\t\t\n for(int i=0; i<n; i++){ \n andd&=nums[i];\n if(i==n-1) break;\n \n if(andd==0){ // IF WE FOUND A SUBARRAY HAVING \'AND\' ZERO\n cnt++;\n andd=nums[i+1];\n }\n }\n \n if(andd==0 || cnt==0) cnt++;\n return cnt; \n }\n };\n\n\'\'\'
| 2 | 0 |
[]
| 1 |
split-array-into-maximum-number-of-subarrays
|
[C++] Double to Single-Pass with BitMask, 68ms, 104.78MB
|
c-double-to-single-pass-with-bitmask-68m-qfir
|
The problem is basically ask us to group consecutive elements so that the score is the lowest possible and since we are using a & operator, we know that this lo
|
Ajna2
|
NORMAL
|
2023-09-30T17:52:16.072089+00:00
|
2023-09-30T17:52:16.072113+00:00
| 56 | false |
The problem is basically ask us to group consecutive elements so that the score is the lowest possible and since we are using a `&` operator, we know that this lowest value can only go down as we add more values.\n\nAnd this is a key factor, since it means that our lowest possible score can\'t be lower or higher than the one we get by `&`ing all the elements together: it has to be it, since otherwise:\n* we might get a greater or equal score from a group adding more elements;\n* we cannot go below the cumulative `&` value by adding more.\n\nWith this in mind, we might then simply group using another pass to find all the elements that we can group together.\n\nFor example for the first case we will have the overall `&`ed value of `0` and we can find `3` groups that go up to that, as explained: `{1,0}`, `{2,0}` and `{1,2}`.\n\nThe situation is slightly complicated when we figure out that any cumulative value `> 1` actually means that we are better off just merging the groups instead of having more than one of them adding up to the score.\n\nWith that in mind, we can proceed with our logic, starting by our usual support variables:\n* `res` will store how many groups we can create;\n* `len` will store the length of our input;\n* `curr` will store the current `&` product, initially set to `INT_MAX` (to make sure we have all the bits of a positive number in range set to `1` - it is basically the neuter element of our process);\n* `minBit` will store the cumulative value of all the `&`ed values.\n\nWe can then rule out the case where `minBit > 0`, since in that case, as stated before, we are better off just grouping all the elements in one - no point in having any `minBit + minBit + minBit + ...` overall series of groups certainly scoring `> minBit`, so in this case we can just `return` `1`.\n\nNow, when `minBit` is actually `0`, we can proceed with a greedy approach to forming our groups, so that for each value `n` in `nums` we will:\n* `&` `n` in `curr`;\n* check if `curr` now equals `minBit` (ie: `0`) and if so, we can start a group by splitting and:\n * increase `res` by `1`;\n * reset `curr` to be `INT_MAX`.\n\nOnce done, we can `return` `res`.\n\n# Complexity\n- Time complexity: $$O(n)$$\n- Space complexity: $$O(1)$$\n\n# Code\n```cpp\nclass Solution {\npublic:\n int maxSubarrays(vector<int>& nums) {\n // support variables\n int res = 0, len = nums.size(), curr = INT_MAX,\n minBit = accumulate(begin(nums), end(nums), INT_MAX, bit_and<int>());\n // minBit is too expensive\n if (minBit > 1) return 1;\n // parsing nums\n for (int n: nums) {\n curr &= n;\n // if we reached the target minBit, we try to open a new sub array\n if (curr == minBit) {\n res++;\n curr = INT_MAX;\n }\n }\n return res;\n }\n};\n```\n\nBut, wait a moment: since we know that the only case in which we can split groups is when our current bitwise `&` product is `0`, we can skip one passage (the `accumulate` one) and go directly with a single one where we will count how often do we get `0`s (if we can get it even a single time, then the minimum score has to be `0`) and finally `return` `res` if it is `> 0` (ie: we encountered at least a `0` product), `1` otherwise.\n\n```cpp\nclass Solution {\npublic:\n int maxSubarrays(vector<int>& nums) {\n // support variables\n int res = 0, curr = INT_MAX;\n // parsing nums\n for (int n: nums) {\n curr &= n;\n // if we reached a cumulative 0, we try to open a new sub array\n if (!curr) {\n res++;\n curr = INT_MAX;\n }\n }\n return res ? res : 1;\n }\n};\n```
| 2 | 0 |
['Array', 'Bit Manipulation', 'Bitmask', 'C++']
| 1 |
split-array-into-maximum-number-of-subarrays
|
c++ solution
|
c-solution-by-dilipsuthar60-g7go
|
\nclass Solution {\npublic:\n int maxSubarrays(vector<int>& nums) {\n int result=0;\n int currentAnd=-1;\n for(int i=0;i<nums.size();i++
|
dilipsuthar17
|
NORMAL
|
2024-02-28T16:29:32.611244+00:00
|
2024-02-28T16:29:32.611283+00:00
| 6 | false |
```\nclass Solution {\npublic:\n int maxSubarrays(vector<int>& nums) {\n int result=0;\n int currentAnd=-1;\n for(int i=0;i<nums.size();i++)\n {\n currentAnd&=nums[i];\n if(currentAnd==0)\n {\n result++;\n currentAnd=-1;\n }\n }\n return result?result:1;\n }\n};\n```
| 1 | 0 |
['C', 'C++']
| 0 |
split-array-into-maximum-number-of-subarrays
|
✅ Simple Solution | cpp
|
simple-solution-cpp-by-just__do__it-9mwj
|
Intuition\n Describe your first thoughts on how to solve this problem. \nIntuition is that smallest AND will be equal to AND of whole array\nthere cannot be any
|
just__do__it
|
NORMAL
|
2024-01-21T09:42:54.473631+00:00
|
2024-01-21T09:42:54.473662+00:00
| 2 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nIntuition is that smallest AND will be equal to AND of whole array\nthere cannot be any subarray whose AND is less than AND of array\nso if array AND is > 0 then ans == 1\nelse we can count subarrys with AND = 0.\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(1)\n# Code\n```\nclass Solution {\npublic:\n int maxSubarrays(vector<int>& nums) {\n int min = INT_MAX,n = nums.size(),count = 0;\n for(int i=0;i<n;i++)\n {\n min&=nums[i];\n } \n if(min != 0)\n {\n return 1;\n }\n int running = INT_MAX;\n for(int i=0;i<n;i++)\n {\n running&=nums[i];\n if(running == 0)\n {\n count++;\n running = INT_MAX;\n }\n }\n return count;\n }\n};\n```
| 1 | 0 |
['C++']
| 0 |
split-array-into-maximum-number-of-subarrays
|
One pass. Easy sliding window solution !!
|
one-pass-easy-sliding-window-solution-by-zs33
|
Intuition\nSliding Window\n\n# Approach\n Keep incrementing window size until 0 appears.\n Make another window from next index position to the position where yo
|
AdityaJha__
|
NORMAL
|
2023-10-18T03:31:53.426168+00:00
|
2023-10-18T03:31:53.426188+00:00
| 15 | false |
# Intuition\nSliding Window\n\n# Approach\n* Keep incrementing window size until 0 appears.\n* Make another window from next index position to the position where you again encounter 0.\n* Increase the count for every window.\n* Please let me know if you found it easy to understand.\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(1)\n\n# Code\n```\nclass Solution {\npublic:\n int maxSubarrays(vector<int>& nums) {\n int n = nums.size();\n if(n == 1) return 1;\n int i = 0, j = 0, count = 0;\n \n int operation = nums[i];\n while(j < n){\n operation &= nums[j];\n if(operation == 0){\n count++;\n i = j+1;\n if(i < n) operation = nums[i];\n }\n j++;\n }\n \n if(count == 0) count++;\n return count;\n }\n};\n```
| 1 | 0 |
['C++']
| 0 |
split-array-into-maximum-number-of-subarrays
|
Easy to understand solution without any tricks :)
|
easy-to-understand-solution-without-any-nqt56
|
Intuition\n\nInspired by @loveshverma_\n\n https://leetcode.com/problems/split-array-into-maximum-number-of-subarrays/solutions/4111160/without-zero-and-intuiti
|
amitbansal13
|
NORMAL
|
2023-10-02T15:04:47.512972+00:00
|
2023-10-02T15:05:22.293817+00:00
| 86 | false |
# Intuition\n\nInspired by @loveshverma_\n\n https://leetcode.com/problems/split-array-into-maximum-number-of-subarrays/solutions/4111160/without-zero-and-intuition/\n\nThe minimum possible score would be the AND of whole array since whenever and reduces the number of set bits in a number hence having more numbers in the subarray will reduce the overall AND value of the subarray.\n\nOnce we have the minimumAnd, we compute the suffixAnd of the array and try to split the arrays so that overall score still equals the minAnd.\n\nAt each index we compute the currentAND and see if the sum of suffix array and currentAnd it equals the minAnd. \n\nIf it does then we can split the array at current point and then try to split the remaining array as much as possible in a similar way.\n\n\n\n# Complexity\n- Time complexity: O(n)\n\n- Space complexity: O(n)\n\n# Code\n```\nclass Solution {\npublic:\n int maxSubarrays(vector<int>& nums) {\n int n = nums.size();\n\n int minAnd = nums[0];\n for(auto i:nums) minAnd = minAnd & i;\n\n int suffixAnd[n+1];\n suffixAnd[n] = 0;\n suffixAnd[n-1] = nums[n-1];\n for(int i = n-2;i>=0;i--) {\n suffixAnd[i] = suffixAnd[i+1] & nums[i];\n }\n int res = 0;\n int curr = INT_MAX;\n for(int i=0;i<n;i++) {\n curr = curr & nums[i];\n if(curr + suffixAnd[i+1] == minAnd) {\n res++;\n minAnd -= curr;\n curr = INT_MAX;\n } \n }\n return res;\n }\n};\n```
| 1 | 0 |
['C++']
| 0 |
split-array-into-maximum-number-of-subarrays
|
🔥C++ Solution || efficient iterative solution
|
c-solution-efficient-iterative-solution-vhlab
|
\n\n# Code\n\nclass Solution {\npublic:\n int maxSubarrays(vector<int>& nums) {\n int totalAnd = INT_MAX; \n \n // calculate the bitwis
|
ravi_verma786
|
NORMAL
|
2023-10-01T15:51:09.504083+00:00
|
2023-10-01T15:51:09.504108+00:00
| 55 | false |
\n\n# Code\n```\nclass Solution {\npublic:\n int maxSubarrays(vector<int>& nums) {\n int totalAnd = INT_MAX; \n \n // calculate the bitwise AND of all elements in nums.\n for (auto num : nums) {\n totalAnd &= num;\n }\n \n // if totalAnd is not zero, return 1 as there is no way to split into subarrays with a total score of 0.\n if (totalAnd != 0) {\n return 1;\n }\n \n int currentAnd = INT_MAX; \n int subarrayCount = 0; \n \n for (auto num : nums) {\n currentAnd &= num; \n \n // if currentAnd becomes 0, it\'s time to split into a new subarray.\n if (currentAnd == 0) {\n subarrayCount++; \n currentAnd = INT_MAX; \n }\n }\n \n return subarrayCount;\n }\n};\n```
| 1 | 0 |
['C++']
| 0 |
split-array-into-maximum-number-of-subarrays
|
Easy Approach ! 💜
|
easy-approach-by-meshram_2003-23a1
|
Intuition\n Describe your first thoughts on how to solve this problem. \nSimply Check if the AND of all the elements is 0 or not \nIf AND > 1 (ie. not 0) then i
|
meshram_2003
|
NORMAL
|
2023-10-01T08:55:41.899571+00:00
|
2023-10-01T08:58:56.897885+00:00
| 5 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nSimply Check if the AND of all the elements is 0 or not \nIf AND > 1 (ie. not 0) then it means that we can\'t divide it into subarrays coz if we try to divide the array; then score will become max.\nIf the AND of all the elements is 0 then it means we can divide into subarrays: so now to divide it into subarrays do the foll steps->\n1. do the AND of the numbers and whenever the AND comes 0 simply increase the count of subarray (cnt) and if there are still elements into array then [ele = next element] because you can include one element into only one subarray !! \n\n**Ezy Pzy Solution! If you think its good Do Upvote!**\n\n\n# \n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(n)$$\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(1)$$\n\n# Code\n```\nclass Solution {\npublic:\n int maxSubarrays(vector<int>& nums) {\n int cnt = 0, ele = nums[0] , mini = nums[0];\n\n for(auto i: nums){\n mini &= i;\n }\n if(mini > 0)return 1;\n\n for(int i=0; i<nums.size(); i++){\n ele &= nums[i];\n if(ele == 0){\n cnt++;\n if(i+1 < nums.size())ele = nums[i+1];\n }\n\n }\n return cnt;\n }\n};\n```
| 1 | 0 |
['C++']
| 0 |
split-array-into-maximum-number-of-subarrays
|
C++ SOLUTION
|
c-solution-by-rounaq_khandelwal-6gbj
|
Approach\n Describe your approach to solving the problem. \nFirst of all, calculate the overall bitAnd by looping via the whole array. If the overall bitAnd ==
|
rounaq_khandelwal
|
NORMAL
|
2023-10-01T06:42:17.985615+00:00
|
2023-10-01T06:42:17.985637+00:00
| 8 | false |
# Approach\n<!-- Describe your approach to solving the problem. -->\nFirst of all, calculate the overall bitAnd by looping via the whole array. If the overall bitAnd == 1, that implies that some bit is definitely "ON/SET" for all the numbers in the array.\n\nIf the bitAnd==0, then count of the number of splits whenever the bitAnd turns to be 0 while re-iterating through the array.\n\n\n# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int maxSubarrays(vector<int>& nums) {\n int bitAnd=nums[0];\n for(auto it=1;it<nums.size();it++){\n bitAnd =(bitAnd & nums[it]);\n }\n if(bitAnd) return 1;\n bitAnd=-1;\n int split=0;\n for(int i=0;i<nums.size();i++){\n if(bitAnd==-1) bitAnd=nums[i];\n else bitAnd &=nums[i];\n if(bitAnd==0){\n bitAnd=-1;\n split++;\n }\n }\n return split;\n }\n};\n```
| 1 | 0 |
['C++']
| 0 |
split-array-into-maximum-number-of-subarrays
|
C++| Easy solution
|
c-easy-solution-by-coder3484-7g9h
|
Code\n\nclass Solution {\npublic:\n int maxSubarrays(vector<int>& nums) {\n int mn = *min_element(nums.begin(), nums.end());\n int ad = 1;\n
|
coder3484
|
NORMAL
|
2023-09-30T16:44:26.186791+00:00
|
2023-09-30T16:44:26.186820+00:00
| 60 | false |
# Code\n```\nclass Solution {\npublic:\n int maxSubarrays(vector<int>& nums) {\n int mn = *min_element(nums.begin(), nums.end());\n int ad = 1;\n for(int num : nums) ad &= num;\n mn = min(mn, ad);\n \n int ans = 0, curr = nums[0];\n for(int i=0;i<nums.size();i++) {\n curr &= nums[i];\n if(curr == mn) {\n ans++;\n if(i+1 < nums.size()) curr = nums[i+1];\n }\n }\n return max(ans, 1);\n }\n};\n```
| 1 | 0 |
['Bit Manipulation', 'C++']
| 0 |
split-array-into-maximum-number-of-subarrays
|
Sliding Window technique O(n)
|
sliding-window-technique-on-by-masud_par-c03r
|
\nclass Solution {\npublic:\n int maxSubarrays(vector<int>& a) \n {\n int c = 0, f = a[0];\n for (int i = 0; i < a.size(); i++)\n {\n
|
masud_parvez
|
NORMAL
|
2023-09-30T16:24:17.120880+00:00
|
2023-09-30T16:24:17.120898+00:00
| 62 | false |
```\nclass Solution {\npublic:\n int maxSubarrays(vector<int>& a) \n {\n int c = 0, f = a[0];\n for (int i = 0; i < a.size(); i++)\n {\n f = f&a[i];\n if (f == 0) {\n c++;\n if (i+1 < a.size()) f = a[i+1];\n }\n }\n return max(1,c);\n }\n};\n```
| 1 | 0 |
['Two Pointers', 'Greedy', 'Bit Manipulation', 'Sliding Window', 'C++']
| 0 |
split-array-into-maximum-number-of-subarrays
|
Well Commented Code & Explained Code✅⭐
|
well-commented-code-explained-code-by-ne-gjs8
|
Approach\nApplying AND operator on whole array will gives us the minimum value, because AND operator never sets a bit thus never increases the answer.\n\nTheref
|
neergx
|
NORMAL
|
2023-09-30T16:09:44.647703+00:00
|
2023-09-30T19:45:13.696787+00:00
| 47 | false |
# Approach\nApplying `AND` operator on whole array will gives us the minimum value, because `AND` operator never `sets` a bit thus never increases the answer.\n\nTherefore we find the `min` value which will either be `zero` or f `nonzero` \n\nIf it is `nonzero` the sum of two `subarray` with each subarray hacing `nonzero AND` result and sum is impossible, therfore in this case the answer would be `1`\n\nIf it is `zero` then we find number of `subarray` with `zero AND` result \n\n# Complexity\n- Time complexity:O(n)\n\n- Space complexity:o(n)\n\n# Code\n```\nclass Solution {\npublic:\n int maxSubarrays(vector<int>& nums) {\n int n = nums.size();\n \n // Initialize \'mini\' with the first element of \'nums\'\n int mini = nums[0];\n for(auto it: nums)\n mini &= it; // Calculate the bitwise AND of all elements in \'nums\'\n \n // If \'mini\' is not zero, return 1 since there\'s at least one subarray with a score of \'mini\'\n if(mini != 0)\n return 1;\n else {\n int ans = 0, curr = nums[0];\n \n // Loop through \'nums\' to find subarrays with score equal to \'mini\'\n for(int i = 0; i < nums.size(); i++) {\n curr &= nums[i]; // Update \'curr\' by bitwise AND with the current element\n \n // If \'curr\' matches \'mini\', increment \'ans\'\n if(curr == mini) {\n ans++;\n \n // Move to the next element if not at the end of the array\n if(i < n-1)\n curr = nums[i+1];\n }\n }\n \n return ans; // Return the count of subarrays with score \'mini\'\n }\n return 0; // This line is unreachable, as the function will have returned earlier\n }\n};\n\n```
| 1 | 0 |
['C++']
| 0 |
split-array-into-maximum-number-of-subarrays
|
Easy Solution || Beats 100 % || Best Approach
|
easy-solution-beats-100-best-approach-by-sx6b
|
class Solution {\npublic:\n int maxSubarrays(vector& nums) {\n int count=0;\n int curr=nums[0];\n for(int i=1;i<nums.size();i++){\n
|
swayam_wish
|
NORMAL
|
2023-09-30T16:09:25.385400+00:00
|
2023-09-30T16:09:25.385420+00:00
| 6 | false |
class Solution {\npublic:\n int maxSubarrays(vector<int>& nums) {\n int count=0;\n int curr=nums[0];\n for(int i=1;i<nums.size();i++){\n if(curr==0){count++; curr=nums[i]; continue;}\n else{ curr= curr& nums[i];}\n }\n if(curr==0){count++;}\n if(count==0){return 1;}\n return count;\n }\n};
| 1 | 0 |
[]
| 0 |
split-array-into-maximum-number-of-subarrays
|
Easy C++ solution O(n) time and O(1) space
|
easy-c-solution-on-time-and-o1-space-by-25lvc
|
Intuition\nIf total and of array is not zero then ans will be 1 as we can\'t divide such that sum of individual subarray will be minimum. If total and of array
|
ujjwal___
|
NORMAL
|
2023-09-30T16:06:56.351464+00:00
|
2023-09-30T16:06:56.351498+00:00
| 11 | false |
# Intuition\nIf total and of array is not zero then ans will be 1 as we can\'t divide such that sum of individual subarray will be minimum. If total and of array is zero then we can use a loop to find all subarray such that their and is zero\n\n\n\n# Complexity\n- Time complexity:O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int maxSubarrays(vector<int>& nums) {\n \n int a=nums[0];\n for(auto it:nums) a&=it;\n \n int ans=0;\n int curr=(1<<24)-1;\n \n if(a!=0) return 1;\n \n \n for(int i=0;i<nums.size();i++){\n curr&=nums[i];\n cout<<curr<<" ";\n if(curr==a) {\n ans++;\n curr=(1<<24)-1;\n }\n }\n \n return ans;\n }\n};\n```
| 1 | 0 |
['C++']
| 0 |
split-array-into-maximum-number-of-subarrays
|
Python | BitMask | O(n)
|
python-bitmask-on-by-aryonbe-wydj
|
Code\n\nclass Solution:\n def maxSubarrays(self, nums: List[int]) -> int:\n mask = nums[0]\n for num in nums:\n mask = mask & num\n
|
aryonbe
|
NORMAL
|
2023-09-30T16:03:20.214181+00:00
|
2023-09-30T16:03:20.214209+00:00
| 52 | false |
# Code\n```\nclass Solution:\n def maxSubarrays(self, nums: List[int]) -> int:\n mask = nums[0]\n for num in nums:\n mask = mask & num\n if mask: return 1\n curmask = 2**20 - 1\n res = 0\n for num in nums:\n curmask &= num\n if not curmask:\n res += 1\n curmask = 2**20 - 1\n return res\n \n \n \n \n \n \n \n \n```
| 1 | 0 |
['Python3']
| 0 |
split-array-into-maximum-number-of-subarrays
|
Split Sub-Array by "&" Result
|
split-sub-array-by-result-by-linda2024-5z5n
|
Intuition
& options will make the result smaller and smaller;
Till it is 0. Start Another sub-array;
ApproachComplexity
Time complexity:
Space complexity:
Code
|
linda2024
|
NORMAL
|
2025-03-06T17:49:13.720822+00:00
|
2025-03-06T17:49:13.720822+00:00
| 3 | false |
# Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
1. & options will make the result smaller and smaller;
2. Till it is 0. Start Another sub-array;
# 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 {
public int MaxSubarrays(int[] nums) {
int res = 0, pre = -1; // -1 -> 32 1s in binary
foreach(int n in nums)
{
pre &= n;
if(pre == 0) // & result to be 0? start another subArray
{
res++;
pre = -1;
}
}
return Math.Max(1, res);
}
}
```
| 0 | 0 |
['C#']
| 0 |
split-array-into-maximum-number-of-subarrays
|
O(N) C++
|
on-c-by-akhil29-1qtw
|
IntuitionWe can only divide the array into more than 1 subarray if the AND of subarrays are 0.
The answer will always be 1 if AND of subarrays is greater than 0
|
akhil29
|
NORMAL
|
2025-02-13T10:21:43.219170+00:00
|
2025-02-13T10:21:43.219170+00:00
| 3 | false |
# Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
We can only divide the array into more than 1 subarray if the AND of subarrays are 0.
The answer will always be 1 if AND of subarrays is greater than 0 otherwise count subarrays whose AND operation results in 0
# 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 maxSubarrays(vector<int>& nums) {
int and_of_complete_arr = nums[0];
int n = nums.size();
for(int i=1;i<n;i++)
{
and_of_complete_arr &=nums[i];
}
int count = 0;
int temp_and = nums[0];
for(int i=0;i<n;i++)
{
temp_and &=nums[i];
if(temp_and==and_of_complete_arr)
{
count++;
if(i<n-1)
temp_and = nums[i+1];
}
}
return and_of_complete_arr == 0?count:1;
}
};
```
| 0 | 0 |
['C++']
| 0 |
split-array-into-maximum-number-of-subarrays
|
Leetcode 2871
|
leetcode-2871-by-tarundandugula-mswb
|
IntuitionUse Arraylist to store the subarray, once the AND value becomes 0, clear it and use recursion to check for another subarray.ApproachComplexity
Time co
|
TarunDandugula
|
NORMAL
|
2025-01-25T02:24:42.494664+00:00
|
2025-01-25T02:24:42.494664+00:00
| 7 | false |
# Intuition
Use Arraylist to store the subarray, once the AND value becomes 0, clear it and use recursion to check for another subarray.
# Approach
# Complexity
- Time complexity:
- Space complexity:
# Code
```java []
class Solution {
public int maxSubarrays(int[] nums) {
ArrayList<Integer> check = new ArrayList<>();
int count=0; int sum=0;
return rec(nums,0,check,count);
}
private int rec(int[] nums, int ind, List<Integer> a, int count){
if(ind< nums.length){
a.add(nums[ind]);
if(minsum(a)==0){
count++; a.clear();
return rec(nums, ind+1, a, count);
}
else{
a.add(nums[ind]);
return rec(nums, ind+1, a, count);
}
}
return count==0?1:count;
}
private int minsum(List<Integer> a){
int cursum = -1;
for(int x:a){
cursum = cursum & x;
}
return cursum;
}
}
```
| 0 | 0 |
['Recursion', 'Java']
| 1 |
split-array-into-maximum-number-of-subarrays
|
2871. Split Array Into Maximum Number of Subarrays
|
2871-split-array-into-maximum-number-of-wtyi4
|
IntuitionApproachComplexity
Time complexity:
Space complexity:
Code
|
G8xd0QPqTy
|
NORMAL
|
2025-01-21T15:20:07.675561+00:00
|
2025-01-21T15:20:07.675561+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
```python3 []
class Solution:
def maxSubarrays(self, nums: List[int]) -> int:
score, ans = -1, 1
for num in nums:
score &= num
if score == 0:
score = -1
ans += 1
return 1 if ans == 1 else ans - 1
```
| 0 | 0 |
['Python3']
| 0 |
split-array-into-maximum-number-of-subarrays
|
Simple bits manipulation solution || c++ || beats 100%
|
simple-bits-manipulation-solution-c-beat-hceg
|
IntuitionApproachComplexity
Time complexity:O(n)
Space complexity:O(1)
Code
|
vikash_kumar_dsa2
|
NORMAL
|
2024-12-27T17:17:50.575759+00:00
|
2024-12-27T17:17:50.575759+00:00
| 4 | false |
# Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:O(n)
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:O(1)
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```cpp []
class Solution {
public:
int maxSubarrays(vector<int>& nums) {
int minVal = INT_MAX;
int n = nums.size();
if(n == 1){
return 1;
}
for(int i = 0;i<n;i++){
minVal = minVal & nums[i];
}
if(minVal != 0){
return 1;
}
int checkVal = INT_MAX;
int cnt = 0;
for(int i = 0;i<n;i++){
checkVal &= nums[i];
if(checkVal == 0){
cnt++;
checkVal = INT_MAX;
}
}
return cnt;
}
};
```
| 0 | 0 |
['Array', 'Greedy', 'Bit Manipulation', 'C++']
| 0 |
split-array-into-maximum-number-of-subarrays
|
Beats 100% C++ solution with O(N) T.C and O(1) S.C
|
beats-100-c-solution-with-on-tc-and-o1-s-b3yw
|
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
|
SAYANTAN_1729
|
NORMAL
|
2024-10-20T07:26:30.824916+00:00
|
2024-10-20T07:26:30.824954+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(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#define ll int\n int maxSubarrays(vector<int>& nums) {\n ll ans=0, val=((1<<30)-1);\n for(ll i=0;i<nums.size();i++){\n val&=nums[i];\n if(val==0){ans++; val=((1<<30)-1);}\n }\n if(ans==0){ans++;}\n return ans;\n }\n};\n```
| 0 | 0 |
['C++']
| 0 |
split-array-into-maximum-number-of-subarrays
|
BEATS 100% C++ SOLUTIONS
|
beats-100-c-solutions-by-sayantan_1729-xo52
|
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
|
SAYANTAN_1729
|
NORMAL
|
2024-10-20T07:10:26.785752+00:00
|
2024-10-20T07:10:26.785789+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: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#define ll int\n#define pb push_back\n int maxSubarrays(vector<int>& nums) {\n vector<ll> a(nums.size());\n ll ans=((1<<30)-1);\n for(ll i=a.size()-1;i>=0;i--){\n ans=(ans&nums[i]);\n a[i]=ans;\n }\n ll x=((1<<30)-1);\n ll y=x;\n ll Ans=1;\n for(ll i=0;i<(nums.size()-1);i++){\n y=(y&nums[i]);\n if(y+a[i+1]==ans){Ans++; y=x;}\n }\n return Ans;\n }\n};\n```
| 0 | 0 |
['C++']
| 0 |
split-array-into-maximum-number-of-subarrays
|
[Java] ✅ PREFIX AND ✅ 3MS ✅ FAST ✅ BEST ✅ CLEAN CODE
|
java-prefix-and-3ms-fast-best-clean-code-rqmp
|
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n1. Calculate the AND prefix of ALL numbers. This prefix will be the lowes
|
StefanelStan
|
NORMAL
|
2024-10-01T04:21:59.815243+00:00
|
2024-10-01T04:21:59.815266+00:00
| 10 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. Calculate the AND prefix of ALL numbers. This prefix will be the lowest prefixAnd that can be achieved.\n2. If prefixAnd is 0, then we can try to split it in as many chunks as possible, because 0 + 0 +.. + 0 = 0. The sum of all chunks is 0.\n3. However, if the prefix is not zero (eg: 7), splitting it into more chunks will lead to a sum of 7+7+..+7. \n - This is greater than 1 single chunk with prefix 7, so we only need to split it into 1 chunk, just to obtain the minumum score.\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```java []\nclass Solution {\n public int maxSubarrays(int[] nums) {\n int minAnd = nums[0];\n for (int num : nums) {\n minAnd &= num;\n }\n if (minAnd != 0) {\n return 1;\n }\n int segments = 0, prefixAnd = nums[0];\n for (int i = 0; i < nums.length; i++) {\n prefixAnd &= nums[i];\n if (prefixAnd == minAnd) {\n segments++;\n prefixAnd = i < nums.length - 1 ? nums[i+1] : -1;\n }\n }\n return segments;\n }\n}\n```
| 0 | 0 |
['Java']
| 0 |
split-array-into-maximum-number-of-subarrays
|
scala solution
|
scala-solution-by-vititov-4btj
|
scala []\nobject Solution {\n def maxSubarrays(nums: Array[Int]): Int =\n if(nums.reduce(_ & _) != 0) 1 else\n LazyList.unfold((0,0,(1<<20)-1)){case (c
|
vititov
|
NORMAL
|
2024-08-28T14:03:20.755445+00:00
|
2024-08-28T14:03:20.755505+00:00
| 1 | false |
```scala []\nobject Solution {\n def maxSubarrays(nums: Array[Int]): Int =\n if(nums.reduce(_ & _) != 0) 1 else\n LazyList.unfold((0,0,(1<<20)-1)){case (cnt,i,mask) =>\n Option.when(i<nums.length){\n lazy val mask1 = mask&nums(i)\n if(mask1==0) (cnt+1, (cnt+1,i+1, (1<<20)-1)) else (cnt, (cnt,i+1, mask1))\n }\n }.last\n}\n```
| 0 | 0 |
['Greedy', 'Bit Manipulation', 'Scala']
| 0 |
split-array-into-maximum-number-of-subarrays
|
SIMPLE SOLUTION--> ALWAYS TRY TO MAKE 0
|
simple-solution-always-try-to-make-0-by-yuv4v
|
\n\n# Code\n\nclass Solution {\npublic:\n int maxSubarrays(vector<int>& nums) {\n \n int i=0;\n int j =0;\n int n = nums.size();
|
im__ArihantJain
|
NORMAL
|
2024-08-05T04:53:29.243306+00:00
|
2024-08-05T04:53:29.243348+00:00
| 1 | false |
\n\n# Code\n```\nclass Solution {\npublic:\n int maxSubarrays(vector<int>& nums) {\n \n int i=0;\n int j =0;\n int n = nums.size();\n int ans =0;\n int currand = nums[0];\n while(j<n){\n currand = currand&nums[j];\n if(currand==0){\n ans++;\n if(j<n-1){\n currand = nums[++j];\n }else{\n j++;\n }\n \n }else{\n j++;\n }\n \n }\n if(ans ==0){\n return 1;\n }\n return ans;\n\n }\n};\n```
| 0 | 0 |
['C++']
| 0 |
split-array-into-maximum-number-of-subarrays
|
Simple Solution Typescript
|
simple-solution-typescript-by-tal0012-uet4
|
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
|
tal0012
|
NORMAL
|
2024-08-02T16:59:17.738488+00:00
|
2024-08-02T16:59:17.738526+00:00
| 0 | 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```\nfunction maxSubarrays(nums: number[]): number {\n const optimalSum = nums.reduce((acc,curr) => (acc&curr));\n let numOfPartiions = 0;\n let currSum = 0;\n let currXor = -1\n for(const num of nums){\n currXor &= num; \n if(currSum+currXor <= optimalSum){\n currSum+= currXor;\n numOfPartiions++;\n currXor = -1;\n }\n }\n return Math.max(numOfPartiions,1);\n};\n```
| 0 | 0 |
['TypeScript']
| 0 |
split-array-into-maximum-number-of-subarrays
|
Greedy
|
greedy-by-sakshamchhimwal2410-knqp
|
Intuition\nIf we do AND of two number, they will always decrease. Hence the minium will always be either 0 or the AND of complete array.\n\n# Approach\nKeep doi
|
sakshamchhimwal2410
|
NORMAL
|
2024-07-25T19:53:47.044080+00:00
|
2024-07-25T19:53:47.044115+00:00
| 1 | false |
# Intuition\n**If we do `AND` of two number, they will always decrease.** Hence the minium will always be either `0` or the `AND` of complete array.\n\n# Approach\nKeep doing the `AND` for the array, stop only when we get a zero.\n\n>### Corner Case\n>**What if the last number remaining is $>0$ ?**\n*If the size of the split is $>1$ this means that there had been a zero before the current `AND` chain, hence we merge it with that particular chain $-$ `splits=splits-1`*\n\n# Complexity\n- Time complexity:\n$$O(n)$$\n\n- Space complexity:\n$$O(1)$$\n\n# Code\n```\nclass Solution {\npublic:\n int maxSubarrays(vector<int>& nums) {\n int splits = 1, res = nums[0], len = nums.size();\n for (int i = 0; i < len; i++) {\n res = res & nums[i];\n if (res == 0) {\n splits += (i + 1 < len);\n if (i + 1 < len)\n res = nums[i + 1];\n }\n }\n if (res != 0 && splits > 1)\n splits--;\n\n return splits;\n }\n};\n```
| 0 | 0 |
['C++']
| 0 |
split-array-into-maximum-number-of-subarrays
|
C++ || EASY
|
c-easy-by-gauravgeekp-c0r6
|
\n# Code\n\nclass Solution {\npublic:\n int maxSubarrays(vector<int>& a) {\n int n=a.size();\n int c=0;\n int m=a[0];\n for(int i
|
Gauravgeekp
|
NORMAL
|
2024-06-06T22:13:47.729581+00:00
|
2024-06-06T22:13:47.729605+00:00
| 2 | false |
\n# Code\n```\nclass Solution {\npublic:\n int maxSubarrays(vector<int>& a) {\n int n=a.size();\n int c=0;\n int m=a[0];\n for(int i=0;i<n;i++)\n {\n m=m&a[i];\n if(m==0)\n {\n c++;\n if(i+1<n)\n m=a[i+1];\n }\n }\n return c==0 ? 1 : c;\n }\n};\n```
| 0 | 0 |
['C++']
| 0 |
split-array-into-maximum-number-of-subarrays
|
C++
|
c-by-akash92-ac6m
|
Intuition\n Describe your first thoughts on how to solve this problem. \nBitwise &, either reduces the value or keeps it same.\nSo minimum score of an array is
|
akash92
|
NORMAL
|
2024-05-31T04:01:08.025063+00:00
|
2024-05-31T04:02:05.746024+00:00
| 1 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nBitwise &, either reduces the value or keeps it same.\nSo minimum score of an array is always the bitwise & of all elements.\nIf minimum score is not 0, then it is optimal to keep all elements in one subarray to minimise the score.\nOtherwise, all of the subarrays should have a score of 0, we can greedily split the array while trying to make each subarray as small as possible.\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```\nclass Solution {\npublic:\n int maxSubarrays(vector<int>& nums) {\n int n = nums.size();\n int maxS = 0;\n int cumulativeAnd = INT_MAX;\n\n for (int i = 0; i < n; ++i) {\n cumulativeAnd &= nums[i];\n if (cumulativeAnd == 0) {\n maxS++;\n cumulativeAnd = INT_MAX;\n }\n }\n return maxS > 0 ? maxS : 1;\n }\n};\n```
| 0 | 0 |
['Bit Manipulation', 'C++']
| 0 |
split-array-into-maximum-number-of-subarrays
|
Well explained with help of test Case🔥🔥
|
well-explained-with-help-of-test-case-by-h9pv
|
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \nfor the test case [22,2
|
_Biranjay_kumar_
|
NORMAL
|
2024-05-23T07:48:51.638318+00:00
|
2024-05-23T07:48:51.638337+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. -->\nfor the test case [22,21,29,22]\nif you break it into 2 subarray then the sum of score of subarray will become 40 which is not minimum that\'s why the ans is 1.\n`(22 & 21) + (29 & 22) =40`\n`(22 & 21 & 29 & 22) = 20 (Min.)`\n\nso the answer other than 1 is only possible when the and of array is 0 beacuse `0*anything == 0`\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int maxSubarrays(vector<int>& nums) {\n int n = nums.size();\n if(n==0)\n return 0;\n int total_and = nums[0];\n for(int i=1; i<n; i++){\n total_and = nums[i] & total_and;\n }\n \n if(total_and == 0)\n {\n int temp = ~0;\n int count=0;\n for(int i=0; i<n;i++){\n temp = temp & nums[i];\n if(temp == total_and)\n {\n count++;\n temp = ~0;\n }\n }\n return count;\n }\n else return 1;\n \n \n }\n};\n```
| 0 | 0 |
['Greedy', 'Bit Manipulation', 'C++']
| 0 |
split-array-into-maximum-number-of-subarrays
|
Shortest, Easiest, Clean & Clear | To the Point & Beginners Friendly Approach (❤️ ω ❤️)
|
shortest-easiest-clean-clear-to-the-poin-b3ko
|
Code\n\nclass Solution {\npublic:\n int maxSubarrays(vector<int>& nums) {\n int a=nums.front(),x=0;\n for(int i=0;i<nums.size();i++){\n
|
Nitansh_Koshta
|
NORMAL
|
2024-05-08T13:55:54.513010+00:00
|
2024-05-08T13:55:54.513032+00:00
| 1 | false |
# Code\n```\nclass Solution {\npublic:\n int maxSubarrays(vector<int>& nums) {\n int a=nums.front(),x=0;\n for(int i=0;i<nums.size();i++){\n a&=nums[i];\n if(i==nums.size()-1)break;\n else if(a==0){x++;a=nums[i+1];}\n }\n return a==0||x==0?x+1:x;\n\n// if you like my approach then please UpVOTE o((>\u03C9< ))o\n }\n};\n```\n\n\n
| 0 | 0 |
['C++']
| 0 |
split-array-into-maximum-number-of-subarrays
|
Small and Fast Solution (59ms)
|
small-and-fast-solution-59ms-by-royalgam-8eb8
|
Intuition\n Describe your first thoughts on how to solve this problem. \nThinking of collecting of disjoint numbers (who\'s and will result in zero. zero is the
|
RoYalGamr
|
NORMAL
|
2024-05-03T05:49:09.606913+00:00
|
2024-05-03T05:49:09.606948+00:00
| 2 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThinking of collecting of disjoint numbers (who\'s and will result in zero. zero is the minimum possible score they can have).\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nCount the number of continuous sub arrays which result is score = 0. if some array not able to score 0 then merge it with existing arrays. if there is no existing array then take whole array as 1.\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```\n#pragma GCC optimize("O3,unroll-loops")\n#pragma GCC target("avx2,bmi,bmi2,lzcnt,popcnt")\nint speedup = []{ ios::sync_with_stdio(0); cin.tie(0); return 0; }();\nclass Solution {\npublic:\n int maxSubarrays(vector<int>& nums) {\n int count =0;\n int andy = INT_MAX;\n for (int i=0;i<nums.size();i++){\n if (andy & nums[i]){\n andy &= nums[i];\n }else{\n count++;\n andy = INT_MAX;\n }\n }\n if (count == 0){\n return 1;\n }else{\n return count;\n }\n }\n};\n```
| 0 | 0 |
['C++']
| 0 |
split-array-into-maximum-number-of-subarrays
|
Prefix counting AND result zero - Java T:O(N) S:O(1)
|
prefix-counting-and-result-zero-java-ton-th5n
|
Intuition\n Describe your first thoughts on how to solve this problem. \nOthers explain very well on why this is counting AND zero in prefix. Here just to add t
|
wangcai20
|
NORMAL
|
2024-04-07T11:38:08.484375+00:00
|
2024-04-07T11:45:41.877417+00:00
| 2 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nOthers explain very well on why this is counting AND zero in prefix. Here just to add the point why we can increase the zero count by `1` as soon as we detect the AND result is zero in prefix and restart the accumlation.\n\nWhen accumlate AND current `==0`, we detect a subarray in prefix that produces `0`, it could be statndalone `0` or end by `0` (`40`) or no `0` (`12`), in all cases, they are as good as a standalone `0`. We can [**opt1**] put it as a separate subarray; or [**opt2**] expand it to the right into a bigger array to achieve the smallest subarray requirement.\n\nIn **opt1**, we need to make sure the next subarray is also AND result zero, otherwise it violate the requirement and it becomes the case of **opt2**. Now we see that we can safely incrase zero count and start checking the right, if the right subarray is zero, the count will increase again, if not, it is the **op2** and the zero count is good. The take away is in either case of **op1** and **opt2**, we can increse the zero count as soon as we detect AND zero.\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```\nclass Solution {\n public int maxSubarrays(int[] nums) {\n // couting AND zeros in prefix\n int carry = -1, sum = 0;\n for (int val : nums) {\n if ((carry = carry & val) == 0) {\n // zero detected\n sum++;\n carry = -1;\n }\n }\n return Integer.max(1, sum);\n }\n}\n```
| 0 | 0 |
['Java']
| 0 |
split-array-into-maximum-number-of-subarrays
|
Brainteaser | Bit Manipulation
|
brainteaser-bit-manipulation-by-coderpri-tsel
|
Intuition\nIf Bitwise AND of complete array is greater than 0 then we can not reduce the score below that so we return 1 otherwise if the score is zero just bre
|
coderpriest
|
NORMAL
|
2024-04-02T06:32:05.790383+00:00
|
2024-04-02T06:32:05.790411+00:00
| 0 | false |
## Intuition\nIf Bitwise `AND` of complete array is greater than `0` then we can not reduce the score below that so we return `1` otherwise if the score is zero just break the array into maximum number of segments such that their `AND` == `0`\n\n## Approach\nIterate through the array, updating `c` and also tracking a secondary bitwise `AND` result `sc`. If `c` becomes 0 during the iteration, I increment the count `cnt` and reset `c` to INT_MAX. Finally, return 1 if `sc` is greater than 0; otherwise, return `cnt`.\n\n## Complexity\n- Time complexity: $$O(n)$$ \n- Space complexity: $$O(1)$$ \n\n## Code\n```cpp\nclass Solution {\npublic:\n int maxSubarrays(vector<int>& nums) {\n ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0);\n int cnt = 0, c = INT_MAX, sc = INT_MAX;\n for(auto &x : nums){\n sc &= x, c &= x;\n if(c == 0) cnt++, c = INT_MAX;\n } \n return sc > 0 ? 1 : cnt;\n }\n};\n```
| 0 | 0 |
['Array', 'Greedy', 'Bit Manipulation', 'C++']
| 0 |
split-array-into-maximum-number-of-subarrays
|
Runtime 96 ms Beats 100.00% of users with Go
|
runtime-96-ms-beats-10000-of-users-with-z9dus
|
Code\n\nfunc maxSubarrays(nums []int) int {\n totalAnd := nums[0]\n\tn := len(nums)\n\tfor _, num := range nums {\n\t\ttotalAnd &= num\n\t}\n\tif totalAnd >
|
pvt2024
|
NORMAL
|
2024-03-30T06:25:59.747100+00:00
|
2024-03-30T06:25:59.747127+00:00
| 1 | false |
# Code\n```\nfunc maxSubarrays(nums []int) int {\n totalAnd := nums[0]\n\tn := len(nums)\n\tfor _, num := range nums {\n\t\ttotalAnd &= num\n\t}\n\tif totalAnd > 0 {\n\t\treturn 1\n\t}\n\tcurrAnd := 0\n\tsplit := 0\n\tfor i := 0; i < n; i++ {\n\t\tif currAnd == 0 {\n\t\t\tcurrAnd = nums[i]\n\t\t\tsplit++\n\t\t} else {\n\t\t\tcurrAnd &= nums[i]\n\t\t}\n\t}\n\tif currAnd > 0 {\n\t\tsplit--\n\t}\n\treturn split \n}\n```
| 0 | 0 |
['Go']
| 0 |
split-array-into-maximum-number-of-subarrays
|
O(N) Recursive in Erlang
|
on-recursive-in-erlang-by-metaphysicalis-qgx9
|
Approach\n Describe your first thoughts on how to solve this problem. \nThe minimum sum of scores of the subarrays is the score of the entire nums because of th
|
metaphysicalist
|
NORMAL
|
2024-03-18T20:16:30.636074+00:00
|
2024-03-18T20:24:34.310231+00:00
| 7 | false |
# Approach\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe minimum sum of scores of the subarrays is the score of the entire `nums` because of the nature of `AND`. If the score of the entire `nums > 0`, then the answer is 1 because the sum of the subarrays\' scores will be always greater than 1. If the score of the entire `nums` is 0, then we can try to split `nums` into `k` subarrays `nums[0:x1], nums[x1+1:x2], ..., nums[xk:n]` and the score of each subarrays is 0. The `k` is maximized. So we perform a recursive function to calculate the maximum split of zero-score subarrays. \n\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: $O(N)$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $O(N)$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n-spec max_subarrays(Nums :: [integer()]) -> integer().\nmax_subarrays(Nums) -> \n [Ans, _] = solve(Nums),\n max(1, Ans).\n\nsolve([]) -> [0, 16#FFFFF];\nsolve([H|T]) -> \n [Ans, V] = solve(T),\n case V band H == 0 of\n true -> [Ans + 1, 16#FFFFF];\n false -> [Ans, V band H]\n end.\n```
| 0 | 0 |
['Greedy', 'Recursion', 'Erlang']
| 0 |
split-array-into-maximum-number-of-subarrays
|
Simple python3 solution | 700 ms - faster than 96.21% solutions
|
simple-python3-solution-700-ms-faster-th-4juu
|
Approach\n Describe your approach to solving the problem. \nIf nums[0] AND nums[1] AND ... AND nums[-1] != 0 than exist only one subarray with minimum score, so
|
tigprog
|
NORMAL
|
2024-03-18T13:47:10.348002+00:00
|
2024-03-18T13:47:10.348037+00:00
| 5 | false |
# Approach\n<!-- Describe your approach to solving the problem. -->\nIf `nums[0] AND nums[1] AND ... AND nums[-1] != 0` than exist only one subarray with minimum score, so split nums to subarrays with `AND` equal to 0, otherwise return 1.\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 maxSubarrays(self, nums: List[int]) -> int:\n big_number = (1 << 20) - 1\n result = 0\n state = big_number\n for elem in nums:\n state &= elem\n if state == 0:\n result += 1\n state = big_number\n return result or 1\n```
| 0 | 0 |
['Math', 'Greedy', 'Bit Manipulation', 'Python3']
| 0 |
split-array-into-maximum-number-of-subarrays
|
2871. Split Array Into Maximum Number of Subarrays
|
2871-split-array-into-maximum-number-of-e8irm
|
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n\nUnderstanding below test cases is half the answer:\n\nseries a
|
pgmreddy
|
NORMAL
|
2024-02-03T02:51:28.955656+00:00
|
2024-02-03T02:51:28.955687+00:00
| 27 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n\nUnderstanding below test cases is half the answer:\n```\nseries ans \n[1,0, 1,0,1,1 ]\t2 <---------- important - maximize (0 AND) subarrays\n[1,0, 2,0, 1,2]\t3 <---------- important - maximize (0 AND) subarrays\n\n[1,0, 1,0, 1,0]\t3\n[1,2, 1,2, 1,2]\t3\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\n---\n\n```\nvar maxSubarrays = function (a) {\n const MAX_ALL_ONES_IN_BINARY_FORM = 2 ** 32 - 1;\n let count = 0;\n let andValue = MAX_ALL_ONES_IN_BINARY_FORM;\n for (const e of a) {\n andValue = andValue & e;\n if (andValue === 0) {\n count++;\n andValue = MAX_ALL_ONES_IN_BINARY_FORM;\n }\n }\n if (a.length > 0) {\n if (count === 0) {\n count = 1;\n }\n }\n return count;\n};\n```\n\n---\n
| 0 | 0 |
['JavaScript']
| 0 |
split-array-into-maximum-number-of-subarrays
|
Java || Greedy || Simple solution || Beats 100%
|
java-greedy-simple-solution-beats-100-by-aqn2
|
Intuition\nNote that a & b is always less than both numbers a and b \nThus, the min possible sum of scores is the logical AND of all numbers in the array. \nHen
|
inefivberive
|
NORMAL
|
2024-01-22T15:08:20.887872+00:00
|
2024-01-22T19:04:40.481596+00:00
| 9 | false |
# Intuition\nNote that `a & b` is always less than both numbers `a` and `b` \nThus, the min possible sum of scores is the logical AND of all numbers in the array. \nHence, arrray can only be splitted if the logical AND of all the number in the array is zero. We can use greedy to find the number of such subarrays. \n\n\n# Complexity\n- Time complexity:$$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:$$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int maxSubarrays(int[] nums) {\n int ind = 0;\n int count = 0;\n\n int minSum = Integer.MAX_VALUE;\n\n //Greedily find the number of subarrays whose score is zero\n while(ind < nums.length){\n minSum &= nums[ind];\n if(minSum == 0){\n count++;\n minSum = Integer.MAX_VALUE;\n }\n ind++;\n } \n \n //Array can only be split if the and of all numbers is zero\n //And of all numbers is zero if count of number of subarrays > 0\n if(count > 0) return count;\n else return 1;\n }\n}\n```
| 0 | 0 |
['Array', 'Greedy', 'Bit Manipulation', 'Java']
| 0 |
split-array-into-maximum-number-of-subarrays
|
Clear and Simple to Understand
|
clear-and-simple-to-understand-by-akash_-fam5
|
Intuition\nIf the AND of the whole array is greater than 1 then the answer will be 1 , otherwise, keep on taking AND untill the val becomes 0, when it becomes 0
|
akash_striver
|
NORMAL
|
2024-01-18T15:07:01.503125+00:00
|
2024-01-18T15:07:01.503156+00:00
| 8 | false |
# Intuition\nIf the AND of the whole array is greater than 1 then the answer will be 1 , otherwise, keep on taking AND untill the val becomes 0, when it becomes 0, increase the value of answer by one.\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int maxSubarrays(int[] nums) {\n \n int min=nums[0];\n for(int i=1;i<nums.length;++i){\n min&=nums[i];\n }\n\n if(min>0) return 1;\n\n int ans=1;\n int temp=nums[0];\n for(int i=1;i<nums.length;++i){\n if(temp==0){\n ans++;\n temp=nums[i];\n }\n else\n temp&=nums[i];\n if(i==nums.length-1 && temp>0)\n ans--;\n }\n return ans;\n }\n}\n```
| 0 | 0 |
['Greedy', 'Bit Manipulation', 'Python', 'Java', 'Python3']
| 0 |
split-array-into-maximum-number-of-subarrays
|
Simple solution without 'bitmask' . Runtime 100%
|
simple-solution-without-bitmask-runtime-vh7lc
|
\n\n\nclass Solution:\n def maxSubarrays(self, nums: List[int]) -> int:\n total, cnt = 0, 0\n for n in nums:\n if not total:\n
|
xxxxkav
|
NORMAL
|
2024-01-07T22:28:11.396676+00:00
|
2024-01-07T22:28:11.396744+00:00
| 3 | false |
\n\n```\nclass Solution:\n def maxSubarrays(self, nums: List[int]) -> int:\n total, cnt = 0, 0\n for n in nums:\n if not total:\n total = n\n cnt += 1\n else:\n total &= n\n return cnt-1 if total and cnt != 1 else cnt \n```
| 0 | 0 |
['Python3']
| 0 |
split-array-into-maximum-number-of-subarrays
|
Java || 4ms Solution || 56% Beats || Easy to Understand || O(N) Solution
|
java-4ms-solution-56-beats-easy-to-under-bomr
|
\n\n# Intuition\nI want to check the And of all the bits first and if it is non-zero then simply return 1\n\n# Approach\nFinding the And of all the elements ini
|
pparam5241
|
NORMAL
|
2024-01-05T05:59:53.279182+00:00
|
2024-01-05T05:59:53.279208+00:00
| 5 | false |
\n\n# Intuition\nI want to check the And of all the bits first and if it is non-zero then simply return 1\n\n# Approach\nFinding the And of all the elements initially and deciding weather we can split the array into sub-arrays or not\nif it is not possible then simply return 1 else try to divide into sub-arrays by simply using And for all total elements on it and keep counter variable for keeping count values.\n\n# Complexity\n- Time complexity:\nO(N)\n\n- Space complexity:\nO(1)\n\n# Code\n```\nclass Solution {\n public int maxSubarrays(int[] nums) {\n int totalAnd = nums[0];\n for(int num: nums) totalAnd &= num;\n if(totalAnd != 0) return 1;\n int count = 0;\n totalAnd = nums[0];\n for(int i = 0;i<nums.length;i++){\n if(totalAnd == 0){\n totalAnd = nums[i];\n }\n totalAnd&=nums[i];\n if(totalAnd == 0) count++;\n }\n return count;\n }\n}\n```
| 0 | 0 |
['Java']
| 0 |
split-array-into-maximum-number-of-subarrays
|
Beats 100% T.C. JAVA users || O(N) Sol. || Bits Manipulation
|
beats-100-tc-java-users-on-sol-bits-mani-6rjy
|
Approach is based on the hints provided\n Describe your first thoughts on how to solve this problem. \n\n# Complexity\n- Time complexity: O(N)\n Add your time c
|
ArchitVohra
|
NORMAL
|
2024-01-04T13:23:21.028110+00:00
|
2024-01-04T13:23:21.028136+00:00
| 3 | false |
# Approach is based on the hints provided\n<!-- Describe your first thoughts on how to solve this 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# Explantion is in the code itself \nI have also discussed an edge case and made everything clear as much I could. Thanks for even viewing.\n\n# Code\n```\n\nclass Solution {\n public int maxSubarrays(int[] nums) {\n //And of all elements will be min as we increase the chances of getting more zeroes by anding more numbers\n //so if And of all elements is not zero then answer will be no splitting i.e. 1\n int AND=-1;\n for(int i:nums){\n AND = ( AND & i );\n }\n if(AND!=0) return 1;\n // if And of the array is 0 then we will iterate over the array by keeping a temp set -1\n // if temp gets 0 we will ans+=1;\n // but for the last elements which are non-zero in the array , thus making the temp !=0\n // that case is already taken care of by the previous occuring temp that was 0\n // i am talking about cases like : {0,8,0,0,0,23}; here req output:4\n // we will have our answer till 4th index as 4 but for the 5th index: 23 it is already taken care by the previous 0 and is the only case where we have our minds on.(just tryin to be cool...)\n\n int ans=0;\n int temp=-1;\n for(int i=0;i<nums.length;i++){\n temp &= nums[i];\n if(temp==0){\n ans++;\n temp=-1;\n }\n }\n return ans;\n }\n}\n```\n
| 0 | 0 |
['Java']
| 0 |
split-array-into-maximum-number-of-subarrays
|
Python Simple Solution | O(n) Two Pass | 740ms, Beats 95% Time
|
python-simple-solution-on-two-pass-740ms-55na
|
Approach\n Describe your approach to solving the problem. \nCheck the total score of the array. If it is not equal to 0, return 1. Else, loop through the array
|
hemantdhamija
|
NORMAL
|
2023-12-31T07:17:51.587981+00:00
|
2023-12-31T07:17:51.588015+00:00
| 6 | false |
# Approach\n<!-- Describe your approach to solving the problem. -->\nCheck the total score of the array. If it is not equal to 0, return 1. Else, loop through the array again and whenever the score becomes 0, split the array and reset the score.\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```python []\nclass Solution:\n def maxSubarrays(self, nums: List[int]) -> int:\n totalScore = nums[0]\n for num in nums:\n totalScore &= num\n if totalScore:\n return 1\n size, score = 1, (1 << 20) - 1\n for num in nums:\n score &= num\n if score == 0:\n size += 1\n score = (1 << 20) - 1\n if score:\n size -= 1\n return size\n```
| 0 | 0 |
['Array', 'Greedy', 'Bit Manipulation', 'Python', 'Python3']
| 0 |
split-array-into-maximum-number-of-subarrays
|
EASY SOLUTION FOR BEGINERS // JAVA
|
easy-solution-for-beginers-java-by-deepa-1pdd
|
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
|
deepakchandra12
|
NORMAL
|
2023-12-23T11:13:58.338949+00:00
|
2023-12-23T11:13:58.338983+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:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int maxSubarrays(int[] nums) {\n int totaland = nums[0];\n for(int i = 0;i<nums.length; i++){\n totaland &= nums[i];\n }\n if(totaland != 0) return 1;\n int currentand = -1;\n int ans = 0;\n for(int i =0;i<nums.length;i++){\n if(currentand == -1) currentand = nums[i];\n else{\n currentand &= nums[i];\n }\n if(currentand == 0){\n ans++;\n currentand = -1;\n }\n }\n return ans;\n\n \n }\n}\n```
| 0 | 0 |
['Java']
| 0 |
split-array-into-maximum-number-of-subarrays
|
EASY SOLUTION FOR BEGINERS // JAVA
|
easy-solution-for-beginers-java-by-deepa-sc2s
|
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
|
deepakchandra12
|
NORMAL
|
2023-12-23T11:13:41.854863+00:00
|
2023-12-23T11:13:41.854895+00:00
| 1 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int maxSubarrays(int[] nums) {\n int totaland = nums[0];\n for(int i = 0;i<nums.length; i++){\n totaland &= nums[i];\n }\n if(totaland != 0) return 1;\n int currentand = -1;\n int ans = 0;\n for(int i =0;i<nums.length;i++){\n if(currentand == -1) currentand = nums[i];\n else{\n currentand &= nums[i];\n }\n if(currentand == 0){\n ans++;\n currentand = -1;\n }\n }\n return ans;\n\n \n }\n}\n```
| 0 | 0 |
['Java']
| 0 |
split-array-into-maximum-number-of-subarrays
|
why greedy
|
why-greedy-by-abc32-xoo9
|
Intuition\n Describe your first thoughts on how to solve this problem. \nThe answer is obtained by greedily taking the interval where & in nums becomes 0 from i
|
abc32
|
NORMAL
|
2023-12-19T14:08:17.146488+00:00
|
2023-12-19T14:52:25.252490+00:00
| 1 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe answer is obtained by greedily taking the interval where & in nums becomes 0 from i=0.\n\nSuppose that when nums[i]&nums[i+1]&...&nums[j]=0, the interval is not separated by the jth interval. Even if we take (j<k), nums[i]&...&nums[k]=0. Suppose that after doing so, we were able to take the next interval {k+1,..,v}. Here, nums[k+1]&...&nums[v]=0, so nums[j]&...&(nums[k+1]&...&nums[v])=0. Therefore, you can also create an interval with {j~v}. So, the minimum cost is greedily take j.\n\nLet the above answer be ans.\nHere, the last interval {L,...,n-1} may not be 0. At that time, even if you separate the intervals within this interval (because there is a certain digit where all nums in this interval are 1), you cannot set it to 0 using the "& operation". Therefore, at least L needs to be extended to the left. In this case, in order to make the answer greater than or equal to ans+1, it is necessary to divide the interval within the "second to last interval" into two or more parts, but if that is possible, then L is not a greedy solution. So it\'s not possible.\n\nTherefore, this interval needs to be merged with the "previous interval". And that interval turns out to be the best answer. So, taking it greedy is the answer.\nI apologize if there are any mistakes or incorrect descriptions.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\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```\nclass Solution {\npublic:\n int maxSubarrays(vector<int>& nums) {\n int n=nums.size();\n int s=nums[0];\n for(int x:nums){\n s&=x;\n }\n if(s!=0){\n return 1;\n }\n int ans=0;\n for(int i=0;i<n;){\n int s=nums[i];\n int j=i+1;\n ans++;\n while(j<n&&s!=0){\n s&=nums[j];\n j++;\n }\n if(s!=0){\n ans--;\n }\n //cout<<i<<" "<<j<<endl;\n i=j;\n }\n return ans;\n }\n};\n```
| 0 | 0 |
['C++']
| 0 |
split-array-into-maximum-number-of-subarrays
|
Effective Greedy Solution
|
effective-greedy-solution-by-adit26-2003-3azn
|
Approach\nWe can simply use a greedy approach here for the answer as the minimum answer for AND we can get is 0. So first take the and of all elements.if its no
|
Adit26-2003
|
NORMAL
|
2023-12-13T03:36:06.964268+00:00
|
2023-12-13T03:36:06.964294+00:00
| 0 | false |
# Approach\nWe can simply use a greedy approach here for the answer as the minimum answer for AND we can get is 0. So first take the and of all elements.if its not 0 then return 1 as the entire array can be taken.\n\nNow iterate through the array and check for zero AND product. Whenever 0 is achieved count increase by 1 and reset the product value to INT_MAX;\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(1)\n\n# Code\n```\nclass Solution {\npublic:\n int maxSubarrays(vector<int>& nums) \n {\n int totalAnd=INT_MAX;\n for(auto i:nums)\n totalAnd&=i;\n if(totalAnd!=0)\n return 1;\n int curr=INT_MAX;\n int count=0;\n for(auto i:nums)\n {\n curr&=i;\n if(curr==0)\n {\n count++;\n curr=INT_MAX;\n }\n }\n return count;\n }\n};\n```
| 0 | 0 |
['C++']
| 0 |
split-array-into-maximum-number-of-subarrays
|
C++
|
c-by-tinachien-052i
|
\nclass Solution {\npublic:\n int maxSubarrays(vector<int>& nums) {\n int count0 = (nums[0] == 0); \n int n = nums.size();\n int
|
TinaChien
|
NORMAL
|
2023-12-10T06:16:57.789625+00:00
|
2023-12-10T06:16:57.789655+00:00
| 0 | false |
```\nclass Solution {\npublic:\n int maxSubarrays(vector<int>& nums) {\n int count0 = (nums[0] == 0); \n int n = nums.size();\n int var = nums[0];\n for(int i = 1; i < n; i++){\n count0 += (nums[i] == 0);\n var &= nums[i];\n }\n if(var != 0)\n return 1;\n int idx = 0;\n int ret = count0;\n while(idx < n){\n if(nums[idx] == 0){\n idx++;\n continue;\n }\n int tmp = nums[idx];\n idx++;\n while(idx < n){\n if(nums[idx] == 0){\n break;\n }\n tmp &= nums[idx];\n if(tmp == 0){\n ret++;\n idx++;\n break;\n }\n idx++;\n }\n }\n return ret;\n }\n};\n```
| 0 | 0 |
[]
| 0 |
split-array-into-maximum-number-of-subarrays
|
scala solution
|
scala-solution-by-lyk4411-1sww
|
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
|
lyk4411
|
NORMAL
|
2023-11-25T10:29:02.516263+00:00
|
2023-11-25T10:29:02.516294+00:00
| 1 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nobject Solution {\n def maxSubarrays(nums: Array[Int]): Int = {\n val mi = nums.reduce(_ & _)\n val n = nums.size\n def f(i: Int, cur: Int, res: Int): Int = {\n if(i == n) res\n else if((nums(i) & cur) != 0) f(i + 1, cur & nums(i), res)\n else f(i + 1, Int.MaxValue, res + 1)\n }\n if(mi == 0) f(0, Int.MaxValue, 0) else 1\n }\n}\n```
| 0 | 0 |
['Scala']
| 0 |
split-array-into-maximum-number-of-subarrays
|
Kotlin O(n) greedy
|
kotlin-on-greedy-by-aliam-b21g
|
Intuition\nThe smallest possible subarray score is 0.\n\nFirst, check if it is possible to sum all of subarray to 0. If not, then return 1 which is the only pos
|
aliam
|
NORMAL
|
2023-11-07T10:03:29.792914+00:00
|
2023-11-07T10:03:29.792943+00:00
| 0 | false |
# Intuition\nThe smallest possible subarray score is 0.\n\nFirst, check if it is possible to sum all of subarray to 0. If not, then return 1 which is the only possible subarray (the whole input aray) that satisfies the conditions and it is not possible to find more subarrays.\n\nIf whole array score is 0, then we try greedily to find more subarrays with 0 score, count them and return the count.\n\nAs worst, the only possbile subarry with 0 score is the whole array.\n\n# Code\n```\nclass Solution {\n fun maxSubarrays(nums: IntArray): Int {\n var p = nums[0]\n for (n in nums)\n p = p and n\n \n if (p != 0)\n return 1\n \n var cur = Integer.MAX_VALUE\n var res = 0\n for (n in nums) {\n cur = cur and n\n\n if (cur == 0) {\n res++\n cur = Integer.MAX_VALUE\n }\n }\n\n return res\n }\n}\n```
| 0 | 0 |
['Greedy', 'Kotlin']
| 0 |
split-array-into-maximum-number-of-subarrays
|
Java O(N) | 100% Faster | Greedy
|
java-on-100-faster-greedy-by-tbekpro-0e6r
|
Intuition\nYou need to find the score for the whole array. And this will be the max score (with count = 1).\n\nThen you need to go through array using greedy ap
|
tbekpro
|
NORMAL
|
2023-11-03T12:35:36.562932+00:00
|
2023-11-03T12:35:36.562997+00:00
| 5 | false |
# Intuition\nYou need to find the score for the whole array. And this will be the max score (with count = 1).\n\nThen you need to go through array using greedy approach:\nYou apply bitwise AND operation until you find currAnd <= andMax. If you find such a subarray, then you sum this score.\n\nIf sum of scores is <= andMax, then you return count, else return 1.\n\n\n# Complexity\n- Time complexity: O(N)\n\n# Code\n```\nclass Solution {\n public int maxSubarrays(int[] nums) {\n if (nums.length == 1) return 1;\n int andMax = nums[0], count = 0, currAnd = nums[0], sum = 0;\n for (int n : nums) andMax &= n;\n for (int i = 1; i < nums.length; i++) {\n int n = nums[i];\n if (currAnd <= andMax) {\n count++;\n sum += currAnd;\n currAnd = n;\n }\n currAnd &= n;\n }\n if (currAnd <= andMax) {\n count++;\n sum += currAnd;\n }\n return sum <= andMax ? count : 1;\n }\n}\n```
| 0 | 0 |
['Java']
| 0 |
split-array-into-maximum-number-of-subarrays
|
O(n) Greedy One Pass Solution
|
on-greedy-one-pass-solution-by-robert961-hltz
|
Intuition\n Describe your first thoughts on how to solve this problem. \nI felt like this problem was tricky and it took me awhile to realize some essential tip
|
robert961
|
NORMAL
|
2023-10-27T17:11:45.329754+00:00
|
2023-10-27T17:11:45.329779+00:00
| 8 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nI felt like this problem was tricky and it took me awhile to realize some essential tips to help solve it. \n\nTricks to Solve this Problem. \n-I realized to find the absolute min of the array, you take each element and & it with the one before. \n\n-& two elements will always result in the min of the two elements or something smaller.\n\n-If the min of the array isn\'t 0 then return it. We do this because if the min isn\'t zero it is impossible to create a sum to equate to that with the array. The smaller amounts of the array will always be at a minimum the min of the array so adding them will surpass the min of the array. \n\nNow iterate through the array and & the current element with the previous. Do this until you get a value equal to minArry. Then create a new group and continue until you are at the end of the array. Return the amount of groups -1 since we either added a group at the end (if the last element made the group equal to minArry) or the last group never equaled minArry(so it must be merged with the previous group which did equal minArry).\n```\nclass Solution:\n def maxSubarrays(self, nums: List[int]) -> int:\n minArry, prev = nums[0], 2**32-1\n length, groups = len(nums), 1\n for num in nums[1:]:\n minArry &= num\n if minArry: return 1\n \n for idx, num in enumerate(nums):\n prev &= num\n if prev == minArry:\n groups += 1\n prev = 2**32-1\n return groups -1\n```
| 0 | 0 |
['Python3']
| 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.