↓Skip to main content
  1. LeetCode/

LeetCode 3819: Rotate Non Negative Elements

·1 min· ·
LeetCode Medium Array Simulation
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: medium First Attempt: 2026-01-25

  • Submissions: Runtime Error → Accepted

Approach
#

Negatives stay put, so only handle non-negatives (Array Template 5): record their positions and values, rotate the values left by k % m (m non-negatives), and fill the positions back in order.

My Attempts
#

Attempt 1 did not handle “no non-negative values”: k % len(non_neg) took a modulo by 0. For nums = [-1], k = 2 it raised ZeroDivisionError. Adding the special case passed.

Solution
#

class Solution:
    def rotateElements(self, nums: List[int], k: int) -> List[int]:
        idx = [i for i, x in enumerate(nums) if x >= 0]
        if not idx:
            return nums
        vals = [nums[i] for i in idx]
        k %= len(vals)
        vals = vals[k:] + vals[:k]                 # 左旋 k 格
        res = nums[:]
        for i, v in zip(idx, vals):
            res[i] = v
        return res

Complexity
#

Time O(n), space O(n).

Mistakes to Avoid
#

  • Make sure the number of non-negatives is not 0 before taking a modulo.
  • Rotating left is vals[k:] + vals[:k].

Interview Explanation
#

I extract the non-negative positions and values, rotate the values left by k, and put them back in order while negatives stay. With no non-negatives I return the array as is. Time O(n).

Related

LeetCode 3679: Minimum Discards to Balance Inventory
·3 mins
LeetCode Medium Sliding-Window Hash-Table Simulation Counting Array
LeetCode 3679 note: the rule already decides what must be discarded, so simulate it; the length-w window counts only kept arrivals, and discarded ones must not be subtracted when they leave
LeetCode 735: Asteroid Collision
·2 mins
LeetCode Medium Array Stack Simulation
LeetCode 735 note: scan left to right with a stack; only a right-moving top meeting a left-moving asteroid collides, the smaller explodes and equal sizes both do
LeetCode 54: Spiral Matrix
·2 mins
LeetCode Medium Array Matrix Simulation
LeetCode 54 note: keep four boundaries and walk right, down, left and up, shrinking a boundary after each side
LeetCode 59: Spiral Matrix II
·2 mins
LeetCode Medium Array Matrix Simulation
LeetCode 59 note: keep four boundaries as in LC 54, but fill in 1 to n² instead of reading
LeetCode 2105: Watering Plants II
·2 mins
LeetCode Medium Two-Pointers Simulation Array
LeetCode 2105 note: Alice from the left and Bob from the right, simulated with converging pointers; when they meet at the same plant, whoever has more water waters it
LeetCode 1222: Queens That Can Attack the King
·2 mins
LeetCode Medium Array Matrix Simulation
LeetCode 1222 note: step outward from the king in eight directions; the first queen met in each direction can attack, with queens in a set for lookups