Leetcode 744: Find Smallest Letter Greater Than Target

grid47
grid47
Exploring patterns and algorithms
Aug 24, 2024 5 min read

A string where the smallest letter greater than the target is found and highlighted with a soft glow.
Solution to LeetCode 744: Find Smallest Letter Greater Than Target Problem

You are given a sorted array letters containing lowercase English letters and a character target. Return the smallest character in letters that is lexicographically greater than target. If no such character exists, return the first character in letters.
Problem
Approach
Steps
Complexity
Input: The input consists of a sorted array of lowercase English characters `letters` and a character `target`. The array `letters` has at least two distinct characters.
Example: letters = ["b", "e", "h", "m", "t"], target = "a"
Constraints:
• 2 <= letters.length <= 10^4
• 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.
Output: Return the smallest character from `letters` that is greater than `target`. If no such character exists, return the first character in `letters`.
Example: For letters = ["b", "e", "h", "m", "t"], target = "a", the output is "b".
Constraints:
Goal: Find the smallest character in `letters` that is greater than `target`, or return the first character if no such character exists.
Steps:
• Iterate over the `letters` array to find the first character that is greater than `target`.
• If such a character is found, return it.
• If no such character is found, return the first character of `letters`.
Goal: The array `letters` is sorted and contains at least two different characters.
Steps:
• 2 <= letters.length <= 10^4
• letters[i] is a lowercase English letter.
• letters is sorted in non-decreasing order.
• target is a lowercase English letter.
Assumptions:
• The array `letters` is sorted in non-decreasing order and contains at least two distinct characters.
Input: For letters = ["b", "e", "h", "m", "t"], target = "a"
Explanation: The smallest character in `letters` that is greater than 'a' is 'b'.

Input: For letters = ["b", "e", "h", "m", "t"], target = "h"
Explanation: The smallest character in `letters` that is greater than 'h' is 'm'.

Input: For letters = ["a", "b", "d", "f"], target = "z"
Explanation: There is no character in `letters` greater than 'z', so we return the first character 'a'.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus