8000 Add solution for "Apply Operations To An Array" problem · khemssharma/leetcode@be321f3 · GitHub
[go: up one dir, main page]

Skip to content

Commit be321f3

Browse files
committed
Add solution for "Apply Operations To An Array" problem
1 parent 1e9b3e9 commit be321f3

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

JavaScript/leetcode 2046

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
# 2460. Apply Operations To An Array
2+
`Array` `Two Pointers` `Simulation`
3+
4+
You are given a 0-indexed array nums of size n consisting of non-negative integers.
5+
6+
You need to apply n - 1 operations to this array where, in the ith operation (0-indexed), you will apply the following on the ith element of nums:
7+
8+
If nums[i] == nums[i + 1], then multiply nums[i] by 2 and set nums[i + 1] to 0. Otherwise, you skip this operation.
9+
After performing all the operations, shift all the 0's to the end of the array.
10+
11+
For example, the array [1,0,2,0,0,1] after shifting all its 0's to the end, is [1,2,1,0,0,0].
12+
Return the resulting array.
13+
14+
Note that the operations are applied sequentially, not all at once.
15+
16+
17+
18+
**Example 1**:
19+
20+
> **Input**: nums = [1,2,2,1,1,0]
21+
**Output**: [1,4,2,0,0,0]
22+
**Explanation**: We do the following operations:
23+
- i = 0: nums[0] and nums[1] are not equal, so we skip this operation.
24+
- i = 1: nums[1] and nums[2] are equal, we multiply nums[1] by 2 and change nums[2] to 0. The array becomes [1,4,0,1,1,0].
25+
- i = 2: nums[2] and nums[3] are not equal, so we skip this operation.
26+
- i = 3: nums[3] and nums[4] are equal, we multiply nums[3] by 2 and change nums[4] to 0. The array becomes [1,4,0,2,0,0].
27+
- i = 4: nums[4] and nums[5] are equal, we multiply nums[4] by 2 and change nums[5] to 0. The array becomes [1,4,0,2,0,0].
28+
After that, we shift the 0's to the end, which gives the array [1,4,2,0,0,0].
29+
30+
**Example 2**:
31+
32+
> **Input**: nums = [0,1]
33+
**Output**: [1,0]
34+
**Explanation**: No operation can be applied, we just shift the 0 to the end.
35+
36+
37+
# Solution
38+
```javascript []
39+
var applyOperations = function (nums) {
40+
for (let i = 0; i < nums.length - 1; i++) {
41+
if (nums[i] === nums[i + 1]) {
42+
nums[i] *= 2;
43+
nums[i + 1] = 0;
44+
}
45+
}
46+
let i = 0;
47+
for (let j = 0; j < nums.length; j++) { // grows window
48+
if (nums[j] !== 0) {
49+
[nums[i], nums[j]] = [nums[j], nums[i]]
50+
i++; // shrinks the window of zeroes
51+
}
52+
}
53+
return nums;
54+
};
55+
```

0 commit comments

Comments
 (0)
0