701240. Sort by Absolute Difference

Easy

Sort by Absolute Difference

Summary

Given an array of integers, sort the elements based on their absolute differences with respect to a given target value. This problem involves arrays and sorting concepts.

Detailed Explanation

To solve this problem, we can use a simple sorting approach. First, calculate the absolute difference between each element in the array and the target value. Then, sort the array based on these calculated differences.

Here's a step-by-step breakdown of the solution:

  1. Initialize an empty array result to store the sorted elements.
  2. Iterate through the input array arr.
  3. For each element x in arr, calculate its absolute difference with respect to the target value target. You can do this using the formula abs(x - target).
  4. Store the calculated difference along with the original element x in a temporary array or list.
  5. Sort the temporary array or list based on the calculated differences.
  6. Finally, construct the result array by iterating through the sorted temporary array and appending each element to the result.

Here's an ASCII art diagram illustrating this approach:

          +---------------+
          |  Calculate    |
          |  absolute     |
          |  differences  |
          +---------------+
                  |
                  v
          +---------------+
          |  Sort by      |
          |  differences  |
          +---------------+
                  |
                  v
          +---------------+
          |  Construct   |
          |  result array|
          +---------------+

Time complexity: O(n log n), where n is the size of the input array. This is because we are sorting the array based on calculated differences, which takes O(n log n) time.

Space complexity: O(1), as we only use a constant amount of space to store temporary variables and arrays.

Optimized Solutions

Java

View on GeeksforGeeks
public class SortByAbsoluteDifference {
    public static int[] sort(int[] arr, int target) {
        int[] result = new int[arr.length];
        int[] differences = new int[arr.length];

        for (int i = 0; i < arr.length; i++) {
            differences[i] = Math.abs(arr[i] - target);
        }

        Arrays.sort(differences);

        int j = 0;
        for (int difference : differences) {
            while (j < arr.length && Math.abs(arr[j] - target) != difference) {
                j++;
            }
            result[j++] = arr[j - 1];
        }

        return result;
    }
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.