Problem · Array

Array Challenge

Learn this problem
MediumJPMorgan Chase logoJPMorgan ChaseOA

Problem statement

For each element in an array, implement a function that:

  1. Initializes a counter to 0 for each element.
  2. Compares the element with each element to its left:
    • If the left element is greater, subtract the absolute difference from the counter.
    • If the left element is smaller, add the absolute difference to the counter.
  3. Returns a new array containing the final counter values for each element.

Function

arrayChallenge(arr: int[]) → int[]

Complete the function arrayChallenge in the editor with the following parameter:

  • int arr[n]: an array of integers

Returns

  • int[n]: an array of integers calculated as described

Examples

Example 1

arr = [2, 4, 3]return = [0, 2, 0]
  • For arr[0] = 2, counter starts at 0, and there are no elements to the left, so the counter is 0.
  • For arr[1] = 4, counter starts at 0 and then increases by |4 - 2| = 2 at the first and only comparison; counter = 2.
  • Testing arr[2] = 3, first against 4, counter = 0 - |3 - 4| = -1, and then against 2, counter = -1 + |3 - 2| = 0.
  • The answer array is [0, 2, 0].

Example 2

arr = [2, 1, 3]return = [0, -1, 3]

The first element has none to its left, so counter = 0.

The second element, counter = 0 - |1 - 2| = -1.

The third element, counter = 0 + |3 - 1| + |3 - 2| = 3.

Constraints

  • 1 <= n <= 10^5
  • 1 <= arr[i] <= 10^9

More JPMorgan Chase problems

drafts saved locally
public int[] arrayChallenge(int[] arr) {
  // write your code here
}
arr[2, 4, 3]
expected[0, 2, 0]
checking account