Open In App

Count ways to select two N sized Substrings differing by one letter

Improve
Improve
Like Article
Like
Save
Share
Report

Given a string str, the task is to find the number of ways two non-overlapping substrings of length N can be selected out of a string that differs by just one letter.

Examples:

Input: str = “abcd”, N = 1
Output: 6
Explanation: Possible non overlapping substrings pairs are (“a”, “b”), (“b”, “c”), (“c”, “d”), (“a”, “c”), (“a”, “d”) and (“b”, “d”).

Input: str = “abcb”, N = 2
Output: 1
Explanation: The only possible substring pair is (“ab”, “cb”).

Naive Approach: To solve the problem follow the below idea:

The approach is to find the number of ways two substrings of a given string, “str”, of length “n” can differ by just one letter. The code first initializes a variable “count” to store the number of ways and a variable “len” to store the length of the given string. Then, the code uses two nested for loops to iterate through all possible substrings of length “n” within the given string. For each pair of substrings found, the code compares each letter of the two substrings. If the two substrings differ by just one letter, the code increases the count by 1. Finally, the code returns the count as the result.

Follow the steps of the code:

  • Declare a variable “count” and initialize it with 0. This variable will be used to store the number of ways the substrings differ by just one letter.
  • Use a for loop to iterate through all substrings of length “N” in the input string “str”. The loop starts from index 0 and goes up to the (length of the string – N)
    • Within the for loop, use the substring method to store the first substring in a variable “s1”.
  • Use another for loop to iterate through all substrings of length “N” starting from the (i + 1)th position.
    • Within the second for loop, use the substring method to store the second substring in a variable “s2”.
  • Declare a variable “diff” and initialize it with 0. This variable will be used to store the number of different letters between the two substrings.
  • Use another for loop to iterate through the letters of the two substrings.
    • Within the third for loop, compare each letter of the two substrings. 
    • If they are different, increment the “diff” variable by 1.
  • Check if the value of “diff” is equal to 1, if so increase the “count” variable by 1.
  • Exit the second for loop
  • Exit the first for loop
  • Return the value of “count”

Below is the implementation for the above approach:

C++14




// C++ code for the above approach:
#include <bits/stdc++.h>
using namespace std;
 
int countWays(string str, int n)
{
    int len = str.length();
 
    // To store the number of ways
    int count = 0;
 
    // Iterate through all the
    // substrings of length n
    for (int i = 0; i <= len - n; i++) {
 
        // To store the first substring
        string s1 = str.substr(i, n);
 
        // Iterate through all the
        // substrings of length n starting
        // from (i + 1)th position
        for (int j = i + 1; j <= len - n; j++) {
 
            // To store the second substring
            string s2 = str.substr(j, n);
 
            // Check if the two substrings
            // differ by just one letter
            int diff = 0;
            for (int k = 0; k < n; k++)
                if (s1[k] != s2[k])
                    diff++;
 
            // If the two substrings differ
            // by just one letter, increase
            // the count
            if (diff == 1)
                count++;
        }
    }
 
    return count;
}
 
// Driver code
int main()
{
    string str = "abcb";
    int N = 2;
 
    // Function Call
    cout << countWays(str, N);
    return 0;
}


Java




// Java code for the above approach:
import java.util.*;
 
class GFG {
    public static int countWays(String str, int n)
    {
        int len = str.length();
 
        // To store the number of ways
        int count = 0;
 
        // Iterate through all the
        // substrings of length n
        for (int i = 0; i <= len - n; i++) {
 
            // To store the first substring
            String s1 = str.substring(i, i + n);
 
            // Iterate through all the
            // substrings of length n starting
            // from (i + 1)th position
            for (int j = i + 1; j <= len - n; j++) {
 
                // To store the second substring
                String s2 = str.substring(j, j + n);
 
                // Check if the two substrings
                // differ by just one letter
                int diff = 0;
                for (int k = 0; k < n; k++) {
                    if (s1.charAt(k) != s2.charAt(k)) {
                        diff++;
                    }
                }
 
                // If the two substrings differ
                // by just one letter, increase
                // the count
                if (diff == 1) {
                    count++;
                }
            }
        }
        return count;
    }
 
    // Driver code
    public static void main(String[] args)
    {
        Scanner sc = new Scanner(System.in);
        String str = "abcb";
        int N = 2;
 
        // Function Call
        System.out.println(countWays(str, N));
    }
}
// This Code is Contributed by Prasad Kandekar(prasad264)


Python




# Java code for the above approach
def countWays(str, n):
       
    len_ = len(str)
     
    # To store the number of ways
    count = 0
     
    # Iterate through all the
    # substrings of length n
    for i in range(len_ - n + 1):
           
        # To store the first substring
        s1 = str[i:i+n]
         
        # Iterate through all the
        # substrings of length n starting
        # from (i + 1)th position
        for j in range(i + 1, len_ - n + 1):
           
              # To store the second substring
            s2 = str[j:j+n]
             
            # Check if the two substrings
            # differ by just one letter
            diff = 0
            for k in range(n):
                if s1[k] != s2[k]:
                    diff += 1
                     
            # If the two substrings differ
            # by just one letter, increase
            # the count
            if diff == 1:
                count += 1
    return count
   
