×

Interleaving string in Java

If the string Str3 contains all of the characters from Str1 and Str2, it is considered interleaving Str1 and Str2. Keep in mind that the order of all characters in individual strings is maintained.

Example 1

Input: Str1 = "ppqrr", Str2 = "wqqrp" and Str3 = "ppwqqrqrpr"

Output: String 3 is an interleaving string.

Explanation: "pp" (from Str1) + "wqqr" (from Str2) + "qr" (from Str1) + "p" (from Str2) + "r" (from Str1)

Example 2

Input: Str1 = "ffzjj", Str2 = "uzzjf", Str3 = "ffuzzzfjjj"

Output: String 3 is not an interleaving string.

Explanation: Str3 cannot be obtained by combining Str1 and Str2.

Problem Description

Given three strings, Str1, Str2, and Str3, develop a program that determines if Str3 is an interleaving of Str1 and Str2.

Problem-solving Approach

The following three ways can be used to solve the problem:

  • Brute Force Approach
  • Using 2D Dynamic Programming
  • Using 1D Dynamic Programming

Brute Force Approach

In this technique, we must keep the following two factors in mind:

  • If the first character of Str3 matches the first character of Str1, we forward to the next character in Str1 and Str3 and call the function repeatedly.
  • If the first character of Str3 matches the first character of Str2, we forward to the next character in Str2 and Str3 and call the function repeatedly.

Steps to Resolve the Issue

  1. First, we examine the base case. If Str1, Str2, and Str3 are empty, return true since empty Str3 is a combination of Str1 and Str2.
  2. Return false if Str3 is empty or Str1 or Str2 is not. This indicates that length(Str3) is less than length(Str1) + length (Str2).
    • If none of the preceding two circumstances is satisfied, go to the next two conditions:
    • If Str3[0] == Str1[0], look for Str1[1...], Str2, and Str3[1...].
    • If Str3[0] == Str2[0], then look for Str1, Str2[1...], and Str3[1...].
    • Return true if any of the two possibilities becomes true; otherwise, return false.

Let's set the following strategy into action in a function.

bool isInterleaved( char[] S1, char S2, char S3)   
{   
//base Case: whenever all strings are empty.
if (not (len(S1) != 0 or len(S2) != 0 or len(S3) != 0) )  
return true  
if (len(S3) == 0)   
return false  
return ((S3[0] == S1[0]) and isInterleaved(S1 + 1, S2, S3 + 1))  
or ((S3[0] == S2[0]) and isInterleaved(S1, S2 + 1, S3 + 1))  
}  

Complexity

The following solution has an O(n2) time complexity since each Str3 character has two alternatives. Because we did not consider recursion stack space in this technique, the space complexity is O(1).

Using 2D Dynamic Programming

First, make a 2D Boolean array called DP[]. It is a prefix of Str3 formed by the interleaving of prefixes of strings Str1 and Str2 with lengths (a+1) and (b+1), respectively.

 In this array, DP[a][b] shows whether it is feasible to obtain a substring of length (a+b+2).

The DP table generally indicates whether str3 is interleaving at the (a+b)-th index when S1 is at the a-th position, and S2 is at the b-th index. The 0th index represents an empty string. The 0th index represents the empty string. We can therefore conclude:

  • If str1 and str2 are both empty, str3 will also be empty. As a result, we might think of it as interleaving.
  • Suppose just str1 is an empty string, the previous str2 position is interleaving, and the current str2 position character is the same as the str3 current position character. In that case, it will be regarded as interleaving.
  • If str2 is empty, the same thing happens. When both str1 and str2 are not empty, we arrive at a, b from a-1, b, and if a-1, b is already interleaving and a and current str3 position are equal, they are interleaving string. If we get to a, b from a, b-1, and if a, b-1 is already interleaving, and b and the current str3 location are identical, then it is also interleaving.

Steps to resolve the problem

  • Make a 2D boolean DP[] array with dimensions u+1 and v+1. Where u and n denote the lengths of Str1 and Str2.
  • Fill up the DP table by comparing the characters of Str1, Str2, and Str3 in the appropriate order.
  • Return DP[u][v]

InterleavingString.java

public class InterleavingString  
{  
public static boolean isInterleave(String s1, String s2, String s3)   
{  
if (s3.length() != s1.length() + s2.length())   
{  
return false;  
}  
boolean dp[][] = new boolean[s1.length() + 1][s2.length() + 1];  
for (int a = 0; a <= s1.length(); a++)   
{  
for (int b = 0; b <= s2.length(); b++)   
{  
if (a == 0 && b == 0)   
{  
dp[a][b] = true;  
}   
else if (a == 0)   
{  
dp[a][b] = dp[a][b - 1] && s2.charAt(b - 1) == s3.charAt(a + b - 1);  
}   
else if (b == 0)   
{  
dp[a][b] = dp[a - 1][b] && s1.charAt(a - 1) == s3.charAt(a + b - 1);  
}   
else   
{  
dp[a][b] = (dp[a - 1][b] && s1.charAt(a - 1) == s3.charAt(a + b - 1)) || (dp[a][b - 1] && s2.charAt(b - 1) == s3.charAt(a + b - 1));  
}  
}  
}  
return dp[s1.length()][s2.length()];  
}  
public static void main(String args[])  
{  
System.out.println(isInterleave("ppqrr", "wqqrp", "ppwqqrqrpr"));  
}  
}

Output:

Interleaving string in Java

Complexity

