Advertisement
amt

DSJSApp

amt
Aug 6th, 2021 (edited)
377
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /* 1 Return indices of 2 numbers in Array, which add up to another number.
  2.  
  3.  
  4. Example:
  5.  
  6. Given nums = [2, 7, 11, 15], target = 9,
  7. Because nums[0] + nums[1] = 2 + 7 = 9,
  8. return [0, 1]. */
  9.  
  10. // 1
  11. let twoSum = function(nums, target) {
  12.     const seenNumsWithIndexes = {};
  13.    
  14.     for (let i = 0; i < nums.length; i++) {
  15.       const num = nums[i];
  16.       if (seenNumsWithIndexes[target - num] !== undefined) {
  17.         return [seenNumsWithIndexes[target - num], i];
  18.       }
  19.       seenNumsWithIndexes[num] = i;
  20.     }
  21.   };
  22.    
  23. //   console.log(twoSum([2,8,3,7],9)); // [ 0, 3 ]
  24.  
  25. /* 2 You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
  26.  
  27. You may assume the two numbers do not contain any leading zero, except the number 0 itself.
  28.  
  29. Example
  30.  
  31. Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
  32. Output: 7 -> 0 -> 8
  33. Explanation: 342 + 465 = 807 */
  34.  
  35. /** 2 @param {ListNode} l1 | @param {ListNode} l2 | @return {ListNode} */
  36. var addTwoNumbers = function(l1, l2) {
  37.     var carry = 0;
  38.     var digitSum = 0;
  39.     var head = new ListNode();
  40.     var now = head;
  41.     while (l1 || l2) {
  42.       digitSum = (l1 ? l1.val : 0) + (l2 ? l2.val : 0) + carry;
  43.       carry = digitSum > 9 ? 1 : 0;
  44.       now.next = new ListNode(digitSum % 10);
  45.       now = now.next;
  46.       l1 = l1 ? l1.next : null;
  47.       l2 = l2 ? l2.next : null;
  48.     }
  49.     if (carry) now.next = new ListNode(carry);
  50.     return head.next;
  51.   };
  52.   //  Time complexity : O(max(m,n)). Space complexity : O(max(m,n)).
  53.    
  54. //   console.log(listToArray(addTwoNumbers(arrToList([2,4,3]), arrToList([5,6,4])))); // [ 7, 0, 8 ]
  55. //   // listToArray(addTwoNumbers(arrToList([9,9,9,9,9,9,9]), arrToList([9,9,9,9]))); // [8,9,9,9,0,0,0,1]
  56.    
  57.   // Helper functions
  58.   function ListNode(val, next) {
  59.        this.val = (val ? val : 0)
  60.        this.next = (next ? next : null);
  61.    }
  62.    
  63.   function listToArray(list) {
  64.     let arr = []; // Initialise an array to return
  65.      while (list) {
  66.       arr = [...arr, list.val];
  67.       list = list.next;
  68.     };
  69.     return arr;
  70.   }
  71.    
  72.   function arrToList (arr) {
  73.     let obj = null;
  74.     for(i=0;i<arr.length;i++){
  75.       obj = {val: arr[i], next: arrToList(arr.slice(i+1,arr.length))}
  76.     }
  77.     return obj;
  78.   }
  79.  
  80. /* 3 Given a string, find the length of the longest substring without repeating characters.
  81.  
  82. Examples:
  83.  
  84. Given "abcabcbb", the answer is "abc", which the length is 3.
  85.  
  86. Given "bbbbb", the answer is "b", with the length of 1.
  87.  
  88. Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring. */
  89.  
  90. /** 3 @param {string} s| @return {number} */
  91. let lengthOfLongestSubstring = function(s) {
  92.     let map = {};
  93.     let max = 0;
  94.     let start = 0;
  95.     for (let i = 0; i < s.length; i++) {
  96.       if (map[s[i]] !== undefined) {
  97.         start = Math.max(start, map[s[i]] + 1); // start from latest instance of char
  98.       }
  99.       map[s[i]] = i;
  100.       max = Math.max(max, i - start + 1);
  101.     }
  102.     return max;
  103.   };
  104.    
  105. //   console.log(lengthOfLongestSubstring("pwwkew")); // 3
  106.  
  107. /* 8 Implement atoi which converts a string to an integer.
  108.  
  109. The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.
  110.  
  111. The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.
  112.  
  113. If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.
  114.  
  115. If no valid conversion could be performed, a zero value is returned.
  116.  
  117. Note:
  118.  
  119. Only the space character ' ' is considered as whitespace character.
  120. Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. If the numerical value is out of the range of representable values, INTMAX (231 − 1) or INTMIN (−231) is returned.
  121. Example 1:
  122.  
  123. Input: "42"
  124. Output: 42
  125. Example 2:
  126.  
  127. Input: "   -42"
  128. Output: -42
  129. Explanation: The first non-whitespace character is '-', which is the minus sign.
  130.              Then take as many numerical digits as possible, which gets 42.
  131. Example 3:
  132.  
  133. Input: "4193 with words"
  134. Output: 4193
  135. Explanation: Conversion stops at digit '3' as the next character is not a numerical digit.
  136. Example 4:
  137.  
  138. Input: "words and 987"
  139. Output: 0
  140. Explanation: The first non-whitespace character is 'w', which is not a numerical
  141.              digit or a +/- sign. Therefore no valid conversion could be performed.
  142. Example 5:
  143.  
  144. Input: "-91283472332"
  145. Output: -2147483648
  146. Explanation: The number "-91283472332" is out of the range of a 32-bit signed integer.
  147.              Thefore INT_MIN (−231) is returned. */
  148.  
  149. /** 8 @param {string} str | @return {number} */
  150. let myAtoi = function(str) {
  151.     let i = 0;
  152.     let sign = 1;
  153.     let res = 0;
  154.     // str = str.trim();
  155.     let INT_MAX = Math.pow(2, 31) - 1;
  156.     let INT_MIN = - Math.pow(2, 31); // 2147483648
  157.    
  158.     while (str[i] === ' ') i++; // str.trim();
  159.    
  160.     if (str[i] === '+' || str[i] === '-') {
  161.       sign = str[i] === '+' ? 1 : -1;
  162.       i++;
  163.     }
  164.    
  165.     while (str[i] >= '0' && str[i] <= '9') {
  166.       res = (res * 10) + (str[i] - 0);
  167.       if (sign === 1 && res > INT_MAX) return INT_MAX;
  168.       if (sign === -1 && res > INT_MIN) return INT_MIN;
  169.       i++;
  170.     }
  171.    
  172.     return res * sign;
  173.   };
  174.   //  Time complexity : O(n). Space complexity : O(1).
  175.    
  176. //   console.log(myAtoi("-2147483649")); // -2147483648
  177. //   console.log(myAtoi("lala -2147483649")); // 0
  178. //   console.log(myAtoi("83649 jin")); // 0
  179.  
  180. // let numbers = [4, 2, 5, 1, 3];
  181. // numbers.sort((a, b) => a - b);
  182. // console.log('sorted numbers', numbers);
  183.  
  184. /* 11 Given n non-negative integers a1, a2, …, an, where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.
  185.  
  186. Note: You may not slant the container and n is at least 2. */
  187.  
  188. /** 11 | @param {number[]} height |@return {number} */
  189. var maxArea = function(height) {
  190.     var max = 0;
  191.     var l = 0; // left
  192.     var r = height.length - 1; // right
  193.     while (l < r) {
  194.       max = Math.max(max, Math.min(height[l], height[r]) * (r - l));
  195.       if (height[l] < height[r]) {
  196.         l++;
  197.       } else {
  198.         r--;
  199.       }
  200.     }
  201.     return max;
  202.   };  
  203.   // Time complexity : O(n) | Space complexity : O(1).
  204.  
  205. //   console.log(maxArea([1,8,6,2,5,4,8,3,7]));
  206.  
  207. /* 15 Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
  208.  
  209. Note:
  210.  
  211. The solution set must not contain duplicate triplets.
  212.  
  213. Example:
  214.  
  215. Given array nums = [-1, 0, 1, 2, -1, -4],
  216.  
  217. A solution set is:
  218. [
  219.   [-1, 0, 1],
  220.   [-1, -1, 2]
  221. ] */
  222.  
  223. /** 15 @param {number[]} nums | @return {number[][]} */
  224.  var threeSum = function(nums) {
  225.   var len = nums.length;
  226.   var res = [];
  227.   var l = 0; // left
  228.   var r = 0; // right
  229.   nums.sort((a, b) => (a - b));
  230.   for (var i = 0; i < len; i++) {
  231.     if (i > 0 && nums[i] === nums[i - 1]) continue;
  232.     l = i + 1;
  233.     r = len - 1;
  234.     while (l < r) {
  235.       if (nums[i] + nums[l] + nums[r] < 0) {
  236.         l++;
  237.       } else if (nums[i] + nums[l] + nums[r] > 0) {
  238.         r--;
  239.       } else {
  240.         res.push([nums[i], nums[l], nums[r]]);
  241.         while (l < r && nums[l] === nums[l + 1]) l++;
  242.         while (l < r && nums[r] === nums[r - 1]) r--;
  243.         l++;
  244.         r--;
  245.       }
  246.     }
  247.   }
  248.   return res;
  249. };
  250. //Time complexity : O(n^2) | Space complexity : O(1)
  251. // console.log(threeSum([-1,0,1,2,-1,-4]));
  252.  
  253. /* 16 Given an array nums of n integers and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution.
  254.  
  255. Example:
  256.  
  257. Given array nums = [-1, 2, 1, -4], and target = 1.
  258.  
  259. The sum that is closest to the target is 2. (-1 + 2 + 1 = 2). */
  260.  
  261. /** 16  @param {number[]} nums | @param {number} target | @return {number} */
  262.  var threeSumClosest = function(nums, target) {
  263.   var len = nums.length;
  264.   var res = nums[0] + nums[1] + nums[2];
  265.   var sum = 0;
  266.   var l = 0; // left
  267.   var r = 0; // right
  268.   nums.sort((a, b) => (a - b));
  269.   for (var i = 0; i < len - 2; i++) {
  270.     if (i > 0 && nums[i] === nums[i - 1]) continue;
  271.     l = i + 1;
  272.     r = len - 1;
  273.     while (l < r) {
  274.       sum = nums[i] + nums[l] + nums[r];
  275.       if (sum < target) {
  276.         l++;
  277.       } else if (sum > target) {
  278.         r--;
  279.       } else {
  280.         return sum;
  281.       }
  282.       if (Math.abs(sum - target) < Math.abs(res - target)) res = sum;
  283.     }
  284.   }
  285.   return res;
  286. };
  287. // Time complexity : O(n^2) Space complexity : O(1)
  288. // console.log(threeSumClosest([-1, 2, 1, -4],1));
  289.  
  290. /* Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
  291.  
  292. An input string is valid if:
  293.  
  294. Open brackets must be closed by the same type of brackets.
  295. Open brackets must be closed in the correct order.
  296. Note that an empty string is also considered valid. */
  297.  
  298. /** 20 @param {string} s | @return {boolean} */
  299.  var isPranthesisValid = function(s) {
  300.   var stack = [];
  301.   var len = s.length;
  302.   var map = {
  303.     '(': ')',
  304.     '[': ']',
  305.     '{': '}'
  306.   };
  307.   for (var i = 0; i < len; i++) {
  308.     if (stack.length > 0 && map[stack[stack.length - 1]] === s[i]) { // value at map's key complements s[i]
  309.     // if (stack.length > 0 && s[i] != s[i+1]) { // generic solution
  310.       stack.pop();
  311.     } else {
  312.       stack.push(s[i]);
  313.     }
  314.   }
  315.   return stack.length === 0;
  316. };
  317. // Time complexity : O(n) Space complexity : O(n)
  318. // console.log(isPranthesisValid("()[]{}}"));
  319. // console.log(isPranthesisValid("([{}])"));
  320.  
  321. // const animals = ['pigs', 'goats', 'sheep'];
  322. // console.log(animals.push('chickens', 'cats', 'dogs')); // 6
  323. // console.log(animals.pop()); // dogs
  324.  
  325. /* 21 Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
  326.  
  327. Input: 1->2->4, 1->3->4
  328. Output: 1->1->2->3->4->4 */
  329.  
  330. /** 21 @param {ListNode} l1 | @param {ListNode} l2 | @return {ListNode} */
  331. var mergeTwoLists = function(l1, l2) {
  332.   var head = new ListNode();
  333.   var now = head;
  334.   while (l1 || l2) {
  335.     if (l1 === null || (l2 !== null && l2.val < l1.val)) {
  336.       now.next = l2;
  337.       l2 = l2.next;
  338.     } else {
  339.       now.next = l1;
  340.       l1 = l1.next;
  341.     }
  342.     now = now.next;
  343.   }
  344.   return head.next;
  345. };
  346. // Time complexity : O(m+n) | Space complexity : O(m+n)
  347.  
  348.  
  349. // console.log(listToArray(mergeTwoLists(arrToList([1,2,4]), arrToList([1,3,4])))); // [ 1,1,2,3,4,4 ]
  350.  
  351. /* Reverse a singly linked list.
  352.  
  353. Example:
  354.  
  355. Input: 1->2->3->4->5->NULL
  356. Output: 5->4->3->2->1->NULL
  357. Follow up:
  358.  
  359. A linked list can be reversed either iteratively or recursively. Could you implement both? */
  360.  
  361. /* Implement strStr().
  362.  
  363. Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
  364.  
  365. Example 1:
  366.  
  367. Input: haystack = "hello", needle = "ll"
  368. Output: 2
  369. Example 2:
  370.  
  371. Input: haystack = "aaaaa", needle = "bba"
  372. Output: -1
  373. Clarification:
  374.  
  375. What should we return when needle is an empty string? This is a great question to ask during an interview.
  376.  
  377. For the purpose of this problem, we will return 0 when needle is an empty string. This is consistent to C's strstr() and Java's indexOf(). */
  378.  
  379. /** 28 @param {string} haystack | @param {string} needle | @return {number} */
  380.  var strStr = function(haystack, needle) {
  381.   var len1 = haystack.length;
  382.   var len2 = needle.length;
  383.   if (!len2) return 0;
  384.   for (var i = 0; i < len1; i++) {
  385.     for (var j = 0; j < len2; j++) {
  386.       if (i + j === len1) return -1;
  387.       if (haystack[i + j] !== needle[j]) break; // chars don't match
  388.       if (j === len2 - 1) return i;
  389.     }
  390.   }
  391.   return -1; // not found
  392. };
  393. // Time complexity : O(n*m) | Space complexity : O(1)
  394. // console.log(strStr('Hello', 'llp')); // 2
  395.  
  396. var trap = function(height) {
  397.   var res = 0;
  398.   var left = 0;
  399.   var right = height.length - 1;
  400.   var leftMax = 0;
  401.   var rightMax = 0;
  402.  
  403.   while (left < right) {
  404.     if (height[left] < height[right]) {
  405.       if (height[left] >= leftMax) {
  406.         leftMax = height[left];
  407.       } else {
  408.         res += leftMax - height[left];
  409.       }
  410.       left++;
  411.     } else {
  412.       if (height[right] >= rightMax) {
  413.         rightMax = height[right];
  414.       } else {
  415.         res += rightMax - height[right];
  416.       }
  417.       right--;
  418.     }
  419.   }
  420.  
  421.   return res;
  422. };
  423. // Time complexity : O(n) | Space complexity : O(1)
  424. // console.log(trap([0,1,0,2,1,0,1,3,2,1,2,1])); // 6
  425. // console.log(trap([1,0,1]));
  426.  
  427. /* Reverse a singly linked list.
  428.  
  429. Example:
  430.  
  431. Input: 1->2->3->4->5->NULL
  432. Output: 5->4->3->2->1->NULL
  433. Follow up:
  434.  
  435. A linked list can be reversed either iteratively or recursively. Could you implement both? */
  436.  
  437. /** 206 1 | @param {ListNode} head |@return {ListNode} */
  438. var reverseList = function(head) {
  439.     var newHead = null;
  440.     var tmp = null;
  441.     while (head) {
  442.       tmp = head.next;
  443.       head.next = newHead;
  444.       newHead = head;
  445.       head = tmp;
  446.     }
  447.     return newHead;
  448.   };
  449.  
  450. //Time complexity : O(n). Space complexity : O(1).
  451.  
  452. // console.log(listToArray(reverseList(arrToList([2,4,3]))));
  453.  
  454. /** 206 2 | @param {ListNode} head |@return {ListNode} */
  455. var reverseListRecursion = function(head) {
  456.   return reverse(null, head);
  457. };
  458.  
  459. var reverseRecursion = function (newHead, head) {
  460.   if (!head) return newHead;
  461.   var tmp = head.next;
  462.   head.next = newHead;
  463.   return reverse(head, tmp);
  464. };
  465.  
  466. // Time complexity : O(n). Space complexity : O(n).
  467.  
  468. // console.log(listToArray(reverseListRecursion(arrToList([2,4,3]))));
  469.  
  470. /**  @param {number} num | @return {string} */
  471.  var intToRoman = function(num) {
  472.   var map = [
  473.     [1, "I"],
  474.     [4, "IV"],
  475.     [5, "V"],
  476.     [9, "IX"],
  477.     [10, "X"],
  478.     [40, "XL"],
  479.     [50, "L"],
  480.     [90, "XC"],
  481.     [100, "C"],
  482.     [400, "CD"],
  483.     [500, "D"],
  484.     [900, "CM"],
  485.     [1000, "M"]
  486.   ];
  487.   var res = '';
  488.   var i = 12;
  489.   var tmp = 0;
  490.   while (num > 0) {
  491.     res += map[i][1].repeat(Math.floor(num / map[i][0]));
  492.     num %= map[i][0];
  493.     console.log(map[i][0]);
  494.     i--;
  495.   }
  496.   return res;
  497. };
  498.  
  499. // console.log(intToRoman(402)); // CDII
  500. // console.log(intToRoman(3000)); // MMM
  501. // console.log(intToRoman(93)); // XCIII
  502. // console.log(intToRoman(4)); // IV
  503.  
  504. /**
  505.  * @param {number} num
  506.  * @return {string}
  507.  */
  508.  var intToRoman1 = function(num) {
  509.   var str = [
  510.     ['I', 'V'], // 1s
  511.     ['X', 'L'], // 10s
  512.     ['C', 'D'], // 100s
  513.     ['M'] // 1000s
  514.   ];
  515.   var res = '';
  516.   var i = 0;
  517.   var digit = 0;
  518.   for ( let i = 0 ; num > 0; i++) {
  519.     digit = num % 10;
  520.     if (digit === 9) {
  521.       res = str[i][0] + str[i + 1][0] + res; // IX + res
  522.     } else if (digit >= 5) {
  523.       res = str[i][1] + str[i][0].repeat(digit - 5) + res;
  524.     } else if (digit === 4) {
  525.       res = str[i][0] + str[i][1] + res; // IV + res
  526.     } else { // 0, 1, 2, 3
  527.       res = str[i][0].repeat(digit) + res;
  528.     }
  529.     num = Math.floor(num / 10);
  530.     // i++;
  531.   }
  532.   return res;
  533. };
  534.  
  535. // console.log(intToRoman1(402)); // CDII
  536. // console.log(intToRoman1(3000)); // MMM
  537. // console.log(intToRoman1(93)); // XCIII
  538. // console.log(intToRoman1(48)); // XLVIII
  539. // console.log(intToRoman1(4)); // IV
  540. // console.log(intToRoman1(900)); // CMXCIX
  541.  
  542.  
  543.  
  544. ============
  545. // convert a number to linked lint in reverse
  546. f = n => n ? { val: n % 10, next: f(n / 10 | 0) } : null;
  547.  
  548. // console.log( f(465) ); // { val: 5, next: { val: 6, next: { val: 4, next: null } } }
  549. ============
  550. function ReverseListNodeToArray(listNode) {
  551.         let returnedArray = []; // Initialise an array to return
  552.         if (listNode.next != null) { // ListNode has level?
  553.             // returnedArray = returnedArray.concat( // Merge with the node result
  554.             //     ReverseListNodeToArray(listNode.next)
  555.             // );
  556.           returnedArray = [...returnedArray, ...ReverseListNodeToArray(listNode.next)];
  557.         }
  558.         returnedArray.push(listNode.val); // Add current node's value
  559.         return returnedArray;
  560.     }
  561.  
  562. // console.log( ReverseListNodeToArray(f(465) ));
  563. ============
  564.  
  565.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement