├── 001-two-sum ├── two-sum.js └── two-sum.py ├── 002-add-two-numbers ├── add-two-numbers.js └── add-two-numbers.py ├── 003-longest-substring-without-repeating-characters ├── longest-substring-without-repeating-characters.js └── longest-substring-without-repeating-characters.py ├── 004-median-of-two-sorted-arrays └── median-of-two-sorted-arrays.py ├── 005-longest-palindromic-substring ├── longest-palindromic-substring.js └── longest-palindromic-substring.py ├── 006-zigzag-conversion ├── zigzag-conversion.js └── zigzag-conversion.py ├── 007-reverse-integer └── reverse-integer.py ├── 008-string-to-integer-atoi └── string-to-integer-atoi.py ├── 009-palindrome-number ├── palindrome-number.js └── palindrome-number.py ├── 010-regular-expression-matching └── regular-expression-matching.py ├── 011-container-with-most-water └── container-with-most-water.py ├── 012-integer-to-roman └── integer-to-roman.py ├── 013-roman-to-integer ├── roman-to-integer.js └── roman-to-integer.py ├── 014-longest-common-prefix ├── longest-common-prefix.js └── longest-common-prefix.py ├── 015-3sum ├── 3sum.js └── 3sum.py ├── 016-3sum-closest └── 3sum-closest.py ├── 017-letter-combinations-of-a-phone-number └── letter-combinations-of-a-phone-number.py ├── 018-4sum └── 4sum.py ├── 019-remove-nth-node-from-end-of-list ├── remove-nth-node-from-end-of-list.js └── remove-nth-node-from-end-of-list.py ├── 020-valid-parentheses ├── valid-parentheses.js └── valid-parentheses.py ├── 021-merge-two-sorted-lists ├── merge-two-sorted-lists.js └── merge-two-sorted-lists.py ├── 022-generate-parentheses └── generate-parentheses.py ├── 023-merge-k-sorted-lists ├── merge-k-sorted-lists.js └── merge-k-sorted-lists.py ├── 024-swap-nodes-in-pairs ├── swap-nodes-in-pairs.js └── swap-nodes-in-pairs.py ├── 025-reverse-nodes-in-k-group └── reverse-nodes-in-k-group.js ├── 026-remove-duplicates-from-sorted-array ├── remove-duplicates-from-sorted-array.js └── remove-duplicates-from-sorted-array.py ├── 027-remove-element ├── remove-element.js └── remove-element.py ├── 028-implement-strstr ├── implement-strstr.js └── implement-strstr.py ├── 033-search-in-rotated-sorted-array └── search-in-rotated-sorted-array.js ├── 034-search-for-a-range ├── search-for-a-range.js └── search-for-a-range.py ├── 035-search-insert-position ├── search-insert-position.js └── search-insert-position.py ├── 038-count-and-say └── count-and-say.py ├── 039-combination-sum └── combination-sum.py ├── 041-first-missing-positive ├── first-missing-positive.js └── first-missing-positive.py ├── 049-anagrams └── anagrams.js ├── 050-powx-n ├── powx-n.js └── powx-n.py ├── 055-jump-game └── jump-game.js ├── 058-length-of-last-word └── length-of-last-word.js ├── 061-rotate-list └── rotate-list.js ├── 066-plus-one └── plus-one.js ├── 067-add-binary └── add-binary.js ├── 069-sqrtx └── sqrtx.js ├── 070-climbing-stairs └── climbing-stairs.js ├── 073-set-matrix-zeroes └── set-matrix-zeroes.js ├── 075-sort-colors └── sort-colors.js ├── 078-subsets └── subsets.js ├── 080-remove-duplicates-from-sorted-array-ii └── remove-duplicates-from-sorted-array-ii.js ├── 081-search-in-rotated-sorted-array-ii └── search-in-rotated-sorted-array-ii.js ├── 082-remove-duplicates-from-sorted-list-ii └── remove-duplicates-from-sorted-list-ii.js ├── 083-remove-duplicates-from-sorted-list └── remove-duplicates-from-sorted-list.js ├── 086-partition-list └── partition-list.js ├── 088-merge-sorted-array └── merge-sorted-array.js ├── 090-subsets-ii └── subsets-ii.js ├── 092-reverse-linked-list-ii └── reverse-linked-list-ii.js ├── 094-binary-tree-inorder-traversal └── binary-tree-inorder-traversal.js ├── 100-same-tree └── same-tree.js ├── 101-symmetric-tree └── symmetric-tree.js ├── 104-maximum-depth-of-binary-tree └── maximum-depth-of-binary-tree.js ├── 107-binary-tree-level-order-traversal-ii └── binary-tree-level-order-traversal-ii.py ├── 111-minimum-depth-of-binary-tree ├── minimum-depth-of-binary-tree.js └── minimum-depth-of-binary-tree.py ├── 118-pascals-triangle └── pascals-triangle.js ├── 119-pascals-triangle-ii └── pascals-triangle-ii.js ├── 121-best-time-to-buy-and-sell-stock └── best-time-to-buy-and-sell-stock.js ├── 122-best-time-to-buy-and-sell-stock-ii └── best-time-to-buy-and-sell-stock-ii.js ├── 125-valid-palindrome ├── valid-palindrome.js └── valid-palindrome.py ├── 128-longest-consecutive-sequence └── longest-consecutive-sequence.js ├── 136-single-number └── single-number.js ├── 137-single-number-ii └── single-number-ii.js ├── 141-linked-list-cycle └── linked-list-cycle.js ├── 142-linked-list-cycle-ii └── linked-list-cycle-ii.js ├── 143-reorder-list └── reorder-list.js ├── 144-binary-tree-preorder-traversal └── binary-tree-preorder-traversal.js ├── 145-binary-tree-postorder-traversal └── binary-tree-postorder-traversal.js ├── 147-insertion-sort-list └── insertion-sort-list.js ├── 150-evaluate-reverse-polish-notation └── evaluate-reverse-polish-notation.js ├── 151-reverse-words-in-a-string └── reverse-words-in-a-string.js ├── 152-maximum-product-subarray └── maximum-product-subarray.js ├── 153-find-minimum-in-rotated-sorted-array └── find-minimum-in-rotated-sorted-array.js ├── 154-find-minimum-in-rotated-sorted-array-ii └── find-minimum-in-rotated-sorted-array-ii.js ├── 160-intersection-of-two-linked-lists └── intersection-of-two-linked-lists.js ├── 162-find-peak-element └── find-peak-element.js ├── 167-two-sum-ii-input-array-is-sorted └── two-sum-ii-input-array-is-sorted.js ├── 168-excel-sheet-column-title └── excel-sheet-column-title.js ├── 169-majority-element └── majority-element.js ├── 171-excel-sheet-column-number └── excel-sheet-column-number.js ├── 172-factorial-trailing-zeroes └── factorial-trailing-zeroes.js ├── 189-rotate-array └── rotate-array.js ├── 190-reverse-bits └── reverse-bits.js ├── 198-house-robber └── house-robber.js ├── 202-happy-number └── happy-number.js ├── 203-remove-linked-list-elements └── remove-linked-list-elements.js ├── 204-count-primes └── count-primes.js ├── 205-isomorphic-strings └── isomorphic-strings.js ├── 206-reverse-linked-list └── reverse-linked-list.js ├── 217-contains-duplicate └── contains-duplicate.js ├── 219-contains-duplicate-ii └── contains-duplicate-ii.js ├── 223-rectangle-area └── rectangle-area.js ├── 225-implement-stack-using-queues └── implement-stack-using-queues.js ├── 226-invert-binary-tree └── invert-binary-tree.js ├── 227-basic-calculator-ii └── basic-calculator-ii.py ├── 228-summary-ranges └── summary-ranges.js ├── 229-majority-element-ii └── majority-element-ii.js ├── 231-power-of-two └── power-of-two.js ├── 232-implement-queue-using-stacks └── implement-queue-using-stacks.js ├── 234-palindrome-linked-list └── palindrome-linked-list.js ├── 235-lowest-common-ancestor-of-a-binary-search-tree └── lowest-common-ancestor-of-a-binary-search-tree.js ├── 237-delete-node-in-a-linked-list └── delete-node-in-a-linked-list.js ├── 238-product-of-array-except-self └── product-of-array-except-self.js ├── 240-search-a-2d-matrix-ii └── search-a-2d-matrix-ii.js ├── 242-valid-anagram └── valid-anagram.js ├── 258-add-digits └── add-digits.js ├── 260-single-number-iii └── single-number-iii.js ├── 263-ugly-number └── ugly-number.js ├── 268-missing-number └── missing-number.js ├── 278-first-bad-version └── first-bad-version.js ├── 283-move-zeroes └── move-zeroes.js ├── 287-find-the-duplicate-number └── find-the-duplicate-number.js ├── 290-word-pattern └── word-pattern.js ├── 292-nim-game └── nim-game.js ├── 299-bulls-and-cows └── bulls-and-cows.js ├── 303-range-sum-query-immutable └── range-sum-query-immutable.js ├── 319-bulb-switcher └── bulb-switcher.js ├── 326-power-of-three └── power-of-three.js ├── 328-odd-even-linked-list └── odd-even-linked-list.js ├── 338-counting-bits └── counting-bits.js ├── 342-power-of-four └── power-of-four.js ├── 344-reverse-string └── reverse-string.js ├── 345-reverse-vowels-of-a-string └── reverse-vowels-of-a-string.js ├── 347-top-k-frequent-elements └── top-k-frequent-elements.js ├── 349-intersection-of-two-arrays └── intersection-of-two-arrays.js ├── 350-intersection-of-two-arrays-ii └── intersection-of-two-arrays-ii.js ├── 371-sum-of-two-integers └── sum-of-two-integers.js ├── 383-ransom-note └── ransom-note.js ├── 387-first-unique-character-in-a-string └── first-unique-character-in-a-string.js ├── 389-find-the-difference └── find-the-difference.js ├── 396-rotate-function └── rotate-function.js ├── 400-nth-digit └── nth-digit.js ├── 404-sum-of-left-leaves └── sum-of-left-leaves.js ├── 405-convert-a-number-to-hexadecimal └── convert-a-number-to-hexadecimal.js ├── 409-longest-palindrome └── longest-palindrome.js ├── 412-fizz-buzz └── fizz-buzz.js ├── 414-third-maximum-number └── third-maximum-number.js ├── 415-add-strings └── add-strings.js ├── 420-strong-password-checker └── strong-password-checker.py ├── 441-arranging-coins └── arranging-coins.js ├── README.md ├── README_leetcode_generate.md ├── demo └── leetcode.gif ├── leetcode_generate.py └── old ├── 001-2sum.py ├── 002-add-two-numbers.py ├── 003-longest-substring-without-repeating-characters.py ├── 004-median-of-two-sorted-arrays.py ├── 005-longest-palindromic-substring.py ├── 006-zigzag-conversion.py ├── 007-reverse-integer.py ├── 008-string-to-integer-atoi.py ├── 009-palindrome-number.py ├── 010-regular-expression-matching.py ├── 011-Container-With-Most-Water.py ├── 012-Integer-to-Roman.py ├── 013-Roman-to-Integer.py ├── 014-longest-common-prefix.py ├── 015-3Sum.py ├── 016-3sum-closest.py ├── 017-letter-combinations-of-a-phone-number.py ├── 023-merge-k-sorted-lists.py ├── 024-swap-nodes-in-pairs.py ├── 025-remove-duplicates-from-sorted-array.py ├── 107-binary-tree-level-order-traversal-ii.py ├── 125-valid-palindrome.py └── 420-strong-password-checker.py /001-two-sum/two-sum.js: -------------------------------------------------------------------------------- 1 | // Given an array of integers, return indices of the two numbers such that they add up to a specific target. 2 | // 3 | // You may assume that each input would have exactly one solution. 4 | // 5 | // 6 | // Example: 7 | // 8 | // Given nums = [2, 7, 11, 15], target = 9, 9 | // 10 | // Because nums[0] + nums[1] = 2 + 7 = 9, 11 | // return [0, 1]. 12 | // 13 | // 14 | // 15 | // 16 | // UPDATE (2016/2/13): 17 | // The return format had been changed to zero-based indices. Please read the above updated description carefully. 18 | 19 | 20 | /** 21 | * @param {number[]} nums 22 | * @param {number} target 23 | * @return {number[]} 24 | */ 25 | var twoSum = function(nums, target) { 26 | const hmap = {} 27 | for (var idx=0; idx 4 -> 3) + (5 -> 6 -> 4) 4 | // Output: 7 -> 0 -> 8 5 | 6 | 7 | /** 8 | * Definition for singly-linked list. 9 | * function ListNode(val) { 10 | * this.val = val; 11 | * this.next = null; 12 | * } 13 | */ 14 | /** 15 | * @param {ListNode} l1 16 | * @param {ListNode} l2 17 | * @return {ListNode} 18 | */ 19 | var addTwoNumbers = function(l1, l2) { 20 | if (!l1) return l2; 21 | if (!l2) return l1; 22 | var l3 = new ListNode(0), fakeHead = l3, carry = 0, sum = 0; 23 | while (l1 || l2 || carry) { 24 | sum = (l1 ? l1.val : 0) + (l2 ? l2.val : 0) + carry; 25 | l3.next = new ListNode(sum % 10); 26 | carry = Math.floor(sum / 10); 27 | l3 = l3.next; l1 = l1 && l1.next; l2 = l2 && l2.next; 28 | } 29 | return fakeHead.next; 30 | }; 31 | -------------------------------------------------------------------------------- /002-add-two-numbers/add-two-numbers.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | 3 | 4 | # You are given two linked lists representing two non-negative numbers. 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. 5 | # 6 | # Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) 7 | # Output: 7 -> 0 -> 8 8 | 9 | 10 | # Definition for singly-linked list. 11 | 12 | # class ListNode(object): 13 | # def __init__(self, x): 14 | # self.val = x 15 | # self.next = None 16 | 17 | class Solution(object): 18 | def addTwoNumbers(self, l1, l2): 19 | """ 20 | :type l1: ListNode 21 | :type l2: ListNode 22 | :rtype: ListNode 23 | """ 24 | if(l1 is None and l2 is None): 25 | return None 26 | 27 | head = ListNode(0) 28 | point = head 29 | carry = 0 30 | while l1 is not None and l2 is not None: 31 | s = carry + l1.val + l2.val 32 | point.next = ListNode(s % 10) 33 | carry = s / 10 34 | l1 = l1.next 35 | l2 = l2.next 36 | point = point.next 37 | 38 | while l1 is not None: 39 | s = carry + l1.val 40 | point.next = ListNode(s % 10) 41 | carry = s / 10 42 | l1 = l1.next 43 | point = point.next 44 | 45 | while l2 is not None: 46 | s = carry + l2.val 47 | point.next = ListNode(s % 10) 48 | carry = s / 10 49 | l2 = l2.next 50 | point = point.next 51 | 52 | if carry != 0: 53 | point.next = ListNode(carry) 54 | 55 | return head.next 56 | 57 | 58 | 59 | 60 | -------------------------------------------------------------------------------- /003-longest-substring-without-repeating-characters/longest-substring-without-repeating-characters.js: -------------------------------------------------------------------------------- 1 | // Given a string, find the length of the longest substring without repeating characters. 2 | // 3 | // Examples: 4 | // 5 | // Given "abcabcbb", the answer is "abc", which the length is 3. 6 | // 7 | // Given "bbbbb", the answer is "b", with the length of 1. 8 | // 9 | // 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. 10 | 11 | 12 | /** 13 | * @param {string} s 14 | * @return {number} 15 | */ 16 | var lengthOfLongestSubstring = function(s) { 17 | var hashMap = {}; 18 | var i = j = 0; 19 | var n = s.length; 20 | var len = 0; 21 | while (i < n && j < n) { 22 | if (!hashMap[s[i]]) { 23 | hashMap[s[i++]] = true; 24 | len = Math.max(len, i - j); 25 | } else { 26 | hashMap[s[j++]] = false; 27 | } 28 | } 29 | return len; 30 | }; 31 | -------------------------------------------------------------------------------- /003-longest-substring-without-repeating-characters/longest-substring-without-repeating-characters.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | 3 | 4 | # Given a string, find the length of the longest substring without repeating characters. 5 | # 6 | # Examples: 7 | # 8 | # Given "abcabcbb", the answer is "abc", which the length is 3. 9 | # 10 | # Given "bbbbb", the answer is "b", with the length of 1. 11 | # 12 | # 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. 13 | 14 | 15 | class Solution(object): 16 | def lengthOfLongestSubstring(self, s): 17 | """ 18 | :type s: str 19 | :rtype: int 20 | """ 21 | 22 | longest, start, visited = 0, 0, [False for _ in range(256)] 23 | for ind, val in enumerate(s): 24 | if not visited[ord(val)]: 25 | visited[ord(val)] = True 26 | else: 27 | while val != s[start]: 28 | visited[ord(s[start])] = False 29 | start += 1 30 | start += 1 31 | longest = max(longest, ind - start + 1) 32 | return longest 33 | 34 | -------------------------------------------------------------------------------- /004-median-of-two-sorted-arrays/median-of-two-sorted-arrays.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | 3 | 4 | # There are two sorted arrays nums1 and nums2 of size m and n respectively. 5 | # 6 | # Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)). 7 | # 8 | # Example 1: 9 | # 10 | # nums1 = [1, 3] 11 | # nums2 = [2] 12 | # 13 | # The median is 2.0 14 | # 15 | # 16 | # 17 | # Example 2: 18 | # 19 | # nums1 = [1, 2] 20 | # nums2 = [3, 4] 21 | # 22 | # The median is (2 + 3)/2 = 2.5 23 | 24 | 25 | class Solution(object): 26 | def findMedianSortedArrays(self, nums1, nums2): 27 | """ 28 | :type nums1: List[int] 29 | :type nums2: List[int] 30 | :rtype: float 31 | """ 32 | nums = sorted(nums1 + nums2) 33 | t_len = len(nums) 34 | if t_len == 1: 35 | return nums[0] 36 | 37 | if t_len % 2: 38 | return nums[t_len/2] 39 | else: 40 | return (nums[t_len/2] + nums[t_len/2 -1]) /2.0 41 | -------------------------------------------------------------------------------- /005-longest-palindromic-substring/longest-palindromic-substring.js: -------------------------------------------------------------------------------- 1 | // Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000. 2 | // 3 | // Example: 4 | // 5 | // Input: "babad" 6 | // 7 | // Output: "bab" 8 | // 9 | // Note: "aba" is also a valid answer. 10 | // 11 | // 12 | // 13 | // Example: 14 | // 15 | // Input: "cbbd" 16 | // 17 | // Output: "bb" 18 | 19 | 20 | /** 21 | * @param {string} s 22 | * @return {string} 23 | */ 24 | var longestPalindrome = function(s) { 25 | var a = s.split(''),left, right, 26 | size = a.length, 27 | max = Number.MIN_VALUE, 28 | start = 0; 29 | 30 | for(var i = 0; i < size; i = i + 0.5){ 31 | left = Math.ceil(i - 1); 32 | right = Math.floor(i + 1); 33 | while(left >=0 && right < size) { 34 | if (a[left] === a[right]){ 35 | left--; 36 | right++; 37 | } else { break;} 38 | } 39 | if (right - left - 1 > max){ 40 | max = right - left - 1; 41 | start = left + 1; 42 | } 43 | } 44 | 45 | return s.slice(start, start + max); 46 | }; 47 | -------------------------------------------------------------------------------- /005-longest-palindromic-substring/longest-palindromic-substring.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | 3 | 4 | # Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000. 5 | # 6 | # Example: 7 | # 8 | # Input: "babad" 9 | # 10 | # Output: "bab" 11 | # 12 | # Note: "aba" is also a valid answer. 13 | # 14 | # 15 | # 16 | # Example: 17 | # 18 | # Input: "cbbd" 19 | # 20 | # Output: "bb" 21 | 22 | 23 | class Solution(object): 24 | def longestPalindrome(self, s): 25 | """ 26 | :type s: str 27 | :rtype: str 28 | """ 29 | longest, mid = "", (len(s) - 1) / 2 30 | i, j = mid, mid 31 | while i >= 0 and j < len(s): 32 | args = [(s, i, i), (s, i, i + 1), (s, j, j), (s, j, j + 1)] 33 | for arg in args: 34 | tmp = self.longestPalindromeByAxis(*arg) 35 | if len(tmp) > len(longest): 36 | longest = tmp 37 | if len(longest) >= i * 2: 38 | if len(longest) == 1: 39 | return s[0] 40 | return longest 41 | i, j = i - 1, j + 1 42 | return longest 43 | 44 | def longestPalindromeByAxis(self, s, left, right): 45 | while left >= 0 and right < len(s) and s[left] == s[right]: 46 | left, right = left - 1, right + 1 47 | return s[left + 1: right] 48 | -------------------------------------------------------------------------------- /006-zigzag-conversion/zigzag-conversion.js: -------------------------------------------------------------------------------- 1 | // The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) 2 | // 3 | // P A H N 4 | // A P L S I I G 5 | // Y I R 6 | // 7 | // 8 | // And then read line by line: "PAHNAPLSIIGYIR" 9 | // 10 | // 11 | // Write the code that will take a string and make this conversion given a number of rows: 12 | // 13 | // string convert(string text, int nRows); 14 | // 15 | // convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR". 16 | 17 | 18 | /** 19 | * @param {string} s 20 | * @param {number} numRows 21 | * @return {string} 22 | */ 23 | var convert = function(s, numRows) { 24 | if (numRows < 2) { 25 | return s; 26 | } 27 | var matrix = []; 28 | for (var i = 0; i < numRows; i++) { 29 | matrix.push([]); 30 | } 31 | var k = 0; 32 | i = 0; 33 | var res = ''; 34 | while (k < s.length) { 35 | while(i < matrix.length && k < s.length) { 36 | matrix[i].push(s[k]); 37 | // down 38 | i++; 39 | k++; 40 | } 41 | i = i-2; 42 | while (i >= 0 && k < s.length) { 43 | matrix[i].push(s[k]); 44 | // up 45 | i--; 46 | k++; 47 | } 48 | i = i+2; 49 | } 50 | for (var i = 0; i < matrix.length; i++) { 51 | for (var k = 0; k < matrix[i].length; k++) { 52 | res += matrix[i][k]; 53 | } 54 | } 55 | return res; 56 | }; 57 | -------------------------------------------------------------------------------- /006-zigzag-conversion/zigzag-conversion.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | 3 | 4 | # The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) 5 | # 6 | # P A H N 7 | # A P L S I I G 8 | # Y I R 9 | # 10 | # 11 | # And then read line by line: "PAHNAPLSIIGYIR" 12 | # 13 | # 14 | # Write the code that will take a string and make this conversion given a number of rows: 15 | # 16 | # string convert(string text, int nRows); 17 | # 18 | # convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR". 19 | 20 | 21 | class Solution(object): 22 | def convert(self, s, numRows): 23 | """ 24 | :type s: str 25 | :type numRows: int 26 | :rtype: str 27 | """ 28 | if not s or len(s) == 0 or numRows <= 0: 29 | return "" 30 | if numRows == 1: 31 | return s 32 | if len(s) % (numRows + numRows - 2): 33 | s = s + '#' * (numRows + numRows - 2 - (len(s) % (numRows + numRows - 2))) 34 | blocks = len(s)/(numRows + numRows - 2) 35 | res = '' 36 | for i in range(numRows): 37 | for j in range(blocks): 38 | if i == 0 or i == numRows-1: 39 | res += s[i + j*(numRows + numRows - 2)] 40 | else: 41 | res += s[i + j*(numRows + numRows - 2)] 42 | res += s[2*numRows-2-i + j*(numRows + numRows - 2)] 43 | return ''.join(res.split('#')) 44 | 45 | -------------------------------------------------------------------------------- /007-reverse-integer/reverse-integer.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | 3 | 4 | # Reverse digits of an integer. 5 | # 6 | # 7 | # Example1: x = 123, return 321 8 | # Example2: x = -123, return -321 9 | # 10 | # 11 | # click to show spoilers. 12 | # 13 | # Have you thought about this? 14 | # 15 | # Here are some good questions to ask before coding. Bonus points for you if you have already thought through this! 16 | # 17 | # If the integer's last digit is 0, what should the output be? ie, cases such as 10, 100. 18 | # 19 | # Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases? 20 | # 21 | # For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows. 22 | # 23 | # 24 | # Update (2014-11-10): 25 | # Test cases had been added to test the overflow behavior. 26 | 27 | 28 | class Solution(object): 29 | def reverse(self, x): 30 | """ 31 | :type x: int 32 | :rtype: int 33 | """ 34 | l = list(str(abs(x))) 35 | l.reverse() 36 | rst = int(''.join(l)) 37 | if rst > 2147483647: 38 | return 0 39 | else: 40 | return rst if x>=0 else rst * (-1) 41 | 42 | 43 | -------------------------------------------------------------------------------- /009-palindrome-number/palindrome-number.js: -------------------------------------------------------------------------------- 1 | // Determine whether an integer is a palindrome. Do this without extra space. 2 | // 3 | // click to show spoilers. 4 | // 5 | // Some hints: 6 | // 7 | // Could negative integers be palindromes? (ie, -1) 8 | // 9 | // If you are thinking of converting the integer to string, note the restriction of using extra space. 10 | // 11 | // You could also try reversing an integer. However, if you have solved the problem "Reverse Integer", you know that the reversed integer might overflow. How would you handle such case? 12 | // 13 | // There is a more generic way of solving this problem. 14 | 15 | 16 | /** 17 | * @param {number} x 18 | * @return {boolean} 19 | */ 20 | var isPalindrome = function(x) { 21 | const INT_MAX = 2147483647; 22 | const INT_MIN = -2147483648; 23 | 24 | if (x < INT_MIN || x > INT_MAX) return false; 25 | if (x < 0) return false; 26 | if (x === 0) return true; 27 | var duplicate = x; 28 | var reverse = 0; 29 | while(x !== 0) { 30 | reverse = reverse * 10 + x % 10; 31 | x = Math.floor(x / 10); 32 | } 33 | if (duplicate === reverse) return true; 34 | return false; 35 | }; 36 | -------------------------------------------------------------------------------- /009-palindrome-number/palindrome-number.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | 3 | 4 | # Determine whether an integer is a palindrome. Do this without extra space. 5 | # 6 | # click to show spoilers. 7 | # 8 | # Some hints: 9 | # 10 | # Could negative integers be palindromes? (ie, -1) 11 | # 12 | # If you are thinking of converting the integer to string, note the restriction of using extra space. 13 | # 14 | # You could also try reversing an integer. However, if you have solved the problem "Reverse Integer", you know that the reversed integer might overflow. How would you handle such case? 15 | # 16 | # There is a more generic way of solving this problem. 17 | 18 | 19 | class Solution(object): 20 | def isPalindrome(self, x): 21 | """ 22 | :type x: int 23 | :rtype: bool 24 | """ 25 | if x < 0: 26 | return False 27 | x = abs(x) 28 | l = len(str(x)) 29 | i = 1 30 | while i < l / 2 + 1: 31 | 32 | head = (x / 10 ** (l-i)) % 10 33 | tail = (x % 10 ** i) if i == 1 else (x % 10 ** i) / (10 ** (i-1)) 34 | if head != tail: 35 | return False 36 | i = i + 1 37 | 38 | return True 39 | -------------------------------------------------------------------------------- /010-regular-expression-matching/regular-expression-matching.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | 3 | 4 | # Implement regular expression matching with support for '.' and '*'. 5 | # 6 | # 7 | # '.' Matches any single character. 8 | # '*' Matches zero or more of the preceding element. 9 | # 10 | # The matching should cover the entire input string (not partial). 11 | # 12 | # The function prototype should be: 13 | # bool isMatch(const char *s, const char *p) 14 | # 15 | # Some examples: 16 | # isMatch("aa","a") → false 17 | # isMatch("aa","aa") → true 18 | # isMatch("aaa","aa") → false 19 | # isMatch("aa", "a*") → true 20 | # isMatch("aa", ".*") → true 21 | # isMatch("ab", ".*") → true 22 | # isMatch("aab", "c*a*b") → true 23 | 24 | 25 | class Solution(object): 26 | def isMatch(self, s, p): 27 | """ 28 | :type s: str 29 | :type p: str 30 | :rtype: bool 31 | """ 32 | result = [[False for j in xrange(len(p) + 1)] for i in xrange(len(s) + 1)] 33 | 34 | result[0][0] = True 35 | for i in xrange(2, len(p) + 1): 36 | if p[i-1] == '*': 37 | result[0][i] = result[0][i-2] 38 | 39 | for i in xrange(1,len(s) + 1): 40 | for j in xrange(1, len(p) + 1): 41 | if p[j-1] != '*': 42 | result[i][j] = result[i-1][j-1] and (s[i-1] == p[j-1] or p[j-1] == '.') 43 | else: 44 | result[i][j] = result[i][j-2] or (result[i-1][j] and (s[i-1] == p[j-2] or p[j-2] == '.')) 45 | 46 | return result[len(s)][len(p)] 47 | -------------------------------------------------------------------------------- /011-container-with-most-water/container-with-most-water.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | 3 | 4 | # 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. 5 | # 6 | # Note: You may not slant the container. 7 | 8 | 9 | class Solution(object): 10 | def maxArea(self, height): 11 | """ 12 | :type height: List[int] 13 | :rtype: int 14 | """ 15 | max_area, i, j = 0, 0, len(height) - 1 16 | while i < j: 17 | max_area = max(max_area, min(height[i], height[j]) * (j - i)) 18 | if height[i] < height[j]: 19 | i += 1 20 | else: 21 | j -= 1 22 | return max_area 23 | 24 | -------------------------------------------------------------------------------- /012-integer-to-roman/integer-to-roman.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | 3 | 4 | # Given an integer, convert it to a roman numeral. 5 | # 6 | # 7 | # Input is guaranteed to be within the range from 1 to 3999. 8 | 9 | 10 | class Solution(object): 11 | def intToRoman(self, num): 12 | """ 13 | :type num: int 14 | :rtype: str 15 | """ 16 | int2roman = { 17 | 1: "I", 18 | 4: "IV", 19 | 5: "V", 20 | 9: "IX", 21 | 22 | 10: "X", 23 | 40: "XL", 24 | 50: "L", 25 | 90: "XC", 26 | 27 | 100: "C", 28 | 400: "CD", 29 | 500: "D", 30 | 900: "CM", 31 | 32 | 1000: "M" 33 | } 34 | 35 | builder = [] 36 | components = [1, 4, 5, 9, 10, 10, 40, 50, 90, 100, 400, 500, 900, 1000] 37 | for item in reversed(components): 38 | while num >= item: 39 | builder.append(int2roman[item]) 40 | num -= item 41 | return "".join(builder) 42 | -------------------------------------------------------------------------------- /013-roman-to-integer/roman-to-integer.js: -------------------------------------------------------------------------------- 1 | // Given a roman numeral, convert it to an integer. 2 | // 3 | // Input is guaranteed to be within the range from 1 to 3999. 4 | 5 | 6 | /** 7 | * @param {string} s 8 | * @return {number} 9 | */ 10 | var romanToInt = function(s) { 11 | var hash = { 12 | 'I': 1, 13 | 'V': 5, 14 | 'X': 10, 15 | 'L': 50, 16 | 'C': 100, 17 | 'D': 500, 18 | 'M': 1000 19 | }; 20 | var lastChar = hash[s.charAt(0)]; 21 | var r = 0; 22 | for (var i = 0, l = s.length; i <= l - 1; ++i) { 23 | var currentChar = hash[s.charAt(i)]; 24 | if (lastChar < currentChar) { 25 | //需要相减 26 | r += currentChar - lastChar - lastChar; 27 | } else { 28 | //直接相加 29 | r += currentChar; 30 | } 31 | lastChar = currentChar; 32 | } 33 | return r; 34 | }; 35 | -------------------------------------------------------------------------------- /013-roman-to-integer/roman-to-integer.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | 3 | 4 | # Given a roman numeral, convert it to an integer. 5 | # 6 | # Input is guaranteed to be within the range from 1 to 3999. 7 | 8 | 9 | class Solution(object): 10 | def romanToInt(self, s): 11 | """ 12 | :type s: str 13 | :rtype: int 14 | """ 15 | roman = {"I":1, "V":5, "X":10, "L":50, "C":100, "D":500, "M":1000} 16 | total = 0 17 | for index in range(len(s)-1): 18 | type = 1 if roman[s[index]]>=roman[s[index+1]] else -1 19 | total += type*roman[s[index]] 20 | return total + roman[s[len(s)-1]] 21 | -------------------------------------------------------------------------------- /014-longest-common-prefix/longest-common-prefix.js: -------------------------------------------------------------------------------- 1 | // Write a function to find the longest common prefix string amongst an array of strings. 2 | 3 | 4 | /** 5 | * @param {string[]} strs 6 | * @return {string} 7 | */ 8 | var longestCommonPrefix = function(strs) { 9 | if (strs.length <= 0) return ''; 10 | return strs.reduce(function (prev, next) { 11 | let i = 0; 12 | while (prev[i] && next[i] && prev[i] === next[i]) i++; 13 | return prev.slice(0, i); 14 | }); 15 | }; 16 | -------------------------------------------------------------------------------- /014-longest-common-prefix/longest-common-prefix.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | 3 | 4 | # Write a function to find the longest common prefix string amongst an array of strings. 5 | 6 | 7 | class Solution(object): 8 | def longestCommonPrefix(self, strs): 9 | """ 10 | :type strs: List[str] 11 | :rtype: str 12 | """ 13 | if not strs: 14 | return "" 15 | if len(strs) == 1: 16 | return strs[0] 17 | 18 | p = strs[0] 19 | idx, rest = 0, strs[1:] 20 | while len(p) > 0: 21 | while idx < len(rest) and len(p) <= len(rest[idx]) and p == rest[idx][:len(p)]: 22 | idx += 1 23 | if idx == len(rest): 24 | return p 25 | p = p[:-1] 26 | return "" 27 | 28 | -------------------------------------------------------------------------------- /015-3sum/3sum.js: -------------------------------------------------------------------------------- 1 | // Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero. 2 | // 3 | // Note: The solution set must not contain duplicate triplets. 4 | // 5 | // 6 | // For example, given array S = [-1, 0, 1, 2, -1, -4], 7 | // 8 | // A solution set is: 9 | // [ 10 | // [-1, 0, 1], 11 | // [-1, -1, 2] 12 | // ] 13 | 14 | 15 | var threeSum = function(nums) { 16 | var result = []; 17 | var hashMap = {}; 18 | nums.sort(function (prev, curr) { 19 | if (prev >= curr) return 1; 20 | return -1; 21 | }); 22 | var before = 0; 23 | var len = nums.length; 24 | 25 | for (; before <= len - 2; ++before) { 26 | if (before > 0 && nums[before] === nums[before - 1]) { 27 | continue; 28 | } 29 | var a = nums[before]; 30 | var start = before + 1; 31 | var end = len - 1; 32 | while (start < end) { 33 | if (start > before + 1 && nums[start - 1] === nums[start]) { 34 | start++; 35 | continue; 36 | } 37 | if (end < len - 1 && nums[end + 1] === nums[end]) { 38 | end--; 39 | continue; 40 | } 41 | var b = nums[start]; 42 | var c = nums[end]; 43 | if (a + b + c === 0) { 44 | result.push([a, b, c]); 45 | end--; 46 | } else if (a + b + c > 0) { 47 | end--; 48 | } else { 49 | start++; 50 | } 51 | } 52 | } 53 | return result; 54 | }; 55 | -------------------------------------------------------------------------------- /015-3sum/3sum.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | 3 | 4 | # Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero. 5 | # 6 | # Note: The solution set must not contain duplicate triplets. 7 | # 8 | # 9 | # For example, given array S = [-1, 0, 1, 2, -1, -4], 10 | # 11 | # A solution set is: 12 | # [ 13 | # [-1, 0, 1], 14 | # [-1, -1, 2] 15 | # ] 16 | 17 | 18 | class Solution(object): 19 | def threeSum(self, nums): 20 | """ 21 | :type nums: List[int] 22 | :rtype: List[List[int]] 23 | """ 24 | nums.sort() 25 | res = [] 26 | 27 | for i in range(len(nums)-1): # because sums of 3 numbers 28 | if i == 0 or i > 0 and nums[i-1] != nums[i]: 29 | # avoid duplicate triplets [1 ,1, 1, -2] 30 | left = i + 1 31 | right = len(nums) - 1 32 | while left < right: # two-way pointer 33 | s = nums[i] + nums[left] + nums[right] 34 | if s == 0: 35 | res.append([nums[i], nums[left], nums[right]]) 36 | left += 1 37 | right -= 1 38 | while left < right and nums[left] == nums[left - 1]: 39 | left += 1 40 | while right > left and nums[right] == nums[right + 1]: 41 | right -= 1 42 | elif s < 0: 43 | left += 1 44 | else: 45 | right -= 1 46 | return res 47 | -------------------------------------------------------------------------------- /016-3sum-closest/3sum-closest.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | 3 | 4 | # Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution. 5 | # 6 | # 7 | # For example, given array S = {-1 2 1 -4}, and target = 1. 8 | # 9 | # The sum that is closest to the target is 2. (-1 + 2 + 1 = 2). 10 | 11 | 12 | class Solution(object): 13 | def threeSumClosest(self, nums, target): 14 | """ 15 | :type nums: List[int] 16 | :type target: int 17 | :rtype: int 18 | """ 19 | nums.sort() 20 | result = sum(nums[:3]) 21 | for i in range(len(nums) - 2): 22 | j, k = i+1, len(nums) - 1 23 | while j < k: 24 | s = nums[i] + nums[j] + nums[k] 25 | if s == target: 26 | return s 27 | 28 | if abs(s - target) < abs(result - target): 29 | result = s 30 | 31 | if s < target: 32 | j += 1 33 | elif s > target: 34 | k -= 1 35 | return result 36 | -------------------------------------------------------------------------------- /017-letter-combinations-of-a-phone-number/letter-combinations-of-a-phone-number.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | 3 | 4 | # Given a digit string, return all possible letter combinations that the number could represent. 5 | # 6 | # 7 | # 8 | # A mapping of digit to letters (just like on the telephone buttons) is given below. 9 | # 10 | # 11 | # 12 | # Input:Digit string "23" 13 | # Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]. 14 | # 15 | # 16 | # 17 | # Note: 18 | # Although the above answer is in lexicographical order, your answer could be in any order you want. 19 | 20 | 21 | class Solution(object): 22 | def letterCombinations(self, digits): 23 | """ 24 | :type digits: str 25 | :rtype: List[str] 26 | """ 27 | l = ['', '', 'abc', 'def', 'ghi', 'jkl', 'mno', 'pqrs', 'tuv', 'wxyz'] 28 | end = [''] 29 | rst = [] 30 | d = digits 31 | 32 | while len(d): 33 | f = int(d[-1]) 34 | lst_f = list(l[f]) 35 | rst = [''.join([i, j]) for i in lst_f for j in end] 36 | end = rst 37 | d = d[:-1] 38 | return rst 39 | 40 | -------------------------------------------------------------------------------- /018-4sum/4sum.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | 3 | 4 | # Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target. 5 | # 6 | # Note: The solution set must not contain duplicate quadruplets. 7 | # 8 | # 9 | # 10 | # For example, given array S = [1, 0, -1, 0, -2, 2], and target = 0. 11 | # 12 | # A solution set is: 13 | # [ 14 | # [-1, 0, 0, 1], 15 | # [-2, -1, 1, 2], 16 | # [-2, 0, 0, 2] 17 | # ] 18 | 19 | 20 | class Solution(object): 21 | def fourSum(self, nums, target): 22 | """ 23 | :type nums: List[int] 24 | :type target: int 25 | :rtype: List[List[int]] 26 | """ 27 | def findNsum(nums, target, N, result, results): 28 | if len(nums) < N or N < 2 or target < nums[0]*N or target > nums[-1]*N: # early termination 29 | return 30 | if N == 2: # two pointers solve sorted 2-sum problem 31 | l,r = 0,len(nums)-1 32 | while l < r: 33 | s = nums[l] + nums[r] 34 | if s == target: 35 | results.append(result + [nums[l], nums[r]]) 36 | l += 1 37 | while l < r and nums[l] == nums[l-1]: 38 | l += 1 39 | elif s < target: 40 | l += 1 41 | else: 42 | r -= 1 43 | else: # recursively reduce N 44 | for i in range(len(nums)-N+1): 45 | if i == 0 or (i > 0 and nums[i-1] != nums[i]): 46 | findNsum(nums[i+1:], target-nums[i], N-1, result+[nums[i]], results) 47 | 48 | results = [] 49 | findNsum(sorted(nums), target, 4, [], results) 50 | return results 51 | -------------------------------------------------------------------------------- /019-remove-nth-node-from-end-of-list/remove-nth-node-from-end-of-list.js: -------------------------------------------------------------------------------- 1 | // Given a linked list, remove the nth node from the end of list and return its head. 2 | // 3 | // 4 | // For example, 5 | // 6 | // 7 | // Given linked list: 1->2->3->4->5, and n = 2. 8 | // 9 | // After removing the second node from the end, the linked list becomes 1->2->3->5. 10 | // 11 | // 12 | // 13 | // Note: 14 | // Given n will always be valid. 15 | // Try to do this in one pass. 16 | 17 | 18 | /** 19 | * Definition for singly-linked list. 20 | * function ListNode(val) { 21 | * this.val = val; 22 | * this.next = null; 23 | * } 24 | */ 25 | /** 26 | * @param {ListNode} head 27 | * @param {number} n 28 | * @return {ListNode} 29 | */ 30 | var removeNthFromEnd = function (head, n) { 31 | function f(x) { 32 | if (x === null) 33 | return 0; 34 | var t = x.next; 35 | var tn = f(t); 36 | if (tn === n) 37 | x.next = t.next; 38 | 39 | return tn + 1; 40 | } 41 | if (f(head) === n) 42 | head = head.next; 43 | return head; 44 | }; 45 | -------------------------------------------------------------------------------- /019-remove-nth-node-from-end-of-list/remove-nth-node-from-end-of-list.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | 3 | 4 | # Given a linked list, remove the nth node from the end of list and return its head. 5 | # 6 | # 7 | # For example, 8 | # 9 | # 10 | # Given linked list: 1->2->3->4->5, and n = 2. 11 | # 12 | # After removing the second node from the end, the linked list becomes 1->2->3->5. 13 | # 14 | # 15 | # 16 | # Note: 17 | # Given n will always be valid. 18 | # Try to do this in one pass. 19 | 20 | 21 | # Definition for singly-linked list. 22 | # class ListNode(object): 23 | # def __init__(self, x): 24 | # self.val = x 25 | # self.next = None 26 | 27 | class Solution(object): 28 | def removeNthFromEnd(self, head, n): 29 | """ 30 | :type head: ListNode 31 | :type n: int 32 | :rtype: ListNode 33 | """ 34 | dummy = ListNode(0) 35 | dummy.next = head 36 | fast = slow = dummy 37 | 38 | while n: 39 | fast = fast.next 40 | n = n-1 41 | 42 | while fast.next: 43 | fast = fast.next 44 | slow = slow.next 45 | slow.next = slow.next.next 46 | return dummy.next 47 | 48 | -------------------------------------------------------------------------------- /020-valid-parentheses/valid-parentheses.js: -------------------------------------------------------------------------------- 1 | // Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. 2 | // 3 | // The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not. 4 | 5 | 6 | /** 7 | * @param {string} s 8 | * @return {boolean} 9 | */ 10 | var map = { 11 | "(": ")", 12 | "[": "]", 13 | "{": "}" 14 | } 15 | 16 | var isValid = function(s) { 17 | var stack = []; 18 | 19 | for (var i = 0; i < s.length; i++) { 20 | var el = s[i]; 21 | 22 | if (map[el]) { 23 | stack.push(map[el]); 24 | } else { 25 | if (el !== stack.pop()) { 26 | return false; 27 | } 28 | } 29 | } 30 | 31 | return stack.length === 0; 32 | }; 33 | 34 | -------------------------------------------------------------------------------- /020-valid-parentheses/valid-parentheses.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | 3 | 4 | # Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. 5 | # 6 | # The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not. 7 | 8 | 9 | class Solution(object): 10 | def isValid(self, s): 11 | """ 12 | :type s: str 13 | :rtype: bool 14 | """ 15 | pattern = { 16 | '(': ')', 17 | '{': '}', 18 | '[': ']' 19 | } 20 | lst = [] 21 | end = None 22 | for item in s: 23 | if item in list(pattern.keys()): 24 | lst.append(item) 25 | end = item 26 | # elif end == None: # 起手是value 的情况 27 | # return False 28 | elif end and pattern[end] == item: 29 | lst.pop() 30 | end = lst[-1] if lst else None 31 | else: 32 | return False 33 | return len(lst)==0 34 | -------------------------------------------------------------------------------- /021-merge-two-sorted-lists/merge-two-sorted-lists.js: -------------------------------------------------------------------------------- 1 | // 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. 2 | 3 | 4 | /** 5 | * Definition for singly-linked list. 6 | * function ListNode(val) { 7 | * this.val = val; 8 | * this.next = null; 9 | * } 10 | */ 11 | /** 12 | * @param {ListNode} l1 13 | * @param {ListNode} l2 14 | * @return {ListNode} 15 | */ 16 | var mergeTwoLists = function(l1, l2) { 17 | var res = new ListNode(-1); 18 | var temp = res; 19 | while(l1 && l2) { 20 | if (l1.val < l2.val) { 21 | res.next = l1; 22 | l1 = l1.next; 23 | } else { 24 | res.next = l2; 25 | l2 = l2.next; 26 | } 27 | res = res.next; 28 | } 29 | if (l1) { 30 | res.next = l1; 31 | } 32 | if (l2) { 33 | res.next = l2; 34 | } 35 | return temp.next; 36 | }; 37 | -------------------------------------------------------------------------------- /021-merge-two-sorted-lists/merge-two-sorted-lists.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | 3 | 4 | # 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. 5 | 6 | 7 | # Definition for singly-linked list. 8 | # class ListNode(object): 9 | # def __init__(self, x): 10 | # self.val = x 11 | # self.next = None 12 | 13 | class Solution(object): 14 | def mergeTwoLists(self, l1, l2): 15 | """ 16 | :type l1: ListNode 17 | :type l2: ListNode 18 | :rtype: ListNode 19 | """ 20 | h = tail = ListNode(0) 21 | while l1 and l2: 22 | if l1.val <= l2.val: 23 | tail.next = l1 24 | l1 = l1.next 25 | else: 26 | tail.next = l2 27 | l2 = l2.next 28 | tail = tail.next 29 | 30 | tail.next = l1 or l2 31 | return h.next 32 | -------------------------------------------------------------------------------- /022-generate-parentheses/generate-parentheses.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | 3 | 4 | # Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. 5 | # 6 | # 7 | # 8 | # For example, given n = 3, a solution set is: 9 | # 10 | # 11 | # [ 12 | # "((()))", 13 | # "(()())", 14 | # "(())()", 15 | # "()(())", 16 | # "()()()" 17 | # ] 18 | 19 | 20 | class Solution(object): 21 | def generateParenthesis(self, n): 22 | """ 23 | :type n: int 24 | :rtype: List[str] 25 | """ 26 | lst = [] 27 | def generate(cur, left, right): 28 | 29 | if left > right: 30 | return 31 | if left == 0 and right == 0: 32 | lst.append(cur) 33 | return 34 | if left > 0: 35 | generate(cur + '(', left - 1, right) 36 | if right > 0: 37 | generate(cur + ')', left, right - 1) 38 | generate('', n, n) 39 | return lst 40 | 41 | 42 | -------------------------------------------------------------------------------- /023-merge-k-sorted-lists/merge-k-sorted-lists.js: -------------------------------------------------------------------------------- 1 | // Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity. 2 | 3 | 4 | /** 5 | * Definition for singly-linked list. 6 | * function ListNode(val) { 7 | * this.val = val; 8 | * this.next = null; 9 | * } 10 | */ 11 | /** 12 | * @param {ListNode[]} lists 13 | * @return {ListNode} 14 | */ 15 | var mergeTwoLists = function(l1, l2) { 16 | if (!l1) return l2; 17 | if (!l2) return l1; 18 | var res = new ListNode(-1); 19 | var temp = res; 20 | while(l1 && l2) { 21 | if (l1.val < l2.val) { 22 | res.next = l1; 23 | l1 = l1.next; 24 | } else { 25 | res.next = l2; 26 | l2 = l2.next; 27 | } 28 | res = res.next; 29 | } 30 | if (l1) res.next = l1; 31 | if (l2) res.next = l2; 32 | return temp.next; 33 | }; 34 | var mergeKLists = function(lists) { 35 | var result = lists[0] || null; 36 | for (var i = 1, l = lists.length; i < l; i++) { 37 | result = mergeTwoLists(result, lists[i]); 38 | } 39 | return result; 40 | }; 41 | -------------------------------------------------------------------------------- /023-merge-k-sorted-lists/merge-k-sorted-lists.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | 3 | 4 | # Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity. 5 | 6 | 7 | # Definition for singly-linked list. 8 | # class ListNode(object): 9 | # def __init__(self, x): 10 | # self.val = x 11 | # self.next = None 12 | 13 | class Solution(object): 14 | def mergeKLists(self, lists): 15 | 16 | if not lists: 17 | return None 18 | 19 | dummyNode = cur = ListNode(0) 20 | minHeap = [(l.val, l) for l in lists if l] 21 | heapq.heapify(minHeap) 22 | 23 | while minHeap: 24 | cur.next = heapq.heappop(minHeap)[1] 25 | cur = cur.next 26 | 27 | if cur.next: 28 | heapq.heappush(minHeap, (cur.next.val, cur.next)) 29 | 30 | return dummyNode.next 31 | -------------------------------------------------------------------------------- /024-swap-nodes-in-pairs/swap-nodes-in-pairs.js: -------------------------------------------------------------------------------- 1 | // Given a linked list, swap every two adjacent nodes and return its head. 2 | // 3 | // 4 | // 5 | // For example, 6 | // Given 1->2->3->4, you should return the list as 2->1->4->3. 7 | // 8 | // 9 | // 10 | // Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed. 11 | 12 | 13 | /** 14 | * Definition for singly-linked list. 15 | * function ListNode(val) { 16 | * this.val = val; 17 | * this.next = null; 18 | * } 19 | */ 20 | /** 21 | * @param {ListNode} head 22 | * @return {ListNode} 23 | */ 24 | 25 | var swapPairs = function(head) { 26 | if(head != null && head.next != null){ 27 | var temp = head.next.next; 28 | var next = head.next; 29 | next.next = head; 30 | head.next = arguments.callee(temp); 31 | 32 | return next; 33 | } 34 | return head; 35 | }; 36 | -------------------------------------------------------------------------------- /024-swap-nodes-in-pairs/swap-nodes-in-pairs.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | 3 | 4 | # Given a linked list, swap every two adjacent nodes and return its head. 5 | # 6 | # 7 | # 8 | # For example, 9 | # Given 1->2->3->4, you should return the list as 2->1->4->3. 10 | # 11 | # 12 | # 13 | # Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed. 14 | 15 | 16 | # Definition for singly-linked list. 17 | # class ListNode(object): 18 | # def __init__(self, x): 19 | # self.val = x 20 | # self.next = None 21 | 22 | class Solution(object): 23 | def swapPairs(self, head): 24 | """ 25 | :type head: ListNode 26 | :rtype: ListNode 27 | """ 28 | dummy = h = ListNode(0) 29 | step = 1 30 | tmp = None 31 | while head: 32 | if step % 2: 33 | tmp = ListNode(head.val) 34 | else: 35 | h.next = ListNode(head.val) 36 | h.next.next = tmp 37 | h = h.next.next 38 | tmp = None 39 | head = head.next 40 | step += 1 41 | if tmp: 42 | h.next = tmp 43 | return dummy.next 44 | -------------------------------------------------------------------------------- /025-reverse-nodes-in-k-group/reverse-nodes-in-k-group.js: -------------------------------------------------------------------------------- 1 | // Given a linked list, reverse the nodes of a linked list k at a time and return its modified list. 2 | // 3 | // 4 | // 5 | // If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is. 6 | // 7 | // You may not alter the values in the nodes, only nodes itself may be changed. 8 | // 9 | // Only constant memory is allowed. 10 | // 11 | // 12 | // For example, 13 | // Given this linked list: 1->2->3->4->5 14 | // 15 | // 16 | // 17 | // For k = 2, you should return: 2->1->4->3->5 18 | // 19 | // 20 | // 21 | // For k = 3, you should return: 3->2->1->4->5 22 | 23 | 24 | /** 25 | * Definition for singly-linked list. 26 | * function ListNode(val) { 27 | * this.val = val; 28 | * this.next = null; 29 | * } 30 | */ 31 | /** 32 | * @param {ListNode} head 33 | * @param {number} k 34 | * @return {ListNode} 35 | */ 36 | 37 | var reverseList = function (head) { 38 | var prev = null; 39 | var next = null; 40 | while (head) { 41 | var temp = head.next; 42 | prev = head; 43 | prev.next = next; 44 | next = prev; 45 | 46 | head = temp; 47 | } 48 | return prev; 49 | }; 50 | 51 | var reverseKGroup = function(head, k) { 52 | if (!head) return head; 53 | if (k === 1) return head; 54 | var count; 55 | var result = new ListNode(-1); 56 | var res = result; 57 | while (head) { 58 | var fakeHead = head; 59 | var next = null; 60 | count = 1; 61 | while (head && count !== k) { 62 | count += 1; 63 | head = head.next; 64 | } 65 | if (head && count === k) { 66 | next = head.next; 67 | head.next = null; 68 | result.next = reverseList(fakeHead); 69 | while (result.next) { 70 | result = result.next; 71 | } 72 | head = next; 73 | } else if (!head){ 74 | while (result.next) { 75 | result = result.next; 76 | } 77 | result.next = fakeHead; 78 | } 79 | } 80 | return res.next; 81 | }; 82 | -------------------------------------------------------------------------------- /026-remove-duplicates-from-sorted-array/remove-duplicates-from-sorted-array.js: -------------------------------------------------------------------------------- 1 | // Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length. 2 | // 3 | // 4 | // Do not allocate extra space for another array, you must do this in place with constant memory. 5 | // 6 | // 7 | // 8 | // For example, 9 | // Given input array nums = [1,1,2], 10 | // 11 | // 12 | // Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. It doesn't matter what you leave beyond the new length. 13 | 14 | 15 | /** 16 | * @param {number[]} nums 17 | * @return {number} 18 | */ 19 | var removeDuplicates = function(nums) { 20 | var j = 0; 21 | var i = 0; 22 | for (l = nums.length; i < l; i++) { 23 | if (nums[j] !== nums[i]) { 24 | nums[++j] = nums[i]; 25 | } 26 | } 27 | return j+1; 28 | }; 29 | -------------------------------------------------------------------------------- /026-remove-duplicates-from-sorted-array/remove-duplicates-from-sorted-array.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | 3 | 4 | # Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length. 5 | # 6 | # 7 | # Do not allocate extra space for another array, you must do this in place with constant memory. 8 | # 9 | # 10 | # 11 | # For example, 12 | # Given input array nums = [1,1,2], 13 | # 14 | # 15 | # Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. It doesn't matter what you leave beyond the new length. 16 | 17 | 18 | class Solution(object): 19 | def removeDuplicates(self, nums): 20 | """ 21 | :type nums: List[int] 22 | :rtype: int 23 | """ 24 | if not nums: 25 | return 0 26 | n = len(nums) 27 | count = curr = 1 28 | while count < n: 29 | if nums[curr] != nums[curr-1]: 30 | curr += 1 31 | else: 32 | del nums[curr] 33 | count += 1 34 | return curr 35 | -------------------------------------------------------------------------------- /027-remove-element/remove-element.js: -------------------------------------------------------------------------------- 1 | // Given an array and a value, remove all instances of that value in place and return the new length. 2 | // 3 | // 4 | // Do not allocate extra space for another array, you must do this in place with constant memory. 5 | // 6 | // The order of elements can be changed. It doesn't matter what you leave beyond the new length. 7 | // 8 | // 9 | // Example: 10 | // Given input array nums = [3,2,2,3], val = 3 11 | // 12 | // 13 | // Your function should return length = 2, with the first two elements of nums being 2. 14 | // 15 | // 16 | // Try two pointers. 17 | // Did you use the property of "the order of elements can be changed"? 18 | // What happens when the elements to remove are rare? 19 | 20 | 21 | /** 22 | * @param {number[]} nums 23 | * @param {number} val 24 | * @return {number} 25 | */ 26 | var removeElement = function(nums, val) { 27 | var j = 0; 28 | for (var index = 0, l = nums.length; index < l; index++) { 29 | if (nums[index] === val) { 30 | continue; 31 | } 32 | nums[j] = nums[index]; 33 | j++; 34 | } 35 | return j; 36 | }; 37 | -------------------------------------------------------------------------------- /027-remove-element/remove-element.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | 3 | 4 | # Given an array and a value, remove all instances of that value in place and return the new length. 5 | # 6 | # 7 | # Do not allocate extra space for another array, you must do this in place with constant memory. 8 | # 9 | # The order of elements can be changed. It doesn't matter what you leave beyond the new length. 10 | # 11 | # 12 | # Example: 13 | # Given input array nums = [3,2,2,3], val = 3 14 | # 15 | # 16 | # Your function should return length = 2, with the first two elements of nums being 2. 17 | # 18 | # 19 | # Try two pointers. 20 | # Did you use the property of "the order of elements can be changed"? 21 | # What happens when the elements to remove are rare? 22 | 23 | 24 | class Solution(object): 25 | def removeElement(self, nums, val): 26 | """ 27 | :type nums: List[int] 28 | :type val: int 29 | :rtype: int 30 | """ 31 | i = 0 32 | l = len(nums) 33 | 34 | while i < l: 35 | if nums[i] == val: 36 | del nums[i] 37 | l = l-1 38 | else: 39 | i = i+1 40 | 41 | return len(nums) 42 | -------------------------------------------------------------------------------- /028-implement-strstr/implement-strstr.js: -------------------------------------------------------------------------------- 1 | // Implement strStr(). 2 | // 3 | // 4 | // Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. 5 | 6 | 7 | /** 8 | * @param {string} haystack 9 | * @param {string} needle 10 | * @return {number} 11 | */ 12 | var strStr = function(haystack, needle) { 13 | return haystack.indexOf(needle); 14 | }; 15 | -------------------------------------------------------------------------------- /028-implement-strstr/implement-strstr.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | 3 | 4 | # Implement strStr(). 5 | # 6 | # 7 | # Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. 8 | 9 | 10 | class Solution(object): 11 | def strStr(self, haystack, needle): 12 | """ 13 | :type haystack: str 14 | :type needle: str 15 | :rtype: int 16 | """ 17 | if not needle: 18 | return 0 19 | lst = haystack.split(needle) 20 | if len(lst) == 1: 21 | return -1 22 | else: 23 | return len(lst[0]) 24 | -------------------------------------------------------------------------------- /033-search-in-rotated-sorted-array/search-in-rotated-sorted-array.js: -------------------------------------------------------------------------------- 1 | // Suppose a sorted array is rotated at some pivot unknown to you beforehand. 2 | // 3 | // (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2). 4 | // 5 | // You are given a target value to search. If found in the array return its index, otherwise return -1. 6 | // 7 | // You may assume no duplicate exists in the array. 8 | 9 | 10 | /** 11 | * @param {number[]} nums 12 | * @param {number} target 13 | * @return {number} 14 | */ 15 | var search = function(nums, target) { 16 | var before = 0; 17 | var after = nums.length - 1; 18 | var mid; 19 | while(before < after - 1) { 20 | mid = before + Math.floor((after - before) / 2); 21 | if (nums[before] < nums[mid]) { 22 | if (target >= nums[before] && target <= nums[mid]) { 23 | after = mid; 24 | } else { 25 | before = mid; 26 | } 27 | } else { 28 | if (target >= nums[mid] && target <= nums[after]) { 29 | before = mid; 30 | } else { 31 | after = mid; 32 | } 33 | } 34 | } 35 | if (nums[before] === target) return before; 36 | if (nums[after] === target) return after; 37 | return -1; 38 | }; 39 | -------------------------------------------------------------------------------- /034-search-for-a-range/search-for-a-range.js: -------------------------------------------------------------------------------- 1 | // Given a sorted array of integers, find the starting and ending position of a given target value. 2 | // 3 | // Your algorithm's runtime complexity must be in the order of O(log n). 4 | // 5 | // If the target is not found in the array, return [-1, -1]. 6 | // 7 | // 8 | // For example, 9 | // Given [5, 7, 7, 8, 8, 10] and target value 8, 10 | // return [3, 4]. 11 | 12 | 13 | /** 14 | * @param {number[]} nums 15 | * @param {number} target 16 | * @return {number[]} 17 | */ 18 | var searchRange = function(nums, target) { 19 | var res = []; 20 | var low = 0; 21 | var high = nums.length - 1; 22 | var mid; 23 | while (low <= high) { 24 | mid = low + Math.floor((high - low) / 2); 25 | if (nums[mid] < target) { 26 | low = mid + 1; 27 | } else { 28 | high = mid - 1; 29 | } 30 | } 31 | if (low < nums.length && nums[low] === target) { 32 | res.push(low); 33 | } else { 34 | return [-1, -1]; 35 | } 36 | low = low; 37 | high = nums.length - 1; 38 | while(low <= high) { 39 | mid = low + Math.floor((high - low) / 2); 40 | if (nums[mid] <= target) { 41 | low = mid + 1; 42 | } else { 43 | high = mid - 1; 44 | } 45 | } 46 | res.push(high); 47 | return res; 48 | }; 49 | -------------------------------------------------------------------------------- /034-search-for-a-range/search-for-a-range.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | 3 | 4 | # Given a sorted array of integers, find the starting and ending position of a given target value. 5 | # 6 | # Your algorithm's runtime complexity must be in the order of O(log n). 7 | # 8 | # If the target is not found in the array, return [-1, -1]. 9 | # 10 | # 11 | # For example, 12 | # Given [5, 7, 7, 8, 8, 10] and target value 8, 13 | # return [3, 4]. 14 | 15 | 16 | class Solution(object): 17 | def searchRange(self, nums, target): 18 | """ 19 | :type nums: List[int] 20 | :type target: int 21 | :rtype: List[int] 22 | """ 23 | n = len(nums) 24 | left, right = -1, -1 25 | l, r = 0, n-1 26 | while l < r: 27 | m = (l+r)/2 28 | if nums[m] < target: l = m+1 29 | else: r = m 30 | if nums[l] != target: return -1, -1 31 | left = l 32 | l, r = left, n-1 33 | while l < r: 34 | m = (l+r)/2+1 35 | if nums[m] == target: l = m 36 | else: r = m-1 37 | right = l 38 | return left, right 39 | -------------------------------------------------------------------------------- /035-search-insert-position/search-insert-position.js: -------------------------------------------------------------------------------- 1 | // Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. 2 | // 3 | // You may assume no duplicates in the array. 4 | // 5 | // 6 | // Here are few examples. 7 | // [1,3,5,6], 5 → 2 8 | // [1,3,5,6], 2 → 1 9 | // [1,3,5,6], 7 → 4 10 | // [1,3,5,6], 0 → 0 11 | 12 | 13 | /** 14 | * @param {number[]} nums 15 | * @param {number} target 16 | * @return {number} 17 | */ 18 | var searchInsert = function(nums, target) { 19 | var len = nums.length; 20 | var low = 0; 21 | var high = len - 1; 22 | var mid; 23 | while (low <= high) { 24 | mid = low + Math.floor((high - low) / 2); 25 | if (nums[mid] === target) { 26 | return mid; 27 | } else if (nums[mid] < target) { 28 | low = mid + 1; 29 | } else { 30 | high = mid - 1; 31 | } 32 | } 33 | return low; 34 | 35 | }; 36 | -------------------------------------------------------------------------------- /035-search-insert-position/search-insert-position.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | 3 | 4 | # Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. 5 | # 6 | # You may assume no duplicates in the array. 7 | # 8 | # 9 | # Here are few examples. 10 | # [1,3,5,6], 5 → 2 11 | # [1,3,5,6], 2 → 1 12 | # [1,3,5,6], 7 → 4 13 | # [1,3,5,6], 0 → 0 14 | 15 | 16 | class Solution(object): 17 | def searchInsert(self, nums, target): 18 | """ 19 | :type nums: List[int] 20 | :type target: int 21 | :rtype: int 22 | """ 23 | if not nums: 24 | return 0 25 | 26 | for idx,val in enumerate(nums): 27 | if val >= target: 28 | return idx 29 | 30 | return len(nums) 31 | -------------------------------------------------------------------------------- /038-count-and-say/count-and-say.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | 3 | 4 | # The count-and-say sequence is the sequence of integers beginning as follows: 5 | # 1, 11, 21, 1211, 111221, ... 6 | # 7 | # 8 | # 9 | # 1 is read off as "one 1" or 11. 10 | # 11 is read off as "two 1s" or 21. 11 | # 21 is read off as "one 2, then one 1" or 1211. 12 | # 13 | # 14 | # 15 | # Given an integer n, generate the nth sequence. 16 | # 17 | # 18 | # 19 | # Note: The sequence of integers will be represented as a string. 20 | 21 | 22 | class Solution(object): 23 | def countAndSay(self, n): 24 | """ 25 | :type n: int 26 | :rtype: str 27 | """ 28 | s = '1' 29 | for i in range(n-1): 30 | count = 1 31 | temp = [] 32 | for index in range(1, len(s)): 33 | if s[index] == s[index-1]: 34 | count += 1 35 | else: 36 | temp.append(str(count)) 37 | temp.append(s[index-1]) 38 | count = 1 39 | temp.append(str(count)) 40 | temp.append(s[-1]) 41 | s = ''.join(temp) 42 | return s 43 | -------------------------------------------------------------------------------- /039-combination-sum/combination-sum.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | 3 | 4 | # Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T. 5 | # 6 | # 7 | # The same repeated number may be chosen from C unlimited number of times. 8 | # 9 | # 10 | # Note: 11 | # 12 | # All numbers (including target) will be positive integers. 13 | # The solution set must not contain duplicate combinations. 14 | # 15 | # 16 | # 17 | # 18 | # For example, given candidate set [2, 3, 6, 7] and target 7, 19 | # A solution set is: 20 | # 21 | # [ 22 | # [7], 23 | # [2, 2, 3] 24 | # ] 25 | 26 | 27 | class Solution(object): 28 | def combinationSum(self, candidates, target): 29 | """ 30 | :type candidates: List[int] 31 | :type target: int 32 | :rtype: List[List[int]] 33 | """ 34 | res = [] 35 | candidates.sort() 36 | self.dfs(candidates, target, 0, [], res) 37 | return res 38 | 39 | def dfs(self, nums, target, index, path, res): 40 | if target < 0: 41 | return # backtracking 42 | if target == 0: 43 | res.append(path) 44 | return 45 | for i in xrange(index, len(nums)): 46 | self.dfs(nums, target-nums[i], i, path+[nums[i]], res) 47 | -------------------------------------------------------------------------------- /041-first-missing-positive/first-missing-positive.js: -------------------------------------------------------------------------------- 1 | // Given an unsorted integer array, find the first missing positive integer. 2 | // 3 | // 4 | // 5 | // For example, 6 | // Given [1,2,0] return 3, 7 | // and [3,4,-1,1] return 2. 8 | // 9 | // 10 | // 11 | // Your algorithm should run in O(n) time and uses constant space. 12 | 13 | 14 | /** 15 | * @param {number[]} nums 16 | * @return {number} 17 | */ 18 | var firstMissingPositive = function(nums) { 19 | var map = []; 20 | for (var i = 0, l = nums.length; i <= l - 1; ++i) { 21 | if (nums[i] > 0) { 22 | map[nums[i]] = true; 23 | } 24 | } 25 | for (i = 1, l = map.length; i <= l - 1; ++i) { 26 | if (!map[i]) { 27 | return i; 28 | } 29 | } 30 | return i; 31 | }; 32 | -------------------------------------------------------------------------------- /041-first-missing-positive/first-missing-positive.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | 3 | 4 | # Given an unsorted integer array, find the first missing positive integer. 5 | # 6 | # 7 | # 8 | # For example, 9 | # Given [1,2,0] return 3, 10 | # and [3,4,-1,1] return 2. 11 | # 12 | # 13 | # 14 | # Your algorithm should run in O(n) time and uses constant space. 15 | 16 | 17 | class Solution(object): 18 | def firstMissingPositive(self, nums): 19 | """ 20 | :type nums: List[int] 21 | :rtype: int 22 | """ 23 | length = len(nums) 24 | if len(nums) == 0: 25 | return 1 26 | lst = range(1, length+2) 27 | for i in nums: 28 | if i > 0 and i < length+1 and i in lst: 29 | lst.remove(i) 30 | return lst[0] 31 | -------------------------------------------------------------------------------- /049-anagrams/anagrams.js: -------------------------------------------------------------------------------- 1 | // Given an array of strings, group anagrams together. 2 | // 3 | // 4 | // For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"], 5 | // Return: 6 | // 7 | // [ 8 | // ["ate", "eat","tea"], 9 | // ["nat","tan"], 10 | // ["bat"] 11 | // ] 12 | // 13 | // Note: All inputs will be in lower-case. 14 | 15 | 16 | /** 17 | * @param {string[]} strs 18 | * @return {string[][]} 19 | */ 20 | 21 | var groupAnagrams = function(strs) { 22 | const hashMap = {}; 23 | strs.forEach((str) => { 24 | const val = generateKey(str); 25 | if (hashMap[val]) { 26 | hashMap[val].push(str); 27 | } else { 28 | hashMap[val] = [str]; 29 | } 30 | }); 31 | const result = []; 32 | for (let item in hashMap) { 33 | result.push(hashMap[item]); 34 | } 35 | return result; 36 | }; 37 | function generateKey (str) { 38 | let result = 1; 39 | for (let i = 0, l = str.length; i < l; i++) { 40 | let n = str[i].charCodeAt() - 'a'.charCodeAt() + 1; 41 | result = result * (n*n + n + 41) % 2147483647; 42 | } 43 | return result; 44 | } 45 | -------------------------------------------------------------------------------- /050-powx-n/powx-n.js: -------------------------------------------------------------------------------- 1 | // Implement pow(x, n). 2 | 3 | 4 | /** 5 | * @param {number} x 6 | * @param {number} n 7 | * @return {number} 8 | */ 9 | var myPow = function(x, n) { 10 | if (x === 0) return 0; 11 | if (n === 0) return 1; 12 | if(n<0){ 13 | n = -n; 14 | x = 1/x; 15 | } 16 | return (n%2 == 0) ? myPow(x*x, Math.floor(n/2)) : x*myPow(x*x, Math.floor(n/2)); 17 | }; 18 | -------------------------------------------------------------------------------- /050-powx-n/powx-n.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | 3 | 4 | # Implement pow(x, n). 5 | 6 | 7 | class Solution(object): 8 | def myPow(self, x, n): 9 | """ 10 | :type x: float 11 | :type n: int 12 | :rtype: float 13 | """ 14 | if not n: 15 | return 1 16 | if n < 0: 17 | return 1 / self.myPow(x, -n) 18 | if n % 2: 19 | return x * self.myPow(x, n-1) 20 | return self.myPow(x*x, n/2) 21 | -------------------------------------------------------------------------------- /055-jump-game/jump-game.js: -------------------------------------------------------------------------------- 1 | // Given an array of non-negative integers, you are initially positioned at the first index of the array. 2 | // 3 | // 4 | // Each element in the array represents your maximum jump length at that position. 5 | // 6 | // 7 | // Determine if you are able to reach the last index. 8 | // 9 | // 10 | // 11 | // For example: 12 | // A = [2,3,1,1,4], return true. 13 | // 14 | // 15 | // A = [3,2,1,0,4], return false. 16 | 17 | 18 | /** 19 | * @param {number[]} nums 20 | * @return {boolean} 21 | */ 22 | var canJump = function(nums) { 23 | var lastIndex = nums.length - 1; 24 | for (var i = nums.length - 2; i >= 0; --i) { 25 | if (i + nums[i] >= lastIndex) { 26 | lastIndex = i; 27 | } 28 | } 29 | return lastIndex === 0; 30 | }; 31 | -------------------------------------------------------------------------------- /058-length-of-last-word/length-of-last-word.js: -------------------------------------------------------------------------------- 1 | // Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string. 2 | // 3 | // If the last word does not exist, return 0. 4 | // 5 | // Note: A word is defined as a character sequence consists of non-space characters only. 6 | // 7 | // 8 | // For example, 9 | // Given s = "Hello World", 10 | // return 5. 11 | 12 | 13 | /** 14 | * @param {string} s 15 | * @return {number} 16 | */ 17 | var lengthOfLastWord = function(s) { 18 | s = s.trim(); 19 | var arr = s.split(' '); 20 | return arr[arr.length - 1].length; 21 | }; 22 | -------------------------------------------------------------------------------- /061-rotate-list/rotate-list.js: -------------------------------------------------------------------------------- 1 | // Given a list, rotate the list to the right by k places, where k is non-negative. 2 | // 3 | // For example: 4 | // Given 1->2->3->4->5->NULL and k = 2, 5 | // return 4->5->1->2->3->NULL. 6 | 7 | 8 | /** 9 | * Definition for singly-linked list. 10 | * function ListNode(val) { 11 | * this.val = val; 12 | * this.next = null; 13 | * } 14 | */ 15 | /** 16 | * @param {ListNode} head 17 | * @param {number} k 18 | * @return {ListNode} 19 | */ 20 | 21 | var reverseList = function (head) { 22 | var prev = null; 23 | var next = null; 24 | while (head) { 25 | var temp = head.next; 26 | prev = head; 27 | prev.next = next; 28 | next = prev; 29 | 30 | head = temp; 31 | } 32 | return prev; 33 | } 34 | var rotateRight = function(head, k) { 35 | if (!head) return null; 36 | var count = 1; 37 | var fakeHead = head; 38 | while (head.next) { 39 | count += 1; 40 | head = head.next; 41 | } 42 | 43 | if (k > count) { 44 | k = k % count; 45 | } 46 | 47 | var target = count - k; 48 | if (target <= 0) { 49 | return fakeHead; 50 | } 51 | head.next = fakeHead; 52 | head = head.next; 53 | count = 1; 54 | 55 | var tail = null; 56 | while (head) { 57 | if (count === target) { 58 | tail = head.next; 59 | head.next = null; 60 | } 61 | count += 1; 62 | head = head.next; 63 | } 64 | return tail; 65 | }; 66 | -------------------------------------------------------------------------------- /066-plus-one/plus-one.js: -------------------------------------------------------------------------------- 1 | // Given a non-negative number represented as an array of digits, plus one to the number. 2 | // 3 | // The digits are stored such that the most significant digit is at the head of the list. 4 | 5 | 6 | /** 7 | * @param {number[]} digits 8 | * @return {number[]} 9 | */ 10 | var plusOne = function(digits) { 11 | var one = 1; 12 | var resultItem = 0; 13 | for (var i = digits.length - 1; i >= 0; i--) { 14 | resultItem = digits[i] + one; 15 | one = parseInt(resultItem / 10); 16 | if (resultItem == 10) { 17 | digits[i] = 0; 18 | } else { 19 | digits[i] = resultItem; 20 | } 21 | } 22 | if (one > 0) { 23 | digits.unshift(one); 24 | } 25 | return digits; 26 | }; 27 | -------------------------------------------------------------------------------- /067-add-binary/add-binary.js: -------------------------------------------------------------------------------- 1 | // Given two binary strings, return their sum (also a binary string). 2 | // 3 | // 4 | // 5 | // For example, 6 | // a = "11" 7 | // b = "1" 8 | // Return "100". 9 | 10 | 11 | /** 12 | * @param {string} a 13 | * @param {string} b 14 | * @return {string} 15 | */ 16 | var addBinary = function(a, b) { 17 | var carry = 0; 18 | var len1 = a.length; 19 | var len2 = b.length; 20 | var res = ''; 21 | while (len1 > 0 || len2 > 0) { 22 | var sum = (+a[len1 - 1] || 0) + (+b[len2 - 1] || 0) + carry; 23 | carry = Math.floor(sum / 2); 24 | res = sum % 2 + res; 25 | len1--; 26 | len2--; 27 | } 28 | if (carry) res = '1' + res; 29 | return res; 30 | }; 31 | -------------------------------------------------------------------------------- /069-sqrtx/sqrtx.js: -------------------------------------------------------------------------------- 1 | // Implement int sqrt(int x). 2 | // 3 | // Compute and return the square root of x. 4 | 5 | 6 | /** 7 | * @param {number} x 8 | * @return {number} 9 | */ 10 | var mySqrt = function(x) { 11 | var left = 1; 12 | var right = Math.floor(x / 2) + 1; 13 | var mid; 14 | 15 | while (left <= right) { 16 | mid = Math.floor((left + right) / 2); 17 | 18 | if (mid * mid > x) { 19 | right = mid - 1; 20 | } else if (mid * mid < x) { 21 | left = mid + 1; 22 | } else { 23 | return mid; 24 | } 25 | } 26 | 27 | return right; 28 | }; 29 | -------------------------------------------------------------------------------- /070-climbing-stairs/climbing-stairs.js: -------------------------------------------------------------------------------- 1 | // You are climbing a stair case. It takes n steps to reach to the top. 2 | // 3 | // Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? 4 | 5 | 6 | /** 7 | * @param {number} n 8 | * @return {number} 9 | */ 10 | var climbStairs = function(n) { 11 | var f1 = 2; 12 | var f2 = 1; 13 | if(n == 1) { 14 | return f2; 15 | } else if(n == 2) { 16 | return f1; 17 | } 18 | 19 | var fn; 20 | for(var i = 3; i <= n; i++) { 21 | fn = f1 + f2; 22 | f2 = f1; 23 | f1 = fn; 24 | } 25 | return fn; 26 | }; 27 | -------------------------------------------------------------------------------- /073-set-matrix-zeroes/set-matrix-zeroes.js: -------------------------------------------------------------------------------- 1 | // Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place. 2 | // 3 | // 4 | // click to show follow up. 5 | // 6 | // Follow up: 7 | // 8 | // 9 | // Did you use extra space? 10 | // A straight forward solution using O(mn) space is probably a bad idea. 11 | // A simple improvement uses O(m + n) space, but still not the best solution. 12 | // Could you devise a constant space solution? 13 | 14 | 15 | /** 16 | * @param {number[][]} matrix 17 | * @return {void} Do not return anything, modify matrix in-place instead. 18 | */ 19 | var setZeroes = function(matrix) { 20 | var r = matrix.length; 21 | var l = matrix[0].length; 22 | for (var i = 0; i < r; i++) { 23 | for (var j = 0; j < l; j++) { 24 | if (matrix[i][j] === 0 && 1 / matrix[i][j] === Infinity) { 25 | for (var x = 0; x < r; x++) { 26 | matrix[x][j] = matrix[x][j] && -0; 27 | } 28 | for (var y = 0; y < l; y++) { 29 | matrix[i][y] = matrix[i][y] && -0; 30 | } 31 | } 32 | } 33 | } 34 | }; 35 | -------------------------------------------------------------------------------- /075-sort-colors/sort-colors.js: -------------------------------------------------------------------------------- 1 | // Given an array with n objects colored red, white or blue, sort them so that objects of the same color are adjacent, with the colors in the order red, white and blue. 2 | // 3 | // 4 | // 5 | // Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively. 6 | // 7 | // 8 | // 9 | // Note: 10 | // You are not suppose to use the library's sort function for this problem. 11 | // 12 | // 13 | // click to show follow up. 14 | // 15 | // 16 | // Follow up: 17 | // A rather straight forward solution is a two-pass algorithm using counting sort. 18 | // First, iterate the array counting number of 0's, 1's, and 2's, then overwrite array with total number of 0's, then 1's and followed by 2's. 19 | // Could you come up with an one-pass algorithm using only constant space? 20 | 21 | 22 | /** 23 | * @param {number[]} nums 24 | * @return {void} Do not return anything, modify nums in-place instead. 25 | */ 26 | var sortColors = function(nums) { 27 | var two_index = 0; 28 | for (var i = 0, j = nums.length; i < j; ++i) { 29 | if (nums[i] !== 2) { 30 | nums[two_index++] = nums[i]; 31 | } 32 | } 33 | var zero_index = two_index - 1; 34 | for (i = two_index - 1; i >= 0; --i) { 35 | if (nums[i] !== 0) { 36 | zero_index--; 37 | } 38 | } 39 | 40 | for (i = 0; i <= zero_index; i++) { 41 | nums[i] = 0; 42 | } 43 | for (; i < two_index; i++) { 44 | nums[i] = 1; 45 | } 46 | for (; i < nums.length; i++) { 47 | nums[i] = 2; 48 | } 49 | }; 50 | -------------------------------------------------------------------------------- /078-subsets/subsets.js: -------------------------------------------------------------------------------- 1 | // Given a set of distinct integers, nums, return all possible subsets. 2 | // 3 | // Note: The solution set must not contain duplicate subsets. 4 | // 5 | // 6 | // For example, 7 | // If nums = [1,2,3], a solution is: 8 | // 9 | // 10 | // 11 | // [ 12 | // [3], 13 | // [1], 14 | // [2], 15 | // [1,2,3], 16 | // [1,3], 17 | // [2,3], 18 | // [1,2], 19 | // [] 20 | // ] 21 | 22 | 23 | var subsets = function(nums) { 24 | if (nums.length === 0) 25 | return []; 26 | 27 | var len = nums.length, 28 | count = Math.pow(2, len), 29 | result = []; 30 | 31 | for (var i = 0; i < count; i++) { 32 | // to binary string 33 | var str = i.toString(2); 34 | 35 | // get one subset from binary string 36 | var subset = []; 37 | // iterate the string from back to front since our binary string is 38 | // e.g.: "11" instead of "011" when i = 3 39 | for (var k = str.length - 1; k >= 0; k--) { 40 | if (str[k] == '1') 41 | subset.unshift(nums[len - str.length + k]); 42 | } 43 | 44 | result.push(subset); 45 | } 46 | 47 | return result; 48 | }; 49 | -------------------------------------------------------------------------------- /080-remove-duplicates-from-sorted-array-ii/remove-duplicates-from-sorted-array-ii.js: -------------------------------------------------------------------------------- 1 | // Follow up for "Remove Duplicates": 2 | // What if duplicates are allowed at most twice? 3 | // 4 | // 5 | // For example, 6 | // Given sorted array nums = [1,1,1,2,2,3], 7 | // 8 | // 9 | // Your function should return length = 5, with the first five elements of nums being 1, 1, 2, 2 and 3. It doesn't matter what you leave beyond the new length. 10 | 11 | 12 | /** 13 | * @param {number[]} nums 14 | * @return {number} 15 | */ 16 | var removeDuplicates = function(nums) { 17 | var lock = 1; 18 | var j = 0; 19 | for (var i = 1, l = nums.length; i < l; i++) { 20 | if (nums[i] !== nums[j]) { 21 | nums[++j] = nums[i]; 22 | lock = 1; 23 | } else { 24 | if (lock < 2) { 25 | nums[++j] = nums[i]; 26 | lock++; 27 | } else { 28 | continue; 29 | } 30 | } 31 | } 32 | nums.length = j + 1; 33 | return j + 1; 34 | }; 35 | -------------------------------------------------------------------------------- /081-search-in-rotated-sorted-array-ii/search-in-rotated-sorted-array-ii.js: -------------------------------------------------------------------------------- 1 | // Follow up for "Search in Rotated Sorted Array": 2 | // What if duplicates are allowed? 3 | // 4 | // Would this affect the run-time complexity? How and why? 5 | // 6 | // Write a function to determine if a given target is in the array. 7 | 8 | 9 | /** 10 | * @param {number[]} nums 11 | * @param {number} target 12 | * @return {boolean} 13 | */ 14 | var search = function(nums, target) { 15 | var before = 0; 16 | var after = nums.length - 1; 17 | var mid; 18 | while(before < after - 1) { 19 | mid = before + Math.floor((after - before) / 2); 20 | if (nums[before] < nums[mid]) { 21 | if (target >= nums[before] && target <= nums[mid]) { 22 | after = mid; 23 | } else { 24 | before = mid; 25 | } 26 | } else if (nums[before] > nums[mid]){ 27 | if (target >= nums[mid] && target <= nums[after]) { 28 | before = mid; 29 | } else { 30 | after = mid; 31 | } 32 | } else { 33 | before++; 34 | } 35 | } 36 | if (nums[before] === target) return true; 37 | if (nums[after] === target) return true; 38 | return false; 39 | }; 40 | -------------------------------------------------------------------------------- /082-remove-duplicates-from-sorted-list-ii/remove-duplicates-from-sorted-list-ii.js: -------------------------------------------------------------------------------- 1 | // Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list. 2 | // 3 | // 4 | // For example, 5 | // Given 1->2->3->3->4->4->5, return 1->2->5. 6 | // Given 1->1->1->2->3, return 2->3. 7 | 8 | 9 | /** 10 | * Definition for singly-linked list. 11 | * function ListNode(val) { 12 | * this.val = val; 13 | * this.next = null; 14 | * } 15 | */ 16 | /** 17 | * @param {ListNode} head 18 | * @return {ListNode} 19 | */ 20 | var deleteDuplicates = function(head) { 21 | var fakeHead = new ListNode(-1); 22 | fakeHead.next = head; 23 | head = fakeHead; 24 | var isDup = false; 25 | while (head.next) { 26 | var current = head.next; 27 | while (current.next) { 28 | if (current.val === current.next.val) { 29 | current = current.next; 30 | isDup = true; 31 | } else { 32 | break; 33 | } 34 | } 35 | if (isDup) { 36 | head.next = current.next; 37 | } else { 38 | head.next = current; 39 | head = head.next; 40 | } 41 | isDup = false; 42 | } 43 | return fakeHead.next; 44 | }; 45 | -------------------------------------------------------------------------------- /083-remove-duplicates-from-sorted-list/remove-duplicates-from-sorted-list.js: -------------------------------------------------------------------------------- 1 | // Given a sorted linked list, delete all duplicates such that each element appear only once. 2 | // 3 | // 4 | // For example, 5 | // Given 1->1->2, return 1->2. 6 | // Given 1->1->2->3->3, return 1->2->3. 7 | 8 | 9 | /** 10 | * Definition for singly-linked list. 11 | * function ListNode(val) { 12 | * this.val = val; 13 | * this.next = null; 14 | * } 15 | */ 16 | /** 17 | * @param {ListNode} head 18 | * @return {ListNode} 19 | */ 20 | var deleteDuplicates = function(head) { 21 | if (!head || !head.next) { 22 | return head; 23 | } 24 | var prev = head; 25 | var next = head.next; 26 | while (next) { 27 | if (next.val !== prev.val) { 28 | prev.next = next; 29 | prev = next; 30 | } 31 | next = next.next; 32 | } 33 | prev.next = null; 34 | return head; 35 | }; 36 | -------------------------------------------------------------------------------- /086-partition-list/partition-list.js: -------------------------------------------------------------------------------- 1 | // Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x. 2 | // 3 | // 4 | // You should preserve the original relative order of the nodes in each of the two partitions. 5 | // 6 | // 7 | // For example, 8 | // Given 1->4->3->2->5->2 and x = 3, 9 | // return 1->2->2->4->3->5. 10 | 11 | 12 | /** 13 | * Definition for singly-linked list. 14 | * function ListNode(val) { 15 | * this.val = val; 16 | * this.next = null; 17 | * } 18 | */ 19 | /** 20 | * @param {ListNode} head 21 | * @param {number} x 22 | * @return {ListNode} 23 | */ 24 | var partition = function(head, x) { 25 | var less = new ListNode(-1); 26 | var more = new ListNode(-1); 27 | var temp1 = less; 28 | var temp2 = more; 29 | while (head) { 30 | if (head.val < x) { 31 | less.next = head; 32 | less = less.next; 33 | } else { 34 | more.next = head; 35 | more = more.next; 36 | } 37 | head = head.next; 38 | } 39 | more.next = null; 40 | less.next = temp2.next; 41 | return temp1.next; 42 | }; 43 | -------------------------------------------------------------------------------- /088-merge-sorted-array/merge-sorted-array.js: -------------------------------------------------------------------------------- 1 | // Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array. 2 | // 3 | // 4 | // Note: 5 | // You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2. The number of elements initialized in nums1 and nums2 are m and n respectively. 6 | 7 | 8 | /** 9 | * @param {number[]} nums1 10 | * @param {number} m 11 | * @param {number[]} nums2 12 | * @param {number} n 13 | * @return {void} Do not return anything, modify nums1 in-place instead. 14 | */ 15 | var merge = function(nums1, m, nums2, n) { 16 | var first = m - 1; 17 | var second = n - 1; 18 | for (var i = m + n - 1; i >= 0; i--) { 19 | if (second < 0) { 20 | break; 21 | } 22 | if (nums1[first] > nums2[second]) { 23 | nums1[i] = nums1[first]; 24 | first--; 25 | } else { 26 | nums1[i] = nums2[second]; 27 | second--; 28 | } 29 | 30 | } 31 | }; 32 | -------------------------------------------------------------------------------- /090-subsets-ii/subsets-ii.js: -------------------------------------------------------------------------------- 1 | // Given a collection of integers that might contain duplicates, nums, return all possible subsets. 2 | // 3 | // Note: The solution set must not contain duplicate subsets. 4 | // 5 | // 6 | // For example, 7 | // If nums = [1,2,2], a solution is: 8 | // 9 | // 10 | // 11 | // [ 12 | // [2], 13 | // [1], 14 | // [1,2,2], 15 | // [2,2], 16 | // [1,2], 17 | // [] 18 | // ] 19 | 20 | 21 | /** 22 | * @param {number[]} nums 23 | * @return {number[][]} 24 | */ 25 | var subsetsWithDup = function(nums) { 26 | if (nums.length === 0) return nums; 27 | var len = nums.length; 28 | var count = Math.pow(2, len); 29 | var hashMap = {}; 30 | var result = []; 31 | for (var i = 0; i < count; i++) { 32 | var str = i.toString(2); 33 | var strLen = str.length; 34 | 35 | var subset = []; 36 | var prefix = len - strLen; 37 | for (var index = 0; index < strLen; index++) { 38 | if (str[index] === '1') { 39 | var subsetItem = nums[index + prefix]; 40 | subset.push(subsetItem); 41 | } 42 | } 43 | subset.sort(); 44 | if (!hashMap[subset]) { 45 | result.push(subset); 46 | hashMap[subset] = true; 47 | 48 | } 49 | } 50 | return result; 51 | }; 52 | -------------------------------------------------------------------------------- /092-reverse-linked-list-ii/reverse-linked-list-ii.js: -------------------------------------------------------------------------------- 1 | // Reverse a linked list from position m to n. Do it in-place and in one-pass. 2 | // 3 | // 4 | // 5 | // For example: 6 | // Given 1->2->3->4->5->NULL, m = 2 and n = 4, 7 | // 8 | // 9 | // return 1->4->3->2->5->NULL. 10 | // 11 | // 12 | // Note: 13 | // Given m, n satisfy the following condition: 14 | // 1 ≤ m ≤ n ≤ length of list. 15 | 16 | 17 | /** 18 | * Definition for singly-linked list. 19 | * function ListNode(val) { 20 | * this.val = val; 21 | * this.next = null; 22 | * } 23 | */ 24 | /** 25 | * @param {ListNode} head 26 | * @param {number} m 27 | * @param {number} n 28 | * @return {ListNode} 29 | */ 30 | var reverseList = function (head) { 31 | var prev = null; 32 | var next = null; 33 | while (head) { 34 | var temp = head.next; 35 | prev = head; 36 | prev.next = next; 37 | next = prev; 38 | 39 | head = temp; 40 | } 41 | return prev; 42 | } 43 | var reverseBetween = function(head, m, n) { 44 | if (!head || !head.next) return head; 45 | if (m === n) return head; 46 | var fakeHead = new ListNode(0); 47 | fakeHead.next = head; 48 | var dupHead = fakeHead; 49 | 50 | var count = 0; 51 | var prev = null; 52 | var next = null; 53 | while (fakeHead) { 54 | if (count === m - 1) { 55 | prev = fakeHead; 56 | } 57 | if (count === n) { 58 | next = fakeHead.next; 59 | fakeHead.next = null; 60 | } 61 | count += 1; 62 | fakeHead = fakeHead.next; 63 | } 64 | 65 | var reverseHead = reverseList(prev.next); 66 | 67 | prev.next = reverseHead; 68 | 69 | head = dupHead; 70 | while (head.next) { 71 | head = head.next; 72 | } 73 | head.next = next; 74 | return dupHead.next; 75 | }; 76 | -------------------------------------------------------------------------------- /094-binary-tree-inorder-traversal/binary-tree-inorder-traversal.js: -------------------------------------------------------------------------------- 1 | // Given a binary tree, return the inorder traversal of its nodes' values. 2 | // 3 | // 4 | // For example: 5 | // Given binary tree [1,null,2,3], 6 | // 7 | // 1 8 | // \ 9 | // 2 10 | // / 11 | // 3 12 | // 13 | // 14 | // 15 | // return [1,3,2]. 16 | // 17 | // 18 | // Note: Recursive solution is trivial, could you do it iteratively? 19 | 20 | 21 | /** 22 | * Definition for a binary tree node. 23 | * function TreeNode(val) { 24 | * this.val = val; 25 | * this.left = this.right = null; 26 | * } 27 | */ 28 | /** 29 | * @param {TreeNode} root 30 | * @return {number[]} 31 | */ 32 | 33 | var dfs = function (result, node) { 34 | if (!node) return ; 35 | dfs(result, node.left); 36 | result.push(node.val); 37 | dfs(result, node.right); 38 | return ; 39 | }; 40 | var inorderTraversal = function(root) { 41 | var result = []; 42 | dfs(result, root); 43 | return result; 44 | }; 45 | -------------------------------------------------------------------------------- /100-same-tree/same-tree.js: -------------------------------------------------------------------------------- 1 | // Given two binary trees, write a function to check if they are equal or not. 2 | // 3 | // 4 | // Two binary trees are considered equal if they are structurally identical and the nodes have the same value. 5 | 6 | 7 | /** 8 | * Definition for a binary tree node. 9 | * function TreeNode(val) { 10 | * this.val = val; 11 | * this.left = this.right = null; 12 | * } 13 | */ 14 | /** 15 | * @param {TreeNode} p 16 | * @param {TreeNode} q 17 | * @return {boolean} 18 | */ 19 | var isSameTree = function(p, q) { 20 | if (!p && !q) return true; 21 | if (!p || !q || p.val !== q.val) return false; 22 | return isSameTree(p.left, q.left) && isSameTree(p.right, q.right); 23 | }; 24 | -------------------------------------------------------------------------------- /101-symmetric-tree/symmetric-tree.js: -------------------------------------------------------------------------------- 1 | // Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center). 2 | // 3 | // 4 | // For example, this binary tree [1,2,2,3,4,4,3] is symmetric: 5 | // 6 | // 1 7 | // / \ 8 | // 2 2 9 | // / \ / \ 10 | // 3 4 4 3 11 | // 12 | // 13 | // 14 | // But the following [1,2,2,null,3,null,3] is not: 15 | // 16 | // 1 17 | // / \ 18 | // 2 2 19 | // \ \ 20 | // 3 3 21 | // 22 | // 23 | // 24 | // 25 | // Note: 26 | // Bonus points if you could solve it both recursively and iteratively. 27 | 28 | 29 | /** 30 | * Definition for a binary tree node. 31 | * function TreeNode(val) { 32 | * this.val = val; 33 | * this.left = this.right = null; 34 | * } 35 | */ 36 | /** 37 | * @param {TreeNode} root 38 | * @return {boolean} 39 | */ 40 | 41 | var isSame = function (left, right) { 42 | if (!left && !right) return true; 43 | if (!left || !right || right.val !== left.val) return false; 44 | return isSame(left.left, right.right) && isSame(left.right, right.left); 45 | }; 46 | var isSymmetric = function(root) { 47 | if (!root) return true; 48 | return isSame(root.left, root.right); 49 | }; 50 | -------------------------------------------------------------------------------- /104-maximum-depth-of-binary-tree/maximum-depth-of-binary-tree.js: -------------------------------------------------------------------------------- 1 | // Given a binary tree, find its maximum depth. 2 | // 3 | // The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. 4 | 5 | 6 | /** 7 | * Definition for a binary tree node. 8 | * function TreeNode(val) { 9 | * this.val = val; 10 | * this.left = this.right = null; 11 | * } 12 | */ 13 | /** 14 | * @param {TreeNode} root 15 | * @return {number} 16 | */ 17 | var maxDepth = function(root) { 18 | if (!root) return 0; 19 | var lval = maxDepth(root.left) + 1; 20 | var rval = maxDepth(root.right) + 1; 21 | return lval > rval ? lval : rval; 22 | }; 23 | -------------------------------------------------------------------------------- /107-binary-tree-level-order-traversal-ii/binary-tree-level-order-traversal-ii.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | 3 | 4 | # Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root). 5 | # 6 | # 7 | # For example: 8 | # Given binary tree [3,9,20,null,null,15,7], 9 | # 10 | # 3 11 | # / \ 12 | # 9 20 13 | # / \ 14 | # 15 7 15 | # 16 | # 17 | # 18 | # return its bottom-up level order traversal as: 19 | # 20 | # [ 21 | # [15,7], 22 | # [9,20], 23 | # [3] 24 | # ] 25 | 26 | 27 | # Definition for a binary tree node. 28 | # class TreeNode(object): 29 | # def __init__(self, x): 30 | # self.val = x 31 | # self.left = None 32 | # self.right = None 33 | 34 | class Solution(object): 35 | rlst = [] 36 | 37 | def levelOrderBottom(self, root): 38 | """ 39 | :type root: TreeNode 40 | :rtype: List[List[int]] 41 | """ 42 | if not root: 43 | return [] 44 | self.rlst=[] 45 | self.levelList(root, 0) 46 | mx = max([item['hight'] for item in self.rlst]) 47 | rst = [list() for _ in range(mx+1)] 48 | for item in self.rlst: 49 | rst[mx - item['hight']].append(item['val']) 50 | 51 | return rst 52 | 53 | def levelList(self, root, hight): 54 | if root: 55 | self.rlst.append({'val': root.val, 'hight': hight}) 56 | hight = hight + 1 57 | if root.left: 58 | self.levelList(root.left, hight) 59 | if root.right: 60 | self.levelList(root.right, hight) 61 | 62 | -------------------------------------------------------------------------------- /111-minimum-depth-of-binary-tree/minimum-depth-of-binary-tree.js: -------------------------------------------------------------------------------- 1 | // Given a binary tree, find its minimum depth. 2 | // 3 | // The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. 4 | 5 | 6 | /** 7 | * Definition for a binary tree node. 8 | * function TreeNode(val) { 9 | * this.val = val; 10 | * this.left = this.right = null; 11 | * } 12 | */ 13 | /** 14 | * @param {TreeNode} root 15 | * @return {number} 16 | */ 17 | 18 | 19 | var minDepth = function(root) { 20 | return root==null ? 0 : root.left==null ? minDepth(root.right) + 1 : 21 | root.right == null? minDepth(root.left)+1 : 22 | Math.min(minDepth(root.left), minDepth(root.right))+1; 23 | }; 24 | -------------------------------------------------------------------------------- /111-minimum-depth-of-binary-tree/minimum-depth-of-binary-tree.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | 3 | 4 | # Given a binary tree, find its minimum depth. 5 | # 6 | # The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. 7 | 8 | 9 | # Definition for a binary tree node. 10 | # class TreeNode(object): 11 | # def __init__(self, x): 12 | # self.val = x 13 | # self.left = None 14 | # self.right = None 15 | 16 | class Solution(object): 17 | def minDepth(self, root): 18 | """ 19 | :type root: TreeNode 20 | :rtype: int 21 | """ 22 | if root == None: 23 | return 0 24 | if root.left==None or root.right==None: 25 | return self.minDepth(root.left)+self.minDepth(root.right)+1 26 | return min(self.minDepth(root.right),self.minDepth(root.left))+1 27 | -------------------------------------------------------------------------------- /118-pascals-triangle/pascals-triangle.js: -------------------------------------------------------------------------------- 1 | // Given numRows, generate the first numRows of Pascal's triangle. 2 | // 3 | // 4 | // For example, given numRows = 5, 5 | // Return 6 | // 7 | // [ 8 | // [1], 9 | // [1,1], 10 | // [1,2,1], 11 | // [1,3,3,1], 12 | // [1,4,6,4,1] 13 | // ] 14 | 15 | 16 | /** 17 | * @param {number} numRows 18 | * @return {number[][]} 19 | */ 20 | var generate = function(numRows) { 21 | var result = []; 22 | for (var i = 0, l = numRows; i < l; i++) { 23 | var arr = []; 24 | arr[0] = arr[i] = 1; 25 | for (var j = 1; j < i; j++) { 26 | arr[j] = result[i - 1][j] + result[i - 1][j - 1]; 27 | } 28 | result[i] = arr; 29 | } 30 | return result; 31 | }; 32 | -------------------------------------------------------------------------------- /119-pascals-triangle-ii/pascals-triangle-ii.js: -------------------------------------------------------------------------------- 1 | // Given an index k, return the kth row of the Pascal's triangle. 2 | // 3 | // 4 | // For example, given k = 3, 5 | // Return [1,3,3,1]. 6 | // 7 | // 8 | // 9 | // Note: 10 | // Could you optimize your algorithm to use only O(k) extra space? 11 | 12 | 13 | /** 14 | * @param {number} rowIndex 15 | * @return {number[]} 16 | */ 17 | var getRow = function(rowIndex) { 18 | var result = []; 19 | for (var i = 0; i < rowIndex + 1; i++) { 20 | var arr = []; 21 | arr[0] = arr[i] = 1; 22 | for (var j = 1; j < i; j++) { 23 | arr[j] = result[i - 1][j - 1] + result[i - 1][j]; 24 | } 25 | result.push(arr); 26 | } 27 | return result[rowIndex]; 28 | }; 29 | -------------------------------------------------------------------------------- /121-best-time-to-buy-and-sell-stock/best-time-to-buy-and-sell-stock.js: -------------------------------------------------------------------------------- 1 | // Say you have an array for which the ith element is the price of a given stock on day i. 2 | // 3 | // If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit. 4 | // 5 | // Example 1: 6 | // 7 | // Input: [7, 1, 5, 3, 6, 4] 8 | // Output: 5 9 | // 10 | // max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price) 11 | // 12 | // 13 | // 14 | // Example 2: 15 | // 16 | // Input: [7, 6, 4, 3, 1] 17 | // Output: 0 18 | // 19 | // In this case, no transaction is done, i.e. max profit = 0. 20 | 21 | 22 | /** 23 | * @param {number[]} prices 24 | * @return {number} 25 | */ 26 | var maxProfit = function(prices) { 27 | if (prices.length <= 1) return 0; 28 | var min = prices[0]; 29 | var difference = prices[1] - min; 30 | for (var index = 2, len = prices.length; index <= len - 1; ++index) { 31 | min = Math.min(min, prices[index - 1]); 32 | difference = Math.max(difference, prices[index] - min); 33 | } 34 | if (difference < 0) { 35 | return 0; 36 | } 37 | return difference; 38 | }; 39 | -------------------------------------------------------------------------------- /122-best-time-to-buy-and-sell-stock-ii/best-time-to-buy-and-sell-stock-ii.js: -------------------------------------------------------------------------------- 1 | // Say you have an array for which the ith element is the price of a given stock on day i. 2 | // 3 | // Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again). 4 | 5 | 6 | /** 7 | * @param {number[]} prices 8 | * @return {number} 9 | */ 10 | var maxProfit = function(prices) { 11 | if (prices.length <= 1) return 0; 12 | var profits = 0; 13 | for (var i = 1, l = prices.length; i <= l - 1; ++i) { 14 | if (prices[i] > prices[i - 1]) { 15 | profits += prices[i] - prices[i - 1]; 16 | } 17 | } 18 | return profits; 19 | }; 20 | -------------------------------------------------------------------------------- /125-valid-palindrome/valid-palindrome.js: -------------------------------------------------------------------------------- 1 | // Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases. 2 | // 3 | // 4 | // 5 | // For example, 6 | // "A man, a plan, a canal: Panama" is a palindrome. 7 | // "race a car" is not a palindrome. 8 | // 9 | // 10 | // 11 | // Note: 12 | // Have you consider that the string might be empty? This is a good question to ask during an interview. 13 | // 14 | // For the purpose of this problem, we define empty string as valid palindrome. 15 | 16 | 17 | /** 18 | * @param {string} s 19 | * @return {boolean} 20 | */ 21 | var isPalindrome = function(s) { 22 | s = s.replace(/[^a-zA-Z0-9]*/g, '').toLowerCase(); 23 | for (var i = 0, l = s.length; i <= l / 2; ++i) { 24 | if (s[i] !== s[l - 1 - i]) { 25 | return false; 26 | } 27 | } 28 | return true; 29 | }; 30 | -------------------------------------------------------------------------------- /125-valid-palindrome/valid-palindrome.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | 3 | 4 | # Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases. 5 | # 6 | # 7 | # 8 | # For example, 9 | # "A man, a plan, a canal: Panama" is a palindrome. 10 | # "race a car" is not a palindrome. 11 | # 12 | # 13 | # 14 | # Note: 15 | # Have you consider that the string might be empty? This is a good question to ask during an interview. 16 | # 17 | # For the purpose of this problem, we define empty string as valid palindrome. 18 | 19 | 20 | class Solution(object): 21 | def isPalindrome(self, s): 22 | """ 23 | :type s: str 24 | :rtype: bool 25 | """ 26 | s = filter(str.isalnum, str(s.lower())) 27 | return s == s[::-1] 28 | -------------------------------------------------------------------------------- /128-longest-consecutive-sequence/longest-consecutive-sequence.js: -------------------------------------------------------------------------------- 1 | // Given an unsorted array of integers, find the length of the longest consecutive elements sequence. 2 | // 3 | // 4 | // For example, 5 | // Given [100, 4, 200, 1, 3, 2], 6 | // The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4. 7 | // 8 | // 9 | // Your algorithm should run in O(n) complexity. 10 | 11 | 12 | /** 13 | * @param {number[]} nums 14 | * @return {number} 15 | */ 16 | var longestConsecutive = function(nums) { 17 | if (nums.length === 1) return 1; 18 | nums.sort(function (prev, curr) { 19 | if (curr >= prev) return -1; 20 | return 1; 21 | }); 22 | var max = 1; 23 | var counter = 1; 24 | for (var i = 1, l = nums.length; i <= l - 1; ++i) { 25 | if (nums[i] === nums[i - 1]) continue; 26 | if (nums[i] - 1 === nums[i - 1]) { 27 | counter++; 28 | } else { 29 | diff = nums[i] - i; 30 | counter = 1; 31 | } 32 | max = Math.max(counter, max); 33 | } 34 | return max; 35 | }; 36 | 37 | -------------------------------------------------------------------------------- /136-single-number/single-number.js: -------------------------------------------------------------------------------- 1 | // Given an array of integers, every element appears twice except for one. Find that single one. 2 | // 3 | // 4 | // Note: 5 | // Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? 6 | 7 | 8 | /** 9 | * @param {number[]} nums 10 | * @return {number} 11 | */ 12 | var singleNumber = function(nums) { 13 | var single; 14 | for (var i = 0, l = nums.length; i < l; i++) { 15 | single ^= nums[i]; 16 | } 17 | return single; 18 | }; 19 | -------------------------------------------------------------------------------- /137-single-number-ii/single-number-ii.js: -------------------------------------------------------------------------------- 1 | // Given an array of integers, every element appears three times except for one. Find that single one. 2 | // 3 | // 4 | // 5 | // Note: 6 | // Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? 7 | 8 | 9 | /** 10 | * @param {number[]} nums 11 | * @return {number} 12 | */ 13 | var singleNumber = function(nums) { 14 | nums.sort(function (prev, next) { 15 | if (next >= prev) return -1; 16 | return 1; 17 | }); 18 | for (var i = 1, l = nums.length; i <= l - 2; ++i) { 19 | if (nums[i] !== nums[i - 1] && nums[i] !== nums[i + 1]) { 20 | return nums[i]; 21 | } 22 | } 23 | if (nums[0] === nums[1]) { 24 | return nums[i]; 25 | } 26 | return nums[0]; 27 | }; 28 | -------------------------------------------------------------------------------- /141-linked-list-cycle/linked-list-cycle.js: -------------------------------------------------------------------------------- 1 | // Given a linked list, determine if it has a cycle in it. 2 | // 3 | // 4 | // 5 | // Follow up: 6 | // Can you solve it without using extra space? 7 | 8 | 9 | /** 10 | * Definition for singly-linked list. 11 | * function ListNode(val) { 12 | * this.val = val; 13 | * this.next = null; 14 | * } 15 | */ 16 | 17 | /** 18 | * @param {ListNode} head 19 | * @return {boolean} 20 | */ 21 | var hasCycle = function(head) { 22 | if(!head) return false; 23 | var faster = head; 24 | var slower = head; 25 | while (faster && faster.next) { 26 | faster = faster.next.next; 27 | slower = slower.next; 28 | if (slower === faster) return true; 29 | } 30 | return false; 31 | }; 32 | -------------------------------------------------------------------------------- /142-linked-list-cycle-ii/linked-list-cycle-ii.js: -------------------------------------------------------------------------------- 1 | // Given a linked list, return the node where the cycle begins. If there is no cycle, return null. 2 | // 3 | // 4 | // 5 | // Note: Do not modify the linked list. 6 | // 7 | // 8 | // Follow up: 9 | // Can you solve it without using extra space? 10 | 11 | 12 | /** 13 | * Definition for singly-linked list. 14 | * function ListNode(val) { 15 | * this.val = val; 16 | * this.next = null; 17 | * } 18 | */ 19 | 20 | /** 21 | * @param {ListNode} head 22 | * @return {ListNode} 23 | */ 24 | var detectCycle = function(head) { 25 | if(!head) return null; 26 | var hash = {}; 27 | while(head) { 28 | if (hash[head.val]) { 29 | for(let i = 0; i < hash[head.val].length; i++) { 30 | if (head === hash[head.val][i]) { 31 | return hash[head.val][i]; 32 | } 33 | } 34 | hash[head.val].push(head); 35 | } else { 36 | hash[head.val] = [head]; 37 | } 38 | head = head.next; 39 | } 40 | return null; 41 | }; 42 | -------------------------------------------------------------------------------- /143-reorder-list/reorder-list.js: -------------------------------------------------------------------------------- 1 | // Given a singly linked list L: L0→L1→…→Ln-1→Ln, 2 | // reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→… 3 | // 4 | // 5 | // You must do this in-place without altering the nodes' values. 6 | // 7 | // 8 | // For example, 9 | // Given {1,2,3,4}, reorder it to {1,4,2,3}. 10 | 11 | 12 | /** 13 | * Definition for singly-linked list. 14 | * function ListNode(val) { 15 | * this.val = val; 16 | * this.next = null; 17 | * } 18 | */ 19 | /** 20 | * @param {ListNode} head 21 | * @return {void} Do not return anything, modify head in-place instead. 22 | */ 23 | 24 | var reverseList = function (head) { 25 | if (head === null || head.next === null) return head; 26 | var prev = new ListNode(0); 27 | prev.next = head; 28 | head = prev; 29 | var cur = prev.next; 30 | while(cur.next !== null) { 31 | var tmp = cur.next; 32 | cur.next = tmp.next; 33 | tmp.next = prev.next; 34 | prev.next = tmp; 35 | } 36 | return prev.next; 37 | } 38 | var reorderList = function(head) { 39 | if (!head || !head.next) return; 40 | var fast = head; 41 | var slow = head; 42 | while (fast && fast.next) { 43 | fast = fast.next.next; 44 | slow = slow.next; 45 | } 46 | var second = reverseList(slow.next); 47 | slow.next = null; 48 | var first = head; 49 | while (second) { 50 | var temp = second.next; 51 | second.next = first.next; 52 | first.next = second; 53 | 54 | first = first.next.next; 55 | second = temp; 56 | } 57 | 58 | }; 59 | -------------------------------------------------------------------------------- /144-binary-tree-preorder-traversal/binary-tree-preorder-traversal.js: -------------------------------------------------------------------------------- 1 | // Given a binary tree, return the preorder traversal of its nodes' values. 2 | // 3 | // 4 | // For example: 5 | // Given binary tree {1,#,2,3}, 6 | // 7 | // 1 8 | // \ 9 | // 2 10 | // / 11 | // 3 12 | // 13 | // 14 | // 15 | // return [1,2,3]. 16 | // 17 | // 18 | // Note: Recursive solution is trivial, could you do it iteratively? 19 | 20 | 21 | /** 22 | * Definition for a binary tree node. 23 | * function TreeNode(val) { 24 | * this.val = val; 25 | * this.left = this.right = null; 26 | * } 27 | */ 28 | /** 29 | * @param {TreeNode} root 30 | * @return {number[]} 31 | */ 32 | 33 | var dfs = function (result, node) { 34 | if (!node) return ; 35 | result.push(node.val); 36 | dfs(result, node.left); 37 | dfs(result, node.right); 38 | return ; 39 | }; 40 | var preorderTraversal = function(root) { 41 | var result = []; 42 | dfs(result, root); 43 | return result; 44 | }; 45 | -------------------------------------------------------------------------------- /145-binary-tree-postorder-traversal/binary-tree-postorder-traversal.js: -------------------------------------------------------------------------------- 1 | // Given a binary tree, return the postorder traversal of its nodes' values. 2 | // 3 | // 4 | // For example: 5 | // Given binary tree {1,#,2,3}, 6 | // 7 | // 1 8 | // \ 9 | // 2 10 | // / 11 | // 3 12 | // 13 | // 14 | // 15 | // return [3,2,1]. 16 | // 17 | // 18 | // Note: Recursive solution is trivial, could you do it iteratively? 19 | 20 | 21 | /** 22 | * Definition for a binary tree node. 23 | * function TreeNode(val) { 24 | * this.val = val; 25 | * this.left = this.right = null; 26 | * } 27 | */ 28 | /** 29 | * @param {TreeNode} root 30 | * @return {number[]} 31 | */ 32 | var dfs = function (result, node) { 33 | if (!node) return ; 34 | dfs(result, node.left); 35 | dfs(result, node.right); 36 | result.push(node.val); 37 | return ; 38 | }; 39 | var postorderTraversal = function(root) { 40 | var result = []; 41 | dfs(result, root); 42 | return result; 43 | }; 44 | -------------------------------------------------------------------------------- /147-insertion-sort-list/insertion-sort-list.js: -------------------------------------------------------------------------------- 1 | // Sort a linked list using insertion sort. 2 | 3 | 4 | /** 5 | * Definition for singly-linked list. 6 | * function ListNode(val) { 7 | * this.val = val; 8 | * this.next = null; 9 | * } 10 | */ 11 | /** 12 | * @param {ListNode} head 13 | * @return {ListNode} 14 | */ 15 | 16 | var insetList = function (sortedList, item) { 17 | if (!sortedList) return null; 18 | var fakeHead = new ListNode(-1); 19 | fakeHead.next = sortedList; 20 | sortedList = fakeHead; 21 | while (sortedList.next) { 22 | if (item.val < sortedList.next.val) { 23 | item.next = sortedList.next; 24 | sortedList.next = item; 25 | return fakeHead.next; 26 | } 27 | sortedList = sortedList.next; 28 | } 29 | sortedList.next = item; 30 | return fakeHead.next; 31 | } 32 | var insertionSortList = function(head) { 33 | if (!head || !head.next) return head; 34 | var sorted = head; 35 | var result = sorted; 36 | var unsorted = head.next; 37 | sorted.next = null; 38 | while (unsorted) { 39 | var temp = unsorted.next; 40 | unsorted.next = null; 41 | 42 | sorted = insetList(sorted, unsorted); 43 | unsorted = temp; 44 | } 45 | return sorted; 46 | }; 47 | -------------------------------------------------------------------------------- /150-evaluate-reverse-polish-notation/evaluate-reverse-polish-notation.js: -------------------------------------------------------------------------------- 1 | // Evaluate the value of an arithmetic expression in Reverse Polish Notation. 2 | // 3 | // 4 | // 5 | // Valid operators are +, -, *, /. Each operand may be an integer or another expression. 6 | // 7 | // 8 | // 9 | // Some examples: 10 | // 11 | // ["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9 12 | // ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6 13 | 14 | 15 | const map = { 16 | '+': add, 17 | '-': subtract, 18 | '*': multiply, 19 | '/': divide 20 | }; 21 | function evalRPN(tokens) { 22 | let stack = []; 23 | 24 | for (let n of tokens) { 25 | // if operator function exists, 26 | // execute it on the two most recent numbers 27 | if (map[n]) { 28 | let fn = map[n]; 29 | let y = stack.pop(); 30 | let x = stack.pop(); 31 | 32 | stack.push(fn(x, y)); 33 | } else { 34 | stack.push(Number(n)); 35 | } 36 | } 37 | 38 | return head(stack); 39 | } 40 | 41 | // helper methods 42 | function add(x, y) { 43 | return x + y; 44 | } 45 | 46 | function subtract(x, y) { 47 | return x - y; 48 | } 49 | 50 | function multiply(x, y) { 51 | return x * y; 52 | } 53 | 54 | function divide(x, y) { 55 | return parseInt(x / y); 56 | } 57 | 58 | function head(list) { 59 | return list[0]; 60 | } 61 | -------------------------------------------------------------------------------- /151-reverse-words-in-a-string/reverse-words-in-a-string.js: -------------------------------------------------------------------------------- 1 | // Given an input string, reverse the string word by word. 2 | // 3 | // 4 | // 5 | // For example, 6 | // Given s = "the sky is blue", 7 | // return "blue is sky the". 8 | // 9 | // 10 | // 11 | // Update (2015-02-12): 12 | // For C programmers: Try to solve it in-place in O(1) space. 13 | // 14 | // 15 | // click to show clarification. 16 | // 17 | // Clarification: 18 | // 19 | // 20 | // 21 | // What constitutes a word? 22 | // A sequence of non-space characters constitutes a word. 23 | // Could the input string contain leading or trailing spaces? 24 | // Yes. However, your reversed string should not contain leading or trailing spaces. 25 | // How about multiple spaces between two words? 26 | // Reduce them to a single space in the reversed string. 27 | 28 | 29 | /** 30 | * @param {string} str 31 | * @returns {string} 32 | */ 33 | var reverseWords = function(str) { 34 | return str.split(" ").reverse().filter(function(v){return v}).join(" "); 35 | }; 36 | -------------------------------------------------------------------------------- /152-maximum-product-subarray/maximum-product-subarray.js: -------------------------------------------------------------------------------- 1 | // Find the contiguous subarray within an array (containing at least one number) which has the largest product. 2 | // 3 | // 4 | // 5 | // For example, given the array [2,3,-2,4], 6 | // the contiguous subarray [2,3] has the largest product = 6. 7 | 8 | 9 | /** 10 | * @param {number[]} nums 11 | * @return {number} 12 | */ 13 | var maxProduct = function(nums) { 14 | var max = nums[0]; 15 | var cache = 1; 16 | for (var i = 0; i < nums.length; i++) { 17 | if (nums[i] === 0){ 18 | cache = 1; 19 | max = Math.max(max, 0); 20 | } else { 21 | cache *= nums[i]; 22 | max = Math.max(max, cache); 23 | } 24 | } 25 | cache = 1; 26 | for ( i = nums.length - 1; i > 0; i--) { 27 | if (nums[i] === 0){ 28 | cache = 1; 29 | max = Math.max(max, 0); 30 | } else { 31 | cache *= nums[i]; 32 | max = Math.max(max, cache); 33 | } 34 | } 35 | return max; 36 | } 37 | 38 | 39 | -------------------------------------------------------------------------------- /153-find-minimum-in-rotated-sorted-array/find-minimum-in-rotated-sorted-array.js: -------------------------------------------------------------------------------- 1 | // Suppose a sorted array is rotated at some pivot unknown to you beforehand. 2 | // 3 | // (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2). 4 | // 5 | // Find the minimum element. 6 | // 7 | // You may assume no duplicate exists in the array. 8 | 9 | 10 | /** 11 | * @param {number[]} nums 12 | * @return {number} 13 | */ 14 | var findMin = function(nums) { 15 | var left_point = 0; 16 | var right_point = nums.length - 1; 17 | var mid; 18 | while(left_point < right_point - 1) { 19 | mid = left_point + Math.floor((right_point - left_point) / 2); 20 | if (nums[mid] < nums[right_point]) { 21 | right_point = mid; 22 | } else { 23 | left_point = mid; 24 | } 25 | } 26 | if (nums[left_point] > nums[right_point]) { 27 | return nums[right_point]; 28 | } 29 | return nums[left_point]; 30 | }; 31 | -------------------------------------------------------------------------------- /154-find-minimum-in-rotated-sorted-array-ii/find-minimum-in-rotated-sorted-array-ii.js: -------------------------------------------------------------------------------- 1 | // Follow up for "Find Minimum in Rotated Sorted Array": 2 | // What if duplicates are allowed? 3 | // 4 | // Would this affect the run-time complexity? How and why? 5 | // 6 | // 7 | // Suppose a sorted array is rotated at some pivot unknown to you beforehand. 8 | // 9 | // (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2). 10 | // 11 | // Find the minimum element. 12 | // 13 | // The array may contain duplicates. 14 | 15 | 16 | /** 17 | * @param {number[]} nums 18 | * @return {number} 19 | */ 20 | var findMin = function(nums) { 21 | var left_point = 0; 22 | var right_point = nums.length - 1; 23 | var mid; 24 | while(left_point < right_point - 1) { 25 | mid = left_point + Math.floor((right_point - left_point) / 2); 26 | if (nums[mid] < nums[right_point]) { 27 | right_point = mid; 28 | } else if (nums[mid] > nums[right_point]){ 29 | left_point = mid; 30 | } else if(nums[mid] === nums[right_point]){ 31 | right_point--; 32 | } 33 | } 34 | if (nums[left_point] > nums[right_point]) { 35 | return nums[right_point]; 36 | } 37 | return nums[left_point]; 38 | }; 39 | -------------------------------------------------------------------------------- /160-intersection-of-two-linked-lists/intersection-of-two-linked-lists.js: -------------------------------------------------------------------------------- 1 | // Write a program to find the node at which the intersection of two singly linked lists begins. 2 | // 3 | // For example, the following two linked lists: 4 | // 5 | // A: a1 → a2 6 | // ↘ 7 | // c1 → c2 → c3 8 | // ↗ 9 | // B: b1 → b2 → b3 10 | // 11 | // begin to intersect at node c1. 12 | // 13 | // Notes: 14 | // 15 | // If the two linked lists have no intersection at all, return null. 16 | // The linked lists must retain their original structure after the function returns. 17 | // You may assume there are no cycles anywhere in the entire linked structure. 18 | // Your code should preferably run in O(n) time and use only O(1) memory. 19 | // 20 | // 21 | // 22 | // Credits:Special thanks to @stellari for adding this problem and creating all test cases. 23 | 24 | 25 | /** 26 | * Definition for singly-linked list. 27 | * function ListNode(val) { 28 | * this.val = val; 29 | * this.next = null; 30 | * } 31 | */ 32 | 33 | /** 34 | * @param {ListNode} headA 35 | * @param {ListNode} headB 36 | * @return {ListNode} 37 | */ 38 | 39 | var getIntersectionNode = function(headA, headB) { 40 | if (!headA || !headB) return null; 41 | var p1 = headA; 42 | var p2 = headB; 43 | while (p1 && p2 && p1 !== p2) { 44 | p1 = p1.next; 45 | p2 = p2.next; 46 | 47 | if (p1 == p2) return p1; 48 | if (!p1) p1 = headB; 49 | if (!p2) p2 = headA; 50 | } 51 | return p1; 52 | }; 53 | 54 | 55 | -------------------------------------------------------------------------------- /162-find-peak-element/find-peak-element.js: -------------------------------------------------------------------------------- 1 | // A peak element is an element that is greater than its neighbors. 2 | // 3 | // Given an input array where num[i] ≠ num[i+1], find a peak element and return its index. 4 | // 5 | // The array may contain multiple peaks, in that case return the index to any one of the peaks is fine. 6 | // 7 | // You may imagine that num[-1] = num[n] = -∞. 8 | // 9 | // For example, in array [1, 2, 3, 1], 3 is a peak element and your function should return the index number 2. 10 | // 11 | // click to show spoilers. 12 | // 13 | // Note: 14 | // Your solution should be in logarithmic complexity. 15 | // 16 | // 17 | // Credits:Special thanks to @ts for adding this problem and creating all test cases. 18 | 19 | 20 | /** 21 | * @param {number[]} nums 22 | * @return {number} 23 | */ 24 | var findPeakElement = function(nums) { 25 | if (nums.length === 1) return 0; 26 | if (nums[0] > nums[1]) return 0; 27 | for (var i = 1, l = nums.length - 1; i < l; i++) { 28 | if (nums[i] > nums[i + 1] && nums[i] > nums[i - 1]) { 29 | return i; 30 | } 31 | } 32 | if (nums[nums.length - 1] > nums[nums.length - 2]) return nums.length - 1; 33 | }; 34 | -------------------------------------------------------------------------------- /167-two-sum-ii-input-array-is-sorted/two-sum-ii-input-array-is-sorted.js: -------------------------------------------------------------------------------- 1 | // Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number. 2 | // 3 | // The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based. 4 | // 5 | // You may assume that each input would have exactly one solution. 6 | // 7 | // 8 | // Input: numbers={2, 7, 11, 15}, target=9 9 | // Output: index1=1, index2=2 10 | 11 | 12 | /** 13 | * @param {number[]} numbers 14 | * @param {number} target 15 | * @return {number[]} 16 | */ 17 | var twoSum = function(numbers, target) { 18 | const hashMap = {}; 19 | for (var i = 0, l = numbers.length; i < l; i++) { 20 | var value = target - numbers[i]; 21 | if (hashMap[value] !== undefined) { 22 | var before = hashMap[value] + 1; 23 | return [before, i + 1]; 24 | } 25 | hashMap[numbers[i]] = i; 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /168-excel-sheet-column-title/excel-sheet-column-title.js: -------------------------------------------------------------------------------- 1 | // Given a positive integer, return its corresponding column title as appear in an Excel sheet. 2 | // 3 | // For example: 4 | // 5 | // 1 -> A 6 | // 2 -> B 7 | // 3 -> C 8 | // ... 9 | // 26 -> Z 10 | // 27 -> AA 11 | // 28 -> AB 12 | // 13 | // Credits:Special thanks to @ifanchu for adding this problem and creating all test cases. 14 | 15 | 16 | /** 17 | * @param {number} n 18 | * @return {string} 19 | */ 20 | var convertToTitle = function(n) { 21 | var result = ''; 22 | while (n) { 23 | var code = String.fromCharCode( (n - 1) % 26 + 'A'.charCodeAt() ); 24 | n = Math.floor((n - 1) / 26); 25 | result = code + result; 26 | } 27 | return result; 28 | }; 29 | -------------------------------------------------------------------------------- /169-majority-element/majority-element.js: -------------------------------------------------------------------------------- 1 | // Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times. 2 | // 3 | // You may assume that the array is non-empty and the majority element always exist in the array. 4 | // 5 | // Credits:Special thanks to @ts for adding this problem and creating all test cases. 6 | 7 | 8 | /** 9 | * @param {number[]} nums 10 | * @return {number} 11 | */ 12 | var majorityElement = function(nums) { 13 | var major = nums[0], count = 1; 14 | for(var i = 1, l = nums.length; i < l; i++){ 15 | if(count === 0){ 16 | count++; 17 | major = nums[i]; 18 | }else if(major === nums[i]){ 19 | count++; 20 | }else count--; 21 | 22 | } 23 | return major; 24 | }; 25 | -------------------------------------------------------------------------------- /171-excel-sheet-column-number/excel-sheet-column-number.js: -------------------------------------------------------------------------------- 1 | // Related to question Excel Sheet Column Title 2 | // Given a column title as appear in an Excel sheet, return its corresponding column number. 3 | // 4 | // For example: 5 | // A -> 1 6 | // B -> 2 7 | // C -> 3 8 | // ... 9 | // Z -> 26 10 | // AA -> 27 11 | // AB -> 28 12 | // 13 | // Credits:Special thanks to @ts for adding this problem and creating all test cases. 14 | 15 | 16 | /** 17 | * @param {string} s 18 | * @return {number} 19 | */ 20 | var titleToNumber = function(s) { 21 | var res = 0; 22 | for (var i = 0, l = s.length; i < l; i++) { 23 | var num = s[i].charCodeAt() - 64; 24 | res += num * Math.pow(26, s.length - i - 1); 25 | } 26 | return res; 27 | }; 28 | -------------------------------------------------------------------------------- /172-factorial-trailing-zeroes/factorial-trailing-zeroes.js: -------------------------------------------------------------------------------- 1 | // Given an integer n, return the number of trailing zeroes in n!. 2 | // 3 | // Note: Your solution should be in logarithmic time complexity. 4 | // 5 | // Credits:Special thanks to @ts for adding this problem and creating all test cases. 6 | 7 | 8 | /** 9 | * @param {number} n 10 | * @return {number} 11 | */ 12 | var trailingZeroes = function(n) { 13 | if (n === 0) return 0; 14 | var res = 0; 15 | while (n !== 0) { 16 | n = parseInt(n / 5); 17 | res += n; 18 | } 19 | return res; 20 | }; 21 | -------------------------------------------------------------------------------- /189-rotate-array/rotate-array.js: -------------------------------------------------------------------------------- 1 | // Rotate an array of n elements to the right by k steps. 2 | // For example, with n = 7 and k = 3, the array [1,2,3,4,5,6,7] is rotated to [5,6,7,1,2,3,4]. 3 | // 4 | // Note: 5 | // Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem. 6 | // 7 | // 8 | // [show hint] 9 | // Hint: 10 | // Could you do it in-place with O(1) extra space? 11 | // 12 | // 13 | // Related problem: Reverse Words in a String II 14 | // 15 | // Credits:Special thanks to @Freezen for adding this problem and creating all test cases. 16 | 17 | 18 | /** 19 | * @param {number[]} nums 20 | * @param {number} k 21 | * @return {void} Do not return anything, modify nums in-place instead. 22 | */ 23 | var rotate = function(nums, k) { 24 | var rotated = []; 25 | var length = nums.length; 26 | if (length < k) {k = k % nums.length;} 27 | for (var i = length - k; i < length; i++) { 28 | rotated.push(nums[i]); 29 | } 30 | for (i = rotated.length - 1; i >= 0; i--) { 31 | nums.unshift(rotated[i]); 32 | } 33 | nums.length = length; 34 | }; 35 | -------------------------------------------------------------------------------- /190-reverse-bits/reverse-bits.js: -------------------------------------------------------------------------------- 1 | // Reverse bits of a given 32 bits unsigned integer. 2 | // 3 | // For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), return 964176192 (represented in binary as 00111001011110000010100101000000). 4 | // 5 | // 6 | // Follow up: 7 | // If this function is called many times, how would you optimize it? 8 | // 9 | // 10 | // Related problem: Reverse Integer 11 | // 12 | // Credits:Special thanks to @ts for adding this problem and creating all test cases. 13 | 14 | 15 | /** 16 | * @param {number} n - a positive integer 17 | * @return {number} - a positive integer 18 | */ 19 | var reverseBits = function(n) { 20 | var str = n.toString(2); 21 | for (var i = 32 - str.length - 1; i >= 0; --i) { 22 | str = '0' + str; 23 | } 24 | var res = Array.prototype.slice.call(str).reverse().join(''); 25 | return(parseInt(res, 2)); 26 | }; 27 | -------------------------------------------------------------------------------- /198-house-robber/house-robber.js: -------------------------------------------------------------------------------- 1 | // You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night. 2 | // 3 | // Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police. 4 | // 5 | // Credits:Special thanks to @ifanchu for adding this problem and creating all test cases. Also thanks to @ts for adding additional test cases. 6 | 7 | 8 | /** 9 | * @param {number[]} nums 10 | * @return {number} 11 | */ 12 | var rob = function(nums) { 13 | var len = nums.length; 14 | if (len === 0) return 0; 15 | if (len === 1) return nums[0]; 16 | 17 | var max = 0; 18 | var pre = 0; 19 | for (var i = len - 1; i >= 0; --i) { 20 | var preMax = max; 21 | max = Math.max(max, pre+nums[i]); 22 | pre = preMax; 23 | } 24 | return max; 25 | }; 26 | -------------------------------------------------------------------------------- /202-happy-number/happy-number.js: -------------------------------------------------------------------------------- 1 | // Write an algorithm to determine if a number is "happy". 2 | // 3 | // A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers. 4 | // 5 | // Example: 19 is a happy number 6 | // 7 | // 8 | // 12 + 92 = 82 9 | // 82 + 22 = 68 10 | // 62 + 82 = 100 11 | // 12 + 02 + 02 = 1 12 | // 13 | // 14 | // Credits:Special thanks to @mithmatt and @ts for adding this problem and creating all test cases. 15 | 16 | 17 | /** 18 | * @param {number} n 19 | * @return {boolean} 20 | */ 21 | var fac = function (num) { 22 | var sum = 0; 23 | num.toString().split('').forEach((item) => { 24 | sum += Math.pow(item, 2); 25 | }); 26 | return sum; 27 | } 28 | var isHappy = function(n) { 29 | var hashMap = {}; 30 | var result = fac(n); 31 | while(!hashMap[result]) { 32 | hashMap[result] = true; 33 | result = fac(result); 34 | } 35 | if (result === 1) { return true; } 36 | return false; 37 | }; 38 | 39 | -------------------------------------------------------------------------------- /203-remove-linked-list-elements/remove-linked-list-elements.js: -------------------------------------------------------------------------------- 1 | // Remove all elements from a linked list of integers that have value val. 2 | // 3 | // Example 4 | // Given: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6 5 | // Return: 1 --> 2 --> 3 --> 4 --> 5 6 | // 7 | // 8 | // Credits:Special thanks to @mithmatt for adding this problem and creating all test cases. 9 | 10 | 11 | /** 12 | * Definition for singly-linked list. 13 | * function ListNode(val) { 14 | * this.val = val; 15 | * this.next = null; 16 | * } 17 | */ 18 | /** 19 | * @param {ListNode} head 20 | * @param {number} val 21 | * @return {ListNode} 22 | */ 23 | var removeElements = function(head, val) { 24 | var point = new ListNode(-1); 25 | var res = point; 26 | while (head !== null) { 27 | if (head.val !== val) { 28 | point.next = head; 29 | point = point.next; 30 | } 31 | head = head.next; 32 | } 33 | point.next = null; 34 | return res.next; 35 | }; 36 | -------------------------------------------------------------------------------- /205-isomorphic-strings/isomorphic-strings.js: -------------------------------------------------------------------------------- 1 | // Given two strings s and t, determine if they are isomorphic. 2 | // 3 | // Two strings are isomorphic if the characters in s can be replaced to get t. 4 | // 5 | // All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character but a character may map to itself. 6 | // 7 | // For example, 8 | // Given "egg", "add", return true. 9 | // 10 | // Given "foo", "bar", return false. 11 | // 12 | // Given "paper", "title", return true. 13 | // 14 | // Note: 15 | // You may assume both s and t have the same length. 16 | 17 | 18 | /** 19 | * @param {string} s 20 | * @param {string} t 21 | * @return {boolean} 22 | */ 23 | var isIsomorphic = function(s, t) { 24 | const hashMapS = {}; 25 | const hashMapT = {}; 26 | for (var i = 0, l = s.length; i < l; i++) { 27 | var sc = s.charAt(i); 28 | var tc = t.charAt(i); 29 | if (hashMapS[sc] === undefined && hashMapT[tc] === undefined) { 30 | hashMapS[sc] = tc; 31 | hashMapT[tc] = sc; 32 | } else if (hashMapS[sc] !== tc) { 33 | return false; 34 | } 35 | } 36 | return true; 37 | }; 38 | -------------------------------------------------------------------------------- /206-reverse-linked-list/reverse-linked-list.js: -------------------------------------------------------------------------------- 1 | // Reverse a singly linked list. 2 | // 3 | // click to show more hints. 4 | // 5 | // Hint: 6 | // A linked list can be reversed either iteratively or recursively. Could you implement both? 7 | 8 | 9 | /** 10 | * Definition for singly-linked list. 11 | * function ListNode(val) { 12 | * this.val = val; 13 | * this.next = null; 14 | * } 15 | */ 16 | /** 17 | * @param {ListNode} head 18 | * @return {ListNode} 19 | */ 20 | var reverseList = function(head) { 21 | var temp = null; 22 | var next = null; 23 | while(head !== null) { 24 | temp = new ListNode(head.val); 25 | temp.next = next; 26 | next = temp; 27 | head = head.next; 28 | } 29 | return temp; 30 | }; 31 | -------------------------------------------------------------------------------- /217-contains-duplicate/contains-duplicate.js: -------------------------------------------------------------------------------- 1 | // Given an array of integers, find if the array contains any duplicates. Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct. 2 | 3 | 4 | /** 5 | * @param {number[]} nums 6 | * @return {boolean} 7 | */ 8 | var containsDuplicate = function(nums) { 9 | const hashTab = {} 10 | for (var i = 0, l = nums.length; i < l; i++) { 11 | if (!hashTab[nums[i]]) { 12 | hashTab[nums[i]] = true; 13 | } else { 14 | return true; 15 | } 16 | } 17 | return false; 18 | }; 19 | -------------------------------------------------------------------------------- /219-contains-duplicate-ii/contains-duplicate-ii.js: -------------------------------------------------------------------------------- 1 | // Given an array of integers and an integer k, find out whether there are two distinct indices i and j in the array such that nums[i] = nums[j] and the difference between i and j is at most k. 2 | 3 | 4 | var containsNearbyDuplicate = function(nums, k) { 5 | const hashTab = {}; 6 | for (var i = 0, l = nums.length; i < l; i++) { 7 | if (hashTab[nums[i]] !== undefined && (i - hashTab[nums[i]]) <= k && (i - hashTab[nums[i]]) !== 0) { 8 | return true; 9 | } 10 | hashTab[nums[i]] = i; 11 | } 12 | return false; 13 | }; 14 | -------------------------------------------------------------------------------- /223-rectangle-area/rectangle-area.js: -------------------------------------------------------------------------------- 1 | // Find the total area covered by two rectilinear rectangles in a 2D plane. 2 | // Each rectangle is defined by its bottom left corner and top right corner as shown in the figure. 3 | // 4 | // 5 | // 6 | // 7 | // Assume that the total area is never beyond the maximum possible value of int. 8 | // 9 | // 10 | // Credits:Special thanks to @mithmatt for adding this problem, creating the above image and all test cases. 11 | 12 | 13 | /** 14 | * @param {number} A 15 | * @param {number} B 16 | * @param {number} C 17 | * @param {number} D 18 | * @param {number} E 19 | * @param {number} F 20 | * @param {number} G 21 | * @param {number} H 22 | * @return {number} 23 | */ 24 | var computeArea = function(A, B, C, D, E, F, G, H) { 25 | var width = (Math.min(C, G) - Math.max(A, E)); 26 | var height = (Math.min(D, H) - Math.max(B, F)); 27 | var cover = width * height; 28 | if (G <= A || D <= F || B >= H || E >= C) { 29 | cover = 0; 30 | } 31 | return ((C - A) * (D - B)) + ((G - E) * (H - F)) - cover; 32 | }; 33 | -------------------------------------------------------------------------------- /225-implement-stack-using-queues/implement-stack-using-queues.js: -------------------------------------------------------------------------------- 1 | // Implement the following operations of a stack using queues. 2 | // 3 | // 4 | // push(x) -- Push element x onto stack. 5 | // 6 | // 7 | // pop() -- Removes the element on top of the stack. 8 | // 9 | // 10 | // top() -- Get the top element. 11 | // 12 | // 13 | // empty() -- Return whether the stack is empty. 14 | // 15 | // 16 | // Notes: 17 | // 18 | // You must use only standard operations of a queue -- which means only push to back, peek/pop from front, size, and is empty operations are valid. 19 | // Depending on your language, queue may not be supported natively. You may simulate a queue by using a list or deque (double-ended queue), as long as you use only standard operations of a queue. 20 | // You may assume that all operations are valid (for example, no pop or top operations will be called on an empty stack). 21 | // 22 | // 23 | // 24 | // 25 | // Update (2015-06-11): 26 | // The class name of the Java function had been updated to MyStack instead of Stack. 27 | // 28 | // 29 | // Credits:Special thanks to @jianchao.li.fighter for adding this problem and all test cases. 30 | 31 | 32 | /** 33 | * @constructor 34 | */ 35 | var Stack = function() { 36 | this.arr = []; 37 | }; 38 | 39 | /** 40 | * @param {number} x 41 | * @returns {void} 42 | */ 43 | Stack.prototype.push = function(x) { 44 | this.arr.push(x); 45 | }; 46 | 47 | /** 48 | * @returns {void} 49 | */ 50 | Stack.prototype.pop = function() { 51 | this.arr.pop(); 52 | }; 53 | 54 | /** 55 | * @returns {number} 56 | */ 57 | Stack.prototype.top = function() { 58 | return this.arr[this.arr.length - 1]; 59 | }; 60 | 61 | /** 62 | * @returns {boolean} 63 | */ 64 | Stack.prototype.empty = function() { 65 | return this.arr.length === 0; 66 | }; 67 | -------------------------------------------------------------------------------- /226-invert-binary-tree/invert-binary-tree.js: -------------------------------------------------------------------------------- 1 | // Invert a binary tree. 2 | // 4 3 | // / \ 4 | // 2 7 5 | // / \ / \ 6 | // 1 3 6 9 7 | // 8 | // to 9 | // 4 10 | // / \ 11 | // 7 2 12 | // / \ / \ 13 | // 9 6 3 1 14 | // 15 | // Trivia: 16 | // This problem was inspired by this original tweet by Max Howell: 17 | // Google: 90% of our engineers use the software you wrote (Homebrew), but you can’t invert a binary tree on a whiteboard so fuck off. 18 | 19 | 20 | /** 21 | * Definition for a binary tree node. 22 | * function TreeNode(val) { 23 | * this.val = val; 24 | * this.left = this.right = null; 25 | * } 26 | */ 27 | /** 28 | * @param {TreeNode} root 29 | * @return {TreeNode} 30 | */ 31 | var invertTree = function(root) { 32 | if (!root) return null; 33 | var temp = root.left; 34 | root.left = root.right; 35 | root.right = temp; 36 | if (root.left) invertTree(root.left); 37 | if (root.right) invertTree(root.right); 38 | return root; 39 | }; 40 | -------------------------------------------------------------------------------- /227-basic-calculator-ii/basic-calculator-ii.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | 3 | 4 | # Implement a basic calculator to evaluate a simple expression string. 5 | # 6 | # The expression string contains only non-negative integers, +, -, *, / operators and empty spaces . The integer division should truncate toward zero. 7 | # 8 | # You may assume that the given expression is always valid. 9 | # 10 | # Some examples: 11 | # 12 | # "3+2*2" = 7 13 | # " 3/2 " = 1 14 | # " 3+5 / 2 " = 5 15 | # 16 | # 17 | # 18 | # 19 | # Note: Do not use the eval built-in library function. 20 | # 21 | # 22 | # Credits:Special thanks to @ts for adding this problem and creating all test cases. 23 | 24 | 25 | class Solution(object): 26 | def calculate(self, s): 27 | """ 28 | :type s: str 29 | :rtype: int 30 | """ 31 | if not s: 32 | return 0 33 | stack, num ,sign= [], 0, '+' 34 | for i in xrange(len(s)): 35 | if s[i].isdigit(): 36 | num = num*10+ord(s[i])-ord('0') 37 | if (not s[i].isdigit() and not s[i].isspace()) or i == len(s)-1: 38 | if sign == '-': 39 | stack.append(-num) 40 | elif sign == '+': 41 | stack.append(num) 42 | elif sign == '*': 43 | stack.append(stack.pop()*num) 44 | else: 45 | tmp = stack.pop() 46 | if tmp < 0 and abs(tmp)%num != 0: 47 | stack.append(tmp/num+1) 48 | else: 49 | stack.append(tmp/num) 50 | sign = s[i] 51 | num = 0 52 | return sum(stack) 53 | -------------------------------------------------------------------------------- /228-summary-ranges/summary-ranges.js: -------------------------------------------------------------------------------- 1 | // Given a sorted integer array without duplicates, return the summary of its ranges. 2 | // 3 | // 4 | // For example, given [0,1,2,4,5,7], return ["0->2","4->5","7"]. 5 | // 6 | // 7 | // Credits:Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases. 8 | 9 | 10 | /** 11 | * @param {number[]} nums 12 | * @return {string[]} 13 | */ 14 | var summaryRanges = function(nums) { 15 | if (nums.length === 0) return []; 16 | 17 | var before = 0; 18 | var index = 0; 19 | var result = []; 20 | while(index < nums.length) { 21 | if(nums[index] - nums[before] !== (index - before)) { 22 | if (nums[index - 1] !== nums[before]) { 23 | result.push(nums[before] + '->' + nums[index - 1]); 24 | } else { 25 | result.push(nums[before] + ''); 26 | } 27 | 28 | before = index; 29 | } 30 | index++; 31 | if (index === nums.length) { 32 | if (nums[before] === nums[index - 1]) { 33 | result.push(nums[index - 1] + ''); 34 | } else { 35 | result.push(nums[before] + '->' + nums[index - 1]) 36 | } 37 | return result; 38 | } 39 | } 40 | }; 41 | -------------------------------------------------------------------------------- /229-majority-element-ii/majority-element-ii.js: -------------------------------------------------------------------------------- 1 | // Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times. The algorithm should run in linear time and in O(1) space. 2 | // 3 | // 4 | // How many majority elements could it possibly have? 5 | // Do you have a better hint? Suggest it! 6 | 7 | 8 | /** 9 | * @param {number[]} nums 10 | * @return {number[]} 11 | */ 12 | var majorityElement = function(nums) { 13 | if (nums.length === 0) return []; 14 | if (nums.length === 1) return nums; 15 | const hashmap = {}; 16 | const result = []; 17 | var lock = []; 18 | for (var i = 0, l = nums.length; i < l; i++) { 19 | if (hashmap[nums[i]] === undefined) { 20 | hashmap[nums[i]] = 1; 21 | } else { 22 | hashmap[nums[i]]++; 23 | } 24 | if (!lock[nums[i]]){ 25 | if (hashmap[nums[i]] > Math.floor(nums.length / 3)) { 26 | result.push(nums[i]); 27 | lock[nums[i]] = true; 28 | } 29 | } 30 | } 31 | return result; 32 | }; 33 | -------------------------------------------------------------------------------- /231-power-of-two/power-of-two.js: -------------------------------------------------------------------------------- 1 | // Given an integer, write a function to determine if it is a power of two. 2 | // 3 | // 4 | // Credits:Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases. 5 | 6 | 7 | /** 8 | * @param {number} n 9 | * @return {boolean} 10 | */ 11 | var isPowerOfTwo = function(n) { 12 | if (n < 0) return false; 13 | var hasOne = false; 14 | while (n > 0) { 15 | if (n & 1) { 16 | if (hasOne) { 17 | return false; 18 | } 19 | hasOne = true; 20 | } 21 | n >>= 1; 22 | } 23 | return hasOne; 24 | }; 25 | -------------------------------------------------------------------------------- /232-implement-queue-using-stacks/implement-queue-using-stacks.js: -------------------------------------------------------------------------------- 1 | // Implement the following operations of a queue using stacks. 2 | // 3 | // 4 | // push(x) -- Push element x to the back of queue. 5 | // 6 | // 7 | // pop() -- Removes the element from in front of queue. 8 | // 9 | // 10 | // peek() -- Get the front element. 11 | // 12 | // 13 | // empty() -- Return whether the queue is empty. 14 | // 15 | // 16 | // Notes: 17 | // 18 | // You must use only standard operations of a stack -- which means only push to top, peek/pop from top, size, and is empty operations are valid. 19 | // Depending on your language, stack may not be supported natively. You may simulate a stack by using a list or deque (double-ended queue), as long as you use only standard operations of a stack. 20 | // You may assume that all operations are valid (for example, no pop or peek operations will be called on an empty queue). 21 | 22 | 23 | /** 24 | * @constructor 25 | */ 26 | var Queue = function() { 27 | this.arr = []; 28 | }; 29 | 30 | /** 31 | * @param {number} x 32 | * @returns {void} 33 | */ 34 | Queue.prototype.push = function(x) { 35 | this.arr.push(x); 36 | }; 37 | 38 | /** 39 | * @returns {void} 40 | */ 41 | Queue.prototype.pop = function() { 42 | this.arr.shift(); 43 | }; 44 | 45 | /** 46 | * @returns {number} 47 | */ 48 | Queue.prototype.peek = function() { 49 | return this.arr[0] 50 | }; 51 | 52 | /** 53 | * @returns {boolean} 54 | */ 55 | Queue.prototype.empty = function() { 56 | return this.arr.length === 0; 57 | }; 58 | -------------------------------------------------------------------------------- /234-palindrome-linked-list/palindrome-linked-list.js: -------------------------------------------------------------------------------- 1 | // Given a singly linked list, determine if it is a palindrome. 2 | // 3 | // Follow up: 4 | // Could you do it in O(n) time and O(1) space? 5 | 6 | 7 | /** 8 | * Definition for singly-linked list. 9 | * function ListNode(val) { 10 | * this.val = val; 11 | * this.next = null; 12 | * } 13 | */ 14 | /** 15 | * @param {ListNode} head 16 | * @return {boolean} 17 | */ 18 | var isPalindrome = function(head) { 19 | if (!head || !head.next) return true; 20 | 21 | var dev = null; 22 | var slow = head; 23 | var fast = head; 24 | while (fast && fast.next && fast.next.next) { 25 | fast = fast.next.next; 26 | slow=slow.next; 27 | } 28 | slow.next = reverseList(slow.next); 29 | slow = slow.next; 30 | while (slow) { 31 | if (slow.val !== head.val) { 32 | return false; 33 | } 34 | slow = slow.next; 35 | head = head.next; 36 | } 37 | return true; 38 | }; 39 | 40 | var reverseList = function(head) { 41 | var prev = null; 42 | var next = null; 43 | while(head !== null) { 44 | next = head.next; 45 | head.next = prev; 46 | prev = head; 47 | head = next; 48 | } 49 | return prev; 50 | }; 51 | -------------------------------------------------------------------------------- /235-lowest-common-ancestor-of-a-binary-search-tree/lowest-common-ancestor-of-a-binary-search-tree.js: -------------------------------------------------------------------------------- 1 | // Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST. 2 | // 3 | // 4 | // 5 | // According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself).” 6 | // 7 | // 8 | // 9 | // _______6______ 10 | // / \ 11 | // ___2__ ___8__ 12 | // / \ / \ 13 | // 0 _4 7 9 14 | // / \ 15 | // 3 5 16 | // 17 | // 18 | // 19 | // For example, the lowest common ancestor (LCA) of nodes 2 and 8 is 6. Another example is LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition. 20 | 21 | 22 | /** 23 | * Definition for a binary tree node. 24 | * function TreeNode(val) { 25 | * this.val = val; 26 | * this.left = this.right = null; 27 | * } 28 | */ 29 | /** 30 | * @param {TreeNode} root 31 | * @param {TreeNode} p 32 | * @param {TreeNode} q 33 | * @return {TreeNode} 34 | */ 35 | var lowestCommonAncestor = function(root, p, q) { 36 | if(root.val > p.val && root.val > q.val) return lowestCommonAncestor(root.left, p, q); 37 | else if(root.val < p.val && root.val < q.val) return lowestCommonAncestor(root.right, p, q); 38 | else return root; 39 | }; 40 | -------------------------------------------------------------------------------- /237-delete-node-in-a-linked-list/delete-node-in-a-linked-list.js: -------------------------------------------------------------------------------- 1 | // Write a function to delete a node (except the tail) in a singly linked list, given only access to that node. 2 | // 3 | // 4 | // 5 | // Supposed the linked list is 1 -> 2 -> 3 -> 4 and you are given the third node with value 3, the linked list should become 1 -> 2 -> 4 after calling your function. 6 | 7 | 8 | /** 9 | * Definition for singly-linked list. 10 | * function ListNode(val) { 11 | * this.val = val; 12 | * this.next = null; 13 | * } 14 | */ 15 | /** 16 | * @param {ListNode} node 17 | * @return {void} Do not return anything, modify node in-place instead. 18 | */ 19 | var deleteNode = function(node) { 20 | node.val = node.next.val; 21 | node.next = node.next.next; 22 | }; 23 | -------------------------------------------------------------------------------- /238-product-of-array-except-self/product-of-array-except-self.js: -------------------------------------------------------------------------------- 1 | // Given an array of n integers where n > 1, nums, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i]. 2 | // 3 | // Solve it without division and in O(n). 4 | // 5 | // For example, given [1,2,3,4], return [24,12,8,6]. 6 | // 7 | // Follow up: 8 | // Could you solve it with constant space complexity? (Note: The output array does not count as extra space for the purpose of space complexity analysis.) 9 | 10 | 11 | /** 12 | * @param {number[]} nums 13 | * @return {number[]} 14 | */ 15 | var productExceptSelf = function(nums) { 16 | var len = nums.length; 17 | var left_product = []; 18 | left_product[0] = 1; 19 | for (var i = 1; i < len; ++i) { 20 | left_product[i] = left_product[i - 1] * nums[i - 1]; 21 | } 22 | var result = []; 23 | var right_product = 1; 24 | for (i = len - 1; i >= 0; i--) { 25 | result[i] = left_product[i] * right_product; 26 | right_product *= nums[i]; 27 | } 28 | return result; 29 | }; 30 | -------------------------------------------------------------------------------- /240-search-a-2d-matrix-ii/search-a-2d-matrix-ii.js: -------------------------------------------------------------------------------- 1 | // Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties: 2 | // 3 | // 4 | // 5 | // Integers in each row are sorted in ascending from left to right. 6 | // Integers in each column are sorted in ascending from top to bottom. 7 | // 8 | // 9 | // 10 | // 11 | // For example, 12 | // 13 | // Consider the following matrix: 14 | // 15 | // 16 | // [ 17 | // [1, 4, 7, 11, 15], 18 | // [2, 5, 8, 12, 19], 19 | // [3, 6, 9, 16, 22], 20 | // [10, 13, 14, 17, 24], 21 | // [18, 21, 23, 26, 30] 22 | // ] 23 | // 24 | // 25 | // Given target = 5, return true. 26 | // Given target = 20, return false. 27 | 28 | 29 | /** 30 | * @param {number[][]} matrix 31 | * @param {number} target 32 | * @return {boolean} 33 | */ 34 | var searchMatrix = function(matrix, target) { 35 | var row = matrix.length - 1; 36 | var length = matrix[0].length; 37 | var col = 0; 38 | while(row >= 0 && col < length) { 39 | if (matrix[row][col] === target) { 40 | return true; 41 | } else if (matrix[row][col] > target) { 42 | row -= 1; 43 | } else { 44 | col += 1; 45 | } 46 | } 47 | return false; 48 | }; 49 | -------------------------------------------------------------------------------- /242-valid-anagram/valid-anagram.js: -------------------------------------------------------------------------------- 1 | // Given two strings s and t, write a function to determine if t is an anagram of s. 2 | // 3 | // For example, 4 | // s = "anagram", t = "nagaram", return true. 5 | // s = "rat", t = "car", return false. 6 | // 7 | // 8 | // Note: 9 | // You may assume the string contains only lowercase alphabets. 10 | // 11 | // Follow up: 12 | // What if the inputs contain unicode characters? How would you adapt your solution to such case? 13 | 14 | 15 | /** 16 | * @param {string} s 17 | * @param {string} t 18 | * @return {boolean} 19 | */ 20 | var isAnagram = function(s, t) { 21 | const len = s.length; 22 | if (len !== t.length) return false; 23 | const hashTab = {}; 24 | for (let i = 0; i < len; i++) { 25 | if (!hashTab[s[i]]) { 26 | hashTab[s[i]] = 1; 27 | } else { 28 | hashTab[s[i]]++; 29 | } 30 | if (!hashTab[t[i]]) { 31 | hashTab[t[i]] = -1; 32 | } else { 33 | hashTab[t[i]]--; 34 | } 35 | } 36 | for (let item in hashTab) { 37 | if (hashTab[item]) return false; 38 | } 39 | return true; 40 | }; 41 | -------------------------------------------------------------------------------- /258-add-digits/add-digits.js: -------------------------------------------------------------------------------- 1 | // Given a non-negative integer num, repeatedly add all its digits until the result has only one digit. 2 | // 3 | // 4 | // 5 | // For example: 6 | // 7 | // 8 | // Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it. 9 | // 10 | // 11 | // Follow up: 12 | // Could you do it without any loop/recursion in O(1) runtime? 13 | // 14 | // 15 | // 16 | // A naive implementation of the above process is trivial. Could you come up with other methods? 17 | // What are all the possible results? 18 | // How do they occur, periodically or randomly? 19 | // You may find this Wikipedia article useful. 20 | // 21 | // 22 | // Credits:Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases. 23 | 24 | 25 | /** 26 | * @param {number} num 27 | * @return {number} 28 | */ 29 | var addDigits = function(num) { 30 | var str = num.toString(); 31 | if (str.length === 1) { 32 | return +str; 33 | } 34 | var result = str.split('').reduce((memo, current) => +memo + +current); 35 | return addDigits(result); 36 | }; 37 | -------------------------------------------------------------------------------- /260-single-number-iii/single-number-iii.js: -------------------------------------------------------------------------------- 1 | // Given an array of numbers nums, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once. 2 | // 3 | // 4 | // For example: 5 | // 6 | // 7 | // Given nums = [1, 2, 1, 3, 2, 5], return [3, 5]. 8 | // 9 | // 10 | // Note: 11 | // 12 | // The order of the result is not important. So in the above example, [5, 3] is also correct. 13 | // Your algorithm should run in linear runtime complexity. Could you implement it using only constant space complexity? 14 | // 15 | // 16 | // 17 | // Credits:Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases. 18 | 19 | 20 | /** 21 | * @param {number[]} nums 22 | * @return {number[]} 23 | */ 24 | var singleNumber = function(nums) { 25 | var hashMap = {}; 26 | for (var i = 0, l = nums.length; i <= l - 1; ++i) { 27 | if (!hashMap[nums[i]]) { 28 | hashMap[nums[i]] = 1; 29 | } else { 30 | hashMap[nums[i]]++; 31 | } 32 | } 33 | var result = []; 34 | for (var item in hashMap) { 35 | if (hashMap[item] === 1) { 36 | result.push(+item); 37 | } 38 | } 39 | return result; 40 | }; 41 | -------------------------------------------------------------------------------- /263-ugly-number/ugly-number.js: -------------------------------------------------------------------------------- 1 | // Write a program to check whether a given number is an ugly number. 2 | // 3 | // 4 | // 5 | // Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. For example, 6, 8 are ugly while 14 is not ugly since it includes another prime factor 7. 6 | // 7 | // 8 | // 9 | // Note that 1 is typically treated as an ugly number. 10 | // 11 | // 12 | // Credits:Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases. 13 | 14 | 15 | /** 16 | * @param {number} num 17 | * @return {boolean} 18 | */ 19 | var isUgly = function(num) { 20 | if (num <= 0) return false; 21 | if (num === 1) return true; 22 | while (num % 2 === 0) num /= 2; 23 | while (num % 3 === 0) num /= 3; 24 | while (num % 5 === 0) num /= 5; 25 | 26 | return num === 1; 27 | }; 28 | -------------------------------------------------------------------------------- /268-missing-number/missing-number.js: -------------------------------------------------------------------------------- 1 | // Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array. 2 | // 3 | // 4 | // For example, 5 | // Given nums = [0, 1, 3] return 2. 6 | // 7 | // 8 | // 9 | // Note: 10 | // Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity? 11 | // 12 | // 13 | // Credits:Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases. 14 | 15 | 16 | /** 17 | * @param {number[]} nums 18 | * @return {number} 19 | */ 20 | var missingNumber = function(nums) { 21 | var length = nums.length; 22 | var sum = (0 + length + 1) * (length) / 2; 23 | for (var i = 0; i < length; i++) { 24 | sum -= nums[i]; 25 | } 26 | return sum; 27 | }; 28 | -------------------------------------------------------------------------------- /278-first-bad-version/first-bad-version.js: -------------------------------------------------------------------------------- 1 | // You are a product manager and currently leading a team to develop a new product. Unfortunately, the latest version of your product fails the quality check. Since each version is developed based on the previous version, all the versions after a bad version are also bad. 2 | // 3 | // 4 | // 5 | // Suppose you have n versions [1, 2, ..., n] and you want to find out the first bad one, which causes all the following ones to be bad. 6 | // 7 | // 8 | // 9 | // You are given an API bool isBadVersion(version) which will return whether version is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API. 10 | // 11 | // 12 | // Credits:Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases. 13 | 14 | 15 | /** 16 | * Definition for isBadVersion() 17 | * 18 | * @param {integer} version number 19 | * @return {boolean} whether the version is bad 20 | * isBadVersion = function(version) { 21 | * ... 22 | * }; 23 | */ 24 | 25 | /** 26 | * @param {function} isBadVersion() 27 | * @return {function} 28 | */ 29 | var solution = function(isBadVersion) { 30 | /** 31 | * @param {integer} n Total versions 32 | * @return {integer} The first bad version 33 | */ 34 | return function(n) { 35 | var start = 1; 36 | var end = n; 37 | while(start + 1 < end) { 38 | var center = parseInt(((end - start) / 2) + start); 39 | if (isBadVersion(center)) { 40 | end = center; 41 | } else { 42 | start = center; 43 | } 44 | 45 | } 46 | if (isBadVersion(start)) { 47 | return start; 48 | } 49 | return end; 50 | }; 51 | }; 52 | -------------------------------------------------------------------------------- /283-move-zeroes/move-zeroes.js: -------------------------------------------------------------------------------- 1 | // Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements. 2 | // 3 | // 4 | // 5 | // For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0]. 6 | // 7 | // 8 | // 9 | // Note: 10 | // 11 | // You must do this in-place without making a copy of the array. 12 | // Minimize the total number of operations. 13 | // 14 | // 15 | // 16 | // Credits:Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases. 17 | 18 | 19 | /** 20 | * @param {number[]} nums 21 | * @return {void} Do not return anything, modify nums in-place instead. 22 | */ 23 | var moveZeroes = function(nums) { 24 | var index = 0; 25 | for (var i = 0, l = nums.length; i < l; i++) { 26 | if (nums[i] !== 0) { 27 | nums[index++] = nums[i]; 28 | } 29 | } 30 | for (i = index; i < l; i++) { 31 | nums[i] = 0; 32 | } 33 | }; 34 | -------------------------------------------------------------------------------- /287-find-the-duplicate-number/find-the-duplicate-number.js: -------------------------------------------------------------------------------- 1 | // Given an array nums containing n + 1 integers where each integer is between 1 and n (inclusive), prove that at least one duplicate number must exist. Assume that there is only one duplicate number, find the duplicate one. 2 | // 3 | // 4 | // 5 | // Note: 6 | // 7 | // You must not modify the array (assume the array is read only). 8 | // You must use only constant, O(1) extra space. 9 | // Your runtime complexity should be less than O(n2). 10 | // There is only one duplicate number in the array, but it could be repeated more than once. 11 | // 12 | // 13 | // 14 | // Credits:Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases. 15 | 16 | 17 | /** 18 | * @param {number[]} nums 19 | * @return {number} 20 | */ 21 | var findDuplicate = function(nums) { 22 | const hashMap = {}; 23 | for (var i = 0, l = nums.length; i < l; i++ ){ 24 | if (!hashMap[nums[i]]) { 25 | hashMap[nums[i]] = true; 26 | } else { 27 | return nums[i]; 28 | } 29 | } 30 | }; 31 | -------------------------------------------------------------------------------- /290-word-pattern/word-pattern.js: -------------------------------------------------------------------------------- 1 | // Given a pattern and a string str, find if str follows the same pattern. 2 | // Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty word in str. 3 | // 4 | // Examples: 5 | // 6 | // pattern = "abba", str = "dog cat cat dog" should return true. 7 | // pattern = "abba", str = "dog cat cat fish" should return false. 8 | // pattern = "aaaa", str = "dog cat cat dog" should return false. 9 | // pattern = "abba", str = "dog dog dog dog" should return false. 10 | // 11 | // 12 | // 13 | // 14 | // Notes: 15 | // You may assume pattern contains only lowercase letters, and str contains lowercase letters separated by a single space. 16 | // 17 | // 18 | // Credits:Special thanks to @minglotus6 for adding this problem and creating all test cases. 19 | 20 | 21 | /** 22 | * @param {string} pattern 23 | * @param {string} str 24 | * @return {boolean} 25 | */ 26 | var wordPattern = function(pattern, str) { 27 | const map = new Map(); 28 | const map2 = new Map(); 29 | var res = str.split(' '); 30 | if (pattern.length !== res.length) return false; 31 | for (var i = 0, l = pattern.length; i <= l - 1; ++i) { 32 | if (!map.has(res[i])) { 33 | map.set(res[i], pattern[i]); 34 | } 35 | else { 36 | if (map.get(res[i]) !== pattern[i]) { 37 | return false; 38 | } 39 | } 40 | if (!map2.has(pattern[i])) { 41 | map2.set(pattern[i], res[i]) 42 | }else { 43 | if (map2.get(pattern[i]) !== res[i]) { 44 | return false; 45 | } 46 | } 47 | } 48 | return true; 49 | }; 50 | -------------------------------------------------------------------------------- /292-nim-game/nim-game.js: -------------------------------------------------------------------------------- 1 | // You are playing the following Nim Game with your friend: There is a heap of stones on the table, each time one of you take turns to remove 1 to 3 stones. The one who removes the last stone will be the winner. You will take the first turn to remove the stones. 2 | // 3 | // 4 | // 5 | // Both of you are very clever and have optimal strategies for the game. Write a function to determine whether you can win the game given the number of stones in the heap. 6 | // 7 | // 8 | // 9 | // For example, if there are 4 stones in the heap, then you will never win the game: no matter 1, 2, or 3 stones you remove, the last stone will always be removed by your friend. 10 | // 11 | // 12 | // 13 | // If there are 5 stones in the heap, could you figure out a way to remove the stones such that you will always be the winner? 14 | // 15 | // 16 | // Credits:Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases. 17 | 18 | 19 | /** 20 | * @param {number} n 21 | * @return {boolean} 22 | */ 23 | var canWinNim = function(n) { 24 | return n % 4 !== 0; 25 | }; 26 | -------------------------------------------------------------------------------- /303-range-sum-query-immutable/range-sum-query-immutable.js: -------------------------------------------------------------------------------- 1 | // Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive. 2 | // 3 | // Example: 4 | // 5 | // Given nums = [-2, 0, 3, -5, 2, -1] 6 | // 7 | // sumRange(0, 2) -> 1 8 | // sumRange(2, 5) -> -1 9 | // sumRange(0, 5) -> -3 10 | // 11 | // 12 | // 13 | // Note: 14 | // 15 | // You may assume that the array does not change. 16 | // There are many calls to sumRange function. 17 | 18 | 19 | /** 20 | * @constructor 21 | * @param {number[]} nums 22 | */ 23 | var NumArray = function(nums) { 24 | this.arr = nums; 25 | }; 26 | 27 | /** 28 | * @param {number} i 29 | * @param {number} j 30 | * @return {number} 31 | */ 32 | NumArray.prototype.sumRange = function(i, j) { 33 | 34 | var res = 0; 35 | for (var index = i; index <= j; index++) { 36 | res += this.arr[index]; 37 | } 38 | return res; 39 | }; 40 | 41 | 42 | /** 43 | * Your NumArray object will be instantiated and called as such: 44 | * var numArray = new NumArray(nums); 45 | * numArray.sumRange(0, 1); 46 | * numArray.sumRange(0, 2); 47 | */ 48 | -------------------------------------------------------------------------------- /319-bulb-switcher/bulb-switcher.js: -------------------------------------------------------------------------------- 1 | // There are n bulbs that are initially off. You first turn on all the bulbs. Then, you turn off every second bulb. On the third round, you toggle every third bulb (turning on if it's off or turning off if it's on). For the ith round, you toggle every i bulb. For the nth round, you only toggle the last bulb. 2 | // 3 | // Find how many bulbs are on after n rounds. 4 | // 5 | // 6 | // 7 | // Example: 8 | // 9 | // Given n = 3. 10 | // At first, the three bulbs are [off, off, off]. 11 | // After first round, the three bulbs are [on, on, on]. 12 | // After second round, the three bulbs are [on, off, on]. 13 | // After third round, the three bulbs are [on, off, off]. 14 | // So you should return 1, because there is only one bulb is on. 15 | 16 | 17 | /** 18 | * @param {number} n 19 | * @return {number} 20 | */ 21 | var bulbSwitch = function(n) { 22 | return Math.floor(Math.sqrt(n)); 23 | }; 24 | -------------------------------------------------------------------------------- /326-power-of-three/power-of-three.js: -------------------------------------------------------------------------------- 1 | // Given an integer, write a function to determine if it is a power of three. 2 | // 3 | // 4 | // Follow up: 5 | // Could you do it without using any loop / recursion? 6 | // 7 | // 8 | // Credits:Special thanks to @dietpepsi for adding this problem and creating all test cases. 9 | 10 | 11 | /** 12 | * @param {number} n 13 | * @return {boolean} 14 | */ 15 | var isPowerOfThree = function(n) { 16 | switch(n) { 17 | case 1: 18 | case 3: 19 | case 9: 20 | case 27: 21 | case 81: 22 | case 243: 23 | case 729: 24 | case 2187: 25 | case 6561: 26 | case 19683: 27 | case 59049: 28 | case 177147: 29 | case 531441: 30 | case 1594323: 31 | case 4782969: 32 | case 14348907: 33 | case 43046721: 34 | case 129140163: 35 | case 387420489: 36 | case 1162261467: 37 | return true; 38 | default: return false; 39 | } 40 | }; 41 | -------------------------------------------------------------------------------- /328-odd-even-linked-list/odd-even-linked-list.js: -------------------------------------------------------------------------------- 1 | // Given a singly linked list, group all odd nodes together followed by the even nodes. Please note here we are talking about the node number and not the value in the nodes. 2 | // 3 | // You should try to do it in place. The program should run in O(1) space complexity and O(nodes) time complexity. 4 | // 5 | // 6 | // Example: 7 | // Given 1->2->3->4->5->NULL, 8 | // return 1->3->5->2->4->NULL. 9 | // 10 | // 11 | // Note: 12 | // The relative order inside both the even and odd groups should remain as it was in the input. 13 | // The first node is considered odd, the second node even and so on ... 14 | // 15 | // 16 | // Credits:Special thanks to @DjangoUnchained for adding this problem and creating all test cases. 17 | 18 | 19 | /** 20 | * Definition for singly-linked list. 21 | * function ListNode(val) { 22 | * this.val = val; 23 | * this.next = null; 24 | * } 25 | */ 26 | /** 27 | * @param {ListNode} head 28 | * @return {ListNode} 29 | */ 30 | var oddEvenList = function(head) { 31 | if (head === null || head.next === null || head.next.next === null) { 32 | return head; 33 | } 34 | var p_odd = head, p_even = head.next, head_of_even = p_even; 35 | while(p_even !== null && p_even.next !== null ) { 36 | p_odd.next = p_even.next ; 37 | p_even.next = p_odd.next.next ; 38 | 39 | p_odd = p_odd.next ; 40 | p_even = p_even.next; 41 | } 42 | p_odd.next = head_of_even; 43 | return head; 44 | }; 45 | -------------------------------------------------------------------------------- /338-counting-bits/counting-bits.js: -------------------------------------------------------------------------------- 1 | // Given a non negative integer number num. For every numbers i in the range 0 ≤ i ≤ num calculate the number of 1's in their binary representation and return them as an array. 2 | // 3 | // 4 | // Example: 5 | // For num = 5 you should return [0,1,1,2,1,2]. 6 | // 7 | // 8 | // Follow up: 9 | // 10 | // It is very easy to come up with a solution with run time O(n*sizeof(integer)). But can you do it in linear time O(n) /possibly in a single pass? 11 | // Space complexity should be O(n). 12 | // Can you do it like a boss? Do it without using any builtin function like __builtin_popcount in c++ or in any other language. 13 | // 14 | // 15 | // 16 | // 17 | // You should make use of what you have produced already. 18 | // Divide the numbers in ranges like [2-3], [4-7], [8-15] and so on. And try to generate new range from previous. 19 | // Or does the odd/even status of the number help you in calculating the number of 1s? 20 | // 21 | // 22 | // Credits:Special thanks to @ syedee for adding this problem and creating all test cases. 23 | 24 | 25 | /** 26 | * @param {number} num 27 | * @return {number[]} 28 | */ 29 | 30 | var calcBit = function (num) { 31 | return num.toString(2).replace(/0/g, '').length; 32 | }; 33 | 34 | var countBits = function(num) { 35 | var res = new Array(num); 36 | var i = 0; 37 | while (i <= num) { 38 | res[i] = calcBit(i); 39 | i++ 40 | } 41 | return res; 42 | 43 | }; 44 | 45 | -------------------------------------------------------------------------------- /342-power-of-four/power-of-four.js: -------------------------------------------------------------------------------- 1 | // Given an integer (signed 32 bits), write a function to check whether it is a power of 4. 2 | // 3 | // Example: 4 | // Given num = 16, return true. 5 | // Given num = 5, return false. 6 | // 7 | // 8 | // Follow up: Could you solve it without loops/recursion? 9 | // 10 | // Credits:Special thanks to @yukuairoy for adding this problem and creating all test cases. 11 | 12 | 13 | /** 14 | * @param {number} num 15 | * @return {boolean} 16 | */ 17 | var isPowerOfFour = function(num) { 18 | var str = num.toString(4); 19 | var reg = /^10*$/; 20 | return reg.test(str); 21 | }; 22 | -------------------------------------------------------------------------------- /344-reverse-string/reverse-string.js: -------------------------------------------------------------------------------- 1 | // Write a function that takes a string as input and returns the string reversed. 2 | // 3 | // 4 | // Example: 5 | // Given s = "hello", return "olleh". 6 | 7 | 8 | /** 9 | * @param {string} s 10 | * @return {string} 11 | */ 12 | var reverseString = function(s) { 13 | return s.split('').reverse().join(''); 14 | }; 15 | -------------------------------------------------------------------------------- /345-reverse-vowels-of-a-string/reverse-vowels-of-a-string.js: -------------------------------------------------------------------------------- 1 | // Write a function that takes a string as input and reverse only the vowels of a string. 2 | // 3 | // 4 | // Example 1: 5 | // Given s = "hello", return "holle". 6 | // 7 | // 8 | // 9 | // Example 2: 10 | // Given s = "leetcode", return "leotcede". 11 | // 12 | // 13 | // 14 | // Note: 15 | // The vowels does not include the letter "y". 16 | 17 | 18 | /** 19 | * @param {string} s 20 | * @return {string} 21 | */ 22 | var reverseVowels = function(s) { 23 | var string = s.split(''); 24 | var re = /[aeiouAEIOU]/g; 25 | var array = []; 26 | while ((match = re.exec(s)) != null) { 27 | array.push(match.index); 28 | } 29 | 30 | for (var i = 0; i < array.length/2; i++) { 31 | var temp = string[array[i]]; 32 | string[array[i]] = string[array[array.length - 1 - i]]; 33 | string[array[array.length - 1 - i]] = temp; 34 | } 35 | return string.join(''); 36 | }; 37 | -------------------------------------------------------------------------------- /347-top-k-frequent-elements/top-k-frequent-elements.js: -------------------------------------------------------------------------------- 1 | // Given a non-empty array of integers, return the k most frequent elements. 2 | // 3 | // For example, 4 | // Given [1,1,1,2,2,3] and k = 2, return [1,2]. 5 | // 6 | // 7 | // Note: 8 | // 9 | // You may assume k is always valid, 1 ≤ k ≤ number of unique elements. 10 | // Your algorithm's time complexity must be better than O(n log n), where n is the array's size. 11 | 12 | 13 | /** 14 | * @param {number[]} nums 15 | * @param {number} k 16 | * @return {number[]} 17 | */ 18 | var topKFrequent = function(nums, k) { 19 | var hashMap = {}; 20 | for (var i = 0, l = nums.length; i <= l - 1; ++i) { 21 | if (!hashMap[nums[i]]) { 22 | hashMap[nums[i]] = 1; 23 | } else { 24 | hashMap[nums[i]]++; 25 | } 26 | } 27 | var max = -Infinity; 28 | for (var item in hashMap) { 29 | max = Math.max(hashMap[item], max); 30 | } 31 | var result = []; 32 | for (i = max; i > 0; --i) { 33 | for (item in hashMap) { 34 | if (hashMap[item] === i && k > 0) { 35 | result.push(+item); 36 | k--; 37 | } 38 | } 39 | } 40 | return result; 41 | }; 42 | -------------------------------------------------------------------------------- /349-intersection-of-two-arrays/intersection-of-two-arrays.js: -------------------------------------------------------------------------------- 1 | // Given two arrays, write a function to compute their intersection. 2 | // 3 | // 4 | // Example: 5 | // Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2]. 6 | // 7 | // 8 | // Note: 9 | // 10 | // Each element in the result must be unique. 11 | // The result can be in any order. 12 | 13 | 14 | /** 15 | * @param {number[]} nums1 16 | * @param {number[]} nums2 17 | * @return {number[]} 18 | */ 19 | var intersection = function(nums1, nums2) { 20 | const hashMap = {}; 21 | const result = []; 22 | for (var i = 0, l = nums1.length; i < l; i++) { 23 | if (!hashMap[nums1[i]]) { 24 | hashMap[nums1[i]] = true; 25 | } 26 | } 27 | for (i = 0, l = nums2.length; i < l; i++) { 28 | if (hashMap[nums2[i]]) { 29 | hashMap[nums2[i]] = false 30 | result.push(nums2[i]); 31 | } 32 | } 33 | return result; 34 | }; 35 | -------------------------------------------------------------------------------- /350-intersection-of-two-arrays-ii/intersection-of-two-arrays-ii.js: -------------------------------------------------------------------------------- 1 | // Given two arrays, write a function to compute their intersection. 2 | // 3 | // 4 | // Example: 5 | // Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2, 2]. 6 | // 7 | // 8 | // Note: 9 | // 10 | // Each element in the result should appear as many times as it shows in both arrays. 11 | // The result can be in any order. 12 | // 13 | // 14 | // 15 | // Follow up: 16 | // 17 | // What if the given array is already sorted? How would you optimize your algorithm? 18 | // What if nums1's size is small compared to nums2's size? Which algorithm is better? 19 | // What if elements of nums2 are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once? 20 | 21 | 22 | /** 23 | * @param {number[]} nums1 24 | * @param {number[]} nums2 25 | * @return {number[]} 26 | */ 27 | var intersect = function(nums1, nums2) { 28 | const hashTab = {}; 29 | const result = []; 30 | for (var i = 0, l = nums1.length; i < l; i++) { 31 | if (!hashTab[nums1[i]]) { 32 | hashTab[nums1[i]] = 1; 33 | } else { 34 | hashTab[nums1[i]]++; 35 | } 36 | } 37 | for (i = 0, l = nums2.length; i < l; i++) { 38 | if (hashTab[nums2[i]]) { 39 | hashTab[nums2[i]]--; 40 | result.push(nums2[i]); 41 | } 42 | } 43 | return result; 44 | }; 45 | -------------------------------------------------------------------------------- /371-sum-of-two-integers/sum-of-two-integers.js: -------------------------------------------------------------------------------- 1 | // Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -. 2 | // 3 | // Example: 4 | // Given a = 1 and b = 2, return 3. 5 | // 6 | // 7 | // Credits:Special thanks to @fujiaozhu for adding this problem and creating all test cases. 8 | 9 | 10 | /** 11 | * @param {number} a 12 | * @param {number} b 13 | * @return {number} 14 | */ 15 | var getSum = function(a, b) { 16 | var c; 17 | while ((c = a & b) != 0) { 18 | a = a ^ b; 19 | b = c << 1; 20 | } 21 | return a ^ b; 22 | }; 23 | -------------------------------------------------------------------------------- /383-ransom-note/ransom-note.js: -------------------------------------------------------------------------------- 1 | // Given an arbitrary ransom note string and another string containing letters from all the magazines, write a function that will return true if the ransom 2 | // note can be constructed from the magazines ; otherwise, it will return false. 3 | // 4 | // 5 | // Each letter in the magazine string can only be used once in your ransom note. 6 | // 7 | // 8 | // Note: 9 | // You may assume that both strings contain only lowercase letters. 10 | // 11 | // 12 | // 13 | // canConstruct("a", "b") -> false 14 | // canConstruct("aa", "ab") -> false 15 | // canConstruct("aa", "aab") -> true 16 | 17 | 18 | /** 19 | * @param {string} ransomNote 20 | * @param {string} magazine 21 | * @return {boolean} 22 | */ 23 | var canConstruct = function(ransomNote, magazine) { 24 | var hashMap = {}; 25 | for (var i = 0, l = magazine.length; i <= l - 1; ++i) { 26 | if (hashMap[magazine[i]] === undefined) { 27 | hashMap[magazine[i]] = 1; 28 | } else { 29 | hashMap[magazine[i]]++; 30 | } 31 | } 32 | for (i = 0, l = ransomNote.length; i <= l - 1; ++i) { 33 | if (!hashMap[ransomNote[i]]) { 34 | return false; 35 | } else { 36 | hashMap[ransomNote[i]]--; 37 | } 38 | } 39 | return true; 40 | }; 41 | -------------------------------------------------------------------------------- /387-first-unique-character-in-a-string/first-unique-character-in-a-string.js: -------------------------------------------------------------------------------- 1 | // Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1. 2 | // 3 | // Examples: 4 | // 5 | // s = "leetcode" 6 | // return 0. 7 | // 8 | // s = "loveleetcode", 9 | // return 2. 10 | // 11 | // 12 | // 13 | // 14 | // Note: You may assume the string contain only lowercase letters. 15 | 16 | 17 | /** 18 | * @param {string} s 19 | * @return {number} 20 | */ 21 | var firstUniqChar = function (s) { 22 | var map= {}; 23 | for (var i = 0; i < s.length; i++) { 24 | if (map[s[i]] === undefined) { 25 | map[s[i]] = 0; 26 | } 27 | map[s[i]]++; 28 | } 29 | for (var i = 0; i < s.length; i++) { 30 | if (map[s[i]] === 1) { 31 | return i; 32 | } 33 | } 34 | return -1; 35 | }; 36 | -------------------------------------------------------------------------------- /389-find-the-difference/find-the-difference.js: -------------------------------------------------------------------------------- 1 | // Given two strings s and t which consist of only lowercase letters. 2 | // 3 | // String t is generated by random shuffling string s and then add one more letter at a random position. 4 | // 5 | // Find the letter that was added in t. 6 | // 7 | // Example: 8 | // 9 | // Input: 10 | // s = "abcd" 11 | // t = "abcde" 12 | // 13 | // Output: 14 | // e 15 | // 16 | // Explanation: 17 | // 'e' is the letter that was added. 18 | 19 | 20 | /** 21 | * @param {string} s 22 | * @param {string} t 23 | * @return {character} 24 | */ 25 | var findTheDifference = function(s, t) { 26 | const hashMap = {}; 27 | for (var i = 0, l = s.length; i < l; i++) { 28 | if (!hashMap[s[i]]) { 29 | hashMap[s[i]] = 1; 30 | } else { 31 | hashMap[s[i]]++; 32 | } 33 | } 34 | for (var i = 0, l = t.length; i < l; i++){ 35 | if (!hashMap[t[i]]) { 36 | return t[i]; 37 | } else { 38 | hashMap[t[i]]--; 39 | } 40 | } 41 | }; 42 | -------------------------------------------------------------------------------- /396-rotate-function/rotate-function.js: -------------------------------------------------------------------------------- 1 | // Given an array of integers A and let n to be its length. 2 | // 3 | // 4 | // 5 | // Assume Bk to be an array obtained by rotating the array A k positions clock-wise, we define a "rotation function" F on A as follow: 6 | // 7 | // 8 | // 9 | // F(k) = 0 * Bk[0] + 1 * Bk[1] + ... + (n-1) * Bk[n-1]. 10 | // 11 | // Calculate the maximum value of F(0), F(1), ..., F(n-1). 12 | // 13 | // 14 | // Note: 15 | // n is guaranteed to be less than 105. 16 | // 17 | // 18 | // Example: 19 | // 20 | // A = [4, 3, 2, 6] 21 | // 22 | // F(0) = (0 * 4) + (1 * 3) + (2 * 2) + (3 * 6) = 0 + 3 + 4 + 18 = 25 23 | // F(1) = (0 * 6) + (1 * 4) + (2 * 3) + (3 * 2) = 0 + 4 + 6 + 6 = 16 24 | // F(2) = (0 * 2) + (1 * 6) + (2 * 4) + (3 * 3) = 0 + 6 + 8 + 9 = 23 25 | // F(3) = (0 * 3) + (1 * 2) + (2 * 6) + (3 * 4) = 0 + 2 + 12 + 12 = 26 26 | // 27 | // So the maximum value of F(0), F(1), F(2), F(3) is F(3) = 26. 28 | 29 | 30 | /** 31 | * @param {number[]} A 32 | * @return {number} 33 | */ 34 | var maxRotateFunction = function(A) { 35 | if(A.length===0) return 0; 36 | 37 | var res = [], 38 | n = A.length, 39 | sum=0, 40 | f=0; 41 | 42 | for(var i=0;i len * count) { 38 | n -= len * count; 39 | len++; 40 | count *= 10; 41 | start *= 10; 42 | } 43 | start += parseInt((n - 1) / len); 44 | var s = start.toString(); 45 | return +s.charAt((n - 1) % len); 46 | }; 47 | -------------------------------------------------------------------------------- /404-sum-of-left-leaves/sum-of-left-leaves.js: -------------------------------------------------------------------------------- 1 | // Find the sum of all left leaves in a given binary tree. 2 | // 3 | // Example: 4 | // 5 | // 3 6 | // / \ 7 | // 9 20 8 | // / \ 9 | // 15 7 10 | // 11 | // There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24. 12 | 13 | 14 | /** 15 | * Definition for a binary tree node. 16 | * function TreeNode(val) { 17 | * this.val = val; 18 | * this.left = this.right = null; 19 | * } 20 | */ 21 | /** 22 | * @param {TreeNode} root 23 | * @return {number} 24 | */ 25 | var sumOfLeftLeaves = function(root, isLeft = false) { 26 | if (!root) return 0; 27 | if (!root.left && !root.right) return isLeft ? root.val : 0; 28 | return sumOfLeftLeaves(root.left, true) + sumOfLeftLeaves(root.right, false); 29 | }; 30 | -------------------------------------------------------------------------------- /405-convert-a-number-to-hexadecimal/convert-a-number-to-hexadecimal.js: -------------------------------------------------------------------------------- 1 | // Given an integer, write an algorithm to convert it to hexadecimal. For negative integer, two’s complement method is used. 2 | // 3 | // 4 | // Note: 5 | // 6 | // All letters in hexadecimal (a-f) must be in lowercase. 7 | // The hexadecimal string must not contain extra leading 0s. If the number is zero, it is represented by a single zero character '0'; otherwise, the first character in the hexadecimal string will not be the zero character. 8 | // The given number is guaranteed to fit within the range of a 32-bit signed integer. 9 | // You must not use any method provided by the library which converts/formats the number to hex directly. 10 | // 11 | // 12 | // 13 | // Example 1: 14 | // 15 | // Input: 16 | // 26 17 | // 18 | // Output: 19 | // "1a" 20 | // 21 | // 22 | // 23 | // Example 2: 24 | // 25 | // Input: 26 | // -1 27 | // 28 | // Output: 29 | // "ffffffff" 30 | 31 | 32 | /** 33 | * @param {number} num 34 | * @return {string} 35 | */ 36 | var toHex = function(num) { 37 | if (num === 0) return '0'; 38 | var mp = '0123456789abcdef'; 39 | var ans = ''; 40 | for (var i = 0; i < 8; i++) { 41 | n = num & 15; 42 | c = mp[n]; 43 | ans = c + ans; 44 | num = num >> 4; 45 | } 46 | return ans.replace(/^[0]*/g, ''); 47 | }; 48 | -------------------------------------------------------------------------------- /409-longest-palindrome/longest-palindrome.js: -------------------------------------------------------------------------------- 1 | // Given a string which consists of lowercase or uppercase letters, find the length of the longest palindromes that can be built with those letters. 2 | // 3 | // This is case sensitive, for example "Aa" is not considered a palindrome here. 4 | // 5 | // Note: 6 | // Assume the length of given string will not exceed 1,010. 7 | // 8 | // 9 | // Example: 10 | // 11 | // Input: 12 | // "abccccdd" 13 | // 14 | // Output: 15 | // 7 16 | // 17 | // Explanation: 18 | // One longest palindrome that can be built is "dccaccd", whose length is 7. 19 | 20 | 21 | /** 22 | * @param {string} s 23 | * @return {number} 24 | */ 25 | var longestPalindrome = function(s) { 26 | var hashMap = {}; 27 | var result = 0; 28 | var hasSingle = 0; 29 | for (var i = 0, l = s.length; i <= l - 1; ++i) { 30 | if (!hashMap[s[i]]) { 31 | hashMap[s[i]] = 1; 32 | } else { 33 | hashMap[s[i]]++; 34 | } 35 | } 36 | for (var item in hashMap) { 37 | var even = hashMap[item] % 2; 38 | if (even) { 39 | result += hashMap[item] - 1; 40 | hasSingle = 1; 41 | } else { 42 | result += hashMap[item]; 43 | } 44 | } 45 | return result + hasSingle; 46 | }; 47 | -------------------------------------------------------------------------------- /412-fizz-buzz/fizz-buzz.js: -------------------------------------------------------------------------------- 1 | // Write a program that outputs the string representation of numbers from 1 to n. 2 | // 3 | // But for multiples of three it should output “Fizz” instead of the number and for the multiples of five output “Buzz”. For numbers which are multiples of both three and five output “FizzBuzz”. 4 | // 5 | // Example: 6 | // 7 | // n = 15, 8 | // 9 | // Return: 10 | // [ 11 | // "1", 12 | // "2", 13 | // "Fizz", 14 | // "4", 15 | // "Buzz", 16 | // "Fizz", 17 | // "7", 18 | // "8", 19 | // "Fizz", 20 | // "Buzz", 21 | // "11", 22 | // "Fizz", 23 | // "13", 24 | // "14", 25 | // "FizzBuzz" 26 | // ] 27 | 28 | 29 | /** 30 | * @param {number} n 31 | * @return {string[]} 32 | */ 33 | var fizzBuzz = function(n) { 34 | var res = []; 35 | for (var i = 0; i < n; i++) { 36 | res[i] = ''; 37 | if ((i + 1) % 3 === 0) { 38 | res[i] += 'Fizz'; 39 | } 40 | if ((i + 1) % 5 === 0) { 41 | res[i] += 'Buzz'; 42 | } 43 | if ((i + 1) % 3 !== 0 && (i + 1) % 5 !== 0) { 44 | res[i] += i + 1; 45 | } 46 | } 47 | return res; 48 | }; 49 | -------------------------------------------------------------------------------- /414-third-maximum-number/third-maximum-number.js: -------------------------------------------------------------------------------- 1 | // Given a non-empty array of integers, return the third maximum number in this array. If it does not exist, return the maximum number. The time complexity must be in O(n). 2 | // 3 | // Example 1: 4 | // 5 | // Input: [3, 2, 1] 6 | // 7 | // Output: 1 8 | // 9 | // Explanation: The third maximum is 1. 10 | // 11 | // 12 | // 13 | // Example 2: 14 | // 15 | // Input: [1, 2] 16 | // 17 | // Output: 2 18 | // 19 | // Explanation: The third maximum does not exist, so the maximum (2) is returned instead. 20 | // 21 | // 22 | // 23 | // Example 3: 24 | // 25 | // Input: [2, 2, 3, 1] 26 | // 27 | // Output: 1 28 | // 29 | // Explanation: Note that the third maximum here means the third maximum distinct number. 30 | // Both numbers with value 2 are both considered as second maximum. 31 | 32 | 33 | /** 34 | * @param {number[]} nums 35 | * @return {number} 36 | */ 37 | var thirdMax = function(nums) { 38 | var hashMap = {}; 39 | var j = 0; 40 | for (var i = 0, l = nums.length; i < l; i++) { 41 | if (!hashMap[nums[i]]) { 42 | hashMap[nums[i]] = true; 43 | } else { 44 | continue; 45 | } 46 | nums[j++] = nums[i]; 47 | } 48 | nums.length = j; 49 | var result = -Infinity; 50 | if (j < 3) { 51 | for (var i = 0; i < j; ++i) { 52 | result = Math.max(result, nums[i]); 53 | } 54 | return result; 55 | } else { 56 | nums.sort(function (prev, next) { 57 | if (next >= prev) return -1; 58 | return 1; 59 | }); 60 | return nums[j - 3] 61 | } 62 | }; 63 | -------------------------------------------------------------------------------- /415-add-strings/add-strings.js: -------------------------------------------------------------------------------- 1 | // Given two non-negative numbers num1 and num2 represented as string, return the sum of num1 and num2. 2 | // 3 | // Note: 4 | // 5 | // The length of both num1 and num2 is < 5100. 6 | // Both num1 and num2 contains only digits 0-9. 7 | // Both num1 and num2 does not contain any leading zero. 8 | // You must not use any built-in BigInteger library or convert the inputs to integer directly. 9 | 10 | 11 | /** 12 | * @param {string} num1 13 | * @param {string} num2 14 | * @return {string} 15 | */ 16 | var addStrings = function(num1, num2) { 17 | var carry = 0; 18 | var len1 = num1.length; 19 | var len2 = num2.length; 20 | var res = ''; 21 | while (len1 > 0 || len2 > 0) { 22 | var sum = (+num1[len1 - 1] || 0) + (+num2[len2 - 1] || 0) + carry; 23 | res = sum % 10 + '' + res; 24 | carry = Math.floor(sum / 10); 25 | len1--; 26 | len2-- 27 | } 28 | if (carry) res = '1' + res; 29 | return res; 30 | }; 31 | -------------------------------------------------------------------------------- /420-strong-password-checker/strong-password-checker.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | 3 | 4 | # A password is considered strong if below conditions are all met: 5 | # 6 | # 7 | # It has at least 6 characters and at most 20 characters. 8 | # It must contain at least one lowercase letter, at least one uppercase letter, and at least one digit. 9 | # It must NOT contain three repeating characters in a row ("...aaa..." is weak, but "...aa...a..." is strong, assuming other conditions are met). 10 | # 11 | # 12 | # Write a function strongPasswordChecker(s), that takes a string s as input, and return the MINIMUM change required to make s a strong password. If s is already strong, return 0. 13 | # 14 | # Insertion, deletion or replace of any one character are all considered as one change. 15 | 16 | 17 | class Solution(object): 18 | def strongPasswordChecker(self, s): 19 | """ 20 | :type s: str 21 | :rtype: int 22 | """ 23 | missing_type = 3 24 | if any(c.islower() for c in s): missing_type -= 1 25 | if any(c.isupper() for c in s): missing_type -= 1 26 | if any(c.isdigit() for c in s): missing_type -= 1 27 | 28 | change = 0 29 | one = two = 0 30 | p = 2 31 | while p < len(s): 32 | if s[p] == s[p-1] == s[p-2]: 33 | length = 2 34 | while p < len(s) and s[p] == s[p-1]: 35 | length += 1 36 | p += 1 37 | 38 | change += length / 3 39 | if length % 3 == 0: one += 1 40 | elif length % 3 == 1: two += 1 41 | else: 42 | p += 1 43 | 44 | if len(s) < 6: 45 | return max(missing_type, 6 - len(s)) 46 | elif len(s) <= 20: 47 | return max(missing_type, change) 48 | else: 49 | delete = len(s) - 20 50 | 51 | change -= min(delete, one) 52 | change -= min(max(delete - one, 0), two * 2) / 2 53 | change -= max(delete - one - 2 * two, 0) / 3 54 | 55 | return delete + max(missing_type, change) 56 | -------------------------------------------------------------------------------- /441-arranging-coins/arranging-coins.js: -------------------------------------------------------------------------------- 1 | // You have a total of n coins that you want to form in a staircase shape, where every k-th row must have exactly k coins. 2 | // 3 | // Given n, find the total number of full staircase rows that can be formed. 4 | // 5 | // n is a non-negative integer and fits within the range of a 32-bit signed integer. 6 | // 7 | // Example 1: 8 | // 9 | // n = 5 10 | // 11 | // The coins can form the following rows: 12 | // ¤ 13 | // ¤ ¤ 14 | // ¤ ¤ 15 | // 16 | // Because the 3rd row is incomplete, we return 2. 17 | // 18 | // 19 | // 20 | // Example 2: 21 | // 22 | // n = 8 23 | // 24 | // The coins can form the following rows: 25 | // ¤ 26 | // ¤ ¤ 27 | // ¤ ¤ ¤ 28 | // ¤ ¤ 29 | // 30 | // Because the 4th row is incomplete, we return 3. 31 | 32 | 33 | /** 34 | * @param {number} n 35 | * @return {number} 36 | */ 37 | var arrangeCoins = function(n) { 38 | return Math.floor(X = (Math.sqrt(8 * n + 1) - 1)/ 2); 39 | }; 40 | -------------------------------------------------------------------------------- /README_leetcode_generate.md: -------------------------------------------------------------------------------- 1 | # leetcode_generate Usage 2 | 3 | ![](https://github.com/bonfy/leetcode/blob/master/demo/leetcode.gif) 4 | 5 | ## Preparements: 6 | 7 | ```cmd 8 | pip install requests 9 | pip install pyquery 10 | ``` 11 | 12 | ## Config: 13 | 14 | Edit your own username, password, language and repo in the **config.cfg** file 15 | 16 | ``` 17 | [leetcode] 18 | 19 | username = username 20 | password = password 21 | language = python 22 | repo = https://github.com/bonfy/leetcode 23 | ``` 24 | 25 | ## Run 26 | 27 | ### Fully Download 28 | ```cmd 29 | python3 leetcode_generate.py 30 | ``` 31 | Usually you can always run fully download 32 | 33 | ### Download by id 34 | ``` 35 | python3 leetcode_generate.py 1 36 | python3 leetcode_generate.py 1 10 100 37 | ``` 38 | You can only download the solution you want. 39 | Just add the id arguments behind (seperate by space) 40 | 41 | 42 | ## Attention 43 | Python 3 have tested 44 | 45 | Python 2 maybe 46 | 47 | -------------------------------------------------------------------------------- /demo/leetcode.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/loatheb/leetcode-javascript/7b4e65cb24b8b3e2812b6d4d3700d5719d87d053/demo/leetcode.gif -------------------------------------------------------------------------------- /old/001-2sum.py: -------------------------------------------------------------------------------- 1 | # -*-coding: utf-8-*- 2 | 3 | # Given an array of integers, return indices of the two numbers 4 | # such that they add up to a specific target. 5 | 6 | # You may assume that each input would have exactly one solution. 7 | 8 | # Example: 9 | # Given nums = [2, 7, 11, 15], target = 9, 10 | 11 | # Because nums[0] + nums[1] = 2 + 7 = 9, 12 | # return [0, 1]. 13 | 14 | # python version: Python 3 15 | 16 | __Author__ = 'BONFY' 17 | 18 | 19 | class Solution: 20 | def twoSum(self, nums, target): 21 | """ 22 | :type nums: List[int] 23 | :type target: int 24 | :rtype: List[int] 25 | """ 26 | for i in range(len(nums)): 27 | if (target - nums[i]) in (nums[0:i] + [nums[i:]]): 28 | return sorted([i, nums.index(target - nums[i])]) 29 | 30 | 31 | # GOOD CASE 32 | class Solution2: 33 | def twoSum(self, nums, target): 34 | """ 35 | :type nums: List[int] 36 | :type target: int 37 | :rtype: List[int] 38 | """ 39 | d = {} 40 | for i, v in enumerate(nums): 41 | if v in d: 42 | return [d[v], i] 43 | d[target-v] = i 44 | 45 | 46 | if __name__ == '__main__': 47 | result = Solution2().twoSum([3, 2, 4], 6) 48 | print(result) 49 | 50 | result = Solution2().twoSum([0, 2, 1, 0], 0) 51 | print(result) 52 | -------------------------------------------------------------------------------- /old/004-median-of-two-sorted-arrays.py: -------------------------------------------------------------------------------- 1 | # -*-coding:utf-8-*- 2 | 3 | # There are two sorted arrays nums1 and nums2 of size m and n respectively. 4 | 5 | # Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)). 6 | 7 | # Example 1: 8 | # nums1 = [1, 3] 9 | # nums2 = [2] 10 | 11 | # The median is 2.0 12 | # Example 2: 13 | # nums1 = [1, 2] 14 | # nums2 = [3, 4] 15 | 16 | # The median is (2 + 3)/2 = 2.5 17 | # Subscribe to see which companies asked this question 18 | 19 | # python version: Python 3 20 | 21 | __Author__ = 'BONFY' 22 | 23 | 24 | class Solution(object): 25 | def findMedianSortedArrays(self, nums1, nums2): 26 | """ 27 | :type nums1: List[int] 28 | :type nums2: List[int] 29 | :rtype: float 30 | """ 31 | l = len(nums1) + len(nums2) 32 | return self.findKth(nums1, nums2, l//2) if l % 2 == 1 else (self.findKth(nums1, nums2, l//2-1)+self.findKth(nums1, nums2, l//2))/2.0 33 | 34 | def findKth(self, nums1, nums2, k): 35 | if len(nums1) > len(nums2): 36 | nums1, nums2 = nums2, nums1 37 | if not nums1: 38 | return nums2[k] 39 | if k == len(nums1) + len(nums2) - 1: 40 | return max(nums1[-1], nums2[-1]) 41 | i = len(nums1)//2 42 | j = k-i 43 | if nums1[i] > nums2[j]: 44 | #Here I assume it is O(1) to get nums1[:i] and nums2[j:]. In python, it's not but in cpp it is. 45 | return self.findKth(nums1[:i], nums2[j:], i) 46 | else: 47 | return self.findKth(nums1[i:], nums2[:j], j) 48 | 49 | if __name__ == '__main__': 50 | nums1 = [1, 3] 51 | nums2 = [2] 52 | print(Solution().findMedianSortedArrays(nums1, nums2)) 53 | 54 | nums1 = [1, 2] 55 | nums2 = [3, 4] 56 | print(Solution().findMedianSortedArrays(nums1, nums2)) 57 | 58 | nums1 = [2, 3, 4] 59 | nums2 = [1] 60 | print(Solution().findMedianSortedArrays(nums1, nums2)) 61 | -------------------------------------------------------------------------------- /old/005-longest-palindromic-substring.py: -------------------------------------------------------------------------------- 1 | # -*-coding:utf-8-*- 2 | 3 | # Given a string S, find the longest palindromic substring in S. 4 | # You may assume that the maximum length of S is 1000, 5 | # and there exists one unique longest palindromic substring. 6 | 7 | # python version: Python 3 8 | 9 | __Author__ = 'BONFY' 10 | 11 | 12 | class Solution: 13 | def longestPalindrome(self, s): 14 | """ 15 | :type s: str 16 | :rtype: str 17 | """ 18 | longest, mid = "", (len(s) - 1) // 2 19 | i, j = mid, mid 20 | while i >= 0 and j < len(s): 21 | args = [(s, i, i), (s, i, i + 1), (s, j, j), (s, j, j + 1)] 22 | for arg in args: 23 | tmp = self.longestPalindromeByAxis(*arg) 24 | if len(tmp) > len(longest): 25 | longest = tmp 26 | if len(longest) >= i * 2: 27 | 28 | # leetcode 回文字符串长度为1 时要求返回第一个字母 29 | # 加上后两句 30 | if len(longest) == 1: 31 | return s[0] 32 | 33 | return longest 34 | i, j = i - 1, j + 1 35 | return longest 36 | 37 | def longestPalindromeByAxis(self, s, left, right): 38 | while left >= 0 and right < len(s) and s[left] == s[right]: 39 | left, right = left - 1, right + 1 40 | return s[left + 1: right] 41 | 42 | 43 | if __name__ == '__main__': 44 | print(Solution().longestPalindrome('abcdefghgfedasd')) 45 | -------------------------------------------------------------------------------- /old/007-reverse-integer.py: -------------------------------------------------------------------------------- 1 | # -*-coding:utf-8-*- 2 | 3 | # Reverse digits of an integer. 4 | 5 | # Example1: x = 123, return 321 6 | # Example2: x = -123, return -321 7 | 8 | # click to show spoilers. 9 | 10 | # Have you thought about this? 11 | # Here are some good questions to ask before coding. Bonus points for you if you have already thought through this! 12 | 13 | # If the integer's last digit is 0, what should the output be? ie, cases such as 10, 100. 14 | 15 | # Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. 16 | # How should you handle such cases? 17 | 18 | # For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows. 19 | 20 | # python version: Python 3 21 | 22 | __Author__ = 'BONFY' 23 | 24 | 25 | class Solution: 26 | def reverse(self, x): 27 | """ 28 | :type x: int 29 | :rtype: int 30 | """ 31 | l = list(str(abs(x))) 32 | l = l[::-1] 33 | rst = int(''.join(l)) 34 | # 这里leetcode 是python 2.7 考虑 int overflow 返回 0 35 | # import sys 36 | # sys.maxint = 2147483647 37 | if rst > 2147483647: 38 | return 0 39 | else: 40 | return rst if x >= 0 else rst * (-1) 41 | 42 | 43 | if __name__ == '__main__': 44 | print(Solution().reverse(-123)) 45 | -------------------------------------------------------------------------------- /old/008-string-to-integer-atoi.py: -------------------------------------------------------------------------------- 1 | # -*-coding:utf-8-*- 2 | 3 | # Implement atoi to convert a string to an integer. 4 | 5 | # Hint: Carefully consider all possible input cases. 6 | # If you want a challenge, please do not see below and ask yourself what are the possible input cases. 7 | 8 | # Notes: It is intended for this problem to be specified vaguely 9 | # (ie, no given input specs). You are responsible to gather all the input requirements up front. 10 | 11 | # python version: Python 3 12 | 13 | __Author__ = 'BONFY' 14 | 15 | 16 | class Solution: 17 | def myAtoi(self, str): 18 | """ 19 | :type str: str 20 | :rtype: int 21 | """ 22 | import re 23 | p = re.compile(r'^[+-]?[0-9]+') 24 | m = re.match(p, str.strip()) 25 | if m: 26 | ret = int(m.group()) 27 | if ret < -0x80000000: 28 | return -0x80000000 29 | elif ret > 0x7fffffff: 30 | return 0x7fffffff 31 | return ret 32 | else: 33 | return 0 34 | 35 | 36 | if __name__ == '__main__': 37 | print(Solution().myAtoi('1234')) 38 | -------------------------------------------------------------------------------- /old/009-palindrome-number.py: -------------------------------------------------------------------------------- 1 | # -*-coding:utf-8-*- 2 | 3 | # Determine whether an integer is a palindrome. Do this without extra space. 4 | 5 | # click to show spoilers. 6 | 7 | # Some hints: 8 | # Could negative integers be palindromes? (ie, -1) 9 | 10 | # If you are thinking of converting the integer to string, note the restriction of using extra space. 11 | 12 | # You could also try reversing an integer. However, if you have solved the problem "Reverse Integer", 13 | # you know that the reversed integer might overflow. How would you handle such case? 14 | 15 | # There is a more generic way of solving this problem. 16 | 17 | 18 | # python version: Python 3 19 | 20 | __Author__ = 'BONFY' 21 | 22 | 23 | class Solution: 24 | def isPalindrome(self, x): 25 | """ 26 | :type x: int 27 | :rtype: bool 28 | """ 29 | if x < 0: 30 | return False 31 | x = abs(x) 32 | l = len(str(x)) 33 | i = 1 34 | while i < l // 2 + 1: 35 | 36 | head = (x // 10 ** (l-i)) % 10 37 | tail = (x % 10 ** i) if i == 1 else (x % 10 ** i) // (10 ** (i-1)) 38 | if head != tail: 39 | return False 40 | i = i + 1 41 | 42 | return True 43 | 44 | 45 | if __name__ == '__main__': 46 | print(Solution().isPalindrome(10011001)) 47 | -------------------------------------------------------------------------------- /old/010-regular-expression-matching.py: -------------------------------------------------------------------------------- 1 | # -*-coding:utf-8-*- 2 | 3 | # Implement regular expression matching with support for '.' and '*'. 4 | 5 | # '.' Matches any single character. 6 | # '*' Matches zero or more of the preceding element. 7 | 8 | # The matching should cover the entire input string (not partial). 9 | 10 | # The function prototype should be: 11 | # bool isMatch(const char *s, const char *p) 12 | 13 | # Some examples: 14 | # isMatch("aa","a") → false 15 | # isMatch("aa","aa") → true 16 | # isMatch("aaa","aa") → false 17 | # isMatch("aa", "a*") → true 18 | # isMatch("aa", ".*") → true 19 | # isMatch("ab", ".*") → true 20 | # isMatch("aab", "c*a*b") → true 21 | 22 | __Auther__ = 'BONFY' 23 | 24 | 25 | class Solution: 26 | def isMatch(self, s, p): 27 | """ 28 | :type s: str 29 | :type p: str 30 | :rtype: bool 31 | """ 32 | result = [[False for _ in range(len(p) + 1)] for _ in range(len(s) + 1)] 33 | 34 | result[0][0] = True 35 | for i in range(2, len(p) + 1): 36 | if p[i-1] == '*': 37 | result[0][i] = result[0][i-2] 38 | 39 | for i in range(1, len(s) + 1): 40 | for j in range(1, len(p) + 1): 41 | if p[j-1] != '*': 42 | result[i][j] = result[i-1][j-1] and (s[i-1] == p[j-1] or p[j-1] == '.') 43 | else: 44 | result[i][j] = result[i][j-2] or (result[i-1][j] and (s[i-1] == p[j-2] or p[j-2] == '.')) 45 | 46 | return result[len(s)][len(p)] 47 | 48 | 49 | if __name__ == '__main__': 50 | print(Solution().isMatch("aab", "c.a.b")) 51 | print(Solution().isMatch("ab", ".*")) 52 | print(Solution().isMatch("aab", "a*b")) 53 | print(Solution().isMatch("aab", "b*b")) 54 | -------------------------------------------------------------------------------- /old/011-Container-With-Most-Water.py: -------------------------------------------------------------------------------- 1 | # -*-coding:utf-8-*- 2 | 3 | # Given n non-negative integers a1, a2, ..., an, 4 | # where each represents a point at coordinate (i, ai). 5 | # n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). 6 | # Find two lines, which together with x-axis forms a container, 7 | # such that the container contains the most water. 8 | 9 | # Note: You may not slant the container. 10 | 11 | # python version: Python 3 12 | 13 | __Auther__ = 'BONFY' 14 | 15 | 16 | class Solution: 17 | def maxArea(self, height): 18 | """ 19 | :type height: List[int] 20 | :rtype: int 21 | """ 22 | max_area, i, j = 0, 0, len(height) - 1 23 | while i < j: 24 | max_area = max(max_area, min(height[i], height[j]) * (j - i)) 25 | if height[i] < height[j]: 26 | i += 1 27 | else: 28 | j -= 1 29 | return max_area 30 | 31 | 32 | # Time Limit Exceeded 33 | class Solution2: 34 | def maxArea(self, height): 35 | """ 36 | :type height: List[int] 37 | :rtype: int 38 | """ 39 | m, l = 0, len(height) 40 | for i in range(0, l//2): 41 | for j in range(i+1, l): 42 | m = max(m, min(height[i], height[j]) * (j-i)) 43 | return m 44 | 45 | 46 | if __name__ == '__main__': 47 | print(Solution().maxArea([28, 342, 418, 485, 719])) 48 | -------------------------------------------------------------------------------- /old/012-Integer-to-Roman.py: -------------------------------------------------------------------------------- 1 | # -*-coding:utf-8-*- 2 | 3 | # Given n non-negative integers a1, a2, ..., an, 4 | # where each represents a point at coordinate (i, ai). 5 | # n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). 6 | # Find two lines, which together with x-axis forms a container, 7 | # such that the container contains the most water. 8 | 9 | # Note: You may not slant the container. 10 | 11 | # python version: Python 3 12 | 13 | __Auther__ = 'BONFY' 14 | 15 | 16 | class Solution: 17 | def intToRoman(self, num): 18 | """ 19 | :type num: int 20 | :rtype: str 21 | """ 22 | int2roman = { 23 | 1: "I", 24 | 4: "IV", 25 | 5: "V", 26 | 9: "IX", 27 | 28 | 10: "X", 29 | 40: "XL", 30 | 50: "L", 31 | 90: "XC", 32 | 33 | 100: "C", 34 | 400: "CD", 35 | 500: "D", 36 | 900: "CM", 37 | 38 | 1000: "M" 39 | } 40 | 41 | builder = [] 42 | components = list(sorted(int2roman.keys()))[::-1] 43 | for item in components: 44 | while num >= item: 45 | builder.append(int2roman[item]) 46 | num -= item 47 | return "".join(builder) 48 | 49 | 50 | if __name__ == '__main__': 51 | print(Solution().intToRoman(1)) 52 | print(Solution().intToRoman(3999)) 53 | -------------------------------------------------------------------------------- /old/013-Roman-to-Integer.py: -------------------------------------------------------------------------------- 1 | # -*-coding:utf-8-*- 2 | 3 | # Given a roman numeral, convert it to an integer. 4 | 5 | # Input is guaranteed to be within the range from 1 to 3999. 6 | 7 | # python version: Python 3 8 | 9 | 10 | __Auther__ = 'BONFY' 11 | 12 | 13 | class Solution: 14 | def romanToInt(self, s): 15 | """ 16 | :type s: str 17 | :rtype: int 18 | """ 19 | roman = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000} 20 | total = 0 21 | for index in range(len(s)-1): 22 | type = 1 if roman[s[index]] >= roman[s[index+1]] else -1 23 | total += type*roman[s[index]] 24 | return total + roman[s[len(s)-1]] 25 | 26 | 27 | if __name__ == '__main__': 28 | print(Solution().romanToInt('DCXXI')) 29 | -------------------------------------------------------------------------------- /old/014-longest-common-prefix.py: -------------------------------------------------------------------------------- 1 | # -*-coding:utf-8-*- 2 | 3 | # Write a function to find the longest common prefix string amongst an array of strings. 4 | 5 | # python version: Python 3 6 | 7 | 8 | __Auther__ = 'BONFY' 9 | 10 | 11 | class Solution: 12 | def longestCommonPrefix(self, strs): 13 | """ 14 | :type strs: List[str] 15 | :rtype: str 16 | """ 17 | if not strs: 18 | return "" 19 | strs = sorted(strs, key=lambda str: len(str)) 20 | idx, p, rest = 0, strs[0], strs[1:] 21 | while len(p) > 0: 22 | while idx < len(rest) and p == rest[idx][:len(p)]: 23 | idx += 1 24 | if idx == len(rest): 25 | return p 26 | p = p[:-1] 27 | return "" 28 | 29 | 30 | # 少一步排序,更优 31 | class Solution2: 32 | def longestCommonPrefix(self, strs): 33 | """ 34 | :type strs: List[str] 35 | :rtype: str 36 | """ 37 | if not strs: 38 | return "" 39 | if len(strs) == 1: 40 | return strs[0] 41 | idx, p, rest = 0, strs[0], strs[1:] 42 | while len(p) > 0: 43 | while idx < len(rest) and len(p) <= len(rest[idx]) and p == rest[idx][:len(p)]: 44 | idx += 1 45 | if idx == len(rest): 46 | return p 47 | p = p[:-1] 48 | return "" 49 | 50 | 51 | if __name__ == '__main__': 52 | strs = ['abd', 'abc', 'abcd', 'abdcdss', 'aaaadss'] 53 | import time 54 | start = time.clock() 55 | print(Solution().longestCommonPrefix(strs)) 56 | end = time.clock() 57 | print(end-start) 58 | 59 | start = time.clock() 60 | print(Solution2().longestCommonPrefix(strs)) 61 | end = time.clock() 62 | print(end-start) 63 | 64 | -------------------------------------------------------------------------------- /old/015-3Sum.py: -------------------------------------------------------------------------------- 1 | # -*-coding:utf-8-*- 2 | 3 | # Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? 4 | # Find all unique triplets in the array which gives the sum of zero. 5 | 6 | # Note: The solution set must not contain duplicate triplets. 7 | 8 | # For example, given array S = [-1, 0, 1, 2, -1, -4], 9 | 10 | # A solution set is: 11 | # [ 12 | # [-1, 0, 1], 13 | # [-1, -1, 2] 14 | # ] 15 | 16 | # python version: Python 3 17 | 18 | 19 | __Auther__ = 'BONFY' 20 | 21 | 22 | class Solution: 23 | def threeSum(self, nums): 24 | """ 25 | :type nums: List[int] 26 | :rtype: List[List[int]] 27 | """ 28 | nums.sort() 29 | res = [] 30 | 31 | for i in range(len(nums)-1): # because sums of 3 numbers 32 | if i == 0 or i > 0 and nums[i-1] != nums[i]: 33 | # avoid duplicate triplets [1 ,1, 1, -2] 34 | left = i + 1 35 | right = len(nums) - 1 36 | while left < right: # two-way pointer 37 | s = nums[i] + nums[left] + nums[right] 38 | if s == 0: 39 | res.append([nums[i], nums[left], nums[right]]) 40 | left += 1 41 | right -= 1 42 | while left < right and nums[left] == nums[left - 1]: 43 | left += 1 44 | while right > left and nums[right] == nums[right + 1]: 45 | right -= 1 46 | elif s < 0: 47 | left += 1 48 | else: 49 | right -= 1 50 | return res 51 | 52 | 53 | if __name__ == '__main__': 54 | print(Solution().threeSum([-1, 0, 1, 2, -1, -4])) -------------------------------------------------------------------------------- /old/016-3sum-closest.py: -------------------------------------------------------------------------------- 1 | # -*-coding:utf-8-*- 2 | 3 | # Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution. 4 | 5 | # For example, given array S = {-1 2 1 -4}, and target = 1. 6 | 7 | # The sum that is closest to the target is 2. (-1 + 2 + 1 = 2). 8 | 9 | # python version: Python 3 10 | 11 | 12 | __Auther__ = 'BONFY' 13 | 14 | 15 | class Solution: 16 | def threeSumClosest(self, nums, target): 17 | """ 18 | :type nums: List[int] 19 | :type target: int 20 | :rtype: int 21 | """ 22 | nums.sort() 23 | result = sum(nums[:3]) 24 | for i in range(len(nums) - 2): 25 | j, k = i+1, len(nums) - 1 26 | while j < k: 27 | s = nums[i] + nums[j] + nums[k] 28 | if s == target: 29 | return s 30 | 31 | if abs(s - target) < abs(result - target): 32 | result = s 33 | 34 | if s < target: 35 | j += 1 36 | elif s > target: 37 | k -= 1 38 | return result 39 | 40 | 41 | if __name__ == '__main__': 42 | print(Solution().threeSumClosest([-1, 2, 1, -4], 1)) 43 | -------------------------------------------------------------------------------- /old/017-letter-combinations-of-a-phone-number.py: -------------------------------------------------------------------------------- 1 | # -*-coding:utf-8-*- 2 | 3 | # Given a digit string, return all possible letter combinations that the number could represent. 4 | 5 | # A mapping of digit to letters (just like on the telephone buttons) is given below. 6 | 7 | # 2 - abc 8 | # 3 - efg 9 | # 4 - ghi 10 | # 5 - jkl 11 | # 6 - mno 12 | # 7 - pqrs 13 | # 8 - tuv 14 | # 9 - wxyz 15 | 16 | # Input:Digit string "23" 17 | # Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]. 18 | 19 | 20 | # python version: Python 3 21 | 22 | __Author = 'BONFY' 23 | 24 | 25 | class Solution: 26 | def letterCombinations(self, digits): 27 | """ 28 | :type digits: str 29 | :rtype: List[str] 30 | """ 31 | l = ['', '', 'abc', 'def', 'ghi', 'jkl', 'mno', 'pqrs', 'tuv', 'wxyz'] 32 | end = [''] 33 | rst = [] 34 | d = digits 35 | 36 | while len(d): 37 | f = int(d[-1]) 38 | lst_f = list(l[f]) 39 | rst = [''.join([i, j]) for i in lst_f for j in end] 40 | end = rst 41 | d = d[:-1] 42 | return rst 43 | 44 | 45 | # Python 2.7 reduce 46 | # one line solution 47 | class Solution2: 48 | def letterCombinations(self, digits): 49 | if '' == digits: 50 | return [] 51 | kvmaps = { 52 | '2': 'abc', 53 | '3': 'def', 54 | '4': 'ghi', 55 | '5': 'jkl', 56 | '6': 'mno', 57 | '7': 'pqrs', 58 | '8': 'tuv', 59 | '9': 'wxyz' 60 | } 61 | return reduce(lambda acc, digit: [x + y for x in acc for y in kvmaps[digit]], digits, ['']) 62 | 63 | if __name__ == '__main__': 64 | print(Solution2().letterCombinations('23')) 65 | -------------------------------------------------------------------------------- /old/025-remove-duplicates-from-sorted-array.py: -------------------------------------------------------------------------------- 1 | # -*-coding:utf-8-*- 2 | 3 | # Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length. 4 | 5 | # Do not allocate extra space for another array, you must do this in place with constant memory. 6 | 7 | # For example, 8 | # Given input array nums = [1,1,2], 9 | 10 | # Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. It doesn't matter what you leave beyond the new length. 11 | 12 | 13 | # python version: Python 3 14 | 15 | __Author = 'BONFY' 16 | 17 | 18 | class Solution(object): 19 | def removeDuplicates(self, nums): 20 | """ 21 | :type nums: List[int] 22 | :rtype: int 23 | """ 24 | if not nums: 25 | return 0 26 | n = len(nums) 27 | count = curr = 1 28 | while count < n: 29 | if nums[curr] != nums[curr-1]: 30 | curr += 1 31 | else: 32 | del nums[curr] 33 | count += 1 34 | return curr 35 | 36 | if __name__ == '__main__': 37 | print(Solution().removeDuplicates([1, 1, 2, 2, 3, 3, 4, 4, 5])) 38 | -------------------------------------------------------------------------------- /old/125-valid-palindrome.py: -------------------------------------------------------------------------------- 1 | # -*-coding:utf-8-*- 2 | 3 | # Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases. 4 | 5 | # For example, 6 | # "A man, a plan, a canal: Panama" is a palindrome. 7 | # "race a car" is not a palindrome. 8 | 9 | # Note: 10 | # Have you consider that the string might be empty? This is a good question to ask during an interview. 11 | 12 | # For the purpose of this problem, we define empty string as valid palindrome. 13 | 14 | # python version: Python 3 15 | 16 | 17 | # Solution TLE : Time Limit Exceeded 18 | class Solution: 19 | def isPalindrome(self, s): 20 | """ 21 | :type s: str 22 | :rtype: bool 23 | """ 24 | words = 'abcdefghijklmnopqrstuvwxyz0123456789' 25 | s_clean = '' 26 | for _, w in enumerate(s): 27 | if w.lower() in words: 28 | s_clean += w.lower() 29 | s_reverse = ''.join(list(s_clean)[::-1]) 30 | return s_clean == s_reverse 31 | 32 | 33 | # Solution :GOOD 34 | class Solution2: 35 | def isPalindrome(self, s): 36 | """ 37 | :type s: str 38 | :rtype: bool 39 | """ 40 | s = filter(str.isalnum, str(s.lower())) 41 | return s == s[::-1] 42 | 43 | 44 | if __name__ == '__main__': 45 | print(Solution2().isPalindrome('A man, a plan, a canal: Panama')) 46 | --------------------------------------------------------------------------------