×

Minimum Window Subsequence in Java

In this article, you will be very well acknowledged about the minimum window subsequence, what is the approach and how it is implemented. The example program is also executed and its output is also displayed.

Problem Statement

Find the smallest (contiguous) substring W in string S such that T is a subset of W given strings S and T.

Return the null string "if there isn't a window in S that includes all the characters in T." Return the minimum-length window with the leftmost starting index if there are numerous ones.

Example 1:

Input:

S = asdfghjkl   T = fhl

Output:

The valid output string is W = fghjkl

The string fghjkl includes every letter in the stringfhl.

Example 2 :

Input:

S = zxcvbnm  T = vbm

Output:

The valid output string is W = vbnm

The string vbnm includes every letter in the string vbm

Methodology

First, we'll search for a window that has the entire string T in its actual form. The window will then be reduced as much as it can be while still retaining the requirement that it contain every character in the string T. After that, we can close the window.

The steps for determining the minimal window subsequence are as follows:

Keep the two references ptr1 as well as ptr2 and give them the value 0. Ptr1 and Ptr2 are for the strings S and T, respectively.

When S[ptr1] == T[ptr2], both points should be advanced at once; otherwise, just the ptr1 pointer should be advanced.

The string T is located within string S because when value of ptr2 reaches the size of the string T. We must now make the window smaller. It is crucial to understand why unnecessary characters may enter the window before adjusting the window size.

Let's use the following strings as an example, with S = "ypcdepdde" and T = "pde".

Ptr1 and Ptr2 be placed at the 0 indices of their corresponding strings at the beginning. Since there is an error (y!= p) at index 0, we advance the pointer ptr1 through one position. We now simultaneously move pointers ptr1 and ptr2 by one step. Now, c and d are being compared, which is an incorrect match. Thus, step 1 causes ptr1 to grow. Now when there is a match, both pointers advance at once. The size of a string T is revealed by the ptr2 at the fourth index of a string S, which is three. Thus, the window with size 5 is obtained. Now, when we move going right to left through the window's elements, if we find a match, we cut pt2 by 1. The border should be placed at the point in which the ptr2 becomes 0. Anything beyond the line is undesirable character.

As a result, after shrinking the window, we obtain "pcde" instead of "ypcde" before. Therefore, the character "y" is undesirable.

For the remaining portion of the string S, the same procedure can be repeated.

File name: WindowSeq.java

public class WindowSeq   
{  
  
public static String findMinWindow(String S1, String S2)   
{  
  
// The window is initially bare in the beginning.
String win = "";  
int ptr2 = 0;  
int minimum = S1.length() + 1;  
  
for (int ptr1 = 0; ptr1 < S1.length(); ptr1++)   
{  
  
// Since ptr1 is just the loop variable, it will automatically increase the ptr2 pointer if the //characters in both strings match.
if (S1.charAt(ptr1) == S2.charAt(ptr2))   
{  
ptr2 = ptr2 + 1;  
  
// The entire string S2 has already been examined. As a result, it is now appropriate to //close the window.
if (ptr2 == S2.length())   
{  
int e = ptr1 + 1;  
ptr2 = ptr2 - 1;  
  
// lowering the size of the window 
while (ptr2 >= 0)   
{  
if (S1.charAt(ptr1) == S2.charAt(ptr2))   
{  
ptr2 = ptr2 - 1;  
}  
ptr1 = ptr1 - 1;  
}  
  
ptr2 = ptr2 + 1;  
ptr1 = ptr1 + 1;  
  
// We must alter the window because we discovered one that is shorter.
if (e - ptr1 < minimum)   
{  
  
// the var minimum being updated
minimum = e - ptr1;  
  
// upgrading the window  
win = S1.substring(ptr1, e);  
}  
}  
}  
}  
      
// returning our final response and saving it in the window
return win;  
}  
  public static void main(String argvs[])  
{  
WindowSeq obj = new WindowSeq();  
String s1 = "zxcvbnm";  
String s2 = "vnm";  
System.out.println("For the given strings \"" + s1 + "\" and \"" + s2 + "\"");  
  
String str = obj.findMinWindow(s1, s2);  
System.out.println("The minimum window is : " + str);  
System.out.println();  
    
s1 = "ypcdepdde";  
s2 = "pde";  
System.out.println("For the given strings \"" + s1 + "\" and \"" + s2 + "\"");  
str = obj.findMinWindow(s1, s2);  
System.out.println("The minimum window is : " + str);  
System.out.println();  
    
s1 = "qwertyiop";  
s2 = "tip";  
System.out.println("For the given strings \"" + s1 + "\" and \"" + s2 + "\"");  
str = obj.findMinWindow(s1, s2);  
System.out.println("The minimum window is : " + str);  
  
}  
  
} 

