-
Notifications
You must be signed in to change notification settings - Fork 0
/
1.EASY_LEETCODE
1493 lines (1217 loc) · 48.4 KB
/
1.EASY_LEETCODE
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
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
/**************************************************************************************/
/*************************************QUESTION********************************************/
/***********************************************************************************/
APRIL 26th 2021 Monday:
TWO SUM LEETCODE #1:
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
You can return the answer in any order.
*/
/**************************************************************************************/
/************************************ANSWER********************************************/
/***********************************************************************************/
let nums = [2,4,7,15];
let target = 9;
var twoSum = function (nums, target) {
for (let i=0; i<nums.length; i++){
for(let j = i + 1; j<nums.length; j++) {
if(nums[i] + nums[j] === target){
return [i, j]
}
}
}
}
twoSum(nums, target);
/**************************************************************************************/
/*************************************QUESTION********************************************/
/***********************************************************************************/
/*
APRIL 27th 2021 Tuesday:
7. Reverse Integer
Difficulty Easy:
Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-231, 231 - 1], then return 0.
Assume the environment does not allow you to store 64-bit integers (signed or unsigned).
Example 1:
Input: x = 123
Output: 321
Example 2:
Input: x = -123
Output: -321
Example 3:
Input: x = 120
Output: 21
Return: 0000000001111001
Example 4:
Input: x = 0
Output: 0
Constraints:
-2 31 <= x <= 2 31 - 1
Our Plan:
1.Convert Number Into String
2. Convert into Array using split
3. Reverse the Array
4. Join the Array Into a String Again
5. Use Parse Float (to account for decimals as well) and to Convert String into Number Again
5. Use Math.sign to get the sign from the original number and multiple the reversed number
to keep the sign consistent
6. Define a 32 bit number
7. Use an if statement to return the reverse number only if it meets the
Constraints of the 32 bit number
8. Else Return 0
*/
/**************************************************************************************/
/************************************ANSWER********************************************/
/***********************************************************************************/
var reverse = function(x) {
let numToString = parseFloat(x.toString().split('').reverse().join('')) * Math.sign(x);
let z = Math.pow(2, 31);
if (numToString < z && numToString > -z){
return numToString
}
else{
return 0
}
};
let input16Bit = 65536; //2^16 Binary Number:10000000000000000
let input16BitNeg = -65536;
let inputFloat16 = 6.5536;
let input31Bit = 2147483648; //2^31 Binary Number:10000000000000000000000000000000
let input32Bit = 2147483647; //2^32 Binary Number:1111111111111111111111111111111
let input64Bit = 18446744073709551616; //2^64
console.log(reverse(input64Bit))
/**************************************************************************************/
/*************************************QUESTION********************************************/
/***********************************************************************************/
/*
9. Palindrome Number
Difficulty: Easy
Given an integer x, return true if x is palindrome integer.
An integer is a palindrome when it reads the same backward as forward. For example, 121 is palindrome while 123 is not.
Example 1:
Input: x = 121
Output: true
Example 2:
Input: x = -121
Output: false
Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.
Example 3:
Input: x = 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
Example 4:
Input: x = -101
Output: false
Constraints:
-231 <= x <= 231 - 1
OUR PLAN:
1. Convert Integer to String
2. Split into Array
3. Reverse Array
4. Join to String
5. Wrap All that in A Parse Float to Convert String back into an Integer
Compare that to Original Integer to see if it is a Palidrome if it's negative it will
automatically be false. And if it's a decimal that is taken care of by the Parse Float
*/
/**************************************************************************************/
/************************************ANSWER********************************************/
/***********************************************************************************/
var isPalindrome = function(x) {
if (x === parseFloat(x.toString().split('').reverse().join(''))) {
return true
}
else{
return false
}
};
console.log(isPalindrome(12.21));
/**************************************************************************************/
/*************************************QUESTION********************************************/
/***********************************************************************************/
/*
APRIL 28 2020 WEDNESDAY
13. Roman to Integer
Difficulty: Easy
Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.
Symbol Value
I 1
V 5
X 10
L 50
C 100
D 500
M 1000
For example, 2 is written as II in Roman numeral, just two one's added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II.
Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used:
I can be placed before V (5) and X (10) to make 4 and 9.
X can be placed before L (50) and C (100) to make 40 and 90.
C can be placed before D (500) and M (1000) to make 400 and 900.
Given a roman numeral, convert it to an integer.
Example 1:
Input: s = "III"
Output: 3
Example 2:
Input: s = "IV"
Output: 4
Example 3:
Input: s = "IX"
Output: 9
Example 4:
Input: s = "LVIII"
Output: 58
Explanation: L = 50, V= 5, III = 3.
Example 5:
Input: s = "MCMXCIV"
Output: 1994
Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.
Constraints:
1 <= s.length <= 15
s contains only the characters ('I', 'V', 'X', 'L', 'C', 'D', 'M').
It is guaranteed that s is a valid roman numeral in the range [1, 3999].
Our Plan:
*/
/**************************************************************************************/
/************************************ANSWER********************************************/
/***********************************************************************************/
var romanToInt = function (s) {
let symbols = {
I: 1,
V: 5,
X: 10,
L: 50,
C: 100,
D: 500,
M: 1000,
};
let result = 0;
for (let i = 0; i < s.length; i++) {
if (symbols[s[i]] < symbols[s[i + 1]]) {
result += symbols[s[i + 1]] - symbols[s[i]];
i++;
} else {
result += symbols[s[i]];
}
}
return result;
};
romanToInt('IV');
/**************************************************************************************/
/*************************************QUESTION********************************************/
/***********************************************************************************/
/*APRIL 28th THURSDAY
14. Longest Common Prefix
Difficulty Easy
Write a function to find the longest common prefix string amongst an array of strings.
If there is no common prefix, return an empty string "".
Example 1:
Input: strs = ["flower","flow","flight"]
Output: "fl"
Example 2:
Input: strs = ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.
Constraints:
1 <= strs.length <= 200
0 <= strs[i].length <= 200
strs[i] consists of only lower-case English letters.
*/
/**************************************************************************************/
/************************************ANSWER********************************************/
/***********************************************************************************/
var longestCommonPrefix = function(strs) {
let prefix = strs[0];
console.log(strs[1][3]);
for(i =1; i < strs.length; i++){
for (j = 0; j < prefix.length; j++) {
if (strs[i][j] !== prefix[j]) {
prefix = strs[i].slice(0,j)
}
}
}
return prefix
};
let arrayOfStrings = ["flower","flow","flight"];
longestCommonPrefix(arrayOfStrings);
/**************************************************************************************/
/*************************************QUESTION********************************************/
/***********************************************************************************/
/*
29 APRIL 2021 FRIDAY
20. Valid Parentheses
Difficulty Easy
Share
Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
An input string is valid if:
Open
brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
Example 1:
Input: s = "()"
Output: true
Example 2:
Input: s = "()[]{}"
Output: true
Example 3:
Input: s = "(]"
Output: false
Example 4:
Input: s = "([)]"
Output: false
Example 5:
Input: s = "{[]}"
Output: true
Constraints:
1 <= s.length <= 104
s consists of parentheses only '()[]{}'.
}
*/
/*hasOwnProperty returns a boolean value indicating whether the object on which you are calling it has a property(keys) with the name of the argument.here we are checking for the opening brackets so the keys in the object
*/
/**************************************************************************************/
/************************************ANSWER********************************************/
/***********************************************************************************/
var isValid = function (s) {
let parenthesesObj = {
"(": ")",
"{": "}",
"[": "]",
}
const stack = [];
for (const item of s) {
//checking for opening brackets
if (parenthesesObj.hasOwnProperty(item)) {
stack.push(item)
} else {
let openBracket = stack.pop();
//ex -> parenthesesObj[{]=}
if (item !== parenthesesObj[openBracket]) {
return false;
}
}
}
return stack.length === 0;
};
isValid("([)]");
/**************************************************************************************/
/*************************************QUESTION********************************************/
/***********************************************************************************/
/*
1832. Check if the Sentence Is Pangram
Difficulty Easy
A pangram is a sentence where every letter of the English alphabet appears at least once.
Given a string sentence containing only lowercase English letters, return true if sentence is a pangram, or false otherwise.
Example 1:
Input: sentence = "thequickbrownfoxjumpsoverthelazydog"
Output: true
Explanation: sentence contains at least one of every letter of the English alphabet.
Example 2:
Input: sentence = "leetcode"
Output: false
Constraints:
1 <= sentence.length <= 1000
sentence consists of lowercase English letters.
*/
/**************************************************************************************/
/************************************ANSWER********************************************/
/***********************************************************************************/
var checkIfPangram = function (sentence) {
let alphabet = 'abcdefghijklmnopqrstuvwxyz';
for (const letter in alphabet) {
if (sentence.indexOf(alphabet[letter]) < 0) {
return false;
}
}
return true
};
checkIfPangram("thequickbrownfoxjumpsoverthelazydog");
/**************************************************************************************/
/*************************************QUESTION********************************************/
/***********************************************************************************/
/*
1480. Running Sum of 1d Array
Difficulty Easy
Given an array nums. We define a running sum of an array as runningSum[i] = sum(nums[0]…nums[i])
Return the running sum of nums.
Example 1:
Input: nums = [1,2,3,4]
Output: [1,3,6,10]
Explanation: Running sum is obtained as follows: [1, 1+2, 1+2+3, 1+2+3+4].
Example 2:
Input: nums = [1,1,1,1,1]
Output: [1,2,3,4,5]
Explanation: Running sum is obtained as follows: [1, 1+1, 1+1+1, 1+1+1+1, 1+1+1+1+1].
Example 3:
Input: nums = [3,1,2,10,1]
Output: [3,4,6,16,17]
Constraints:
1 <= nums.length <= 1000
-10^6 <= nums[i] <= 10^6
*/
/**************************************************************************************/
/************************************ANSWER********************************************/
/***********************************************************************************/
var runningSum = function(nums) {
let sum = 0;
let runSum = [];
for(const x in nums){
sum+=parseFloat(nums[x]);
runSum.push(sum);
}
return runSum;
};
/**************************************************************************************/
/*************************************QUESTION********************************************/
/***********************************************************************************/
/*
1108. Defanging an IP Address
Difficulty Easy
Given a valid (IPv4) IP address, return a defanged version of that IP address.
A defanged IP address replaces every period "." with "[.]".
Example 1:
Input: address = "1.1.1.1"
Output: "1[.]1[.]1[.]1"
Example 2:
Input: address = "255.100.50.0"
Output: "255[.]100[.]50[.]0"
}
Constraints: The given address is a valid IPv4 address.
*/
*/
/**************************************************************************************/
/************************************ANSWER********************************************/
/***********************************************************************************/
var defangIPaddr = function (address) {
return address.replace(/\./g, "[.]");
};
defangIPaddr("255.100.50.0");
/**************************************************************************************/
/*************************************QUESTION********************************************/
/***********************************************************************************/
/*21. Merge Two Sorted Lists
Easy
Merge two sorted linked lists and return it as a sorted list. The list should be made by splicing together the nodes of the first two lists.
Example 1:
Input: l1 = [1,2,4], l2 = [1,3,4]
Output: [1,1,2,3,4,4]
Example 2:
Input: l1 = [], l2 = []
Output: []
Example 3:
Input: l1 = [], l2 = [0]
Output: [0]
Constraints:
The number of nodes in both lists is in the range [0, 50].
-100 <= Node.val <= 100
Both l1 and l2 are sorted in non-decreasing order.
Seen this question in a real interview before?*/
/*********OUR ANSWER *******DIDNT WORK*/
var mergeTwoLists = function(l1, l2){
let l3 = [...l1, ...l2];
l3.sort();
return l3
};
mergeTwoLists([1,5,4], [1,3,4] );
/**********FUCKED UP REAL ANSWER ********/
function ListNode(val) {
this.val = val;
this.next = null;
}
var mergeTwoLists = function(l1, l2) {
let dummyHead = new ListNode(0);
let currentNode = dummyHead;
while(l1 !== null && l2 !== null){
if(l1.val < l2.val){
currentNode.next = l1;
l1 = l1.next
} else {
currentNode.next = l2
l2 = l2.next
}
currentNode = currentNode.next
}
if(l1 !== null) {
currentNode.next = l1;
} else if (l2 !== null) {
currentNode.next = l2
}
return dummyHead.next
}
/**************************************************************************************/
/*************************************QUESTION********************************************/
/***********************************************************************************/
/*
26. Remove Duplicates from Sorted Array
Difficulty : Easy
Given a sorted array nums, remove the duplicates in-place such that each element appears only once and returns the new length.
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
Clarification:
Confused why the returned value is an integer but your answer is an array?
Note that the input array is passed in by reference, which means a modification to the input array will be known to the caller as well.
Internally you can think of this:
// nums is passed in by reference. (i.e., without making a copy)
int len = removeDuplicates(nums);
// any modification to nums in your function would be known by the caller.
// using the length returned by your function, it prints the first len elements.
for (int i = 0; i < len; i++) {
print(nums[i]);
}
Example 1:
Input: nums = [1,1,2]
Output: 2, nums = [1,2]
Explanation: Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. It doesn't matter what you leave beyond the returned length.
Example 2:
Input: nums = [0,0,1,1,1,2,2,3,3,4]
Output: 5, nums = [0,1,2,3,4]
Explanation: Your function should return length = 5, with the first five elements of nums being modified to 0, 1, 2, 3, and 4 respectively. It doesn't matter what values are set beyond the returned length.
Constraints:
0 <= nums.length <= 3 * 104
-104 <= nums[i] <= 104
nums is sorted in ascending order.
*/
*/
/**************************************************************************************/
/************************************ANSWER********************************************/
/***********************************************************************************/
/******THIS QUESTION IS STUPID DONT DO IT */
var removeDuplicates = function(nums) {
var len = nums.length;
var last = NaN;
var count = 0;
for (var i = 0; i < len; i++) {
if (nums[i] !== last) {
nums[count] = nums[i];
last = nums[i];
count++;
}
}
return count;
};
removeDuplicates([1, 1, 2]);
/**************************************************************************************/
/*************************************QUESTION********************************************/
/***********************************************************************************/
/*819. Most Common Word
Given a string paragraph and a string array of the banned words banned, return the most frequent word that is not banned. It is guaranteed there is at least one word that is not banned, and that the answer is unique.
The words in paragraph are case-insensitive and the answer should be returned in lowercase.
Example 1:
Input: paragraph = "Bob hit a ball, the hit BALL flew far after it was hit.", banned = ["hit"]
Output: "ball"
Explanation:
"hit" occurs 3 times, but it is a banned word.
"ball" occurs twice (and no other word does), so it is the most frequent non-banned word in the paragraph.
Note that words in the paragraph are not case sensitive,
that punctuation is ignored (even if adjacent to words, such as "ball,"),
and that "hit" isn't the answer even though it occurs more because it is banned.
Example 2:
Input: paragraph = "a.", banned = []
Output: "a"
Constraints: 1 <= paragraph.length <= 1000
paragraph consists of English letters, space ' ', or one of the symbols: "!?',;.".
0 <= banned.length <= 100
1 <= banned[i].length <= 10
banned[i] consists of only lowercase English letters.
*/
/**************************************************************************************/
/************************************ANSWER********************************************/
/***********************************************************************************/
var mostCommonWord = function (paragraph, banned) {
let obj = {};
let mostCommon;
let wordArr = paragraph.toLowerCase().replace(/(~|`|!|@|#|$|%|^|&|\*|\(|\)|{|}|\[|\]|;|:|\"|'|<|,|\.|>|\?|\/|\\|\||-|_|\+|=)/g," ").split(" ");
let bannedSet = new Set();
banned.forEach((e) => bannedSet.add(e));
let result = wordArr.filter(Boolean).filter((x) => !bannedSet.has(x));
let counter = (key) => (obj[key] = ++obj[key] || 1);
result.forEach(counter);
let topWordLength = Math.max(...Object.values(obj));
let findMatch = (key) => obj[key] === topWordLength ? (mostCommon = key) : false;
result.forEach(findMatch);
return mostCommon
};
mostCommonWord("Bob hit a ball, the hit BALL ball flew far after it was hit.", ['hit']);
/**************************************************************************************/
/*************************************QUESTION********************************************/
/***********************************************************************************/
1800. Maximum Ascending Subarray Sum
Given an array of positive integers nums, return the maximum possible sum of an ascending subarray in nums.
A subarray is defined as a contiguous sequence of numbers in an array.
A subarray [numsl, numsl+1, ..., numsr-1, numsr] is ascending if for all i where l <= i < r, numsi < numsi+1. Note that a subarray of size 1 is ascending.
Example 1:
Input: nums = [10,20,30,5,10,50]
Output: 65
Explanation: [5,10,50] is the ascending subarray with the maximum sum of 65.
Example 2:
Input: nums = [10,20,30,40,50]
Output: 150
Explanation: [10,20,30,40,50] is the ascending subarray with the maximum sum of 150.
Example 3:
Input: nums = [12,17,15,13,10,11,12]
Output: 33
Explanation: [10,11,12] is the ascending subarray with the maximum sum of 33.
Example 4:
Input: nums = [100,10,1]
Output: 100
Constraints:
1 <= nums.length <= 100
1 <= nums[i] <= 100
*/
/**************************************************************************************/
/************************************ANSWER********************************************/
/***********************************************************************************/
var maxAscendingSum = function (nums) {
let sum = 0;
let count = [];
for (let item = 0; item < nums.length; item++) {
if (nums[item] < nums[item + 1] && sum >= nums[item] && nums[item] > nums[item - 1]) {
sum += nums[item];
} else if (nums[item] <= nums[item - 1] ||(nums[item] < nums[item + 1] && sum >= nums[item])
) {
sum = nums[item];
} else {
sum += nums[item];
count.push(sum);
}
}
return Math.max(...count);
};
maxAscendingSum([12,17,15,13,10,11,12])
/**************************************************************************************/
/*************************************QUESTION********************************************/
/***********************************************************************************/
1700. Number of Students Unable to Eat Lunch
Easy
The school cafeteria offers circular and square sandwiches at lunch break, referred to by numbers 0 and 1 respectively. All students stand in a queue. Each student either prefers square or circular sandwiches.
The number of sandwiches in the cafeteria is equal to the number of students. The sandwiches are placed in a stack. At each step:
If the student at the front of the queue prefers the sandwich on the top of the stack, they will take it and leave the queue.
Otherwise, they will leave it and go to the queue's end.
This continues until none of the queue students want to take the top sandwich and are thus unable to eat.
You are given two integer arrays students and sandwiches where sandwiches[i] is the type of the ith sandwich in the stack (i = 0 is the top of the stack) and students[j] is the preference of the jth student in the initial queue (j = 0 is the front of the queue). Return the number of students that are unable to eat.
Example 1:
Input: students = [1,1,0,0], sandwiches = [0,1,0,1]
Output: 0
Explanation:
- Front student leaves the top sandwich and returns to the end of the line making students = [1,0,0,1].
- Front student leaves the top sandwich and returns to the end of the line making students = [0,0,1,1].
- Front student takes the top sandwich and leaves the line making students = [0,1,1] and sandwiches = [1,0,1].
- Front student leaves the top sandwich and returns to the end of the line making students = [1,1,0].
- Front student takes the top sandwich and leaves the line making students = [1,0] and sandwiches = [0,1].
- Front student leaves the top sandwich and returns to the end of the line making students = [0,1].
- Front student takes the top sandwich and leaves the line making students = [1] and sandwiches = [1].
- Front student takes the top sandwich and leaves the line making students = [] and sandwiches = [].
Hence all students are able to eat.
Example 2:
Input: students = [1,1,1,0,0,1], sandwiches = [1,0,0,0,1,1]
Output: 3
Constraints:
1 <= students.length, sandwiches.length <= 100
students.length == sandwiches.length
sandwiches[i] is 0 or 1.
students[i] is 0 or 1.
*/
/*************************************************************************************/
/************************************ANSWER********************************************/
/***********************************************************************************/
var countStudents = function (students, sandwiches) {
let shift = students.length * sandwiches.length;
for (i = 0; i < shift; i++) {
if (students[0] != sandwiches[0]) {
students.push(students.splice(0, 1)[0]);
} else {
sandwiches.splice(0, 1);
students.splice(0, 1);
}
}
return students.length;
};
countStudents([0,0,0,1,1,1,1,0,0,0], [1,0,1,0,0,1,1,0,0,0]);
/**************************************************************************************/
/*************************************QUESTION********************************************/
/***********************************************************************************/
/*
1200.
Difficulty: EASY
Given an array of distinct integers arr, find all pairs of elements with the minimum absolute difference of any two elements.
Return a list of pairs in ascending order(with respect to pairs), each pair [a, b] follows
a, b are from arr
a < b
b - a equals to the minimum absolute difference of any two elements in arr
Example 1:
Input: arr = [4,2,1,3]
Output: [[1,2],[2,3],[3,4]]
Explanation: The minimum absolute difference is 1. List all pairs with difference equal to 1 in ascending order.
Example 2:
Input: arr = [1,3,6,10,15]
Output: [[1,3]]
Example 3:
Input: arr = [3,8,-10,23,19,-4,-14,27]
Output: [[-14,-10],[19,23],[23,27]]
Constraints:
2 <= arr.length <= 10^5
-10^6 <= arr[i] <= 10^6
*/
*/
/*************************************************************************************/
/************************************ANSWER********************************************/
/***********************************************************************************/
takes too long
var minimumAbsDifference = function(arr) {
let diff;
let obj={};
let pairs;
arr.sort(function(a, b){return a-b});
for(let i=0; i<arr.length; i++){
for(let j=i+1; j<arr.length; j++){
diff=Math.abs(arr[i]-(arr[j]));
obj[[arr[i], arr[j]]]=diff;
if(i===0 && j===1){
curr=diff
}
if(diff<curr){
curr=diff
}
}
}
Object.keys(obj).forEach((key)=> obj[key]!=curr ? delete obj[key] : false);
pairs = Array.from((Object.keys(obj)), e => e.split(','));
let pairsNums = pairs.map((x) => x.map((y) => +y));
return pairsNums
};
//minimumAbsDifference([1,3,6,10,15])
minimumAbsDifference([3,8,-10,23,19,-4,-14,27])
//minimumAbsDifference([4,2,1,3])
//actual answervar minimumAbsDifference = function (arr) {
let diff;
let curr;
let newArr = [];
arr.sort(function (a, b) {
return a - b;
});
for (let i = 0; i < arr.length; i++) {
diff = Math.abs(arr[i] - arr[i + 1]);
if (i === 0) {
curr = diff;
}
if (diff < curr) {
curr = diff;
newArr = [[arr[i], arr[i + 1]]];
} else if (diff === curr) {
newArr.push([arr[i], arr[i + 1]]);
}
}
return newArr;
};
minimumAbsDifference([3,8,-10,23,19,-4,-14,27])
/**************************************************************************************/
/*************************************QUESTION********************************************/
/***********************************************************************************/
/*28. Implement strStr()
Difficulty:Easy
Implement strStr().
Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Clarification:
What should we return when needle is an empty string? This is a great question to ask during an interview.
For the purpose of this problem, we will return 0 when needle is an empty string. This is consistent to C's strstr() and Java's indexOf().
Example 1:
Input: haystack = "hello", needle = "ll" [he, o]
Output: 2
Example 2:
Input: haystack = "aaaaa", needle = "bba"
Output: -1
Example 3:
Input: haystack = "", needle = ""
Output: 0
Constraints: 0 <= haystack.length, needle.length <= 5 * 104
haystack and needle consist of only lower-case English characters.
*/
/*************************************************************************************/
/************************************ANSWER********************************************/
/***********************************************************************************/
var strStr = function(haystack, needle) {
if(needle===''){return 0}
if(!haystack.includes(needle)) return -1
return haystack.split(needle)[0].length;
};
strStr("hello", 'll');
/**************************************************************************************/
/*************************************QUESTION********************************************/
/***********************************************************************************/
35. Search Insert Position
Easy
Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
Example 1:
Input: nums = [1,3,5,6], target = 5
Output: 2
Example 2:
Input: nums = [1,3,5,6], target = 2
Output: 1
Example 3:
Input: nums = [1,3,5,6], target = 7
Output: 4
Example 4:
Input: nums = [1,3,5,6], target = 0
Output: 0
Example 5:
Input: nums = [1], target = 0
Output: 0
Constraints:
1 <= nums.length <= 104
-104 <= nums[i] <= 104
nums contains distinct values sorted in ascending order.
-104 <= target <= 104
*/
/*************************************************************************************/
/************************************ANSWER********************************************/
/***********************************************************************************/
var searchInsert = function (nums, target) {
if (nums.includes(target)) {
return nums.indexOf(target);
} else {
let bigger = nums.find((item) => item > target);
if (bigger) {
return nums.indexOf(bigger);
} else {
return nums.length;
}
}
};
searchInsert([1, 2, 5, 6], 3);
/**************************************************************************************/
/*************************************QUESTION********************************************/
/*******************************************************************************/
53. Maximum Subarray
Difficulty: Easy
Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
Example 1:
Input: nums = [-2,1,-3,4,-1,2,1,-5,4]
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.
Example 2:
Input: nums = [1]
Output: 1
Example 3:
Input: nums = [5,4,-1,7,8]
Output: 23
Constraints: 1 <= nums.length <= 3 * 104 -105 <= nums[i] <= 105
*/
/*************************************************************************************/
/************************************ANSWER********************************************/
/***********************************************************************************/
var maxSubArray = function(nums) {
let maxSoFar = nums[0];
let max = nums[0];
for(let i = 1; i < nums.length; i++){
let current = nums[i];
maxSoFar = Math.max(0, current + maxSoFar);
max = Math.max(max, maxSoFar);
}
return max;
};
var maxSubArray = function(nums) {
let max = Number.MIN_SAFE_INTEGER;
let sum = 0;
for(let i = 0; i <nums.length; i++){
sum += nums[i];
max = Math.max(max,sum);
sum = sum < 0 ? 0 : sum;
}
return max;
};
maxSubArray([8,-19,5,-4,20]);/**************************************************************************************/