Find the Smallest Letter Greater Than Target

Easy
42
3
65.1% Acceptance

In this lab, you will implement a function nextGreatestLetter that finds the smallest character greater than a given target character from an array of characters. The array is sorted in non-decreasing order, and there are at least two different characters in it. If such a character does not exist, return the first character in the given array.

You are given an array of sorted characters letters and a character target. Your task is to return the smallest character in letters that is lexicographically greater than target. In other words, return the next greater character in the sorted array after the target character.

/** * @param {character[]} letters * @param {character} target * @return {character} */ export function nextGreatestLetter(letters, target) { }

Example

Example 1:

Input: letters = ["c","f","j"], target = "a"

Output: "c"

Explanation: The smallest character that is lexicographically greater than 'a' in the array letters is 'c'.

Example 2:

Input: letters = ["c","f","j"], target = "c"

Output: "f"

Explanation: The smallest character that is lexicographically greater than 'c' in the array letters is 'f'.

Example 3:

Input: letters = ["x","x","y","y"], target = "z"

Output: "x"

Explanation: There are no characters in the array letters that are lexicographically greater than 'z', so we return the first character 'x'.

Constraints

  • 2 <= letters.length <= 104
  • letters[i] is a lowercase English letter.
  • letters is sorted in non-decreasing order.
  • letters contains at least two different characters.
  • target is a lowercase English letter.

Challenges

  1. Export a function named nextGreatestLetter that takes two arguments: an array of characters letters and a character target. The function should return a character.
  2. The function must find the smallest character in the array letters that is lexicographically greater than the target character. The array is non-decreasing, and there are at least two different characters in it.
  3. If no such character is found, the function should return the first character in the array.