#1625
Lexicographically Smallest String After Applying Operations
MediumStringDepth-First SearchBreadth-First SearchEnumerationDepth-First SearchBreadth-First SearchEnumeration
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)
The optimal solution leverages the fact that we can generate all possible strings by focusing on the even and odd indices separately. By applying the add operation strategically and using rotations, we can minimize the number of generated strings and efficiently find the smallest one.
⚙️
Algorithm
3 steps- 1Step 1: Generate all possible values for the odd indices by applying the add operation up to 10 times (since digits cycle from 0 to 9).
- 2Step 2: For each generated odd index configuration, rotate the string and check all configurations.
- 3Step 3: Keep track of the smallest string encountered.
solution.py18 lines
1# Full working Python code
2from itertools import product
3
4def lexicographically_smallest_string(s, a, b):
5 n = len(s)
6 odd_indices = [int(s[i]) for i in range(1, n, 2)]
7 even_indices = [s[i] for i in range(0, n, 2)]
8 smallest = s
9 for add_ops in product(range(10), repeat=len(odd_indices)):
10 new_odd = [(odd + a * op) % 10 for odd, op in zip(odd_indices, add_ops)]
11 new_string = ''.join(even_indices[i] + str(new_odd[i]) for i in range(len(new_odd)))
12 for rotation in range(n):
13 rotated = new_string[rotation:] + new_string[:rotation]
14 smallest = min(smallest, rotated)
15 return smallest
16
17# Example usage
18print(lexicographically_smallest_string('5525', 9, 2))ℹ
Complexity note: The time complexity is O(n) because we efficiently generate possible strings by focusing on odd indices and then rotating them, leading to a linear growth in operations based on the string length.
- 1The operations can be applied in any order, leading to a combinatorial explosion of possibilities.
- 2Focusing on odd and even indices separately helps reduce the complexity.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.