#744

Find Smallest Letter Greater Than Target

Easy
ArrayBinary SearchBinary SearchArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n)
O(log n)
Space
O(1)
O(1)
💡

Intuition

Time O(log n)Space O(1)

Since the letters are sorted, we can use binary search to find the smallest letter greater than the target efficiently. This reduces the time complexity significantly.

⚙️

Algorithm

5 steps
  1. 1Step 1: Initialize left pointer to 0 and right pointer to the length of letters.
  2. 2Step 2: While left pointer is less than right pointer, calculate mid index.
  3. 3Step 3: If the letter at mid index is less than or equal to the target, move the left pointer to mid + 1.
  4. 4Step 4: If the letter at mid index is greater than the target, move the right pointer to mid.
  5. 5Step 5: After the loop, return the letter at the left pointer, which will be the smallest letter greater than target.
solution.py9 lines
1def nextGreatestLetter(letters, target):
2    left, right = 0, len(letters)
3    while left < right:
4        mid = (left + right) // 2
5        if letters[mid] <= target:
6            left = mid + 1
7        else:
8            right = mid
9    return letters[left % len(letters)]

Complexity note: The time complexity is O(log n) due to binary search, which is much faster than linear search. The space complexity remains O(1) as we are using a constant amount of space.

  • 1Binary search is a powerful technique for searching in sorted arrays, significantly reducing time complexity.
  • 2Understanding the properties of sorted arrays can lead to more efficient algorithms.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.