#K95492. Find Pair with Given Absolute Difference
Find Pair with Given Absolute Difference
Find Pair with Given Absolute Difference
You are given an array of integers and an integer K. Your task is to find two distinct indices i and j (1-indexed) such that \(|a_i - a_j| = K\). If there are multiple possible pairs, return the one that is found first using the algorithm described below. If no such pair exists, output -1.
Problem Details:
- The solution should read the input from standard input (stdin) and write the output to standard output (stdout).
- The first line of input contains two integers: n (the number of elements in the array) and K (the target absolute difference).
- The second line contains n space-separated integers representing the elements of the array.
- If a valid pair exists, output the two indices separated by a space. If no such pair exists, output -1.
The intended algorithm uses a hash map (or dictionary) to store the array elements along with their indices. As you iterate through the array, for the current element a, check if either a + K or a - K has already been seen. If yes, output the indices corresponding to these values (with 1-indexing). Otherwise, store the current element and its index in the map.
inputFormat
The input is given via standard input (stdin) with the following format:
n K a1 a2 a3 ... an
Where:
n
is the number of elements in the array.K
is the target absolute difference.a1, a2, ..., an
are the elements of the array.
outputFormat
Output to standard output (stdout) a single line. If a valid pair is found, print the two indices (1-indexed) separated by a space. If no such pair exists, print -1
.
5 3
1 5 3 4 2
1 4