Bernard Wong
  • Software Engineer
  • Problems
    • Lowest Common Ancestor of a Binary Tree
    • Longest Substring Without Repeating Characters
    • Longest Palindromic Substring
    • Longest Common Prefix
    • Isomorphic Strings
    • Integer to Roman
    • Frog Jump
    • Find the Difference
    • Find k closest elements to a given value
    • Longest Common Subsequence
    • Binary Search Tree from Sorted Array
    • Balanced Binary Tree
    • Sort Using Two Stacks
    • O(1) Stack
    • k-th element to last of a LinkedList
    • Dedup LinkedList
    • Check Rotated String
    • Compress String by Character Count
    • Escape HTML whitespace
    • Check String Permutation
    • Unique String
    • Container With Most Water
    • 4 Sum
    • 3 Sum Closest
    • 3 Sum
    • 2 Sum
    • Maximum Subarray
    • Nested List Weight Sum
    • Palindrome Number
    • Pow(x, n)
    • Regular Expression Matching
    • Remove Nth Node From End of List
    • Reverse Integer
    • Roman to Integer
    • Rotate Array
    • Search a 2D Matrix
    • Shortest Word Distance
    • Two Sum III - Data structure design
    • Valid Parentheses
    • ZigZag Conversion
    • Quicksort
    • Add Two Numbers
    • Best Time to Buy and Sell Stock
    • Letter Combinations of a Phone Number
  • Data Structures
    • Heap
Powered by GitBook
On this page
  1. Problems

Find k closest elements to a given value

Given a sorted array arr[] and a value X, find the k closest elements to X in arr[].

Examples:

Input:

K = 4

X = 35

arr[] = {12, 16, 22, 30, 35, 39, 42, 45, 48, 50, 53, 55, 56}

Output:

30 39 42 45

Note that if the element is present in array, then it should not be in output, only the other closest elements are required.

def findKClosest(arr: Array[Int], target: Int, k: Int): List[Int] = {
  def findClosest(start: Int, end: Int): Int = {
    val mid = (start + end) / 2
    arr(mid) match {
      case m if m == target || (m < target && arr(mid + 1) > target) => mid
      case m if m > target => findClosest(start, mid - 1)
      case m if m < target => findClosest(mid + 1, start)
    }
  }
  if (k <= 0) Nil
  else {
    var lst: List[Int] = Nil
    val m = findClosest(0, arr.length - 1)
    var (l, r) = (m, m + 1)

    // excludes numbers equal to target
    while (l >= 0 && arr(l) == target) l -= 1
    while (r < arr.length && arr(r) == target) r += 1

    // select left/right closest
    while (lst.length < k && l >= 0 && r < arr.length) {
      if (target - arr(l) < arr(r) - target) {
        lst = arr(l) :: lst
        l -= 1
      } else {
        lst = arr(r) :: lst
        r += 1
      }
    }

    // select left/right closest if l < 0/r >= arr.length
    while (lst.length < k && r < arr.length) {
      lst = arr(r) :: lst
      r += 1
    }
    while (lst.length < k && l >= 0) {
      lst = arr(l) :: lst
      l -= 1
    }
    lst
  }
}

val arr = Array(12, 16, 22, 30, 35, 39, 42, 45, 48, 50, 53, 55, 56)
findKClosest(arr, 35, 4)

PreviousFind the DifferenceNextLongest Common Subsequence

Last updated 6 years ago