Number of Substrings with Single Character Difference - Microsoft Top Interview Questions


Problem Statement :


You are given two lowercase alphabet strings s and t. Return the number of pairs of substrings across s and t such that if we replace a single character to a different character, it becomes a substring of t.

Constraints

0 ≤ n ≤ 100 where n is the length of s

0 ≤ m ≤ 100 where m is the length of t

Example 1

Input

s = "ab"

t = "db"

Output

4

Explanation

We can have the following substrings:



"a" changed to "d"

"a" changed to "b"

"b" changed to "d"

"ab" changed to "db"



Solution :



title-img




                        Solution in C++ :

int solve(string s, string t) {
    int m = s.length(), n = t.length();

    /*
     * dp[i][j][0] -> number of same substrings ending at the ith character in s and j th chaaracter
     * in t such that no change has been made to the string s 'yet'. dp[i][j][0] -> number of same
     * substrings ending at the ith character in s and j th chaaracter in t such that exactly one
     * change has been made to the string.
     */
    vector<vector<vector<int>>> dp(m + 1, vector<vector<int>>(n + 1, vector<int>(2)));

    for (int i = 1; i <= m; ++i) {       // ending at i - 1th character in s
        for (int j = 1; j <= n; ++j) {   // ending at the j - 1 th character in t
            if (s[i - 1] == t[j - 1]) {  // if the characters are same
                /*
                * number of equal substrings would be:
                * 1. With no change -> 1 + number of equal substrings ending at s[i - 2] and t[j -
                2] with no change 1 because s[i - 1] == t[j - 1], ie substring of length 1 is also
                valid
                * 2. With change -> number of equal substrings ending at s[i - 2] and t[j - 2] with
                exatly one change.
                */
                dp[i][j][0] = 1 + dp[i - 1][j - 1][0];
                dp[i][j][1] = dp[i - 1][j - 1][1];
            } else
                dp[i][j][1] = 1 +
                              dp[i - 1][j - 1]
                                [0];  // if charactes are not same then we have only one option, ie
                                      // to change it. So, number of equal substrings ending here ->
                                      // 1 + number of equal substrings ending at s[i - 1] and t[j -
                                      // 1] with no change. 1 because when s[i - 1] is changed to
                                      // t[j - 1] we have equal substring of length 1.
        }
    }

    // count all substrings ending at some s[i - 1] and t[j - 1] and with exactly one change
    int res = 0;
    for (int i = 0; i <= m; ++i) {
        for (int j = 0; j <= n; ++j) res += dp[i][j][1];
    }

    return res;
}
                    


                        Solution in Java :

import java.util.*;

class Solution {
    public int solve(String s, String t) {
        /*
            definitions :
                let string s = s1 s2 s3 ..... si-1 si si+1 ..... sm-2 sm-1 sm
                let string t = t1 t2 t3 ..... tj-1 tj tj+1 ..... tn-2 tn-1 tn
                LEFT[i][j] = max size equal substring ending at position i in string s and position
           j in string t when traversing s and t from left side RIGHT[i][j] = max size equal
           substring ending at position i in string s and position j in string t when traversing s
           and t from right side

            Base Cases :
                LEFT[0][0] = 0
                RIGH[M + 1][N + 1] = 0

            Transitive Equations :
                LEFT[i][j] = (1 + LEFT[i - 1][j - 1])   ; si == tj
                LEFT[i][j] = 0                          ; si != tj
                RIGHT[i][j] = (1 + RIGHT[i + 1][j + 1]) ; si == tj
                RIGHT[i][j] = 0                         ; si != tj

            Final Answer :
                count += (1 + LEFT[i - 1][j - 1] + RIGHT[i + 1][j + 1] + (LEFT[i - 1][j - 1] *
           RIGHT[i + 1][j + 1])) ; si != tj
        */
        int M = s.length(), N = t.length(), count = 0;
        int[][] LEFT = new int[M + 1][N + 1], RIGHT = new int[M + 2][N + 2];
        for (int i = 1; i <= M; i++) {
            for (int j = 1; j <= N; j++) {
                if (s.charAt(i - 1) == t.charAt(j - 1)) {
                    LEFT[i][j] = (1 + LEFT[i - 1][j - 1]);
                }
            }
        }
        for (int i = M; i >= 1; i--) {
            for (int j = N; j >= 1; j--) {
                if (s.charAt(i - 1) == t.charAt(j - 1)) {
                    RIGHT[i][j] = (1 + RIGHT[i + 1][j + 1]);
                } else {
                    count += (1 + LEFT[i - 1][j - 1] + RIGHT[i + 1][j + 1]
                        + (LEFT[i - 1][j - 1] * RIGHT[i + 1][j + 1]));
                }
            }
        }
        return count;
    }
}
                    


                        Solution in Python : 
                            
class Solution:
    def solve(self, s, t):
        ans = 0

        for i in range(len(s)):
            for j in range(len(t)):
                mismatches = 0
                for k in range(min(len(s) - i, len(t) - j)):
                    mismatches += s[i + k] != t[j + k]
                    if mismatches == 1:
                        ans += 1

        return ans
                    


View More Similar Problems

No Prefix Set

There is a given list of strings where each string contains only lowercase letters from a - j, inclusive. The set of strings is said to be a GOOD SET if no string is a prefix of another string. In this case, print GOOD SET. Otherwise, print BAD SET on the first line followed by the string being checked. Note If two strings are identical, they are prefixes of each other. Function Descriptio

View Solution →

Cube Summation

You are given a 3-D Matrix in which each block contains 0 initially. The first block is defined by the coordinate (1,1,1) and the last block is defined by the coordinate (N,N,N). There are two types of queries. UPDATE x y z W updates the value of block (x,y,z) to W. QUERY x1 y1 z1 x2 y2 z2 calculates the sum of the value of blocks whose x coordinate is between x1 and x2 (inclusive), y coor

View Solution →

Direct Connections

Enter-View ( EV ) is a linear, street-like country. By linear, we mean all the cities of the country are placed on a single straight line - the x -axis. Thus every city's position can be defined by a single coordinate, xi, the distance from the left borderline of the country. You can treat all cities as single points. Unfortunately, the dictator of telecommunication of EV (Mr. S. Treat Jr.) do

View Solution →

Subsequence Weighting

A subsequence of a sequence is a sequence which is obtained by deleting zero or more elements from the sequence. You are given a sequence A in which every element is a pair of integers i.e A = [(a1, w1), (a2, w2),..., (aN, wN)]. For a subseqence B = [(b1, v1), (b2, v2), ...., (bM, vM)] of the given sequence : We call it increasing if for every i (1 <= i < M ) , bi < bi+1. Weight(B) =

View Solution →

Kindergarten Adventures

Meera teaches a class of n students, and every day in her classroom is an adventure. Today is drawing day! The students are sitting around a round table, and they are numbered from 1 to n in the clockwise direction. This means that the students are numbered 1, 2, 3, . . . , n-1, n, and students 1 and n are sitting next to each other. After letting the students draw for a certain period of ti

View Solution →

Mr. X and His Shots

A cricket match is going to be held. The field is represented by a 1D plane. A cricketer, Mr. X has N favorite shots. Each shot has a particular range. The range of the ith shot is from Ai to Bi. That means his favorite shot can be anywhere in this range. Each player on the opposite team can field only in a particular range. Player i can field from Ci to Di. You are given the N favorite shots of M

View Solution →