logoNEURAL COOK
SearchAll PostsTagsNotesAuthor
logoNEURAL COOK

A posts created with Next.js and Tailwind.css

Explore

  • All posts
  • Notes
  • Snippets
  • Tags
  • RSS feed

Connect

instagramtwitterfacebookyoutubelinkedinmailgithub

© 2026 VIKI. All rights reserved.

Built with
Contents
Table Of Contents
2. Add Two Numbers3. Longest Substring Without Repeating Characters5. Longest Palindromic Substring8. String to Integer (atoi)11. Container With Most Water15. 3Sum17. Letter Combinations of a Phone Number19. Remove Nth Node From End of List22. Generate Parentheses33. Search in Rotated Sorted Array34. Find First and Last Position of Element in Sorted Array48. Rotate Image49. Group Anagrams50. Pow(x, n)53. Maximum Subarray54. Spiral Matrix56. Merge Intervals61. Rotate List73. Set Matrix Zeroes74. Search a 2D Matrix75. Sort Colors78. Subsets137. Single Number II138. Copy List with Random Pointer150. Evaluate Reverse Polish Notation151. Reverse Words in a String153. Find Minimum in Rotated Sorted Array155. Min Stack162. Find Peak Element169. Majority Element198. House Robber207. Course Schedule215. Kth Largest Element in an Array227. Basic Calculator II236. Lowest Common Ancestor of a Binary Tree237. Delete Node in a Linked List238. Product of Array Except Self451. Sort Characters By Frequency540. Single Element in a Sorted Array560. Subarray Sum Equals K636. Exclusive Time of Functions875. Koko Eating Bananas1011. Capacity To Ship Packages Within D Days1101. The Earliest Moment When Everyone Become Friends1283. Find the Smallest Divisor Given a Threshold2140. Solving Questions With Brainpower3169. Count Days Without Meetings3481. Apply Substitutions
Code Scratch/leetcode/medium

3481. Apply Substitutions

2 min read
On this pageIntuition
IntuitionComplexityCode

# Intuition

We are given placeholders like %a% and a map of replacements. Since a replacement can itself contain other placeholders, we must recursively resolve each key until we get plain text.\

To avoid recomputing the same replacements again and again, we use memoization.

# Complexity

Space ComplexityTime Complexity
O(1)\text{O}(1)O(1)O(N∗M)\text{O}(N*M)O(N∗M)

# Code

// Memoization map to store already resolved substitutions
Map&lt;Character, String&gt; resolvedMapping = new HashMap<>();
 
// Recursive function to resolve a placeholder completely
public String resolve(Map&lt;Character, String&gt; replacementsMap, char key) {
    if (resolvedMapping.containsKey(key)) 
        return resolvedMapping.get(key);
 
    StringBuilder resolvedString = new StringBuilder();
    String originalString = replacementsMap.get(key);
 
    for (int index = 0; index &lt; originalString.length(); ) {
        // If a placeholder pattern like %x% is found
        if (originalString.charAt(index) == '%' && originalString.charAt(index + 2) == '%') {
            char innerKey = originalString.charAt(index + 1);
            resolvedString.append(resolve(replacementsMap, innerKey));
            index += 3; // Skip the %x%
        } else {
            resolvedString.append(originalString.charAt(index));
            index++;
        }
    }
 
    // Store resolved result for future use
    resolvedMapping.put(key, resolvedString.toString());
    return resolvedMapping.get(key);
}
 
// Main function to apply all substitutions
public String applySubstitutions(List&lt;List<String&gt;&gt; replacements, String text) {
    // Prepare the replacement map
    Map&lt;Character, String&gt; replacementsMap = new HashMap<>();
    for (List&lt;String&gt; replacement : replacements) {
        replacementsMap.put(replacement.get(0).charAt(0), replacement.get(1));
    }
 
    StringBuilder finalResult = new StringBuilder();
    for (int index = 0; index < text.length(); ) {
        // If a placeholder pattern like %x% is found
        if (text.charAt(index) == '%' && text.charAt(index + 2) == '%') {
            char key = text.charAt(index + 1);
            finalResult.append(resolve(replacementsMap, key));
            index += 3; // Skip the %x%
        } else {
            finalResult.append(text.charAt(index));
            index++;
        }
    }
 
    return finalResult.toString();
}
 
←Previous3169. Count Days Without MeetingsNext→189. Rotate Array (Approach 2 )

On this page

IntuitionComplexityCode