DDSA Solutions

1844. Replace All Digits with Characters

Time: O(n)
Space: O(n)
Advertisement

Approach

For each even-index letter, shift the following digit to produce the target char.

Key Techniques

String

String problems range from simple character counting to complex pattern matching. Common approaches include two pointers, sliding window, prefix hashing, and the KMP algorithm. In C#, strings are immutable — use StringBuilder for efficient concatenation inside loops.

1844.cs
C#
// Approach: For each even-index letter, shift the following digit to produce the target char.
// Time: O(n) Space: O(n)

public class Solution
{
    public string ReplaceDigits(string s)
    {
        char[] chars = s.ToCharArray();
        for (int i = 1; i < chars.Length; i += 2)
            chars[i] = (char)(chars[i] + chars[i - 1] - '0');

        return new string(chars);
    }
}
Advertisement
Was this solution helpful?