# Driver Code
str_ = "abcb"
N = 2
 
# Function Call
print(countWays(str_, N))
 
# This Code is Contributed by Prasad Kandekar(prasad264)


C#




// C# code for the above approach:
using System;
 
public class GFG {
    static int CountWays(string str, int n)
    {
        int len = str.Length;
       
          // To store the number of ways
        int count = 0;
 
          // Iterate through all the
        // substrings of length n
        for (int i = 0; i <= len - n; i++) {
               
              // To store the first substring
            string s1 = str.Substring(i, n);
           
              // Iterate through all the
            // substrings of length n starting
            // from (i + 1)th position
            for (int j = i + 1; j <= len - n; j++) {
               
                  // To store the second substring
                string s2 = str.Substring(j, n);
               
                  // Check if the two substrings
                // differ by just one letter
                int diff = 0;
                for (int k = 0; k < n; k++) {
                    if (s1[k] != s2[k])
                        diff++;
                }
                if (diff == 1)
                    count++;
            }
        }
 
        return count;
    }
 
      // Driver code
    static void Main(string[] args)
    {
        string str = "abcb";
        int N = 2;
           
          // Function Call
        Console.WriteLine(CountWays(str, N));
    }
}
// This Code is Contributed by Prasad Kandekar(prasad264)


Javascript




// Javascript code for the above approach:
function countWays( str,  n)
{
    let len = str.length;
 
    // To store the number of ways
    let count = 0;
 
    // Iterate through all the
    // substrings of length n
    for (let i = 0; i <= len - n; i++) {
 
        // To store the first substring
        let s1 = str.substr(i);
 
        // Iterate through all the
        // substrings of length n starting
        // from (i + 1)th position
        for (let j = i + 1; j <= len - n; j++) {
 
            // To store the second substring
            let s2 = str.substr(j);
 
            // Check if the two substrings
            // differ by just one letter
            let diff = 0;
            for (let k = 0; k < n; k++)
                if (s1[k] != s2[k])
                    diff++;
 
            // If the two substrings differ
            // by just one letter, increase
            // the count
            if (diff == 1)
                count++;
        }
    }
 
    return count;
}
 
// Driver code
let str = "abcb";
let N = 2;
 
// Function Call
console.log(countWays(str, N));
   
  // this code is contributed by poojaagarwal2.


Output

1




Time Complexity: O((len – N)*(len – N) * N), where N is the required substring length and len is the length of string str.
Auxiliary Space: O(1)

Another Approach:

  1. The main function initializes a string “str” with the value “abcb” and an integer “N” with the value 2.
  2. The main function calls the “countWays” function with “str” and “N” as parameters.
  3. The “countWays” function first calculates the length of the input string “str”.
  4. The function initializes a variable “count” to store the number of ways to form substrings and a variable “diff” to store the count of different characters in the current substring.
  5. The function then initializes the first substring “s1” with the first “N” characters of the input string “str”.
  6. The function then counts the different characters in the first substring “s1” by comparing each character with the corresponding character “N” positions to the right of it in the input string “str”. If the characters are different, the “diff” variable is incremented.
  7. If the “diff” variable is equal to 1, it means that there is only one different character in the first substring, so the “count” variable is incremented.
  8. The function then slides the window from left to right by iterating through the input string “str” from the (N+1)th position to the end of the string.
  9. In each iteration, the function removes the leftmost character from the previous substring “s1” and adds the rightmost character from the new substring “s1”. The “diff” variable is updated accordingly.
  10. If the “diff” variable is equal to 1, it means that there is only one different character in the current substring, so the “count” variable is incremented.
  11. After iterating through all possible substrings, the function returns the “count” variable.
  12. Finally, the main function prints the value returned by the “countWays” function, which in this case is 2. This means that there are two ways to form substrings of length 2 from the input string “abcb” such that there is only one different character in each substring. The two possible substrings are “ab” and “bc”.

Below is the implementation of the above approach:

C++




#include <bits/stdc++.h>
using namespace std;
 
int countWays(string str, int N) {
    int len = str.length();
 
    // To store the number of ways
    int count = 0;
 
    // Initialize the count of
    // different characters
    int diff = 0;
 
    // Initialize the first substring
    string s1 = str.substr(0, N);
 
    // Count the different characters
    // in the first substring
    for (int i = 0; i < N; i++) {
        if (s1[i] != str[i + N]) {
            diff++;
        }
    }
 
    // If the count of different characters
    // is exactly one, increment the count
    if (diff == 1) {
        count++;
    }
 
    // Slide the window from left to right
    for (int i = 1; i <= len - N; i++) {
        // Remove the leftmost character
        if (s1[i - 1] != str[i - 1]) {
            diff--;
        }
 
        // Add the rightmost character
        if (s1[N - 1] != str[i + N - 1]) {
            diff++;
        }
 
        // Update the first substring
        s1 = str.substr(i, N);
 
        // If the count of different characters
        // is exactly one, increment the count
        if (diff == 1) {
            count++;
        }
    }
 
    return count;
}
 
