#3106

Lexicographically Smallest String After Operations With Constraint

Medium
StringGreedyGreedyDynamic Programming
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)

The optimal solution uses a greedy approach to minimize the string lexicographically while keeping track of the distance. Instead of checking all characters for each position, we can directly compute the best character to change to based on the remaining distance.

⚙️

Algorithm

5 steps
  1. 1Step 1: Initialize an empty result string and a variable to track the total distance.
  2. 2Step 2: For each character in the input string, calculate the distance to 'a'.
  3. 3Step 3: If the distance is less than or equal to k, change the character to 'a' and reduce k by the distance.
  4. 4Step 4: If k is exhausted, keep the original character.
  5. 5Step 5: Continue until all characters are processed.
solution.py13 lines
1def distance(c1, c2):
2    return min((ord(c1) - ord(c2)) % 26, (ord(c2) - ord(c1)) % 26)
3
4def lexicographically_smallest_string(s, k):
5    result = ''
6    for char in s:
7        dist = distance(char, 'a')
8        if dist <= k:
9            result += 'a'
10            k -= dist
11        else:
12            result += char
13    return result

Complexity note: The complexity is O(n) because we only iterate through the string once, making a constant-time decision for each character.

  • 1Greedy approaches often yield optimal solutions for problems involving minimization or maximization under constraints.
  • 2Understanding the cyclic nature of character distances helps in efficiently calculating the required transformations.

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