"LeetCode Problem #2460: Array Operations and Zero Shifting"

🚀 Day 43 of #100DaysOfCode – LeetCode Problem #2460: Apply Operations to an Array 💬 Problem Summary: You’re given a non-negative integer array nums. You need to: Sequentially check each element nums[i]. If nums[i] == nums[i + 1], then: Multiply nums[i] by 2 Set nums[i + 1] to 0 After all operations, move all zeros to the end of the array. Return the resulting array. 🧩 Example: Input: [1,2,2,1,1,0] Output: [1,4,2,0,0,0] Explanation: - i=1: 2 == 2 → [1,4,0,1,1,0] - i=3: 1 == 1 → [1,4,0,2,0,0] Shift zeros → [1,4,2,0,0,0] 🧠 Logic: ✅ Traverse the array once, applying the doubling rule. ✅ Use a two-pointer approach or list building to shift zeros efficiently. 💻 Java Solution: 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 index = 0; for (int num : nums) { if (num != 0) nums[index++] = num; } while (index < n) { nums[index++] = 0; } return nums; } } ⚙️ Complexity: Time: O(n) Space: O(1) ✅ Result: Accepted (Runtime: 0 ms) 💬 Takeaway: This problem reinforces the importance of in-place transformations and efficient data movement.

To view or add a comment, sign in

Explore content categories