Advertisement
amt

JS

amt
Dec 8th, 2020 (edited)
784
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*
  2.  
  3. 1 | Two Sum | Easy
  4.  
  5. Return indices of 2 numbers from array adding to given sum.
  6.  
  7. console.log(twoSum([2, 7, 11, 15],9)); // [ 0, 1 ]
  8.  
  9. */
  10.  
  11. // A-I
  12.  
  13. let twoSum = (arr, sum) => {
  14.  
  15.     const seen = {};
  16.  
  17.     for (let i = 0; i < arr.length; i++) {
  18.  
  19.       const number = arr[i];
  20.       const diff = sum - arr[i];
  21.  
  22.       if (seen[diff] !== undefined) {
  23.         return [seen[diff], i];
  24.       }
  25.  
  26.       seen[number] = i;
  27.     }
  28.   };
  29.  
  30. // console.log(twoSum([2,8,3,7],9)); // [ 0, 3 ]
  31.  
  32. // A-II
  33.  
  34. let twoSum2 = function(arr, sum) {
  35.  
  36.   const seen = new Set();
  37.  
  38.   for (let i = 0; i < arr.length; i++) {
  39.  
  40.     const number = arr[i];
  41.     const diff = sum - arr[i];
  42.  
  43.     if (seen.has(diff)) {
  44.       return [arr.indexOf(diff), i]
  45.     }
  46.  
  47.     seen.add(number);
  48.   }
  49. };
  50.  
  51. // console.log(twoSum2([2,8,3,7],9)); // [ 0, 3 ]
  52.  
  53.  
  54. /*
  55.  
  56. 2 | Add Two Numbers | Medium
  57.  
  58. Given two linked lists of integers with digits stored in reverse order, Add two numbers and return the sum as a linked list.
  59.  
  60. You may assume the two numbers do not contain any leading zero, except the number 0 itself.
  61.  
  62. Input: l1 = [2,4,3], l2 = [5,6,4]
  63. Output: [7,0,8] // 342 + 465 = 807
  64.  
  65. */
  66.  
  67. // A-I
  68.  
  69. /** @param {ListNode} l1 | @param {ListNode} l2 | @return {ListNode} */
  70. var addTwoNumbers = function(l1, l2) {
  71.   let carry = 0;
  72.   let digitSum = 0;
  73.   let head = new ListNode();
  74.   let now = head;
  75.   while (l1 || l2) {
  76.     digitSum = (l1 ? l1.val : 0) + (l2 ? l2.val : 0) + carry;
  77.     carry = digitSum > 9 ? 1 : 0;
  78.     now.next = new ListNode(digitSum % 10);
  79.     now = now.next;
  80.     l1 = l1 ? l1.next : null;
  81.     l2 = l2 ? l2.next : null;
  82.   }
  83.   if (carry) now.next = new ListNode(carry);
  84.   return head.next;
  85. };
  86. //  Time complexity : O(max(m,n)). Space complexity : O(max(m,n)).
  87.  
  88. // console.log(listToArray(addTwoNumbers(arrToList([2,4,3]), arrToList([5,6,4])))); // [ 7, 0, 8 ]
  89. // listToArray(addTwoNumbers(arrToList([9,9,9,9,9,9,9]), arrToList([9,9,9,9]))); // [8,9,9,9,0,0,0,1]
  90.  
  91. // Helper functions
  92. function ListNode(val, next) {
  93.      this.val = (val ? val : 0)
  94.      this.next = (next ? next : null);
  95.  }
  96.  
  97. function listToArray(list) {
  98.   let arr = []; // Initialise an array to return
  99.    while (list) {
  100.     arr = [...arr, list.val];
  101.     list = list.next;
  102.   };
  103.   return arr;
  104. }
  105.  
  106. function arrToList (arr) {
  107.   let list = null;
  108.   for(i=0;i<arr.length;i++){
  109.     list = {val: arr[i], next: arrToList(arr.slice(i+1,arr.length))}
  110.   }
  111.   return list;
  112. }
  113.  
  114. /*
  115.  
  116. 3 | Longest Substring Without Repeating Characters | Medium
  117.  
  118. Return length of Longest Substring
  119. Input: s = "abcabcbb" Substring = "abc", "bca", "cab" so Output: 3
  120. Input: s = "pwwkew" Substring = "wke", "kew" so Output: 3. Substring != pwke, as substrings are "pw" and "wke", resetting when "w" repeats.
  121.  
  122. */
  123.  
  124. // A-I
  125.  
  126. /** @param {string} s| @return {number} */
  127. let subStrL = function(str) {
  128.     let map = {};
  129.     let max = 0;
  130.     let start = 0;
  131.     for (let position = 0; position < str.length; position++) {
  132.       const charc = str[position];
  133.       if (map[charc] !== undefined) {
  134.         start = Math.max(start, map[charc] + 1); // start from next charcter after duplicate charc
  135.       }
  136.       map[charc] = position;
  137.       max = Math.max(max, position - start + 1); // current length position - start + 1
  138.     }
  139.     return max;
  140. };
  141.  
  142. //  Time complexity : O(n). Space complexity : O(1).
  143.  
  144. // console.log(subStrL("pwwkew")); // 3
  145.  
  146. 8 | String to Integer (atoi) | Medium
  147. Implement function which converts a string to a 32-bit signed integer capped in range [-231, 231 - 1].
  148. Ignore leading whitespaces and disregard characters other than +, - and numbers.
  149.  
  150. Input: s = "42" Output: 42 | Input: s = "   -42" Output: -42 | Input: s = "4193 with words" Output: 4193
  151. Input: s = "words and 987" Output: 0 | Input: s = "-91283472332" Output: -2147483648
  152.  
  153. // A-I
  154.  
  155. /** @param {string} str | @return {number} */
  156. let myAtoi = function(str) {
  157.   let i = 0;
  158.   let sign = 1;
  159.   let res = 0;
  160.   // str = str.trim();
  161.   let len = str.length;
  162.   let INT_MAX = Math.pow(2, 31) - 1;
  163.   let INT_MIN = - Math.pow(2, 31); // 2147483648
  164.  
  165.   while (str[i] === ' ') i++; // str.trim();
  166.  
  167.   if (str[i] === '+' || str[i] === '-') {
  168.     sign = str[i] === '+' ? 1 : -1;
  169.     i++;
  170.   }
  171.  
  172.   while (str[i] >= '0' && str[i] <= '9') {
  173.     res = (res * 10) + (str[i] - 0);
  174.     if (sign === 1 && res > INT_MAX) return INT_MAX;
  175.     if (sign === -1 && res > INT_MIN) return INT_MIN;
  176.     i++;
  177.   }
  178.  
  179.   return res * sign;
  180. };
  181. //  Time complexity : O(n). Space complexity : O(1).
  182.  
  183. console.log(myAtoi("-2147483649")); // -2147483648
  184.  
  185. /*
  186.  
  187. 11 | Container with most water |
  188.  
  189. Return max amount of water container can store, given an array of numbers which represent heights.
  190.  
  191. */
  192.  
  193. var maxArea = function(height) {
  194.     var max = 0;
  195.     var l = 0; // left
  196.     var r = height.length - 1; // right
  197.     while (l < r) {
  198.       max = Math.max(max, Math.min(height[l], height[r]) * (r - l));
  199.       if (height[l] < height[r]) {
  200.         l++;
  201.       } else {
  202.         r--;
  203.       }
  204.     }
  205.     return max;
  206.   };
  207.   // Time complexity : O(n) | Space complexity : O(1).
  208.  
  209.   // console.log(maxArea([1,8,6,2,5,4,8,3,7])); // 49
  210.   // console.log(maxArea([1,1])); // 1
  211.  
  212.  
  213. /** 12 2 @param {number} num | @return {string} */
  214.  var intToRoman1 = function(num) {
  215.   var str = [
  216.     ['I', 'V'], // 1s: 1, 5
  217.     ['X', 'L'], // 10s: 10, 50
  218.     ['C', 'D'], // 100s: 100, 500
  219.     ['M'] // 1000s: 1000
  220.   ];
  221.   var res = '';
  222.   var i = 0;
  223.   var digit = 0;
  224.   for ( let i = 0 ; num > 0; i++) {
  225.     digit = num % 10;
  226.     if (digit === 9) {
  227.       res = str[i][0] + str[i + 1][0] + res;
  228.     } else if (digit >= 5) { // 6, 7, 8
  229.       res = str[i][1] + str[i][0].repeat(digit - 5) + res;
  230.     } else if (digit === 4) {
  231.       res = str[i][0] + str[i][1] + res;
  232.     } else { // 0, 1, 2, 3
  233.       res = str[i][0].repeat(digit) + res;
  234.     }
  235.     num = Math.floor(num / 10);
  236.     // i++;
  237.   }
  238.   return res;
  239. };
  240.  
  241. // Time complexity : O(log(n)) | Space complexity : O(1).
  242.  
  243. // console.log(intToRoman1(402)); // CDII
  244. // console.log(intToRoman1(3000)); // MMM
  245. // console.log(intToRoman1(93)); // XCIII
  246. // console.log(intToRoman1(48)); // XLVIII
  247. // console.log(intToRoman1(4)); // IV
  248. // console.log(intToRoman1(900)); // CMXCIX
  249.  
  250. // console.log('Hi'.repeat(2)) // HiHi
  251. // console.log('Hi'.repeat(1)) // Hi
  252. // console.log('Hi'.repeat(0)) //
  253.  
  254. /**  12 @param {number} num | @return {string} */
  255. var intToRoman2 = function(num) {
  256.   var map = [
  257.     [1, "I"],
  258.     [4, "IV"],
  259.     [5, "V"],
  260.     [9, "IX"],
  261.     [10, "X"],
  262.     [40, "XL"],
  263.     [50, "L"],
  264.     [90, "XC"],
  265.     [100, "C"],
  266.     [400, "CD"],
  267.     [500, "D"],
  268.     [900, "CM"],
  269.     [1000, "M"]
  270.   ];
  271.   var res = '';
  272.   var i = 12;
  273.   var tmp = 0;
  274.   while (num > 0) {
  275.     res += map[i][1].repeat(Math.floor(num / map[i][0]));
  276.     num %= map[i][0];
  277.     console.log(map[i][0]);
  278.     i--;
  279.   }
  280.   return res;
  281. };
  282.  
  283. //Time complexity : O(log(n)) | Space complexity : O(1).
  284.  
  285. // console.log(intToRoman2(402)); // CDII
  286. // console.log(intToRoman2(3000)); // MMM
  287. // console.log(intToRoman2(93)); // XCIII
  288. // console.log(intToRoman2(4)); // IV
  289.  
  290. 189. WIP
  291. let nums = [1,2,3,4,5,6,7], k = 3;
  292.  
  293. const numsLength = nums.length;
  294. let newArr = [];
  295. let mapArr = nums.map((element, index) => {
  296.     if(index < (numsLength - k)){
  297.         newArr[(numsLength - 1) - (numsLength - k)] = element;
  298.        
  299.     }else{
  300.         newArr[(index -1) - (numsLength - k)] = element;
  301.     }
  302. });
  303. console.log(numsLength, newArr);
  304.  
  305. =========================================================
  306. 1281 |Subtract the Product and Sum of Digits of an Integer | Easy
  307. Given an integer number n, return the difference between the product of its digits and the sum of its digits.
  308. var subtractProductAndSum = function(n) {
  309.     // Initialize the sum and the product with neutral values
  310.     var sum = 0;
  311.     var product = 1;
  312.  
  313.     while (n > 0) {
  314.         var digit = n % 10;
  315.         sum += digit;
  316.         product *= digit;
  317.  
  318.         n = Math.floor(n / 10);
  319.     }
  320.  
  321.     return product - sum;
  322. };
  323.  
  324.  
  325. const firstTen = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
  326.  
  327. // console.log(firstTen.some((element) => {
  328. //   return element % 2 === 0 }
  329. // )); // true
  330.  
  331. const even = (element) => element % 2 === 0;
  332. // console.log(firstTen.some(even)); // true
  333.  
  334.  
  335. const fibonacciElements = [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144]
  336. function fibonacci(num) {
  337.     if(num < 2) {
  338.         return num;
  339.     }
  340.     else {
  341.         return fibonacci(num-1) + fibonacci(num - 2);
  342.     }
  343. }
  344. // console.log('fibonacci', fibonacci(3)); // 2
  345.  
  346. // for(let i = 0; i < 5; i++) {
  347. //         console.log(fibonacci(i));
  348. //     }
  349. /*
  350. 0
  351. 1
  352. 1
  353. 2
  354. 3
  355. */
  356.  
  357. // Pagination
  358. const pagination = () => {
  359.   const paginationReference = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
  360.  
  361.   let paginatedData = [];
  362.   let pageSize = 2;
  363.   const dataPages = Math.ceil(paginationReference.length/ pageSize);
  364.   for(let i = 0; i < 10; i += pageSize) {
  365.     paginatedData.push([...paginationReference.slice(i, i+ pageSize)]);
  366.   }
  367. }
  368.  
  369.  
  370. let strForNumber = "234";
  371. // console.log(strForNumber[1]); // 3
  372. // console.log(strForNumber[2]); // 4
  373. // console.log("234"[2]) // 4
  374. // console.log(5 * 10); // 50
  375. // console.log((strForNumber[2] - 0)); // 4
  376. // console.log((5 * 10) + (strForNumber[2] - 0)); // 54
  377. // console.log(typeof((5 * 10) + (strForNumber[2] - 0))); // number
  378.  
  379. let numbersToSort = [4, 2, 5, 1, 3];
  380. numbersToSort.sort((a, b) => a - b);
  381. // console.log('sorted numbers', numbersToSort); // sorted numbers [ 1, 2, 3, 4, 5 ]
  382.  
  383. let valueToFilter = 3
  384. let arrToFilter = [1, 2, 3, 4, 5, 3]
  385. arrFltered1 = arrToFilter.filter(item => item !== valueToFilter)
  386. arrFiltered2 = arrToFilter.filter(item => {return item !== valueToFilter})
  387. // console.log('after filter', arrFltered1); // after filter [ 1, 2, 4, 5 ]
  388. // console.log('after filter', arrFiltered2); // after filter [ 1, 2, 4, 5 ]
  389.  
  390. const animals = ['pigs', 'goats', 'sheep'];
  391. // console.log(animals.push('chickens', 'cats', 'dogs')); // 6
  392. // console.log(animals.pop()); // dogs
  393.  
  394. [aRest, bRest] = [10, 20];
  395. // console.log(aRest);// 10
  396. // console.log(bRest);// 20
  397. const [aResting, bResting, ...resting] = [10, 20, 30, 40, 50];
  398. // console.log(resting);// [30,40,50]
  399.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement