├── FINAL450.xlsx
└── myNotes
/FINAL450.xlsx:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/priya42bagde/myDSA_CodingSolutions/HEAD/FINAL450.xlsx
--------------------------------------------------------------------------------
/myNotes:
--------------------------------------------------------------------------------
1 | 450 questions- https://drive.google.com/file/d/1FMdN_OCfOI0iAeDlqswCiC2DZzD4nPsb/view
2 | frequent asked quetions-https://docs.google.com/spreadsheets/d/1k6hcdNsmBPxSPqaqmUpRKqBjax1-miMaRRKcbscL3ow/edit#gid=0
3 | https://zhenchaogan.gitbook.io/leetcode-solution/leetcode-1-two-sum
4 | https://www.youtube.com/watch?v=0IAPZzGSbME&list=PLDN4rrl48XKpZkf03iYFl-O29szjTrs_O&index=1
5 | https://www.techinterviewhandbook.org/grind75
6 | GFG(company specific questions): https://www.geeksforgeeks.org/company-interview-corner/?ref=gcse
7 | Leetcode(explorer): https://leetcode.com/explore/
8 | Leetcode: https://leetcode.com/problem-list/top-interview-questions/
9 | https://leetcode.com/problemset/all/?status=AC&page=1(List of solved problems)
10 | https://leetcode.com/submissions/#/1(solutions of the solved problems)
11 | https://www.youtube.com/c/NeetCode
12 | Udemy: https://ibm-learning.udemy.com/course/js-algorithms-and-data-structures-masterclass/learn/lecture/8344148#overview
13 | https://www.geeksforgeeks.org/must-do-coding-questions-for-product-based-companies/?ref=shm
14 | https://practice.geeksforgeeks.org/explore?page=1&sortBy=submissions
15 | https://www.youtube.com/watch?v=PzWtPDGHV18&list=PL8EhujvLdk7WuGPfsDpE8jQMwv7I2YitK
16 |
17 | https://www.youtube.com/playlist?list=PLC3y8-rFHvwiRYB4-HHKHblh3_bQNJTMa
18 | https://www.bigocheatsheet.com/
19 | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
20 | Reverse of string/ array/ number:-
21 | var a = [1,2,3,4,5];
22 | a.reverse();
23 | document.write(a);
24 | ------------------------------------
25 | function customReverse(originalArray) {
26 | let leftIndex = 0;
27 | let rightIndex = originalArray.length - 1;
28 |
29 | while (leftIndex < rightIndex) {
30 | let temp = originalArray[leftIndex];
31 | originalArray[leftIndex] = originalArray[rightIndex];
32 | originalArray[rightIndex] = temp;
33 | leftIndex++;
34 | rightIndex--;
35 | }
36 | }
37 | let myArray = [1, 2, 3, 4, 5];
38 | customReverse(myArray);
39 | console.log(myArray);
40 | -------------------------------------
41 | let numbers = [1, 2, 3, 5];
42 | let reversedNumbers = [];
43 | for(let i = numbers.length -1; i >= 0; i--) {
44 | reversedNumbers.push(numbers[i]);
45 | }
46 | console.log(reversedNumbers);
47 | -----------------------------------
48 | var t = [];
49 | var a = [1,2,5];
50 | for(var i = 0; i < a.length;i++){
51 | t[i] = a[a.length-1-i]
52 | }
53 | console.log(t)
54 | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
55 | Find Minimum and Maximum Values in an Array:-(“[The spread] operator causes the values in the array to be expanded, or ‘spread,’ into the function’s arguments.”)
56 | Math.min(1,3,5) // 1
57 | Math.min([1,3,5]) // NaN
58 | // Using the spread operator
59 | Math.min(...[1,3,5]) // 1
60 | Math.max(...[1,3,5]) // 5
61 | ---------------------------------
62 | // Using Function.prototype.apply() instead of the spread operator
63 | Math.min.apply(null, [1,3,5]) // 1(first argument to .apply() is the target for this, which in this case does not matter, so I passed in null as the first argument.)
64 | Math.max.apply(null, [1,3,5]) // 5
65 | ----------------------------------
66 | const arr = [1,3,53];
67 | let minValue = arr[0]; let maxValue = arr[0];
68 | for(var i = 1; i < arr.length; i++){
69 | if(arr[i] < minValue){ //3<1 //53<0
70 | minValue = arr[i];
71 | }
72 | if(arr[i] > maxValue){ //3>1 //53>0
73 | maxValue = arr[i]; //3 //53
74 | }
75 | }
76 | console.log(minValue);
77 | console.log(maxValue);
78 | ---------------------------
79 | let arrayOfNumbers = [4, 12, 62, 70, -10];
80 | console.log("Max: " + Math.max.apply(Math, arrayOfNumbers));
81 | // output ==> Max: 70
82 | console.log("Min: " + Math.min.apply(Math, arrayOfNumbers));
83 | // output ==> Min: -10
84 | ----------------------------
85 | var arr = [ 3, 8, 7, 6, 5, -4, 31, 2, 21, 20, 1 ].sort(function(a, b) { return a - b }), // [-4, 1, 2, 3, 5, 6, 7, 8, 20, 21, 31]
86 | min = arr[0], // min
87 | max = arr[arr.length-1]; //max
88 | console.log(min, max);
89 | -----------------------------
90 | let arrayList = [1, 2, 3, 4, 3, 20, 0];
91 | let maxNum = arrayList.reduce((prev, current) => {
92 | return Math.max(prev, current)
93 | });
94 | let minNum = arrayList.reduce((prev, current) => {
95 | return Math.min(prev, current)
96 | });
97 | console.log(minNum);
98 | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
99 | To find kth mini and max from an array:-
100 | var numbers = [1,4,3,5,6,2];
101 | var sorted = numbers.sort(function(a, b) { return a - b });
102 | var smallest = sorted[0], secondSmallest = sorted[1], thirdSmallest = sorted[2],
103 | largest = sorted[sorted.length - 1], secondLargest = sorted[sorted.length - 2], thirdLargest = sorted[sorted.length - 3];
104 | console.log('Smallest: ' + smallest);
105 | console.log('Second Smallest: ' + secondSmallest);
106 | console.log('Third Smallest: ' + thirdSmallest);
107 | console.log('Third Largest: ' + thirdLargest);
108 | console.log('Second Largest: ' + secondLargest);
109 | console.log('Largest: ' + largest);
110 | -------------------------------
111 | function kthSmallest(arr, k){
112 | arr.sort((a,b) => a-b);
113 | return arr[k - 1];
114 | }
115 | console.log(kthSmallest([ 1,2,3,4,5,6,7,8,9,10], 3));
116 | function kthLargest(arr, k){
117 | arr.sort((a,b) => a-b);
118 | return arr[arr.length - k];
119 | }
120 | console.log(kthLargest([ 1,2,3,4,5,6,7,8,9,10], 3));
121 | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
122 | Given an array A[] consisting 0s, 1s and 2s, write a function that sorts A[]. The functions should put all 0s first, then all 1s and all 2s in last.
123 | function sort012(arr)
124 | {
125 | let count0 = 0, count1 = 0, count2 = 0;
126 | for (let i = 0; i < arr.length; i++) {
127 | if (arr[i] == 0) count0++;
128 | if (arr[i] == 1) count1++;
129 | if (arr[i] == 2) count2++;
130 | }
131 | for (let i = 0; i < count0; i++) arr[i] = 0;
132 | for (let i = count0; i <(count0 + count1); i++) arr[i] = 1;
133 | for (let i = (count0 + count1); i < arr.length; i++) arr[i] = 2;
134 |
135 | for (let i = 0; i < arr.length; i++) console.log(arr[i] + " ");
136 | }
137 | sort012([ 0,1, 1,0, 1, 2 ]);
138 | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
139 | Move all negative numbers to beginning and positive to end with constant extra space;-
140 | Algorithm===>
141 | Set the j to 0.
142 | Traversing the array from 0 to n(exclusively, where n is array’s length).
143 | Check if any element of an array is less than the 0,
144 | Check if i should not be equal to j,
145 | Swap the values of indexes arr[i] and arr[j], and increase the value of j.
146 | Print the array.
147 | -----------
148 | function rearrange(arr){
149 | for (let i = 0, j = 0; i < arr.length; i++)
150 | {
151 | if (arr[i] < 0) { //-1 //2 //-3 //4 //5
152 | if (i != j)
153 | { //0,0 //not // 2,1 // not,2 //
154 | let temp = arr[i]; //-3
155 | arr[i] = arr[j];
156 | arr[j] = temp; //arr[1]=-3 //
157 | }
158 | j++;
159 | }
160 | }
161 | for (let i = 0; i < arr.length; i++) document.write(arr[i] + " ");
162 | }
163 | rearrange([ -1, 2, -3, 4, -5, 6, -7, 8, 9 ]); //-1 -3 -5 -7 2 6 4 8 9
164 | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
165 | To find union and intersection of the 2 sorted arrays:-
166 | var a = [34, 35, 45, 48, 49];
167 | var b = [48, 55];
168 | var union = [...new Set([...a, ...b])];
169 | console.log(union);
170 | ------------------------------
171 | function union(a, b) {
172 | return a.concat(b.filter(function(el) {
173 | return a.indexOf(el) === -1;
174 | }));
175 | }
176 | console.log(union([1,2,3,4,5],[2,3,4,5,6,7,9]))
177 | -------------------------------------
178 | const arr1 = [1,2,3,4];
179 | const arr2 = [1,2,5,6];
180 | const intersection = arr1.filter(value=>arr2.includes(value));
181 | console.log(intersection); // [1,2] //duplicate
182 |
183 | const arr3 = [1,2,3,4];
184 | const arr4 = [1,2,5,6];
185 | const array3 = arr3.filter(value=>!arr4.includes(value));
186 | const array4 = arr4.filter(value=>!arr3.includes(value));
187 | console.log(array3.concat(array4)) //[3,4,5,6] //unique
188 | -----------------------------------
189 | const yourArray = [1,2,2,3,3,3,4,4,4,4]
190 | let duplicates = []
191 | const tempArray = [...yourArray].sort()
192 | for (let i = 0; i < tempArray.length; i++) {
193 | if (tempArray[i + 1] === tempArray[i]) {
194 | duplicates.push(tempArray[i]) //all the times of each duplicates //[2,3,3,4,4,4]
195 | }
196 | }
197 | console.log(duplicates)
198 | ----------------------------------
199 | function printUnion( arr1, arr2)
200 | {var i = 0, j = 0;
201 | while (i < arr1.length && j < arr2.length) { //5-0,1,2,3,4
202 | if (arr1[i] < arr2[j])
203 | document.write(arr1[i++] + " ");
204 | else if (arr2[j] < arr1[i])
205 | document.write(arr2[j++] + " ");
206 | else {
207 | document.write(arr2[j++] + " ");
208 | i++;
209 | }
210 | }
211 | while (i < arr1.length)
212 | document.write(arr1[i++] + " ");
213 | while (j < arr2.length)
214 | document.write(arr2[j++] + " ");
215 | }
216 | printUnion([ 1, 2, 4, 5, 6 ], [ 1, 2, 3, 5, 7 ]);
217 | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
218 | Program to cyclically rotate an array by one:-
219 | function rotate(arr)
220 | {
221 | var x = arr[arr.length-1], i;
222 | for(i = arr.length-1; i > 0; i--) arr[i] = arr[i-1];
223 | arr[0] = x;
224 | }
225 |
226 | let arr = [1, 2, 3, 4, 5];
227 | rotate(arr);
228 |
229 | for(var i = 0; i < arr.length; i++) document.write(arr[i] + " "); //5 1 2 3 4
230 | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
231 | Maximum Sum Subarray Problem (Kadane’s Algorithm) : https://dev.to/cleancodestudio/kadane-s-algorithm-maximum-sum-subarray-problem-2nhp
232 | function maxSubArraySum(nums) {
233 | let maxCurrent = nums[0];
234 | let maxGlobal = nums[0];
235 | for (let i = 1; i < nums.length; i++) {
236 | maxCurrent = Math.max(nums[i], maxCurrent + nums[i]);
237 | if (maxCurrent > maxGlobal) {
238 | maxGlobal = maxCurrent;
239 | }
240 | }
241 | return maxGlobal
242 | }
243 | let a = [-2, -3, 4, -1, -2, 1, 5, -3];
244 | let n = a.length;
245 | document.write("Maximum contiguous sum is ",maxSubArraySum(a, n));
246 | ------------------------------------------------------
247 | function maxSubArraySum(a,size)
248 | {
249 | let max_so_far = a[0];
250 | let curr_max = a[0];
251 | for (let i = 1; i < size; i++)
252 | {
253 | curr_max = Math.max(a[i], curr_max+a[i]);
254 | max_so_far = Math.max(max_so_far, curr_max);
255 | console.log(curr_max, max_so_far, a[i]); //max_so_far
256 | }
257 | return max_so_far;
258 | }
259 | let a = [-2, -3, 4, -1, -2, 1, 5, -3];
260 | let n = a.length;
261 | document.write("Maximum contiguous sum is ",maxSubArraySum(a, n));
262 | -----------------------------------------------------
263 | function maxSubArraySum(a , size) {
264 | var max_so_far = 0, max_ending_here = 0, start = 0, end = 0, s = 0;
265 | for (i = 0; i < size; i++) {
266 | max_ending_here = a[i]+max_ending_here;
267 | if (max_so_far < max_ending_here) { //0<-2
268 | max_so_far = max_ending_here;
269 | start = s;
270 | end = i;
271 | }
272 | if (max_ending_here < 0) {
273 | max_ending_here = 0;
274 | s = i + 1;
275 | }
276 | }
277 | document.write("Maximum contiguous sum is " + max_so_far);
278 | document.write("
Starting index " + start);
279 | document.write("
Ending index " + end);
280 | }
281 | var a = [ -2, -3, 4, -1, -2, 1, 5, -3 ];
282 | var n = a.length;
283 | maxSubArraySum(a, n);
284 | -----------------------------------------------
285 | Given an array arr[] denoting heights of N towers and a positive integer K, you have to modify the height of each tower either by increasing or decreasing them by K only once. After modifying, height should be a non-negative integer.
286 | Find out what could be the possible minimum difference of the height of shortest and longest towers after you have modified each tower.
287 | Expected Time Complexity: O(N*logN)
288 | Expected Auxiliary Space: O(N)
289 | Input:
290 | K = 2, N = 4
291 | Arr[] = {1, 5, 8, 10}
292 | Output:
293 | 5
294 | Explanation:
295 | The array can be modified as
296 | {3, 3, 6, 8}. The difference between
297 | the largest and the smallest is 8-3 = 5.
298 | ---
299 | function getMinDiff(arr, n, k) {
300 | var result = arr[n - 1] - arr[0];
301 | for (var i = 1; i < arr.length; i++)
302 | {
303 | min = Math.min(arr[0] + k, arr[i] - k);
304 | max = Math.max(arr[i - 1] + k, arr[n - 1] - k);
305 | console.log(max, min)
306 | result = Math.min(result, max-min);
307 | }
308 | return result;
309 | }
310 | console.log( getMinDiff([1, 5, 8, 10], 4, 2))
311 | --------------------------------------
312 | Given an array of N integers arr[] where each element represents the max number of steps that can be made forward from that element. Find the minimum number of jumps to reach the end of the array (starting from the first element). If an element is 0, then you cannot move through that element.
313 | Note: Return -1 if you can't reach the end of the array.
314 | https://www.youtube.com/watch?v=muDPTDrpS28
315 |
316 | function jumpPossible(arr){
317 | var reachable = 0;
318 | for(var i=0; i arr2[0]) { //4>2
382 | if (arr1[i] > arr2[0]) { //1>2 //4>2
383 | // Swap arr1[i] with first element of arr2 and
384 | // sorting the updated arr2(arr1 is already sorted)
385 | // swap(arr1[i],arr2[0]);
386 | temp = arr1[i]; //1
387 | arr1[i] = arr2[0]; //2
388 | arr2[0] = temp;
389 | arr2.sort((a,b)=>a-b);
390 | }
391 | i++;
392 | }
393 | }
394 | merge(arr1.length, arr2.length);
395 | document.write("After Merging
First Array: ");
396 | document.write(arr1.toString());
397 | document.write("
Second Array: ");
398 | document.write(arr2.toString());
399 | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
400 | Kadane's Algorithm:- Given an array Arr[] of N integers. Find the contiguous sub-array(containing at least one number) which has the maximum sum and return its sum.
401 | function sumSubArray(arr){
402 | var maxi=arr[0]; //1 //2//5
403 | var cursum=arr[0]; //1 //2 //3 //1
404 | for(var i=1;i max) {
421 | max = sum;
422 | }
423 | if (sum < 0 ) {
424 | sum = 0;
425 | }
426 | }
427 | return max;
428 | }
429 | console.log(sumSubArray([ -1,-2,-3,-4])) //-1
430 | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
431 | Given an array of intervals where intervals[i] = [starti, endi], merge all overlapping intervals, and return an array of the non-overlapping intervals that cover
432 | all the intervals in the input.
433 | Example 1:
434 | Input: intervals = [[1,3],[2,6],[8,10],[15,18]]
435 | Output: [[1,6],[8,10],[15,18]]
436 | Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6].
437 | -------
438 | https://www.youtube.com/watch?v=LvygwImtvEw
439 | function merge(intervals) {
440 | intervals.sort((a,b) => a[0] - b[0]);
441 | let result = [intervals[0]];
442 | for (let interval of intervals ) {
443 | let e1 = result[result.length-1][1];
444 | let s2 = interval[0];
445 | let e2 = interval[1];
446 | if(e1>=s2){
447 | result[result.length-1][1] = Math.max(e1,e2);
448 | } else {
449 | result.push(interval)
450 | }
451 | }
452 | return result;
453 | };
454 | console.log(merge([[1,3],[2,6],[8,10],[15,18]]))
455 | -------------------------------------------
456 | function merge(intervals) {
457 | intervals.sort((a,b) => a[0] - b[0]); document.write(intervals +"
");
458 | let results = [[intervals[0][0], intervals[0][1]]]; document.write(results +"
");
459 |
460 | for (let i = 1; i < intervals.length; i++) { //1,2,3
461 | if (intervals[i][0] <= results[results.length-1][1]) { 2<6
462 | results[results.length-1][1] = Math.max(results[results.length-1][1], intervals[i][1]) // 6,6
463 | } else {
464 | results.push(intervals[i])
465 | }
466 | }
467 | return results;
468 | };
469 | console.log(merge([[1,3],[2,6],[8,10],[15,18]]))
470 | --------------------------------------------------
471 | function merge(intervals) {
472 | if(intervals.length <= 1) return intervals; //// test if there are at least 2 intervals
473 | var result = []; var top = null;
474 | intervals = intervals.sort(function(a, b) {return a[0] - b[0]});
475 | result.push(intervals[0]); //document.write(result) //// push the 1st interval into the result
476 |
477 | // start from the next interval and merge if needed
478 | for (var i = 1; i < intervals.length; i++)
479 | {
480 | // get the top element
481 | top = result[result.length - 1];
482 | // if the current interval doesn't overlap with the
483 | // result top element, push it to the result
484 | if (top[1] < intervals[i][0]) {
485 | result.push(intervals[i]);
486 | }
487 | // otherwise update the end value of the top element
488 | // if end of current interval is higher
489 | else if (top[1] < intervals[i][1])
490 | {
491 | top[1] = intervals[i][1];
492 | result.pop();
493 | result.push(top);
494 | }
495 | }
496 | return result;
497 | }
498 | console.log(merge([[1,3],[2,6],[8,10],[15,18]]))
499 | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
500 | Next Permutation:-Implement the next permutation, which rearranges the list of numbers into Lexicographically next greater permutation of list of numbers.
501 | If such arrangement is not possible, it must be rearranged to the lowest possible order i.e. sorted in an ascending order. You are given an list of numbers arr[ ] of size N.
502 | https://www.youtube.com/watch?v=IhsUbEMfIbY
503 | var nextPermutation = function(nums) {
504 | let index = -1; // // Index of the first element that is smaller than the element to its right.
505 | for (let i = nums.length - 1; i > 0; i--) { //2,1 //Loop from right to left
506 | if (nums[i] > nums[i - 1]) { //3>2 //2>1
507 | index = i - 1; //1=2-1 //0=1-1
508 | break;
509 | }
510 | }
511 | if (index === -1) {
512 | reverse(nums, 0, nums.length - 1);
513 | return nums;
514 | }
515 | let j = nums.length - 1; // Again swap from right to left to find first element that is greater than the above find element
516 | for (let i = nums.length - 1; i >= index + 1; i--) {
517 | if (nums[i] > nums[index]) {
518 | j = i;
519 | break;
520 | }
521 | }
522 | swap(nums, index, j);
523 | reverse(nums, index + 1, nums.length - 1);
524 | return nums;
525 | };
526 |
527 | const reverse = (nums, i, j) => {
528 | while (i < j) {
529 | swap(nums, i, j);
530 | i++;
531 | j--;
532 | }
533 | };
534 |
535 | const swap = (nums, i, index) => {
536 | const temp = nums[index];
537 | nums[index] = nums[i];
538 | nums[i] = temp;
539 | };
540 | console.log(nextPermutation([1, 2, 3]))
541 | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
542 | Find the Inversion Count in the array. Inversion Count: For an array, inversion count indicates how far (or close) the array is from being sorted. If array is already sorted then the inversion count is 0.
543 | If an array is sorted in the reverse order then the inversion count is the maximum.
544 | Formally, two elements a[i] and a[j] form an inversion if a[i] > a[j] and i < j.
545 | https://www.youtube.com/watch?v=k9RQh21KrH8&t=119s
546 | var countInversion = function(arr) {
547 | let count=0;
548 | for(var i=0; iarr[j]){ document.write(arr[i], arr[j] + " ")
551 | count++;
552 | }
553 | }
554 | }
555 | return count;
556 | }
557 | console.log(countInversion([2, 4, 1, 3, 5])) //3
558 | -----------------------------------------
559 | function mergeAndCount(arr,l,m,r){
560 | // Left subarray
561 | let left = [];
562 | for(let i = l; i < m + 1; i++)
563 | {
564 | left.push(arr[i]);
565 |
566 | }
567 |
568 | // Right subarray
569 | let right = [];
570 | for(let i = m + 1; i < r + 1; i++)
571 | {
572 | right.push(arr[i]);
573 | }
574 | let i = 0, j = 0, k = l, swaps = 0;
575 | while (i < left.length && j < right.length)
576 | {
577 | if (left[i] <= right[j])
578 | {
579 | arr[k++] = left[i++];
580 | }
581 | else
582 | {
583 | arr[k++] = right[j++];
584 | swaps += (m + 1) - (l + i);
585 | }
586 | }
587 | while (i < left.length)
588 | {
589 | arr[k++] = left[i++];
590 | }
591 | while (j < right.length)
592 | {
593 | arr[k++] = right[j++];
594 | }
595 | return swaps;
596 | }
597 |
598 | // Merge sort function
599 | function mergeSortAndCount(arr, l, r){
600 | // Keeps track of the inversion count at a
601 | // particular node of the recursion tree
602 | let count = 0;
603 | if (l < r)
604 | {
605 | let m = Math.floor((l + r) / 2);
606 |
607 | // Total inversion count = left subarray count
608 | // + right subarray count + merge count
609 |
610 | // Left subarray count
611 | count += mergeSortAndCount(arr, l, m);
612 |
613 | // Right subarray count
614 | count += mergeSortAndCount(arr, m + 1, r);
615 |
616 | // Merge count
617 | count += mergeAndCount(arr, l, m, r);
618 | }
619 | return count;
620 | }
621 | // Driver code
622 | let arr= [2, 4, 1, 3, 5]
623 | document.write(mergeSortAndCount(arr, 0, arr.length - 1));
624 | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------
625 | Best Time to Buy and Sell Stock:-
626 | var maxProfit = function(prices) {
627 | let profit
628 | let maxProfit = 0
629 | prices.forEach(function(buy, index) {
630 | let rest = prices.slice(index + 1); document.write(rest+ "---");
631 | if (rest){
632 | let sell = Math.max(...rest)
633 | sell > buy ? profit = sell - buy : null
634 | profit > maxProfit ? maxProfit = profit : null
635 | console.log(profit)
636 | }
637 | })
638 | return maxProfit
639 | };
640 | console.log(maxProfit ([7,1,5,3,6,4]))
641 | ------------------------------------
642 | const maxProfit = function(prices) {
643 | let maxProfit = 0; let min = prices[0];
644 | let lowestPrice = prices[0];
645 | for(let i = 1; i < prices.length; i++) {
646 | min = Math.min(prices[i], min);
647 | maxProfit = Math.max(maxProfit, prices[i] - min);
648 | }
649 | return maxProfit;
650 | };
651 | console.log(maxProfit ([7,1,5,3,6,4]))
652 | -------------------------------------
653 | Count pairs with given sum :-
654 | function getPairsCount(arr, n, sum)
655 | {
656 | let count = 0; // Initialize result
657 | for (let i = 0; i < n; i++)
658 | for (let j = i + 1; j < n; j++)
659 | if (arr[i] + arr[j] == sum){
660 | count++;
661 | console.log(arr[i], arr[j])
662 | }
663 |
664 | return count;
665 | }
666 | let arr = [ 1, 5, 7, -1, 5 ];
667 | let n = arr.length;
668 | let sum = 6;
669 | document.write("Count of pairs is " + getPairsCount(arr, n, sum));
670 | ------------------------------------
671 | function printPairs(arr, n, sum) {
672 | var m = {};
673 | for (var i = 0; i < n; i++) {
674 | var rem = sum - arr[i];
675 | if (m.hasOwnProperty(rem)) {
676 | var count = m[rem];
677 | for (var j = 0; j < count; j++) {
678 | document.write("(" + rem + ", " + arr[i] + ")" + "
");
679 | }
680 | }
681 | if (m.hasOwnProperty(arr[i])) {
682 | m[arr[i]]++;
683 | } else {
684 | m[arr[i]] = 1;
685 | }
686 | }
687 | }
688 | var arr = [1, 5, 7, -1, 5];
689 | var n = arr.length;
690 | var sum = 6;
691 | printPairs(arr, n, sum);
692 | ---------------------------------------
693 | function pairedElements(arr, sum, n) {
694 | var low = 0;
695 | var high = n - 1;
696 | while (low < high) {
697 | if (arr[low] + arr[high] == sum) {
698 | document.write("The pair is : (" +
699 | arr[low] + ", " +
700 | arr[high] + ")
");
701 | }
702 | if (arr[low] + arr[high] > sum) {
703 | high--;
704 | }
705 | else {
706 | low++;
707 | }
708 | }
709 | }
710 | var arr = [ 2, 3, 4, -2, 6, 8, 9, 11]
711 | var n = arr.length;
712 | arr.sort(function(a,b){return a-b;});
713 | pairedElements(arr, 6, n);
714 | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
715 | Given three arrays sorted in increasing order. Find the elements that are common in all three arrays. https://www.youtube.com/watch?v=ajWCEu1razQ
716 | function findCommon(ar1, ar2, ar3, n1, n2, n3)
717 | {
718 | var i = 0,j = 0,k = 0;
719 | while (i < n1 && j < n2 && k < n3)
720 | {
721 | if (ar1[i] == ar2[j] && ar2[j] == ar3[k])
722 | {
723 | document.write(ar1[i] + " ");
724 | i++;
725 | j++;
726 | k++;
727 | }
728 | else if (ar1[i] < ar2[j]) i++;
729 | else if (ar2[j] < ar3[k]) j++;
730 | else k++;
731 | }
732 | }
733 | var ar1 = [1, 5, 10, 20, 40, 80];
734 | var ar2 = [6, 7, 20, 80, 100];
735 | var ar3 = [3, 4, 15, 20, 30, 70, 80, 120];
736 | var n1 = ar1.length;
737 | var n2 = ar2.length;
738 | var n3 = ar3.length;
739 | document.write("Common Elements are ");
740 | findCommon(ar1, ar2, ar3, n1, n2, n3);
741 | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
742 | Rearrange array in alternating positive & negative items with O(1) extra space: https://www.youtube.com/watch?v=5MeI5Kk8KTQ
743 | function rightrotate(arr , n , outofplace , cur) {
744 | var tmp = arr[cur];
745 | for ( var i = cur; i > outofplace; i--)
746 | arr[i] = arr[i - 1];
747 | arr[outofplace] = tmp;
748 | }
749 | function rearrange(arr , n) {
750 | var outofplace = -1;
751 | for (var index = 0; index < n; index++)
752 | {
753 | if (outofplace >= 0)
754 | {
755 | if ((arr[index] >= 0 && arr[outofplace] < 0) || (arr[index] < 0 && arr[outofplace] >= 0)) {
756 | if (index - outofplace >= 2)
757 | outofplace = outofplace + 2;
758 | else
759 | outofplace = -1;
760 | }
761 | }
762 | if (outofplace == -1) {
763 | if ((arr[index] <0 && index%2 == 1) || (arr[index] >= 0 && index%2 == 0))
764 | outofplace = index;
765 | }
766 | }
767 | }
768 | function printArray(arr , n) {
769 | for (i = 0; i < n; i++)
770 | document.write(arr[i] + " ");
771 | document.write("");
772 | }
773 | var arr = [ -5, -2, 5, 2, 4, 7, 1, 8, 0, -8 ];
774 | var n = arr.length;
775 |
776 | document.write("Given array is ");
777 | printArray(arr, n);
778 |
779 | rearrange(arr, n);
780 |
781 | document.write("
RearrangeD array is ");
782 | printArray(arr, n);
783 | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
784 | subArray sum equals to zero:-
785 | const subArrayExists = (arr) => {
786 | const sumSet = new Set();
787 | // Traverse through array and store prefix sums
788 | let sum = 0;
789 | for (let i = 0 ; i < arr.length ; i++)
790 | {
791 | sum = sum + arr[i]; //0+4=4 // 4+2=6 //6+(-3)=3 //3+1=4
792 | document.write(arr[i] + " ")
793 | if (sum === 0 || sumSet.has(sum)) return true; // If prefix sum is 0 or it is already present
794 | sumSet.add(sum);
795 | }
796 | return false;
797 | }
798 | const arr = [4, 2, 0, 1, 6] //[4, 2, -3, 1, 6];
799 | if (subArrayExists(arr))
800 | console.log("Found a subarray with 0 sum");
801 | else
802 | console.log("No Such Sub Array Exists!");
803 | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
804 | Factorials of large numbers
805 | function factorialize(num) {
806 | if (num < 0) return -1;
807 | else if (num == 0) return 1;
808 | else { return (num * factorialize(num - 1)); }
809 | }
810 | console.log(factorialize(5));
811 | ------------------------------------------
812 | function factorialize(num) {
813 | var result = num;
814 | if (num === 0 || num === 1) return 1;
815 | while (num > 1)
816 | {
817 | num--;
818 | result *= num;
819 | }
820 | return result;
821 | }
822 | console.log(factorialize(5));
823 | -----------------------------------------
824 | function factorialize(num) {
825 | if (num === 0 || num === 1)
826 | return 1;
827 | for (var i = num - 1; i >= 1; i--) {
828 | num *= i;
829 | }
830 | return num;
831 | }
832 | console.log(factorialize(5));
833 | -----------------------------------------------------------------------------------------------------------------------------------------------------------------------------
834 | Maximum Product Subarray
835 | function productSubArray(nums) {
836 | let globalMaxProduct = nums[0];
837 | for (let i = 0; i < nums.length; i++) {
838 | let localMaxProduct = 1;
839 | for (let j = i; j < nums.length; j++) {
840 | localMaxProduct *= nums[j];
841 |
842 | if (localMaxProduct > globalMaxProduct) {
843 | globalMaxProduct = localMaxProduct;
844 | }
845 | }
846 | }
847 | return globalMaxProduct;
848 | }
849 | console.log(productSubArray([6, -3, -10, 0, 2]))
850 | -------------------------------------------------
851 | function productSubArray(nums) {
852 | if(nums == null || nums.length == 0) return 0;
853 | if(nums.length ==1) return nums[0];
854 | let maxProduct = 0;
855 | let currProduct = 1;
856 | for (let i = 0; i < nums.length; i++) {
857 | currProduct *= nums[i];
858 | maxProduct = Math.max(currProduct, maxProduct);
859 | if(currProduct ==0) currProduct = 1;
860 | }
861 | currProduct = 1;
862 | for (let i = nums.length-1; i >=0; i--) {
863 | currProduct *= nums[i];
864 | maxProduct = Math.max(currProduct, maxProduct);
865 | if(currProduct ==0) currProduct = 1;
866 | }
867 | return maxProduct
868 | }
869 | console.log(productSubArray([6, -3, -10, 0, 2]))
870 | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
871 | Longest consecutive subsequence :-
872 | function findLongestConseqSubseq(arr, n) {
873 | let count = 0;
874 | arr.sort(function (a, b) { return a - b; })
875 | var v = [];
876 | v.push(arr[0]);
877 | for (let i = 1; i < n; i++) { //remove duplicate elements //or use include method
878 | if (arr[i] != arr[i - 1])
879 | v.push(arr[i]);
880 | }
881 | console.log(v)
882 | for (let i = 0; i < v.length; i++) { //main logic to find longest length
883 | if (v[i] - v[i - 1] == 1){
884 | count++;
885 | console.log(v[i])
886 | }
887 | }
888 | return count;
889 | }
890 | let arr = [1, 9, 3, 10, 4, 20, 2];
891 | let n = arr.length;
892 | document.write( "Length of the Longest contiguous subsequence is " +findLongestConseqSubseq(arr, n) );
893 | -----------------------------------------------
894 | function findLongestConseqSubseq(arr, n) {
895 | var mx = 0; var count = 0; arr.sort(function (a, b) { return a - b; })
896 | for (var i = 0; i < n; i++) {
897 | if (i > 0 && (arr[i] == arr[i - 1] + 1)) { // Check if the previous value is consecutive to the current value.
898 | count++;
899 | }
900 | else if (i > 0 && arr[i] == arr[i - 1]) { // Skip if the current value is equal to the previous value.
901 | continue;
902 | }
903 | else { // Resetting count for next upcoming consecutive sequence.
904 | count = 1;
905 | }
906 | mx = Math.max(mx, count);
907 | }
908 | return mx;
909 | }
910 | let arr = [1, 9, 3, 10, 4, 20, 2];
911 | let n = arr.length;
912 | document.write("Length of the Longest contiguous subsequence is " + findLongestConseqSubseq(arr, n));
913 | -----------------------------------------------
914 | function findLongestConseqSubseq(arr, n) {
915 | let S = new Set(); let ans = 0;
916 | for (let i = 0; i < n; i++) S.add(arr[i]); // Hash all the array elements
917 | for (let i = 0; i < n; i++)
918 | {
919 | if (!S.has(arr[i] - 1)) //if element not present //0 // if current element is the starting element of a sequence
920 | {
921 | let j = arr[i]; //j=1//2 //3//4 // Then check for next elementsin the sequence
922 | while (S.has(j))
923 | j++; //2
924 | ans = Math.max(ans, j - arr[i]);
925 | }
926 | }
927 | return ans;
928 | }
929 | let arr = [1, 9, 3, 10, 4, 20, 2];
930 | let n = arr.length;
931 | document.write("Length of the Longest contiguous subsequence is " + findLongestConseqSubseq(arr, n));
932 | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------
933 | Given an array of size n and a number k, find all elements that appear more than n/k times
934 | function morethanNdK(a,n,k)
935 | {
936 | let x = n / k;
937 | let y=new Map(); // Hash map initialization
938 | for (let i = 0; i < n; i++) // count the frequency of each element.
939 | {
940 | if (!y.has(a[i])) // element doesn't exist in hash table
941 | y.set(a[i], 1);
942 | else // element exist in the hash table
943 | {
944 | let count = y.get(a[i]);
945 | y.set(a[i], count + 1);
946 | }
947 | }
948 | for (let [key, value] of y.entries()) // iterate over each element in the hash table and check their frequency, if it is more than n/k, print it.
949 | {
950 | let temp = value;
951 | if (temp > x) document.write(key+"
");
952 | }
953 | }
954 | let a=[1, 1, 2, 2, 3, 5, 4, 2, 2, 3, 1, 1, 1]; console.log(a.sort())
955 | let n = 12;
956 | let k = 4;
957 | morethanNdK(a, n, k);
958 | -----------------------------------------
959 | function printElements(arr , n , k) {
960 | var x = parseInt(n / k);
961 | var mp = new Map(); // Counting frequency of every element using Counter //MAP works on key-value pairs
962 | for (var i = 0; i < n; i++) {
963 | if (mp.has(arr[i]))
964 | mp.set(arr[i],mp.get(arr[i])+1);
965 | else
966 | mp.set(arr[i], 1);
967 | }
968 | for (var k of mp) { // Traverse the map and print all the elements with occurrence more than n/k times
969 | if (parseInt(k[1]) > x) document.write(k[0]+"
");
970 | }
971 | }
972 | var arr = [ 1, 1, 2, 2, 3, 5, 4, 2, 2, 3, 1, 1, 1 ];
973 | var n = arr.length;
974 | var k = 4;
975 | printElements(arr, n, k);
976 | -----------------------------------------------------------------------------------------------------------------------------------------------------------------------
977 | Maximum profit by buying and selling a share at most twice:-
978 | var price = [ 2, 30, 15, 10, 8, 25, 80 ];
979 | var n = price.length;
980 | var profit = 0;
981 | for (var i = 1; i < n; i++) //1,2,3,4,5,6
982 | {
983 | var sub = price[i] - price[i - 1]; // 28=30-2 //15-30 //10-15 //8-10 //25-8 //80-25
984 | if (sub > 0) //28 //-15 //-5 //-2 //17 //55
985 | { console.log(price[i-1], price[i]);
986 | profit += sub; //28 //17 //55
987 | }
988 | }
989 | document.write("Maximum Profit=" + profit);
990 | -------------------------------------------------
991 | Array Subset of another array :-
992 | function isSubset(arr1, arr2){
993 | let i = 0;let j = 0;
994 | for (i = 0; i < arr2.length; i++) { //0, 1, 2, 3
995 | for (j = 0; j < arr1.length; j++){ //0,1,2,3,4,5
996 | if (arr2[i] == arr1[j]) //11=11 //11=1 //11=13 //11=21 //11=3 //11=7
997 | break;}
998 | if (j == arr1.length) // If the above inner loop was not broken at all then arr2[i] is not present in arr1[]
999 | return false;
1000 | }
1001 | return true; /* If we reach here then all elements of arr2[] are present in arr1[] */
1002 | }
1003 | let arr1 = [ 11, 1, 13, 21, 3, 7 ]; //j
1004 | let arr2 = [ 11, 3, 7, 1 ]; //i
1005 | if (isSubset(arr1, arr2)) document.write("arr2[] is " + "subset of arr1[] ");
1006 | else document.write("arr2[] is " + "not a subset of arr1[]");
1007 | --------------------------------------------
1008 | function isSubset(arr1, arr2)
1009 | {
1010 | arr1.sort(function(a,b){return a-b}); arr2.sort(function(a,b){return a-b})
1011 | let i = 0, j = 0
1012 | while (i < arr1.length && j < arr2.length )
1013 | {
1014 | if( arr1[i] < arr2[j] )
1015 | i = i+1
1016 | else if( arr1[i] == arr2[j] )
1017 | {
1018 | j = j+1
1019 | i = i+1
1020 | }
1021 | else if( arr1[i] > arr2[j] )
1022 | return -1
1023 | }
1024 | if (j PlayerOne.includes(val));
1035 | console.log(result);
1036 | --------------------------------------------------
1037 | function isSubset(arr1, arr2){
1038 | let i = 0, j = 0;
1039 | if (arr1.length< arr2.length) return 0;
1040 | arr1.sort((a, b) => a - b); arr2.sort((a, b) => a - b);
1041 | while (i < arr2.length && j < arr1.length)
1042 | {
1043 |
1044 | // If the element is smaller than
1045 | // Move aheaad in the first array
1046 | if (arr1[j] < arr2[i])
1047 | j++;
1048 |
1049 | // If both are equal, then move
1050 | // both of them forward
1051 | else if (arr1[j] == arr2[i])
1052 | {
1053 | j++;
1054 | i++;
1055 | }
1056 |
1057 | // If we donot have a element smaller
1058 | // or equal to the second array then break
1059 | else if (arr1[j] > arr2[i])
1060 | return 0;
1061 | }
1062 | return (i < arr1.length) ? false : true;
1063 | }
1064 | let arr1 = [ 11, 1, 13, 21, 3, 7 ];
1065 | let arr2 = [ 11, 3, 7, 1 ];
1066 | consol.log(isSubset(arr1, arr2, m, n))
1067 | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------
1068 | function isSubset(arr1, arr2){
1069 | let i = 0, j = 0;
1070 | if (arr1.length < arr2.length) return 0;
1071 | arr1.sort((a, b) => a - b);
1072 | arr2.sort((a, b) => a - b);
1073 | while (i < arr2.length && j < arr1.length)
1074 | {
1075 | if (arr1[j] < arr2[i]) // If the element is smaller than Move aheaad in the first array
1076 | j++;
1077 | else if (arr1[j] == arr2[i]) // If both are equal, then move both of them forward
1078 | {
1079 | j++;
1080 | i++;
1081 | }
1082 | else if (arr1[j] > arr2[i]) // If we donot have a element smaller or equal to the second array then break
1083 | return 0;
1084 | }
1085 | return (i < arr2.length) ? false : true;
1086 | }
1087 | let arr1 = [ 11, 1, 13, 21, 3, 7 ]; //j
1088 | let arr2 = [ 11, 3, 7, 1 ]; //i
1089 | if (isSubset(arr1, arr2)) document.write("arr2[] is subset of arr1[] ");
1090 | else document.write("arr2[] is not a subset of arr1[] ");
1091 | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
1092 | Triplet Sum in Array:--
1093 | function find3Numbers(A, arr_size, sum){
1094 | let l, r;
1095 | for (let i = 0; i < arr_size - 2; i++)
1096 | {
1097 | for (let j = i + 1; j < arr_size - 1; j++)
1098 | {
1099 | for (let k = j + 1; k < arr_size; k++)
1100 | {
1101 | if (A[i] + A[j] + A[k] == sum)
1102 | {
1103 | document.write("Triplet is " + A[i] + ", " + A[j] + ", " + A[k]);
1104 | return true;
1105 | }
1106 | }
1107 | }
1108 | }
1109 | return false;
1110 | }
1111 | let A = [ 1, 4, 45, 6, 10, 8 ];
1112 | let sum = 11;
1113 | let arr_size = A.length;
1114 | console.log(find3Numbers(A, arr_size, sum));
1115 | ----------------------------------------------
1116 | function find3Numbers(A, arr_size, sum){
1117 | let l, r;
1118 | A.sort((a,b) => a-b);
1119 | for (let i = 0; i < arr_size - 2; i++) {
1120 | l = i + 1; r = arr_size - 1;
1121 | while (l < r) {
1122 | if (A[i] + A[l] + A[r] == sum){
1123 | document.write("Triplet is " + A[i] + ", " + A[l] + ", " + A[r]);
1124 | return true;
1125 | }
1126 | else if (A[i] + A[l] + A[r] < sum)
1127 | l++;
1128 | else // A[i] + A[l] + A[r] > sum
1129 | r--;
1130 | }
1131 | }
1132 | return false;
1133 | }
1134 | let A = [ 1, 4, 45, 6, 10, 8 ];
1135 | let sum = 22;
1136 | let arr_size = A.length;
1137 | console.log(find3Numbers(A, arr_size, sum));
1138 | --------------------------------------------------
1139 | function find3Numbers(A,arr_size,sum){
1140 | for (let i = 0; i < arr_size - 2; i++) {
1141 | // Find pair in subarray A[i+1..n-1] with sum equal to sum - A[i]
1142 | let s = new Set();
1143 | let curr_sum = sum - A[i];
1144 | for (let j = i + 1; j < arr_size; j++)
1145 | {
1146 | if (s.has(curr_sum - A[j]))
1147 | {
1148 | document.write("Triplet is " +A[i]+", "+A[j]+", "+(curr_sum - A[j])+"
" );
1149 | return true;
1150 | }
1151 | s.add(A[j]);
1152 | }
1153 | }
1154 | return false;
1155 | }
1156 | let A = [ 1, 4, 45, 6, 10, 8 ];
1157 | let sum = 11;
1158 | let arr_size = A.length;
1159 | console.log(find3Numbers(A, arr_size, sum));
1160 | -----------------------------------------------------------------------------------------------------------------------------------------------------------------------------
1161 | Trapping Rain Water :- https://www.youtube.com/watch?v=F4d15bMiYEQ
1162 | function rainWater(arr){
1163 | let n = arr.length; let left = [n]; let right= [n]; let result = 0;
1164 | left[0] = arr[0];
1165 | for(var i =1 ; i=0; i--){
1170 | right[i]= Math.max(right[i+1], arr[i])
1171 | }
1172 | for (var i =1; i x) return 1;
1205 | for (let end=start+1; end x && (end - start + 1) < min_len) //56>51 // <7
1209 | min_len = (end - start + 1); console.log(end - start + 1);
1210 | }
1211 | }
1212 | return min_len;
1213 | }
1214 | let arr1 = [ 1, 4, 45, 6, 10, 19 ];
1215 | let x = 51;
1216 | let n1 = arr1.length;
1217 | let res1 = smallestSubWithSum(arr1, n1, x);
1218 | (res1 == n1 + 1) ? document.write("Not possible
"): document.write(res1 + "
");
1219 | -----------------------------------------------------
1220 | function smallestSubWithSum(arr, n, x) //x=51, n=6
1221 | {
1222 | let min_len = n + 1; //7
1223 | for (let start=0; start x) return 1;
1227 | for (let end=start+1; end x && (end - start + 1) < min_len) //56>51 // <7
1231 | min_len = (end - start + 1);
1232 | }
1233 | }
1234 | return min_len;
1235 | }
1236 | let arr1 = [ 1, 4, 45, 6, 10, 19 ];
1237 | let x = 51;
1238 | let n1 = arr1.length;
1239 | let res1 = smallestSubWithSum(arr1, n1, x);
1240 | (res1 == n1 + 1) ? document.write("Not possible
"): document.write(res1 + "
");
1241 | ---------------------------------------------------------------
1242 | function smallestSubWithSum(arr, n, x) //x=51, n=6
1243 | {
1244 | let min=n + 1, sum=0, start=0, end=0;
1245 | while(endx && start"): document.write(res1 + "
");
1261 | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
1262 | Three way partitioning of an array around a given range:-
1263 | function threeWayPartition(arr,n, lowVal, highVal)
1264 | {
1265 | let start = 0, end = n - 1;
1266 | for(let i = 0; i <= end;)
1267 | {
1268 | if (arr[i] < lowVal)
1269 | {
1270 | let temp = arr[start];
1271 | arr[start] = arr[i];
1272 | arr[i] = temp;
1273 | start++;
1274 | i++;
1275 | }
1276 | else if(arr[i] > highVal)
1277 | {
1278 | let temp = arr[end];
1279 | arr[end] = arr[i];
1280 | arr[i] = temp;
1281 | end--;
1282 | }
1283 | else
1284 | i++;
1285 | }
1286 | }
1287 | let arr = [ 1, 14, 5, 20, 4, 2, 54, 20, 87, 98, 3, 1, 32 ];
1288 | let n = arr.length;
1289 | threeWayPartition(arr, n, 10, 20);
1290 | document.write("Modified array
");
1291 | for(let i = 0; i < n; i++) document.write(arr[i] + " ");
1292 | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
1293 | Minimum swaps and K together :- https://www.youtube.com/watch?v=PLu6uvp9l1k
1294 | function minSwap(arr, n, k) {
1295 | var good=0, bad=0;
1296 | for (var i = 0; i < n; i++){ // Find count of elements which are less than equals to k
1297 | if (arr[i] <= k) good++; //3
1298 | }
1299 | var bad = 0; // Find unwanted elements in current window of size 'count'
1300 | for (var i = 0; i < good; i++){ //0,1,2 <3
1301 | if (arr[i] > k) bad++; //5
1302 | }
1303 | var i=0, j=good, ans = bad;
1304 | while(j k) bad--;
1306 | if (arr[j] > k) bad++;
1307 | ans = Math.min(ans, bad);
1308 | i++; j++;
1309 | }
1310 | return ans;
1311 | }
1312 | var arr=[2, 1, 5, 6, 3]; var n =arr.length; var k = 3;
1313 | document.write(minSwap(arr, n, k));
1314 | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
1315 | Palindromic Array :- (Find minimum number of merge operations to make an array palindrome)(https://www.youtube.com/watch?v=wiDLcGxhh80)
1316 | function arrayPalindrome(arr,n){
1317 | let result=0, i=0, j=n-1;
1318 | while(iarr[j]){
1328 | j--;
1329 | arr[j]=arr[j]+arr[j+1];
1330 | result++;
1331 | }
1332 | }
1333 | return result;
1334 | }
1335 | let arr=[1, 4, 5, 9, 1];
1336 | let n= arr.length;
1337 | console.log(arrayPalindrome(arr,n))
1338 | -------------------------------------------
1339 | function palindrome(arr, n){
1340 | let flag = 0;
1341 | for (let i = 0; i <= n / 2 && n != 0; i++) { // Loop till array size n/2.
1342 | if (arr[i] != arr[n - i - 1]) { // Check if first and last element are different Then set flag to 1.
1343 | flag = 1;
1344 | break;
1345 | }
1346 | }
1347 | if (flag == 1) document.write("Not Palindrome");
1348 | else document.write("Palindrome");
1349 | }
1350 | let arr = [ 1, 2, 3, 2, 1 ];let n = arr.length;
1351 | palindrome(arr, n); //palindrome
1352 | ---------------------------------------
1353 | function isPalindrome(N){ //121
1354 | let str = "" + N;
1355 | let len = str.length;
1356 | for (let i = 0; i < parseInt(len / 2, 10); i++){
1357 | if (str[i] != str[len - 1 - i ])
1358 | return false;
1359 | }
1360 | return true;
1361 | }
1362 | function isPalinArray(arr, n){ // Function to check if an array is PalinArray or not
1363 | for (let i = 0; i < n; i++){ //121
1364 | let ans = isPalindrome(arr[i]);
1365 | if (ans == false)
1366 | return false;
1367 | }
1368 | return true;
1369 | }
1370 | let arr = [ 121, 131, 20 ];
1371 | let n = arr.length;
1372 | let res = isPalinArray(arr, n);
1373 | if (res == true) document.write("Array is a PalinArray");
1374 | else document.write("Array is not a PalinArray");
1375 | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------
1376 | Median of two sorted arrays:- https://www.youtube.com/watch?v=afwPSXmRsGs https://www.youtube.com/watch?v=NTop3VTjmxk&t=17s https://www.youtube.com/watch?v=ws98ud9uxl4
1377 | var findMedianSortedArrays = function(nums1, nums2) {
1378 | const nums = nums1.concat(nums2)
1379 | nums.sort( function(a,b) { return a - b; } )
1380 | if (((nums.length + 1) % 2 ) === 0){ //odd
1381 | let median = (nums.length + 1)/2
1382 | return nums[median - 1] //find the index of the median in the array
1383 | }
1384 | else { //you need to subtract one from the index since arrays start at 0
1385 | let first = (nums.length/2) //index of the first median
1386 | let second = first + 1 //index of the second median
1387 | let med1 = nums[first - 1]
1388 | let med2 = nums[second - 1]
1389 | const median = (med1 + med2)/2
1390 | return parseInt(median)
1391 | }
1392 | };
1393 | let arr1 = [1,2,3], arr2=[4,5,6];
1394 | console.log(findMedianSortedArrays(arr1, arr2));
1395 | ---------------------------------------------------
1396 | var findMedianSortedArrays = function(nums1, nums2) {
1397 | const nums = nums1.concat(nums2)
1398 | nums.sort( function(a,b) { return a - b; } )
1399 | if (((nums.length + 1) % 2 ) === 0){ //odd
1400 | let median = (nums.length + 1)/2
1401 | return nums[median - 1] //find the index of the median in the array
1402 | }
1403 | else { //you need to subtract one from the index since arrays start at 0
1404 | let first = (nums.length/2) //index of the first median
1405 | let second = first + 1 //index of the second median
1406 | let med1 = nums[first - 1]
1407 | let med2 = nums[second - 1]
1408 | const median = (med1 + med2)/2
1409 | return parseInt(median)
1410 | }
1411 | };
1412 | let arr1 = [1,2,3], arr2=[4,5,6];
1413 | console.log(findMedianSortedArrays(arr1, arr2));
1414 | --------------------------------------------------
1415 | function findmedian(a, n1, b, n2){
1416 | let i = 0; let j = 0; let k; let m1 = -1, m2 = -1;
1417 | for(k = 0; k <= (n1 + n2) / 2; k++){
1418 | if (i < n1 && j < n2){
1419 | if (a[i] < b[j])
1420 | {
1421 | m2 = m1;
1422 | m1 = a[i];
1423 | i++;
1424 | }
1425 | else{
1426 | m2 = m1;
1427 | m1 = b[j];
1428 | j++;
1429 | }
1430 | }
1431 | else if (i == n1){ /* all elements of a[] are smaller than smallest(or first) element of b[] or a[] is empty*/
1432 | m2 = m1;
1433 | m1 = b[j];
1434 | j++;
1435 | }
1436 | else if (j == n2){ /* all elements of b[] are smaller than smallest(or first) element of a[] or b[] is empty*/
1437 | m2 = m1;
1438 | m1 = a[i];
1439 | i++;
1440 | }
1441 | }
1442 | if ((n1 + n2) % 2 == 0){ /*sum of number of elements of the arrays is even */
1443 | return (m1 + m2) / 2;
1444 | }
1445 | return m1; /* sum of number of elements of the arrays is odd */
1446 | }
1447 | let a = [ 1, 12, 15, 26, 38 ]; let b = [ 2, 13, 24 ];
1448 | let n1 = a.length; let n2 = b.length;
1449 | document.write(findmedian(a, n1, b, n2));
1450 | --------------------------------------
1451 | function getMedian(ar1, ar2, n){
1452 | var i = 0; var j = 0; var count; var m1 = -1, m2 = -1;
1453 | for (count = 0; count <= n; count++){
1454 | if (i == n) { /*all elements of ar1[] are smaller than smallest(or first) element of ar2[]*/
1455 | m1 = m2;
1456 | m2 = ar2[0];
1457 | break;
1458 | }
1459 | else if (j == n){ /*all elements of ar2[] are smaller than smallest(or first) element of ar1[]*/
1460 | m1 = m2;
1461 | m2 = ar1[0];
1462 | break;
1463 | }
1464 | if (ar1[i] <= ar2[j]){ /* equals sign because if two arrays have some common elements */
1465 | m1 = m2; /* Store the prev median */
1466 | m2 = ar1[i];
1467 | i++;
1468 | }
1469 | else{
1470 | m1 = m2; /* Store the prev median */
1471 | m2 = ar2[j];
1472 | j++;
1473 | }
1474 | }
1475 | return (m1 + m2)/2;
1476 | }
1477 | var ar1 = [1, 12, 15, 26, 38]; var ar2 = [2, 13, 17, 30, 45];
1478 | var n1 = ar1.length; var n2 = ar2.length;
1479 | if (n1 == n2) document.write("Median is "+ getMedian(ar1, ar2, n1));
1480 | else document.write("Doesn't work for arrays of unequal size");
1481 | -------------------------------------------------
1482 | Spirally traversing a matrix :--https://www.youtube.com/watch?v=4mSTiSBk_iY&t=903s https://www.geeksforgeeks.org/print-a-given-matrix-in-spiral-form/
1483 | function spriral(arr,r,c){
1484 | var top=0, bottom=r-1, left=0, right=c-1, i, result;
1485 | while(top<=bottom && left<=right){
1486 | for(i=left; i<=right; i++){
1487 | document.write(arr[top][i] + ' ')
1488 | }
1489 | top++;
1490 | for(i=top; i<=bottom; i++){
1491 | document.write(arr[i][right] + ' ')
1492 | }
1493 | right--;
1494 | if(top<=bottom){
1495 | for(i=right; i>=right; i--){
1496 | document.write(arr[bottom][i] + ' ')
1497 | }
1498 | bottom--;
1499 | }
1500 | if(left<=right){
1501 | for(i=bottom; i>=top; i--){
1502 | document.write(arr[i][left] + ' ')
1503 | }
1504 | left++;
1505 | }
1506 | }
1507 | return result;
1508 | }
1509 | var arr=[[1, 2, 3, 4],
1510 | [5, 6, 7, 8],
1511 | [9, 10, 11, 12],
1512 | [13, 14, 15,16]]
1513 | var r=4;
1514 | var c=4;
1515 | console.log(spriral(arr,r,c)) //1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10
1516 | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
1517 | Search an element in matrix:-
1518 | function search(mat, m, n, x) //m=5, n=4, x=29
1519 | {
1520 | var i = m - 1; //i=5-1=4 //3
1521 | var j = 0; //1
1522 | while (i >= 0 && j < n) //4>=0, 0<29
1523 | {
1524 | if (mat[i][j] == x)
1525 | return true;
1526 | if (mat[i][j] > x) //4,1(32)>29
1527 | i--;
1528 | else // if mat[i][j] < x //27<29
1529 | j++;
1530 | }
1531 | return false;
1532 | }
1533 | var mat = [[10, 20, 30, 40],
1534 | [15, 25, 35, 45],
1535 | [27, 29, 37, 48],
1536 | [32, 33, 39, 50],
1537 | [50, 60, 70, 80]]; //[[1,3,5,7],[10,11,16,20],[23,30,34,60]];
1538 | if (search(mat, 5, 4, 29)) document.write("Yes");
1539 | else document.write("No");
1540 | ----------------------------------------------------------
1541 | const linearSearch = (arr, target) => {
1542 | for (let i = 0; i < arr.length; i++) {
1543 | for (let j = 0; j < arr[i].length; j++) {
1544 | if (arr[i][j] == target) {
1545 | return [i, j];
1546 | }
1547 | }
1548 | }
1549 | return [-1, -1];
1550 | }
1551 | let arr = [[3, 12, 9],
1552 | [5, 2, 89],
1553 | [90, 45, 22]];
1554 | let target = 2;
1555 | let ans = linearSearch(arr, target); console.log(ans);
1556 | document.write(`Element found at index: [${ans[0]} ${ans[1]}]`);
1557 | --------------------------------------------------------------------------
1558 | Median in a row-wise sorted Matrix:--
1559 | function countlessThanMid(a, mid){
1560 | var l = 0, h = a.length-1;
1561 | while(l <= h) {
1562 | var md = (l + h)/2;
1563 | if(a[md] <= mid) {
1564 | l = md + 1;
1565 | }
1566 | else {
1567 | h = md - 1;
1568 | }
1569 | }
1570 | return l;
1571 | }
1572 | function binaryMedian(arr, r, c)
1573 | {
1574 | //var median(int matrix[][], int r, int c) {
1575 | var low = 0;
1576 | var high = 10000000000;
1577 | while(low<=high){
1578 | var mid=(low+high)/2;
1579 | var count=0;
1580 | for(var i=0;i=0; j--){
1603 | if(arr[i][j]==1){
1604 | temp_res++
1605 | }
1606 | else{
1607 | break;
1608 | }
1609 | }
1610 | if(temp_res >max){
1611 | max = temp_res;
1612 | ansrow=i;
1613 | }
1614 | }
1615 | return ansrow;
1616 | }
1617 | let arr= [[0, 1, 1, 1],
1618 | [0, 0, 1, 1],
1619 | [1, 1, 1, 1],
1620 | [0, 0, 0, 0]]
1621 | console.log(rowWithMaxOne(arr,4,4))
1622 | -----------------------------------------
1623 | function rowWithMaxOne(arr, n, m){
1624 | var ansrow = -1;
1625 | var j = m-1;
1626 | for(var i=0; i=0; i++){
1627 | while(j>=0){
1628 | if(arr[i][j]==1){
1629 | j--;
1630 | ansrow = i;
1631 | }
1632 | else{
1633 | break;
1634 | }
1635 | }
1636 | }
1637 | return ansrow;
1638 | }
1639 | let arr= [[0, 1, 1, 1],
1640 | [0, 0, 1, 1],
1641 | [1, 1, 1, 1],
1642 | [0, 0, 0, 0]]
1643 | console.log(rowWithMaxOne(arr,4,4))
1644 | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
1645 | Sorted matrix:-
1646 | function sortMat(mat, n)
1647 | {
1648 | let temp = new Array(n * n); // temporary matrix of size n^2
1649 | let k = 0;
1650 | for (let i = 0; i < n; i++) // copy the elements of matrix one by one into temp[]
1651 | for (let j = 0; j < n; j++)
1652 | temp[k++] = mat[i][j]; console.log(temp) //[5, 4, 7, 1, 3, 8, 2, 9, 6]
1653 | temp.sort();
1654 | k = 0; // copy the elements of temp[] one by one in mat[][]
1655 | for (let i = 0; i < n; i++)
1656 | for (let j = 0; j < n; j++)
1657 | mat[i][j] = temp[k++];
1658 | }
1659 | function printMat(mat, n)// function to print the given matrix
1660 | {
1661 | for (let i = 0; i < n; i++) {
1662 | for (let j = 0; j < n; j++)
1663 | document.write( mat[i][j] + " ");
1664 | document.write( "
");
1665 | }
1666 | }
1667 | let mat = [ [ 5, 4, 7 ],
1668 | [ 1, 3, 8 ],
1669 | [ 2, 9, 6 ] ];
1670 | let n = 3;
1671 | sortMat(mat, n);
1672 | document.write( "\nMatrix After Sorting: " + "
");
1673 | printMat(mat, n);
1674 | ----------------------------------------------------
1675 | function printSorted(Mat,N)
1676 | {
1677 | var a=new Array(N * N);
1678 | var k=0;
1679 | for(var i=0;i 0) {
1722 | area = top_val * (i - result[result.length - 1] - 1);
1723 | }
1724 | max_area = Math.max(area, max_area);
1725 | }
1726 | }
1727 | while (result.length > 0) { // Now pop the remaining bars from stack and calculate area with every popped bar as the smallest bar
1728 | top_val = row[result[result.length - 1]];
1729 | result.pop();
1730 | area = top_val * i;
1731 | if (result.length > 0) {
1732 | area = top_val * (i - result[result.length - 1] - 1);
1733 | }
1734 |
1735 | max_area = Math.max(area, max_area);
1736 | }
1737 | return max_area;
1738 | }
1739 | function maxRectangle(R, C, A) // Returns area of the largest rectangle with all 1s in A[][]
1740 | {
1741 | let result = maxHist(R, C, A[0]); //console.log( A[0]) //Calculate area for first row and initialize it as result
1742 | for (let i = 1; i < R; i++) { // iterate over row to find maximum rectangular area considering each row as histogram
1743 | for (let j = 0; j < C; j++) {
1744 | if (A[i][j] == 1) { // if A[i][j] is 1 then add A[i -1][j]
1745 | A[i][j] += A[i - 1][j];
1746 | }
1747 | }
1748 | result = Math.max(result, maxHist(R, C, A[i])); // Update result if area with current row (as last row of rectangle) is more
1749 | }
1750 | return result;
1751 | }
1752 | let R = 4;let C = 4;
1753 | let A = [ [ 0, 1, 1, 0 ],
1754 | [ 1, 1, 1, 1 ],
1755 | [ 1, 1, 1, 1 ],
1756 | [ 1, 1, 0, 0 ] ];
1757 | document.write("Area of maximum rectangle is " + maxRectangle(R, C, A));
1758 | --------------------------------------------------------------------------
1759 | function maxRectangle(A){
1760 | for(var i=0; i=0; j--){
1774 | area=A[i][j]*width;
1775 | width++;
1776 | maxArea=Math.max(maxArea,area);
1777 | }
1778 | }
1779 | return maxArea;
1780 | }
1781 | let R = 4;let C = 4;
1782 | let A = [ [ 0, 1, 1, 0 ],
1783 | [ 1, 1, 1, 1 ],
1784 | [ 1, 1, 1, 1 ],
1785 | [ 1, 1, 0, 0 ] ];
1786 | console.log("Area of maximum rectangle is " + maxRectangle(A));
1787 | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
1788 | Find a specific pair in Matrix:-
1789 | function findMaxValue(N,mat){
1790 | let maxValue = Number.MIN_VALUE;
1791 | for (let a = 0; a < N - 1; a++) //0,1,2,3 Consider all possible pairs mat[a][b] and mat1[d][e]
1792 | for (let b = 0; b < N - 1; b++) //0,1,2,3 //
1793 | for (let d = a + 1; d < N; d++) //1,2,3,4
1794 | for (let e = b + 1; e < N; e++) //1,2,3,4
1795 | if (maxValue < (mat[d][e] - mat[a][b])){
1796 | maxValue = mat[d][e] - mat[a][b];
1797 | //document.write(mat[d][e], mat[a][b]+ " ")
1798 | console.log(maxValue)
1799 | }
1800 | return maxValue;
1801 | }
1802 | let N = 5;
1803 | let mat=[ [ 1, 2, -1, -4, -20],
1804 | [-8, -3, 4, 2, 1],
1805 | [3, 8, 6, 1, 3],
1806 | [ -4, -1, 1, 7, -6 ],
1807 | [ 0, -4, 10, -5, 1 ]];
1808 | document.write("Maximum Value is " +findMaxValue(N,mat));
1809 | ---------------------------------------------
1810 | function findMaxValue(N,mat){
1811 | let maxValue = Number.MIN_VALUE;
1812 | let maxArr=new Array(N); // maxArr[i][j] stores max of elements in matrix from (i, j) to (N-1, N-1)
1813 | for(let i = 0; i < N; i++){
1814 | maxArr[i]=new Array(N);
1815 | }
1816 | maxArr[N - 1][N - 1] = mat[N - 1][N - 1]; // last element of maxArr will be same's as of the input matrix
1817 | let maxv = mat[N-1][N-1]; //1 preprocess last row // Initialize max
1818 | for (let j = N - 2; j >= 0; j--){
1819 | if (mat[N - 1][j] > maxv)
1820 | maxv = mat[N - 1][j];
1821 | maxArr[N - 1][j] = maxv;
1822 | }
1823 | maxv = mat[N - 1][N - 1]; // // preprocess last column //Initialize max
1824 | for (let i = N - 2; i >= 0; i--){
1825 | if (mat[i][N - 1] > maxv)
1826 | maxv = mat[i][N - 1];
1827 | maxArr[i][N - 1] = maxv;
1828 | }
1829 | for (let i = N-2; i >= 0; i--) // preprocess rest of the matrix from bottom
1830 | {
1831 | for (let j = N-2; j >= 0; j--)
1832 | {
1833 | if (maxArr[i+1][j+1] - mat[i][j] > maxValue) // Update maxValue
1834 | maxValue = maxArr[i + 1][j + 1] - mat[i][j];
1835 | maxArr[i][j] = Math.max(mat[i][j], Math.max(maxArr[i][j + 1], maxArr[i + 1][j]) ); // set maxArr (i, j)
1836 | }
1837 | }
1838 | return maxValue;
1839 | }
1840 | let N = 5;
1841 | let mat = [[ 1, 2, -1, -4, -20 ],
1842 | [-8, -3, 4, 2, 1 ],
1843 | [ 3, 8, 6, 1, 3 ],
1844 | [ -4, -1, 1, 7, -6] ,
1845 | [0, -4, 10, -5, 1 ]];
1846 | document.write("Maximum Value is " + findMaxValue(N,mat));
1847 | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------
1848 | Rotate a matrix by 90 degree in clockwise direction without using any extra space:-
1849 | var N = 4;
1850 | function rotate90Clockwise(a) { // Function to rotate the matrix 90 degree clockwise
1851 | for (i = 0; i < parseInt(N / 2); i++) { // Traverse each cycle //0,1
1852 | for (j = i; j < N - i - 1; j++) { //3, 2
1853 | var temp = a[i][j]; // Swap elements of each cycle in clockwise direction
1854 | a[i][j] = a[N - 1 - j][i];
1855 | a[N - 1 - j][i] = a[N - 1 - i][N - 1 - j];
1856 | a[N - 1 - i][N - 1 - j] = a[j][N - 1 - i];
1857 | a[j][N - 1 - i] = temp;
1858 | }
1859 | }
1860 | }
1861 | function printMatrix(arr) { // Function for print matrix
1862 | for (i = 0; i < N; i++) {
1863 | for (j = 0; j < N; j++)
1864 | document.write(arr[i][j] + " ");
1865 | document.write("
");
1866 | }
1867 | }
1868 | var arr = [ [ 1, 2, 3, 4 ],
1869 | [ 5, 6, 7, 8 ],
1870 | [ 9, 10, 11, 12 ],
1871 | [ 13, 14, 15, 16 ] ];
1872 | rotate90Clockwise(arr);
1873 | printMatrix(arr);
1874 | -----------------------------------------------
1875 | var N = 4;
1876 | function rotate90Clockwise(arr) { // Function to rotate the matrix 90 degree clockwise
1877 | for (j = 0; j < N; j++) { //0,1,2,3 printing the matrix on the basis of observations made on indices.
1878 | // console.log(arr[0]) //[1, 2, 3, 4]
1879 | for (i = N - 1; i >= 0; i--){ //3,2,1,0
1880 | // console.log(arr[i]) //[13, 14, 15, 16]
1881 | document.write(arr[i][j] + " ");
1882 | }
1883 | document.write("
");
1884 | }
1885 | }
1886 | var arr = [ [ 1, 2, 3, 4 ],
1887 | [ 5, 6, 7, 8 ],
1888 | [ 9, 10, 11, 12 ],
1889 | [ 13, 14, 15, 16 ] ];
1890 | rotate90Clockwise(arr);
1891 | ---------------------------------------------------------
1892 | let N = 4
1893 | function print(arr){
1894 | for(let i = 0; i < N; ++i){
1895 | for(let j = 0; j < N; ++j)
1896 | document.write(arr[i][j] + " ");
1897 | document.write("
");
1898 | }
1899 | }
1900 | function rotate(arr){
1901 | for(let i = 0; i < N; ++i) // First rotation with respect to main diagonal
1902 | {
1903 | for(let j = 0; j < i; ++j)
1904 | {
1905 | let temp = arr[i][j];
1906 | arr[i][j] = arr[j][i];
1907 | arr[j][i] = temp;
1908 | }
1909 | }
1910 | for(let i = 0; i < N; ++i) // Second rotation with respect to middle column
1911 | {
1912 | for(let j = 0; j < N / 2; ++j)
1913 | {
1914 | let temp = arr[i][j];
1915 | arr[i][j] = arr[i][N - j - 1];
1916 | arr[i][N - j - 1] = temp;
1917 | }
1918 | }
1919 | }
1920 | let arr = [ [ 1, 2, 3, 4 ],
1921 | [ 5, 6, 7, 8 ],
1922 | [ 9, 10, 11, 12 ],
1923 | [ 13, 14, 15, 16 ] ];
1924 | rotate(arr);
1925 | print(arr);
1926 | -----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
1927 | Kth element in Matrix:- https://www.youtube.com/watch?v=w36ekZYq-Ms https://www.geeksforgeeks.org/k-th-element-two-sorted-arrays/
1928 | function getElementsGreaterThanOrEqual(num,n,mat){
1929 | let ans = 0
1930 | for (let i = 0; i < n; i++) { // if num is less than the first element then no more element in matrix further are less than or equal to num
1931 | if (mat[i][0] > num) {
1932 | return ans;
1933 | }
1934 | if (mat[i][n - 1] <= num) { // if num is greater than last element, it is greater than all elements in that row
1935 | ans += n;
1936 | continue;
1937 | }
1938 | let greaterThan = 0; // This contain the col index of last element in matrix less than of equal to num
1939 | for (let jump = n / 2; jump >= 1; jump /= 2) {
1940 | while (greaterThan + jump < n &&
1941 | mat[i][greaterThan + jump] <= num) {
1942 | greaterThan += jump;
1943 | }
1944 | }
1945 | ans += greaterThan + 1;
1946 | }
1947 | return ans;
1948 | }
1949 | function kthSmallest(mat,n,k){ // reuturs kth smallest index in the matrix
1950 | // We know the answer lies between the first and the last element So do a binary search on answer based on the number of elements our current element is greater than the elements in the matrix
1951 | let l = mat[0][0], r = mat[n - 1][n - 1];
1952 | while (l <= r) {
1953 | let mid = l + parseInt((r - l) / 2, 10);
1954 | let greaterThanOrEqualMid =
1955 | getElementsGreaterThanOrEqual(mid, n, mat);
1956 | if (greaterThanOrEqualMid >= k)
1957 | r = mid - 1;
1958 | else
1959 | l = mid + 1;
1960 | }
1961 | return l;
1962 | }
1963 | let n = 4;
1964 | let mat = [
1965 | [10, 20, 30, 40],
1966 | [15, 25, 35, 45],
1967 | [25, 29, 37, 48],
1968 | [32, 33, 39, 50],
1969 | ];
1970 | document.write("7th smallest element is " + kthSmallest(mat, 4, 7));
1971 | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
1972 | Find distinct elements common to all rows of a matrix:- https://www.youtube.com/watch?v=oY-BlyCImSc
1973 | let M = 4; //row
1974 | let N =5; //column
1975 | function printCommonElements(mat){
1976 | let mp = new Map(); //used for count of an elements
1977 | for (let j = 0; j < N; j++) // initialize 1st row elements with value 1
1978 | mp.set(mat[0][j],1);
1979 | for (let i = 1; i < M; i++) // traverse the matrix
1980 | {
1981 | for (let j = 0; j < N; j++){
1982 | if (mp.get(mat[i][j]) != null && mp.get(mat[i][j]) == i) // If element is present in the map and is not duplicated in current row.
1983 | {
1984 | mp.set(mat[i][j], i + 1); // we increment count of the element in map by 1
1985 | if (i == M - 1) // If this is last row
1986 | document.write(mat[i][j] + " ");
1987 | }
1988 | }
1989 | }
1990 | }
1991 | let mat = [[1, 2, 1, 4, 8],
1992 | [3, 7, 8, 5, 1],
1993 | [8, 7, 7, 3, 1],
1994 | [8, 1, 2, 7, 9]]
1995 | printCommonElements(mat)
1996 | -----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
1997 | Reverse String:-
1998 | function reverseString(s){
1999 | var i = 0, j = s.length -1;
2000 | while(i < j){ //0<4 //1<3
2001 | var ch = s[i];
2002 | s[i] = s[j];
2003 | s[j] = ch;
2004 | i++;j--;
2005 | }
2006 | return s;
2007 | }
2008 | console.log(reverseString(["h","e","l","l","o"]))
2009 | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
2010 | Palindrome:- https://itnext.io/11-way-to-check-for-palindromes-in-javascript-85dbfe7dfb5d
2011 | function checkPalindrome(str) {
2012 | const len = string.length;
2013 | for (let i = 0; i < len / 2; i++) { // loop through half of the string
2014 | if (string[i] !== string[len - 1 - i]) {
2015 | return 'It is not a palindrome';
2016 | }
2017 | }
2018 | return 'It is a palindrome';
2019 | }
2020 | const string = prompt('Enter a string: ');
2021 | const value = checkPalindrome(string);
2022 | console.log(value);
2023 | -------------------------------------------
2024 | function checkPalindrome(str) {
2025 | const arrayValues = string.split(''); // convert string to an array
2026 | const reverseArrayValues = arrayValues.reverse(); // reverse the array values
2027 | const reverseString = reverseArrayValues.join(''); // convert array to string
2028 | if(string == reverseString) {
2029 | console.log('It is a palindrome');
2030 | }
2031 | else {
2032 | console.log('It is not a palindrome');
2033 | }
2034 | }
2035 | const string = prompt('Enter a string: ');
2036 | checkPalindrome(string);
2037 | -------------------------------------------
2038 | function checkPalindrome(str) {
2039 | let i = 0;
2040 | let j = str.length - 1;
2041 | while(i < j) {
2042 | if(str[i] == str[j]) {
2043 | i++;
2044 | j--;
2045 | }
2046 | else {
2047 | return false;
2048 | }
2049 | }
2050 | return true;
2051 | }
2052 | const string = prompt('Enter a string: ');
2053 | console.log(checkPalindrome(string));
2054 | ---------------------------------------------
2055 | function checkPalindrome(str) {
2056 | return str.split('').every((char, i) => {
2057 | return char === str[str.length - i - 1]; //ccharater matching
2058 | });
2059 | }
2060 | const string = prompt('Enter a string: ');
2061 | console.log(checkPalindrome(string));
2062 | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
2063 | Find Duplicate characters in a string:-
2064 | function printDups(str){
2065 | var count = {};
2066 | for (var i = 0; i < str.length; i++) {
2067 | count[str[i]] = 0; } console.log(count)
2068 | for (var i = 0; i < str.length; i++) {
2069 | count[str[i]]++; } console.log(count)
2070 | for (var it in count) {
2071 | if (count[it] > 1) document.write(it + ", count = " + count[it] + "
");
2072 | }
2073 | }
2074 | var str = "test string";
2075 | printDups(str);
2076 | ---------------------------------
2077 | let NO_OF_CHARS = 256;
2078 | function printDups(str){
2079 | let count = new Array(NO_OF_CHARS); // Create an array of size 256 and fill count of every character in it
2080 | count.fill(0);
2081 | for (let i = 0; i < str.length; i++){
2082 | count[str[i].charCodeAt()]++;}
2083 | for (let i = 0; i < NO_OF_CHARS; i++){
2084 | if(count[i] > 1)
2085 | {
2086 | document.write(String.fromCharCode(i) + ", " + "count = " + count[i] + "");
2087 | }
2088 | }
2089 | }
2090 | var str = "test string";
2091 | printDups(str);
2092 | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
2093 | A Program to check if strings are rotations of each other or not:- https://www.geeksforgeeks.org/a-program-to-check-if-strings-are-rotations-of-each-other/
2094 | https://www.youtube.com/watch?v=-xX8WHd7Ztk
2095 | function areRotations( str1, str2){ // There lengths must be same and str2 must be a substring of str1 concatenated with str1.
2096 | return (str1.length == str2.length) && ((str1 + str1).indexOf(str2) != -1); //AACDAACD //ACDA //not present
2097 | }
2098 | var str1 = "AACD"; var str2 = "ACDA";
2099 | if (areRotations(str1, str2)) document.write("Strings are rotations of each other");
2100 | else document.write("Strings are not rotations of each other");
2101 | ----------------------------------------------
2102 | function areRotations( s1, s2) {
2103 | if(s1.length!=s2.length){
2104 | return false;
2105 | }
2106 | else{
2107 | s1=s1+s1;
2108 | return s1.includes(s2);
2109 | }
2110 | }
2111 | var str1 = "AACD"; var str2 = "ACDA";
2112 | if (areRotations(str1, str2)) document.write("Strings are rotations of each other");
2113 | else document.write("Strings are not rotations of each other");
2114 | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------
2115 | Program to Check if a string is a valid shuffle of two distinct strings:- (https://www.youtube.com/watch?v=qN_vwYtvFUM)
2116 | function shuffleCheck(){
2117 | var s1="XY";var s2="12"; var result="X1Y2";
2118 | if((s1.length+s2.length)!=result.length) console.log("No");
2119 | else{
2120 | var i=0, j=0, k=0;
2121 | while(k{
2153 | while(i>=0 && j");
2253 | }
2254 | }
2255 | }
2256 | let str="abc";
2257 | subString(str, str.length);
2258 | ---------------------------------------------
2259 | function SubString( str , n)
2260 | {
2261 | for (var i = 0; i < n; i++) //0<4 //1<4
2262 | for (var j = i+1; j <= n; j++) // 1<=4 //2<=4 //3<=4 //4<=4
2263 | document.write(str.substring(i, j)+"
"); //0,1 //0,2 //0,3 //0,4
2264 | }
2265 | var str = "abcd";
2266 | SubString(str, str.length);
2267 | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
2268 | print all permutations of a given string:-- https://www.youtube.com/watch?v=va3NEycUxsg
2269 | function permute(s , answer)
2270 | {
2271 | if (s.length == 0)
2272 | {
2273 | document.write(answer + "");
2274 | }
2275 | for(let i = 0 ;i < s.length; i++)
2276 | {
2277 | let ch = s[i]; //a //b //c ....
2278 | let rest = s.slice(0, i) + s.slice(i + 1); //console.log(rest) //bc
2279 | //console.log(answer + ch)
2280 | permute(rest, answer + ch);
2281 | }
2282 | }
2283 | let s= "abc"; let answer="";
2284 | permute(s, answer);
2285 | -----------------------------------------------
2286 | const swap=(string, i, j)=>{
2287 | let temp; let charArray = string.split(""); console.log(string)
2288 | temp = charArray[i] ;
2289 | charArray[i] = charArray[j];
2290 | charArray[j] = temp;
2291 | return charArray.join("");
2292 | }
2293 | function permute(str, l, r){ //l=0, r=3
2294 | if (l == r) document.write(str+"
");
2295 | else
2296 | {
2297 | for (let i = l; i <= r; i++)
2298 | {
2299 | str = swap(str, l, i);
2300 | permute(str, l + 1, r);
2301 | str = swap(str, l, i);
2302 | }
2303 | }
2304 | }
2305 | let str = "abc"; let n = str.length;
2306 | permute(str, 0, n-1);
2307 | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
2308 | Split the binary string into substrings with equal number of 0s and 1s:- https://www.youtube.com/watch?v=UyX22tCpzhI
2309 | function maxSubStr(str, n){
2310 | var count0 = 0, count1 = 0; // To store the count of 0s and 1s
2311 | var cnt = 0; // To store the count of maximum substrings str can be divided into
2312 | for (var i = 0; i < n; i++)
2313 | {
2314 | if (str[i] == '0') {
2315 | count0++;
2316 | }
2317 | else {
2318 | count1++;
2319 | }
2320 | if (count0 == count1) {
2321 | cnt++;
2322 | }
2323 | }
2324 | if (count0 != count1) { // It is not possible to split the string
2325 | return -1;
2326 | }
2327 | return cnt;
2328 | }
2329 | var str = "0100110101"; var n = str.length;
2330 | document.write( maxSubStr(str, n));
2331 | -----------------------------------------------------------------------------------------------------------------------------------------------------------------------
2332 | Longest Common Prefix :- https://www.youtube.com/watch?v=0SF6RLMYBcE
2333 | var longestCommonPrefix = function(strs) {
2334 | if(strs === null || strs.length === 0) return "";
2335 | for (let i=0; i < strs[0].length; i++) //flower 5
2336 | {
2337 | for (let j = 1; j < strs.length; j++)
2338 | {
2339 | if(strs[0][i] !== strs[j][i] ) return strs[0].slice(0,i)
2340 | }
2341 | }
2342 | return strs[0];
2343 | }
2344 | console.log(longestCommonPrefix(["flower","flow","flight"]))
2345 | -----------------------------------------------------------------
2346 | var longestCommonPrefix = function(strs) {
2347 | let prefix = ""
2348 | if(strs === null || strs.length === 0) return prefix
2349 | for (let i=0; i < strs[0].length; i++){
2350 | const char = strs[0][i] // loop through all characters of the very first string.
2351 | for (let j = 1; j < strs.length; j++){
2352 | // loop through all other strings in the array
2353 | if(strs[j][i] !== char) return prefix
2354 | }
2355 | prefix = prefix + char
2356 | }
2357 | return prefix
2358 | }
2359 | console.log(longestCommonPrefix(["flower","flow","flight"]))
2360 | ----------------------------------------------------------------
2361 | function longestCommonPrefix(array){
2362 | var A= array.sort(); console.log(A); var i= 0; //["flight", "flow", "flower"]
2363 | while(i 5 - 1 = 4
2389 | i++ // to increse the 2 pointer so 1 is happening here
2390 | }
2391 | else {
2392 | result += cur
2393 | }
2394 | }
2395 | return result;
2396 | };
2397 | console.log(romanToInt("V"))
2398 | -----------------------------------------------------------------------------------------------------------------------------------------------------------------------------
2399 | Most frequent word in an array of strings:-
2400 | function findWord(arr) {
2401 | var hs = {}; // Create Dictionary(map) to store word and it's frequency
2402 | for (var i = 0; i < arr.length; i++)
2403 | { // Iterate through array of words
2404 | if (hs.hasOwnProperty(arr[i])) { // If word already exist in Dictionary then increase it's count by 1
2405 | hs[arr[i]] = hs[arr[i]] + 1;
2406 | }
2407 | else { // Otherwise add word to Dictionary
2408 | hs[arr[i]] = 1;
2409 | }
2410 | } //console.log(Object.entries(hs))
2411 | var Key = ""; // Create set to iterate over Dictionary
2412 | var Val = 0;
2413 | for (const [key, value] of Object.entries(hs)) {
2414 | if (value > Val) { // Check for word having highest frequency
2415 | Val = value;
2416 | Key = key;
2417 | }
2418 | } console.log(Key, Val)
2419 | return Key; // Return word having highest frequency
2420 | }
2421 | var arr = ["aaa", "bbb", "bbb", "ccc", "ccc", "ccc"];
2422 | document.write(findWord(arr));
2423 | -------------------------------------------------------------------------------------------------------------------------------------
2424 | Second most repeated word in a sequence:-
2425 | function findWord(arr) {
2426 | var hs = {}; // Create Dictionary(map) to store word and it's frequency
2427 | for (var i = 0; i < arr.length; i++)
2428 | { // Iterate through array of words
2429 | if (hs.hasOwnProperty(arr[i])) { // If word already exist in Dictionary then increase it's count by 1
2430 | hs[arr[i]] = hs[arr[i]] + 1;
2431 | }
2432 | else { // Otherwise add word to Dictionary
2433 | hs[arr[i]] = 1;
2434 | }
2435 | }
2436 | const frequencyArray = Object.entries(hs); console.log(frequencyArray)
2437 | return frequencyArray.sort((a, b) => {
2438 | return b[1] - a[1];
2439 | })[1][0];
2440 | }
2441 | var arr = ["aaa", "bbb", "bbb", "ccc", "ccc", "ccc"];
2442 | document.write(findWord(arr));
2443 | ------------------------------------------------------------
2444 | const str = 'aaa bbb ccc bbb aaa aaa';
2445 | const secondMostFrequent = str => {
2446 | const strArr = str.split(''); console.log(strArr)
2447 | const map = strArr.reduce((acc, val) => {
2448 | if(acc.has(val)){
2449 | acc.set(val, acc.get(val) + 1);
2450 | }else{
2451 | acc.set(val, 1);
2452 | };
2453 | return acc;
2454 | }, new Map);
2455 | const frequencyArray = Array.from(map);
2456 | return frequencyArray.sort((a, b) => {
2457 | return b[1] - a[1];
2458 | })[1][0];
2459 | };
2460 | document.write(secondMostFrequent(str));
2461 | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
2462 | Minimum Swaps for Bracket Balancing:-
2463 | https://www.youtube.com/watch?v=WhMbbnHZpis
2464 | function BalancedStringBySwapping(s){
2465 | var k=0,count=0;
2466 | for(var i=0;i=0) k++;
2471 | else
2472 | {
2473 | count=count+(-1*k);
2474 | k++;
2475 | }
2476 | }
2477 | else if(s[i]==']') k--;
2478 | }
2479 | return count;
2480 | }
2481 | var s = "[]][][";
2482 | document.write(BalancedStringBySwapping(s));
2483 | --------------------------------------------------
2484 | function BalancedStringBySwapping(s){
2485 | var open=0,close=0,shift=0,unbalanced=0;
2486 | for(var i=0;i0)
2491 | {
2492 | shift=shift+unbalanced;
2493 | unbalanced--;
2494 | }
2495 | }
2496 | else
2497 | {
2498 | close++;
2499 | unbalanced = close-open;
2500 | }
2501 | }
2502 | return shift;
2503 | }
2504 | var s = "[]][][";
2505 | document.write(BalancedStringBySwapping(s));
2506 | -----------------------------------------------------------------------------------------------------------------------------------------------------------------------------
2507 | Longest Common Subsequence:- https://www.youtube.com/watch?v=Ua0GhsJSlWM https://www.worldofitech.com/longest-common-subsequence/ LCS
2508 | var longestCommonSubsequence = function(text1, text2) { // Create dp table
2509 | const dp = Array(text1.length+1).fill(0).map(() => Array(text2.length+1).fill(0)); console.log(dp)
2510 | for(let i = 1; i < dp.length; i++) {
2511 | for(let j = 1; j < dp[i].length; j++) {
2512 | // If the letters match, look diagonally to get the max subsequence before this letter and add one
2513 | if(text1[i-1]===text2[j-1]){
2514 | dp[i][j] = dp[i-1][j-1] + 1
2515 | } else {
2516 | // If there is no match, set the cell to the previous current longest subsequence
2517 | dp[i][j] = Math.max(dp[i][j-1], dp[i-1][j])
2518 | }
2519 | }
2520 | }
2521 | return dp[text1.length][text2.length]
2522 | };
2523 | var s1 = "ABCDGH", s2="AEDFHR";
2524 | document.write(longestCommonSubsequence(s1, s2));
2525 | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
2526 | Rearrange characters in a string such that no two adjacent are same:- https://www.youtube.com/watch?v=sSDAN_WwNwU https://leetcode.com/problems/reorganize-string/discuss/1409359/Two-JavaScript-solutions
2527 | function isPossible(str){
2528 | let freq = new Map(); // To store the frequency of each of the character
2529 | let max_freq = 0; // To store the maximum frequency so far
2530 | for (let j = 0; j < str.length; j++)
2531 | { //console.log(max_freq, freq)
2532 | if (freq.has(str[j])) {
2533 | freq.set(str[j], freq.get(str[j]) + 1);
2534 | if (freq.get(str[j]) > max_freq)
2535 | max_freq = freq.get(str[j]);
2536 | }
2537 | else {
2538 | freq.set(str[j], 1);
2539 | if (freq.get(str[j]) > max_freq)
2540 | max_freq = freq.get(str[j]);
2541 | }
2542 | }
2543 | if (max_freq <= (str.length - max_freq + 1)) return true;
2544 | return false;
2545 | }
2546 | let str = "geeksforgeeks";
2547 | if (isPossible(str.split(''))) document.write("Yes");
2548 | else document.write("No");
2549 | ----------------------------------------------------------
2550 | let reorganizeString = (str) => {
2551 | let map = {}; // build a frequency map for characters in S - max 26 entries...
2552 | for (let i = 0; i < str.length; i++) {
2553 | let char = str[i];
2554 | map[char] = (map[char] || 0) + 1;
2555 | } console.log(map)
2556 | let sorted = Object.keys(map).sort((a, b) => map[b] - map[a]); console.log(sorted)// sorted array based on frequency count - max 26 entries => O(1) => constant time
2557 | let max = (str.length + 1) / 2; // fast path early return if a count is (N+1) / 2 for first item
2558 | if (map[sorted[0]] > max) return '';
2559 | let result = []; // interleave characters
2560 | let position = 0;
2561 | for (let idx = 0; idx < sorted.length; idx++) {
2562 | let char = sorted[idx];
2563 | let frequency = map[char];
2564 | for (let j = 0; j < frequency; j++) {
2565 | // rewind pointer to 1 when we overflow odd indexes... note: we don't have enough characters to overflow again
2566 | if (position >= str.length) position = 1;
2567 | result[position] = char;
2568 | position += 2;
2569 | }
2570 | }
2571 | return result.join('');
2572 | };
2573 | console.log(reorganizeString("geeksforgeeks"));
2574 | --------------------------------------------------------
2575 | var reorganizeString1 = function(S) {
2576 | let hash = {};
2577 | for (let c of S) hash[c] = hash[c] + 1 || 1;
2578 | let sort = Object.keys(hash).sort((a,b)=>hash[b] - hash[a]); console.log(sort)
2579 | let res = [];
2580 | let index = 0;
2581 | for (let i = 0;i parseInt((S.length + 1)/2)) return "";
2584 | for (let j = 0;j < occur;j++) {
2585 | if (index >= S.length) index = 1;
2586 | res[index] = sort[i];
2587 | index += 2;
2588 | }
2589 | }
2590 | return res.join('');
2591 | };
2592 | console.log(reorganizeString1("geeksforgeeks"));
2593 | -----------------------------------------------------------------------------------------------------------------------------------------------------------------------------
2594 | Remove Consecutive Characters:-
2595 | function isPossible(S){
2596 | var ans="";
2597 | for(var i=0;i {
2623 | const sortedWord = word.split('').sort().join('');
2624 | if (anagrams[sortedWord]) {
2625 | return anagrams[sortedWord].push(word);
2626 | }
2627 | anagrams[sortedWord] = [word];
2628 | });
2629 | return anagrams;
2630 | }
2631 | const groupedAnagrams = getGroupedAnagrams(words); //console.log(groupedAnagrams)
2632 | for (const sortedWord in groupedAnagrams) {
2633 | console.log(groupedAnagrams[sortedWord].toString());
2634 | }
2635 | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
2636 | String matching where one string contains wildcard characters:--- https://www.youtube.com/watch?v=Q6ZX95GadA8 (multiple recursion is happening so better to do with DP because
2637 | in DP we can store already calculated values)
2638 | https://www.youtube.com/watch?v=Lw4_BOwSOcA https://www.geeksforgeeks.org/wildcard-character-matching/ https://www.youtube.com/watch?v=x4TG1x0STNE
2639 | function match(first, second)
2640 | {
2641 | // If we reach at the end of both strings, we are done
2642 | if (first.length == 0 && second.length == 0)
2643 | return true;
2644 | // Make sure that the characters after '*' are present in second string.
2645 | // This function assumes that the first string will not contain two consecutive '*'
2646 | if (first.length > 1 && first[0] == '*' && second.length == 0)
2647 | return false;
2648 | // If the first string contains '?', or current characters of both strings match
2649 | if ((first.length > 1 && first[0] == '?') || (first.length != 0 && second.length != 0 && first[0] == second[0]))
2650 | return match(first.substring(1), second.substring(1));
2651 | // If there is *, then there are two possibilities // a) We consider current character of second string
2652 | // b) We ignore current character of second string.
2653 | if (first.length > 0 && first[0] == '*')
2654 | return match(first.substring(1), second) || match(first, second.substring(1));
2655 | return false;
2656 | }
2657 | function test(first, second) // A function to run test cases
2658 | {
2659 | if (match(first, second)) document.write("Yes" + "
");
2660 | else document.write("No" + "
");
2661 | }
2662 | test("g*ks", "geeks"); // Yes
2663 | test("ge?ks*", "geeksforgeeks"); // Yes
2664 | test("g*k", "gee"); // No because 'k' is not in second
2665 | test("*pqrs", "pqrst"); // No because 't' is not in first
2666 | test("abc*bcd", "abcdhghgbcd"); // Yes
2667 | test("abc*c?d", "abcd"); // No because second must have 2 instances of 'c'
2668 | test("*c*d", "abcd"); // Yes
2669 | test("*?c*d", "abcd"); // Yes
2670 | ---------------------------------------------------------------------------
2671 | https://www.youtube.com/watch?v=7SHV_QfVROE https://www.youtube.com/watch?v=x4TG1x0STNE
2672 | function wildCard( p, s){
2673 | var n=p.length;
2674 | var m=s.length;
2675 | //bool dp[n+1][m+1];
2676 | var dp = Array(s.length).fill(null).map(()=>new Array(p.length).fill(null));
2677 | for(var i=0; i<=n; i++){
2678 | for(var j=0; j<=m; j++){
2679 | if(i==0&&j==0) dp[i][j]=true;
2680 | else if(i==0) dp[i][j]=false;
2681 | else if(j==0){
2682 | if(p[i-1]=='*'){
2683 | dp[i][j]=dp[i-1][j];
2684 | }
2685 | else dp[i][j]=0;
2686 | }
2687 | else if(p[i-1]=='?'||p[i-1]==s[j-1]) dp[i][j]=dp[i-1][j-1];
2688 | else if(p[i-1]=='*') dp[i][j]=dp[i-1][j]||dp[i][j-1];
2689 | else dp[i][j]=0;
2690 | }
2691 | }
2692 | return dp[n][m];
2693 | }
2694 | //console.log(wildCard("ba*a?","baaabab")) //Yes
2695 | //console.log(wildCard("g*ks", "geeks")); // Yes
2696 | //console.log(wildCard("ge?ks*", "geeksforgeeks")); // Yes
2697 | //console.log(wildCard("g*k", "gee")? "true" : false); // No because 'k' is not in second
2698 | //console.log(wildCard("*pqrs", "pqrst")); // No because 't' is not in first
2699 | //console.log(wildCard("abc*bcd", "abcdhghgbcd")); // Yes
2700 | //console.log(wildCard("abc*c?d", "abcd")); // No because second must have 2 instances of 'c'
2701 | //console.log(wildCard("*c*d", "abcd")); // Yes
2702 | //console.log(wildCard("*?c*d", "abcd")); // Yes
2703 | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------
2704 | Isomorphic Strings :-
2705 | const str1 = 'abcde';
2706 | const str2 = 'eabdc';
2707 | const isIsomorphic = (str1 , str2) => {
2708 | if (str1.length !== str2.length) {
2709 | return false;
2710 | };
2711 | for (let i = 0; i < str1.length; i++) {
2712 | const a = str1.indexOf(str1[i]); //a
2713 | const b = str2.indexOf(str2[i]); //e
2714 | if (str2[a] !== str2[i] || str1[b] !== str1[i]) {
2715 | return false;
2716 | };
2717 | };
2718 | return true;
2719 | };
2720 | console.log(isIsomorphic(str1, str2));
2721 | --------------------------------------------------
2722 | const str1 = 'abcde';
2723 | const str2 = 'eabdc';
2724 | const isIsomorphic = (firstStr, nextStr) => {
2725 | if (str1.length != str2.length)
2726 | {
2727 | console.log('Both strings have different lenghts');
2728 | return false;
2729 | }
2730 | var chMap = {};
2731 | for (var i = 0; i < str1.length; i++) {
2732 | if (!chMap[str1[i]]) //not
2733 | {
2734 | chMap[str1[i]] = str2[i];
2735 | }
2736 | else if (chMap[str1[i]] !== str2[i])
2737 | {
2738 | console.log('Both strings differ in maaping at index ' + i);
2739 | return false;
2740 | }
2741 | }
2742 | return true;
2743 | }
2744 | console.log(isIsomorphic(str1, str2));
2745 | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
2746 | Transform One String to Another using Minimum Number of Given Operation
2747 | function minOps(A, B){
2748 | if (A.length != B.length) return -1;
2749 | let i, j, res = 0; let count = new Array(256);
2750 | for(let i = 0; i < 256; i++)
2751 | {
2752 | count[i] = 0;
2753 | }
2754 | // count characters in A
2755 | // Subtract count for every character in B
2756 | for(i = 0; i < A.length; i++)
2757 | {
2758 | count[A[i].charCodeAt(0)]++;
2759 | count[B[i].charCodeAt(0)]--;
2760 | }
2761 | console.log(count)
2762 | // Check if all counts become 0
2763 | for(i = 0; i < 256; i++)
2764 | if (count[i] != 0)
2765 | return -1;
2766 |
2767 | i = A.length - 1;
2768 | j = B.length - 1;
2769 | while(i >= 0)
2770 | {
2771 | // If there is a mismatch, then keep incrementing result 'res'until B[j] is not found in A[0..i]
2772 | if (A[i] != B[j])
2773 | res++;
2774 | else
2775 | j--;
2776 |
2777 | i--;
2778 | }
2779 | return res;
2780 | }
2781 | let A = "EACBD";
2782 | let B = "EABCD";
2783 | document.write("Minimum number of operations required is " + minOps(A, B));
2784 | -----------------------------------------------------------------------------
2785 | Recursively print all sentences that can be formed from list of word lists:-
2786 | var R = 3; var C = 3;
2787 | function printUtil(arr, m, n, output)
2788 | {
2789 | output[m] = arr[m][n]; // Add current word to output array
2790 | // If this is last word of current output sentence, then print the output sentence
2791 | if (m == R - 1)
2792 | {
2793 | for (var i=0; i < R; i++)
2794 | {
2795 | document.write(output[i] + " " );
2796 | }
2797 | document.write("")
2798 | return;
2799 | }
2800 | for (var i=0; i < C; i++) // Recur for next row
2801 | {
2802 | if (arr[m + 1][i] != "" && m < C)
2803 | {
2804 | printUtil(arr, m + 1, i, output);
2805 | }
2806 | }
2807 | }
2808 | function print(arr){
2809 | var output = Array(R).fill(null); // Create an array to store sentence
2810 | // Consider all words for first row as starting points and print all sentences
2811 | for (var i=0; i < C; i++)
2812 | {
2813 | if (arr[0][i] != "")
2814 | {
2815 | printUtil(arr, 0, i, output);
2816 | }
2817 | }
2818 | }
2819 | var arr =
2820 | [
2821 | ["you", "we", ""],
2822 | ["have", "are", ""],
2823 | ["sleep", "eat", "drink"]];
2824 | console.log(print(arr));
2825 | -----------------------------------------------------------------------------------------------------------------------------------------------------------------------------
2826 | Smallest window in a string containing all the characters of another string :-
2827 | function Minimum_Window(s,t){
2828 | let m = new Array(256);
2829 | for(let i = 0; i < 256; i++)
2830 | {
2831 | m[i] = 0;
2832 | }
2833 | let ans = Number.MAX_VALUE; // Length of ans
2834 | let start = 0; // Starting index of ans
2835 | let count = 0;
2836 | for(let i = 0; i < t.length; i++) // Creating map
2837 | {
2838 | if (m[t[i].charCodeAt(0)] == 0)
2839 | count++;
2840 |
2841 | m[t[i].charCodeAt(0)]++;
2842 | }
2843 | let i = 0; // References of Window
2844 | let j = 0;
2845 | while (j < s.length) // Traversing the window
2846 | {
2847 | m[s[j].charCodeAt(0)]--; // Calculations
2848 |
2849 | if (m[s[j].charCodeAt(0)] == 0)
2850 | count--;
2851 | if (count == 0) // Condition matching
2852 | {
2853 | while (count == 0)
2854 | {
2855 | if (ans > j - i + 1) // Sorting ans
2856 | {
2857 | ans = Math.min(ans, j - i + 1);
2858 | start = i;
2859 | }
2860 | m[s[i].charCodeAt(0)]++; // Sliding I Calculation for removing I
2861 | if (m[s[i].charCodeAt(0)] > 0)
2862 | count++;
2863 | i++;
2864 | }
2865 | }
2866 | j++;
2867 | }
2868 | if (ans != Number.MAX_VALUE) return (s).join("").substring(start, (start + ans));
2869 | else return "-1";
2870 | }
2871 | let s = "ADOBECODEBANC"; let t = "ABC";
2872 | document.write(Minimum_Window( s.split(""), t.split("")));
2873 | -----------------------------------------------------------------------------------------------------------------------------------------------------------------------------
2874 | Number of flips to make binary string alternate:- https://www.youtube.com/watch?v=7b2ShX5YMXY
2875 | var minNumOfFlip = function(s) {
2876 | let count = 0;
2877 | for (var i = 0; i< s.length; i++)
2878 | {
2879 | if(i%2 == 0 && s.charAt(i)=="0") count++;
2880 | if(i%2 != 0 && s.charAt(i)=="1") count++;
2881 | }
2882 | return Math.min(count, s.length-count);
2883 | };
2884 | console.log(minNumOfFlip("001"))
2885 | ----------------------------------------------------------------
2886 | var minNumOfFlip = function(s) {
2887 | let count = 0;
2888 | for (let i = 0; i< s.length; i++)
2889 | {
2890 | if(i%2 == 0)
2891 | {
2892 | if(s.charAt(i)=="0")
2893 | {
2894 | count++;
2895 | }
2896 | }
2897 | else if(i%2 != 0)
2898 | {
2899 | if(s.charAt(i)=="1")
2900 | {
2901 | count++;
2902 | }
2903 | }
2904 | }
2905 | return Math.min(count, s.length-count);
2906 | };
2907 | console.log(minNumOfFlip("001"))
2908 | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
2909 | Convert a sentence into its equivalent mobile numeric keypad sequence:- https://www.youtube.com/watch?v=OIwab9G2O18 from ASCII and index
2910 | function printSequence(arr,input){
2911 | let output = "";
2912 | for (let i = 0; i < input.length; i++)
2913 | {
2914 | if (input[i] == ' ') output = output + "0".charCodeAt(0); // Checking for space
2915 | else
2916 | {
2917 | let position = input[i].charCodeAt(0) - 'A'.charCodeAt(0); // Calculating index for each character
2918 | output = output + arr[position];
2919 | }
2920 | }
2921 | return output;
2922 | }
2923 | let str = ["2", "22", "222",
2924 | "3", "33", "333",
2925 | "4", "44", "444",
2926 | "5", "55", "555",
2927 | "6", "66", "666",
2928 | "7", "77", "777", "7777",
2929 | "8", "88", "888",
2930 | "9", "99", "999", "9999" ]
2931 |
2932 | let input = "GEEKSFORGEEKS";
2933 | document.write(printSequence(str, input));
2934 | ----------------------------------------------------------------
2935 | function printSequence(S)
2936 | {
2937 | //code here
2938 | var num=0;
2939 | var temp="";
2940 |
2941 | for(var i=0;i 0)
3081 | {
3082 | if (ispalindrome(s)) { // if string becomes palindrome then break
3083 | flag = 1;
3084 | break;
3085 | }
3086 | else {
3087 | cnt++;
3088 | s = s.substring(0, s.length - 1);
3089 | //console.log(s)// erase the last element of the string
3090 | }
3091 | }
3092 | if (flag) document.write(cnt);
3093 | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
3094 | Smallest window that contains all characters of string itself:-
3095 | function smallestWindow(s){
3096 | let stack = [];
3097 | for(let i = 0; i < s.length; i++)
3098 | {
3099 | if(stack.includes(s[i])) continue;
3100 | while(stack[stack.length-1]>s[i] && s.substring(i).includes(stack[stack.length-1])) // 10-1>a
3101 | {
3102 | stack.pop(); //remove
3103 | }
3104 | stack.push(s[i]); console.log(stack) //add
3105 | }
3106 | return stack.join("");
3107 | }
3108 | let str="aabcbcdbca"
3109 | let array= str.split('');
3110 | console.log(smallestWindow(array))
3111 | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
3112 | Program to generate all possible valid IP addresses from given string:- https://www.youtube.com/watch?v=g1SOXwvSqe4
3113 | function isValid( s) {
3114 | if (s.length > 3 || s.length == 0 || (s.charAt(0) == '0' && s.length > 1) || parseInt(s) > 255) {
3115 | return false;
3116 | }
3117 | return true;
3118 | }
3119 | function validIPs(ip){
3120 | var res = []
3121 | var length = ip.length;
3122 | for (var i = 1; i < 4 && i < length - 2; i++)
3123 | for (var j = i + 1; j < i + 4 && j < length - 1; j++)
3124 | for (var k = j + 1; k < j + 4 && k < length; k++) {
3125 | var part1 = ip.substring(0, i);
3126 | var part2 = ip.substring(i, j);
3127 | var part3 = ip.substring(j, k);
3128 | var part4 = ip.substring(k, length);
3129 | if (isValid(part1) && isValid(part2) && isValid(part3) && isValid(part4)) {
3130 | res.push(part1 + "." + part2 + "." + part3 + "." + part4);
3131 | }
3132 | }
3133 | return res;
3134 | }
3135 | console.log(validIPs("25525511135"))
3136 | ----------------------------------------------------
3137 | function validIPs(s){
3138 | var num, nextIndex, leftLength, result = [];
3139 | if (s.length < 4 || s.length > 12) return result; //between 0-255
3140 | var generate = function (index, block, ip) {
3141 | if (block === 4) { //only 4 digits
3142 | result.push(ip);
3143 | return;
3144 | }
3145 | var maxNextBlockSize = 12 - (block + 1) * 3;
3146 | for (var i = 1; i <= 3; i++) {
3147 | num = s.substr(index, i);
3148 | nextIndex = index + i;
3149 | leftLength = s.length - nextIndex;
3150 | if (nextIndex <= s.length && num < 256 && (num === "0" || num[0] !== "0") && leftLength <= maxNextBlockSize) {
3151 | generate(nextIndex, block + 1, ip + num + (block !== 3 ? "." : ""));
3152 | }
3153 | }
3154 | };
3155 | generate(0, 0, "");
3156 | return result;
3157 | }
3158 | console.log(validIPs("25525511135"))
3159 | ----------------------------------------------------------
3160 | function validIPs(s){
3161 | if (s.length > 12) return [];
3162 | const IP = [];
3163 | const restore = (curr = [], remain = s) =>
3164 | {
3165 | const currLen = curr.length; const remainLen = remain.length;
3166 | if (currLen > 4 || remainLen / (4 - currLen) > 3) return;
3167 | if (remainLen === 0) {
3168 | currLen === 4 && IP.push(curr.join("."));
3169 | return;
3170 | }
3171 | for (let index = 1; index <= 3 && index <= remainLen; index++)
3172 | {
3173 | const integer = remain.slice(0, index);
3174 | if (integer.length > 1 && integer[0] === "0" || integer > 255) continue;
3175 | restore([...curr, integer], remain.slice(index));
3176 | }
3177 | };
3178 | restore();
3179 | return IP;
3180 | }
3181 | console.log(validIPs("25525511135"))
3182 | ------------------------------------------------------------
3183 | function validIPs(s){
3184 | const res = [];
3185 | const addresses = (addr,combi,curIndex)=> {
3186 | let len = addr.length;
3187 | if (curIndex>4) return;
3188 | if (curIndex==4 && addr!="") return;
3189 | if (curIndex==4 && addr=="") {
3190 | res.push(combi.join('.'));
3191 | return;
3192 | }
3193 |
3194 | //1-symbol
3195 | if (len>0) {
3196 | let sub1 = parseInt(addr.substr(0,1));
3197 | addresses(addr.substr(1,len-1),[...combi,sub1],curIndex+1);
3198 | }
3199 |
3200 | //2-symbols
3201 | if (len>1) {
3202 | if (addr.charAt(0) !='0' && addr.substr(0,2) != '00') {
3203 | let sub2 = parseInt(addr.substr(0,2));
3204 | addresses(addr.substr(2,len-2),[...combi,sub2],curIndex+1);
3205 | }
3206 | }
3207 |
3208 | //3-symbols
3209 | if (len>2) {
3210 | if (addr.charAt(0) !='0' && addr.substr(0,2) != '00' && addr.substr(0,3) != '000') {
3211 | let sub3 = parseInt(addr.substr(0,3));
3212 | if (sub3<=255) addresses(addr.substr(3,len-3),[...combi,sub3],curIndex+1);
3213 | }
3214 | }
3215 | }
3216 | addresses(s,[],0);
3217 | return res;
3218 | }
3219 | console.log(validIPs("25525511135"))
3220 | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
3221 | Count of number of given string in 2D character array:- https://www.youtube.com/watch?v=ZYeVllg0D7E
3222 | function solve(i, j, s, input, size, index){
3223 | var found=0;
3224 | if(i>=0 && j>=0 && i<6 && j<6 && s[index]==input[i][j]){
3225 | var temp = s[index];
3226 | input[i][j]=0;
3227 | index+=1;
3228 | if(index==size) found =1;
3229 | else{
3230 | found= found+solve(i+1, j, s, input, size, index);
3231 | found= found+solve(i-1, j, s, input, size, index);
3232 | found= found+solve(i, j+1, s, input, size, index);
3233 | found= found+solve(i, j-1, s, input, size, index);
3234 | }
3235 | input[i][j]=temp;
3236 | }
3237 | return found;
3238 | }
3239 | function stringFind(){
3240 | var Input =[
3241 | ['D','D','D','G','D','D'],
3242 | ['B','B','D','E','B','S'],
3243 | ['B','S','K','E','B','K'],
3244 | ['D','D','D','D','D','E'],
3245 | ['D','D','D','D','D','E'],
3246 | ['D','D','D','D','D','G']
3247 | ]
3248 | var str= "GEEKS"
3249 | var size=5;//str.length; //5
3250 | var ans=0;
3251 | for(var i=0; i<6; i++){
3252 | for(var j=0; j<6; j++){
3253 | ans= ans+solve(i,j,str,Input, size,0)
3254 | }
3255 | }
3256 | return ans;
3257 | }
3258 | console.log(stringFind())
3259 | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
3260 | Search a Word in a 2D Grid of characters:-
3261 | let R, C;
3262 | let x=[-1, -1, -1, 0, 0, 1, 1, 1]; // For searching in all 8 direction
3263 | let y=[-1, 0, 1, -1, 1, -1, 0, 1];
3264 |
3265 | // This function searches in all
3266 | // 8-direction from point
3267 | // (row, col) in grid[][]
3268 | function search2D(grid,row,col,word)
3269 | {
3270 | // If first character of word
3271 | // doesn't match with
3272 | // given starting point in grid.
3273 | if (grid[row][col] != word[0])
3274 | return false;
3275 |
3276 | let len = word.length;
3277 |
3278 | // Search word in all 8 directions
3279 | // starting from (row, col)
3280 | for (let dir = 0; dir < 8; dir++) {
3281 | // Initialize starting point
3282 | // for current direction
3283 | let k, rd = row + x[dir], cd = col + y[dir];
3284 |
3285 | // First character is already checked,
3286 | // match remaining characters
3287 | for (k = 1; k < len; k++) {
3288 | // If out of bound break
3289 | if (rd >= R || rd < 0 || cd >= C || cd < 0)
3290 | break;
3291 |
3292 | // If not matched, break
3293 | if (grid[rd][cd] != word[k])
3294 | break;
3295 |
3296 | // Moving in particular direction
3297 | rd += x[dir];
3298 | cd += y[dir];
3299 | }
3300 | if (k == len) // If all character matched,then value of must be equal to length of word
3301 | return true;
3302 | }
3303 | return false;
3304 | }
3305 | // Searches given word in a given matrix in all 8 directions
3306 | function exist( grid,word) // Consider every point as starting point and search given word
3307 | {
3308 | let res=false;
3309 | for (let row = 0; row < R; row++) {
3310 | for (let col = 0; col < C; col++) {
3311 | if (search2D(grid, row, col, word))
3312 | document.write("pattern found at " + row + ", " + col+"
");
3313 | }
3314 | }
3315 | return true;
3316 | }
3317 | R = 3;
3318 | C = 13;
3319 | let grid = [['a','b','a','b'],['a','b','e','b'],['e','b','e','b'] ]
3320 | console.log(exist(grid, "abe"));
3321 | document.write("
");
3322 |
3323 | document.write("");
3324 |
3325 | let grid1 = [[ 'a','b','c'],['d','r','f'],['g','h','i'] ];
3326 | console.log(exist(grid1, "abc"));
3327 | document.write("
");
3328 | ------------------------------------------------
3329 | const isOutOfBound = (board, row, col) => row < 0 || row >= board.length || col < 0 || col >= board[0].length;
3330 |
3331 | const checkNeighbors = (board, word, row, col) => {
3332 | // Check exit conditions
3333 | if (!word.length) return true;
3334 | if (isOutOfBound(board, row, col) || board[row][col] !== word[0]) return false;
3335 |
3336 | // Save some stuff
3337 | const curChar = board[row][col];
3338 | const newWord = word.substr(1);
3339 |
3340 | board[row][col] = 0; // Disable the current character
3341 |
3342 | // Check if neighbors are fruitful
3343 | const results = checkNeighbors(board, newWord, row + 1, col) ||
3344 | checkNeighbors(board, newWord, row - 1, col) ||
3345 | checkNeighbors(board, newWord, row, col + 1) ||
3346 | checkNeighbors(board, newWord, row, col - 1);
3347 |
3348 | // Enable current character
3349 | board[row][col] = curChar;
3350 | //console.log(board[row][col])
3351 |
3352 | return results;
3353 | };
3354 |
3355 |
3356 | var exist = function(board, word) {
3357 | for (let row = 0; row < board.length; row++) {
3358 | for (let col = 0; col < board[0].length; col++) {
3359 | document.write("pattern found at " + row + ", " + col+"
");
3360 | if (checkNeighbors(board, word, row, col)) {
3361 |
3362 | return true
3363 | };
3364 | }
3365 | }
3366 | return false;
3367 | };
3368 | let grid = [['a','b','a','b'],['a','b','e','b'],['e','b','e','b'] ]
3369 | console.log(exist(grid, "abe"));
3370 | document.write("
");
3371 |
3372 | document.write("");
3373 |
3374 | let grid1 = [[ 'a','b','c'],['d','r','f'],['g','h','i'] ];
3375 | console.log(exist(grid1, "abc"));
3376 | document.write("
");
3377 | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
3378 | Function to find Number of customers who could not get a computer:-
3379 | let MAX_CHAR = 26; // n is number of computers in cafe. // 'seq' is given sequence of customer entry, exit events
3380 | function runCustomerSimulation(n, seq) {
3381 | // seen[i] = 0, indicates that customer 'i' is not in cafe
3382 | // seen[1] = 1, indicates that customer 'i' is in cafe but computer is not assigned yet.
3383 | // seen[2] = 2, indicates that customer 'i' is in cafe and has occupied a computer.
3384 | let seen = new Array(MAX_CHAR).fill(0); // Initialize result which is number of customers who could not get any compute
3385 | let res = 0;
3386 | let occupied = 0; // To keep track of occupied computers
3387 | for (let i = 0; i < seq.length; i++)
3388 | {
3389 | let ind = seq[i].charCodeAt(0) - 'A'.charCodeAt(0); // Find index of current character in seen[0...25]
3390 | if (seen[ind] == 0)
3391 | { // If First occurrence of 'seq[i]'
3392 | seen[ind] = 1; // set the current character as seen
3393 | if (occupied < n) { // If number of occupied computers is less than n, then assign a computer to new customer
3394 | occupied++;
3395 | seen[ind] = 2; // Set the current character as occupying a computer
3396 | }
3397 | else // Else this customer cannot get a computer,increment result
3398 | res++;
3399 | }
3400 | else { // If this is second occurrence of 'seq[i]'
3401 | if (seen[ind] == 2) { // Decrement occupied only if this customer was using a computer
3402 | occupied--;
3403 | }
3404 | seen[ind] = 0;
3405 | }
3406 | }
3407 | return res;
3408 | }
3409 | document.write(runCustomerSimulation(2, "ABBAJJKZKZ") + "
");
3410 | document.write(runCustomerSimulation(3, "GACCBDDBAGEE") + "
");
3411 | document.write(runCustomerSimulation(3, "GACCBGDDBAEE") + "
");
3412 | document.write(runCustomerSimulation(1, "ABCBCA") + "
");
3413 | document.write(runCustomerSimulation(1, "ABCBCADEED") + "
");
3414 | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
3415 | EDIT Distance: Given two strings s and t. Return the minimum number of operations required to convert s to t. (Using DP)
3416 | var minDistance = function(word1, word2) {
3417 | let dp = Array(word1.length+1).fill(null).map(()=>(Array(word2.length+1).fill(0)));
3418 | for (let i=0;i= 0)
3462 | {
3463 | // If there is a mismatch, then keep incrementing result 'res' until B[j] is not found in A[0..i]
3464 | if (A[i] != B[j])
3465 | res++;
3466 | else
3467 | j--;
3468 |
3469 | i--;
3470 | }
3471 | return res;
3472 | }
3473 |
3474 | let A = "EACBD";
3475 | let B = "EABCD";
3476 | console.log(minOps(A, B));
3477 | ------------------------------------------------------------------------------------------------------------------------------------------------------------------
3478 |
3479 |
3480 |
--------------------------------------------------------------------------------