Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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'.
Problem Example
If the input array and letter are:
const arr = ["c", "f", "j"]; const target = "a";
Then the output should be:
"c"
Solution Using Binary Search
Since the array is sorted, we can use binary search to efficiently find the smallest letter greater than the target:
const arr = ["c", "f", "j"];
const target = "a";
const findNearestLetter = (arr = [], target = '') => {
let left = 0;
let right = arr.length - 1;
while (left
c
Testing Different Cases
Let's test the function with various scenarios including the wrap-around case:
const findNearestLetter = (arr = [], target = '') => {
let left = 0;
let right = arr.length - 1;
while (left
Target 'a' in ['c', 'f', 'j']: c
Target 'f' in ['c', 'f', 'j']: j
Target 'z' in ['a', 'b', 'c']: a
Target 'd' in ['c', 'f', 'j']: f
How It Works
The algorithm uses binary search with the following logic:
- Compare the middle element with the target
- If middle element is less than or equal to target, search the right half
- Otherwise, search the left half
- When the loop ends, `left` points to the first element greater than target
- If `left` equals array length, wrap around to the first element
Time Complexity
The time complexity is O(log n) due to binary search, making it efficient for large sorted arrays. The space complexity is O(1) as we only use a constant amount of extra space.
Conclusion
This binary search approach efficiently finds the smallest letter greater than the target in a sorted array. The wrap-around feature handles cases where no letter is greater than the target by returning the first letter in the array.
