Grokking the Coding Interview: Patterns for Coding Questions

0% completed

Solution: Minimum Difference Element

Problem Statement

Given an array of numbers sorted in ascending order, find the element in the array that has the minimum difference with the given ‘key’.

Example 1:

Input: [4, 6, 10], key = 7
Output: 6
Explanation: The difference between the key '7' and '6' is minimum than any other number in the array 

Example 2:

Input: [4, 6, 10], key = 4
Output: 4

Example 3:

Input: [1, 3, 8, 10, 15], key = 12
Output: 10

Example 4:

Input: [4, 6, 10], key = 17
Output: 10

Solution

The problem follows the Binary Search pattern

.....

.....

.....

Like the course? Get enrolled and start learning!
Gustavo Alves

Gustavo Alves

· 8 months ago

My solution gives this error when running submit:

RuntimeException 0.071 s

Runtime error: Cannot read properties of undefined (reading 'length')

Your Input[10, 20, 30, 40, 50] 35 Output undefined Expected 30

But when i run it manually it passes just fine.