#3798
Largest Even Number
EasyStringString ManipulationGreedy Algorithms
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
Find the last '2' in the string and return the prefix up to that point. This guarantees the largest even number.
⚙️
Algorithm
3 steps- 1Step 1: Find the last occurrence of '2' in s.
- 2Step 2: If found, return the substring from the start to that index (inclusive).
- 3Step 3: If not found, return an empty string.
solution.py3 lines
1def largest_even_number(s):
2 last_two = s.rfind('2')
3 return s[:last_two + 1] if last_two != -1 else ""ℹ
Complexity note: Finding the last index and slicing the string is linear in time.
- 1An even number must end with '2'.
- 2The largest number is formed by keeping the leftmost digits intact.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.