LeetCode 744: Find Smallest Letter Greater Than Target Solution

Master LeetCode problem 744 (Find Smallest Letter Greater Than Target), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

744. Find Smallest Letter Greater Than Target

Problem Explanation

Explanation

To solve this problem, we can perform a binary search on the given sorted array of characters. The key idea is to find the smallest character in the array that is greater than the target character. If such a character does not exist, we return the first character in the array.

  1. Initialize left to 0 and right to n-1, where n is the size of the input array letters.
  2. Perform binary search by updating mid as the middle index of the current range.
  3. Check if letters[mid] is greater than the target character. If true, update right to mid-1.
  4. If letters[mid] is less than or equal to the target character, update left to mid+1.
  5. Repeat steps 2-4 until left > right.
  6. If left is still within the bounds of the array, return letters[left]. Otherwise, return letters[0].

The time complexity of this solution is O(log n) where n is the size of the input array letters. The space complexity is O(1).

Solution Code

class Solution {
    public char nextGreatestLetter(char[] letters, char target) {
        int left = 0;
        int right = letters.length - 1;
        
        while (left <= right) {
            int mid = left + (right - left) / 2;
            if (letters[mid] <= target) {
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }
        
        return left < letters.length ? letters[left] : letters[0];
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 744 (Find Smallest Letter Greater Than Target)?

This page provides optimized solutions for LeetCode problem 744 (Find Smallest Letter Greater Than Target) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 744 (Find Smallest Letter Greater Than Target)?

The time complexity for LeetCode 744 (Find Smallest Letter Greater Than Target) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 744 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 744 in Java, C++, or Python.

Back to LeetCode Solutions