
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find Smallest Letter Greater Than Target in JavaScript
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 −
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
Advertisements