×

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

Minimum Difference Between Groups of Size Two in Java

There is given an array with various integers in it. The goal is to divide the elements into distinct groups, each of which has just two, so that the difference...

3 minutes read.

How to avoid deadlock in java

Deadlock: A deadlock is an event that never going to occur. In java, deadlock is just a part of the multithreading. It is an environment that allows us to run multiple...

4 minutes read.

Java Integer toUnsignedString() method

The toUnsignedString() method of Java Integer class returns a string representation of the argument as an unsigned decimal value. The second syntax returns a string representation of the given argument as...

2 minutes read.

Converting Long to Date in Java

What Long and Date are in Java and how are they implemented in the Java programming language are the topics of this article. Additionally, we'll go into great detail on...

4 minutes read.

How to add Elements in Array in Java

Consider an array of the size n, in the given size we must add the elements in the given array. In this tutorial we are preferred to learn how to add...

3 minutes read.

What is interpreter in Java?

The programming language Java is platform-neutral. Therefore, can use Java on any platform that supports the Java processor. The Piece of software transforms the Java bytecode contained in the class...

5 minutes read.

Traverse through HashMap in Java

In this tutorial, we will discuss traversing through HashMap in Java Introduction: HashMap<Key, Value> is a part of the java collection implemented from the java 1.2 version. HashMap is written as HashMap<K,...

4 minutes read.

Java Integer remainder Unsigned() method

The remainderUnsigned() method of Java Integer class returns the unsigned remainder by dividing the first and second argument. Syntax public static int remainderUnsigned(int dividend, int divisor)  Parameters The ‘dividend’ and ‘divisor’ represents the value...

1 minute read.

Interface Program in Java

Interface Program in Java In the previous topic, we discussed that abstraction is possible through the interface and abstract class. An abstract class provides partial to 100% abstraction. 100 %abstraction in...

4 minutes read.

Difference between next() and nextline() in Java

One of the simplest methods for receiving input of the basic data types, also including int, double, and strings, in Java, is to use the Scanner class, which is part...

3 minutes read.

Sparse Numbers in Java

In this section, we will be very well acknowledged about the sparse numbers in Java, how a number can be verified if it is a sparse number or not. Sparse Numbers Any...

3 minutes read.

Java Garbage Collection Interview Questions

One of the key areas of Java is garbage collection. Garbage collection enables apps to manage memory automatically. Interviewers frequently ask inquiries about garbage collection. Q1: What is the purpose of...

6 minutes read.

Binary Strings Without Consecutive Ones in Java

N, an integer, is provided. Our objective is to determine the overall number of strings with length N that do not include successive 1s. Example: Input: 3 Output: 6 Explanation The binary forms of length...

6 minutes read.

How to Assign Static Value to Date in Java?

In this tutorial, we will learn certain ways to assign a static value to a date in java. We will see the limitation of each method that will lead to...

3 minutes read.

Bubble Sort in Java

Bubble Sort in Java Bubble sort isalso known as sinking sort. It is one of the simplest sorting algorithms. In the bubble sort algorithm, the given array is traversed from left...

5 minutes read.

Activity selection problem in Java

The activity selection problem is a multiple objective problem hat requires choosing non-conflicting tasks to complete within a specific amount of time from a list of tasks identified by a...

5 minutes 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.

Java String trim() method

Java String trim() method returns String after eliminating leading and trailing spaces. Note:- Java String trim() method doesn't trim or omit middle spaces. Syntax: public String trim() Returns: It returns string with omitted leading and...

2 minutes read.

Hashtable in Java

Hashtable in Java The Hashtable class implements the Map interface and extends the Dictionary class. It implements a hash table which shows the key-value relation, i.e., it maps the keys to the values....

9 minutes read.

Singleton Design Pattern in Java

In the singleton pattern, a class that only has one instance and offers a universal point of access is taken into consideration. It can also be defined in another way, a...

4 minutes read.