#3403
Find the Lexicographically Largest String From the Box I
MediumTwo PointersStringEnumerationSubstring SearchGreedy 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)
Instead of generating all splits, we can find the largest substring of length up to n - numFriends + 1 starting from each index. This reduces unnecessary computations.
⚙️
Algorithm
3 steps- 1Step 1: Initialize maxStr as an empty string.
- 2Step 2: Loop through the string and check substrings of length up to n - numFriends + 1.
- 3Step 3: Update maxStr if a larger substring is found.
solution.py7 lines
1def largestSubstring(word, numFriends):
2 max_str = ""
3 n = len(word)
4 for i in range(n):
5 for j in range(i + 1, min(n, i + n - numFriends + 1)):
6 max_str = max(max_str, word[i:j])
7 return max_strℹ
Complexity note: We only check substrings of limited length, leading to linear time complexity.
- 1Focus on substring lengths based on numFriends.
- 2Lexicographical comparison can be efficiently managed.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.