2460. Apply Operations to an Array #21
Unanswered
iamAntimPal
asked this question in
Q&A
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
2460. Apply Operations to an Array
Difficulty: Easy
Topics: Arrays, Operations
Hint: Operations are applied sequentially, not simultaneously.
Problem Statement
You are given a 0-indexed array
nums
of sizen
consisting of non-negative integers.You need to apply
n - 1
operations to this array where, in the i-th operation (0-indexed), you will do the following on thei
-th element ofnums
:nums[i] == nums[i + 1]
, then multiplynums[i]
by 2 and setnums[i + 1]
to0
.After performing all the operations, shift all the
0
s to the end of the array.Return the resulting array.
Note: The operations are applied sequentially, not all at once.
Examples
Example 1
Explanation:
nums[0]
andnums[1]
are not equal, so skip this operation.nums[1]
andnums[2]
are equal, multiplynums[1]
by 2 and setnums[2]
to0
.Array becomes:
[1,4,0,1,1,0]
.nums[2]
andnums[3]
are not equal, skip.nums[3]
andnums[4]
are equal, multiplynums[3]
by 2 and setnums[4]
to0
.Array becomes:
[1,4,0,2,0,0]
.nums[4]
andnums[5]
are equal, multiplynums[4]
by 2 and setnums[5]
to0
.Array remains:
[1,4,0,2,0,0]
.After shifting all
0
s to the end, the result is[1,4,2,0,0,0]
.Example 2
Explanation:
No operation can be applied. Simply shift the
0
to the end.Constraints
2 <= nums.length <= 2000
0 <= nums[i] <= 1000
Discussion
I'm looking for the most efficient approach to solve this problem while handling edge cases such as multiple adjacent equal numbers. Some points for discussion:
I’d love to hear your thoughts, optimizations, or alternative implementations for this problem. Please share your solutions and ideas below!
Feel free to start a discussion and share your implementations. Let’s collaborate and learn together!
Beta Was this translation helpful? Give feedback.
All reactions