[LeetCode] Rotate Non Negative Elements

3819. Rotate Non Negative Elements

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public:
vector<int> rotateElements(vector<int>& nums, int k) {
vector<int> nonNegs;
for(int i = 0; i < nums.size(); i++) {
if(nums[i] >= 0) nonNegs.push_back(i);
}
if(nonNegs.size() == 0) return nums;
k %= nonNegs.size();
vector<int> res;
for(int i = 0; i < nums.size(); i++) {
if(nums[i] < 0) res.push_back(nums[i]);
else {
res.push_back(nums[nonNegs[k % nonNegs.size()]]);
k++;
}
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2026/09/04/PS/LeetCode/rotate-non-negative-elements/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.