Skip to content

Commit d9aef71

Browse files
committed
up 27/02/22
1 parent 28ade38 commit d9aef71

1 file changed

Lines changed: 81 additions & 0 deletions

File tree

  • JavaPractice/SmallestWindowContaining 0, 1 and 2
Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
## Smallest window containing 0, 1 and 2
2+
Given a string S consisting of the characters 0, 1 and 2. Your task is to find the length of the smallest substring of string S that contains all the three characters 0, 1 and 2. If no such substring exists, then return -1. [🔗Goto](https://practice.geeksforgeeks.org/problems/d6e88f06b273a60ae83992314ac514f71841a27d/1#)
3+
4+
<details>
5+
<summary>Full Code</summary>
6+
7+
```java
8+
import java.io.*;
9+
import java.util.*;
10+
import java.lang.*;
11+
12+
class GFG {
13+
public static void main(String args[]) throws IOException {
14+
BufferedReader read =
15+
new BufferedReader(new InputStreamReader(System.in));
16+
int t = Integer.parseInt(read.readLine());
17+
while (t-- > 0) {
18+
String S = read.readLine();
19+
Solution ob = new Solution();
20+
int ans = ob.smallestSubstring(S);
21+
22+
System.out.println(ans);
23+
}
24+
}
25+
}
26+
```
27+
</details>
28+
29+
```java
30+
class Solution {
31+
public int smallestSubstring(String S) {
32+
// Code here
33+
int len = S.length();
34+
int zero = -1;
35+
int one = -1;
36+
int two = -1;
37+
int min = Integer.MAX_VALUE;
38+
for(int i =0;i<len;i++){
39+
char ch = S.charAt(i);
40+
if(ch=='0'){
41+
zero = i;
42+
}
43+
if(ch == '1'){
44+
one = i;
45+
}
46+
if(ch == '2'){
47+
two = i;
48+
}
49+
if(zero>=0 && one>=0 && two>=0){
50+
51+
int minpos = -1,maxpos = -1;
52+
if(zero<=one && zero <= two){
53+
minpos = zero;
54+
}
55+
else if(one <= two && one <= two){
56+
minpos = one;
57+
}else{
58+
minpos = two;
59+
}
60+
61+
if(zero>=one && zero >= two){
62+
maxpos = zero;
63+
}
64+
else if(one >= two && one >= two){
65+
maxpos = one;
66+
}else{
67+
maxpos = two;
68+
}
69+
70+
int y = (Math.abs(maxpos-minpos))+1;
71+
min = Math.min(min,y);
72+
}
73+
}
74+
75+
if(min == Integer.MAX_VALUE){
76+
min = -1;
77+
}
78+
return min;
79+
}
80+
};
81+
```

0 commit comments

Comments
 (0)