#3819

Rotate Non Negative Elements

Medium
ArraySimulationHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

This approach efficiently rotates the non-negative elements by leveraging modular arithmetic and direct indexing, ensuring minimal operations.

⚙️

Algorithm

3 steps
  1. 1Step 1: Extract non-negative elements and their indices.
  2. 2Step 2: Calculate effective rotation using k %= m, where m is the count of non-negative elements.
  3. 3Step 3: Place rotated elements back into their original indices.
solution.py10 lines
1def rotate(nums, k):
2    non_neg = [x for x in nums if x >= 0]
3    k %= len(non_neg)
4    rotated = non_neg[k:] + non_neg[:k]
5    j = 0
6    for i in range(len(nums)):
7        if nums[i] >= 0:
8            nums[i] = rotated[j]
9            j += 1
10    return nums

Complexity note: The complexity is linear due to single-pass extraction and reinsertion, with additional space for storing non-negative elements.

  • 1Non-negative elements can be independently rotated.
  • 2Negative elements serve as fixed points in the array.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.