-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLongestSubstringWithoutRepeatingCharacters.java
More file actions
298 lines (210 loc) · 7.73 KB
/
LongestSubstringWithoutRepeatingCharacters.java
File metadata and controls
298 lines (210 loc) · 7.73 KB
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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
package Algorithms.SlidingWindow;
import java.util.*;
/**
* @author Srinivas Vadige, srinivas.vadige@gmail.com
* @since 26 Sept 2024
* @link 3. Longest Substring Without Repeating Characters <a href="https://leetcode.com/problems/longest-substring-without-repeating-characters/">LeetCode link</a>
* @topics String, Hash Table, Sliding Window / Dynamic Sliding Window
* @companies Amazon, Google, Microsoft, Bloomberg, Meta, TikTok, Visa, Oracle, Yandex, Walmart Labs, Goldman Sachs, Turing, Apple, Zoho, Cisco, Infosys, Netflix, EPAM, Nvidia, HCL, Adobe, Yahoo, Tinkoff, Tesla, IBM, Uber, Flipkart, Accenture, Agoda, Salesforce
*/
public class LongestSubstringWithoutRepeatingCharacters {
public static void main(String[] args) {
String s = "dvdfd";
System.out.println("lengthOfLongestSubstring using TwoPointers & HashSet: " + lengthOfLongestSubstringUsingTwoPointersAndHashSet(s));
System.out.println("lengthOfLongestSubstring using LinkedHashSet: " + lengthOfLongestSubstringUsingLinkedHashSet(s));
System.out.println("lengthOfLongestSubstring using HashMap: " + lengthOfLongestSubstringUsingHashMap(s));
System.out.println("lengthOfLongestSubstring using HashMap Optimized: " + lengthOfLongestSubstringUsingHashMapOptimized(s));
System.out.println("lengthOfLongestSubstring using BruteForce: " + lengthOfLongestSubstringUsingBruteForce(s));
}
/**
* @TimeComplexity O(n)
* @SpaceComplexity O(n)
Example 1:
Input: s = "abcabcbb"
Output: 3
Explanation: The answer is "abc" or "bca" or "cba", with the length of 3.
move r till no duplicates
a b c a b c
lr
a b c a b c
l r
a b c a b c
l r
a b c a b c ---> found duplicate, now move l
l r
a b c a b c ---> no duplicate, now move r
l r
a b c a b c ---> found duplicate, now move l
l r
a b c a b c ---> no duplicate, now move r
l r
a b c a b c ---> found duplicate, now move l
l r
a b c a b c
l r
*/
public static int lengthOfLongestSubstringUsingTwoPointersAndHashSet(String s) {
Set<Character> set = new HashSet<>();
int maxLen = 0;
int l=0;
for(int r=0; r<s.length(); r++) {
if(set.add(s.charAt(r))) {
maxLen = Math.max(maxLen, r-l+1);
} else {
while(set.contains(s.charAt(r))) {
set.remove(s.charAt(l++));
}
set.add(s.charAt(r));
}
}
return maxLen;
}
public static int lengthOfLongestSubstringUsingTwoPointersAndHashSet2(String s) {
int l=0;
int n=s.length();
int maxLen = 0;
Set<Character> set = new HashSet<>(); // to check duplicates
for(int r=0; r<n; r++) {
if(!set.add(s.charAt(r))) {
while(l<n) {
char c = s.charAt(l++);
if(c == s.charAt(r)) {
break;
}
set.remove(c);
}
}
maxLen = Math.max(maxLen, set.size()); // or maxLen = Math.max(maxLen, r-l+1);
}
return maxLen;
}
/**
* @TimeComplexity O(n)
* @SpaceComplexity O(n)
* Only one variable needed, not two
*/
public static int lengthOfLongestSubstringUsingLinkedHashSet(String s) {
Set<Character> set = new LinkedHashSet<>();
int maxLen = 0;
for(char c : s.toCharArray()) {
if(!set.add(c)) {
Iterator<Character> it = set.iterator(); // but try(Iterator it = ..) {} is not valid as "it" is not the type that implements AutoCloseable like Reader, Scanner, Stream, InputStream, Connection
while(it.hasNext() && it.next() != c) {
it.remove();
}
// change the access order i.e., shift 'c' to the end
set.remove(c);
set.add(c);
}
maxLen = Math.max(maxLen, set.size());
}
return maxLen;
}
/**
* @TimeComplexity O(n)
* @SpaceComplexity O(n)
*/
public static int lengthOfLongestSubstringUsingHashMap(String s) {
Map<Character, Integer> counter = new HashMap<>();
int l = 0;
int r = 0;
int maxLen = 0;
while (r < s.length()) {
char rChar = s.charAt(r);
counter.merge(rChar, 1, Integer::sum);
while (counter.get(rChar) > 1) {
char lChar = s.charAt(l);
counter.merge(lChar, -1, Integer::sum);
l++;
}
maxLen = Math.max(maxLen, r-l+1);
r++;
}
return maxLen;
}
/**
* @TimeComplexity O(n)
* @SpaceComplexity O(n)
*/
public static int lengthOfLongestSubstringUsingHashMapOptimized(String s) {
int n = s.length(), maxLen = 0;
Map<Character, Integer> map = new HashMap<>(); // --> map - index after current character
// try to extend the range [i, j]
for (int j = 0, i = 0; j < n; j++) {
if (map.containsKey(s.charAt(j))) {
i = Math.max(map.get(s.charAt(j)), i);
}
maxLen = Math.max(maxLen, j-i+1);
map.put(s.charAt(j), j + 1);
}
return maxLen;
}
/**
* @TimeComplexity O(n^3)
* @SpaceComplexity O(1)
*/
public static int lengthOfLongestSubstringUsingBruteForce(String s) {
int n = s.length();
int res = 0;
for (int i = 0; i < n; i++) {
for (int j = i; j < n; j++) {
if (checkRepetition(s, i, j)) {
res = Math.max(res, j - i + 1);
}
}
}
return res;
}
private static boolean checkRepetition(String s, int start, int end) {
Set<Character> chars = new HashSet<>();
for (int i = start; i <= end; i++) {
char c = s.charAt(i);
if (chars.contains(c)) {
return false;
}
chars.add(c);
}
return true;
}
/*
* No need to use two pointer approach like MinimumWindowSubString problem. Because we're focussing only one dup char
*/
public static int lengthOfLongestSubstringNoPointers(String s) {
int n = s.length();
if(n <= 1) {
return n;
}
String subStr = "";
int maxL = 0;
String[] chars = s.split("");
for(int i=0; i<n; i++){
int repStrIndex = subStr.indexOf(chars[i]); // as we check the index of subStr not s. It's working fine
if(repStrIndex > -1){
subStr = subStr.substring(repStrIndex+1) + chars[i]; // --- or HashSet
} else subStr += chars[i];
System.out.println(subStr);
maxL = Math.max(maxL, subStr.length());
}
return maxL;
}
// won't work for Eg: dvdf -- here max sub string length is 3
public static int lengthOfLongestSubstringMyApproachOldNotWorking(String s) {
Map<String, Integer> map = new HashMap<>();
String[] chars = s.split("");
int maxL = 0;
int tempStart=0;
for(int i=0; i<s.length(); i++){
if(map.containsKey(chars[i])){
maxL = Math.max(maxL, i-tempStart);
tempStart = i;
map.clear();
map.put(chars[i], 1);
}
else
map.put(chars[i], 1);
System.out.println(maxL);
System.out.println(map);
}
return map.size();
}
}