You are given a sorted array of integers. Write a program that implements a binary search algorithm to find the element with the minimum difference from the given target.Note: This question was asked in CTS coding test.Input format :The first line input consists of an integer N, representing the number of array elements.The second line consists of N space-separated integers, representing the sorted array elements.The third line consists of an integer representing the target element.Output format :The output prints an integer representing the element with the minimum difference from the given target.
Question
You are given a sorted array of integers. Write a program that implements a binary search algorithm to find the element with the minimum difference from the given target.Note: This question was asked in CTS coding test.Input format :The first line input consists of an integer N, representing the number of array elements.The second line consists of N space-separated integers, representing the sorted array elements.The third line consists of an integer representing the target element.Output format :The output prints an integer representing the element with the minimum difference from the given target.
Solution 1
Here is a Python solution for the problem:
def find_min_diff_element(arr, target):
low = 0
high = len(arr) - 1
min_diff = float('inf')
closest_num = None
# Edge cases for empty list of list with only one element
if len(arr) == 0:
return None
if len(arr) == 1:
return arr[0]
while low <= high:
mid = (low + high)//2
# Ensure you do not read beyond the bounds
# of the list.
if mid+1 < len(arr):
min_diff_right = abs(arr[mid+1] - target)
if mid > 0:
min_diff_left = abs(arr[mid-1] - target)
# Check if the absolute value between left
# and right elements are smaller than any
# seen prior.
if min_diff_left < min_diff:
min_diff = min_diff_left
closest_num = arr[mid-1]
if min_diff_right < min_diff:
min_diff = min_diff_right
closest_num = arr[mid+1]
# Move the mid-point appropriately as is done
# via binary search.
if arr[mid] < target:
low = mid + 1
elif arr[mid] > target:
high =
Solution 2
Here is a Python solution for the problem:
def find_min_diff_element(arr, target):
low = 0
high = len(arr) - 1
while low <= high:
mid = (low + high) // 2
if arr[mid] == target:
return arr[mid]
if arr[mid] < target:
low = mid + 1
else:
high = mid - 1
# After the loop, low and high point to two closest numbers
# Check which one is closer to the target
if abs(arr[low] - target) < abs(arr[high] - target):
return arr[low]
else:
return arr[high]
# Input
N = int(input())
arr = list(map(int, input().split()))
target = int(input())
# Output
print(find_min_diff_element(arr, target))
This program first reads the input. It then calls the function find_min_diff_element which performs a binary search on the array. If the target is found, it is returned immediately. If not, the binary search will eventually narrow down to two elements that are closest to the target. The program then checks which of these two elements is closer to the target and returns it.
Solution 3
Here is a Python solution for the problem:
def find_min_diff_element(arr, target):
low = 0
high = len(arr) - 1
closest_num = None
min_diff = float("inf")
# Edge cases for empty list of list with one item
if len(arr) == 0:
return None
if len(arr) == 1:
return arr[0]
while low <= high:
mid = (low + high)//2
# Ensure you do not read beyond the bounds
# of the list.
if mid+1 < len(arr):
min_diff_right = abs(arr[mid+1] - target)
if mid > 0:
min_diff_left = abs(arr[mid-1] - target)
# Check if the absolute difference between the
# mid element and target is smaller than the current min_diff
if min_diff_left < min_diff:
min_diff = min_diff_left
closest_num = arr[mid-1]
if min_diff_right < min_diff:
min_diff = min_diff_right
closest_num = arr[mid+1]
# Move the mid-point appropriately as is done
# via binary search.
if arr[mid] < target:
low = mid + 1
elif arr[mid] > target:
high = mid - 1
# If the element itself is the target, the closest
# number to it is itself. Return the number.
else:
return arr[mid]
return closest_num
# Test the function
arr = [1, 2, 4,
Similar Questions
Given a sorted array A of size N, along with an integer target K, implement Binary Search to find the target K in the given array.Input FormatThe first line of input contains an integer N - the size of an array and target K. The second line contains the elements of the array.Output FormatFor each iteration of Binary Search, print the values of low, high, and mid. At the end, if the target K is found in the array, print "True" otherwise, print "False".Constraints1 <= N <= 201 <= A[i] <= 103ExampleInput 19 121 4 6 7 10 11 12 20 23Output 10 8 45 8 6TrueInput 210 213 5 8 11 15 17 19 23 26 30Output 20 9 45 9 75 6 56 6 6False
Alex wants to create a program to search a target value in a sorted array. The program should input the array size and elements, as well as the target value. Utilizing binary search, it should determine if the target is present, and if so, provide the index. If not, display a message indicating its absence.Assist Alex in completing the program efficiently.Input format :The first line of input consists of an integer N, representing the size of the sorted array.The second line consists of N space-separated integers, the elements of the sorted array in ascending order.The third line consists of an integer target, the value to search for in the array.Output format :If the target is present in the array, print "The target value X is present at index Y", where X is the target element and Y is the index position (index starts from 0).If the target is not present, print "The target value X is not present in the array", where X is the target element.
You are given two integers n and x. You have to construct an array of positive integers nums of size n where for every 0 <= i < n - 1, nums[i + 1] is greater than nums[i], and the result of the bitwise AND operation between all elements of nums is x.Return the minimum possible value of nums[n - 1]. Example 1:Input: n = 3, x = 4Output: 6Explanation:nums can be [4,5,6] and its last element is 6.Example 2:Input: n = 2, x = 7Output: 15Explanation:nums can be [7,15] and its last element is 15. Constraints:1 <= n, x <= 108
Analyze the code for compile time errors. You are provided with the code skeleton having the full solution with compile time errors. Fix the compile time error in the code.Write a Java program to read an array of integer elements. The program should find the difference between the alternate numbers in the array and find the index position of the smallest element with the largest difference. If more than one pair has the same largest difference, consider the first occurrence.Note: When taking the difference, take the absolute value, i.e. neglecting the sign.Example: If it is 3 - 10= -7, consider it as 7.If the array size is less than 3, Display "Invalid array size".Note:In the Sample Input / Output provided, the highlighted text in bold corresponds to the input given by the user, and the rest of the text represents the output.Ensure to follow the object-oriented specifications provided in the question description.Ensure to provide the names for classes, attributes, and methods as specified in the question description.Adhere to the code template, if provided.Please do not use System.exit(0) to terminate the program.Sample Input/Output 1:Enter the size of the array6Enter the inputs43210861Explanation :Here alternate number difference means4-2, 3-10, 2-8, 10-6Neglect the sign So diff is 2,7,6,4Largest diff is 7 -------> 3-10, here the smallest number is 3 and its index is 1. Hence the output is 1.Sample Input/Output 2:Enter the size of the array7Enter the inputs76223182Sample Input/Output 3:-1Invalid array size
You are given an integer array nums.In one move, you can choose one element of nums and change it to any value.Return the minimum difference between the largest and smallest value of nums after performing at most three moves.
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.