Find Smallest Letter Greater Than Target in JavaScript

JavascriptWeb DevelopmentFront End Technology

Suppose we are given an array of sorted characters letters containing only lowercase letters. And given a target letter target.

We are required to write a JavaScript function that takes in the array as the first argument and the letter as the second. The function is supposed to find the smallest element in the list that is larger than the given target.

We have to keep in mind that letters also wrap around. For example, if the target is target = 'z' and letters = ['a', 'b'], the answer is 'a'.

For Example −

If the input array and letter are −

const arr = ["c", "f", "j"];
const target = "a";

Then the output should be −

const output: "c";

Example

The code for this will be −

 Live Demo

const arr = ["c", "f", "j"];
const target = "a";
const findNearestLetter = (arr = [], target = '') => {
   let left = 0;
   let right = arr.length - 1;
   while (left <= right) {
      let mid = left + (right - left) / 2;
      if (arr[mid] <= target) {
         left ++;
      } else {
         right --;
      };
   };
   if (left == arr.length) {
      return arr[0];
   };
   return arr[left];
};
console.log(findNearestLetter(arr, target));

Output

And the output in the console will be −

c
raja
Published on 27-Feb-2021 06:06:39
Advertisements