#1844

Replace All Digits with Characters

Easy
StringCharacter ManipulationString Processing
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 approach is similar to the brute-force method but avoids unnecessary calculations by directly calculating the new character based on the ASCII values. This allows us to achieve the desired result in linear time.

⚙️

Algorithm

4 steps
  1. 1Step 1: Initialize an empty result string.
  2. 2Step 2: Loop through each character in the string `s`.
  3. 3Step 3: If the index is even, append the character to the result.
  4. 4Step 4: If the index is odd, calculate the new character using ASCII values and append it to the result.
solution.py9 lines
1def replaceDigits(s):
2    result = ''
3    for i in range(len(s)):
4        if i % 2 == 0:
5            result += s[i]
6        else:
7            new_char = chr(ord(s[i - 1]) + int(s[i]))
8            result += new_char
9    return result

Complexity note: The optimal solution runs in linear time because we only traverse the string once, performing constant-time operations for each character.

  • 1Each digit's replacement depends solely on the preceding character.
  • 2ASCII values can be used for efficient character shifting.

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