FastPrepSmallest Absolute Difference Between Two Array Elements

Smallest Absolute Difference Between Two Array Elements

Marshall Wace logoMarshall Wace● EasyNEW GRADPHONE SCREEN

Problem statement

Given an integer array A, return the smallest absolute difference between elements at two distinct indices.

The two elements need not be neighbours in the original array. Equal values at different indices are allowed and give a difference of 0.

Function

solution(A: int[]) → int

Examples

Example 1

A = [8,1,9]return = 1

The values 8 and 9 differ by 1, even though they are not neighbours in the original array.

Example 2

A = [4,4]return = 0

The equal values occupy distinct indices, so their absolute difference is 0.

Example 3

A = [-5,-1,-4]return = 1

The closest values are -5 and -4.

Constraints

  • 2 <= A.length <= 200000.
  • -10^9 <= A[i] <= 10^9.

More Marshall Wace problems

See Marshall Wace hiring insights
Saved
public int solution(int[] A) {
    // Write your solution here.
}
A[8,1,9]
expected1
Checking account…