Last Updated: 15 Jan, 2021

Absolute difference in an array

Easy
Asked in companies
AdobeFacebookBarclays

Problem statement

You are given an array/list 'ARR' consisting of 'N' non - negative integers. Your task is to return the running absolute difference of the elements at even and odd index positions separately.

The index of the first element in the array is considered to be zero that is 0 - based indexing is considered for calculating the parity of the index.

Example:

Consider the array - [1, 2, 3, 4, 5, 6]
The elements at even positions will be 1, 3, 5. The running absolute difference of elements will be - 
|1 - 3| = 2 , |2 -5| = 3. Hence our answer will be 3.

The elements at odd positions will be 2, 4, 6. The running absolute difference of elements will be - 
|2 - 4| = 2 , |2 - 6| = 4. Hence our answer will be 4.
Input Format
The first line of input contains an integer ‘T’ denoting the number of test cases to run. Then the test cases follow.

The first line of each test case contains a single integer ‘N’ denoting the number of elements of ARR.

The next line of each test case contains ‘N’ space-separated integers denoting the elements of ARR.
Output Format :
For each test case, return two integers denoting the running absolute difference of elements at even and odd positions respectively.
Note:
You do not need to print anything; it has already been taken care of. Just implement the given function.
Constraints:
 1 <= T <= 10
 1 <= N <= 5 * 10^4
 1 <= ARR[i] <=10^5

Time Limit: 1 sec

Approaches

01 Approach

We will keep two variables 'SUM_EVEN’ and ‘SUM_ODD' initially initialised to zero, denoting the running absolute difference of elements at even and odd positions respectively. For each index ‘i’, if ‘i’ is even, we set 'SUM_EVEN' to |'SUM_EVEN' - ‘ARR[i]’| else, we set 'SUM_ODD' to |'SUM_ODD' - ‘ARR[i]’|.

The algorithm will be -

  • For each ‘i’ from 0 to ‘N - 1’:
    • If ‘i’ % 2 == 0 :
      • 'SUM_EVEN' = |'SUM_EVEN' - ARR[i]|.
    • Else,
      • 'SUM_ODD' = |'SUM_ODD' - ARR[i]|.
  • We finally return the value of 'SUM_EVEN' and 'SUM_ODD'.