Rotate Non Negative Elements Problem
Description
LeetCode Problem 3819.
You are given an integer array nums and an integer k.
Rotate only the non-negative elements of the array to the left by k positions, in a cyclic manner.
All negative elements must stay in their original positions and must not move.
After rotation, place the non-negative elements back into the array in the new order, filling only the positions that originally contained non-negative values and skipping all negative positions.
Return the resulting array.
Example 1:
Input: nums = [1,-2,3,-4], k = 3
Output: [3,-2,1,-4]
Explanation:
- The non-negative elements, in order, are [1, 3].
- Left rotation with k = 3 results in:
- [1, 3] -> [3, 1] -> [1, 3] -> [3, 1]
- Placing them back into the non-negative indices results in [3, -2, 1, -4].
Example 2:
Input: nums = [-3,-2,7], k = 1
Output: [-3,-2,7]
Explanation:
- The non-negative elements, in order, are [7].
- Left rotation with k = 1 results in [7].
- Placing them back into the non-negative indices results in [-3, -2, 7].
Example 3:
Input: nums = [5,4,-9,6], k = 2
Output: [6,5,-9,4]
Explanation:
- The non-negative elements, in order, are [5, 4, 6].
- Left rotation with k = 2 results in [6, 5, 4].
- Placing them back into the non-negative indices results in [6, 5, -9, 4].
Constraints:
1 <= nums.length <= 10^5-10^5 <= nums[i] <= 10^50 <= k <= 10^5
Solution
Approach: Simulation
Collect the non-negative elements into an array t of length m. Rotating t left by k moves the element at index i to index (i - k) mod m (taken as a non-negative remainder), so write each t[i] into a new array d at that index.
Then walk through nums again. Every time you meet a non-negative value, replace it with the next unused element of d; negative values are left alone.
Complexity: O(n) time and O(m) extra space, where n is the length of nums and m the number of non-negative elements.
class Solution:
def rotateElements(self, nums: List[int], k: int) -> List[int]:
t = [x for x in nums if x >= 0]
m = len(t)
d = [0] * m
for i, x in enumerate(t):
d[((i - k) % m + m) % m] = x
j = 0
for i, x in enumerate(nums):
if x >= 0:
nums[i] = d[j]
j += 1
return nums