// Driver code
int main() {
    string str = "abcb";
    int N = 2;
 
    // Function Call
    cout << countWays(str, N);
    return 0;
}


Java




import java.util.*;
 
class Main {
    public static int countWays(String str, int N) {
        int len = str.length();
 
        // To store the number of ways
        int count = 0;
 
        // Initialize the count of
        // different characters
        int diff = 0;
 
        // Initialize the first substring
        String s1 = str.substring(0, N);
 
        // Count the different characters
        // in the first substring
        for (int i = 0; i < N; i++) {
            if (s1.charAt(i) != str.charAt(i + N)) {
                diff++;
            }
        }
 
        // If the count of different characters
        // is exactly one, increment the count
        if (diff == 1) {
            count++;
        }
 
        // Slide the window from left to right
        for (int i = 1; i <= len - N; i++) {
            // Remove the leftmost character
            if (s1.charAt(i - 1) != str.charAt(i - 1)) {
                diff--;
            }
 
            // Add the rightmost character
            if (s1.charAt(N - 1) != str.charAt(i + N - 1)) {
                diff++;
            }
 
            // Update the first substring
            s1 = str.substring(i, i + N);
 
            // If the count of different characters
            // is exactly one, increment the count
            if (diff == 1) {
                count++;
            }
        }
 
        return count;
    }
 
    // Driver code
    public static void main(String[] args) {
        String str = "abcb";
        int N = 2;
 
        // Function Call
        System.out.println(countWays(str, N));
    }
}


Python3




def countWays(str, N):
    le = len(str)
     
    # To store the number of ways
    count = 0
     
    # Initialize the count of
    # different characters
    diff = 0
     
    # Initialize the first substring
    s1 = str[0:N]
     
    # Count the different characters
    # in the first substring
    for i in range(N):
        if s1[i] != str[i + N]:
            diff += 1
     
    # If the count of different characters
    # is exactly one, increment the count
    if diff == 1:
        count += 1
         
    # Slide the window from left to right
    for i in range(1, le - N + 1):
        # Remove the leftmost character
        if s1[i - 1] != str[i - 1]:
            diff -= 1
        # Add the rightmost character
        if s1[N - 1] != str[i + N - 1]:
            diff += 1
        # Update the first substring
        s1 = str[i:i + N]
         
        # If the count of different characters
        # is exactly one, increment the count
        if diff == 1:
            count += 1
    return count
# Test case
str = "abcb"
N = 2
print(countWays(str, N))


C#




using System;
 
class GFG
{
    static int CountWays(string str, int N)
    {
        int len = str.Length;
       
          // To store the number of ways
        int count = 0;
       
          // Initialize the count of
        // different characters
        int diff = 0;
       
          // Initialize the first substring
        string s1 = str.Substring(0, N);
 
          // Count the different characters
        // in the first substring
        for (int i = 0; i < N; i++)
        {
            if (s1[i] != str[i + N])
            {
                diff++;
            }
        }
 
          // If the count of different characters
        // is exactly one, increment the count
        if (diff == 1)
        {
            count++;
        }
 
          // Slide the window from left to right
        for (int i = 1; i <= len - N; i++)
        {
            // Remove the leftmost character
            if (s1[i - 1] != str[i - 1])
            {
                diff--;
            }
 
              // Add the rightmost character
            if (s1[N - 1] != str[i + N - 1])
            {
                diff++;
            }
 
              // Update the first substring
            s1 = str.Substring(i, N);
           
           
            // If the count of different characters
                // is exactly one, increment the count
            if (diff == 1)
            {
                count++;
            }
        }
 
        return count;
    }
     
      // Driver code
    static void Main(string[] args)
    {
        string str = "abcb";
        int N = 2;
 
        Console.WriteLine(CountWays(str, N));
    }
}


Javascript




function countWays(str, N) {
    let le = str.length;
     
    // To store the number of ways
    let count = 0;
     
    // Initialize the count of
    // different characters
    let diff = 0;
     
    // Initialize the first substring
    let s1 = str.substring(0, N);
     
    // Count the different characters
    // in the first substring
    for (let i = 0; i < N; i++) {
        if (s1[i] !== str[i + N]) {
            diff += 1;
        }
    }
     
    // If the count of different characters
    // is exactly one, increment the count
    if (diff === 1) {
        count += 1;
    }
     
    // Slide the window from left to right
    for (let i = 1; i < le - N + 1; i++) {
         
        // Remove the leftmost character
        if (s1[i - 1] !== str[i - 1]) {
            diff -= 1;
        }
        // Add the rightmost character
        if (s1[N - 1] !== str[i + N - 1]) {
            diff += 1;
        }
        // Update the first substring
        s1 = str.substring(i, i + N);
         
        // If the count of different characters
        // is exactly one, increment the count
        if (diff === 1) {
            count += 1;
        }
    }
    return count;
}
 
// Test case
let str = "abcb";
let N = 1;
console.log(countWays(str, N));


Output

1




Time complexity: O(len*N)

Auxiliary Space: O(n)

Related Articles:



Last Updated : 16 Aug, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads