 Open in App
Not now

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

• Last Updated : 07 Feb, 2023

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 ` `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)

Related Articles:

My Personal Notes arrow_drop_up
Related Articles