Post

Created by @nathanedwards
 at November 1st 2023, 12:03:16 pm.

Question:

You are given an array of integers, arr, of size n where n > 1. Each element in the array is unique and lies in the range [0, n-1]. Your task is to traverse and manipulate the array in the following manner:

  1. Traverse the array and for each element x at index i, find the element y at index arr[i].
  2. Increment y by n.
  3. Traverse the array again and for each element x at index i, find the element y at index arr[i].
  4. Divide y by n and store the result back at index i in the array.

Write a method, traverseAndManipulateArray(arr: List[int]) -> List[float], to perform the above operations and return the modified array.

Example:

Input:

arr = [1, 2, 0]

Output:

[2.0, 0.0, 1.0]

Explanation:

  1. Initial array: [1, 2, 0]

    Traversing the array:

    • Element 1 at index 0, find element 2 at index 1, increment 2 by 3 (since n=3), so arr becomes [1, 5, 0].
    • Element 2 at index 1, find element 0 at index 2, increment 0 by 3, so arr becomes [1, 5, 3].
    • Element 0 at index 2, find element 1 at index 0, increment 1 by 3, so arr becomes [4, 5, 3].
  2. Traversing the array after the first traversal:

    • Divide each element x by n, so arr becomes [1.333, 1.666, 1.0].

    Note: The expected output is rounded to 3 decimal places.

Hints:

  • The elements of the array can store both the original value and modified value for each index.
  • Use the modulo operator to access the original value at each index.
  • Use integer division to calculate the modified value to keep the precision intact.