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
apply-operations-to-an-array
Short and sweet solution in Leetcode history
short-and-sweet-solution-in-leetcode-his-8jcu
\n\n# Code\n\nclass Solution {\npublic:\n vector<int> applyOperations(vector<int>& nums) {\n int n=nums.size();\n for(int i=0;i<n-1;i++){\n
vishnoi29
NORMAL
2022-11-06T04:17:40.476537+00:00
2022-11-06T04:17:40.476582+00:00
710
false
\n\n# Code\n```\nclass Solution {\npublic:\n vector<int> applyOperations(vector<int>& nums) {\n int n=nums.size();\n for(int i=0;i<n-1;i++){\n if(nums[i]==nums[i+1]){\n nums[i]=nums[i]*2;\n nums[i+1]=0;\n }\n }\n int nc=0;\n for(int i=0;i<n;i++){\n if(nums[i]!=0){\n swap(nums[nc],nums[i]);\n nc++;\n }\n }\n return nums;\n }\n};\n```
9
0
['Array', 'C++']
1
apply-operations-to-an-array
Simple Do what is said!!
simple-do-what-is-said-by-arunk_leetcode-c47s
IntuitionThe problem requires us to process adjacent elements in an array and move all zeros to the end while preserving the order of non-zero elements.Approach
arunk_leetcode
NORMAL
2025-03-01T04:28:46.847697+00:00
2025-03-01T04:28:46.847697+00:00
545
false
# Intuition The problem requires us to process adjacent elements in an array and move all zeros to the end while preserving the order of non-zero elements. # Approach 1. Traverse the array once and check for adjacent equal elements. 2. If two consecutive elements are equal, double the first element and set the second to zero. 3. Perform another pass using a two-pointer approach to move all non-zero elements to the left while keeping zeros at the end. # Complexity - Time complexity: - $$O(n)$$ as we traverse the array twice. - Space complexity: - $$O(1)$$ as we modify the array in place. ```cpp [] class Solution { public: vector<int> applyOperations(vector<int>& nums) { int n = nums.size(); // Step 1: Process adjacent elements for (int i = 0; i < n - 1; i++) { if (nums[i] == nums[i + 1]) { nums[i] *= 2; nums[i + 1] = 0; } } // Step 2: Move zeros to the end int j = 0; for (int i = 0; i < n; i++) { if (nums[i] != 0) { swap(nums[i], nums[j]); j++; } } return nums; } }; ```
8
0
['Array', 'Two Pointers', 'Simulation', 'C++']
0
apply-operations-to-an-array
Easy Python Solution
easy-python-solution-by-vistrit-aekb
\n# Code\n\nclass Solution:\n def applyOperations(self, nums: List[int]) -> List[int]:\n l=[]\n c=0\n for i in range(len(nums)-1):\n
vistrit
NORMAL
2022-11-15T16:13:54.192701+00:00
2022-11-15T16:13:54.192748+00:00
1,124
false
\n# Code\n```\nclass Solution:\n def applyOperations(self, nums: List[int]) -> List[int]:\n l=[]\n c=0\n for i in range(len(nums)-1):\n if(nums[i]==nums[i+1]):\n nums[i]=nums[i]*2\n nums[i+1]=0\n for i in nums:\n if i!=0:\n l.append(i)\n else:\n c+=1\n return l+[0]*c\n```
8
0
['Python', 'Python3']
0
apply-operations-to-an-array
C++ clean and simple sol || single pass || Time O(N) || Space O(1)
c-clean-and-simple-sol-single-pass-time-yj4mv
\nclass Solution {\npublic:\n vector<int> applyOperations(vector<int>& nums) {\n \n int j=0;\n for(int i=0;i<nums.size()-1;i++)\n
aniketpawar
NORMAL
2022-11-06T05:59:52.769053+00:00
2022-11-06T09:12:45.505257+00:00
643
false
```\nclass Solution {\npublic:\n vector<int> applyOperations(vector<int>& nums) {\n \n int j=0;\n for(int i=0;i<nums.size()-1;i++)\n {\n if(nums[i]&&nums[i]==nums[i+1])\n {\n int a=nums[i]*2;\n nums[i]=nums[i+1]=0;\n nums[j++]=a;\n }\n else if(nums[i])\n {\n int a=nums[i];\n nums[i]=0;\n nums[j++]=a; \n }\n }\n if(nums[nums.size()-1])\n {\n int a=nums[nums.size()-1];\n nums[nums.size()-1]=0;\n nums[j]=a; \n }\n return nums;\n }\n};\n```\npls upvote the sol if u like
8
0
['C']
0
apply-operations-to-an-array
Efficient Array Transformation: Merging & Zero Shifting
efficient-array-transformation-merging-z-g18u
IntuitionThe problem requires sequentially modifying the array by merging adjacent equal elements and shifting all zeros to the end. The key idea is to perform
anill056
NORMAL
2025-03-01T16:39:41.977521+00:00
2025-03-01T16:39:41.977521+00:00
14
false
# Intuition The problem requires sequentially modifying the array by merging adjacent equal elements and shifting all zeros to the end. The key idea is to perform these operations in a step-by-step manner while ensuring minimal extra operations and maintaining the relative order of elements. # Approach First, we iterate through the array to check adjacent elements. If two consecutive elements are equal, we merge them by doubling the first one and setting the second to zero. After this step, we make a second pass to shift all zeros to the end, ensuring the relative order of non-zero elements is preserved. # Complexity - Time complexity: O(n) - Space complexity: O(1) # Code ```cpp [] #include <iostream> #include <vector> using namespace std; class Solution { public: vector<int> applyOperations(vector<int>& nums) { int n = nums.size(); int position = 0; int i; for (i = 0; i < n - 1; i++) { if (nums[i] == nums[i + 1]) { nums[i] *= 2; nums[i + 1] = 0; } } for (i = 0; i < n; i++) { if (nums[i] != 0) { swap(nums[i], nums[position]); position++; } } return nums; } }; ```
7
0
['Array', 'Simulation', 'C++']
0
apply-operations-to-an-array
Simple Java Solution
simple-java-solution-by-siddhant_2002-7x9g
Complexity Time complexity: O(n) Space complexity: O(1) Code
siddhant_2002
NORMAL
2025-03-01T07:21:15.071822+00:00
2025-03-01T07:21:15.071822+00:00
369
false
# Complexity - Time complexity: $$O(n)$$ - Space complexity: $$O(1)$$ # Code ```java [] class Solution { public int[] applyOperations(int[] nums) { int len = nums.length; for(int i = 0; i < len-1; i++) { if(nums[i] == nums[i+1]) { nums[i] = nums[i] << 1; nums[i+1] = 0; } } for(int i = 0, j = 0; i < len; i++) { if(nums[i] != 0) { int dup = nums[i]; nums[i] = nums[j]; nums[j] = dup; j++; } } return nums; } } ```
7
0
['Array', 'Two Pointers', 'Simulation', 'Java']
1
apply-operations-to-an-array
One Pass
one-pass-by-votrubac-qhuh
C++\ncpp\nvector<int> applyOperations(vector<int>& nums) {\n vector<int> res(nums.size());\n for(int i = 0, j = 0; i < nums.size(); ++i)\n if (nums
votrubac
NORMAL
2022-11-14T17:35:48.411910+00:00
2022-11-14T17:35:48.411951+00:00
469
false
**C++**\n```cpp\nvector<int> applyOperations(vector<int>& nums) {\n vector<int> res(nums.size());\n for(int i = 0, j = 0; i < nums.size(); ++i)\n if (nums[i]) {\n if (i < nums.size() - 1 && nums[i] == nums[i + 1]) {\n res[j++] = nums[i] * 2;\n nums[i + 1] = 0;\n } \n else if (nums[i])\n res[j++] = nums[i];\n }\n return res;\n}\n```
7
0
['C']
1
apply-operations-to-an-array
Java One-pass | Time O(n) | Space O(n)
java-one-pass-time-on-space-on-by-chenli-niaz
\nclass Solution {\n public int[] applyOperations(int[] nums) {\n int[] ans = new int[nums.length];\n if (nums.length == 0) return ans;\n
chenlize96
NORMAL
2022-11-06T04:08:31.848622+00:00
2022-11-09T06:50:34.736758+00:00
761
false
```\nclass Solution {\n public int[] applyOperations(int[] nums) {\n int[] ans = new int[nums.length];\n if (nums.length == 0) return ans;\n int pointer = 0;\n for (int i = 0; i < nums.length - 1; i++) {\n if (nums[i] == nums[i + 1] && nums[i] != 0) {\n nums[i] *= 2;\n ans[pointer++] = nums[i];\n nums[i + 1] = 0;\n } else if (nums[i] != 0) {\n ans[pointer++] = nums[i];\n }\n }\n if (nums[nums.length - 1] != 0) {\n ans[pointer] = nums[nums.length - 1];\n }\n return ans;\n }\n}\n```
7
0
['Java']
1
apply-operations-to-an-array
Brute Force Approach
brute-force-approach-by-burle_damodar-dzan
IntuitionApproachComplexity Time complexity: Space complexity: Code
Burle_Damodar
NORMAL
2025-03-01T06:13:20.908288+00:00
2025-03-01T06:13:20.908288+00:00
284
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```cpp [] class Solution { public: vector<int> applyOperations(vector<int>& nums) { int n = nums.size(); // Step 1: Merge adjacent equal numbers for (int i = 0; i < n - 1; i++) { if (nums[i] == nums[i + 1]) { nums[i] = 2 * nums[i]; nums[i + 1] = 0; } } // Step 2: Move all zeros to the right (Bubble Move technique) for (int i = 0; i < n; i++) { for (int j = 0; j < n - 1; j++) { if (nums[j] == 0 && nums[j + 1] != 0) { swap(nums[j], nums[j + 1]); } } } return nums; } }; ```
6
0
['C++']
0
apply-operations-to-an-array
Good to go💯🚀. Must read Easy Template
good-to-go-must-read-easy-template-by-di-l008
26. Remove Duplicates from Sorted Array\n27. Remove Element\n80. Remove Duplicates from Sorted Array II\n283. Move Zeroes\n2460. Apply Operations to an Array\n9
Dixon_N
NORMAL
2024-09-19T21:36:43.266551+00:00
2024-09-19T22:51:13.387937+00:00
322
false
[26. Remove Duplicates from Sorted Array](https://leetcode.com/problems/remove-duplicates-from-sorted-array/solutions/5505499/my-accepted-java-solution/)\n[27. Remove Element](https://leetcode.com/problems/remove-element/solutions/5505493/good-to-go/)\n[80. Remove Duplicates from Sorted Array II](https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/solutions/5505483/my-accepted-java-solution-with-similar-problems/)\n[283. Move Zeroes](https://leetcode.com/problems/move-zeroes/solutions/5810033/good-to-go-okay-so-here-is-the-template/)\n[2460. Apply Operations to an Array](https://leetcode.com/problems/apply-operations-to-an-array/solutions/5810074/good-to-go-must-read-easy-template/)\n[905. Sort Array By Parity](https://leetcode.com/problems/sort-array-by-parity/solutions/5810076/fastest-solution-out-there-bits-on-fire/)\n[2418. Sort the People](https://leetcode.com/problems/sort-the-people/solutions/5810092/goo-to-go-all-possible-solution/)\n\n\n# Code\n```java []\n// Approach -1\n\nclass Solution {\n public int[] applyOperations(int[] nums) {\n int n = nums.length;\n \n // Apply operations\n for (int i = 0; i < n - 1; i++) {\n if (nums[i] == nums[i + 1]) {\n nums[i]= nums[i]<<1;\n nums[i + 1] = 0;\n }\n }\n \n // Move non-zero elements to the front\n int nonZeroIndex = 0;\n for (int i = 0; i < n; i++) {\n if (nums[i] != 0) {\n nums[nonZeroIndex++] = nums[i];\n }\n }\n \n // Fill the rest with zeros\n while (nonZeroIndex < n) {\n nums[nonZeroIndex++] = 0;\n }\n \n return nums;\n }\n}\n```\n```java []\n// Appraoch - 2\n\nclass Solution {\n public int[] applyOperations(int[] nums) {\n int n = nums.length;\n \n // Apply operations\n for (int i = 0; i < n - 1; i++) {\n if (nums[i] == nums[i + 1]) {\n nums[i] = nums[i]<<1;\n nums[i + 1] = 0;\n }\n }\n \n // Move zeros to the end using two pointers\n int nonZeroPtr = 0;\n for (int i = 0; i < n; i++) {\n if (nums[i] != 0) {\n swap(nums, i, nonZeroPtr);\n nonZeroPtr++;\n }\n }\n \n return nums;\n }\n \n private void swap(int[] nums, int i, int j) {\n if (i != j && nums[i] != nums[j]) {\n nums[i] = nums[i] ^ nums[j];\n nums[j] = nums[i] ^ nums[j];\n nums[i] = nums[i] ^ nums[j];\n }\n }\n}\n```
6
0
['Java']
3
apply-operations-to-an-array
JAVA | apply-operations-to-an-array
java-apply-operations-to-an-array-by-ven-q0eq
\nclass Solution {\n public int[] applyOperations(int[] nums) {\n int k=0;\n int n=nums.length;\n for(int i=0;i<n-1;i++)\n {\n
Venkat089
NORMAL
2022-11-06T10:54:08.109872+00:00
2022-11-06T10:54:08.109912+00:00
681
false
```\nclass Solution {\n public int[] applyOperations(int[] nums) {\n int k=0;\n int n=nums.length;\n for(int i=0;i<n-1;i++)\n {\n if(nums[i]==nums[i+1]){\n nums[i]*=2;\n nums[i+1]=0;\n }\n if(nums[i]!=0)nums[k++]=nums[i];\n }\n if(nums[n-1]!=0)nums[k++]=nums[n-1];\n \n for(int j=k;j<n;j++)nums[j]=0;\n \n return nums;\n }\n}\n```
6
0
['Java']
0
apply-operations-to-an-array
Java Easy Solution
java-easy-solution-by-abhishekalimchanda-fpf7
\n# Code\n\nclass Solution {\n public int[] moveZeroes(int[] nums) {\n if(nums.length == 0 || nums == null) return nums;\n int j = 0;\n
abhishekalimchandani69
NORMAL
2022-11-06T06:15:01.450344+00:00
2022-11-06T06:15:01.450388+00:00
1,090
false
\n# Code\n```\nclass Solution {\n public int[] moveZeroes(int[] nums) {\n if(nums.length == 0 || nums == null) return nums;\n int j = 0;\n for (int i : nums){\n if(i!=0) nums[j++] = i;\n }\n while (j< nums.length){\n nums[j++] = 0;\n }\n return nums;\n }\n public int[] applyOperations(int[] nums) {\n ArrayList<Integer> list = new ArrayList<>();\n for (int i = 0; i < nums.length - 1; i++) {\n if(nums[i] == nums[i+1]){\n nums[i] = nums[i]*2;\n nums[i+1] = 0;\n }\n }\n return moveZeroes(nums);\n }\n}\n```
6
0
['Java']
2
apply-operations-to-an-array
two pointers approach O(1) space || JAVA || python || python3
two-pointers-approach-o1-space-java-pyth-limf
IntuitionApproachiterate every pair of elements and check whether it is same or not if same then perform actions he gave Approach 1 : create an empty arr of siz
yuvejkumar
NORMAL
2025-03-01T17:40:43.153309+00:00
2025-03-01T17:40:43.153309+00:00
130
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> iterate every pair of elements and check whether it is same or not if same then perform actions he gave Approach 1 : create an empty arr of size nums.length iterate in nums if value > 0 then update in newarr and increment the index this approach is faster but space complexity is O(N) Approach 2 : use two pointers one points --> 0 and other which is > 0 swap the elements # 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 ```java [] class Solution { public int[] applyOperations(int[] nums) { for (int i=0;i<nums.length-1;i++){ if (nums[i]==nums[i+1]){ nums[i]*=2; nums[i+1]=0; } } int i; int j=0; while (j<nums.length){ if (nums[j]==0){ i=j+1; while (i<nums.length){ if (nums[i]>0){ nums[j]=nums[i]; nums[i]=0; break; } i++; } } j++; } return nums; ``` ```python [] class Solution(object): def applyOperations(self, nums): for i in range(len(nums)-1): if (nums[i]==nums[i+1]): nums[i]=nums[i]*2 nums[i+1]=0 n=nums.count(0) for i in range(n): nums.remove(0) nums.append(0) return nums """ :type nums: List[int] :rtype: List[int] """ ``` ```python3 [] class Solution: def applyOperations(self, nums: List[int]) -> List[int]: for i in range(len(nums)-1): if (nums[i]==nums[i+1]): nums[i]=nums[i]*2 nums[i+1]=0 n=nums.count(0) for i in range(n): nums.remove(0) nums.append(0) return nums ```
5
0
['Python', 'Java', 'Python3']
0
apply-operations-to-an-array
JAVA
java-by-choudhry7-p71u
Code
choudhry7
NORMAL
2025-03-01T08:37:01.415894+00:00
2025-03-01T08:37:01.415894+00:00
87
false
# Code ```java [] class Solution { public int[] applyOperations(int[] nums) { int nz=0; int n = nums.length; for(int i=0;i<n;i++){ if(i < n-1 && nums[i]!=0 && nums[i]==nums[i+1]){ nums[i]*=2; nums[i+1]=0; } if(nums[i]!=0){ if(i!=nz){ int temp = nums[i]; nums[i] = nums[nz]; nums[nz] = temp; } nz++; } } return nums; } } ```
5
0
['Java']
0
apply-operations-to-an-array
Easy and Beginner Friendly Solution💯. Apply Operations to an Array (Optimized Solution 🚀)
easy-and-beginner-friendly-solution-appl-7ix8
IntuitionThe problem requires modifying the array based on adjacent values and then rearranging it efficiently.The key steps involve merging adjacent equal elem
VATSAL_30
NORMAL
2025-03-01T04:25:47.746913+00:00
2025-03-01T04:25:47.746913+00:00
180
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> The problem requires modifying the array based on adjacent values and then rearranging it efficiently. The key steps involve merging adjacent equal elements and shifting non-zero elements to the front while pushing zeros to the end. A simple two-pass approach (first pass for merging, second pass for shifting) is sufficient. # Approach <!-- Describe your approach to solving the problem. --> 1. First Pass (Modify the Array) Iterate through the array. If two adjacent elements are equal, double the first and set the second to zero. 2. Second Pass (Rearrange Elements) Traverse the array again to collect all non-zero elements into a new array. Append the required number of zeros at the end. # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> Merging step: O(n) Shifting non-zero elements: O(n) Total: O(n) - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> Using extra vector v: O(n) # Code ```cpp [] class Solution { public: vector<int> applyOperations(vector<int>& nums) { int n= nums.size(); vector<int> v; for (int i = 0; i < n - 1; i++) { if (nums[i] == nums[i + 1]) { nums[i] = nums[i]*2; nums[i+1]=0; } } for (int i = 0; i < n; i++) { if (nums[i]!=0) { v.push_back(nums[i]); } } for (int i = 0; i < n; i++) { if (nums[i]==0) { v.push_back(nums[i]); } } return v; } }; ``` If You Like Solution, Just Click On Upvote. ![image.png](https://assets.leetcode.com/users/images/5fee76f2-9539-48e4-a370-48e3be61786e_1740803067.193718.png)
5
0
['C++']
0
apply-operations-to-an-array
Beats 100% | Array | Two Pointers | Solution for LeetCode#2460
beats-100-array-two-pointers-solution-fo-fm2i
IntuitionThe problem requires applying a specific operation to an array and then moving all non-zero elements to the left while preserving their relative order.
samir023041
NORMAL
2025-03-01T01:30:46.135696+00:00
2025-03-01T01:30:46.135696+00:00
548
false
![image.png](https://assets.leetcode.com/users/images/dc5f20d6-7e29-45ce-9cf7-baa319fcc9fe_1740792433.414112.png) # Intuition <!-- Describe your first thoughts on how to solve this problem. --> The problem requires applying a specific operation to an array and then moving all non-zero elements to the left while preserving their relative order. The initial thought is to perform the operations in-place and then shift the non-zero elements. # Approach <!-- Describe your approach to solving the problem. --> 1. Iterate through the array from left to right (except the last element). 2. If two adjacent elements are equal, multiply the left one by 2 and set the right one to 0. 3. While iterating, move all non-zero elements to a new array, effectively shifting them to the left. 4. Handle the last element separately if it's non-zero. 5. Return the new array with non-zero elements shifted to the left and zeros at the end. # Complexity - Time complexity: O(n) <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: O(n) <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```java [] class Solution { public int[] applyOperations(int[] nums) { int n=nums.length; int[] arr=new int[n]; int i=0, j=0; // Apply operations and move non-zero elements for(i=0; i<n-1; i++){ if(nums[i]==nums[i+1]){ nums[i]=nums[i]*2; nums[i+1]=0; } if(nums[i]!=0){ arr[j++]=nums[i]; } } // Handle the last element if(nums[i]!=0){ arr[j++]=nums[i]; } return arr; } } ```
5
0
['Java']
0
apply-operations-to-an-array
Easy Solution Using Java with Explaination
easy-solution-using-java-with-explainati-2mrc
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \nThe approach is to use
hashcoderz
NORMAL
2022-11-06T04:15:38.728642+00:00
2022-11-08T04:58:26.567971+00:00
2,519
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nThe approach is to use an arraylist and then add the elements in it.\nif nums[i]==nums[i+1] then we multiply nums[i]*=2 & set nums[i+1]=0.\nThen we count the number of zeros in the array. And move it to the end of the array by using arraylists.\nThen we return the nums array which has been updated with new values.\n\n# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:$$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int[] applyOperations(int[] nums) {\n int n = nums.length;\n ArrayList<Integer> list = new ArrayList<>();\n for(int i=0; i<n; i++){\n if(i<n-1){\n if(nums[i]==nums[i+1]){\n nums[i]*=2;\n nums[i+1]=0;\n }\n }\n }\n int count=0;\n for(int i=0;i<n;i++){\n if(nums[i]==0){\n count++;\n }\n }\n for(int i=0; i<n;i++){\n if(nums[i]!=0){\n list.add(nums[i]);\n }\n }\n for(int i=0; i<count; i++){\n list.add(0);\n }\n for (int i = 0; i < list.size(); i++){\n nums[i] = list.get(i);\n }\n return nums;\n }\n}\n```\n### If you like the solution then please upvote me.\n\n\n## Thanks to @arun2020 he gave the solution in O(1) space.\n\n### His Approach is as follow\nThe approach is to first check if the adjacent elements are equal. If they are, then we multiply them and make the next element zero. After this, we shift all zeroes to right side of array using two pointers technique.\n\n# Code\n```\nclass Solution {\n public int[] applyOperations(int[] a) {\n int n = a.length;\n for (int i = 0; i < n - 1; i++) {\n if (a[i] == a[i + 1]) {\n a[i] = 2 * a[i];\n a[i + 1] = 0;\n }\n }\n int high=0;\n int low=0;\n while(high<n && low<n){\n if(a[high]!=0 && a[low]!=0){\n high++;\n low++;\n}\n else if(a[low]==0 && a[high]==0){\n high++;\n}\n else{\n int temp = a[low];\n a[low] = a[high];\n a[high] = temp;\n low++;\n high++;\n}\n}\nreturn a;\n}\n }\n\n```\n\n## Thanks @here-comes-the-g for beautiful approach\n### His Approach is as follows:\nFor each pair of numbers, if they are equal, double the first number and set the second to zero.\nMove all zeros to the end of the array by moving non-zero numbers one at a time from left to right until there are no more non-zeros on the left side of any zeros in between them.\n\n# Code\n```\nclass Solution {\n public int[] applyOperations(int[] nums) {\n int n = nums.length;\n for(int i=0; i<n-1; i++){\n if(nums[i]==nums[i+1]){\n nums[i]*=2;\n nums[i+1] = 0;\n }\n }\n for(int i=0, left =0; i<n;i++){\n if(nums[i]!=0){\n int temp = nums[i];\n nums[i] = 0;\n nums[left]=temp;\n left++;\n }\n }\n return nums;\n }\n}\n```\n\n\n
5
0
['Java']
3
apply-operations-to-an-array
✅ Java Easy Solution ✅
java-easy-solution-by-tangobee-l2fh
\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\n- Space complexity:
TangoBee
NORMAL
2022-11-06T04:04:39.408003+00:00
2022-11-06T04:04:39.408038+00:00
852
false
\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\n- Space complexity: O(N)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int[] applyOperations(int[] nums) {\n for(int i = 0; i < nums.length-1; i++) {\n if(nums[i] == nums[i+1]) {\n nums[i] = nums[i]*2;\n nums[i+1] = 0;\n }\n }\n \n int[] result = new int[nums.length];\n int k = 0;\n for(int i = 0; i < nums.length; i++) {\n if(nums[i] != 0)\n result[k++] = nums[i];\n }\n \n return result;\n }\n}\n```
5
0
['Java']
0
apply-operations-to-an-array
✅ 🔥 0ms Runtime Beats 100% || Efficient Array Transformation: Merging & Zero Shifting 🚀
0ms-runtime-beats-100-efficient-array-tr-7whe
🌟 Intuition:The task is to modify the array by merging adjacent equal elements and moving zeros to the end. The idea is to:Merge Adjacent Equal Elements: If two
4oICmhj3tm
NORMAL
2025-03-03T13:14:13.558726+00:00
2025-03-03T13:16:52.147867+00:00
43
false
![Capture3.PNG](https://assets.leetcode.com/users/images/9bbb639a-0c33-43f7-8968-41a20e8cf9cf_1741006894.2690184.png) # 🌟 Intuition: The task is to modify the array by merging adjacent equal elements and moving zeros to the end. ***The idea is to:*** **Merge Adjacent Equal Elements:** If two adjacent numbers are the same, combine them into one, doubling its value. **Move Zeros to the End:** All zeros should be shifted to the end, keeping the order of the non-zero elements. **Key Observations:** We can process each element just once to achieve the desired result. We’ll need to skip zeros while iterating and place the merged elements in the correct position. # 🧠 Approach: **Let’s break it down in simple steps:** **Traverse the Array:** Loop through the array. If two adjacent numbers are equal, merge them (double the value) and skip the next one. **Skip Zeros:** If a number is zero, we don’t need to do anything with it—just move to the next element. **Temporary Array:** Use a temporary array to store the modified values. **Return the Result:** After processing all elements, return the modified array. # ⏱ Complexity - **Time complexity:** *****O(n)*****, where n is the length of the array. We go through the array once, making it efficient. - **Space complexity:** ***O(n)***, because we use an additional array (temp) to store the results. # 🔍 Explanation of the Code - ***Array Traversal:*** Loop through nums, merging equal elements and copying non-zero elements to temp. - ***Skip Zeros:*** Zeros are ignored in the result. - ***Edge Case:*** The last element is processed differently since it doesn’t have a next element to compare to. # 🎯 Example Walkthrough **Example 1:** Input: nums = [1, 2, 2, 4, 0] - **Steps:** Compare nums[0] = 1 with nums[1] = 2: They’re not equal, so copy 1. Compare nums[1] = 2 with nums[2] = 2: They are equal, so double it to 4 and skip the next element. Compare nums[3] = 4 with nums[4] = 0: Copy 4 and skip zero. **Final Output: [1, 4, 4, 0, 0]** 🎉 # 🚀 Conclusion We keep things simple and use an extra array to store the result. The approach is perfect for large arrays, and it’s easy to implement. **Good luck with your LeetCode challenge! ✨** # Code ```java [] class Solution { public int[] applyOperations(int[] nums) { int[] temp =new int[nums.length]; int k=0; for(int i=0;i<nums.length;i++){ if(i==nums.length-1){ temp[k]=nums[i] ; break; } if(nums[i]!=0){ if(nums[i]==nums[i+1]){ temp[k]=nums[i]*2; i=i+1; } else { temp[k]=nums[i]; } k++;} } return temp; } } ```
4
0
['Array', 'Java']
1
apply-operations-to-an-array
🏆 THE MOST EASIEST TO UNDERSTAND SOLUTION | Beats 100 % 🎯 💯
the-most-easiest-to-understand-solution-v9w98
IntuitionThe problem requires modifying an array based on specific operations: doubling consecutive equal elements and shifting non-zero elements to the front.
Adiverse_7
NORMAL
2025-03-01T19:53:06.608374+00:00
2025-03-01T19:53:06.608374+00:00
18
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> The problem requires modifying an array based on specific operations: doubling consecutive equal elements and shifting non-zero elements to the front. Observing the requirements, a single pass can handle both operations efficiently. # Approach <!-- Describe your approach to solving the problem. --> 1. Traverse the array from left to right. 2. If two consecutive elements are equal, double the first and set the second to zero. 3. Maintain a pointer `non_zero_idx` to track the position where non-zero elements should be placed. 4. In the same pass, swap non-zero elements with `non_zero_idx` to shift them forward. # Complexity - Time complexity: - $$O(n)$$ since we traverse the array only once. - Space complexity: - $$O(1)$$ as the operations are done in-place. # Code ```cpp [] class Solution { public: vector<int> applyOperations(vector<int>& nums) { int n = nums.size(); int non_zero_idx = 0; for(int i = 0; i < n; i++) { if(i < n - 1 && nums[i] == nums[i + 1]) { nums[i] *= 2; nums[i + 1] = 0; } if(nums[i] != 0) { swap(nums[i], nums[non_zero_idx++]); } } return nums; } };
4
0
['C++']
2
apply-operations-to-an-array
👩‍💻Easy 🔥 Just read & code💻
easy-just-read-code-by-patilprajakta-85y8
Please Upvote only if you get something from my Solution! 💡🙌Don't give up! Keep practising! 😊🔥📚First just store array length in variable n.Then create new array
patilprajakta
NORMAL
2025-03-01T16:36:31.209665+00:00
2025-03-01T16:36:31.209665+00:00
94
false
# Please Upvote only if you get something from my Solution! 💡🙌 # Don't give up! Keep practising! 😊🔥📚 ------------------------------------------------------ First just store array length in variable n. int n=nums.length; Then create new array ans[] of size n. int ans[]=new int[n]; Then use for loop & just do as mntion in the question. if nums[i]==nums[i+1] then multiply nums[i] by 2 and nums[i+1]=0. for(int i=0;i<n-1;i++){ if(nums[i]==nums[i+1]){ nums[i]*=2; nums[i+1]=0; } } Now we just need to shift all zeros to end of the array. So,we use for each loop and check inside it. If x is not zero, then add it to our ans array. int i=0; for(int x:nums){ if(x!=0){ ans[i]=x; i++; } } Then finally, return the array. return ans; # Please Upvote only if you get something from my Solution! 💡🙌 # Don't give up! Keep practising! 😊🔥📚 # Code ```java [] class Solution { public int[] applyOperations(int[] nums) { int n=nums.length; int ans[]=new int[n]; for(int i=0;i<n-1;i++){ if(nums[i]==nums[i+1]){ nums[i]*=2; nums[i+1]=0; } } int i=0; for(int x:nums){ if(x!=0){ ans[i]=x; i++; } } return ans; } } ```
4
0
['Array', 'Java']
0
apply-operations-to-an-array
🔥Beats 100% |✨Easy Approach | Easy for Beginners | C++ | Java
beats-100-easy-approach-easy-for-beginne-mdrv
IntuitionWe need to modify the given array based on certain operations: - If two consecutive elements are equal, double the first element and set the second ele
panvishdowripilli
NORMAL
2025-03-01T14:28:56.925146+00:00
2025-03-01T14:28:56.925146+00:00
45
false
![Screenshot 2025-03-01 194756.png](https://assets.leetcode.com/users/images/bca1620b-8c92-49d5-9f55-b64bb9c5176d_1740839261.3764608.png) # Intuition We need to modify the given array based on certain operations: - If two consecutive elements are equal, double the first element and set the second element to 0. - Ahift all zero elements to the right of the array. **** # Approach - The loop iterates through the array for index `0` to `n - 1`. - It checks if two consecutive elements `nums[i]` and `nums[i + 1]` are equal or not. - If equal, it doubles `nums[i]` and sets `nums[i + 1]` to 0. - If not equal, it continues to next iteration. - We another loop to swap the elements with zeroes and move all the zeroes to right while maintaining order of non-zer0 elements. **** # Complexity - **Time complexity:** - **O(N)** -> To iterate over all elements in the given array. - **Space complexity:** - **O(1)** -> No extra space is used. **** # Code ```cpp [] class Solution { public: vector<int> applyOperations(vector<int>& nums) { int n = nums.size(), idx = 0; for(int i = 0; i < n - 1; i++){ if(nums[i] == nums[i + 1]){ nums[i] = nums[i] * 2; nums[i + 1] = 0; } } for(int i = 0; i < n; i++){ if(nums[i] != 0){ swap(nums[i], nums[idx]); idx++; } } return nums; } }; ``` ```java [] class Solution { public int[] applyOperations(int[] nums) { int n = nums.length, idx = 0; for(int i = 0; i < n - 1; i++){ if(nums[i] == nums[i + 1]){ nums[i] = nums[i] * 2; nums[i + 1] = 0; } } for(int i = 0; i < n; i++){ if(nums[i] != 0){ int temp = nums[i]; nums[i] = nums[idx]; nums[idx] = temp; idx++; } } return nums; } } ```
4
0
['Array', 'Simulation', 'C++', 'Java']
0
apply-operations-to-an-array
Optimal Solution ✅ for Applying Operations and Shifting Zeros in an Array
optimal-solution-for-applying-operations-vxrg
BEATS 100% 🚀Intuition 💡When two consecutive numbers are the same, we double the first and set the next to zero. Then, we simply move all non-zero numbers to the
lordprateekverma
NORMAL
2025-03-01T13:04:55.209985+00:00
2025-03-01T13:04:55.209985+00:00
9
false
### BEATS 100% 🚀 ![image.png](https://assets.leetcode.com/users/images/9ccceed2-4766-43be-89d4-ccbe4ec29c27_1740834134.8252292.png) # Intuition 💡 When two consecutive numbers are the same, we double the first and set the next to zero. Then, we simply move all non-zero numbers to the front and push zeros to the end. # Approach 🔍 1. Go through the array and double any number that equals the next one. 2. Move all non-zero numbers to the front of the array. 3. Fill the remaining places with zeros. # Complexity ⏱️ - **Time complexity:** $$O(n)$$ (we loop through the array twice). - **Space complexity:** $$O(1)$$ (in-place modification). # Code ```cpp [] class Solution { public: vector<int> applyOperations(vector<int>& nums) { for (int i = 0; i < nums.size() - 1; i++) { if (nums[i] == nums[i + 1]) { nums[i] = 2 * nums[i]; nums[i + 1] = 0; } } int pos = 0; for (int i = 0; i < nums.size(); i++) { if (nums[i] != 0) { nums[pos] = nums[i]; pos++; } } while (pos < nums.size()) { nums[pos] = 0; pos++; } return nums; } }; ```
4
0
['Two Pointers', 'C++']
0
apply-operations-to-an-array
JAVA CODE
java-code-by-ayeshakhan7-hsnl
Complexity Time complexity: O(n) Space complexity: O(1) Code
ayeshakhan7
NORMAL
2025-03-01T08:29:37.394429+00:00
2025-03-01T08:29:37.394429+00:00
72
false
# 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 ```java [] class Solution { public int[] applyOperations(int[] nums) { int n = nums.length; //Simulation int j = 0; for(int i = 0; i < n; i++) { if(i+1 < n && nums[i] == nums[i+1] && nums[i] != 0) { nums[i] *= 2; nums[i+1] = 0; } if(nums[i] != 0) { if(i != j) { int temp = nums[i]; nums[i] = nums[j]; nums[j] = temp; } j++; } } return nums; } } ```
4
0
['Java']
0
apply-operations-to-an-array
🌟 Beats 96.37% 🌟 | ✔️ Easiest Solution & Beginner Friendly ✔️ | 🔥 1MS & 2MS 🔥 | 2 Solutions
beats-9359-easiest-solution-beginner-fri-wdbu
🚀 Solution 1 : Brute Force (2MS)💡 IntuitionThe problem requires modifying an array based on adjacent equal elements and then shifting all zeros to the end. The
gauravpawar7
NORMAL
2025-03-01T04:18:30.501768+00:00
2025-03-01T04:19:33.200124+00:00
85
false
--- ![image.png](https://assets.leetcode.com/users/images/178f70a1-8065-4b5a-9a89-c7c2a28b4cdb_1740800826.0790913.png) --- ![cat.jpeg](https://assets.leetcode.com/users/images/65bf8eab-255c-4930-8364-d90ee6f70af7_1740802544.738743.jpeg) --- # 🚀 Solution 1 : Brute Force (2MS) --- # 💡 Intuition The problem requires modifying an `array` based on **adjacent equal elements** and then shifting all `zeros` to the `end`. The approach involves **two main steps**: first, iterating through the `array` and **merging adjacent equal elements** while replacing the next element with `zero`; second, **rearranging the array** by moving non-zero elements **forward** and shifting all `zeros` to the end. # 📜🔢 Approach `Step 1` **Merge Adjacent Elements** - Iterate through the `array` and whenever two adjacent elements are **equal**, double the **first** one and set the **second** one to `zero`. `Step 2` **Count Zeroes** - Traverse the `array` again to `count` the number of `zero` elements. `Step 3` **Extract Non-Zero Elements** - Store all **non-zero** elements in a separate `list`. `Step 4` **Rearrange the Array** - Overwrite the original `array` with the **non-zero** elements followed by the counted `zeroes`. `Step 5` **Return the Modified Array.** # ⏳📊 Complexity - Time complexity : $$O(n)$$ - Space complexity : $$O(n)$$ # 💻 Code ```Java [] class Solution { public int[] applyOperations(int[] nums) { // Step 1: Merge adjacent elements if they are equal for(int i = 0; i < nums.length - 1; i++) { if(nums[i] == nums[i + 1]) { nums[i] *= 2; nums[i + 1] = 0; } } // Step 2: Count zeroes int countZero = 0; for(int num : nums) { if(num == 0) { countZero++; } } // Step 3: Extract non-zero elements ArrayList<Integer> list = new ArrayList<>(); for(int num : nums) { if(num > 0) { list.add(num); } } // Step 4: Rearrange the array by moving non-zero elements first for(int i = 0; i < list.size(); i++) { nums[i] = list.get(i); } // Step 5: Append zeros at the end for(int i = list.size(); i < nums.length; i++) { nums[i] = 0; } // Step 6: Return the modified array return nums; } } ``` ``` C++ [] class Solution { public: vector<int> applyOperations(vector<int>& nums) { // Step 1: Merge adjacent elements if they are equal for(int i = 0; i < nums.size() - 1; i++) { if(nums[i] == nums[i + 1]) { nums[i] *= 2; nums[i + 1] = 0; } } // Step 2: Count zeroes and extract non-zero elements vector<int> result; int zeroCount = 0; for(int num : nums) { if(num == 0) { zeroCount++; } else { result.push_back(num); } } // Step 3: Rearrange array by placing non-zero elements first for(int i = 0; i < result.size(); i++) { nums[i] = result[i]; } // Step 4: Append zeroes at the end for(int i = result.size(); i < nums.size(); i++) { nums[i] = 0; } // Step 5: Return the modified array return nums; } }; ``` --- # 🚀 Solution 2 : Optimized (1MS) --- # 💡 Intuition The problem requires us to modify an `array` by merging **adjacent equal elements** and then shifting all **non-zero elements** forward while maintaining the **relative order**. Here, we use an extra `array` `result[]` to store the final values, ensuring all non-zero elements appear `first`, followed by `zeroes`. This simplifies the **shifting process** and avoids modifying the **input array** in place. # 📜🔢 Approach `Step 1` **Merge Adjacent Elements** - Iterate through the `array` and whenever **two adjacent elements** are `equal`, double the **first** one and set the **second** one to `zero`. `Step 2` **Create a Result Array** - Initialize a new array `result[]` of the same **size** as `nums[]`. `Step 3` **Copy Non-Zero Elements** - Traverse `nums[]`, copy all **non-zero** elements into `result[]` sequentially. `Step 4` **Return the result[] array** # ⏳📊 Complexity - Time complexity : $$O(n)$$ - Space complexity : $$O(n)$$ # 💻 Code ```Java [] class Solution { public int[] applyOperations(int[] nums) { // Step 1: Create a result array initialized with zeros int[] result = new int[nums.length]; // Step 2: Merge adjacent elements if they are equal for(int i = 0; i < nums.length - 1; i++) { if(nums[i] == nums[i + 1]) { nums[i] *= 2; nums[i + 1] = 0; } } // Step 3: Copy non-zero elements into result array int j = 0; for(int i = 0; i < nums.length; i++) { if(nums[i] != 0) { result[j] = nums[i]; j++; } } // Step 4: Return the modified array return result; } } ``` ``` C++ [] class Solution { public: vector<int> applyOperations(vector<int>& nums) { // Step 1: Create a result array initialized with zeros int n = nums.size(); vector<int> result(n, 0); // Step 2: Merge adjacent elements if they are equal for(int i = 0; i < n - 1; i++) { if(nums[i] == nums[i + 1]) { nums[i] *= 2; nums[i + 1] = 0; } } // Step 3: Copy non-zero elements into result array int j = 0; for(int i = 0; i < n; i++) { if(nums[i] != 0) { result[j] = nums[i]; j++; } } // Step 4: Return the modified array return result; } }; ```
4
0
['Array', 'Two Pointers', 'Greedy', 'Suffix Array', 'Sorting', 'Heap (Priority Queue)', 'Simulation', 'Combinatorics', 'C++', 'Java']
0
apply-operations-to-an-array
[ Python ] 🐍🐍 Simple Python Solution ✅✅ 89 ms
python-simple-python-solution-89-ms-by-s-61kh
\nclass Solution:\n def applyOperations(self, nums: List[int]) -> List[int]:\n for i in range(len(nums)-1):\n if nums[i]==nums[i+1]:\n
sourav638
NORMAL
2022-11-06T21:02:16.244754+00:00
2022-11-06T21:02:16.244784+00:00
1,139
false
```\nclass Solution:\n def applyOperations(self, nums: List[int]) -> List[int]:\n for i in range(len(nums)-1):\n if nums[i]==nums[i+1]:\n nums[i]*=2\n nums[i+1]=0 \n temp = []\n zeros = []\n a=nums\n for i in range(len(a)):\n if a[i] !=0:\n temp.append(a[i])\n else:\n zeros.append(a[i])\n return (temp+zeros)\n \n```
4
0
['Python', 'Python3']
1
apply-operations-to-an-array
🔥🔥 BINGO [ C++ ] Easy Clean Code :)
bingo-c-easy-clean-code-by-princesah999-jgt7
\nclass Solution\n{\n public:\n vector<int> applyOperations(vector<int> &nums)\n {\n int n = nums.size() - 1;\n for (int
Princesah999
NORMAL
2022-11-06T05:09:27.116843+00:00
2022-11-06T05:09:27.116906+00:00
150
false
```\nclass Solution\n{\n public:\n vector<int> applyOperations(vector<int> &nums)\n {\n int n = nums.size() - 1;\n for (int i = 0; i < n;)\n {\n if (nums[i] == nums[i + 1])\n {\n nums[i] = nums[i] *2;\n nums[i + 1] = 0;\n i = i + 1;\n }\n i++;\n }\n int i = 0;\n for (int j = 0; j < nums.size(); j++)\n {\n if (nums[j] != 0)\n {\n swap(nums[j], nums[i]);\n i++;\n }\n }\n return nums;\n }\n};\n\n// TC -> O(N)\n// SC -> O(1)\n\n```
4
0
['C', 'C++']
2
apply-operations-to-an-array
[C++] O(n) Easy Solution
c-on-easy-solution-by-ayush479-yisr
\nclass Solution {\npublic:\n vector<int> applyOperations(vector<int>& nums) {\n for(int i=0;i<nums.size()-1;i++){\n if(nums[i]==nums[i+1])
Ayush479
NORMAL
2022-11-06T04:23:37.292581+00:00
2022-11-06T04:23:37.292623+00:00
184
false
```\nclass Solution {\npublic:\n vector<int> applyOperations(vector<int>& nums) {\n for(int i=0;i<nums.size()-1;i++){\n if(nums[i]==nums[i+1]){\n nums[i]*=2;\n nums[i+1]=0;\n }\n }\n int place=0;\n for(int i=0;i<nums.size();i++){\n if(nums[i]!=0){\n nums[place++]=nums[i];\n }\n }\n for(int i=place;i<nums.size();i++){\n nums[i]=0;\n }\n return nums;\n }\n};\n\n// if you liked the solution then please upvote it so that it can reach to more people \n// If you have any doubt or want to discuss any thing related to solution please leave a comment, so that all of the viewers can discuss it\n```
4
0
['C']
0
apply-operations-to-an-array
✔️ 2ms C++ solution | Explained
2ms-c-solution-explained-by-coding_menan-nzyl
Here is the solution along with explanations in the comments:\n\nC++ []\nclass Solution {\npublic:\n vector<int> applyOperations(vector<int>& nums) {\n
coding_menance
NORMAL
2022-11-06T04:02:16.728219+00:00
2022-11-06T04:08:14.651017+00:00
208
false
Here is the solution along with explanations in the comments:\n\n``` C++ []\nclass Solution {\npublic:\n vector<int> applyOperations(vector<int>& nums) {\n for (int i{0}; i<nums.size()-1; ++i) {\n // checking if the number matches with the next one or not\n if (nums[i]==nums[i+1]) {\n // set the first number of the matching pair to twice it\'s value & other to 0\n nums[i]*=2;\n nums[i+1]=0;\n // i++ because the next element is already set to 0 and can\'t be same as it\'s next one\n // so we need to skip it\n i++;\n }\n }\n \n // this function moves 0 to last\n for (int i{1},j{0}; i<nums.size(); ++i) {\n // if element at j is -ve, then we check if element at index i is something\n // other than 0 or not. If it is then we swap otherwise,\n // we don\'t increment j and move i to the next index and try to swap\n if (!nums[j]) {\n if (nums[i]) swap(nums[i], nums[j++]);\n } else j++;\n }\n \n return nums; \n }\n};\n```\n\n*Upvote if the solution helped you!*
4
0
['C++']
1
apply-operations-to-an-array
✅C++ | ✅Brute-force approach
c-brute-force-approach-by-yash2arma-s7w4
\nclass Solution \n{\npublic:\n vector<int> applyOperations(vector<int>& nums) \n {\n int n=nums.size();\n for(int i=0; i<n-1; i++)\n
Yash2arma
NORMAL
2022-11-06T04:01:27.157283+00:00
2022-11-06T04:37:34.983170+00:00
1,531
false
```\nclass Solution \n{\npublic:\n vector<int> applyOperations(vector<int>& nums) \n {\n int n=nums.size();\n for(int i=0; i<n-1; i++)\n {\n if(nums[i]==nums[i+1])\n {\n nums[i] = 2*nums[i];\n nums[i+1] = 0;\n i++;\n }\n \n }\n \n vector<int> res(n, 0);\n int idx=0;\n for(int i=0; i<n; i++)\n {\n if(nums[i]!=0)\n {\n res[idx]=nums[i];\n idx++;\n }\n }\n return res;\n }\n};\n```
4
0
['C', 'C++']
1
apply-operations-to-an-array
Beats 100% with JAVA Beginners Friendly || YoU HaVe To ChEck ThiS OUt
beats-100-with-java-beginners-friendly-y-53o9
IntuitionThe main idea behind solving this problem is that if we follow the same process described in the problem's description, we need to first modify the arr
TAJUDDIN_USMAN_KHAN_2909
NORMAL
2025-03-01T23:51:37.712276+00:00
2025-03-02T01:34:43.304733+00:00
46
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> The main idea behind solving this problem is that if we follow the same process described in the problem's description, we need to first modify the array as instructed and then move all the `0`s to the last positions. This is the naive brute-force approach I initially thought of, but it takes a time complexity of O(2n) in the worst case. To optimize the time complexity, I decided to go with a more beginner-friendly approach by creating a new array called `result`. ![7b864aef-f8a2-4d0b-a376-37cdcc64e38c_1735298989.3319144.jpeg](https://assets.leetcode.com/users/images/81732cac-737b-4df2-8dcc-153902117ce0_1740879261.37014.jpeg) # Approach <!-- Describe your approach to solving the problem. --> After reviewing some solutions from the **LeetCode discussions**, I found that certain test cases were particularly useful in guiding me toward solving this problem. Here are the test cases that helped me understand the issue and improve my approach by 98%: - Test Case 1: `[0, 1, 0, 1]` - Test Case 2: `[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]` - Test Case 3: `[1, 3, 2, 3, 2, 2, 1, 2, 2, 1]` - Test Case 4: `[6, 4, 1, 18, 1, 4, 14, 9, 7, 17, 18, 14, 8, 12, 20, 16, 7, 5, 9, 3, 3, 17, 2, 12, 8, 9, 8, 12, 19, 14, 7, 19, 19, 8, 12, 20, 9, 7, 3, 0, 13, 2, 7, 16, 14, 19, 18, 7, 4, 8, 4, 14, 15, 9, 4, 12, 15, 12, 1, 10, 3, 3, 16, 17, 8, 4, 2, 19, 7, 19, 18, 20, 5, 20, 16, 12, 16, 10, 16, 15, 15, 4, 11, 4, 3, 3, 5, 13, 13, 15, 13, 11, 9, 9, 7, 20, 12, 0, 16, 1]` By analyzing these test cases, I refined my approach to solving the problem with greater accuracy and efficiency. Use the following images for best understanding : ![IMG_20250302_050824.jpg](https://assets.leetcode.com/users/images/c7753cdd-923a-412b-ae48-6e458aab3c01_1740872878.2119477.jpeg) # Complexity - Time complexity: O(N) <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity:O(N) <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```java [] class Solution { public int[] applyOperations(int[] nums) { int[] result = new int[nums.length]; int count = 0; int i; for(i = 0; i < nums.length - 1; i++){ if(nums[i] != 0){ if(nums[i] == nums[i + 1]){ result[count] = nums[i] * 2; i++; } else{ result[count] = nums[i]; } count++; } } if(i != nums.length){ result[count] = nums[nums.length - 1]; } return result; } } ```
3
0
['Java']
1
apply-operations-to-an-array
Easiest solution , Very simple to understand for beginners also
easiest-solution-very-simple-to-understa-ayc3
Intuition1.Initialization: l is an empty list to store intermediate results. ans is an empty list for the final answer. x is a counter for the number of zeros e
Vedagna_12
NORMAL
2025-03-01T14:47:51.063306+00:00
2025-03-01T14:47:51.063306+00:00
34
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> **1.Initialization:** - l is an empty list to store intermediate results. - *ans* is an empty list for the final answer. - x is a counter for the number of zeros encountered. **2.Doubling and Zeroing:** - The for loop goes through the list nums from the beginning to the second last element. - If nums[i] is equal to nums[i+1], it doubles the value of nums[i] and sets nums[i+1] to zero, then appends nums[i] to list l. - If nums[i] and nums[i+1] are not equal, nums[i] is directly appended to l. - The last element of nums is appended to l. **3.Handling Zeros:** - The next for loop iterates through the list l. - Non-zero elements are appended to *ans*, while zero elements increment the counter x. **4.Appending Zeros:** - Finally, a second for loop runs x times to append x zeros to *ans*. **5.Return:** - The function returns the list ***ans***. # Approach <!-- Describe your approach to solving the problem. --> - **Merge and Double:** Iterate through nums, double adjacent equal elements, set the second to zero, and store results in l. - **Filter Non-Zero:** Collect all non-zero elements from l into ans. - **Fill Zeros:** Append zeros to ans to match the original list's length and return ans. # Complexity - Time complexity: 0 ms <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: 18.24 mb <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```python3 [] class Solution: def applyOperations(self, nums: List[int]) -> List[int]: l=[] ans=[] x=0 for i in range(len(nums)-1): if nums[i] == nums[i+1]: nums[i] = 2*nums[i] nums[i+1]=0 l.append(nums[i]) else: l.append(nums[i]) l.append(nums[-1]) for i in l: if i!=0: ans.append(i) else: x+=1 for i in range(x): ans.append(0) return ans ```
3
0
['Python3']
0
apply-operations-to-an-array
Easiest way
easiest-way-by-xayrulloh-39dz
Approach If equal multiply by 2 (n * 2) If result is zero (0) store it and don't add to result Combine result and zeros (spread operator ...) Complexity Time c
Xayrulloh
NORMAL
2025-03-01T07:44:29.101731+00:00
2025-03-01T07:44:29.101731+00:00
140
false
# Approach 1. If equal multiply by 2 (n * 2) 2. If result is zero (0) store it and don't add to result 3. Combine result and zeros (spread operator ...) # Complexity - Time complexity: O(n) - Space complexity: O(n) (IMO) # Upwote if you want, I don't beg # Code ```typescript [] function applyOperations(nums: number[]): number[] { const res = [] const zeros = [] for (let i = 0; i < nums.length; i++) { if (nums[i] === nums[i + 1]) { [nums[i], nums[i + 1]] = [nums[i] * 2, 0] } if (nums[i] === 0) zeros.push(0) else res.push(nums[i]) } return [...res, ...zeros] }; ```
3
0
['TypeScript']
1
apply-operations-to-an-array
✅ Beginner Friendly | Easy to Understand | Two Pointers | Detailed Video Explanation 🔥
beginner-friendly-easy-to-understand-two-t5j2
IntuitionThe problem requires modifying an array in two steps: If two adjacent elements are equal, double the first one and set the second to zero. Shift all ze
sahilpcs
NORMAL
2025-03-01T07:17:00.788561+00:00
2025-03-01T07:17:00.788561+00:00
97
false
# Intuition The problem requires modifying an array in two steps: 1. If two adjacent elements are equal, double the first one and set the second to zero. 2. Shift all zeroes to the end while maintaining the relative order of non-zero elements. This hints at a **two-pass approach**—one for modifying the array and another for reordering the elements. # Approach 1. **Modify the array** - Iterate through the array and check if two adjacent elements are equal. - If they are, double the first element and set the second to zero. 2. **Shift non-zero elements to the left** - Use two pointers: - One pointer (`i`) keeps track of the position where the next non-zero element should go. - Another pointer (`j`) iterates through the array. - If `nums[j]` is nonzero, place it at `nums[i]` and increment `i`. 3. **Fill the remaining positions with zero** - After placing all non-zero elements, fill the rest of the array with zeroes. # Complexity - **Time complexity:** - The first loop runs in **O(n)** time. - The second loop (shifting elements) also runs in **O(n)** time. - The final loop (filling zeros) runs in **O(n)** time in the worst case. - **Overall complexity:** $$O(n)$$ - **Space complexity:** - We modify the array in place, using only a few extra variables. - **Overall complexity:** $$O(1)$$ # Code ```java [] class Solution { public int[] applyOperations(int[] nums) { int n = nums.length; // Step 1: Modify the array by doubling adjacent equal elements and setting the next one to zero for(int i = 0; i <= n - 2; i++){ if(nums[i] == nums[i+1]){ nums[i] *= 2; // Double the current element nums[i+1] = 0; // Set the next element to zero } } // Step 2: Shift all non-zero elements to the left while maintaining their relative order int i = 0, j = 0; for(; j < n; j++){ if(nums[j] > 0){ nums[i++] = nums[j]; // Move non-zero elements to the front } } // Step 3: Fill the remaining positions with zeroes while(i < n) nums[i++] = 0; return nums; } } ``` https://youtu.be/9_Bq597dykw
3
0
['Array', 'Two Pointers', 'Simulation', 'Java']
0
apply-operations-to-an-array
EASY C++ CODE WITH GOOD/DETAILED EXPLANATION
easy-c-code-with-gooddetailed-explanatio-lstg
IntuitionWhen I first saw this problem, I recognized it had two distinct parts: Apply the doubling operation on equal adjacent elements Move all resulting zeroe
YoGeSh_P2004
NORMAL
2025-03-01T05:11:06.307795+00:00
2025-03-01T05:11:06.307795+00:00
122
false
# Intuition When I first saw this problem, I recognized it had two distinct parts: 1. Apply the doubling operation on equal adjacent elements 1. Move all resulting zeroes to the end while preserving the order of other elements The natural approach is to handle these operations sequentially rather than trying to combine them. --- # Approach My solution uses a two-step approach: 1. First, I iterate through the array and apply the doubling operation: - When two adjacent elements are equal, I double the first and set the second to zero - This creates zeroes throughout the array wherever equal elements were found 2. Then, I use a separate function to move all zeroes to the end: - I maintain a pointer count that tracks where the next non-zero element should go - As I iterate through the array, whenever I find a non-zero element, I swap it to position count and increment count - This effectively collects all non-zero elements at the front while pushing zeroes to the end This approach is efficient because it only requires two passes through the array and modifies the array in-place without requiring extra space for a new array. --- # Complexity - Time complexity: O(N) - Space complexity: O(1) --- # Code ```cpp [] class Solution { public: // Helper function to move all zeroes to the end while preserving the order of non-zero elements void shiftZeroesToEnd(vector<int>& nums) { int count = 0; // Keep track of position where next non-zero element should go // Iterate through array for (int i = 0; i < nums.size(); i++) { // If current element is non-zero if (nums[i] != 0) { // Move it to the position tracked by count swap(nums[i], nums[count]); // Increment position for next non-zero element count++; } // If element is zero, we skip it (don't increment count) // This effectively pushes zeroes to the end } } vector<int> applyOperations(vector<int>& nums) { // Apply the operation: if two adjacent elements are equal, // double the first one and set the second one to zero for(int i = 0; i < nums.size() - 1; i++) { if(nums[i] == nums[i+1]) { nums[i] *= 2; // Double the current element nums[i+1] = 0; // Set next element to zero } } // Move all zeroes to the end while maintaining the order of non-zero elements shiftZeroesToEnd(nums); // Return the modified array return nums; } }; ```
3
0
['C++']
0
apply-operations-to-an-array
BruteForce Java Solution ✅✅✅
bruteforce-java-solution-by-bharanidhara-xbt7
IntuitionApproachComplexity Time complexity: Space complexity: Code
BHARANIdharankumaresan
NORMAL
2025-03-01T04:06:13.493589+00:00
2025-03-01T04:06:13.493589+00:00
35
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 ```java [] class Solution { public int[] applyOperations(int[] nums) { for (int i=0;i<nums.length;i++) { if(i<nums.length -1 && nums[i]==nums[i+1]) { nums[i]=nums[i]*2; nums[i+1]=0; } } int index = 0; for(int i = 0;i<nums.length;i++) { if(nums[i]!=0){ nums[index++]=nums[i]; } } while(index<nums.length){ nums[index++]=0; } return nums; } } ```
3
0
['Java']
0
apply-operations-to-an-array
100% Beat Simple Solution
100-beat-simple-solution-by-viratkohli-vh9n
Complexity Time complexity: O(N) Space complexity: O(N) Code
viratkohli_
NORMAL
2025-03-01T03:57:36.308161+00:00
2025-03-01T03:57:36.308161+00:00
95
false
![image.png](https://assets.leetcode.com/users/images/33649b56-77d7-4b52-a752-f06e00ffd589_1740801448.0410573.png) # Complexity - Time complexity: O(N) <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: O(N) <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```cpp [] class Solution { public: vector<int> applyOperations(vector<int>& nums) { int n = nums.size(); for(int i = 0; i<n-1; i++){ if(nums[i] == nums[i+1]){ nums[i] *= 2; nums[i+1] = 0; } } vector<int> ans; for(int i = 0; i<n; i++){ if(nums[i] > 0){ ans.push_back(nums[i]); } } while(ans.size() < n){ ans.push_back(0); } return ans; } }; ```
3
0
['Array', 'Two Pointers', 'Simulation', 'C++']
0
apply-operations-to-an-array
"Applying Operations and Rearranging an Array of Non-Negative Integers"
applying-operations-and-rearranging-an-a-q66o
IntuitionThe problem requires us to sequentially apply operations on an array where we double the value of an element if it is equal to its neighbor and set the
ofc_tarunn
NORMAL
2025-03-01T02:39:05.931990+00:00
2025-03-01T02:39:05.931990+00:00
30
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> The problem requires us to sequentially apply operations on an array where we double the value of an element if it is equal to its neighbor and set the neighbor to zero. After processing all elements, we also need to shift all zeros to the end of the array. The key idea is to iterate through the array, apply the operations where applicable, and then handle the zeros at the end. # Approach <!-- Describe your approach to solving the problem. --> 1. **Iterate through the array**: Use a loop to go through each element of the array, comparing each element with the next one. 2. **Apply operations**: If two adjacent elements are equal, double the first one and set the second to zero. If they are not equal, just move the current element to a new position in the result. 3. **Shift zeros**: After processing the array, fill the rest of the array with zeros to move them to the end. 4. **Return the modified array**. # Complexity - **Time complexity**: <!-- Add your time complexity here, e.g. $$O(n)$$ --> The time complexity is O(n),where n is the length of the input array. This is because we go through the array a constant number of times. - **Space complexity**: <!-- Add your space complexity here, e.g. $$O(n)$$ --> The space complexity is O(1) since we are modifying the array in place and not using any additional data structures that scale with input size. # Code ```java [] class Solution { public int[] applyOperations(int[] nums) { int n = nums.length; int idx = 0,i=0; while(i<n-1){ if(nums[i]!=0){ if(nums[i]==nums[i+1]){ nums[idx++]=nums[i]*2; i++; } else nums[idx++]=nums[i]; } i++; } if(i<=n-1 && nums[n-1]!=0)nums[idx++]=nums[n-1]; while(idx<n){ nums[idx++]=0; } return nums; } } ```
3
0
['Java']
0
apply-operations-to-an-array
Two pointers. 0 ms JS/TS. Beats 100.00%
two-pointers-0-ms-jsts-beats-10000-by-no-mi7p
ApproachTwo pointers.Complexity Time complexity: O(n) Space complexity: O(1) Code
nodeforce
NORMAL
2025-03-01T00:46:03.079638+00:00
2025-03-01T00:54:14.282732+00:00
143
false
# Approach Two pointers. ![1.png](https://assets.leetcode.com/users/images/82f26fe0-6213-43f6-b79a-502e3e8671a6_1740789759.9259782.png) # 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 ```javascript [] const applyOperations = (a) => { const n = a.length; let j = 0; for (let i = 0; i < n; ++i) { if (i < n - 1 && a[i] === a[i + 1]) { a[i] *= 2; a[i + 1] = 0; } if (a[i] !== 0) a[j++] = a[i]; } a.fill(0, j); return a; }; ```
3
0
['Array', 'Two Pointers', 'Simulation', 'TypeScript', 'JavaScript']
0
apply-operations-to-an-array
Java Solution💪✨ | | Beats 100% 🚀🚀 | | Solution By Kanishka 🧠 🧠
java-solution-beats-100-solution-by-kani-xe5f
IntuitionThe problem requires us to apply two operations: If two adjacent elements are equal, double the first element and set the second element to zero. Shift
kanishka21535
NORMAL
2025-02-13T05:27:14.784801+00:00
2025-02-13T05:27:14.784801+00:00
123
false
# Intuition The problem requires us to apply two operations: 1. If two adjacent elements are equal, double the first element and set the second element to zero. 2. Shift all non-zero elements to the left while maintaining their order, and fill the remaining positions with zeros. To efficiently solve this, we process the array in two passes: - **First Pass:** Apply the transformation for adjacent equal elements. - **Second Pass:** Move all non-zero elements to the front and fill the remaining indices with zero. # Approach 1. **First Loop:** Iterate over the array and check adjacent elements. - If `arr[i] == arr[i+1]`, double `arr[i]` and set `arr[i+1] = 0`. 2. **Second Loop:** Move non-zero elements to the front (`nz` index). 3. **Third Loop:** Fill the rest of the array with zeros. # Complexity - **Time Complexity:** $$O(n)$$ - The first loop runs in $$O(n)$$, and the shifting of elements runs in $$O(n)$$. - **Space Complexity:** $$O(1)$$ - We modify the input array in place without using extra space. # Code ```java class Solution { public int[] applyOperations(int[] arr) { int nz = 0; int n = arr.length; // Step 1: Apply operations to double adjacent equal elements for (int i = 0; i < n - 1; i++) { if (arr[i] == arr[i + 1]) { arr[i] = arr[i]* 2; arr[i + 1] = 0; } } // Step 2: Move non-zero elements forward for (int i = 0; i < n; i++) { if (arr[i] != 0) { arr[nz] = arr[i]; nz++; } } // Step 3: Fill remaining positions with zero for (int i = nz; i < n; i++) { arr[i] = 0; } return arr; } }
3
0
['Java']
0
apply-operations-to-an-array
Easiest beginner friendly solution
easiest-beginner-friendly-solution-by-a_-ae0x
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
A_drishti1
NORMAL
2024-05-07T10:32:45.195985+00:00
2024-05-07T10:32:45.196018+00:00
149
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n vector<int> applyOperations(vector<int>& nums) {\n \n for(int i=0;i<nums.size()-1;i++)\n {\n if(nums[i]==nums[i+1])\n {\n nums[i]=nums[i]*2;\n nums[i+1]=0;\n }\n \n }\n int cnt=0;\n for(auto i:nums)\n {\n if(i!=0)\n {\n nums[cnt++]=i;\n }\n }\n while(cnt<nums.size())\n {\n nums[cnt++]=0;\n }\n return nums;\n }\n};\n```
3
0
['C++']
0
apply-operations-to-an-array
👏Beats 93.57% of users with Java || 1ms Easy & Simple Explained Solution 🔥💥
beats-9357-of-users-with-java-1ms-easy-s-2o4g
Intuition\nCheck over the array if ith index and i+1th index are same then ith index element multiply by 2 and make i+1th inddex as a 0.\n\n# I Think This Can H
Rutvik_Jasani
NORMAL
2024-03-12T07:58:45.701399+00:00
2024-03-12T07:58:45.701418+00:00
130
false
# Intuition\nCheck over the array if ith index and i+1th index are same then ith index element multiply by 2 and make i+1th inddex as a 0.\n\n# I Think This Can Help You\n![Screenshot 2024-02-24 232407.png](https://assets.leetcode.com/users/images/db05d5a6-844a-457f-9726-0adb5319b6d3_1710230123.5292735.png)\n\n\n# Approach\n1. Iterate over the nums and check if ith index element and i+1th index element both are same then ith index elemen multiply by 2 & i+1th index element is equal to 0.\n2. Create ans array variable to store answer array(We use extra array for reduce time complexity).\n3. Make cnt variable for maintain ans array index.\n4. Itearate over the loop and add element of cnt in the ans it is not equal to 0.\n5. return ans array.\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(n) --> for extra array ans\n\n# Code\n```\nclass Solution {\n public int[] applyOperations(int[] nums) {\n for(int i=0;i<nums.length-1;i++){ // Iterate over the nums and check if ith index element and i+1th index element both are same then ith index elemen multiply by 2 & i+1th index element is equal to 0.\n if(nums[i]==nums[i+1]){\n nums[i] = nums[i] * 2;\n nums[i+1] = 0;\n }\n }\n int[] ans = new int[nums.length]; // Create ans array variable to store answer array(We use extra array for reduce time complexity).\n int cnt=0; // Make cnt variable for maintain ans array index.\n for(int i=0;i<nums.length;i++){ // Itearate over the loop and add element of cnt in the ans it is not equal to 0.\n if(nums[i]!=0){\n ans[cnt] = nums[i];\n cnt++;\n }\n }\n return ans; // return ans array.\n }\n}\n```\n\n![_5aa88f78-fb67-453e-9e02-bc042a0631cd.jpeg](https://assets.leetcode.com/users/images/9d684b2b-0116-42e3-aa3e-cf91560707ba_1710230191.6701322.jpeg)\n
3
0
['Array', 'Simulation', 'Java']
0
apply-operations-to-an-array
Python Solution (Beats 99.50%) || 41ms|| O(N) || Easy Solution
python-solution-beats-9950-41ms-on-easy-1favr
Complexity\n- Time complexity:\n O(N)\n# Code\n\nclass Solution:\n def applyOperations(self, nums: List[int]) -> List[int]:\n zeros=0\n i=0\
varshith2134
NORMAL
2023-03-14T06:18:04.673775+00:00
2023-03-14T06:18:04.673819+00:00
857
false
# Complexity\n- Time complexity:\n O(N)\n# Code\n```\nclass Solution:\n def applyOperations(self, nums: List[int]) -> List[int]:\n zeros=0\n i=0\n while(i<(len(nums)-1)):\n if(nums[i]==nums[i+1]):\n nums[i]*=2\n nums[i+1]=0\n i+=1\n i+=1\n # print(nums)\n zeros=nums.count(0)\n nums = [i for i in nums if i != 0]\n return nums+([0]*zeros)\n```
3
0
['Python3']
1
apply-operations-to-an-array
2 Approaches- choose yourself🤔🤔|| cpp solution
2-approaches-choose-yourself-cpp-solutio-f1v4
Intuition\n Describe your first thoughts on how to solve this problem. \nHere we have to do, if nums[i] == nums[i + 1], then multiply nums[i] by 2 and set nums[
Bhaskar_Agrawal
NORMAL
2023-03-13T14:54:33.066347+00:00
2023-03-13T14:54:33.066392+00:00
932
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nHere we have to do, if nums[i] == nums[i + 1], then multiply nums[i] by 2 and set nums[i + 1] to 0. Otherwise, you skip this operation. and then move zeroes to end. If you havent solved **move zeroes**(leetcode- 283) problem, u can solve that also after solving this question. \n\n# Approach No. 1(beats 39%) \n# SPACE OPTIMIZED \n<!-- Describe your approach to solving the problem. -->\n1. Iterate through the array and do the following,\n- If nums[i] == nums[i + 1], then multiply nums[i] by 2 and set nums[i + 1] to 0.\n- Otherwise, you skip this operation.\n2. Iterate again throughout the array and shift all zeroes to end and non- zero in ascending order.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->O(2N) equivalent to 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 vector<int> applyOperations(vector<int>& nums) {\n for(int i = 0; i < nums.size()-1; i++){\n if(nums[i] == nums[i+1])\n {\n nums[i] *= 2;\n nums[i+1] = 0;\n i++; \n }\n }\n int temp = 0;\n for(int i = 0; i < nums.size(); i++){\n if((i == temp) && nums[i] != 0){\n temp++;\n continue;\n }\n if(nums[i] != 0){\n nums[temp] = nums[i];\n temp++;\n nums[i] = 0;\n }\n }\n return nums;\n }\n};\n```\n# Approach No. 2(beats 90%)\n# TIME OPTIMIZED\n1. Iterate through the array and do the following,\n- If nums[i] == nums[i + 1], then multiply nums[i] by 2 and set nums[i + 1] to 0. \n- check if nums[i] == 0 or not,\n- nums[i] == 0, store in v1, else v2.\n- for the last index, do it seperately.\n2. erase nums, and set nums to v2. and then insert v1.\n\n# COMPLEXITY \n- **TIME** - O(N)\n- **SPACE**- O(2N) equivalent to O(N)\n\n# CODE\n```\nclass Solution {\npublic:\n vector<int> applyOperations(vector<int>& nums) {\n vector<int> v1; // zero vector\n vector<int> v2; // non-zero vector\n for(int i = 0; i < nums.size()-1; i++){\n if(nums[i] == nums[i+1])\n {\n nums[i] *= 2;\n nums[i+1] = 0;\n }\n if(nums[i]==0)\n v1.push_back(nums[i]);\n else\n v2.push_back(nums[i]);\n }\n // for last element \n if(nums[nums.size()-1]==0)\n v1.push_back(nums[nums.size()-1]);\n else\n v2.push_back(nums[nums.size()-1]);\n nums.erase(nums.begin(), nums.end());\n // sort(v2.begin(), v2.end());\n nums = v2;\n for(auto i : v1)\n nums.push_back(i);\n return nums;\n }\n};\n```
3
0
['Array', 'Simulation', 'C++']
0
apply-operations-to-an-array
EASY SOLUTION IN C++
easy-solution-in-c-by-chhayagupta900-6u5i
```\nclass Solution {\npublic:\n vector applyOperations(vector& nums) {\n \n int j =0;\n for(int i =0;i<nums.size()-1;i++)\n {\n
chhayagupta900
NORMAL
2022-11-28T18:05:40.235808+00:00
2022-11-28T18:05:40.235850+00:00
269
false
```\nclass Solution {\npublic:\n vector<int> applyOperations(vector<int>& nums) {\n \n int j =0;\n for(int i =0;i<nums.size()-1;i++)\n {\n if (nums[i]==nums[i+1])\n {\n nums[i]=(nums[i]*2);\n nums[i+1]=0;\n }\n else \n {\n nums[i];\n }\n }\n for(int i =0;i<nums.size();i++)\n {\n \n if( i==j && nums[i]!=0)\n {\n j++;\n continue;\n }\n if (nums[i]!=0)\n {\n nums[j]=nums[i];\n nums[i]=0;\n j++;\n }\n \n }\n \n return nums;\n }\n};
3
0
[]
0
apply-operations-to-an-array
Python || Easy || 98.81% Faster || O(N) Solution
python-easy-9881-faster-on-solution-by-p-dwsg
\nclass Solution:\n def applyOperations(self, nums: List[int]) -> List[int]:\n for i in range(1,len(nums)):\n if nums[i-1]==nums[i]:\n
pulkit_uppal
NORMAL
2022-11-08T20:11:36.876965+00:00
2022-11-08T20:11:36.877004+00:00
299
false
```\nclass Solution:\n def applyOperations(self, nums: List[int]) -> List[int]:\n for i in range(1,len(nums)):\n if nums[i-1]==nums[i]:\n nums[i-1]*=2\n nums[i]=0\n c,a=0,[]\n for i in nums:\n if i==0:\n c+=1\n continue\n a.append(i)\n return a+[0]*c\n```\n\n**Please upvote if you like the solution**
3
0
['Python']
0
apply-operations-to-an-array
Easy JS solution explained | O(n) time and O(1) space
easy-js-solution-explained-on-time-and-o-vunc
Easy JS solution explained | O(n) time and O(1) space\nTC: O(n) and SC: O(1)\n\nvar applyOperations = function(nums) {\n// perform the operation on each array e
loid_forger
NORMAL
2022-11-07T07:43:54.533669+00:00
2022-11-07T07:43:54.533718+00:00
332
false
# Easy JS solution explained | O(n) time and O(1) space\n**TC: O(n) and SC: O(1)**\n```\nvar applyOperations = function(nums) {\n// perform the operation on each array element\n for(let i = 0; i < nums.length - 1; i++){\n if(nums[i] === nums[i + 1]){\n nums[i] *= 2;\n nums[i + 1] = 0;\n }\n }\n// Move zeroes to end\n let index = 0;\n nums.forEach(num => {\n if(num !== 0)\n nums[index++] = num;\n });\n while(index < nums.length){\n nums[index++] = 0;\n }\n return nums;\n};\n```\n\n**If the interviewer asks you not to alter the input**\n```\nvar applyOperations = function(nums) {\n// perform the operation on each array element\n for(let i = 0; i < nums.length - 1; i++){\n if(nums[i] === nums[i + 1]){\n nums[i] *= 2;\n nums[i + 1] = 0;\n }\n }\n const res = Array(nums.length).fill(0);\n let index = 0;\n\t// Copy the non-zero elements to result array\n nums.forEach(num => {\n if(num !== 0)\n res[index++] = num;\n });\n return res;\n};\n```
3
0
['JavaScript']
0
apply-operations-to-an-array
Python two pointers without using extra space
python-two-pointers-without-using-extra-wcx70
\nclass Solution:\n def applyOperations(self, nums: List[int]) -> List[int]:\n \n for i in range(len(nums) - 1):\n if nums[i] == num
theReal007
NORMAL
2022-11-06T12:10:58.906325+00:00
2022-11-13T11:43:09.013947+00:00
241
false
```\nclass Solution:\n def applyOperations(self, nums: List[int]) -> List[int]:\n \n for i in range(len(nums) - 1):\n if nums[i] == nums[i+1]:\n nums[i] = nums[i] * 2\n nums[i+1] = 0\n \n l = 0\n \n for r in range(len(nums)):\n if nums[l] ==0 and nums[r] !=0:\n nums[l], nums[r] = nums[r], nums[l]\n l += 1\n elif nums[l] !=0:\n l += 1\n \n return nums\n```
3
0
['Two Pointers', 'Python']
0
apply-operations-to-an-array
JAVA | Constant space | Easy ✅
java-constant-space-easy-by-sourin_bruh-4pgn
Please Upvote :D\n\nclass Solution {\n public int[] applyOperations(int[] nums) {\n int n = nums.length;\n \n for (int i = 0; i < n - 1;
sourin_bruh
NORMAL
2022-11-06T09:03:58.751123+00:00
2022-11-06T17:25:55.708021+00:00
660
false
### **Please Upvote** :D\n```\nclass Solution {\n public int[] applyOperations(int[] nums) {\n int n = nums.length;\n \n for (int i = 0; i < n - 1; i++) {\n if (nums[i] == nums[i + 1]) {\n nums[i] *= 2;\n nums[i + 1] = 0;\n }\n }\n \n int i = 0, j = 0;\n \n while (j < n) {\n if (nums[j] != 0) {\n nums[i++] = nums[j];\n }\n j++;\n }\n \n while (i < n) {\n nums[i++] = 0;\n }\n \n return nums;\n }\n}\n\n// TC: O(n), SC: O(1)\n```
3
0
['Java']
0
apply-operations-to-an-array
cpp best solution
cpp-best-solution-by-rajan087-2ld6
Intuition\nCpp best solution\n\n# Approach\nvector\n\n# Complexity\n- Time complexity:\n(o)n\n\n- Space complexity:\n(o)n\n\n# Code\n\nclass Solution {\npublic:
rajan087
NORMAL
2022-11-06T06:46:56.598572+00:00
2022-11-06T06:46:56.598610+00:00
14
false
# Intuition\nCpp best solution\n\n# Approach\nvector\n\n# Complexity\n- Time complexity:\n(o)n\n\n- Space complexity:\n(o)n\n\n# Code\n```\nclass Solution {\npublic:\n vector<int> applyOperations(vector<int>& nums) {\n \n int res=0;\n \n for(int i=0;i<nums.size()-1;i++)\n {\n if(nums[i]==nums[i+1])\n {\n nums[i+1]=0;\n nums[i]*=2;\n }\n if(nums[i]==0)\n res++;\n }\n \n if(nums[nums.size()-1]==0)\n res++;\n // leet code\n \n vector<int> flag;\n for(auto i:nums)\n if(i>0)\n flag.push_back(i);\n \n for(int i=0;i<res;i++)\n flag.push_back(0);\n \n \n \n return flag;\n}\n};\n```
3
0
['C++']
1
apply-operations-to-an-array
Java Easy Solution | 100% faster | O(1) space
java-easy-solution-100-faster-o1-space-b-xfzd
\nclass Solution {\n public int[] applyOperations(int[] nums) {\n for (int i = 0; i < nums.length - 1; i++){\n if (nums[i] == nums[i + 1]){
srujan_14
NORMAL
2022-11-06T04:03:30.377993+00:00
2022-11-06T04:26:57.710688+00:00
762
false
```\nclass Solution {\n public int[] applyOperations(int[] nums) {\n for (int i = 0; i < nums.length - 1; i++){\n if (nums[i] == nums[i + 1]){\n nums[i] *= 2;\n nums[i + 1] = 0;\n }\n }\n \n move(nums);\n return nums;\n }\n \n //move zeroes to end\n public void move(int arr[]) {\n\t\tint count=0;\n\t\tfor(int i=0;i<arr.length;i++) {\n\t\t\tif(arr[i]!=0)\n\t\t\t{\n\t\t\t\tint temp=arr[count];\n\t\t\t\tarr[count] = arr[i];\n\t\t\t\tarr[i]= temp;\n\t\t\t\tcount++;\n\t\t\t}\n\t\t}\n\t}\n}\n```
3
1
['Java']
0
apply-operations-to-an-array
Python3, solved in place
python3-solved-in-place-by-silvia42-fem1
Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(1)\n\n# Code\n\nclass Solution:\n def applyOperations(self, nums: List[int]) -> List[int]:\n
silvia42
NORMAL
2022-11-06T04:03:08.798000+00:00
2022-11-06T04:03:08.798033+00:00
645
false
# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(1)\n\n# Code\n```\nclass Solution:\n def applyOperations(self, nums: List[int]) -> List[int]:\n zeros=0\n nums+=[0]\n for i in range(len(nums)-1):\n if nums[i]==0:\n zeros+=1\n elif nums[i]==nums[i+1]:\n nums[i-zeros]=nums[i]*2\n nums[i+1]=0\n else:\n nums[i-zeros]=nums[i]\n \n return nums[:len(nums)-1-zeros] + [0]*zeros \n```
3
0
['Python3']
0
apply-operations-to-an-array
Using swap function to move zeros at the end #simple java code#efficient swapping
using-swap-function-to-move-zeros-at-the-nxcc
IntuitionApproachComplexity Time complexity: Space complexity: Code
harinimuruges04
NORMAL
2025-03-27T08:09:55.569468+00:00
2025-03-27T08:09:55.569468+00:00
26
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 ```java [] class Solution { public int[] applyOperations(int[] nums) { int n=nums.length; for(int i=0;i<n-1;i++){ if(nums[i]==nums[i+1]){ nums[i]*=2; nums[i+1]=0; } } int j=0; int temp; for(int i=0;i<n;i++){ if(nums[i]!=0){ temp=nums[i]; nums[i]=nums[j]; nums[j]=temp; j++; } } return nums; } } ```
2
0
['Java']
1
apply-operations-to-an-array
Simple TS Solution
simple-ts-solution-by-nurzhansultanov-4xny
Code
NurzhanSultanov
NORMAL
2025-03-03T05:11:37.967792+00:00
2025-03-03T05:11:37.967792+00:00
9
false
# Code ```typescript [] function applyOperations(nums: number[]): number[] { let result: number[] = []; let numberOfZero = 0; for (let i = 0; i < nums.length - 1; i++) { if (nums[i] === nums[i + 1]) { nums[i] = nums[i] * 2; nums[i + 1] = 0; if(nums[i] > 0){ result.push(nums[i]); } } else { if(nums[i] > 0){ result.push(nums[i]); } } } if(nums[nums.length - 1] > 0){ result.push(nums[nums.length - 1]); } numberOfZero = nums.length - result.length; for(let j = 0; j < numberOfZero; j++){ result.push(0) } return result; } ```
2
0
['TypeScript']
0
apply-operations-to-an-array
TWO POINTER APPROACH || O(N) Time Complexity || O(1) Space Complexity || BASIC ARRAY
two-pointer-approach-on-time-complexity-qooq3
IntuitionApproachFirstly Declare two variable i and j where i starts from 0 and j from i+1 . Then checking the conditions if nums[i]==nums[j] then just multipl
prakharpatel
NORMAL
2025-03-01T21:23:49.956511+00:00
2025-03-01T21:23:49.956511+00:00
5
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. -->TWO POINTER APPROACH || Basic Array Solution || Using Move Zeroes to End (Another Leetcode Question* # Approach <!-- Describe your approach to solving the problem. --> Firstly Declare two variable i and j where i starts from 0 and j from i+1 . Then checking the conditions if nums[i]==nums[j] then just multiply the nums[i] by 2 and set the nums[j] = 0 if the condition is not true then increment the i and j. Using Move Zeroes to End Algo 1. Check for the first index where first zero is found. 2. Insert the position of First zero'th index into a variable. 3. Start from the index+1 position and then check that value is not zero. 4. If it is then swap the zero and the value which is not zero and increment the index of j. # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> The Time complexity for this approach is O(n) because we are using a for loop. - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> Space complexity will be O(1) as we are not using any extra space in order to store the array. UPVOTE IT IF YOU LIKEEEEEE the solution. # Code ```cpp [] class Solution { public: vector<int> applyOperations(vector<int>& nums) { int i = 0; int j = i+1; while(i<nums.size() and j<nums.size()){ if(nums[i]!=nums[j]){ i++; j++; } else{ nums[i] = nums[i] * 2; nums[j] = 0; i++; j++; } } int indexj = -1; for(int i=0;i<nums.size();i++){ if(nums[i]==0){ indexj = i; break; } } if(indexj==-1){ return nums; } else{ for(int i=indexj+1;i<nums.size();i++){ if(nums[i]!=0){ swap(nums[i],nums[indexj]); indexj++; } } } return nums; } }; ```
2
0
['Array', 'Two Pointers', 'Simulation', 'C++']
0
apply-operations-to-an-array
2460. Apply Operations to an Array in Python3
2460-apply-operations-to-an-array-in-pyt-wp7v
Code
Shivmishra75
NORMAL
2025-03-01T19:33:54.500946+00:00
2025-03-01T19:33:54.500946+00:00
24
false
# Code ```python3 [] class Solution: def applyOperations(self, nums: List[int]) -> List[int]: n = len(nums) j = 0 # index of first zero for i in range(n): if i + 1 < n and nums[i] == nums[i + 1]: # check if should apply operation nums[i] *= 2 nums[i + 1] = 0 if nums[i] != 0: nums[i], nums[j] = nums[j], nums[i] # swap zero and non-zero j += 1 # j + 1 for next zero index return nums ```
2
0
['Python3']
1
apply-operations-to-an-array
Java ✅🤯 - Best Solution
java-best-solution-by-aimlc_22b1531167-fwho
IntuitionApproach Iterate through the array, doubling adjacent equal numbers and setting the next one to zero. Move all non-zero elements to the front while mai
aimlc_22b1531167
NORMAL
2025-03-01T19:10:20.891756+00:00
2025-03-01T19:10:20.891756+00:00
8
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> Modify the array by doubling adjacent equal elements and setting the next element to zero, then shift non-zero elements forward. # Approach <!-- Describe your approach to solving the problem. --> 1. Iterate through the array, doubling adjacent equal numbers and setting the next one to zero. 2. Move all non-zero elements to the front while maintaining order. # 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 ```java [] class Solution { public int[] applyOperations(int[] nums) { for(int i=0; i<nums.length-1; i++){ if(nums[i]==nums[i+1]){ nums[i] *= 2; nums[i+1]=0; } } moveZeroes(nums); return nums; } public void moveZeroes(int[] nums) { int index=0; for(int num:nums){ if(num!=0){ nums[index++]=num; } } while(index<nums.length){ nums[index++]=0; } } } ```
2
0
['Java']
0
apply-operations-to-an-array
"LeetCode 2460 | Apply Operations to an Array | Easy & Optimized Java Solution"
leetcode-2460-apply-operations-to-an-arr-z7jm
IntuitionThe problem requires us to perform two operations sequentially:Merge adjacent equal elements by doubling the first and setting the second to 0. Shift a
kshitij_srivastava16
NORMAL
2025-03-01T15:43:31.114845+00:00
2025-03-01T15:43:31.114845+00:00
24
false
# Intuition The problem requires us to perform two operations sequentially: Merge adjacent equal elements by doubling the first and setting the second to 0. Shift all 0s to the end while maintaining the order of non-zero elements. Since both operations are sequential, we can achieve the result efficiently by processing the array in a single pass without extra space. # Approach We iterate through the array using a single loop, applying the operations in two steps: Merging adjacent equal elements If nums[i] == nums[i + 1], we double nums[i] and set nums[i + 1] to 0. Shifting non-zero elements We maintain a pointer j to track the position of the next non-zero element. Whenever we encounter a non-zero value, we swap it to the front. This approach effectively merges and shifts in one traversal, optimizing performance. # Complexity - Time complexity:O(n) We traverse the array once, performing both merging and shifting in-place. - Space complexity:O(1) We use only a few extra variables and modify the input array directly. # Code ```java [] class Solution { public int[] applyOperations(int[] nums) { for (int i = 0, j = 0; i < nums.length; ++i) { if (i + 1 < nums.length && nums[i] == nums[i + 1]) { nums[i] *= 2; nums[i + 1] = 0; } if (nums[i] > 0) { swap(nums, i, j++); } } return nums; } private void swap(int[] nums, int i, int j) { final int temp = nums[i]; nums[i] = nums[j]; nums[j] = temp; } } ```
2
0
['Java']
0
apply-operations-to-an-array
Python Solution
python-solution-by-iloabachie-tzcu
Code
iloabachie
NORMAL
2025-03-01T15:36:10.756658+00:00
2025-03-01T15:48:33.742653+00:00
37
false
# Code ```python [] class Solution: def applyOperations(self, nums: List[int]) -> List[int]: for i in range(len(nums) - 1): if nums[i] and nums[i] == nums[i + 1]: nums[i] *= 2 nums[i + 1] = 0 return sorted(nums, key=lambda x: not x) ```
2
0
['Python3']
0
apply-operations-to-an-array
Simple solution for beginners
simple-solution-for-beginners-by-ai_prin-v6pc
IntuitionThe problem involves modifying an array based on specific rules: If two adjacent numbers are the same, double the first one and set the second to zero.
ai_prince
NORMAL
2025-03-01T14:58:46.907259+00:00
2025-03-01T14:58:46.907259+00:00
47
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> The problem involves modifying an array based on specific rules: 1. If two adjacent numbers are the same, double the first one and set the second to zero. 2. After processing the array, shift all zeros to the end while maintaining the order of non-zero elements. The key idea is to process the list in one pass, apply transformations, and then separate non-zero elements while shifting zeros to the end. # Approach <!-- Describe your approach to solving the problem. --> 1. Iterate Through the Array - Traverse nums from index 0 to n-2. - If nums[i] == nums[i+1], double nums[i] and set nums[i+1] to zero. - Store the non-zero numbers in a new list r. 2. Handle the Last Element - If nums[n-1] is not zero, append it to r. 3. Shift Zeros to the End - Compute the number of missing elements (n - len(r)) and append that many zeros. 4. Return the Modified List - Concatenate r (non-zero elements) with zeros to maintain O(n) complexity. # 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 ```python3 [] class Solution: def applyOperations(self, nums: List[int]) -> List[int]: r=[] n=len(nums) for i in range(n-1): if nums[i]==0: continue if nums[i]==nums[i+1]: nums[i]*=2 nums[i+1]=0 r.append(nums[i]) else: r.append(nums[i]) if nums[n-1]!=0: r.append(nums[n-1]) zl=[0]*(n-len(r)) print(r) nums=r+zl return nums ```
2
0
['Python3']
0
apply-operations-to-an-array
100% BEAT 🚀 || WITH APPROACH 😁 || BIGNNER FRIENDLY 😊 || EASY SOLN 🎯|| 2 LOOP SOLN ||💯🚀🎯🔥🔥
100-beat-with-approach-bignner-friendly-iwelp
Approach1 ) Initialize the result array: Create a new array result of the same length as the input array nums. This will store the final result with all non-z
Dhruv-AFK4545
NORMAL
2025-03-01T13:34:38.349344+00:00
2025-03-01T13:34:38.349344+00:00
31
false
# Approach <!-- Describe your approach to solving the problem. --> 1 ) Initialize the result array: - > Create a new array result of the same length as the input array nums. This will store the final result with all non-zero values moved to the front and zeroes moved to the end. 2 ) First Pass: Apply the merge operation: - > Iterate through the array nums (except the last element). - > For each adjacent pair nums[i] and nums[i + 1], if they are equal, merge them: - > Double the value of nums[i] (i.e., nums[i] = 2 * nums[i]). - > Set nums[i + 1] = 0 (since it has been merged into nums[i]). 3 ) Second Pass : Place non-zero elements into the result array: - > Iterate through the array nums and copy all non-zero elements into the result array starting from the first position. 4 ) Fill the remaining positions with zeroes: - > After placing all non-zero elements, fill the remaining positions in the result array with zeros. 5) Return the result: - > The final result array now contains all merged elements at the front, followed by the zeros at the end. # Complexity - Time complexity : O(n) <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity : O(n) <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```cpp [] class Solution { public: vector<int> applyOperations(vector<int>& nums) { int n = nums.size(); vector<int> result(n, 0); // Create a result vector initialized to zero. int index = 0; // This will keep track of where to place non-zero elements in the result. // First pass: Apply the operation and merge adjacent elements. for (int i = 0; i < n - 1; ++i) { if (nums[i] == nums[i + 1]) { nums[i] = 2 * nums[i]; // Double the value of nums[i] nums[i + 1] = 0; // Set nums[i + 1] to zero } } // Place non-zero elements in the result vector. for (int i = 0; i < n; ++i) { if (nums[i] != 0) { result[index++] = nums[i]; // Add non-zero elements to the result. } } // Fill the remaining spaces with zeroes. for (int i = index; i < n; ++i) { result[i] = 0; } return result; // Return the final result array } }; ``` PLEASE UPVOTE 🤗🤗🤗🤗🤗🤗🤗🤗🤗🤗🤗🤗🤗🤗🤗🤗🤗🤗🤗🤗🤗🤗
2
0
['C++']
1
apply-operations-to-an-array
Easy C++ Solution || Beats 100%
easy-c-solution-beats-100-by-manish_code-gigo
IntuitionApproachComplexity Time complexity: Space complexity: Code
manish_code_fun
NORMAL
2025-03-01T13:23:35.212524+00:00
2025-03-01T13:23:35.212524+00:00
43
false
![{C9F1CB38-1318-42DA-ADE7-FEC762775858}.png](https://assets.leetcode.com/users/images/03d40d96-29b6-4ce6-8f2b-03dc1eecbf89_1740835406.684324.png) # Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```cpp [] class Solution { public: vector<int> applyOperations(vector<int>& nums) { for(int i=0;i<nums.size()-1;i++){ if(nums[i]==nums[i+1]){ nums[i]*=2; nums[i+1]=0; } } int curr=0; for(int i=0;i<nums.size();i++){ if(nums[i]!=0){ swap(nums[i],nums[curr]); curr++; } } return nums; } }; ```
2
0
['C++']
0
apply-operations-to-an-array
Simple CPP solution beats 100%
simple-cpp-solution-beats-100-by-abhinav-c2uk
Code
Abhinav_Bisht
NORMAL
2025-03-01T11:59:51.498914+00:00
2025-03-01T12:11:22.577391+00:00
16
false
# Code ```cpp [] class Solution { public: vector<int> applyOperations(vector<int>& nums) { int n = nums.size(); vector<int> ans(n,0); int idx=0; for(int i=0;i<n;i++){ if(i<n-1 && nums[i] == nums[i+1] && nums[i]!=0){ ans[idx++]=nums[i]*2; i++; } else if(nums[i]!=0){ ans[idx++]=nums[i]; } } return ans; } }; ```
2
0
['C++']
0
apply-operations-to-an-array
O(1) Space || Single Pass || BEATS 100% || Single Loop
o1-space-single-pass-beats-100-single-lo-a6t8
Fastest Code with Single LoopComplexity Time complexity: O(N) Space complexity: O(1) Code
Gagan_70
NORMAL
2025-03-01T11:56:04.724267+00:00
2025-03-01T11:56:04.724267+00:00
5
false
**Fastest Code with Single Loop** # Complexity - Time complexity: O(N) - Space complexity: O(1) # Code ```cpp [] class Solution { public: vector<int> applyOperations(vector<int>& nums) { int j =0; int i = 0; int n = nums.size(); for(i;i<n-1;i++){ if(nums[i]==nums[i+1]){ nums[i]*=2; nums[i+1]=0; } if(nums[j]==0 && nums[i]!=0) swap(nums[j++],nums[i]); else if(nums[j]!=0) j++; } if(nums[n-1]!=0) swap(nums[n-1],nums[j]); return nums; } }; ```
2
0
['Array', 'Two Pointers', 'C++']
1
apply-operations-to-an-array
✅ 🎯 📌 Simple Solution || Pointers || Fastest Solution ✅ 🎯 📌
simple-solution-pointers-fastest-solutio-i6j8
Code
vvnpais
NORMAL
2025-03-01T09:14:38.732867+00:00
2025-03-01T09:14:38.732867+00:00
22
false
# Code ```python3 [] class Solution: def applyOperations(self, nums: List[int]) -> List[int]: for i in range(len(nums)-1): if nums[i]==nums[i+1]: nums[i],nums[i+1]=nums[i]*2,0 z=0 for i in range(len(nums)): if nums[i]==0: z+=1 else: nums[i-z]=nums[i] for i in range(z): nums[len(nums)-1-i]=0 return nums ```
2
0
['Array', 'Two Pointers', 'Simulation', 'Python3']
0
apply-operations-to-an-array
simple py solution - beats 100%
simple-py-solution-beats-100-by-noam971-jal2
IntuitionApproachComplexity Time complexity: Space complexity: Code
noam971
NORMAL
2025-03-01T08:59:31.675019+00:00
2025-03-01T08:59:31.675019+00:00
58
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 applyOperations(self, nums: List[int]) -> List[int]: zeros = 0 res = [] for i in range(len(nums) - 1): if nums[i] == nums[i + 1]: nums[i] *= 2 nums[i + 1] = 0 for n in nums: if n == 0: zeros += 1 else: res.append(n) return res + ([0] * (zeros)) ```
2
0
['Python3']
0
apply-operations-to-an-array
Efficient And Easy Solution 😉😉💯💯Beats
efficient-and-easy-solution-beats-by-kum-y0fg
IntuitionThe problem requires modifying an array by doubling adjacent equal elements and setting the second one to zero, followed by shifting all zeroes to the
Kumar_s29
NORMAL
2025-03-01T08:30:27.285093+00:00
2025-03-01T08:30:27.285093+00:00
14
false
--- ## **Intuition** The problem requires modifying an array by doubling adjacent equal elements and setting the second one to zero, followed by shifting all zeroes to the end while maintaining the order of non-zero elements. The approach is similar to the **2048 game mechanics**. --- ## **Approach** 1. **Merging Adjacent Equal Elements:** - Iterate through the array from left to right. - If two adjacent elements are equal, double the first element and set the second one to zero. 2. **Shifting Zeroes to the End:** - Create a new list to store non-zero elements while iterating through the array. - Append zeroes at the end to maintain the original array size. This approach ensures that the array is processed efficiently in two passes. --- ## **Complexity Analysis** - **Time Complexity:** - First pass (merging): \(O(n)\) - Second pass (shifting zeroes): \(O(n)\) - Overall: **\(O(n)\)** - **Space Complexity:** - Using an extra `vector<int> result` of size \(n\): **\(O(n)\)** - If modifying in place, space can be reduced to **\(O(1)\)**. --- ## **Code** ```cpp class Solution { public: vector<int> applyOperations(vector<int>& nums) { int n = nums.size(); for (int i = 0; i < n - 1; i++) { if (nums[i] == nums[i + 1]) { nums[i] *= 2; nums[i + 1] = 0; } } vector<int> result; for (int num : nums) { if (num != 0) result.push_back(num); } while (result.size() < n) { result.push_back(0); } return result; } }; ``` This solution is **efficient** and follows a **clear logical structure**. 🚀
2
0
['C++']
0
apply-operations-to-an-array
I Scored 100%—In the Weirdest Way Possible!
i-scored-100-in-the-weirdest-way-possibl-1d6t
IntuitionI thought to keep a counter of number of zeros possible in the resultant array and only pushed the non zero possible elements first and then pushed the
Shoaib09
NORMAL
2025-03-01T08:04:55.363357+00:00
2025-03-01T08:04:55.363357+00:00
7
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> I thought to keep a counter of number of zeros possible in the resultant array and only pushed the non zero possible elements first and then pushed the remaining 0's which are supposed to be at the end of the resultant 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 ```cpp [] class Solution { public: vector<int> applyOperations(vector<int>& nums) { int size=nums.size(); vector<int>ans; int count=0; for(int i=0;i<size;i++){ if(nums[i]==0)count++; else if(i+1<size && nums[i]==nums[i+1]){ ans.push_back(nums[i]*2); i++; count++; } else{ ans.push_back(nums[i]); } } while(count){ ans.push_back(0); count--; } return ans; } }; ```
2
0
['C++']
0
apply-operations-to-an-array
✅✅ Beats 100% || O(n) || Easy Solution
beats-100-on-easy-solution-by-karan_agga-1wqs
IntuitionThe problem requires modifying an array based on certain rules: If two adjacent elements are equal, double the first and set the second to zero. Move a
Karan_Aggarwal
NORMAL
2025-03-01T07:46:21.826475+00:00
2025-03-01T07:46:21.826475+00:00
6
false
## Intuition The problem requires modifying an array based on certain rules: 1. If two adjacent elements are equal, double the first and set the second to zero. 2. Move all nonzero elements to the left while maintaining relative order. ## Approach - Iterate through the array once. If two adjacent elements are equal (and nonzero), double the first and set the second to zero. - Use a two-pointer technique to shift nonzero elements to the left efficiently. - The `j` pointer keeps track of where the next nonzero element should be placed. - If `nums[i]` is nonzero, swap it with `nums[j]` (if needed) and increment `j`. ## Complexity Analysis - **Time Complexity**: \(O(n)\), as we traverse the array twice in a single pass. - **Space Complexity**: \(O(1)\), since we modify the array in place without extra storage. ## Code ```cpp [] class Solution { public: vector<int> applyOperations(vector<int>& nums) { int n = nums.size(); int j = 0; for (int i = 0; i < n; i++) { if (i + 1 < n && nums[i] == nums[i + 1] && nums[i] != 0) { nums[i] *= 2; nums[i + 1] = 0; } if (nums[i] != 0) { if (i != j) swap(nums[i], nums[j]); j++; } } return nums; } }; ``` # Have a Good Day 😊 UpVote?
2
0
['Array', 'Two Pointers', 'Simulation', 'C++']
0
apply-operations-to-an-array
✅💥BEATS 100%✅💥 || 🔥EASY CODE🔥 || ✅💥EASY EXPLAINATION✅💥 || JAVA || C++ || PYTHON
beats-100-easy-code-easy-explaination-ja-5xku
IntuitionThe problem asks us to apply some operations on an array of integers. The goal is to iterate through the array and, whenever two adjacent elements are
chaitanyameshram_07
NORMAL
2025-03-01T06:54:59.400354+00:00
2025-03-01T06:54:59.400354+00:00
42
false
# Intuition The problem asks us to apply some operations on an array of integers. The goal is to iterate through the array and, whenever two adjacent elements are the same, combine them by multiplying the first element by 2 and setting the second one to 0. After that, we need to shift the non-zero elements to the left side of the array and set all remaining elements to 0. The solution should be done in-place without using extra space for a second array. # Approach We can break the solution into two main steps: 1. **Merge adjacent equal elements**: We iterate through the array, and whenever we find two adjacent elements that are the same, we double the first element and set the second element to 0. 2. **Shift the non-zero elements to the left**: Once we’ve handled the merging step, we need to shift all non-zero elements to the left side of the array and fill the remaining positions with 0s. - The first loop ensures that adjacent elements that are the same are combined. - The second loop is responsible for shifting all non-zero values to the left side of the array. - The third loop fills the remaining positions with zeros. # Complexity - **Time complexity**: $$O(n)$$ We are iterating through the array a constant number of times (twice in total), so the overall time complexity is linear. - **Space complexity**: $$O(1)$$ The solution modifies the array in place without using any extra space. # Code ``` Java [] class Solution { public int[] applyOperations(int[] nums) { // Step 1: Merge adjacent equal elements for(int i = 0; i < nums.length - 1; i++) { if(nums[i] == nums[i + 1]) { nums[i] = nums[i] * 2; // Combine the elements nums[i + 1] = 0; // Set the second element to 0 } } // Step 2: Shift non-zero elements to the left int j = 0; for(int i = 0; i < nums.length; i++) { if(nums[i] != 0) { nums[j] = nums[i]; // Move non-zero elements to the left j++; } } // Step 3: Fill the remaining positions with zeros while(j < nums.length) { nums[j] = 0; j++; } return nums; } } ``` ``` C++ [] class Solution { public: vector<int> applyOperations(vector<int>& nums) { // Step 1: Merge adjacent equal elements for (int i = 0; i < nums.size() - 1; i++) { if (nums[i] == nums[i + 1]) { nums[i] = nums[i] * 2; // Combine the elements nums[i + 1] = 0; // Set the second element to 0 } } // Step 2: Shift non-zero elements to the left int j = 0; for (int i = 0; i < nums.size(); i++) { if (nums[i] != 0) { nums[j] = nums[i]; // Move non-zero elements to the left j++; } } // Step 3: Fill the remaining positions with zeros while (j < nums.size()) { nums[j] = 0; j++; } return nums; } }; ``` ``` Python [] class Solution: def applyOperations(self, nums): # Step 1: Merge adjacent equal elements for i in range(len(nums) - 1): if nums[i] == nums[i + 1]: nums[i] = nums[i] * 2 # Combine the elements nums[i + 1] = 0 # Set the second element to 0 # Step 2: Shift non-zero elements to the left j = 0 for i in range(len(nums)): if nums[i] != 0: nums[j] = nums[i] # Move non-zero elements to the left j += 1 # Step 3: Fill the remaining positions with zeros while j < len(nums): nums[j] = 0 j += 1 return nums ```
2
0
['Array', 'Math', 'Two Pointers', 'Simulation', 'Python', 'C++', 'Java']
0
apply-operations-to-an-array
🔄 Apply Operations and Move Zeros | Java | C++ | python | Javascript | O(n)
apply-operations-and-move-zeros-java-c-p-368e
🔍 Problem BreakdownWe need to modify the array in-place by following two rules: 1️⃣ Merge adjacent equal numbers: If nums[i] == nums[i+1], then double nums[i] a
koushiRai
NORMAL
2025-03-01T06:02:28.185352+00:00
2025-03-01T06:02:28.185352+00:00
89
false
# 🔍 Problem Breakdown We need to modify the array in-place by following two rules: 1️⃣ Merge adjacent equal numbers: If nums[i] == nums[i+1], then double nums[i] and set nums[i+1] = 0. 2️⃣ Move all zeros to the end: Maintain the relative order of non-zero elements. # 💡 Intuition We can solve this problem in two simple passes: First pass ➝ Apply the merging operation on adjacent elements. Second pass ➝ Shift non-zero elements forward, then fill remaining positions with 0. # 📝 Approach 1: Merging Adjacent Equal Numbers Iterate through nums, and when we find nums[i] == nums[i+1], we double nums[i] and set nums[i+1] = 0. 2: Move All Zeros to the End Traverse the array again, shift all non-zero numbers forward, and replace the rest with 0 # Complexity ⏳ Time Complexity: O(n) 🛠 Space Complexity: O(1) (in-place modification) # Code ```java [] class Solution { public int[] applyOperations(int[] nums) { for (int i = 0; i < nums.length - 1; i++) { if (nums[i] == nums[i + 1]) { nums[i] *= 2; nums[i + 1] = 0; } } // Movinh all zeros to the end while maintaining order int index = 0; for (int i = 0; i < nums.length; i++) { if (nums[i] != 0) { nums[index++] = nums[i]; } } // Filling remaining elements with zero while (index < nums.length) { nums[index++] = 0; } return nums; } } ``` ```C++ [] class Solution { public: vector<int> applyOperations(vector<int>& nums) { for (int i = 0; i < nums.size() - 1; i++) { if (nums[i] == nums[i + 1]) { nums[i] *= 2; nums[i + 1] = 0; } } int index = 0; for (int i = 0; i < nums.size(); i++) { if (nums[i] != 0) { swap(nums[index++], nums[i]); } } return nums; } }; ``` ```Javascript [] var applyOperations = function(nums) { for (let i = 0; i < nums.length - 1; i++) { if (nums[i] === nums[i + 1]) { nums[i] *= 2; nums[i + 1] = 0; } } let index = 0; for (let i = 0; i < nums.length; i++) { if (nums[i] !== 0) { [nums[index], nums[i]] = [nums[i], nums[index]]; index++; } } return nums; }; ``` ```Python [] class Solution: def applyOperations(self, nums): for i in range(len(nums) - 1): if nums[i] == nums[i + 1]: nums[i] *= 2 nums[i + 1] = 0 index = 0 for i in range(len(nums)): if nums[i] != 0: nums[index], nums[i] = nums[i], nums[index] index += 1 return nums solution = Solution() print(solution.applyOperations([2, 2, 0, 4, 4, 8])) ```
2
0
['Python', 'C++', 'Java', 'JavaScript']
0
apply-operations-to-an-array
One Pass Go Easy Solution !!!
one-pass-go-easy-solution-by-dipak__pati-jhjb
One Pass Solution !!!Complexity Time complexity: O(n) Space complexity: O(1) Code
dipak__patil
NORMAL
2025-03-01T05:08:58.348842+00:00
2025-03-01T05:08:58.348842+00:00
43
false
# One Pass Solution !!! # Complexity - Time complexity: O(n) - Space complexity: O(1) # Code ```golang [] func applyOperations(nums []int) []int { insertPos := 0 for i := 0; i < len(nums); i++ { if i+1 < len(nums) && nums[i] == nums[i+1] { nums[i] *= 2 nums[i+1] = 0 } if nums[i] != 0 { nums[insertPos], nums[i] = nums[i], nums[insertPos] insertPos++ } } return nums } ```
2
0
['Array', 'Go']
0
apply-operations-to-an-array
Apply Operations to an Array || Beats 100% || Easy Solution in C++
apply-operations-to-an-array-beats-100-e-w9di
IntuitionThe question clearly states the requirement: if(nums[i] == nums[i+1]) then doulbe nums[i] and set nums[i+1] as 0. at the end, we need to move all 0s to
rajputsatvik12
NORMAL
2025-03-01T05:07:01.242633+00:00
2025-03-01T05:07:01.242633+00:00
9
false
# Intuition The question clearly states the requirement: if(nums[i] == nums[i+1]) then doulbe nums[i] and set nums[i+1] as 0. at the end, we need to move all 0s to the end of the array. # Approach <!-- Describe your approach to solving the problem. --> Step 1: check for consecutive equal elements and apply the operation. Step 2: count the total number of 0s and delete all 0 entries. Step 3: push 0s to the end of the array. # 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: vector<int> applyOperations(vector<int>& nums) { int size = nums.size(); for(int i=0;i<size-1;i++){ if(nums[i] == nums[i+1]){ nums[i] *= 2; nums[i+1] = 0; } } int count = 0; for(int i=0;i<nums.size();i++){ if(nums[i] == 0){ count++; nums.erase(nums.begin()+i--); } } for(int i=0;i<count;i++){ nums.push_back(0); } return nums; } }; ``` > Consider upvoting if the solution helps!
2
0
['C++']
0
apply-operations-to-an-array
Easy code in Java | Must try | Beats 100%
easy-code-in-java-must-try-beats-100-by-9qy1v
IntuitionApproachComplexity Time complexity: Space complexity: Code
NotAditya09
NORMAL
2025-03-01T04:57:47.173366+00:00
2025-03-01T04:57:47.173366+00:00
58
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 ```java [] class Solution { public int[] applyOperations(int[] nums) { int[] ans = new int[nums.length]; for (int i = 0; i + 1 < nums.length; ++i) if (nums[i] == nums[i + 1]) { nums[i] *= 2; nums[i + 1] = 0; } int i = 0; for (final int num : nums) if (num > 0) ans[i++] = num; return ans; } } ```
2
0
['Java']
0
apply-operations-to-an-array
Easiest Solution with Intitution (Beats 100% solutions)
easiest-solution-with-intitution-beats-1-m8nh
Intuition Traverse through array and apply operations as given in the question. Count number of zeros present in array & shift digits in front. Iterate from end
sakshidabral_
NORMAL
2025-03-01T04:34:31.188940+00:00
2025-03-01T04:34:31.188940+00:00
24
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> 1. Traverse through array and apply operations as given in the question. 2. Count number of zeros present in array & shift digits in front. 3. Iterate from end to fix the positioning of zeros. <!-- 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: vector<int> applyOperations(vector<int>& nums) { int n = nums.size(); // Applying operations for(int i=0;i<n-1;i++){ if(nums[i] != nums[i+1]) continue; nums[i] *= 2; nums[i+1] = 0; } int count = 0, ptr = 0; //taking a pointer to keep a record for number index for(int i=0;i<n;i++){ if(nums[i] == 0) count++; else { // If it is a number, put it at ptr index nums[ptr] = nums[i]; ptr++; } } // Fixing zeros for(int i=0;i<count;i++){ nums[n-i-1] = 0; } return nums; } }; ``` UPVOTE if it helps!
2
0
['Array', 'C++']
0
apply-operations-to-an-array
Simple solution | Runtime 0 ms | Beats 100.00%
simple-solution-runtime-0-ms-beats-10000-2rbn
IntuitionPerform the operation as given, ensuring merged values are stored while skipping zeros. After processing, append the remaining zeros to maintain array
arpita_sat
NORMAL
2025-03-01T04:07:46.776357+00:00
2025-03-01T04:07:46.776357+00:00
26
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> Perform the operation as given, ensuring merged values are stored while skipping zeros. After processing, append the remaining zeros to maintain array size. # Approach <!-- Describe your approach to solving the problem. --> 1. **Initialization**: Initialize `i` with 0. Use a `while` loop to traverse the array from left to right. 2. **Skip Zeros**: If `nums[i-1] == 0`, simply move to the next element without adding it to `ans`. 3. **Merge Adjacent Equal Elements**: If `nums[i] == nums[i-1]`, double `nums[i-1]`, set `nums[i]` to `0`, and store the doubled value in the result vector `ans`. 4. **Store Non-Zero Elements**: If the numbers are not equal, push `nums[i-1]` into `ans`. 5. **Add the Last Element**: Ensure the last element of `nums` is included in `ans`. 6. **Fill Remaining Spaces with Zeroes**: If `ans` is smaller than `nums`, append zeros to match the original size. # Complexity - Time complexity: O(n) <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: O(n) <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```cpp [] class Solution { public: vector<int> applyOperations(vector<int>& nums) { vector<int> ans; int i=1; while( i<nums.size()) { if(nums[i-1] == 0){ // skip it i++; } else if(nums[i] == nums[i-1]) { nums[i-1] *= 2; nums[i] = 0; ans.push_back(nums[i-1]); i+=2; } else { ans.push_back(nums[i-1]); i++; } } ans.push_back(nums[nums.size()-1]); // insert the last element // fill rest of the array with zeroes for(i=ans.size(); i<nums.size(); i++) { ans.push_back(0); } return ans; } }; ```
2
0
['C++']
0
apply-operations-to-an-array
JavaScript Solution || Using Array Iteration || Beats 100% Users ||
javascript-solution-using-array-iteratio-mg4v
IntuitionApproachComplexity Time complexity: Space complexity: Code
Heisenberg_wc
NORMAL
2025-03-01T03:42:29.821680+00:00
2025-03-01T03:42:29.821680+00:00
34
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 * @return {number[]} */ var applyOperations = function(nums) { const arr=[] var l=nums.length for(let i=0;i<l-1;i++){ if(nums[i]==nums[i+1]){nums[i]*=2;nums[i+1]=0;i++;} } var counter=0; nums.forEach((ele,index)=>{ if(ele===0) {counter++;} else{ arr.push(ele) } }) while(counter){ arr.push(0) counter--; } return arr }; ```
2
0
['JavaScript']
0
apply-operations-to-an-array
🔥😎6 Lines C++✅✅
6-lines-c-by-sapilol-56j3
C++
LeadingTheAbyss
NORMAL
2025-03-01T03:41:37.264692+00:00
2025-03-01T03:41:37.264692+00:00
11
false
# C++ ```cpp class Solution { public: vector<int> applyOperations(vector<int>& nums) { for (int i = 0; i < nums.size() - 1; i++) if (nums[i] == nums[i + 1]) nums[i] *= 2,nums[i + 1] = 0; for (int i = 0; i < nums.size(); i++) { if (count(nums.begin() + i, nums.end(), 0) == nums.size() - i) break; if (nums[i] == 0) nums.erase(nums.begin() + i), nums.push_back(0), i--; } return nums; } }; ```
2
0
['C++']
0
apply-operations-to-an-array
CPP || 100% beats || easy to understand
cpp-100-beats-easy-to-understand-by-apoo-ntou
Complexity Time complexity: O(N) Space complexity: O(N) Code
apoorvjain7222
NORMAL
2025-03-01T03:33:58.800765+00:00
2025-03-01T03:33:58.800765+00:00
20
false
# Complexity - Time complexity: O(N) <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: O(N) <!-- Add your space complexity here, e.g. $$O(n)$$ --> ![upvote.jpg](https://assets.leetcode.com/users/images/f8f7e8ba-1ce7-453d-8728-5002617cdabf_1740800031.834896.jpeg) # Code ```cpp [] class Solution { public: vector<int> applyOperations(vector<int>& nums) { int n = nums.size(); int j = 0; vector<int>v(n); for(int i=0;i<n-1;i++){ if(nums[i] == nums[i+1]){ nums[i] *= 2; nums[i+1] = 0; } } for(int i=0;i<n;i++){ if(nums[i]){ v[j] = nums[i]; j++; } } return v; } }; ```
2
0
['Array', 'Two Pointers', 'Simulation', 'C++']
0
apply-operations-to-an-array
Easy Beginner Friendly Solution 🔥 ✅ ⭐️ Simple Logic 💡
easy-beginner-friendly-solution-simple-l-3a2r
Intuitionas per the question If nums[i] == nums[i + 1], we multiply nums[i] by 2 and set nums[i + 1] to 0. then we just moving the zeros to the end .ApproachIf
Muhammed_Razi
NORMAL
2025-03-01T03:09:05.588446+00:00
2025-03-01T03:11:28.727336+00:00
40
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> as per the question If nums[i] == nums[i + 1], we multiply nums[i] by 2 and set nums[i + 1] to 0. then we just moving the zeros to the end . # Approach If it helps Please Upvote ⬆️ ⬆️ ⬆️ <!-- 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 ```javascript [] /** * @param {number[]} nums * @return {number[]} */ var applyOperations = function (nums) { let res = 0; for (let i = 0; i < nums.length; i++) { if (nums[i] === nums[i + 1]) { nums[i] = nums[i] * 2 nums[i + 1] = 0 } if (nums[i] > 0) { const temp = nums[res]; nums[res++] = nums[i] nums[i] = temp } } return nums }; ```
2
0
['Array', 'Two Pointers', 'Simulation', 'JavaScript']
0
apply-operations-to-an-array
[Java][Two-Pointer] Beat 100%
javatwo-pointer-beat-100-by-kuan1025-6t23
IntuitionThe problem requires merging adjacent equal elements and shifting non-zero values to the front while maintaining their order. A simple traversal can ac
kuan1025
NORMAL
2025-03-01T03:08:26.434772+00:00
2025-03-01T03:08:26.434772+00:00
58
false
# Intuition The problem requires merging adjacent equal elements and shifting non-zero values to the front while maintaining their order. A simple traversal can achieve this efficiently. # Approach - Iterate through the array and merge consecutive equal elements by doubling the first one and skipping the second. - Store non-zero elements sequentially in a new array. - Return the modified array with remaining positions filled with zeros. # Complexity - **Time complexity:** \( O(n) \) — Single pass through the array. - **Space complexity:** \( O(n) \) — Uses an extra array for results. # Code ```java [] class Solution { public int[] applyOperations(int[] nums) { int[] res = new int[nums.length]; int j = 0; for (int i = 0 ; i < nums.length ; i++) { if(nums[i] == 0){ } else if( i + 1 < nums.length && nums[i] == nums[i+1]) { res[j++] = nums[i] * 2; i += 1; }else { res[j++] = nums[i]; } } return res; } }
2
0
['Java']
0
apply-operations-to-an-array
My kotlin solution with time O(N) and space O(1)
my-kotlin-solution-with-time-on-and-spac-ps01
The idea is to simulate the process. We can eliminate the shifting of zeros by clearing the existing values and assigning nonzero values to the front of nums du
hj-core
NORMAL
2025-03-01T02:18:56.286705+00:00
2025-03-01T02:31:13.285954+00:00
77
false
The idea is to simulate the process. We can eliminate the shifting of zeros by clearing the existing values and assigning nonzero values to the front of nums during the iteration. Below are my implementations, ```kotlin [] class Solution { // Complexity: // Time O(N) and Space O(1) where N is the length of `nums`. fun applyOperations(nums: IntArray): IntArray { var tail = 0 // The index in `nums` to place the next nonzero value var currValue = 0 for ((i, nextValue) in nums.withIndex()) { nums[i] = 0 if (currValue == 0) { currValue = nextValue continue } if (currValue == nextValue) { nums[tail] = currValue * 2 currValue = 0 } else { nums[tail] = currValue currValue = nextValue } tail++ } if (currValue != 0) { nums[tail] = currValue tail++ } return nums } } ``` ```golang [] // Complexity: // Time O(N) and Space O(1) where N is the length of nums. func applyOperations(nums []int) []int { tail := 0 // The index in nums to place the next nonzero value currValue := 0 for i, nextValue := range nums { nums[i] = 0 if currValue == 0 { currValue = nextValue continue } if currValue == nextValue { nums[tail] = currValue * 2 currValue = 0 } else { nums[tail] = currValue currValue = nextValue } tail++ } if currValue != 0 { nums[tail] = currValue tail++ } return nums } ```
2
0
['Go', 'Kotlin']
1
apply-operations-to-an-array
Python one-liner (code golf)
cursed-python-one-liner-by-killer-whale-jjxg
You can also make everything one line:
killer-whale
NORMAL
2025-03-01T02:17:47.631749+00:00
2025-03-01T02:52:01.429618+00:00
58
false
```python3 class Solution: def applyOperations(self, nums: List[int]) -> List[int]: return sorted(sum(((l:=len([*g]))//2*[k*2,0]+l%2*[k]for k,g in groupby(nums)),[]),key=not_) ``` You can also make everything one line: ```python3 class Solution:applyOperations=lambda _,n:sorted(sum(((l:=len([*g]))//2*[k*2,0]+l%2*[k]for k,g in groupby(n)),[]),key=not_) ```
2
0
['Sorting', 'Python', 'Python3']
1
apply-operations-to-an-array
Optimized In-Place Array Transformation | Beats 💯% | Pseudo Code
optimized-in-place-array-transformation-pscdr
Intuition~ The problem requires us to perform two operations on the given array nums: Merge adjacent equal elements: If nums[i] == nums[i+1], we double nums[i]
rajnandi006
NORMAL
2025-03-01T02:11:39.309619+00:00
2025-03-01T02:36:11.155890+00:00
10
false
# Intuition ~ The problem requires us to perform two operations on the given array nums: - Merge adjacent equal elements: If nums[i] == nums[i+1], we double nums[i] and set nums[i+1] to 0. - Shift all non-zero elements to the left: Move all 0s to the end while maintaining the relative order of non-zero elements. # Approach - Step 1: Merge Adjacent Equal Elements - Traverse the array from i = 0 to n-2. - If nums[i] == nums[i+1], set nums[i] = nums[i] * 2 and nums[i+1] = 0. - This ensures that every adjacent pair is checked only once, merging them if they are equal. - Step 2: Shift Non-Zero Elements to the Left - Traverse the array again while maintaining a pointer zero that tracks the position where the next non-zero element should be placed. - If nums[i] is non-zero, swap nums[i] with nums[zero] and increment zero. - This effectively moves all non-zero elements to the front while pushing 0s to the end. # Complexity - Time complexity: - ***O(N)*** - Space complexity: - ***O(1)*** # ~ If this Solution was helpfull make sure to upvote!!✅✅🔥🔥 # Code ```cpp [] class Solution { public: vector<int> applyOperations(vector<int>& nums) { int n = nums.size(); for(int i = 0; i < n - 1 ; i++) { if(nums[i] == nums[i + 1]) { nums[i] = nums[i] * 2; nums[i + 1] = 0; } } int zero = 0; for(int i = 0; i < n ; i++) { if(nums[i] != 0) { swap(nums[i] , nums[zero]); zero++; } } return nums; } }; ``` # ~ If this Solution was helpfull make sure to upvote!!✅✅🔥🔥
2
0
['Array', 'Two Pointers', 'Simulation', 'C++']
0
apply-operations-to-an-array
Python | Simple One-Pass | O(n), O(1) | Beats 100%
python-simple-one-pass-on-o1-beats-100-b-12tj
CodeComplexity Time complexity: O(n). Visits each index in nums, n total, and performs constant operations, so n overall. Space complexity: O(1). Only variab
2pillows
NORMAL
2025-03-01T01:11:06.126749+00:00
2025-03-01T05:26:32.854089+00:00
302
false
# Code ```python3 [] class Solution: def applyOperations(self, nums: List[int]) -> List[int]: n = len(nums) j = 0 # index of first zero for i in range(n): if i + 1 < n and nums[i] == nums[i + 1]: # check if should apply operation nums[i] *= 2 nums[i + 1] = 0 if nums[i] != 0: nums[i], nums[j] = nums[j], nums[i] # swap zero and non-zero j += 1 # j + 1 for next zero index return nums ``` # Complexity - Time complexity: $$O(n)$$. Visits each index in nums, n total, and performs constant operations, so n overall. - Space complexity: $$O(1)$$. Only variables made are n and j, both constant space. # Performance ![Screenshot (904).png](https://assets.leetcode.com/users/images/0e9ef281-026b-490d-be0e-df918b946d65_1740791151.600152.png)
2
0
['Two Pointers', 'Python3']
1
apply-operations-to-an-array
EasyPeezy | StraightForward | O(n) +O(1) | C++
easypeezy-straightforward-on-o1-c-by-sav-19jf
Code
savetrees
NORMAL
2025-03-01T01:04:50.249556+00:00
2025-03-01T01:04:50.249556+00:00
137
false
# Code ```cpp [] /* By :: savetrees Used :: Optimal */ class Solution { public: vector<int> applyOperations(vector<int>& nums) { int n=nums.size(),j=0; for (int i=0;i<n;i++) { if (i<n-1&&nums[i]==nums[i+1]) { nums[i]*=2; nums[i+1]=0; } if (nums[i]!=0) swap(nums[j++],nums[i]); } return nums; } }; ```
2
0
['C++']
0
group-sold-products-by-the-date
SIMPLE | Explanation | EASY
simple-explanation-easy-by-babasaheb256-rmgz
<<<< Please Press upvote Button !!!!!\n\nAlmost immediately detected, the only serious challange of this problem is how to aggregate the product names in one ce
babasaheb256
NORMAL
2022-06-11T18:53:54.166971+00:00
2022-06-20T06:57:19.674846+00:00
87,090
false
**<<<< Please Press upvote Button !!!!!**\n\nAlmost immediately detected, the only serious challange of this problem is how to aggregate the product names in one cell. In MySql, this can be done using GROUP_CONCAT, in which you can also specify the sorting mechanism for the group concatenation (aggregation). The rest is simple.\n```\nselect sell_date, count( DISTINCT product ) as num_sold ,\n \n GROUP_CONCAT( DISTINCT product order by product ASC separator \',\' ) as products\n \n FROM Activities GROUP BY sell_date order by sell_date ASC;\n\n```\n![image](https://assets.leetcode.com/users/images/1a22513a-f19e-4338-b241-14a37d53c39d_1655656234.9439957.jpeg)\n
959
5
['MySQL']
40
group-sold-products-by-the-date
MySQL Order by Product name AND Sell date
mysql-order-by-product-name-and-sell-dat-nyy7
In June 2024, I realized the first upvoted solution (by @babasaheb256), is an EXACT COPY word by word of my solution. That guy just copies from other people\'s
SubBuffer
NORMAL
2020-06-17T23:03:29.421808+00:00
2024-07-12T22:34:13.891709+00:00
31,642
false
___In June 2024, I realized the first upvoted solution (by @babasaheb256), is an EXACT COPY word by word of my solution. That guy just copies from other people\'s solutions and adds a MEME to them! Check his profile for his other solutions. Dude WTF! Lol___\n\nPlease consider __Upvoting__ my solution to beat his ass and __downvote__ his solution to spread awareness.\n\n_Now, going back to June 2020 when I posted my solution:_\n\nAlmost immediately detected, the only serious challange of this problem is how to aggregate the product names in one cell. In MySql, this can be done using GROUP_CONCAT, in which you can also specify the sorting mechanism for the group concatenation (aggregation). The rest is simple.\n```\nSELECT sell_date,\n\t\tCOUNT(DISTINCT(product)) AS num_sold, \n\t\tGROUP_CONCAT(DISTINCT product ORDER BY product ASC SEPARATOR \',\') AS products\nFROM Activities\nGROUP BY sell_date\nORDER BY sell_date ASC
222
1
['MySQL']
11
group-sold-products-by-the-date
MySQL Solution, CLEAN, FASTER than 92 %
mysql-solution-clean-faster-than-92-by-y-quxz
please UPVOTE \n\nSELECT \n\tsell_date,\n\t(COUNT(sell_date ) ) as num_sold ,\n\tGROUP_CONCAT(distinct product ORDER BY product) as products \nFROM \n\t(SELEC
YassineAmmani
NORMAL
2022-08-28T23:56:52.089248+00:00
2022-08-28T23:56:52.089283+00:00
24,898
false
* ***please UPVOTE ***\n```\nSELECT \n\tsell_date,\n\t(COUNT(sell_date ) ) as num_sold ,\n\tGROUP_CONCAT(distinct product ORDER BY product) as products \nFROM \n\t(SELECT DISTINCT sell_date,product FROM Activities) as Activities\nGROUP BY sell_date;\n```\n\n* ***please UPVOTE ***\n\n
122
0
['MySQL']
2
group-sold-products-by-the-date
Pandas vs SQL | Elegant & Short | All 30 Days of Pandas solutions ✅
pandas-vs-sql-elegant-short-all-30-days-evm7n
Complexity\n- Time complexity: O(n)\n- Space complexity: O(n)\n\n# Code\nPython []\ndef categorize_products(activities: pd.DataFrame) -> pd.DataFrame:\n retu
Kyrylo-Ktl
NORMAL
2023-08-04T14:49:28.526534+00:00
2023-08-06T17:18:22.099123+00:00
10,021
false
# Complexity\n- Time complexity: $$O(n)$$\n- Space complexity: $$O(n)$$\n\n# Code\n```Python []\ndef categorize_products(activities: pd.DataFrame) -> pd.DataFrame:\n return activities.groupby(\n \'sell_date\'\n )[\'product\'].agg([\n (\'num_sold\', \'nunique\'),\n (\'products\', lambda x: \',\'.join(sorted(x.unique())))\n ]).reset_index()\n```\n```SQL []\nSELECT sell_date,\n count(DISTINCT product) AS num_sold,\n group_concat(DISTINCT product ORDER BY product ASC SEPARATOR \',\') products\n FROM activities\n GROUP BY sell_date\n ORDER BY sell_date;\n```\n\n# Important!\n###### If you like the solution or find it useful, feel free to **upvote** for it, it will support me in creating high quality solutions)\n\n# 30 Days of Pandas solutions\n\n### Data Filtering \u2705\n- [Big Countries](https://leetcode.com/problems/big-countries/solutions/3848474/pandas-elegant-short-1-line/)\n- [Recyclable and Low Fat Products](https://leetcode.com/problems/recyclable-and-low-fat-products/solutions/3848500/pandas-elegant-short-1-line/)\n- [Customers Who Never Order](https://leetcode.com/problems/customers-who-never-order/solutions/3848527/pandas-elegant-short-1-line/)\n- [Article Views I](https://leetcode.com/problems/article-views-i/solutions/3867192/pandas-elegant-short-1-line/)\n\n\n### String Methods \u2705\n- [Invalid Tweets](https://leetcode.com/problems/invalid-tweets/solutions/3849121/pandas-elegant-short-1-line/)\n- [Calculate Special Bonus](https://leetcode.com/problems/calculate-special-bonus/solutions/3867209/pandas-elegant-short-1-line/)\n- [Fix Names in a Table](https://leetcode.com/problems/fix-names-in-a-table/solutions/3849167/pandas-elegant-short-1-line/)\n- [Find Users With Valid E-Mails](https://leetcode.com/problems/find-users-with-valid-e-mails/solutions/3849177/pandas-elegant-short-1-line/)\n- [Patients With a Condition](https://leetcode.com/problems/patients-with-a-condition/solutions/3849196/pandas-elegant-short-1-line-regex/)\n\n\n### Data Manipulation \u2705\n- [Nth Highest Salary](https://leetcode.com/problems/nth-highest-salary/solutions/3867257/pandas-elegant-short-1-line/)\n- [Second Highest Salary](https://leetcode.com/problems/second-highest-salary/solutions/3867278/pandas-elegant-short/)\n- [Department Highest Salary](https://leetcode.com/problems/department-highest-salary/solutions/3867312/pandas-elegant-short-1-line/)\n- [Rank Scores](https://leetcode.com/problems/rank-scores/solutions/3872817/pandas-elegant-short-1-line-all-30-days-of-pandas-solutions/)\n- [Delete Duplicate Emails](https://leetcode.com/problems/delete-duplicate-emails/solutions/3849211/pandas-elegant-short/)\n- [Rearrange Products Table](https://leetcode.com/problems/rearrange-products-table/solutions/3849226/pandas-elegant-short-1-line/)\n\n\n### Statistics \u2705\n- [The Number of Rich Customers](https://leetcode.com/problems/the-number-of-rich-customers/solutions/3849251/pandas-elegant-short-1-line/)\n- [Immediate Food Delivery I](https://leetcode.com/problems/immediate-food-delivery-i/solutions/3872719/pandas-elegant-short-1-line-all-30-days-of-pandas-solutions/)\n- [Count Salary Categories](https://leetcode.com/problems/count-salary-categories/solutions/3872801/pandas-elegant-short-1-line-all-30-days-of-pandas-solutions/)\n\n\n### Data Aggregation \u2705\n- [Find Total Time Spent by Each Employee](https://leetcode.com/problems/find-total-time-spent-by-each-employee/solutions/3872715/pandas-elegant-short-1-line-all-30-days-of-pandas-solutions/)\n- [Game Play Analysis I](https://leetcode.com/problems/game-play-analysis-i/solutions/3863223/pandas-elegant-short-1-line/)\n- [Number of Unique Subjects Taught by Each Teacher](https://leetcode.com/problems/number-of-unique-subjects-taught-by-each-teacher/solutions/3863239/pandas-elegant-short-1-line/)\n- [Classes More Than 5 Students](https://leetcode.com/problems/classes-more-than-5-students/solutions/3863249/pandas-elegant-short/)\n- [Customer Placing the Largest Number of Orders](https://leetcode.com/problems/customer-placing-the-largest-number-of-orders/solutions/3863257/pandas-elegant-short-1-line/)\n- [Group Sold Products By The Date](https://leetcode.com/problems/group-sold-products-by-the-date/solutions/3863267/pandas-elegant-short-1-line/)\n- [Daily Leads and Partners](https://leetcode.com/problems/daily-leads-and-partners/solutions/3863279/pandas-elegant-short-1-line/)\n\n\n### Data Aggregation \u2705\n- [Actors and Directors Who Cooperated At Least Three Times](https://leetcode.com/problems/actors-and-directors-who-cooperated-at-least-three-times/solutions/3863309/pandas-elegant-short/)\n- [Replace Employee ID With The Unique Identifier](https://leetcode.com/problems/replace-employee-id-with-the-unique-identifier/solutions/3872822/pandas-elegant-short-1-line-all-30-days-of-pandas-solutions/)\n- [Students and Examinations](https://leetcode.com/problems/students-and-examinations/solutions/3872699/pandas-elegant-short-1-line-all-30-days-of-pandas-solutions/)\n- [Managers with at Least 5 Direct Reports](https://leetcode.com/problems/managers-with-at-least-5-direct-reports/solutions/3872861/pandas-elegant-short/)\n- [Sales Person](https://leetcode.com/problems/sales-person/solutions/3872712/pandas-elegant-short-1-line-all-30-days-of-pandas-solutions/)\n\n
109
0
['Python', 'Python3', 'MySQL', 'Pandas']
5
group-sold-products-by-the-date
✅MySQL || Beginner level ||Easy to Understand||Simple-Short -Solution✅
mysql-beginner-level-easy-to-understands-b2hu
Please upvote to motivate me in my quest of documenting all leetcode solutions. HAPPY CODING:)\nAny suggestions and improvements are always welcome.\n==========
Anos
NORMAL
2022-08-31T20:23:29.943936+00:00
2022-08-31T20:23:29.943975+00:00
8,195
false
**Please upvote to motivate me in my quest of documenting all leetcode solutions. HAPPY CODING:)\nAny suggestions and improvements are always welcome.***\n*====================================================================*\n\u2705 **MySQL Code :**\n```\nSELECT sell_date,\n\t\tCOUNT(DISTINCT(product)) AS num_sold, \n\t\tGROUP_CONCAT(DISTINCT product ORDER BY product ASC SEPARATOR \',\') AS products\nFROM Activities\nGROUP BY sell_date\nORDER BY sell_date ASC\n```\n**Runtime:** 380 ms\n**Memory Usage:** 0B\n________________________________\n__________________________________\n\nIf you like the solution, please upvote \uD83D\uDD3C\nFor any questions, or discussions, comment below. \uD83D\uDC47\uFE0F
55
0
['MySQL']
0
group-sold-products-by-the-date
All DBs, simple solution
all-dbs-simple-solution-by-yurokusa-btmw
Oracle\n\nselect to_char(a.sell_date, \'yyyy-mm-dd\') sell_date\n , count(a.product) num_sold\n , listagg(a.product, \',\') within group(order by a.produc
yurokusa
NORMAL
2020-09-14T02:46:14.904948+00:00
2020-09-14T02:46:14.905007+00:00
7,930
false
Oracle\n```\nselect to_char(a.sell_date, \'yyyy-mm-dd\') sell_date\n , count(a.product) num_sold\n , listagg(a.product, \',\') within group(order by a.product) products\nfrom (select distinct * from activities) a\ngroup by a.sell_date\norder by a.sell_date\n```\nMy SQL\n```\nselect sell_date\n\t, count(distinct product) num_sold\n\t, group_concat(distinct product order by product asc separator \',\') products\nfrom activities\ngroup by sell_date\norder by sell_date\n```\nMS SQL\n```\nselect a.sell_date\n , count(a.product) num_sold\n , string_agg(a.product,\',\') within group (order by a.product) products\nfrom (select distinct sell_date,product from activities) a\ngroup by a.sell_date\norder by a.sell_date\n```
51
0
['MySQL', 'Oracle']
9
group-sold-products-by-the-date
[Pandas] || My Approach with Clear Comments...
pandas-my-approach-with-clear-comments-b-dukz
\n\n# Code\n\nimport pandas as pd\n\ndef categorize_products(activities: pd.DataFrame) -> pd.DataFrame:\n # Group the activities by sell_date and collect the
sriganesh777
NORMAL
2023-08-22T18:01:47.581977+00:00
2023-08-22T18:01:47.582005+00:00
3,792
false
\n\n# Code\n```\nimport pandas as pd\n\ndef categorize_products(activities: pd.DataFrame) -> pd.DataFrame:\n # Group the activities by sell_date and collect the unique products for each date\n grouped = activities.groupby(\'sell_date\')[\'product\'].agg([\'nunique\', lambda x: \',\'.join(sorted(set(x)))]).reset_index()\n \n # Rename the columns for clarity\n grouped.columns = [\'sell_date\', \'num_sold\', \'products\']\n \n # Replace variations of \'Mask\' with just \'Mask\'\n grouped[\'products\'] = grouped[\'products\'].str.replace(r\'(^|,)Mask(,|$)\', r\'\\1Mask\\2\')\n \n # Sort the result table by sell_date\n result = grouped.sort_values(by=\'sell_date\')\n \n return result\n\n```\n![upvote img.jpg](https://assets.leetcode.com/users/images/fe39393f-fae2-42ae-8f28-c486468073a2_1692727296.8042412.jpeg)\n
29
0
['Pandas']
3
group-sold-products-by-the-date
MySQL | Simple n Concise query
mysql-simple-n-concise-query-by-raviteja-ws9v
Query\n\n# Write your MySQL query statement below\nSELECT sell_date,\n COUNT(DISTINCT(product), sell_date) AS num_sold, \n GROUP_CONCAT(DISTINCT pro
ravitejay
NORMAL
2023-01-13T06:52:35.026553+00:00
2023-01-17T07:43:21.087761+00:00
5,630
false
# Query\n```\n# Write your MySQL query statement below\nSELECT sell_date,\n COUNT(DISTINCT(product), sell_date) AS num_sold, \n GROUP_CONCAT(DISTINCT product ORDER BY product) AS products\nFROM Activities\nGROUP BY sell_date\n```\n\n\n\n*if the solution worked for you* ***please upvote***
25
0
['MySQL']
3
group-sold-products-by-the-date
SQL | Easy to Understand | Using GROUP_CONCAT
sql-easy-to-understand-using-group_conca-z60d
\nSELECT sell_date, \n count(DISTINCT product) as num_sold,\n GROUP_CONCAT(DISTINCT product ORDER BY product) AS products\nFROM Activities \nGROUP BY sell
nidhi_ranjan
NORMAL
2022-06-28T11:46:50.637719+00:00
2022-06-28T11:46:50.637748+00:00
2,484
false
```\nSELECT sell_date, \n count(DISTINCT product) as num_sold,\n GROUP_CONCAT(DISTINCT product ORDER BY product) AS products\nFROM Activities \nGROUP BY sell_date \nORDER BY sell_date;\n```\nPlease upvote if you found this useful :)
24
1
['MySQL']
2
group-sold-products-by-the-date
Easiest Solution ;)
easiest-solution-by-youssefgirgeis-yg06
\nSELECT\n sell_date,\n COUNT(DISTINCT product) num_sold,\n GROUP_CONCAT(DISTINCT product) products\nFROM activities\nGROUP BY sell_date\nORDER BY sell
youssefgirgeis
NORMAL
2021-06-10T04:48:51.201699+00:00
2021-06-10T04:48:51.201742+00:00
5,758
false
```\nSELECT\n sell_date,\n COUNT(DISTINCT product) num_sold,\n GROUP_CONCAT(DISTINCT product) products\nFROM activities\nGROUP BY sell_date\nORDER BY sell_date\n```
24
1
[]
4
group-sold-products-by-the-date
Postgre SQL Solution
postgre-sql-solution-by-swetha_murthy-44mo
\n# Approach\n1. We are given with only one table so no need to use JOINs here.\n2. We need to find the number of diff products sold for each date , this indica
Swetha_Murthy
NORMAL
2024-04-02T02:59:27.900822+00:00
2024-04-02T02:59:27.900849+00:00
2,390
false
\n# Approach\n1. We are given with only one table so no need to use JOINs here.\n2. We need to find the number of diff products sold for each date , this indicates we need to group the products by "date"\n3. The output should contain three columns: sell_date, num_sold (distinct count of products) and products\n4. ORDER BY products & ORDER BY sell_date\n5. In order to group the products seperated by comma \n STRING_AGG() Function can be used in postgre sql\n\n# Code\n```\n--For each date -- find no of diff prod sold\n--order prod name lexico, order by sell_date\n--Output -- sell_date, num_sold , products\n\nSELECT sell_date, COUNT(DISTINCT product) AS num_sold, \nSTRING_AGG(DISTINCT product, \',\' ORDER BY product) AS products\nFROM Activities\nGROUP BY sell_date\nORDER BY sell_date\n\n```
19
0
['PostgreSQL']
2
group-sold-products-by-the-date
faster than 83% of MySQL online submissions
faster-than-83-of-mysql-online-submissio-2xlw
<<<<upvote \n\n\tSELECT sell_date, COUNT( DISTINCT product ) AS num_sold , \n GROUP_CONCAT( DISTINCT product ORDER BY product ASC separator \',\' ) AS pro
RohiniK98
NORMAL
2022-10-13T02:50:31.211068+00:00
2022-10-13T02:50:31.211109+00:00
4,628
false
**<<<<upvote **\n\n\tSELECT sell_date, COUNT( DISTINCT product ) AS num_sold , \n GROUP_CONCAT( DISTINCT product ORDER BY product ASC separator \',\' ) AS product \n FROM Activities GROUP BY sell_date ORDER BY sell_date ASC;
15
0
['MySQL']
2
group-sold-products-by-the-date
ms sql solution with string_agg
ms-sql-solution-with-string_agg-by-user0-crgx
Please note that this solution with string_agg will work only from SQL Server 2017 and above and SQL Azure\n\nselect sell_date, count(product) as \'num_sold\',
user0763PD
NORMAL
2022-06-10T07:56:39.780128+00:00
2022-06-10T07:56:39.780160+00:00
3,975
false
Please note that this solution with `string_agg` will work only from SQL Server 2017 and above and SQL Azure\n```\nselect sell_date, count(product) as \'num_sold\', string_agg(product, \',\') as products\nfrom\n(\n select distinct *\n from Activities\n) t\ngroup by sell_date\n```
15
0
['MS SQL Server']
3
group-sold-products-by-the-date
SQL query with detailed explanation ||SQL
sql-query-with-detailed-explanation-sql-4ttrg
GROUPCONCAT() is used to concatenat data from multiple rows into one field\nstep 1: First we will count distinct products and name the column as num_sold\nstep
dinesh47
NORMAL
2022-05-06T07:10:01.958406+00:00
2022-07-20T18:06:36.165435+00:00
1,514
false
##### **GROUPCONCAT() is used to concatenat data from multiple rows into one field**\n***step 1*: First we will count distinct products and name the column as num_sold\n*step 2*: Next we use group concat to get the disctinct products and to display them in a column with a seperator(,) and order by products and name the column as products\n*step 3*: We will group them by sell_date**\n\n\n```\nselect sell_date,count(distinct(product)) as num_sold, GROUP_CONCAT(distinct product order by product asc) as products\nfrom Activities\ngroup by sell_date\n```\n\nUpvote this if you find it useful\nThanks
15
1
['MySQL']
0