-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBlind 75
350 lines (320 loc) · 11.3 KB
/
Blind 75
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
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
class ArrayAndHashmap {
containsDuplicate = function (nums) {
const map = new Map()
for (let char of nums) {
map.set(char, (map.get(char) || 0) + 1)
}
for (let [key, value] of map) {
if (value > 1) return true
}
return false;
};
isAnagram = function (s, t) {
if (s.length !== t.length) return false
let map = new Map()
for (let char of s) {
map.set(char, (map.get(char) || 0) + 1);
} //you have map now compare with t
for (let char of t) {
if (!map.has(char)) return false
map.set(char, map.get(char) - 1);
if (map.get(char) === 0) map.delete(char)
}
return map.size === 0
};
twoSum = function (nums, target) { // Find two numbers which are two-sum of target in nums
const map = new Map(); // create a new map
for (let i = 0; i < nums.length; i++) { // now iterate over nums
const complement = target - nums[i] // find complement of target to current
if (map.has(complement)) { // if there's complement in map
return [map.get(complement), i] // return complement and current index
}
map.set(nums[i], i) // map current number to current index otherwise
}
};
groupAnagrams = function (strs) {
const map = new Map()
for (let str of strs) {
const sorted = str.split('').sort().join('')
if (!map.has(sorted)) map.set(sorted, [])
map.get(sorted).push(str)
}
return Array.from(map.values())
};
topKFrequent = function (nums, k) {
const frequencyMap = new Map()
const buckets = Array.from({ // bucket sort
length: nums.length + 1
}, () => [])
const result = []
for (const num of nums) {
frequencyMap.set(num, (frequencyMap.get(num) || 0) + 1)
}
for (const [num, freq] of frequencyMap.entries()) {
buckets[freq].push(num)
}
for (let i = buckets.length - 1; i >= 0; i--) {
for (const num of buckets[i]) {
result.push(num)
if (result.length === k) {
return result
}
}
}
return result
}
EncodeDecode = function () { // Encode and decode string
function encode(strs) {
let encoded = ''
for (let str of strs) {
encoded += str.length + "#" + str
}
return encoded;
}
function decode(str) {
let decoded = []
let i = 0;
while (i < str.length) { //while i is in bound
let j = str.indexOf('#', i) //find delimeter
let length = parseInt(str.slice(i, j)); // find length
i = j + 1; // start from the beginning of string
decoded.push(str.slice(i, i + length)) // push into str
i += length // jump to next string
}
return decoded
}
}
productExceptSelf(nums) {
const n = nums.length;
const result = Array(n).fill(1)
let leftProduct = 1;
for (let i = 0; i < n; i++) {
result[i] = leftProduct;
leftProduct *= nums[i]
}
let rightProduct = 1
for (let i = n - 1; i >= 0; i--) {
result[i] *= rightProduct;
rightProduct *= nums[i]
}
return result
}
longestConsecutive = function (nums) { // longest coonsecutive subsequence
if (nums.length === 0) return 0
let longest = 0;
let numSet = new Set(nums)
for (let num of nums) {
if (!numSet.has(num - 1)) {
let currentStreak = 1;
let currentNum = num
while (numSet.has(currentNum + 1)) {
currentNum++;
currentStreak++;
}
longest = Math.max(longest, currentStreak)
}
}
return longest
};
}
class Twopointer {
isPalindrome = function (s) { // Check if a string is a palindrome
const cleaned = s.toLowerCase().replace(/[^a-z0-9]/g, '');
return cleaned === cleaned.split('').reverse().join('');
};
threeSum = function (nums) {
const result = []; // result
nums.sort((a, b) => a - b) // sort the array
for (let i = 0; i < nums.length - 2; i++) { // iterate over nums
if (i > 0 && nums[i] === nums[i - 1]) continue // skip first duplicate
let left = i + 1,
right = nums.length - 1; // two pointer
while (left < right) { // inner loop
const currentSum = nums[i] + nums[left] + nums[right] // find sum
if (currentSum === 0) { // if valid
result.push([nums[i], nums[left], nums[right]]) //push into result
while (left < right && nums[left] === nums[left + 1]) left++; //duplicates
while (left < right && nums[right] === nums[right - 1]) right--;
left++; // carry on
right--;
} else if (currentSum < 0) {
left++
} else right--;
}
}
return result
};
maxArea = function (height) { // container with most water
let left = 0; // two pointers
let right = height.length - 1;
let maxWater = 0;
while (left < right) {
const area = Math.min(height[left], height[right]) * (right - left) // calculate area enclosed by left and right pillar
maxWater = Math.max(maxWater, area) // if current area is maximum, update it
if (height[left] < height[right]) { // continue with next larger pillar whether it is left or right
left++;
} else {
right--;
}
}
return maxWater;
};
}
class SlidingWindow {
maxProfit = function (prices) { // Best time to buy and sell stocks
let maxProfit = 0;
let minPrice = Infinity;
for (let price of prices) {
minPrice = Math.min(minPrice, price);
const profit = price - minPrice;
maxProfit = Math.max(maxProfit, profit);
}
return maxProfit;
};
lengthOfLongestSubstring = function (s) { // without repeating characters
let left = 0;
let max_length = 0;
const map = new Map();
for (let right = 0; right < s.length; right++) {
while (map.has(s[right])) {
map.delete(s[left]);
left++
}
map.set(s[right], right)
max_length = Math.max(max_length, right - left + 1)
}
return max_length;
};
characterReplacement = function(s, k) { //Longest repeating character replacement
let left = 0, freq = {}, maxFrequency = 0, maxLength = 0;
for (let right = 0; right < s.length; right++){
const char = s[right];
freq[char] = (freq[char] || 0)+1
maxFrequency = Math.max(maxFrequency, freq[char])
while ((right-left+1)-maxFrequency > k) {
freq[s[left]]--
left++
}
maxLength = Math.max(maxLength, right-left+1)
}
return maxLength
};
// NOTE: It is advised to solve hard question like this in python or even C++
minWindow(s, t) { // minimum window substring
if (s.length < t.length) return "";
const requiredChars = new Map();
for (const char of t) {
requiredChars.set(char, (requiredChars.get(char) || 0) + 1);
}
let left = 0;
let right = 0;
let formed = 0;
const windowCounts = new Map();
const required = requiredChars.size;
let minLength = Infinity;
let minWindowStart = 0;
while (right < s.length) {
const char = s[right];
windowCounts.set(char, (windowCounts.get(char) || 0) + 1);
if (requiredChars.has(char) && windowCounts.get(char) === requiredChars.get(char)) {
formed += 1;
}
while (left <= right && formed === required) {
if (right - left + 1 < minLength) {
minLength = right - left + 1;
minWindowStart = left;
}
const leftChar = s[left];
windowCounts.set(leftChar, windowCounts.get(leftChar) - 1);
if (requiredChars.has(leftChar) && windowCounts.get(leftChar) < requiredChars.get(leftChar)) {
formed -= 1;
}
left += 1;
}
right += 1;
}
return minLength === Infinity ? "" : s.slice(minWindowStart, minWindowStart + minLength);
}
}
class Stack {
isValid = function(s) {
let stack = []
const map = {
'}':'{',
')':'(',
']':'['
}
for (let char of s){
if (char === '{' || char ==='('|| char ==='[' ){
stack.push(char)
}else{
if (stack.length===0 ||stack.pop() !== map[char] ) return false;
}
}
return stack.length === 0
};
}
class BinarySearch{
findMin = function(nums) { // Find minimum in a rotated sorted array
let left = 0, right = nums.length-1;
while (left < right){
const mid = Math.floor((left+right)/2)
if (nums[right] < nums[mid]){ // If mid is greater than minimum is on the right
left = mid +1;
}else{
right = mid;
}
}
return nums[left]
};
search = function(nums, target) { // search target in a rotated sorted array
let left = 0, right = nums.length -1;
while (left <= right ){
const mid = Math.floor((left + right )/2);
if ( nums[mid] === target) return mid;
if ( nums[left] <= nums[mid]) {
if (nums[left] <= target && target < nums[mid]){
right = mid;
}else {
left = mid +1;
}
}else{
if (nums[mid] < target && target <= nums[right]){
left = mid+1;
} else {
right = mid;
}
}
}
return -1;
};
}
class LinkedList{
reverseList = function(head) {
let prev = null
let curr = head
while (curr !== null){
let next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
return prev;
};
mergeTwoLists = function(list1, list2) {
let dummy = new ListNode(-1);
let curr = dummy;
while (list1 !== null && list2 !== null){
if ( list1.val <= list2.val){
curr.next = list1
list1 = list1.next
}else{
curr.next = list2
list2 = list2.next
}
curr = curr.next
}
curr.next = list1 !== null ? list1 :list2
return dummy.next;
};
}