Taro Logo

Rotate Non Negative Elements

Medium
Asked by:
Accolite
0 views
Topics:
Arrays

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 <= 105
  • -105 <= nums[i] <= 105
  • 0 <= k <= 105

Solution


Brute Force Solution

Approach

This solution separates the non-negative numbers from the input array while noting their order. It then rotates these non-negative values to the left by the specified offset cyclically. Finally, it populates a copy of the original array with the rotated elements at the positions that originally held non-negative integers.

Here's how the algorithm would work step-by-step:

  1. Collect all non-negative numbers from the array into an auxiliary list.
  2. Return the original array unchanged if no non-negative numbers are present.
  3. Compute the effective left rotation using the modulo operator with the count of non-negative elements.
  4. Rotate the auxiliary list of non-negative elements to the left by the effective shift.
  5. Iterate through the original array and overwrite non-negative positions sequentially with the rotated values.
  6. Return the updated array containing the rotated elements.

Code Implementation

def rotate_non_negative_elements(nums: list[int], k: int) -> list[int]:
    # Extract all non-negative elements in their original relative order.
    non_negatives = [val for val in nums if val >= 0]
    if not non_negatives:
        return nums
    # Calculate the effective rotation shift using modulo arithmetic.
    shift = k % len(non_negatives)
    rotated = non_negatives[shift:] + non_negatives[:shift]
    # Reconstruct the result array by placing rotated elements at non-negative positions.
    result = list(nums)
    rotated_index = 0
    for index in range(len(result)):
        if result[index] >= 0:
            result[index] = rotated[rotated_index]
            rotated_index += 1
    return result

Big(O) Analysis

Time Complexity
O(N) – Extracting the non-negative elements, rotating them, and reinserting them each takes linear time with respect to the length of the input array.
Space Complexity
O(N) – Additional memory is used to store the extracted non-negative elements and create the result array, both of which are bounded by the size of the input.

Optimal Solution

Approach

The algorithm rotates only the non-negative numbers in an array to the left while keeping all negative elements in their original positions. It collects the non-negative values, cyclically shifts them using modular arithmetic, and writes them back into their original indices. This guarantees that negative values remain untouched and non-negative elements appear in the newly rotated order.

Here's how the algorithm would work step-by-step:

  1. Collect all elements with a value greater than or equal to zero into a separate list.
  2. Check if the collected list is empty, returning the original array immediately if so.
  3. Compute the rotation offset modulo the length of the non-negative values list.
  4. Perform the left rotation by slicing and concatenating the list of non-negative elements.
  5. Create a copy of the input array to hold the final results.
  6. Iterate through the array and overwrite each non-negative slot with the next rotated value.
  7. Return the modified array containing the rotated elements.

Code Implementation

def rotate_non_negative_elements(nums: list[int], k: int) -> list[int]:
    # Extract all non-negative elements in their original order.
    non_negatives = [val for val in nums if val >= 0]
    total_non_negatives = len(non_negatives)
    if total_non_negatives == 0:
        return nums
    # Calculate effective shift and perform cyclic left rotation.
    shift_amount = k % total_non_negatives
    rotated_elements = non_negatives[shift_amount:] + non_negatives[:shift_amount]
    result_array = list(nums)
    rotated_index = 0
    # Place rotated elements back into positions originally holding non-negative values.
    for current_index in range(len(result_array)):
        if result_array[current_index] >= 0:
            result_array[current_index] = rotated_elements[rotated_index]
            rotated_index += 1
    return result_array

Big(O) Analysis

Time Complexity
O(n) – We iterate through the array of length n once to filter the non-negative elements, perform a rotation in linear time relative to the number of non-negative elements, and iterate through the array once more to reconstruct the result.
Space Complexity
O(n) – We store the non-negative elements and allocate a new list for the rotated elements and output array, which takes additional linear space in the worst case.

Edge Cases

Empty array or null input
How to Handle:
Return the array as-is since there are no elements to extract or rotate.
Array with all negative numbers
How to Handle:
Return the array unchanged because no non-negative elements exist to be rotated.
Array with all non-negative numbers
How to Handle:
Perform a standard right rotation on the entire array based on the value of k.
Rotation count k is greater than the count of non-negative elements
How to Handle:
Normalize k using modulo operation with the count of non-negative elements to avoid redundant rotations.
Rotation count k is zero or a multiple of the non-negative count
How to Handle:
Return the original array since the non-negative elements effectively rotate back to their starting positions.
Array contains a mix of negative numbers and zeros
How to Handle:
Treat zeros as non-negative elements, extracting and rotating them alongside positive integers while keeping negatives fixed.
Single-element array containing either a negative or non-negative value
How to Handle:
Skip rotation and return the single-element array directly as no movement is possible.
Very large arrays with millions of elements
How to Handle:
Ensure O(N) time complexity by collecting indices and values in a single pass before in-place or copied rearrangement.