709944. Farthest number

Medium

Farthest Number

Slug: farthest-number--170636 Difficulty: Medium Id: 709944 Topic Tags: Arrays, Binary Search, Data Structures, Algorithms Company Tags: Amazon

Summary

Find the farthest number from a given target number in an array of integers. The problem involves arrays and binary search, with an optional sorting step.

Detailed Explanation

The algorithm for this problem is straightforward: sort the array in ascending order, then perform a binary search to find the target number. If the target is not found, we know that it must be either the largest or smallest integer in the array, depending on whether it's greater than or less than all elements in the array.

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

  1. Sort the array in ascending order.
  2. Perform a binary search to find the target number.
  3. If the target is found, return the closest integer to it.
  4. If the target is not found, check if all elements are less than or greater than the target.
  5. Return the farthest integer from the target.

Time complexity: O(n log n) for sorting, and O(log n) for binary search. Space complexity: O(1), as we're only using a constant amount of space to store variables.

Optimized Solutions

Here are optimized solutions in various programming languages:

Java

View on GeeksforGeeks
public class Main {
    public static int farthestNumber(int[] arr, int target) {
        Arrays.sort(arr);
        int left = 0;
        int right = arr.length - 1;
        while (left <= right) {
            int mid = left + (right - left) / 2;
            if (arr[mid] == target) {
                return Math.max(Math.abs(target - arr[left]), Math.abs(target - arr[right]));
            } else if (arr[mid] < target) {
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }
        return Math.max(Math.abs(target - arr[0]), Math.abs(target - arr[arr.length - 1]));
    }

    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4, 5};
        int target = 3;
        System.out.println(farthestNumber(arr, target));
    }
}

DevExCode

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

© 2026 DevExCode. All rights reserved.