#3403

Find the Lexicographically Largest String From the Box I

Medium
Two PointersStringEnumerationSubstring SearchGreedy Algorithms
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal 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
  1. 1Step 1: Initialize maxStr as an empty string.
  2. 2Step 2: Loop through the string and check substrings of length up to n - numFriends + 1.
  3. 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.