Post

Created by @nathanedwards
 at November 4th 2023, 9:49:06 pm.

Question: You have been given an array nums of integers with a length of n. Write a Java method traverseAndManipulate that takes in this array and performs the following operations:

  1. Traverse the array from left to right and find the sum of all the elements at even indices (0, 2, 4, etc.). Store this sum in a variable evenSum.
  2. Traverse the array from right to left and find the product of all the elements at odd indices (n-1, n-3, n-5, etc.). Store this product in a variable oddProduct.
  3. Traverse the array once again and replace each element at even indices with the value of the corresponding element at odd indices (0 with n-1, 2 with n-3, and so on).

The method should return the modified array with the replaced values at even indices. Assume that the length of nums is always even.

Write the complete method traverseAndManipulate with the following signature:

public static int[] traverseAndManipulate(int[] nums)

Example:

Input:

int[] nums = {1, 2, 3, 4, 5, 6, 7, 8};

Output:

// evenSum = 1+3+5+7 = 16
// oddProduct = 8*6*4*2 = 384
// After replacing elements at even indices: {8, 2, 6, 4, 384, 6, 5, 8}

Explanation:

To solve the problem, we can follow the following steps:

  1. Initialize evenSum as 0 and oddProduct as 1 to keep track of values.
  2. Traverse the nums array from left to right using a for loop. In each iteration, check if the current index i is even or odd using the modulus operator %. If even, add the element at nums[i] to evenSum.
  3. Traverse the nums array from right to left using a for loop. In each iteration, check if the current index i is even or odd using the modulus operator %. If odd, multiply the element at nums[i] to oddProduct.
  4. Traverse the nums array once again using a for loop. In each iteration, check if the current index i is even or odd using the modulus operator %. If even, replace the element at nums[i] with the value at nums[i-1].
  5. Finally, return the modified nums array.

Here is the implementation of the traverseAndManipulate method:

public static int[] traverseAndManipulate(int[] nums) {
    int evenSum = 0;
    int oddProduct = 1;

    // Step 1: Find sum of elements at even indices
    for (int i = 0; i < nums.length; i++) {
        if (i % 2 == 0) {
            evenSum += nums[i];
        }
    }

    // Step 2: Find product of elements at odd indices
    for (int i = nums.length - 1; i >= 0; i--) {
        if (i % 2 == 1) {
            oddProduct *= nums[i];
        }
    }

    // Step 3: Replace elements at even indices
    for (int i = 0; i < nums.length; i++) {
        if (i % 2 == 0) {
            nums[i] = nums[i + 1];
        }
    }

    // Step 4: Return modified array
    return nums;
}

This implementation correctly traverses the array, performs the required operations, and returns the modified array with replaced values at even indices.