Output

For the given strings “zxcvbnm” and “vnm”
The minimum window is: vbnm
For the given strings “asdfghjkl” and “fhl”
The minimum window is: fghjkl
For the given strings “qwertyuiop” and “tip”
The minimum window is: tyiop

The program's time complexity is O(n2), where n represents the total amount of characters in the string, due to the loops (one for-loop and another while-loop). The program does not consume any additional space, increasing the space's complexity to O (1).


Related Topics

Armstrong Number Program in Java

Armstrong Number Program in Java: A positive number is called an Armstrong number if the sum of the cube of each digit is equal to the number itself. There are...

6 minutes read.

Java File

Java file class implements the concept of file handling. It has several methods, such as deleting, creating, reading, and updating files. This class allows java users to perform various operations...

5 minutes read.

Leap Year Program in Java

Leap Year Program in Java: A leap year is a calendar year that have an extra day i.e. 366 days instead of 365 days is called leap year. In other...

2 minutes read.

Java Class Methods

Methods called on a class rather than a specific object instance are known as class methods. The static modifier guarantees uniform implementation across all instances of the class. Syntax public class NameOfClass...

3 minutes read.

Access specifiers in Java

What are access specifiers in Java? Access specifiers in Java are used to determine whether other classes can use a particular field or invoke a particular method. Access specifiers mainly specify...

7 minutes read.

Reserved Keywords in Java

In Java, a reserved term is used as a code key called a keyword. Because they are predefined, these terms cannot be used for anything else. They cannot serve as...

3 minutes read.

Stone Game in Java

In this tutorial, we will learn to design a stone game in Java. First of all, we will understand what is this game all about. We will grasp it through...

9 minutes read.

Constructor Overloading in Java

In Java, constructors can be overloaded just like methods. The idea of having multiple constructors with various parameter sets so that each function Object()  can carry out a particular task...

3 minutes read.

URLConnection class in Java

A communication channel between the URL and the program is represented by the Java URLConnection class. It may be utilized to read from and write to the given resource the...

4 minutes read.

Pattern Programs in Java

Pattern Programs in Java In Java, pattern programs are the most important from the perspective of interviews. The pattern programs improve thinking and coding skills. It also helps us to develop a...

27 minutes read.

Features of Java

The objective of the Java programming language is to provide portability, security, and simplicity. In spite of this, Java has a number of features that makes it a popular language...

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 Rename File

Renaming a file is the process of changing its name. Using the renameTo() function of the Java File class, renaming operations are possible. A file can be renamed using Java's renameTo()...

3 minutes read.

How to Calculate the Time Difference between Two Dates in Java?

The date is used extensively in Java to calculate date discrepancies. The date of joining an organization, admittance, appointment, etc., can be included when creating the application. The differences between...

4 minutes read.

The Maximum Rectangular Area in a Histogram in Java

Continuous bars should be used to form the largest possible rectangle. We'll assume in the interest of convenience that each bar's width is 1. Naive Approach In this method, each bar will be...

6 minutes read.

Economical number in Java

Economical number is said to be economically efficient if the number of digits after prime factorization of the original number with their powers is less than the number of digits...

3 minutes read.

Thread Synchronization in Java

In Java, the smallest processing component is a thread, which is a small subprocess. It follows a different course of action. Threads are autonomous. If an exception occurs in one thread,...

6 minutes read.

Java Arrays

An array is an object that stores a collection of values. An array can store two types of collection data: objects and primitives. An array is a collection of values which...

2 minutes read.

Java String replaceFirst() method

This method replace the first substring with user specified String. Syntax: public String replaceFirst(String Regexp, String Replacement) Parameter: Regexp : Regular Expression Replacement : the String which would replace found expression Return: a string Java String replaceFirst()...

1 minute read.

Level order Traversal of a Binary Tree in Java

In Java, a level order traversal of a tree structure is also referred to as the breadth-first traversal of the binary tree. Regarding the subsequent binary tree: Level order traversal is as...

5 minutes read.