Similar Problems

Similar Problems not available

Find And Replace In String - Leetcode Solution


  • google

LeetCode:  Find And Replace In String Leetcode Solution

Difficulty: Medium

Topics: string sorting array  

Problem Statement:

You are given a string s and two integers left and right representing the indices of the first and last characters of a contiguous substring of s.

You want to perform the following action on s:

If the substring doesn't contain any '0's, then reverse it.
Otherwise, replace all the '1's in the substring with '0's and all the '0's with '1's.

Return the resulting string.


The solution to this problem is relatively easy. We just need to perform the steps as mentioned in the problem statement.

To perform these steps, we first get the substring from the given indices using the substring() function. Then we check if the substring contains any '0's or not.

If it does not contain any '0's, then we reverse the substring using the reverse() function.

If it contains '0's, then we replace all the '1's with '0's and all the '0's with '1's using the replace() function.

Finally, we concatenate the modified substring with the original string (excluding the substring) to get the resulting string.

The detailed implementation of the above approach is given below:

class Solution { public: string findReplaceString(string s, vector<int>& indices, vector<string>& sources, vector<string>& targets) { int n = s.length(); string res = "";

    // Create a map to store the indices and corresponding pairs of sources and targets
    unordered_map<int, pair<string, string>> mp;
    for (int i = 0; i < indices.size(); i++) {
        mp[indices[i]] = make_pair(sources[i], targets[i]);

    for (int i = 0; i < n; ++i) {
        if (mp.count(i)) {
            auto [source, target] = mp[i];
            string temp = s.substr(i, source.length());
            if (temp == source) {
                res += target;
                i += source.length() - 1;
        res += s[i];
    return res;


Time Complexity: O(n)

Space Complexity: O(n)

Find And Replace In String Solution Code