-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathd9.cpp
101 lines (92 loc) · 2.52 KB
/
d9.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
// minimum window substring | variable size sliding window
#include <iostream>
#include <climits>
#include <string.h>
#include <unordered_map>
using namespace std;
// map[s[i]] = i;
int answer1(string s, string t)
{
unordered_map<char, int> map;
int n = s.length();
int currentWindowIndex = 0;
int size = 0;
int minLength = INT_MAX;
for (auto c : t)
{
map[c]++;
size++;
}
for (int i = 0; i < n; i++)
{
if (map.find(s[i]) != map.end())
{
map[s[i]]--;
size--;
}
if (size == 0)
{
minLength = min(minLength, i - currentWindowIndex + 1);
currentWindowIndex++;
if (map.find(s[currentWindowIndex]) != map.end())
{
map[s[currentWindowIndex]]++;
size++;
}
}
}
return minLength;
}
// gpt reviewed
// size after auto loop will be equal to t.length()-1
int answer2(string s, string t)
{
unordered_map<char, int> map;
unordered_map<char, int> windowMap;
int n = s.length();
int currentWindowIndex = 0;
int minLength = INT_MAX;
// Initialize the map with frequencies of characters in t
for (char c : t)
{
map[c]++;
}
int required = map.size();
int formed = 0;
// Two pointer approach with sliding window
for (int r = 0; r < n; r++)
{
char c = s[r];
if (map.find(c) != map.end())
{
windowMap[c]++;
if (map[c] == windowMap[c])
{
formed++;
}
}
// when formed == required means found a valid window
// if(formed==required){
// minLength= min(minLength,r-currentWindowIndex+1);
// }
// okay told gpt that it was wrong here and it should be a while loop till we find a relevant letter
// also in case when the substring is in the latter section of the string this approach won't work with a while loop inside
while (formed == required)
{
minLength = min(minLength, r - currentWindowIndex + 1);
char leftChar = s[currentWindowIndex];
if (map.find(leftChar) != map.end())
{
windowMap[leftChar]--;
if (windowMap[leftChar] < map[leftChar])
{
formed--;
}
}
currentWindowIndex;
}
}
return minLength;
}
// asked gpt to check this one works
// yiippppiii got the intership!!!