The time and space complexity of the preceding technique is O(u*v). Where u and v are the lengths of the strings

Using 1D Dynamic Programming

The above technique has an O(u*v) time and space complexity. Where u and v are the string lengths, The method is the same as described earlier. The only difference is that we just utilized a 1D array to hold the results of the supplied string's prefixes, which we then processed. The benefit of utilizing a 1D array is that we only need to update the array's element dp[a] when necessary by using dp[a-1] and the previous value of dp[a].

InterleavingString .java

public class InterleavingString  
{  
public static boolean isInterleave(String s1, String s2, String s3)   
{  
if (s3.length() != s1.length() + s2.length())   
{  
return false;  
}  
boolean dp[][] = new boolean[s1.length() + 1][s2.length() + 1];  
for (int a = 0; a <= s1.length(); a++)   
{  
for (int b = 0; b <= s2.length(); b++)   
{  
if (a == 0 && b == 0)   
{  
dp[a][b] = true;  
}   
else if (a == 0)   
{  
dp[a][b] = dp[a][b - 1] && s2.charAt(b - 1) == s3.charAt(a + b - 1);  
}   
else if (b == 0)   
{  
dp[a][b] = dp[a - 1][b] && s1.charAt(a - 1) == s3.charAt(a + b - 1);  
}   
else   
{  
dp[a][b] = (dp[a - 1][b] && s1.charAt(a - 1) == s3.charAt(a + b - 1)) || (dp[a][b - 1] && s2.charAt(b - 1) == s3.charAt(a + b - 1));  
}  
}  
}  
return dp[s1.length()][s2.length()];  
}  
public static void main(String args[])  
{  
System.out.println(isInterleave("ppqrr", "wqqrp", "ppwqqrqrpr"));  
}  
}  

Output:

Interleaving string in Java

Related Topics

Internal Working of ArrayList in Java

Java's version of a resizable array is called ArrayList. The dynamic growth of an array list ensures that there is always room for new elements. ArrayList's backing data structure is...

8 minutes read.

Java OCR

In this article, you will be acknowledged about what is a tesseract OCR, how it works, what are its used and advantages and disadvantages. Also, you will be able to...

4 minutes read.

Java Program to Create Set of Pairs Using HashSet

HashSet in Java: HashSet is an assortment in Java that has a place with java.util bundle. It inside utilises HashMap to store components. It is an execution of the Set connection...

11 minutes read.

How to encrypt password in Java

Every software program needs a username and password to identify a legitimate user. A username can be any number of things, including an email address or a string of characters....

6 minutes read.

Java Math floor() Method

The floor() method of Math class returns the largest double value that is equal to a mathematical integer and is less than or equal to the argument. Syntax: public static double floor(double...

2 minutes read.

Bin Packing Problem Java

Assigning some items with known weights to bins with consistent capacities is necessary for the bin packing problem. The goal is to use the smallest possible boxes while ensuring everything is put...

6 minutes read.

Advantages of Generics in Java

Generic offers a variety of benefits. The programmer's life is made easier by using generic Java. In this section, we are going to discuss about Java's generic’s and its benefits. 1....

4 minutes read.

Rehashing in Java

The most crucial idea mostly in the data structure is hashing, which is utilized to change a particular key into some other value. The hash function can be used to...

7 minutes read.

Java List Node

In Java, List Node is the same as the single linked list, which is the collection of nodes. So, we can say, the list nodes are grouped together to get...

8 minutes read.

Abstract Class Program in Java

Abstract Class Program in Java Abstraction is a technique by which a developer hides the implementation details from the user and shows only the functionality.It is not only confined to the...

6 minutes read.

Java Do While Loop

When we wish to test the exit condition at the end of the loop, we use a do-while loop. The do-while loop always executes its body at least once, because...

1 minute read.

Root exception in java

Java: The main feature of java which is not in C or object oriented programming language is platform independence. Not only the platform independence there are many other features in java...

3 minutes read.

Java Finally Keyword

The final block in Java is used to run essential code, such as connection closure, among other things. Whether an exception is resolved or not, the Java finally block has...

3 minutes read.

Reverse a String using Collections in Java

Generally, a String is a grouping of characters. Yet, in Java, a String is an item that addresses a succession of characters. The Java.lang.String class is utilized to make a...

5 minutes read.

How to add 4 Years to the Current Date in Java?

In this tutorial, we will learn how to add 4 years to the local or current date in Java language. We will begin our topic with basic concepts and would...

2 minutes read.

Java Database Connectivity with Oracle

JDBC: A Programmer can develop a complete application using the Java built-in API’s. So, for storing the data required for solving a real-world problem is stored into a database. To connect...

5 minutes read.

String vs StringBuilder

String vs StringBuilder In this section, we will discuss the comparison between Java String and StringBuilder class. String In Java, a string is treated as an object that represents a sequence of characters....

4 minutes read.

Java String getChars() Method

Java String getChars() method copies characters from current String to the destination character array . Syntax: public void getChars(int srcBeginIndex, int srcEndIndex, char[] destination, int dstBeginIndex) Parameters: srcBegin - index of the first character...

1 minute read.

Heap Sort in Java

Heap Sort in JavaHeap sort in Java uses the data structure binary heap, min-heap, or max heap to do the sorting of elements. Since min-heap always gives the minimum element first,...

8 minutes read.

Check whether a Number is a Power of 4 or Not in Java

There are many ways to figure out if an integer is a power of 4. This section will go over a variety of techniques for figuring out whether or not...

11 minutes read.