From 309ce747bf77c1629af5c11b18fbdea6c9f13019 Mon Sep 17 00:00:00 2001 From: Pralav Singh <174412353+pralav-25@users.noreply.github.com> Date: Tue, 29 Sep 2026 23:15:06 +0530 Subject: [PATCH] fix: find interpolation search keys in constant arrays --- Search/InterpolationSearch.js | 5 +++++ Search/test/InterpolationSearch.test.js | 12 ++++++++++++ 2 files changed, 17 insertions(+) diff --git a/Search/InterpolationSearch.js b/Search/InterpolationSearch.js index 93f3b78b0e..47e10179ef 100644 --- a/Search/InterpolationSearch.js +++ b/Search/InterpolationSearch.js @@ -18,6 +18,11 @@ export function interpolationSearch(arr, key) { // Because the array is sorted the key must be between low and high while (low <= high && key >= arr[low] && key <= arr[high]) { + // Equal endpoints mean every remaining element matches the key. + if (arr[low] === arr[high]) { + return low + } + delta = (key - arr[low]) / (arr[high] - arr[low]) position = low + Math.floor((high - low) * delta) diff --git a/Search/test/InterpolationSearch.test.js b/Search/test/InterpolationSearch.test.js index 674c059db2..c4b2ce8588 100644 --- a/Search/test/InterpolationSearch.test.js +++ b/Search/test/InterpolationSearch.test.js @@ -1,5 +1,17 @@ import { interpolationSearch } from '../InterpolationSearch' +test.each([ + [[7], 7, 0], + [[7, 7, 7], 7, 0], + [[-4, -4, -4], -4, 0], + [[0, 0], 0, 0], + [[7], 6, -1], + [[7, 7, 7], 8, -1], + [[], 7, -1] +])('interpolationSearch(%j, %s) => %s', (array, key, expected) => { + expect(interpolationSearch(array, key)).toBe(expected) +}) + test('interpolationSearch([2, 6, 8, 14, 122, 169], 144) => -1', () => { const array = [2, 6, 8, 14, 122, 169] const key = 144