├── .gitignore ├── LICENSE ├── README.md ├── TAG.md ├── java ├── _001TwoSum.java ├── _002AddTwoNumbers.java ├── _003LongestSubStringWithoutRepeatingCharacters.java ├── _004MedianOfTwoSortedArrays.java ├── _007ReverseInteger.java ├── _009PalindromeNumber.java ├── _013RomanToInteger.java ├── _0184Sum.java ├── _019RemoveNthNodeFromEndOfList.java ├── _020ValidParentheses.java ├── _021MergeTwoSortedLists.java ├── _023MergeKSortedLists.java ├── _024SwapNodesInPairs.java ├── _025ReverseNodesInKGroup.java ├── _042TrappingRainWater.java ├── _071SimplifyPath.java ├── _094BinaryTreeInorderTraversal.java ├── _095UniqueBinarySearchTreesII.java ├── _096UniqueBinarySearchTrees.java ├── _098ValidateBinarySearchTree.java ├── _099RecoverBinarySearchTree.java ├── _100SameTree.java ├── _101SymmetricTree.java ├── _102BinaryTreeLevelOrderTraversal.java ├── _103BinaryTreeZigzagLevelOrderTraversal.java ├── _144BinaryTreePreorderTraversal.java ├── _145BinaryTreePostorderTraversal.java ├── _150EvaluateReversePolishNotation.java ├── _155MinStack.java ├── _173BinarySearchTreeIterator.java ├── _215KthLargestElementInAnArray.java ├── _224BasicCalculator.java ├── _225ImplementStackUsingQueues.java ├── _232ImplementQueueUsingStacks.java ├── _239SlidingWindowMaximum.java ├── _257BinaryTreePaths.java ├── _258AddDigits.java ├── _260SingleNumberIII.java ├── _264UglyNumberII.java ├── _273IntegertoEnglishWords.java ├── _274H_Index.java ├── _283MoveZeroes.java ├── _292NimGame.java ├── _295FindMedianFromDataStream.java ├── _299BullsandCows.java ├── _313SuperUglyNumber.java ├── _316RemoveDuplicateLetters.java ├── _331VerifyPreorderSerializationOfABinaryTree.java ├── _341FlattenNestedListIterator.java ├── _347TopKFrequentElements.java ├── _385MiniParser.java ├── _387FirstUniqueCharacterinaString.java ├── _394DecodeString.java ├── _402RemoveKDigits.java ├── _456132Pattern.java └── _496NextGreaterElementI.java └── python ├── 001 Two Sum.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.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 ├── 018 4Sum.py ├── 019 Remove Nth Node From End of List.py ├── 020 Valid Parentheses.py ├── 021 Merge Two Sorted Lists.py ├── 022 Generate Parentheses.py ├── 023 Merge k Sorted Lists.py ├── 024 Swap Nodes in Pairs.py ├── 025 Reverse Nodes in k-Group.py ├── 026 Remove Duplicates from Sorted Array.py ├── 027 Remove Element.py ├── 028 Implement strStr().py ├── 029 Divide Two Integers.py ├── 030 Substring with Concatenation of All Words.py ├── 031 Next Permutation.py ├── 032 Longest Valid Parentheses.py ├── 033 Search in Rotated Sorted Array.py ├── 034 Search for a Range.py ├── 035 Search Insert Position.py ├── 036 Valid Sudoku.py ├── 037 Sudoku Solver.py ├── 038 Count and Say.py ├── 039 Combination Sum.py ├── 040 Combination Sum II.py ├── 041 First Missing Positive.py ├── 042 Trapping Rain Water.py ├── 043 Multiply Strings.py ├── 044 Wildcard Matching.py ├── 045 Jump Game II.py ├── 046 Permutations.py ├── 047 Permutations II.py ├── 048 Rotate Image.py ├── 049 Group Anagrams.py ├── 050 Pow(x, n).py ├── 051 N-Queens.py ├── 052 N-Queens II.py ├── 053 Maximum Subarray.py ├── 054 Spiral Matrix.py ├── 055 Jump Game.py ├── 056 Merge Intervals.py ├── 057 Insert Interval.py ├── 058 Length of Last Word.py ├── 059 Spiral Matrix II.py ├── 060 Permutation Sequence.py ├── 061 Rotate List.py ├── 062 Unique Paths.py ├── 063 Unique Paths II.py ├── 064 Minimum Path Sum.py ├── 065 Valid Number.py ├── 066 Plus One.py ├── 067 Add Binary.py ├── 068 Text Justification.py ├── 069 Sqrt(x).py ├── 070 Climbing Stairs.py ├── 071 Simplify Path.py ├── 072 Edit Distance.py ├── 073 Set Matrix Zeroes.py ├── 074 Search a 2D Matrix.py ├── 075 Sort Colors.py ├── 076 Minimum Window Substring.py ├── 077 Combinations.py ├── 078 Subsets.py ├── 079 Word Search.py ├── 080 Remove Duplicates from Sorted Array II.py ├── 081 Search in Rotated Sorted Array II.py ├── 082 Remove Duplicates from Sorted List II.py ├── 083 Remove Duplicates from Sorted List.py ├── 084 Largest Rectangle in Histogram.py ├── 085 Maximal Rectangle.py ├── 086 Partition List.py ├── 087 Scramble String.py ├── 088 Merge Sorted Array.py ├── 089 Gray Code.py ├── 090 Subsets II.py ├── 091 Decode Ways.py ├── 092 Reverse Linked List II.py ├── 093 Restore IP Addresses.py ├── 094 Binary Tree Inorder Traversal.py ├── 095 Unique Binary Search Trees II.py ├── 096 Unique Binary Search Trees.py ├── 097 Interleaving String.py ├── 098 Validate Binary Search Tree.py ├── 099 Recover Binary Search Tree.py ├── 100 Same Tree.py ├── 101 Symmetric Tree.py ├── 102 Binary Tree Level Order Traversal.py ├── 103 Binary Tree Zigzag Level Order Traversal.py ├── 104 Maximum Depth of Binary Tree.py ├── 105 Construct Binary Tree from Preorder and Inorder Traversal.py ├── 106 Construct Binary Tree from Inorder and Postorder Traversal.py ├── 107 Binary Tree Level Order Traversal II.py ├── 108 Convert Sorted Array to Binary Search Tree.py ├── 109 Convert Sorted List to Binary Search Tree.py ├── 110 Balanced Binary Tree.py ├── 111 Minimum Depth of Binary Tree.py ├── 112 Path Sum.py ├── 113 Path Sum II.py ├── 114 Flatten Binary Tree to Linked List.py ├── 115 Distinct Subsequences.py ├── 116 Populating Next Right Pointers in Each Node.py ├── 117 Populating Next Right Pointers in Each Node II.py ├── 118 Pascal's Triangle.py ├── 119 Pascal's Triangle II.py ├── 120 Triangle.py ├── 121 Best Time to Buy and Sell Stock.py ├── 122 Best Time to Buy and Sell Stock II.py ├── 123 Best Time to Buy and Sell Stock III.py ├── 124 Binary Tree Maximum Path Sum.py ├── 125 Valid Palindrome.py ├── 126 Word Ladder II.py ├── 127 Word Ladder.py ├── 128 Longest Consecutive Sequence.py ├── 129 Sum Root to Leaf Numbers.py ├── 130 Surrounded Regions.py ├── 131 Palindrome Partitioning.py ├── 132 Palindrome Partitioning II.py ├── 133 Clone Graph.py ├── 134 Gas Station.py ├── 135 Candy.py ├── 136 Single Number.py ├── 137 Single Number II.py ├── 138 Copy List with Random Pointer.py ├── 139 Word Break.py ├── 140 Word Break II.py ├── 141 Linked List Cycle.py ├── 142 Linked List Cycle II.py ├── 143 Reorder List.py ├── 144 Binary Tree Preorder Traversal.py ├── 145 Binary Tree Postorder Traversal.py ├── 146 LRU Cache.py ├── 147 Insertion Sort List.py ├── 149 Max Points on a Line.py ├── 150 Evaluate Reverse Polish Notation.py ├── 151 Reverse Words in a String.py ├── 152 Maximum Product Subarray.py ├── 153 Find Minimum in Rotated Sorted Array.py ├── 155 Min Stack.py ├── 160 Intersection of Two Linked Lists.py ├── 162 Find Peak Element.py ├── 164 Maximum Gap.py ├── 165 Compare Version Numbers.py ├── 166 Fraction to Recurring Decimal.py ├── 168 Excel Sheet Column Title.py ├── 169 Majority Element.py ├── 171 Excel Sheet Column Number.py ├── 172 Factorial Trailing Zeroes.py ├── 173 Binary Search Tree Iterator.py ├── 174 Dungeon Game.py ├── 179 Largest Number.py ├── 189 Rotate Array.py ├── 190 Reverse Bits.py ├── 191 Number of 1 Bits.py ├── 198 House Robber.py ├── 199 Binary Tree Right Side View.py ├── 200 Number of Islands.py ├── 201 Bitwise AND of Numbers Range.py ├── 202 Happy Number.py ├── 203 Remove Linked List Elements.py ├── 204 Count Primes.py ├── 205 Isomorphic Strings.py ├── 206 Reverse Linked List.py ├── 207 Course Schedule.py ├── 217 Contains Duplicate.py ├── 219 Contains Duplicate II.py ├── 233 Number of Digit One.py ├── 234 Palindrome Linked List.py ├── 237 Delete Node in a Linked List.py ├── 238 Product of Array Except Self.py └── 242 Valid Anagram.py /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | 5 | # C extensions 6 | *.so 7 | 8 | # Distribution / packaging 9 | .Python 10 | env/ 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | *.egg-info/ 23 | .installed.cfg 24 | *.egg 25 | 26 | # PyInstaller 27 | # Usually these files are written by a python script from a template 28 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 29 | *.manifest 30 | *.spec 31 | 32 | # Installer logs 33 | pip-log.txt 34 | pip-delete-this-directory.txt 35 | 36 | # Unit test / coverage reports 37 | htmlcov/ 38 | .tox/ 39 | .coverage 40 | .coverage.* 41 | .cache 42 | nosetests.xml 43 | coverage.xml 44 | *,cover 45 | 46 | # Translations 47 | *.mo 48 | *.pot 49 | 50 | # Django stuff: 51 | *.log 52 | 53 | # Sphinx documentation 54 | docs/_build/ 55 | 56 | # PyBuilder 57 | target/ 58 | 59 | # IntelliJ Idea 60 | out/ 61 | .idea/ 62 | *.iml 63 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2017 Drfish 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # leetcode-share 2 | 3 | [![Language python](https://img.shields.io/badge/python-3.5-blue.svg)](https://www.python.org) 4 | [![Language java](https://img.shields.io/badge/java-8-orange.svg)](http://www.oracle.com/technetwork/java/javase/overview/java8-2100321.html) 5 | [![License](https://img.shields.io/dub/l/vibe-d.svg)](https://opensource.org/licenses/MIT) 6 | 7 | This repository shares my experience in solving leetcode problems. The first edition was written in Python3, and now I am working on resolving them with Java8. There are articles describing the solution. For further information, please see the Articles part. 8 | 9 | ## Problems 10 | 11 | You can find all the problems on [LeetCode](https://leetcode.com). 12 | 13 | ## Issue 14 | 15 | You are welcome if you have any question or suggestion. 16 | 17 | ## Tag 18 | 19 | I have classified the problems into different tags like the leetcode OJ does. You can check them [here](./TAG.md). 20 | 21 | ## Articles 22 | 23 | There are articles about each problem, describing how I solve that problem. You can visit them on [GitBook](https://shenjie1993.gitbooks.io/leetcode-python/content/) or [CSDN](http://blog.csdn.net/column/details/leetcode-python.html). 24 | 25 | It is a pity that they are only in Chinese. 26 | 27 | ## License 28 | 29 | [MIT LICENSE](./LICENSE) -------------------------------------------------------------------------------- /java/_001TwoSum.java: -------------------------------------------------------------------------------- 1 | import java.util.HashMap; 2 | import java.util.Map; 3 | 4 | /** 5 | * Given an array of integers, return indices of the two numbers such that they add up to a specific target. 6 | * You may assume that each input would have exactly one solution, and you may not use the same element twice. 7 | *

8 | * Example: 9 | * Given nums = [2, 7, 11, 15], target = 9, 10 | * Because nums[0] + nums[1] = 2 + 7 = 9, 11 | * return [0, 1]. 12 | *

13 | * Created by drfish on 04/05/2017. 14 | */ 15 | public class _001TwoSum { 16 | public int[] twoSum(int[] nums, int target) { 17 | int[] result = new int[2]; 18 | Map map = new HashMap<>(); 19 | for (int i = 0; i < nums.length; i++) { 20 | if (map.containsKey(target - nums[i])) { 21 | result[0] = map.get(target - nums[i]); 22 | result[1] = i; 23 | return result; 24 | } 25 | map.put(nums[i], i); 26 | } 27 | return result; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /java/_003LongestSubStringWithoutRepeatingCharacters.java: -------------------------------------------------------------------------------- 1 | import java.util.HashMap; 2 | import java.util.Map; 3 | 4 | /** 5 | * Given a string, find the length of the longest substring without repeating characters. 6 | *

7 | * Examples: 8 | * Given "abcabcbb", the answer is "abc", which the length is 3. 9 | * Given "bbbbb", the answer is "b", with the length of 1. 10 | * Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a 11 | * subsequence and not a substring. 12 | * Created by drfish on 13/05/2017. 13 | */ 14 | public class _003LongestSubStringWithoutRepeatingCharacters { 15 | public int lengthOfLongestSubstring(String s) { 16 | if (s == null) 17 | return 0; 18 | if (s.length() <= 1) 19 | return s.length(); 20 | Map map = new HashMap<>(); 21 | int start = -1; 22 | int result = 0; 23 | for (int i = 0; i < s.length(); i++) { 24 | if (map.containsKey(s.charAt(i))) { 25 | start = Math.max(start, map.get(s.charAt(i))); 26 | } 27 | map.put(s.charAt(i), i); 28 | result = Math.max(result, i - start); 29 | } 30 | return result; 31 | } 32 | 33 | public static void main(String[] args) { 34 | _003LongestSubStringWithoutRepeatingCharacters solution = new _003LongestSubStringWithoutRepeatingCharacters(); 35 | assert 3 == solution.lengthOfLongestSubstring("abcabcbb"); 36 | assert 1 == solution.lengthOfLongestSubstring("bbbbb"); 37 | assert 3 == solution.lengthOfLongestSubstring("pwwkew"); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /java/_007ReverseInteger.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Reverse digits of an integer. 3 | *

4 | * Example1: x = 123, return 321 5 | * Example2: x = -123, return -321 6 | *

7 | * Have you thought about this? 8 | * Here are some good questions to ask before coding. Bonus points for you if you have already thought through this! 9 | *

10 | * If the integer's last digit is 0, what should the output be? ie, cases such as 10, 100. 11 | * Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 12 | * 1000000003 overflows. How should you handle such cases? 13 | * For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows. 14 | *

15 | * Note: 16 | * The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer 17 | * overflows. 18 | *

19 | * Created by drfish on 25/06/2017. 20 | */ 21 | public class _007ReverseInteger { 22 | public int reverse(int x) { 23 | int result = 0; 24 | while (x != 0) { 25 | int tail = x % 10; 26 | int temp = result * 10 + tail; 27 | if ((temp - tail) / 10 != result) { 28 | return 0; 29 | } 30 | result = temp; 31 | x /= 10; 32 | } 33 | return result; 34 | } 35 | 36 | public static void main(String[] args) { 37 | _007ReverseInteger solution = new _007ReverseInteger(); 38 | assert 321 == solution.reverse(123); 39 | assert -321 == solution.reverse(-123); 40 | assert 0 == solution.reverse(2147483647); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /java/_009PalindromeNumber.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Determine whether an integer is a palindrome. Do this without extra space. 3 | *

4 | * Some hints: 5 | * Could negative integers be palindromes? (ie, -1) 6 | *

7 | * If you are thinking of converting the integer to string, note the restriction of using extra space. 8 | *

9 | * You could also try reversing an integer. However, if you have solved the problem "Reverse Integer", you know that 10 | * the reversed integer might overflow. How would you handle such case? 11 | *

12 | * There is a more generic way of solving this problem. 13 | *

14 | * Created by drfish on 25/06/2017. 15 | */ 16 | public class _009PalindromeNumber { 17 | public boolean isPalindrome(int x) { 18 | if (x < 0 || (x != 0 && x % 10 == 0)) { 19 | return false; 20 | } 21 | int reverse = 0; 22 | while (x > reverse) { 23 | reverse = reverse * 10 + x % 10; 24 | x /= 10; 25 | } 26 | return (x == reverse || x == reverse / 10); 27 | } 28 | 29 | public static void main(String[] args) { 30 | _009PalindromeNumber solution = new _009PalindromeNumber(); 31 | assert solution.isPalindrome(12321); 32 | assert solution.isPalindrome(123321); 33 | assert !solution.isPalindrome(-121); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /java/_013RomanToInteger.java: -------------------------------------------------------------------------------- 1 | import java.util.HashMap; 2 | import java.util.Map; 3 | 4 | /** 5 | * Created by drfish on 25/06/2017. 6 | */ 7 | public class _013RomanToInteger { 8 | public int romanToInt(String s) { 9 | Map map = new HashMap() {{ 10 | put('M', 1000); 11 | put('D', 500); 12 | put('C', 100); 13 | put('L', 50); 14 | put('X', 10); 15 | put('V', 5); 16 | put('I', 1); 17 | }}; 18 | int result = 0; 19 | for (int i = 0; i < s.length(); i++) { 20 | if (i > 0 && map.get(s.charAt(i)) > map.get(s.charAt(i - 1))) { 21 | result -= map.get(s.charAt(i - 1)); 22 | result += map.get(s.charAt(i)) - map.get(s.charAt(i - 1)); 23 | } else { 24 | result += map.get(s.charAt(i)); 25 | } 26 | } 27 | return result; 28 | } 29 | 30 | public static void main(String[] args) { 31 | _013RomanToInteger solution = new _013RomanToInteger(); 32 | assert 12 == solution.romanToInt("XII"); 33 | assert 21 == solution.romanToInt("XXI"); 34 | assert 99 == solution.romanToInt("XCIX"); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /java/_019RemoveNthNodeFromEndOfList.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Given a linked list, remove the nth node from the end of list and return its head. 3 | * For example, 4 | * Given linked list: 1->2->3->4->5, and n = 2. 5 | * After removing the second node from the end, the linked list becomes 1->2->3->5. 6 | *

7 | * Note: 8 | * Given n will always be valid. 9 | * Try to do this in one pass. 10 | *

11 | * Created by drfish on 16/04/2017. 12 | */ 13 | 14 | public class _019RemoveNthNodeFromEndOfList { 15 | public ListNode removeNthFromEnd(ListNode head, int n) { 16 | ListNode dummy = new ListNode(-1); 17 | dummy.next = head; 18 | ListNode fast = dummy; 19 | ListNode slow = dummy; 20 | for (int i = 0; i < n; i++) 21 | fast = fast.next; 22 | while (fast.next != null) { 23 | fast = fast.next; 24 | slow = slow.next; 25 | } 26 | slow.next = slow.next.next; 27 | return dummy.next; 28 | } 29 | } -------------------------------------------------------------------------------- /java/_020ValidParentheses.java: -------------------------------------------------------------------------------- 1 | import java.util.Stack; 2 | 3 | /** 4 | * Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. 5 | * The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not. 6 | *

7 | * Created by drfish on 6/7/2017. 8 | */ 9 | public class _020ValidParentheses { 10 | public boolean isValid(String s) { 11 | if (s == null) { 12 | return true; 13 | } 14 | Stack stack = new Stack<>(); 15 | for (char c : s.toCharArray()) { 16 | switch (c) { 17 | case '(': 18 | stack.push(')'); 19 | break; 20 | case '{': 21 | stack.push('}'); 22 | break; 23 | case '[': 24 | stack.push(']'); 25 | break; 26 | default: 27 | if (stack.isEmpty() || stack.pop() != c) { 28 | return false; 29 | } 30 | } 31 | } 32 | return stack.isEmpty(); 33 | } 34 | 35 | public static void main(String[] args) { 36 | _020ValidParentheses solution = new _020ValidParentheses(); 37 | assert solution.isValid("()"); 38 | assert solution.isValid("()[]()"); 39 | assert !solution.isValid("(]"); 40 | assert !solution.isValid("([)]"); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /java/_021MergeTwoSortedLists.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 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. 3 | *

4 | * Created by drfish on 16/04/2017. 5 | */ 6 | public class _021MergeTwoSortedLists { 7 | public ListNode mergeTwoLists(ListNode l1, ListNode l2) { 8 | ListNode dummy = new ListNode(-1); 9 | ListNode head = dummy; 10 | while (l1 != null && l2 != null) { 11 | if (l1.val < l2.val) { 12 | dummy.next = l1; 13 | l1 = l1.next; 14 | } else { 15 | dummy.next = l2; 16 | l2 = l2.next; 17 | } 18 | dummy = dummy.next; 19 | } 20 | if (l1 == null) 21 | dummy.next = l2; 22 | if (l2 == null) 23 | dummy.next = l1; 24 | return head.next; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /java/_023MergeKSortedLists.java: -------------------------------------------------------------------------------- 1 | import java.util.PriorityQueue; 2 | 3 | /** 4 | * Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity. 5 | *

6 | * Created by drfish on 16/04/2017. 7 | */ 8 | public class _023MergeKSortedLists { 9 | public ListNode mergeKLists(ListNode[] lists) { 10 | PriorityQueue nodesHeap = new PriorityQueue((n1, n2) -> (n1.val - n2.val)); 11 | for (ListNode node : lists) { 12 | if (node != null) 13 | nodesHeap.add(node); 14 | } 15 | ListNode dummy = new ListNode(-1); 16 | ListNode head = dummy; 17 | while (!nodesHeap.isEmpty()) { 18 | ListNode node = nodesHeap.poll(); 19 | if (node.next != null) 20 | nodesHeap.add(node.next); 21 | dummy.next = node; 22 | dummy = dummy.next; 23 | } 24 | return head.next; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /java/_024SwapNodesInPairs.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Given a linked list, swap every two adjacent nodes and return its head. 3 | *

4 | * For example, 5 | * Given 1->2->3->4, you should return the list as 2->1->4->3. 6 | *

7 | * Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed. 8 | *

9 | * Created by drfish on 16/04/2017. 10 | */ 11 | public class _024SwapNodesInPairs { 12 | public ListNode swapPairs(ListNode head) { 13 | if (head == null || head.next == null) 14 | return head; 15 | ListNode dummy = new ListNode(-1); 16 | dummy.next = head; 17 | for (ListNode prev = dummy, cur = prev.next, next = cur.next; 18 | next != null; 19 | prev = cur, cur = cur.next, next = cur != null ? cur.next : null) { 20 | prev.next = next; 21 | cur.next = next.next; 22 | next.next = cur; 23 | } 24 | return dummy.next; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /java/_094BinaryTreeInorderTraversal.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Given a binary tree, return the inorder traversal of its nodes' values. 3 | *

4 | * For example: 5 | * Given binary tree [1,null,2,3], 6 | * 1 7 | * \ 8 | * 2 9 | * / 10 | * 3 11 | * return [1,3,2]. 12 | *

13 | * Note: Recursive solution is trivial, could you do it iteratively? 14 | * Created by drfish on 27/05/2017. 15 | */ 16 | 17 | import java.util.ArrayList; 18 | import java.util.List; 19 | import java.util.Stack; 20 | 21 | /** 22 | * Definition for a binary tree node. 23 | */ 24 | class TreeNode { 25 | int val; 26 | TreeNode left; 27 | TreeNode right; 28 | 29 | TreeNode(int x) { 30 | val = x; 31 | } 32 | } 33 | 34 | public class _094BinaryTreeInorderTraversal { 35 | public List inorderTraversal(TreeNode root) { 36 | Stack stack = new Stack<>(); 37 | List result = new ArrayList<>(); 38 | while (root != null || !stack.empty()) { 39 | while (root != null) { 40 | stack.push(root); 41 | root = root.left; 42 | } 43 | root = stack.pop(); 44 | result.add(root.val); 45 | root = root.right; 46 | } 47 | return result; 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /java/_096UniqueBinarySearchTrees.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Given n, how many structurally unique BST's (binary search trees) that store values 1...n? 3 | *

4 | * For example, 5 | * Given n = 3, there are a total of 5 unique BST's. 6 | *

7 | * 1 3 3 2 1 8 | * \ / / / \ \ 9 | * 3 2 1 1 3 2 10 | * / / \ \ 11 | * 2 1 2 3 12 | *

13 | * Created by drfish on 27/05/2017. 14 | */ 15 | public class _096UniqueBinarySearchTrees { 16 | public int numTrees(int n) { 17 | int[] counts = new int[n + 1]; 18 | counts[0] = 1; 19 | for (int i = 1; i <= n; i++) { 20 | int count = 0; 21 | for (int j = 0; j < i; j++) { 22 | count += counts[j] * counts[i - 1 - j]; 23 | } 24 | counts[i] = count; 25 | } 26 | return counts[n]; 27 | } 28 | 29 | public static void main(String[] args) { 30 | _096UniqueBinarySearchTrees uniqueBinarySearchTrees = new _096UniqueBinarySearchTrees(); 31 | assert uniqueBinarySearchTrees.numTrees(3) == 5; 32 | assert uniqueBinarySearchTrees.numTrees(6) == 132; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /java/_098ValidateBinarySearchTree.java: -------------------------------------------------------------------------------- 1 | import java.util.Stack; 2 | 3 | /** 4 | * Given a binary tree, determine if it is a valid binary search tree (BST). 5 | *

6 | * Assume a BST is defined as follows: 7 | * The left subtree of a node contains only nodes with keys less than the node's key. 8 | * The right subtree of a node contains only nodes with keys greater than the node's key. 9 | * Both the left and right subtrees must also be binary search trees. 10 | *

11 | * Example 1: 12 | * 2 13 | * / \ 14 | * 1 3 15 | * Binary tree [2,1,3], return true. 16 | * Example 2: 17 | * 1 18 | * / \ 19 | * 2 3 20 | * Binary tree [1,2,3], return false. 21 | *

22 | * Created by drfish on 28/05/2017. 23 | */ 24 | public class _098ValidateBinarySearchTree { 25 | public boolean isValidBST(TreeNode root) { 26 | if (root == null) { 27 | return true; 28 | } 29 | Stack stack = new Stack<>(); 30 | TreeNode prev = null; 31 | while (root != null || !stack.isEmpty()) { 32 | while (root != null) { 33 | stack.push(root); 34 | root = root.left; 35 | } 36 | root = stack.pop(); 37 | if (prev != null && prev.val >= root.val) { 38 | return false; 39 | } 40 | prev = root; 41 | root = root.right; 42 | } 43 | return true; 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /java/_099RecoverBinarySearchTree.java: -------------------------------------------------------------------------------- 1 | import java.util.Stack; 2 | 3 | /** 4 | * Two elements of a binary search tree (BST) are swapped by mistake. 5 | * Recover the tree without changing its structure. 6 | *

7 | * Note: 8 | * A solution using O(n) space is pretty straight forward. Could you devise a constant space solution? 9 | *

10 | * Created by drfish on 28/05/2017. 11 | */ 12 | public class _099RecoverBinarySearchTree { 13 | public void recoverTree(TreeNode root) { 14 | TreeNode first = null; 15 | TreeNode second = null; 16 | TreeNode prev = null; 17 | Stack stack = new Stack<>(); 18 | while (root != null || !stack.isEmpty()) { 19 | while (root != null) { 20 | stack.push(root); 21 | root = root.left; 22 | } 23 | root = stack.pop(); 24 | if (prev != null && prev.val >= root.val) { 25 | if (first == null) { 26 | first = prev; 27 | } 28 | second = root; 29 | } 30 | prev = root; 31 | root = root.right; 32 | } 33 | swap(first, second); 34 | } 35 | 36 | private void swap(TreeNode node1, TreeNode node2) { 37 | int temp = node1.val; 38 | node1.val = node2.val; 39 | node2.val = temp; 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /java/_100SameTree.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Given two binary trees, write a function to check if they are equal or not. 3 | * Two binary trees are considered equal if they are structurally identical and the nodes have the same value. 4 | *

5 | * Created by drfish on 28/05/2017. 6 | */ 7 | public class _100SameTree { 8 | public boolean isSameTree(TreeNode p, TreeNode q) { 9 | if (p == null && q == null) { 10 | return true; 11 | } 12 | if (p != null && q != null) { 13 | if (p.val == q.val) { 14 | return isSameTree(p.left, q.left) && isSameTree(p.right, q.right); 15 | } 16 | } 17 | return false; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /java/_101SymmetricTree.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center). 3 | *

4 | * For example, this binary tree [1,2,2,3,4,4,3] is symmetric: 5 | * 1 6 | * / \ 7 | * 2 2 8 | * / \ / \ 9 | * 3 4 4 3 10 | * But the following [1,2,2,null,3,null,3] is not: 11 | * 1 12 | * / \ 13 | * 2 2 14 | * \ \ 15 | * 3 3 16 | *

17 | * Note: 18 | * Bonus points if you could solve it both recursively and iteratively. 19 | *

20 | * Created by drfish on 28/05/2017. 21 | */ 22 | public class _101SymmetricTree { 23 | public boolean isSymmetric(TreeNode root) { 24 | if (root == null) { 25 | return true; 26 | } 27 | return check(root.left, root.right); 28 | } 29 | 30 | private boolean check(TreeNode p, TreeNode q) { 31 | if (p == null && q == null) { 32 | return true; 33 | } 34 | if (p != null && q != null) { 35 | if (p.val == q.val) { 36 | return check(p.left, q.right) && check(p.right, q.left); 37 | } 38 | } 39 | return false; 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /java/_102BinaryTreeLevelOrderTraversal.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.List; 3 | 4 | /** 5 | * Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level). 6 | *

7 | * For example: 8 | * Given binary tree [3,9,20,null,null,15,7], 9 | * 3 10 | * / \ 11 | * 9 20 12 | * / \ 13 | * 15 7 14 | *

15 | * return its level order traversal as: 16 | * [ 17 | * [3], 18 | * [9,20], 19 | * [15,7] 20 | * ] 21 | *

22 | * Created by drfish on 29/05/2017. 23 | */ 24 | public class _102BinaryTreeLevelOrderTraversal { 25 | public List> levelOrder(TreeNode root) { 26 | List> result = new ArrayList<>(); 27 | List curr = new ArrayList<>(); 28 | 29 | 30 | if (root == null) { 31 | return result; 32 | } 33 | curr.add(root); 34 | 35 | while (!curr.isEmpty()) { 36 | List next = new ArrayList<>(); 37 | List level = new ArrayList<>(); 38 | for (TreeNode node : curr) { 39 | if (node.left != null) { 40 | next.add(node.left); 41 | } 42 | if (node.right != null) { 43 | next.add(node.right); 44 | } 45 | level.add(node.val); 46 | } 47 | result.add(level); 48 | curr = next; 49 | } 50 | return result; 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /java/_144BinaryTreePreorderTraversal.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.List; 3 | import java.util.Stack; 4 | 5 | /** 6 | * Given a binary tree, return the preorder traversal of its nodes' values. 7 | *

8 | * For example: 9 | * Given binary tree {1,#,2,3}, 10 | * 1 11 | * \ 12 | * 2 13 | * / 14 | * 3 15 | * return [1,2,3]. 16 | *

17 | * Note: Recursive solution is trivial, could you do it iteratively? 18 | * Created by drfish on 6/8/2017. 19 | */ 20 | public class _144BinaryTreePreorderTraversal { 21 | public List preorderTraversal(TreeNode root) { 22 | List result = new ArrayList<>(); 23 | Stack stack = new Stack<>(); 24 | while (root != null || !stack.isEmpty()) { 25 | while (root != null) { 26 | result.add(root.val); 27 | stack.push(root); 28 | root = root.left; 29 | } 30 | root = stack.pop(); 31 | root = root.right; 32 | } 33 | return result; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /java/_145BinaryTreePostorderTraversal.java: -------------------------------------------------------------------------------- 1 | import java.util.LinkedList; 2 | import java.util.List; 3 | import java.util.Stack; 4 | 5 | /** 6 | * Given a binary tree, return the postorder traversal of its nodes' values. 7 | *

8 | * For example: 9 | * Given binary tree {1,#,2,3}, 10 | * 1 11 | * \ 12 | * 2 13 | * / 14 | * 3 15 | * return [3,2,1]. 16 | *

17 | * Note: Recursive solution is trivial, could you do it iteratively? 18 | *

19 | * Created by drfish on 6/8/2017. 20 | */ 21 | public class _145BinaryTreePostorderTraversal { 22 | public List postorderTraversal(TreeNode root) { 23 | List result = new LinkedList<>(); 24 | Stack stack = new Stack<>(); 25 | while (root != null || !stack.isEmpty()) { 26 | while (root != null) { 27 | stack.push(root); 28 | result.add(0, root.val); 29 | root = root.right; 30 | } 31 | root = stack.pop().left; 32 | } 33 | return result; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /java/_173BinarySearchTreeIterator.java: -------------------------------------------------------------------------------- 1 | import java.util.Stack; 2 | 3 | /** 4 | * Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST. 5 | * Calling next() will return the next smallest number in the BST. 6 | *

7 | * Note: next() and hasNext() should run in average O(1) time and uses O(h) memory, where h is the height of the tree. 8 | *

9 | * Credits: 10 | * Special thanks to @ts for adding this problem and creating all test cases. 11 | *

12 | * Created by drfish on 6/8/2017. 13 | */ 14 | public class _173BinarySearchTreeIterator { 15 | public class BSTIterator { 16 | private Stack stack; 17 | private TreeNode node; 18 | 19 | public BSTIterator(TreeNode root) { 20 | stack = new Stack<>(); 21 | node = root; 22 | } 23 | 24 | /** 25 | * @return whether we have a next smallest number 26 | */ 27 | public boolean hasNext() { 28 | return node != null || !stack.isEmpty(); 29 | } 30 | 31 | /** 32 | * @return the next smallest number 33 | */ 34 | public int next() { 35 | while (node != null) { 36 | stack.push(node); 37 | node = node.left; 38 | } 39 | TreeNode temp = stack.pop(); 40 | node = temp.right; 41 | return temp.val; 42 | } 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /java/_215KthLargestElementInAnArray.java: -------------------------------------------------------------------------------- 1 | import java.util.PriorityQueue; 2 | 3 | /** 4 | * Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, 5 | * not the kth distinct element. 6 | *

7 | * For example, 8 | * Given [3,2,1,5,6,4] and k = 2, return 5. 9 | *

10 | * Note: 11 | * You may assume k is always valid, 1 ≤ k ≤ array's length. 12 | *

13 | * Credits: 14 | * Special thanks to @mithmatt for adding this problem and creating all test cases. 15 | *

16 | * Created by drfish on 10/06/2017. 17 | */ 18 | public class _215KthLargestElementInAnArray { 19 | /** 20 | * heap solution 21 | */ 22 | public int findKthLargest(int[] nums, int k) { 23 | PriorityQueue heap = new PriorityQueue<>(); 24 | for (int num : nums) { 25 | heap.offer(num); 26 | if (heap.size() > k) { 27 | heap.poll(); 28 | } 29 | } 30 | return heap.peek(); 31 | } 32 | 33 | public static void main(String[] args) { 34 | _215KthLargestElementInAnArray solution = new _215KthLargestElementInAnArray(); 35 | assert 5 == solution.findKthLargest(new int[]{3, 2, 1, 5, 6, 4}, 2); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /java/_257BinaryTreePaths.java: -------------------------------------------------------------------------------- 1 | import java.util.List; 2 | 3 | import javax.management.relation.RelationTypeSupport; 4 | import javax.swing.tree.TreeNode; 5 | 6 | /** 7 | * Given a binary tree, return all root-to-leaf paths. 8 | * 9 | * For example, given the following binary tree: 10 | * 11 | * 1 12 | * / \ 13 | * 2 3 14 | * \ 15 | * 5 16 | * All root-to-leaf paths are: 17 | * 18 | * ["1->2->5", "1->3"] 19 | */ 20 | 21 | public class _257BinaryTreePaths { 22 | public List binaryTreePaths(TreeNode root) { 23 | List result = new ArrayList<>(); 24 | if (root != null) { 25 | search(root, "", result); 26 | } 27 | return result; 28 | } 29 | 30 | public void search(TreeNode node, String path, List result) { 31 | if (node.left == null && node.right == null) { 32 | result.add(path + node.val); 33 | } 34 | if (node.left != null) { 35 | search(node.left, path + node.val + "->", result); 36 | } 37 | if (node.right != null) { 38 | search(node.right, path + node.val + "->", result); 39 | } 40 | } 41 | } -------------------------------------------------------------------------------- /java/_258AddDigits.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Given a non-negative integer num, repeatedly add all its digits until the result has only one digit. 3 | * 4 | * For example: 5 | * 6 | * Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it. 7 | * 8 | * Follow up: 9 | * Could you do it without any loop/recursion in O(1) runtime? 10 | */ 11 | public class _258AddDigits { 12 | public int addDigits(int num) { 13 | int result = num % 9; 14 | return (result != 0 || num == 0) ? result : 9; 15 | } 16 | } -------------------------------------------------------------------------------- /java/_260SingleNumberIII.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 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. 3 | * 4 | * For example: 5 | * 6 | * Given nums = [1, 2, 1, 3, 2, 5], return [3, 5]. 7 | * 8 | * Note: 9 | * The order of the result is not important. So in the above example, [5, 3] is also correct. 10 | * Your algorithm should run in linear runtime complexity. Could you implement it using only constant space complexity? 11 | */ 12 | public class _260SingleNumberIII { 13 | public int[] singleNumber(int[] nums) { 14 | int diff = 0; 15 | for (int num : nums) { 16 | diff ^= num; 17 | } 18 | diff &= -diff; 19 | int[] result = { 0, 0 }; 20 | for (int num : nums) { 21 | if ((num & diff) == 0) { 22 | result[0] ^= num; 23 | } else { 24 | result[1] ^= num; 25 | } 26 | } 27 | return result; 28 | } 29 | } -------------------------------------------------------------------------------- /java/_264UglyNumberII.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Write a program to find the n-th ugly number. 3 | * Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. For example, 1, 2, 3, 4, 5, 6, 8, 9, 4 | * 10, 12 is the sequence of the first 10 ugly numbers. 5 | *

6 | * Note that 1 is typically treated as an ugly number, and n does not exceed 1690. 7 | *

8 | * Credits: 9 | * Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases. 10 | *

11 | * Created by drfish on 12/06/2017. 12 | */ 13 | public class _264UglyNumberII { 14 | public int nthUglyNumber(int n) { 15 | int index2 = 0, index3 = 0, index5 = 0; 16 | int[] dp = new int[n]; 17 | dp[0] = 1; 18 | for (int i = 1; i < n; i++) { 19 | dp[i] = Math.min(dp[index2] * 2, Math.min(dp[index3] * 3, dp[index5] * 5)); 20 | if (dp[i] == dp[index2] * 2) { 21 | index2++; 22 | } 23 | if (dp[i] == dp[index3] * 3) { 24 | index3++; 25 | } 26 | if (dp[i] == dp[index5] * 5) { 27 | index5++; 28 | } 29 | } 30 | return dp[n - 1]; 31 | } 32 | 33 | public static void main(String[] args) { 34 | _264UglyNumberII solution = new _264UglyNumberII(); 35 | assert 1 == solution.nthUglyNumber(1); 36 | assert 12 == solution.nthUglyNumber(10); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /java/_274H_Index.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Given an array of citations (each citation is a non-negative integer) of a researcher, write a function to compute the researcher's h-index. 3 | * 4 | * According to the definition of h-index on Wikipedia: "A scientist has index h if h of his/her N papers have at least h citations each, and the other N − h papers have no more than h citations each." 5 | * 6 | * For example, given citations = [3, 0, 6, 1, 5], which means the researcher has 5 papers in total and each of them had received 3, 0, 6, 1, 5 citations respectively. Since the researcher has 3 papers with at least 3 citations each and the remaining two with no more than 3 citations each, his h-index is 3. 7 | * 8 | * Note: If there are several possible values for h, the maximum one is taken as the h-index. 9 | */ 10 | public class _274H_Index { 11 | public int hIndex(int[] citations) { 12 | if (citations == null || citations.length == 0) { 13 | return 0; 14 | } 15 | int n = citations.length; 16 | int[] cnts = new int[n + 1]; 17 | for (int citation : citations) { 18 | if (citation >= n) { 19 | cnts[n]++; 20 | } else { 21 | cnts[citation]++; 22 | } 23 | } 24 | int count = 0; 25 | for (int i = n; i >= 0; i--) { 26 | count += cnts[i]; 27 | if (count >= i) { 28 | return i; 29 | } 30 | } 31 | return 0; 32 | } 33 | } -------------------------------------------------------------------------------- /java/_283MoveZeroes.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 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. 3 | * 4 | * For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0]. 5 | * 6 | * Note: 7 | * You must do this in-place without making a copy of the array. 8 | * Minimize the total number of operations. 9 | */ 10 | 11 | public class _283MoveZeroes { 12 | public void moveZeroes(int[] nums) { 13 | if (nums == null || nums.length == 0) { 14 | return; 15 | } 16 | int index = 0; 17 | for (int i = 0; i < nums.length; i++) { 18 | if (nums[i] != 0) { 19 | nums[index++] = nums[i]; 20 | } 21 | } 22 | for (int i = index; i < nums.length; i++) { 23 | nums[i] = 0; 24 | } 25 | } 26 | } -------------------------------------------------------------------------------- /java/_292NimGame.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 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. 3 | * 4 | * 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. 5 | * 6 | * 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. 7 | */ 8 | public class _292NimGame { 9 | public boolean canWinNim(int n) { 10 | return n % 4 != 0; 11 | } 12 | } -------------------------------------------------------------------------------- /java/_347TopKFrequentElements.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | /** 4 | * Given a non-empty array of integers, return the k most frequent elements. 5 | *

6 | * For example, 7 | * Given [1,1,1,2,2,3] and k = 2, return [1,2]. 8 | *

9 | * Note: 10 | * You may assume k is always valid, 1 ≤ k ≤ number of unique elements. 11 | * Your algorithm's time complexity must be better than O(n log n), where n is the array's size. 12 | *

13 | * Created by drfish on 15/06/2017. 14 | */ 15 | public class _347TopKFrequentElements { 16 | public List topKFrequent(int[] nums, int k) { 17 | List result = new ArrayList<>(); 18 | Map map = new HashMap<>(); 19 | PriorityQueue> maxHeap = new PriorityQueue<>((n1, n2) -> n2.getValue() - 20 | n1.getValue()); 21 | for (int num : nums) { 22 | map.put(num, map.getOrDefault(num, 0) + 1); 23 | } 24 | for (Map.Entry entry : map.entrySet()) { 25 | maxHeap.offer(entry); 26 | } 27 | while (k > 0) { 28 | k--; 29 | result.add(maxHeap.poll().getKey()); 30 | } 31 | return result; 32 | } 33 | 34 | public static void main(String[] args) { 35 | _347TopKFrequentElements solution = new _347TopKFrequentElements(); 36 | assert Arrays.asList(1, 2).equals(solution.topKFrequent(new int[]{1, 1, 1, 2, 2, 3}, 2)); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /java/_387FirstUniqueCharacterinaString.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | * Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1. 4 | * 5 | * Examples: 6 | * 7 | * s = "leetcode" 8 | * return 0. 9 | * 10 | * s = "loveleetcode", 11 | * return 2. 12 | * Note: You may assume the string contain only lowercase letters. 13 | */ 14 | public class _387FirstUniqueCharacterinaString { 15 | public int firstUniqChar(String s) { 16 | int[] frequency = new int[26]; 17 | for (int i = 0; i < s.length(); i++) { 18 | frequency[s.charAt(i) - 'a']++; 19 | } 20 | for (int i = 0; i < s.length(); i++) { 21 | if (frequency[s.charAt(i) - 'a'] == 1) { 22 | return i; 23 | } 24 | } 25 | return -1; 26 | } 27 | } -------------------------------------------------------------------------------- /python/001 Two Sum.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an array of integers, find two numbers such that they add up to a specific target number. 3 | 4 | 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. 5 | 6 | You may assume that each input would have exactly one solution. 7 | 8 | Input: numbers={2, 7, 11, 15}, target=9 9 | Output: index1=1, index2=2 10 | ''' 11 | 12 | class Solution(object): 13 | def twoSum(self, nums, target): 14 | """ 15 | :type nums: List[int] 16 | :type target: int 17 | :rtype: List[int] 18 | """ 19 | hash_map = {} 20 | for index, value in enumerate(nums): 21 | hash_map[value] = index 22 | for index1, value in enumerate(nums): 23 | if target - value in hash_map: 24 | index2 = hash_map[target - value] 25 | if index1 != index2: 26 | return [index1 + 1, index2 + 1] 27 | 28 | 29 | if __name__ == "__main__": 30 | print(Solution().twoSum([2, 7, 11, 15], 9)); 31 | -------------------------------------------------------------------------------- /python/003 Longest Substring Without Repeating Characters.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1. 3 | ''' 4 | 5 | class Solution(object): 6 | def lengthOfLongestSubstring(self, s): 7 | """ 8 | :type s: str 9 | :rtype: int 10 | """ 11 | if not s: 12 | return 0 13 | if len(s) <= 1: 14 | return len(s) 15 | locations = [-1 for i in range(256)] 16 | index = -1 17 | m = 0 18 | for i, v in enumerate(s): 19 | if (locations[ord(v)] > index): 20 | index = locations[ord(v)] 21 | m = max(m, i - index) 22 | locations[ord(v)] = i 23 | return m 24 | 25 | if __name__ == "__main__": 26 | assert Solution().lengthOfLongestSubstring("abcea") == 4 -------------------------------------------------------------------------------- /python/007 Reverse Integer.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Reverse digits of an integer. 3 | 4 | Example1: x = 123, return 321 5 | Example2: x = -123, return -321 6 | 7 | Here are some good questions to ask before coding. Bonus points for you if you have already thought through this! 8 | 9 | If the integer's last digit is 0, what should the output be? ie, cases such as 10, 100. 10 | 11 | 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? 12 | 13 | For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows. 14 | ''' 15 | 16 | class Solution(object): 17 | def reverse(self, x): 18 | """ 19 | :type x: int 20 | :rtype: int 21 | """ 22 | # Consider positive and negative situation 23 | flag = 0 24 | if x < 0: 25 | flag = -1 26 | else: 27 | flag = 1 28 | x *= flag 29 | result = 0 30 | while x: 31 | result = result * 10 + x % 10 32 | x /= 10 33 | if result > 2147483647: 34 | return 0 35 | else: 36 | return result * flag 37 | 38 | 39 | if __name__ == "__main__": 40 | assert Solution().reverse(321000) == 123 41 | assert Solution().reverse(-321) == -123 42 | assert Solution().reverse(1534236469) == 0 43 | -------------------------------------------------------------------------------- /python/009 Palindrome Number.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Determine whether an integer is a palindrome. Do this without extra space. 3 | 4 | Could negative integers be palindromes? (ie, -1) 5 | 6 | If you are thinking of converting the integer to string, note the restriction of using extra space. 7 | 8 | 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? 9 | 10 | There is a more generic way of solving this problem. 11 | ''' 12 | 13 | class Solution(object): 14 | def isPalindrome(self, x): 15 | """ 16 | :type x: int 17 | :rtype: bool 18 | """ 19 | if x < 0: 20 | return False 21 | div = 1 22 | while x / div >= 10: 23 | div *= 10 24 | while x > 0: 25 | l = x // div 26 | r = x % 10 27 | 28 | if l != r: 29 | return False 30 | x %= div 31 | x //= 10 32 | div /= 100 33 | return True 34 | 35 | 36 | if __name__ == "__main__": 37 | assert Solution().isPalindrome(123) == False 38 | assert Solution().isPalindrome(12321) == True 39 | assert Solution().isPalindrome(-121) == False 40 | -------------------------------------------------------------------------------- /python/011 Container With Most Water.py: -------------------------------------------------------------------------------- 1 | ''' 2 | 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. 3 | 4 | Note: You may not slant the container. 5 | ''' 6 | 7 | class Solution(object): 8 | def maxArea(self, height): 9 | """ 10 | :type height: List[int] 11 | :rtype: int 12 | """ 13 | if not height: 14 | return 0 15 | left = 0 16 | right = len(height) - 1 17 | result = 0 18 | while left < right: 19 | if height[left] < height[right]: 20 | area = height[left] * (right - left) 21 | result = max(result, area) 22 | left += 1 23 | else: 24 | area = height[right] * (right - left) 25 | result = max(result, area) 26 | right -= 1 27 | return result 28 | 29 | if __name__ == "__main__": 30 | assert Solution().maxArea([1, 1]) == 1 -------------------------------------------------------------------------------- /python/012 Integer to Roman.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an integer, convert it to a roman numeral. 3 | 4 | Input is guaranteed to be within the range from 1 to 3999. 5 | ''' 6 | 7 | class Solution(object): 8 | def intToRoman(self, num): 9 | """ 10 | :type num: int 11 | :rtype: str 12 | """ 13 | nums = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1] 14 | strings = ["M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"] 15 | result = '' 16 | for i in range(len(nums)): 17 | while num >= nums[i]: 18 | num -= nums[i] 19 | result += strings[i] 20 | return result 21 | 22 | # Test cases 23 | if __name__ == "__main__": 24 | assert Solution().intToRoman(12) == "XII" 25 | assert Solution().intToRoman(21) == "XXI" 26 | assert Solution().intToRoman(99) == "XCIX" -------------------------------------------------------------------------------- /python/013 Roman to Integer.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a roman numeral, convert it to an integer. 3 | 4 | Input is guaranteed to be within the range from 1 to 3999. 5 | ''' 6 | 7 | class Solution(object): 8 | def romanToInt(self, s): 9 | """ 10 | :type s: str 11 | :rtype: int 12 | """ 13 | map = {"M": 1000, "D": 500, "C": 100, "L": 50, "X": 10, "V": 5, "I": 1} 14 | result = 0 15 | for i in range(len(s)): 16 | if i > 0 and map[s[i]] > map[s[i - 1]]: 17 | result -= map[s[i - 1]] 18 | result += map[s[i]] - map[s[i - 1]] 19 | else: 20 | result += map[s[i]] 21 | return result 22 | 23 | # Test cases 24 | if __name__ == "__main__": 25 | assert Solution().romanToInt("XII") == 12 26 | assert Solution().romanToInt("XXI") == 21 27 | assert Solution().romanToInt("XCIX") == 99 -------------------------------------------------------------------------------- /python/014 Longest Common Prefix.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Write a function to find the longest common prefix string amongst an array of strings. 3 | ''' 4 | 5 | class Solution(object): 6 | def longestCommonPrefix(self, strs): 7 | """ 8 | :type strs: List[str] 9 | :rtype: str 10 | """ 11 | if not strs: 12 | return "" 13 | longest = strs[0] 14 | for i in range(len(strs[0])): 15 | for str in strs: 16 | if len(str) <= i or strs[0][i] != str[i]: 17 | return strs[0][:i] 18 | return strs[0] 19 | 20 | 21 | if __name__ == "__main__": 22 | assert Solution().longestCommonPrefix(["hello", "heabc", "hell"]) == "he" -------------------------------------------------------------------------------- /python/016 3Sum Closest.py: -------------------------------------------------------------------------------- 1 | ''' 2 | 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. 3 | 4 | For example, given array S = {-1 2 1 -4}, and target = 1. 5 | 6 | The sum that is closest to the target is 2. (-1 + 2 + 1 = 2). 7 | ''' 8 | 9 | class Solution(object): 10 | def threeSumClosest(self, nums, target): 11 | """ 12 | :type nums: List[int] 13 | :type target: int 14 | :rtype: int 15 | """ 16 | nums.sort() 17 | i = 0 18 | result = 0 19 | # Init the distance between result and target with a very large number 20 | distance = pow(2, 32) - 1 21 | for i in range(len(nums)): 22 | j = i + 1 23 | k = len(nums) - 1 24 | while j < k: 25 | l = [nums[i], nums[j], nums[k]] 26 | if sum(l) == target: 27 | return target 28 | if abs(sum(l) - target) < distance: 29 | result = sum(l) 30 | distance = abs(sum(l) - target) 31 | elif sum(l) > target: 32 | k -= 1 33 | else: 34 | j += 1 35 | return result 36 | 37 | 38 | if __name__ == "__main__": 39 | assert Solution().threeSumClosest([1, 1, 1, 1], -100) == 3 -------------------------------------------------------------------------------- /python/017 Letter Combinations of a Phone Number.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a digit string, return all possible letter combinations that the number could represent. 3 | 4 | A mapping of digit to letters (just like on the telephone buttons) is given below. 5 | 6 | Input:Digit string "23" 7 | Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]. 8 | Note: 9 | Although the above answer is in lexicographical order, your answer could be in any order you want. 10 | ''' 11 | 12 | class Solution(object): 13 | digit2letters = { 14 | '2': "abc", 15 | '3': "def", 16 | '4': "ghi", 17 | '5': "jkl", 18 | '6': "mno", 19 | '7': "pqrs", 20 | '8': "tuv", 21 | '9': "wxyz", 22 | } 23 | 24 | def letterCombinations(self, digits): 25 | """ 26 | :type digits: str 27 | :rtype: List[str] 28 | """ 29 | if not digits: 30 | return [] 31 | result = [] 32 | self.dfs(digits, "", result) 33 | return result 34 | 35 | def dfs(self, digits, current, result): 36 | if not digits: 37 | result.append(current) 38 | return 39 | for c in self.digit2letters[digits[0]]: 40 | self.dfs(digits[1:], current + c, result) 41 | 42 | 43 | if __name__ == "__main__": 44 | assert Solution().letterCombinations("23") == ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"] 45 | -------------------------------------------------------------------------------- /python/019 Remove Nth Node From End of List.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a linked list, remove the nth node from the end of list and return its head. 3 | 4 | For example, 5 | 6 | Given linked list: 1->2->3->4->5, and n = 2. 7 | 8 | After removing the second node from the end, the linked list becomes 1->2->3->5. 9 | Note: 10 | Given n will always be valid. 11 | Try to do this in one pass. 12 | ''' 13 | 14 | # Definition for singly-linked list. 15 | class ListNode(object): 16 | def __init__(self, x): 17 | self.val = x 18 | self.next = None 19 | 20 | # Define this to check if it works well 21 | def myPrint(self): 22 | print(self.val) 23 | if self.next: 24 | self.next.myPrint() 25 | 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 | if not head: 35 | return head 36 | dummy = ListNode(-1) 37 | dummy.next=head 38 | prev = dummy 39 | cur = dummy 40 | while prev and n >= 0: 41 | prev = prev.next 42 | n -= 1 43 | while prev: 44 | prev = prev.next 45 | cur = cur.next 46 | cur.next = cur.next.next 47 | return dummy.next 48 | 49 | 50 | if __name__ == "__main__": 51 | n5 = ListNode(5) 52 | n4 = ListNode(4) 53 | n3 = ListNode(3) 54 | n2 = ListNode(2) 55 | n1 = ListNode(1) 56 | n1.next = n2 57 | n2.next = n3 58 | n3.next = n4 59 | n4.next = n5 60 | result = Solution().removeNthFromEnd(n1, 5) 61 | result.myPrint() -------------------------------------------------------------------------------- /python/020 Valid Parentheses.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. 3 | 4 | The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not. 5 | ''' 6 | 7 | class Solution(object): 8 | def isValid(self, s): 9 | """ 10 | :type s: str 11 | :rtype: bool 12 | """ 13 | # Valid str must be even 14 | if len(s) % 2 == 1: 15 | return False 16 | stack = [] 17 | left = ("(", "[", "{") 18 | right = (")", "]", "}") 19 | zip(left,right) 20 | for v in s: 21 | if v in left: 22 | stack.append(v) 23 | else: 24 | if not stack: 25 | return False 26 | p = stack.pop() 27 | if left.index(p) != right.index(v): 28 | return False 29 | return len(stack) == 0 30 | 31 | 32 | if __name__ == "__main__": 33 | assert Solution().isValid("({}){}") == True 34 | assert Solution().isValid("({)}") == False 35 | assert Solution().isValid("}}}") == False 36 | assert Solution().isValid("(((") == False -------------------------------------------------------------------------------- /python/021 Merge Two Sorted Lists.py: -------------------------------------------------------------------------------- 1 | ''' 2 | 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. 3 | ''' 4 | 5 | # Definition for singly-linked list. 6 | class ListNode(object): 7 | def __init__(self, x): 8 | self.val = x 9 | self.next = None 10 | 11 | 12 | class Solution(object): 13 | def mergeTwoLists(self, l1, l2): 14 | """ 15 | :type l1: ListNode 16 | :type l2: ListNode 17 | :rtype: ListNode 18 | """ 19 | temp = ListNode(-1) 20 | head = temp 21 | while l1 and l2: 22 | if l1.val > l2.val: 23 | temp.next = l2 24 | l2 = l2.next 25 | else: 26 | temp.next = l1 27 | l1 = l1.next 28 | temp = temp.next 29 | if l1: 30 | temp.next = l1 31 | else: 32 | temp.next = l2 33 | return head.next 34 | 35 | 36 | if __name__ == "__main__": 37 | assert Solution().mergeTwoLists(ListNode(1), ListNode(2)).val == 1 -------------------------------------------------------------------------------- /python/022 Generate Parentheses.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. 3 | ''' 4 | 5 | class Solution(object): 6 | def generateParenthesis(self, n): 7 | """ 8 | :type n: int 9 | :rtype: List[str] 10 | """ 11 | result = [] 12 | self.generate(n, n, "", result) 13 | return result 14 | 15 | def generate(self, left, right, str, result): 16 | if left == 0 and right == 0: 17 | result.append(str) 18 | return 19 | if left > 0: 20 | self.generate(left - 1, right, str + "(", result) 21 | if right > left: 22 | self.generate(left, right - 1, str + ")", result) 23 | 24 | 25 | if __name__ == "__main__": 26 | assert (Solution().generateParenthesis(3)) == ['((()))', '(()())', '(())()', '()(())', '()()()'] 27 | -------------------------------------------------------------------------------- /python/023 Merge k Sorted Lists.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity. 3 | ''' 4 | 5 | import heapq 6 | 7 | 8 | # Definition for singly-linked list. 9 | class ListNode(object): 10 | def __init__(self, x): 11 | self.val = x 12 | self.next = None 13 | 14 | 15 | class Solution(object): 16 | def mergeKLists(self, lists): 17 | """ 18 | :type lists: List[ListNode] 19 | :rtype: ListNode 20 | """ 21 | heap = [] 22 | for node in lists: 23 | if node: 24 | heapq.heappush(heap, (node.val, node)) 25 | 26 | temp = ListNode(-1) 27 | head = temp 28 | while heap: 29 | smallestNode = heapq.heappop(heap)[1] 30 | temp.next = smallestNode 31 | temp = temp.next 32 | if smallestNode.next: 33 | heapq.heappush(heap, (smallestNode.next.val, smallestNode.next)) 34 | return head.next -------------------------------------------------------------------------------- /python/024 Swap Nodes in Pairs.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a linked list, swap every two adjacent nodes and return its head. 3 | 4 | For example, 5 | Given 1->2->3->4, you should return the list as 2->1->4->3. 6 | 7 | Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed. 8 | 9 | Subscribe to see which companies asked this question 10 | ''' 11 | 12 | # Definition for singly-linked list. 13 | class ListNode(object): 14 | def __init__(self, x): 15 | self.val = x 16 | self.next = None 17 | 18 | 19 | class Solution(object): 20 | def swapPairs(self, head): 21 | """ 22 | :type head: ListNode 23 | :rtype: ListNode 24 | """ 25 | prev = ListNode(-1) 26 | prev.next = head 27 | temp = prev 28 | while temp.next and temp.next.next: 29 | node1 = temp.next 30 | node2 = temp.next.next 31 | temp.next = node2 32 | node1.next = node2.next 33 | node2.next = node1 34 | temp = temp.next.next 35 | return prev.next 36 | -------------------------------------------------------------------------------- /python/026 Remove Duplicates from Sorted Array.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length. 3 | 4 | Do not allocate extra space for another array, you must do this in place with constant memory. 5 | 6 | For example, 7 | Given input array nums = [1,1,2], 8 | 9 | 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. 10 | ''' 11 | 12 | class Solution(object): 13 | def removeDuplicates(self, nums): 14 | """ 15 | :type nums: List[int] 16 | :rtype: int 17 | """ 18 | if not nums: 19 | return 0 20 | # The index where the character needs to be placed 21 | index = 1 22 | # The index of repeating characters 23 | start = 0 24 | for i in range(1, len(nums)): 25 | if nums[start] != nums[i]: 26 | nums[index] = nums[i] 27 | index += 1 28 | start = i 29 | return index 30 | 31 | 32 | if __name__ == "__main__": 33 | assert Solution().removeDuplicates([1, 1, 2]) == 2 -------------------------------------------------------------------------------- /python/027 Remove Element.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an array and a value, remove all instances of that value in place and return the new length. 3 | 4 | The order of elements can be changed. It doesn't matter what you leave beyond the new length. 5 | ''' 6 | 7 | class Solution(object): 8 | def removeElement(self, nums, val): 9 | """ 10 | :type nums: List[int] 11 | :type val: int 12 | :rtype: int 13 | """ 14 | left = 0 15 | right = len(nums) - 1 16 | while left <= right: 17 | while left <= right and nums[left] != val: 18 | left += 1 19 | while left <= right and nums[right] == val: 20 | right -= 1 21 | if left < right: 22 | nums[left] = nums[right] 23 | left += 1 24 | right -= 1 25 | return right + 1 26 | 27 | 28 | if __name__ == "__main__": 29 | assert Solution().removeElement([1, 2, 3, 4, 3, 2, 1], 1) == 5 30 | assert Solution().removeElement([2], 3) == 1 31 | -------------------------------------------------------------------------------- /python/028 Implement strStr().py: -------------------------------------------------------------------------------- 1 | ''' 2 | Implement strStr(). 3 | 4 | Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. 5 | 6 | Subscribe to see which companies asked this question 7 | ''' 8 | 9 | class Solution(object): 10 | def strStr(self, haystack, needle): 11 | """ 12 | :type haystack: str 13 | :type needle: str 14 | :rtype: int 15 | """ 16 | if not needle: 17 | return 0 18 | if not haystack: 19 | return -1 20 | i = 0 21 | needleLength = len(needle) 22 | while i < len(haystack): 23 | a = haystack[i:i + needleLength] 24 | if haystack[i:i + needleLength] == needle: 25 | return i 26 | else: 27 | index = 0 28 | try: 29 | index = needle.rindex(haystack[i + needleLength]) 30 | except Exception: 31 | i += needleLength + 1 32 | i += needleLength-index 33 | return -1 34 | 35 | 36 | if __name__ == "__main__": 37 | assert Solution().strStr("abcdefg", "ab") == 0 38 | assert Solution().strStr("abcdefg", "bc") == 1 39 | assert Solution().strStr("abcdefg", "cd") == 2 40 | assert Solution().strStr("abcdefg", "fg") == 5 41 | assert Solution().strStr("abcdefg", "bcf") == -1 42 | -------------------------------------------------------------------------------- /python/029 Divide Two Integers.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Divide two integers without using multiplication, division and mod operator. 3 | 4 | If it is overflow, return MAX_INT. 5 | ''' 6 | 7 | class Solution(object): 8 | def divide(self, dividend, divisor): 9 | """ 10 | :type dividend: int 11 | :type divisor: int 12 | :rtype: int 13 | """ 14 | MAX_INT = 2147483647 15 | sign = 1 16 | if dividend >= 0 and divisor < 0 or dividend <= 0 and divisor > 0: 17 | sign = -1 18 | dividend = abs(dividend) 19 | divisor = abs(divisor) 20 | 21 | result = 0 22 | current = divisor 23 | currentResult = 1 24 | while current <= dividend: 25 | current <<= 1 26 | currentResult <<= 1 27 | while divisor <= dividend: 28 | current >>= 1 29 | currentResult >>= 1 30 | if current <= dividend: 31 | dividend -= current 32 | result += currentResult 33 | return min(sign * result, MAX_INT) 34 | 35 | 36 | if __name__ == "__main__": 37 | assert Solution().divide(5, -1) == -5 38 | assert Solution().divide(10, 2) == 5 -------------------------------------------------------------------------------- /python/031 Next Permutation.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers. 3 | 4 | If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order). 5 | 6 | The replacement must be in-place, do not allocate extra memory. 7 | 8 | Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column. 9 | 1,2,3 → 1,3,2 10 | 3,2,1 → 1,2,3 11 | 1,1,5 → 1,5,1 12 | ''' 13 | 14 | class Solution(object): 15 | def nextPermutation(self, nums): 16 | """ 17 | :type nums: List[int] 18 | :rtype: void Do not return anything, modify nums in-place instead. 19 | """ 20 | length = len(nums) 21 | 22 | targetIndex = 0 23 | changeIndex = 0 24 | for i in range(length - 1, 0, -1): 25 | if nums[i] > nums[i - 1]: 26 | targetIndex = i - 1 27 | break 28 | for i in range(length - 1, -1, -1): 29 | if nums[i] > nums[targetIndex]: 30 | changeIndex = i 31 | break 32 | nums[targetIndex], nums[changeIndex] = nums[changeIndex], nums[targetIndex] 33 | if targetIndex == changeIndex == 0: 34 | nums.reverse() 35 | else: 36 | nums[targetIndex + 1:] = reversed(nums[targetIndex + 1:]) -------------------------------------------------------------------------------- /python/032 Longest Valid Parentheses.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring. 3 | 4 | For "(()", the longest valid parentheses substring is "()", which has length = 2. 5 | 6 | Another example is ")()())", where the longest valid parentheses substring is "()()", which has length = 4. 7 | ''' 8 | 9 | class Solution(object): 10 | def longestValidParentheses(self, s): 11 | """ 12 | :type s: str 13 | :rtype: int 14 | """ 15 | if not s: 16 | return 0 17 | length = len(s) 18 | dp = [0 for __ in range(length)] 19 | for i in range(1, length): 20 | if s[i] == ")": 21 | j = i - 1 - dp[i - 1] 22 | if j >= 0 and s[j] == "(": 23 | dp[i] = dp[i - 1] + 2 24 | if j - 1 >= 0: 25 | dp[i] += dp[j - 1] 26 | return max(dp) 27 | 28 | 29 | if __name__ == "__main__": 30 | assert Solution().longestValidParentheses("(()))())(") == 4 31 | assert Solution().longestValidParentheses("(()") == 2 32 | assert Solution().longestValidParentheses(")()())") == 4 33 | -------------------------------------------------------------------------------- /python/033 Search in Rotated Sorted Array.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Suppose a sorted array is rotated at some pivot unknown to you beforehand. 3 | 4 | (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2). 5 | 6 | You are given a target value to search. If found in the array return its index, otherwise return -1. 7 | 8 | You may assume no duplicate exists in the array. 9 | ''' 10 | 11 | class Solution(object): 12 | def search(self, nums, target): 13 | """ 14 | :type nums: List[int] 15 | :type target: int 16 | :rtype: int 17 | """ 18 | left = 0 19 | right = len(nums) - 1 20 | while left <= right: 21 | mid = left + (right - left) // 2 22 | if nums[mid] == target: 23 | return mid 24 | 25 | if nums[mid] > nums[left]: 26 | if nums[left] <= target <= nums[mid]: 27 | right = mid - 1 28 | else: 29 | left = mid + 1 30 | elif nums[mid] < nums[left]: 31 | if nums[mid] <= target <= nums[right]: 32 | left = mid + 1 33 | else: 34 | right = mid - 1 35 | else: 36 | left += 1 37 | return -1 38 | 39 | 40 | if __name__ == "__main__": 41 | assert Solution().search([4, 5, 6, 7, 0, 1, 2], 4) == 0 42 | assert Solution().search([4, 5, 6, 7, 0, 1, 2], 7) == 3 43 | assert Solution().search([4, 5, 6, 7, 0, 1, 2], 0) == 4 44 | assert Solution().search([4, 5, 6, 7, 0, 1, 2], 2) == 6 45 | assert Solution().search([3, 1], 3) == 0 46 | assert Solution().search([3, 1], 1) == 1 47 | -------------------------------------------------------------------------------- /python/035 Search Insert Position.py: -------------------------------------------------------------------------------- 1 | ''' 2 | 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. 3 | 4 | You may assume no duplicates in the array. 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 | class Solution(object): 14 | def searchInsert(self, nums, target): 15 | """ 16 | :type nums: List[int] 17 | :type target: int 18 | :rtype: int 19 | """ 20 | length = len(nums) 21 | start = 0 22 | end = length 23 | while start < end: 24 | mid = (start + end) // 2 25 | if nums[mid] == target or (nums[mid] > target and (mid == 0 or nums[mid - 1] < target)): 26 | return mid 27 | if mid == length - 1 and nums[mid] < target: 28 | return mid + 1 29 | if nums[mid] < target: 30 | start = mid + 1 31 | else: 32 | end = mid 33 | 34 | 35 | if __name__ == "__main__": 36 | assert Solution().searchInsert([1, 3, 5, 6], 5) == 2 37 | assert Solution().searchInsert([1, 3, 5, 6], 2) == 1 38 | assert Solution().searchInsert([1, 3, 5, 6], 7) == 4 39 | assert Solution().searchInsert([1, 3, 5, 6], 0) == 0 -------------------------------------------------------------------------------- /python/036 Valid Sudoku.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules. 3 | 4 | The Sudoku board could be partially filled, where empty cells are filled with the character '.'. 5 | 6 | 7 | A partially filled sudoku which is valid. 8 | 9 | Note: 10 | A valid Sudoku board (partially filled) is not necessarily solvable. Only the filled cells need to be validated. 11 | ''' 12 | 13 | class Solution(object): 14 | def isValidSudoku(self, board): 15 | """ 16 | :type board: List[List[str]] 17 | :rtype: bool 18 | """ 19 | point = "." 20 | for i in range(9): 21 | row = [] 22 | column = [] 23 | diagonal = [] 24 | for j in range(9): 25 | element = board[i][j] 26 | if element != point: 27 | if element in row: 28 | return False 29 | else: 30 | row.append(element) 31 | 32 | element = board[j][i] 33 | if element != point: 34 | if element in column: 35 | return False 36 | else: 37 | column.append(element) 38 | 39 | element = board[i // 3 * 3 + j // 3][i % 3 * 3 + j % 3] 40 | if element != point: 41 | if element in diagonal: 42 | return False 43 | else: 44 | diagonal.append(element) 45 | return True -------------------------------------------------------------------------------- /python/038 Count and Say.py: -------------------------------------------------------------------------------- 1 | ''' 2 | The count-and-say sequence is the sequence of integers beginning as follows: 3 | 1, 11, 21, 1211, 111221, ... 4 | 5 | 1 is read off as "one 1" or 11. 6 | 11 is read off as "two 1s" or 21. 7 | 21 is read off as "one 2, then one 1" or 1211. 8 | Given an integer n, generate the nth sequence. 9 | 10 | Note: The sequence of integers will be represented as a string. 11 | ''' 12 | 13 | class Solution(object): 14 | def countAndSay(self, n): 15 | """ 16 | :type n: int 17 | :rtype: str 18 | """ 19 | result = "1" 20 | for __ in range(1, n): 21 | result = self.getNext(result) 22 | return result 23 | 24 | def getNext(self, s): 25 | result = [] 26 | start = 0 27 | while start < len(s): 28 | curr = start + 1 29 | while curr < len(s) and s[start] == s[curr]: 30 | curr += 1 31 | result.extend((str(curr - start), s[start])) 32 | start = curr 33 | return "".join(result) -------------------------------------------------------------------------------- /python/039 Combination Sum.py: -------------------------------------------------------------------------------- 1 | ''' 2 | 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. 3 | 4 | The same repeated number may be chosen from C unlimited number of times. 5 | 6 | Note: 7 | All numbers (including target) will be positive integers. 8 | Elements in a combination (a1, a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak). 9 | The solution set must not contain duplicate combinations. 10 | For example, given candidate set 2,3,6,7 and target 7, 11 | A solution set is: 12 | [7] 13 | [2, 2, 3] 14 | ''' 15 | 16 | class Solution(object): 17 | def combinationSum(self, candidates, target): 18 | """ 19 | :type candidates: List[int] 20 | :type target: int 21 | :rtype: List[List[int]] 22 | """ 23 | if not candidates: 24 | return [] 25 | candidates.sort() 26 | result = [] 27 | self.combination(candidates, target, [], result) 28 | return result 29 | 30 | def combination(self, candidates, target, current, result): 31 | s = sum(current) if current else 0 32 | if s > target: 33 | return 34 | elif s == target: 35 | result.append(current) 36 | return 37 | else: 38 | for i, v in enumerate(candidates): 39 | self.combination(candidates[i:], target, current + [v], result) 40 | 41 | 42 | if __name__ == "__main__": 43 | assert Solution().combinationSum([2, 3, 6, 7], 7) == [[2, 2, 3], [7]] 44 | -------------------------------------------------------------------------------- /python/041 First Missing Positive.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an unsorted integer array, find the first missing positive integer. 3 | 4 | For example, 5 | Given [1,2,0] return 3, 6 | and [3,4,-1,1] return 2. 7 | 8 | Your algorithm should run in O(n) time and uses constant space. 9 | ''' 10 | 11 | class Solution(object): 12 | def firstMissingPositive(self, nums): 13 | """ 14 | :type nums: List[int] 15 | :rtype: int 16 | """ 17 | if not nums: 18 | return 1 19 | i = 0 20 | length = len(nums) 21 | while i < length: 22 | current = nums[i] 23 | if current <= 0 or current > length or nums[current - 1] == current: 24 | i += 1 25 | else: 26 | nums[current - 1], nums[i] = nums[i], nums[current - 1] 27 | 28 | for i in range(length): 29 | if nums[i] != i + 1: 30 | return i + 1 31 | return length + 1 32 | 33 | 34 | if __name__ == "__main__": 35 | assert Solution().firstMissingPositive([1, 2, 0]) == 3 36 | assert Solution().firstMissingPositive([1, 2, 3]) == 4 37 | assert Solution().firstMissingPositive([3, 4, -1, 1]) == 2 -------------------------------------------------------------------------------- /python/042 Trapping Rain Water.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining. 3 | 4 | For example, 5 | Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6. 6 | 7 | 8 | The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. Thanks Marcos for contributing this image! 9 | ''' 10 | 11 | class Solution(object): 12 | def trap(self, height): 13 | """ 14 | :type height: List[int] 15 | :rtype: int 16 | """ 17 | if not height: 18 | return 0 19 | length = len(height) 20 | maxh = [0 for __ in range(length)] 21 | h = height[length - 1] 22 | for i in range(length - 2, -1, -1): 23 | maxh[i] = h 24 | h = max(h, height[i]) 25 | 26 | h = height[0] 27 | result = 0 28 | for i in range(1, length - 1): 29 | h = max(h, height[i]) 30 | result += max(0, min(h, maxh[i]) - height[i]) 31 | return result 32 | 33 | 34 | if __name__ == "__main__": 35 | assert Solution().trap([0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1]) == 6 -------------------------------------------------------------------------------- /python/043 Multiply Strings.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given two numbers represented as strings, return multiplication of the numbers as a string. 3 | 4 | Note: The numbers can be arbitrarily large and are non-negative. 5 | ''' 6 | 7 | class Solution(object): 8 | def multiply(self, num1, num2): 9 | """ 10 | :type num1: str 11 | :type num2: str 12 | :rtype: str 13 | """ 14 | num1 = num1[::-1] 15 | num2 = num2[::-1] 16 | length1 = len(num1) 17 | length2 = len(num2) 18 | temp = [0 for __ in range(length1 + length2)] 19 | # Do multiply 20 | for i in range(length1): 21 | for j in range(length2): 22 | temp[i + j] += int(num1[i]) * int(num2[j]) 23 | carry = 0 24 | digits = [] 25 | # Do plus 26 | for num in temp: 27 | s = carry + num 28 | carry = s // 10 29 | digits.append(str(s % 10)) 30 | result = "".join(digits)[::-1] 31 | # Remove the surplus zero 32 | sub_index = 0 33 | for i in range(length1 + length2 - 1): 34 | if result[i] == "0": 35 | sub_index += 1 36 | else: 37 | break 38 | result = result[sub_index:] 39 | return result 40 | 41 | 42 | if __name__ == "__main__": 43 | assert Solution().multiply("120", "20000") == 2400000 44 | assert Solution().multiply("0", "3421") == 0 -------------------------------------------------------------------------------- /python/045 Jump Game II.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an array of non-negative integers, you are initially positioned at the first index of the array. 3 | 4 | Each element in the array represents your maximum jump length at that position. 5 | 6 | Your goal is to reach the last index in the minimum number of jumps. 7 | 8 | For example: 9 | Given array A = [2,3,1,1,4] 10 | 11 | The minimum number of jumps to reach the last index is 2. (Jump 1 step from index 0 to 1, then 3 steps to the last index.) 12 | 13 | Note: 14 | You can assume that you can always reach the last index. 15 | ''' 16 | 17 | class Solution(object): 18 | def jump(self, nums): 19 | """ 20 | :type nums: List[int] 21 | :rtype: int 22 | """ 23 | length = len(nums) 24 | counter = 0 25 | longest = 0 26 | reach = 0 27 | for i in range(length): 28 | if longest < i: 29 | counter += 1 30 | longest = reach 31 | reach = max(reach, nums[i] + i) 32 | return counter 33 | 34 | 35 | if __name__ == "__main__": 36 | assert Solution().jump([2, 3, 1, 1, 4]) == 2 -------------------------------------------------------------------------------- /python/046 Permutations.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a collection of distinct numbers, return all possible permutations. 3 | 4 | For example, 5 | [1,2,3] have the following permutations: 6 | [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], and [3,2,1]. 7 | ''' 8 | 9 | class Solution(object): 10 | def permute(self, nums): 11 | """ 12 | :type nums: List[int] 13 | :rtype: List[List[int]] 14 | """ 15 | result = [] 16 | self.get_permute([], nums, result) 17 | return result 18 | 19 | def get_permute(self, current, num, result): 20 | if not num: 21 | result.append(current + []) 22 | return 23 | for i, v in enumerate(num): 24 | current.append(num[i]) 25 | self.get_permute(current, num[:i] + num[i + 1:], result) 26 | current.pop() 27 | 28 | 29 | if __name__ == "__main__": 30 | assert Solution().permute([1, 2, 3]) == [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]] -------------------------------------------------------------------------------- /python/047 Permutations II.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a collection of numbers that might contain duplicates, return all possible unique permutations. 3 | 4 | For example, 5 | [1,1,2] have the following unique permutations: 6 | [1,1,2], [1,2,1], and [2,1,1]. 7 | ''' 8 | 9 | class Solution(object): 10 | def permuteUnique(self, nums): 11 | """ 12 | :type nums: List[int] 13 | :rtype: List[List[int]] 14 | """ 15 | result = [] 16 | nums.sort() 17 | self.get_permute([], nums, result) 18 | return result 19 | 20 | def get_permute(self, current, num, result): 21 | if not num: 22 | result.append(current + []) 23 | return 24 | for i, v in enumerate(num): 25 | if i - 1 >= 0 and num[i] == num[i - 1]: 26 | continue 27 | current.append(num[i]) 28 | self.get_permute(current, num[:i] + num[i + 1:], result) 29 | current.pop() 30 | 31 | 32 | if __name__ == "__main__": 33 | assert Solution().permuteUnique([1, 2, 1]) == [[1, 1, 2], [1, 2, 1], [2, 1, 1]] -------------------------------------------------------------------------------- /python/048 Rotate Image.py: -------------------------------------------------------------------------------- 1 | ''' 2 | You are given an n x n 2D matrix representing an image. 3 | 4 | Rotate the image by 90 degrees (clockwise). 5 | 6 | Follow up: 7 | Could you do this in-place? 8 | ''' 9 | 10 | class Solution(object): 11 | def rotate(self, matrix): 12 | """ 13 | :type matrix: List[List[int]] 14 | :rtype: void Do not return anything, modify matrix in-place instead. 15 | """ 16 | n = len(matrix) 17 | for row in range(n): 18 | for column in range(n - row): 19 | matrix[row][column], matrix[n - 1 - column][n - 1 - row] = matrix[n - 1 - column][n - 1 - row], \ 20 | matrix[row][column] 21 | for row in range(n // 2): 22 | for column in range(n): 23 | matrix[row][column], matrix[n - 1 - row][column] = matrix[n - 1 - row][column], matrix[row][column] 24 | # No need, just to test 25 | return matrix 26 | 27 | 28 | if __name__ == "__main__": 29 | assert Solution().rotate([[1, 2, 3], [8, 9, 4], [7, 6, 5]]) == [[7, 8, 1], [6, 9, 2], [5, 4, 3]] -------------------------------------------------------------------------------- /python/049 Group Anagrams.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an array of strings, group anagrams together. 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 | Note: 13 | For the return value, each inner list's elements must follow the lexicographic order. 14 | All inputs will be in lower-case. 15 | ''' 16 | 17 | class Solution(object): 18 | def groupAnagrams(self, strs): 19 | """ 20 | :type strs: List[str] 21 | :rtype: List[List[str]] 22 | """ 23 | map = {} 24 | for i, v in enumerate(strs): 25 | target = "".join(sorted(v)) 26 | if target not in map: 27 | map[target]=[v] 28 | else: 29 | map[target].append(v) 30 | 31 | result = [] 32 | for value in map.values(): 33 | result += [sorted(value)] 34 | return result 35 | 36 | 37 | if __name__ == "__main__": 38 | assert Solution().groupAnagrams(["eat", "tea", "tan", "ate", "nat", "bat"]) == [['nat', 'tan'], ['bat'], 39 | ['ate', 'eat', 'tea']] -------------------------------------------------------------------------------- /python/050 Pow(x, n).py: -------------------------------------------------------------------------------- 1 | ''' 2 | Implement pow(x, n). 3 | ''' 4 | 5 | class Solution(object): 6 | def myPow(self, x, n): 7 | """ 8 | :type x: float 9 | :type n: int 10 | :rtype: float 11 | """ 12 | flag = 1 if n >= 0 else -1 13 | result = 1 14 | n = abs(n) 15 | while n > 0: 16 | if n & 1 == 1: 17 | result *= x 18 | n >>= 1 19 | x *= x 20 | if flag < 0: 21 | result = 1 / result 22 | return result 23 | 24 | 25 | if __name__ == "__main__": 26 | assert Solution().myPow(2, -1) == 0.5 27 | assert Solution().myPow(2.1, 2) == 4.41 -------------------------------------------------------------------------------- /python/052 N-Queens II.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Follow up for N-Queens problem. 3 | 4 | Now, instead outputting board configurations, return the total number of distinct solutions. 5 | ''' 6 | 7 | class Solution(object): 8 | def totalNQueens(self, n): 9 | """ 10 | :type n: int 11 | :rtype: int 12 | """ 13 | self.col = [False] * n 14 | self.diag = [False] * (2 * n) 15 | self.anti_diag = [False] * (2 * n) 16 | self.result = 0 17 | self.recursive(0, n) 18 | return self.result 19 | 20 | def recursive(self, row, n): 21 | 22 | if row == n: 23 | self.result += 1 24 | else: 25 | for i in range(n): 26 | if not self.col[i] and not self.diag[row + i] and not self.anti_diag[n - i + row]: 27 | self.col[i] = self.diag[row + i] = self.anti_diag[n - i + row] = True 28 | self.recursive(row + 1, n) 29 | self.col[i] = self.diag[row + i] = self.anti_diag[n - i + row] = False 30 | 31 | 32 | if __name__ == "__main__": 33 | assert Solution().totalNQueens(8) == 92 -------------------------------------------------------------------------------- /python/053 Maximum Subarray.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Find the contiguous subarray within an array (containing at least one number) which has the largest sum. 3 | 4 | For example, given the array [−2,1,−3,4,−1,2,1,−5,4], 5 | the contiguous subarray [4,−1,2,1] has the largest sum = 6. 6 | ''' 7 | 8 | class Solution(object): 9 | def maxSubArray(self, nums): 10 | """ 11 | :type nums: List[int] 12 | :rtype: int 13 | """ 14 | if not nums: 15 | return 0 16 | length = len(nums) 17 | current = nums[0] 18 | m = current 19 | for i in range(1, length): 20 | if current < 0: 21 | current = 0 22 | current += nums[i] 23 | m = max(current, m) 24 | return m 25 | 26 | 27 | if __name__ == "__main__": 28 | assert Solution().maxSubArray([-2, 1, -3, 4, -1, 2, 1, -5, 4]) == 6 -------------------------------------------------------------------------------- /python/055 Jump Game.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an array of non-negative integers, you are initially positioned at the first index of the array. 3 | 4 | Each element in the array represents your maximum jump length at that position. 5 | 6 | Determine if you are able to reach the last index. 7 | 8 | For example: 9 | A = [2,3,1,1,4], return true. 10 | 11 | A = [3,2,1,0,4], return false. 12 | ''' 13 | 14 | class Solution(object): 15 | def canJump(self, nums): 16 | """ 17 | :type nums: List[int] 18 | :rtype: bool 19 | """ 20 | if not nums: 21 | return False 22 | length = len(nums) 23 | index = 0 24 | longest = nums[0] 25 | while index <= longest: 26 | if longest >= length - 1: 27 | return True 28 | longest = max(longest, index + nums[index]) 29 | index += 1 30 | return False 31 | 32 | 33 | if __name__ == "__main__": 34 | assert Solution().canJump([2, 3, 1, 1, 4]) == True 35 | assert Solution().canJump([3, 2, 1, 0, 4]) == False -------------------------------------------------------------------------------- /python/056 Merge Intervals.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a collection of intervals, merge all overlapping intervals. 3 | 4 | For example, 5 | Given [1,3],[2,6],[8,10],[15,18], 6 | return [1,6],[8,10],[15,18]. 7 | ''' 8 | 9 | # Definition for an interval. 10 | class Interval(object): 11 | def __init__(self, s=0, e=0): 12 | self.start = s 13 | self.end = e 14 | 15 | # To print the result 16 | def __str__(self): 17 | return "[" + str(self.start) + "," + str(self.end) + "]" 18 | 19 | 20 | class Solution(object): 21 | def merge(self, intervals): 22 | """ 23 | :type intervals: List[Interval] 24 | :rtype: List[Interval] 25 | """ 26 | result = [] 27 | if not intervals: 28 | return result 29 | intervals.sort(key=lambda x: x.start) 30 | result.append(intervals[0]) 31 | for interval in intervals[1:]: 32 | prev = result[-1] 33 | if prev.end >= interval.start: 34 | prev.end = max(prev.end, interval.end) 35 | else: 36 | result.append(interval) 37 | return result 38 | 39 | 40 | if __name__ == "__main__": 41 | intervals = Solution().merge([Interval(1, 3), Interval(2, 6), Interval(8, 10), Interval(15, 18)]) 42 | for interval in intervals: 43 | print(interval) -------------------------------------------------------------------------------- /python/057 Insert Interval.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary). 3 | 4 | You may assume that the intervals were initially sorted according to their start times. 5 | 6 | Example 1: 7 | Given intervals [1,3],[6,9], insert and merge [2,5] in as [1,5],[6,9]. 8 | 9 | Example 2: 10 | Given [1,2],[3,5],[6,7],[8,10],[12,16], insert and merge [4,9] in as [1,2],[3,10],[12,16]. 11 | 12 | This is because the new interval [4,9] overlaps with [3,5],[6,7],[8,10] 13 | ''' 14 | 15 | # Definition for an interval. 16 | class Interval(object): 17 | def __init__(self, s=0, e=0): 18 | self.start = s 19 | self.end = e 20 | 21 | # To print the result 22 | def __str__(self): 23 | return "[" + str(self.start) + "," + str(self.end) + "]" 24 | 25 | 26 | class Solution(object): 27 | def insert(self, intervals, newInterval): 28 | start, end = newInterval.start, newInterval.end 29 | left = list(filter(lambda x: x.end < start, intervals)) 30 | right = list(filter(lambda x: x.start > end, intervals)) 31 | if len(left) + len(right) != len(intervals): 32 | start = min(start, intervals[len(left)].start) 33 | end = max(end, intervals[-len(right) - 1].end) 34 | 35 | return left + [Interval(start, end)] + right 36 | 37 | 38 | if __name__ == "__main__": 39 | intervals = Solution().insert([Interval(2, 6), Interval(8, 10), Interval(15, 18)], Interval(13, 16)) 40 | for interval in intervals: 41 | print(interval) -------------------------------------------------------------------------------- /python/058 Length of Last Word.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string. 3 | 4 | If the last word does not exist, return 0. 5 | 6 | Note: A word is defined as a character sequence consists of non-space characters only. 7 | 8 | For example, 9 | Given s = "Hello World", 10 | return 5. 11 | ''' 12 | 13 | class Solution(object): 14 | def lengthOfLastWord(self, s): 15 | """ 16 | :type s: str 17 | :rtype: int 18 | """ 19 | length = len(s) 20 | index = length - 1 21 | count = 0 22 | while index >= 0 and s[index] == " ": 23 | index -= 1 24 | while index >= 0 and s[index] != " ": 25 | index -= 1 26 | count += 1 27 | return count 28 | 29 | 30 | if __name__ == "__main__": 31 | assert Solution().lengthOfLastWord(" ") == 0 32 | assert Solution().lengthOfLastWord(" a") == 1 33 | assert Solution().lengthOfLastWord(" drfish ") == 6 -------------------------------------------------------------------------------- /python/059 Spiral Matrix II.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order. 3 | 4 | For example, 5 | Given n = 3, 6 | 7 | You should return the following matrix: 8 | [ 9 | [ 1, 2, 3 ], 10 | [ 8, 9, 4 ], 11 | [ 7, 6, 5 ] 12 | ] 13 | ''' 14 | 15 | class Solution(object): 16 | def generateMatrix(self, n): 17 | """ 18 | :type n: int 19 | :rtype: List[List[int]] 20 | """ 21 | left = top = 0 22 | right = n - 1 23 | bottom = n - 1 24 | num = 1 25 | result = [[0 for __ in range(n)] for __ in range(n)] 26 | while left < right and top < bottom: 27 | for i in range(left, right): 28 | result[top][i] = num 29 | num += 1 30 | for i in range(top, bottom): 31 | result[i][right] = num 32 | num += 1 33 | for i in range(right, left, -1): 34 | result[bottom][i] = num 35 | num += 1 36 | for i in range(bottom, top, -1): 37 | result[i][left] = num 38 | num += 1 39 | left += 1 40 | right -= 1 41 | top += 1 42 | bottom -= 1 43 | if left == right and top == bottom: 44 | result[top][left] = num 45 | return result 46 | 47 | 48 | if __name__ == "__main__": 49 | assert Solution().generateMatrix(5) == [[1, 2, 3, 4, 5], [16, 17, 18, 19, 6], [15, 24, 25, 20, 7], 50 | [14, 23, 22, 21, 8], [13, 12, 11, 10, 9]] -------------------------------------------------------------------------------- /python/060 Permutation Sequence.py: -------------------------------------------------------------------------------- 1 | ''' 2 | The set [1,2,3,…,n] contains a total of n! unique permutations. 3 | 4 | By listing and labeling all of the permutations in order, 5 | We get the following sequence (ie, for n = 3): 6 | 7 | "123" 8 | "132" 9 | "213" 10 | "231" 11 | "312" 12 | "321" 13 | Given n and k, return the kth permutation sequence. 14 | 15 | Note: Given n will be between 1 and 9 inclusive. 16 | ''' 17 | 18 | class Solution(object): 19 | def getPermutation(self, n, k): 20 | """ 21 | :type n: int 22 | :type k: int 23 | :rtype: str 24 | """ 25 | k -= 1 26 | factorial = 1 27 | for i in range(1, n): 28 | factorial *= i 29 | 30 | result = [] 31 | array = list(range(1, n + 1)) 32 | for i in range(n - 1, 0, -1): 33 | index = k // factorial 34 | result.append(str(array[index])) 35 | array = array[:index] + array[index + 1:] 36 | k %= factorial 37 | factorial //= i 38 | result.append(str(array[0])) 39 | return "".join(result) 40 | 41 | 42 | if __name__ == "__main__": 43 | assert Solution().getPermutation(3, 3) == "213" 44 | assert Solution().getPermutation(9, 324) == "123685974" -------------------------------------------------------------------------------- /python/061 Rotate List.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a list, rotate the list to the right by k places, where k is non-negative. 3 | 4 | For example: 5 | Given 1->2->3->4->5->NULL and k = 2, 6 | return 4->5->1->2->3->NULL. 7 | ''' 8 | 9 | # Definition for singly-linked list. 10 | class ListNode(object): 11 | def __init__(self, x): 12 | self.val = x 13 | self.next = None 14 | 15 | def myprint(self): 16 | print(self.val) 17 | if self.next: 18 | self.next.myprint() 19 | 20 | 21 | class Solution(object): 22 | def rotateRight(self, head, k): 23 | """ 24 | :type head: ListNode 25 | :type k: int 26 | :rtype: ListNode 27 | """ 28 | if not head: 29 | return [] 30 | curr = head 31 | length = 1 32 | while curr.next: 33 | curr = curr.next 34 | length += 1 35 | curr.next = head 36 | cur = head 37 | shift = length - k % length 38 | while shift > 0: 39 | curr = curr.next 40 | shift -= 1 41 | result = curr.next 42 | curr.next = None 43 | return result 44 | 45 | 46 | if __name__ == "__main__": 47 | l1 = ListNode(1) 48 | l2 = ListNode(2) 49 | l3 = ListNode(3) 50 | l4 = ListNode(4) 51 | l5 = ListNode(5) 52 | l1.next = l2 53 | l2.next = l3 54 | l3.next = l4 55 | l4.next = l5 56 | result = Solution().rotateRight(l1, 2) 57 | result.myprint() -------------------------------------------------------------------------------- /python/062 Unique Paths.py: -------------------------------------------------------------------------------- 1 | ''' 2 | A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below). 3 | 4 | The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below). 5 | 6 | How many possible unique paths are there? 7 | 8 | 9 | Above is a 3 x 7 grid. How many possible unique paths are there? 10 | 11 | Note: m and n will be at most 100. 12 | ''' 13 | 14 | class Solution(object): 15 | def uniquePaths(self, m, n): 16 | """ 17 | :type m: int 18 | :type n: int 19 | :rtype: int 20 | """ 21 | dp = [[1 for __ in range(n)] for __ in range(m)] 22 | for i in range(1, n): 23 | for j in range(1, m): 24 | dp[j][i] = dp[j - 1][i] + dp[j][i - 1] 25 | return dp[m - 1][n - 1] 26 | 27 | 28 | if __name__ == "__main__": 29 | assert Solution().uniquePaths(3, 7) == 28 -------------------------------------------------------------------------------- /python/063 Unique Paths II.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Follow up for "Unique Paths": 3 | 4 | Now consider if some obstacles are added to the grids. How many unique paths would there be? 5 | 6 | An obstacle and empty space is marked as 1 and 0 respectively in the grid. 7 | 8 | For example, 9 | There is one obstacle in the middle of a 3x3 grid as illustrated below. 10 | 11 | [ 12 | [0,0,0], 13 | [0,1,0], 14 | [0,0,0] 15 | ] 16 | The total number of unique paths is 2. 17 | ''' 18 | 19 | class Solution(object): 20 | def uniquePathsWithObstacles(self, obstacleGrid): 21 | """ 22 | :type obstacleGrid: List[List[int]] 23 | :rtype: int 24 | """ 25 | if obstacleGrid[0][0] == 1: 26 | return 0 27 | m = len(obstacleGrid) 28 | n = len(obstacleGrid[0]) 29 | dp = [[0 for __ in range(n)] for __ in range(m)] 30 | dp[0][0] = 1 31 | for i in range(1, m): 32 | dp[i][0] = dp[i - 1][0] if obstacleGrid[i][0] == 0 else 0 33 | for j in range(1, n): 34 | dp[0][j] = dp[0][j - 1] if obstacleGrid[0][j] == 0 else 0 35 | for i in range(1, m): 36 | for j in range(1, n): 37 | if obstacleGrid[i][j] == 1: 38 | dp[i][j] = 0 39 | else: 40 | dp[i][j] = dp[i - 1][j] + dp[i][j - 1] 41 | return dp[m - 1][n - 1] 42 | 43 | 44 | if __name__ == "__main__": 45 | assert Solution().uniquePathsWithObstacles([ 46 | [0, 0, 0], 47 | [0, 1, 0], 48 | [0, 0, 0] 49 | ]) == 2 -------------------------------------------------------------------------------- /python/064 Minimum Path Sum.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path. 3 | 4 | Note: You can only move either down or right at any point in time. 5 | ''' 6 | 7 | class Solution(object): 8 | def minPathSum(self, grid): 9 | """ 10 | :type grid: List[List[int]] 11 | :rtype: int 12 | """ 13 | m = len(grid) 14 | n = len(grid[0]) 15 | 16 | dp = [0 for __ in range(n)] 17 | dp[0] = grid[0][0] 18 | for j in range(1, n): 19 | dp[j] = dp[j - 1] + grid[0][j] 20 | for i in range(1, m): 21 | dp[0] += grid[i][0] 22 | for j in range(1, n): 23 | dp[j] = min(dp[j], dp[j - 1]) + grid[i][j] 24 | return dp[-1] 25 | 26 | 27 | if __name__ == "__main__": 28 | assert Solution().minPathSum([ 29 | [1, 2, 4], 30 | [2, 4, 1], 31 | [3, 2, 1]]) == 9 -------------------------------------------------------------------------------- /python/066 Plus One.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a non-negative number represented as an array of digits, plus one to the number. 3 | 4 | The digits are stored such that the most significant digit is at the head of the list. 5 | ''' 6 | 7 | class Solution(object): 8 | def plusOne(self, digits): 9 | """ 10 | :type digits: List[int] 11 | :rtype: List[int] 12 | """ 13 | carry = 1 14 | for i in range(len(digits) - 1, -1, -1): 15 | digits[i] += carry 16 | if digits[i] < 10: 17 | carry = 0 18 | break 19 | else: 20 | digits[i] -= 10 21 | if carry == 1: 22 | digits.insert(0, 1) 23 | return digits 24 | 25 | 26 | if __name__ == "__main__": 27 | assert Solution().plusOne([1, 2, 3, 4, 9]) == [1, 2, 3, 5, 0] 28 | assert Solution().plusOne([9]) == [1, 0] -------------------------------------------------------------------------------- /python/067 Add Binary.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given two binary strings, return their sum (also a binary string). 3 | 4 | For example, 5 | a = "11" 6 | b = "1" 7 | Return "100". 8 | ''' 9 | 10 | class Solution(object): 11 | def addBinary(self, a, b): 12 | """ 13 | :type a: str 14 | :type b: str 15 | :rtype: str 16 | """ 17 | result = [] 18 | carry = val = 0 19 | if len(a) < len(b): 20 | a, b = b, a 21 | lengthA = len(a) 22 | lengthB = len(b) 23 | for i in range(lengthA): 24 | val = carry 25 | val += int(a[-(i + 1)]) 26 | if i < lengthB: 27 | val += int(b[-(i + 1)]) 28 | carry, val = val // 2, val % 2 29 | result.append(str(val)) 30 | if carry: 31 | result.append(str(carry)) 32 | return "".join(result[::-1]) 33 | 34 | 35 | if __name__ == "__main__": 36 | assert Solution().addBinary("111", "1") == "1000" -------------------------------------------------------------------------------- /python/069 Sqrt(x).py: -------------------------------------------------------------------------------- 1 | ''' 2 | Implement int sqrt(int x). 3 | 4 | Compute and return the square root of x. 5 | ''' 6 | 7 | class Solution(object): 8 | def mySqrt(self, x): 9 | """ 10 | :type x: int 11 | :rtype: int 12 | """ 13 | result = 1.0 14 | while abs(result * result - x) > 0.1: 15 | result = (result + x / result) / 2 16 | return int(result) 17 | 18 | 19 | if __name__ == "__main__": 20 | assert Solution().mySqrt(5) == 2 21 | assert Solution().mySqrt(0) == 0 -------------------------------------------------------------------------------- /python/070 Climbing Stairs.py: -------------------------------------------------------------------------------- 1 | ''' 2 | You are climbing a stair case. It takes n steps to reach to the top. 3 | 4 | Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? 5 | ''' 6 | 7 | class Solution(object): 8 | def climbStairs(self, n): 9 | """ 10 | :type n: int 11 | :rtype: int 12 | """ 13 | if n <= 2: 14 | return n 15 | dp = [0 for __ in range(n)] 16 | dp[0] = 1 17 | dp[1] = 2 18 | for i in range(2, n): 19 | dp[i] = dp[i - 1] + dp[i - 2] 20 | return dp[n - 1] 21 | 22 | 23 | if __name__ == "__main__": 24 | assert Solution().climbStairs(6) == 13 -------------------------------------------------------------------------------- /python/071 Simplify Path.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an absolute path for a file (Unix-style), simplify it. 3 | 4 | For example, 5 | path = "/home/", => "/home" 6 | path = "/a/./b/../../c/", => "/c" 7 | 8 | Corner Cases: 9 | Did you consider the case where path = "/../"? 10 | In this case, you should return "/". 11 | Another corner case is the path might contain multiple slashes '/' together, such as "/home//foo/". 12 | In this case, you should ignore redundant slashes and return "/home/foo". 13 | ''' 14 | 15 | class Solution(object): 16 | def simplifyPath(self, path): 17 | """ 18 | :type path: str 19 | :rtype: str 20 | """ 21 | parts = path.split("/") 22 | result = [''] 23 | for part in parts: 24 | if part: 25 | if part not in ('.', '..'): 26 | if len(result) == 0: 27 | result.append('') 28 | result.append(part) 29 | elif part == '..' and len(result) > 0: 30 | result.pop() 31 | if len(result) < 2: 32 | return "/" 33 | else: 34 | return "/".join(result) 35 | 36 | 37 | if __name__ == "__main__": 38 | assert Solution().simplifyPath("/a/./b/../../c/") == '/c' 39 | assert Solution().simplifyPath("/home/") == "/home" 40 | assert Solution().simplifyPath("/../../") == "/" -------------------------------------------------------------------------------- /python/072 Edit Distance.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given two words word1 and word2, find the minimum number of steps required to convert word1 to word2. (each operation is counted as 1 step.) 3 | 4 | You have the following 3 operations permitted on a word: 5 | 6 | a) Insert a character 7 | b) Delete a character 8 | c) Replace a character 9 | ''' 10 | 11 | class Solution(object): 12 | def minDistance(self, word1, word2): 13 | """ 14 | :type word1: str 15 | :type word2: str 16 | :rtype: int 17 | """ 18 | m = len(word1) 19 | n = len(word2) 20 | dp = [[0 for __ in range(m + 1)] for __ in range(n + 1)] 21 | for j in range(m + 1): 22 | dp[0][j] = j 23 | for i in range(n + 1): 24 | dp[i][0] = i 25 | for i in range(1, n + 1): 26 | for j in range(1, m + 1): 27 | onemore = 1 if word1[j - 1] != word2[i - 1] else 0 28 | dp[i][j] = min(dp[i - 1][j] + 1, dp[i][j - 1] + 1, dp[i - 1][j - 1] + onemore) 29 | return dp[n][m] 30 | 31 | 32 | if __name__ == "__main__": 33 | assert Solution().minDistance("", "a") == 1 34 | assert Solution().minDistance("faf", "efef") == 2 -------------------------------------------------------------------------------- /python/074 Search a 2D Matrix.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties: 3 | 4 | Integers in each row are sorted from left to right. 5 | The first integer of each row is greater than the last integer of the previous row. 6 | For example, 7 | 8 | Consider the following matrix: 9 | 10 | [ 11 | [1, 3, 5, 7], 12 | [10, 11, 16, 20], 13 | [23, 30, 34, 50] 14 | ] 15 | Given target = 3, return true. 16 | ''' 17 | 18 | class Solution(object): 19 | def searchMatrix(self, matrix, target): 20 | """ 21 | :type matrix: List[List[int]] 22 | :type target: int 23 | :rtype: bool 24 | """ 25 | m = len(matrix) 26 | n = len(matrix[0]) 27 | l, h = 0, m * n - 1 28 | while l <= h: 29 | mid = l + (h - l) // 2 30 | if matrix[mid // n][mid % n] == target: 31 | return True 32 | elif matrix[mid // n][mid % n] < target: 33 | l = mid + 1 34 | else: 35 | h = mid - 1 36 | return False 37 | 38 | 39 | if __name__ == "__main__": 40 | assert Solution().searchMatrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]], 5) == True 41 | assert Solution().searchMatrix([[1, 2], [3, 4]], 4) == True 42 | assert Solution().searchMatrix([[1]], 2) == False -------------------------------------------------------------------------------- /python/075 Sort Colors.py: -------------------------------------------------------------------------------- 1 | ''' 2 | 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. 3 | 4 | Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively. 5 | 6 | Note: 7 | You are not suppose to use the library's sort function for this problem. 8 | 9 | Follow up: 10 | A rather straight forward solution is a two-pass algorithm using counting sort. 11 | 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. 12 | 13 | Could you come up with an one-pass algorithm using only constant space? 14 | ''' 15 | 16 | class Solution(object): 17 | def sortColors(self, nums): 18 | """ 19 | :type nums: List[int] 20 | :rtype: void Do not return anything, modify nums in-place instead. 21 | """ 22 | left = mid = 0 23 | right = len(nums) - 1 24 | while mid <= right: 25 | if nums[mid] == 0: 26 | nums[mid], nums[left] = nums[left], nums[mid] 27 | left += 1 28 | mid += 1 29 | elif nums[mid] == 1: 30 | mid += 1 31 | else: 32 | nums[mid], nums[right] = nums[right], nums[mid] 33 | right -= 1 34 | 35 | 36 | if __name__ == "__main__": 37 | l = [1, 2, 1, 2, 0, 2, 1, 0, 2, 0, 0, 2] 38 | Solution().sortColors(l) 39 | assert l == [0, 0, 0, 0, 1, 1, 1, 2, 2, 2, 2, 2] -------------------------------------------------------------------------------- /python/077 Combinations.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given two integers n and k, return all possible combinations of k numbers out of 1 ... n. 3 | 4 | For example, 5 | If n = 4 and k = 2, a solution is: 6 | 7 | [ 8 | [2,4], 9 | [3,4], 10 | [2,3], 11 | [1,2], 12 | [1,3], 13 | [1,4], 14 | ] 15 | ''' 16 | 17 | class Solution(object): 18 | def combine(self, n, k): 19 | """ 20 | :type n: int 21 | :type k: int 22 | :rtype: List[List[int]] 23 | """ 24 | if k == 1: 25 | return [[i + 1] for i in range(n)] 26 | result = [] 27 | if n > k: 28 | result = [r + [n] for r in self.combine(n - 1, k - 1)] + self.combine(n - 1, k) 29 | else: 30 | result = [r + [n] for r in self.combine(n - 1, k - 1)] 31 | return result 32 | 33 | 34 | if __name__ == "__main__": 35 | assert Solution().combine(4, 2) == [[1, 4], [2, 4], [3, 4], [1, 3], [2, 3], [1, 2]] -------------------------------------------------------------------------------- /python/078 Subsets.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a set of distinct integers, nums, return all possible subsets. 3 | 4 | Note: 5 | Elements in a subset must be in non-descending order. 6 | The solution set must not contain duplicate subsets. 7 | For example, 8 | If nums = [1,2,3], a solution is: 9 | 10 | [ 11 | [3], 12 | [1], 13 | [2], 14 | [1,2,3], 15 | [1,3], 16 | [2,3], 17 | [1,2], 18 | [] 19 | ] 20 | ''' 21 | 22 | class Solution(object): 23 | def subsets(self, nums): 24 | """ 25 | :type nums: List[int] 26 | :rtype: List[List[int]] 27 | """ 28 | result = [[]] 29 | for num in sorted(nums): 30 | result += [item + [num] for item in result] 31 | return result 32 | 33 | 34 | if __name__ == "__main__": 35 | assert Solution().subsets([1, 2, 3]) == [[], [1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3]] -------------------------------------------------------------------------------- /python/080 Remove Duplicates from Sorted Array II.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Follow up for "Remove Duplicates": 3 | What if duplicates are allowed at most twice? 4 | 5 | For example, 6 | Given sorted array nums = [1,1,1,2,2,3], 7 | 8 | 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. 9 | ''' 10 | 11 | class Solution(object): 12 | def removeDuplicates(self, nums): 13 | """ 14 | :type nums: List[int] 15 | :rtype: int 16 | """ 17 | count = 0 18 | for i in range(len(nums)): 19 | if count < 2 or nums[count - 2] != nums[i]: 20 | nums[count] = nums[i] 21 | count += 1 22 | return count 23 | 24 | 25 | if __name__ == "__main__": 26 | l = [1, 1, 1, 2, 2, 3] 27 | r = Solution().removeDuplicates(l) 28 | assert l == [1, 1, 2, 2, 3, 3] 29 | assert r == 5 -------------------------------------------------------------------------------- /python/081 Search in Rotated Sorted Array II.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Follow up for "Search in Rotated Sorted Array": 3 | What if duplicates are allowed? 4 | 5 | Would this affect the run-time complexity? How and why? 6 | 7 | Write a function to determine if a given target is in the array. 8 | ''' 9 | 10 | class Solution(object): 11 | def search(self, nums, target): 12 | """ 13 | :type nums: List[int] 14 | :type target: int 15 | :rtype: int 16 | """ 17 | left = 0 18 | right = len(nums) - 1 19 | while left <= right: 20 | mid = left + (right - left) // 2 21 | if nums[mid] == target: 22 | return True 23 | if nums[mid] > target: 24 | if nums[left] <= target or nums[mid] < nums[left]: 25 | right = mid - 1 26 | else: 27 | left = mid + 1 28 | else: 29 | if nums[left] > target or nums[mid] >= nums[left]: 30 | left = mid + 1 31 | else: 32 | right = mid - 1 33 | return False 34 | 35 | 36 | if __name__ == "__main__": 37 | assert Solution().search([4, 5, 5, 6, 7, 0, 1, 2], 4) == True 38 | assert Solution().search([4, 5, 6, 7, 7, 7, 7, 7, 0, 1, 2], 7) == True -------------------------------------------------------------------------------- /python/082 Remove Duplicates from Sorted List II.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list. 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 | # Definition for singly-linked list. 10 | class ListNode(object): 11 | def __init__(self, x): 12 | self.val = x 13 | self.next = None 14 | 15 | def my_print(self): 16 | print(self.val) 17 | if self.next: 18 | print(self.next.val) 19 | 20 | 21 | class Solution(object): 22 | def deleteDuplicates(self, head): 23 | """ 24 | :type head: ListNode 25 | :rtype: ListNode 26 | """ 27 | dummy = ListNode(-1) 28 | dummy.next = head 29 | curr = dummy 30 | is_repeat = False 31 | while curr.next: 32 | while curr.next.next and curr.next.val == curr.next.next.val: 33 | curr.next = curr.next.next 34 | is_repeat = True 35 | if is_repeat: 36 | curr.next = curr.next.next 37 | is_repeat = False 38 | else: 39 | curr = curr.next 40 | return dummy.next 41 | 42 | 43 | if __name__ == "__main__": 44 | n1 = ListNode(1) 45 | n2 = ListNode(1) 46 | n3 = ListNode(2) 47 | n1.next = n2 48 | n2.next = n3 49 | r = Solution().deleteDuplicates(n1) 50 | r.my_print() -------------------------------------------------------------------------------- /python/083 Remove Duplicates from Sorted List.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a sorted linked list, delete all duplicates such that each element appear only once. 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 | # Definition for singly-linked list. 10 | class ListNode(object): 11 | def __init__(self, x): 12 | self.val = x 13 | self.next = None 14 | 15 | def my_print(self): 16 | print(self.val) 17 | if self.next: 18 | print(self.next.val) 19 | 20 | 21 | class Solution(object): 22 | def deleteDuplicates(self, head): 23 | """ 24 | :type head: ListNode 25 | :rtype: ListNode 26 | """ 27 | curr = head 28 | while curr: 29 | while curr.next and curr.val == curr.next.val: 30 | curr.next = curr.next.next 31 | curr = curr.next 32 | return head 33 | 34 | 35 | if __name__ == "__main__": 36 | n1 = ListNode(1) 37 | n2 = ListNode(1) 38 | n3 = ListNode(2) 39 | n1.next = n2 40 | n2.next = n3 41 | r = Solution().deleteDuplicates(n1) 42 | r.my_print() -------------------------------------------------------------------------------- /python/084 Largest Rectangle in Histogram.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given n non-negative integers representing the histogram's bar height where the width of each bar is 1, find the area of largest rectangle in the histogram. 3 | 4 | 5 | Above is a histogram where width of each bar is 1, given height = [2,1,5,6,2,3]. 6 | 7 | 8 | The largest rectangle is shown in the shaded area, which has area = 10 unit. 9 | 10 | For example, 11 | Given heights = [2,1,5,6,2,3], 12 | return 10. 13 | ''' 14 | 15 | class Solution(object): 16 | def largestRectangleArea(self, heights): 17 | """ 18 | :type heights: List[int] 19 | :rtype: int 20 | """ 21 | heights.append(0) 22 | stack = [-1] 23 | result = 0 24 | for i in range(len(heights)): 25 | while heights[i] < heights[stack[-1]]: 26 | h = heights[stack.pop()] 27 | w = i - stack[-1] - 1 28 | result = max(result, h * w) 29 | stack.append(i) 30 | heights.pop() 31 | return result 32 | 33 | 34 | if __name__ == "__main__": 35 | assert Solution().largestRectangleArea([2, 1, 5, 6, 2, 3]) == 10 -------------------------------------------------------------------------------- /python/085 Maximal Rectangle.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing all ones and return its area. 3 | ''' 4 | 5 | class Solution(object): 6 | def maximalRectangle(self, matrix): 7 | """ 8 | :type matrix: List[List[str]] 9 | :rtype: int 10 | """ 11 | if not matrix or not matrix[0]: 12 | return 0 13 | n = len(matrix[0]) 14 | heights = [0 for __ in range(n + 1)] 15 | result = 0 16 | for row in matrix: 17 | for i in range(n): 18 | heights[i] = heights[i] + 1 if row[i] == '1' else 0 19 | stack = [-1] 20 | for i in range(n + 1): 21 | while heights[i] < heights[stack[-1]]: 22 | h = heights[stack.pop()] 23 | w = i - stack[-1] - 1 24 | result = max(result, h * w) 25 | stack.append(i) 26 | return result 27 | 28 | 29 | if __name__ == "__main__": 30 | assert Solution().maximalRectangle([['1', '1', '0', '1', '0', '1'], 31 | ['0', '1', '0', '0', '1', '1'], 32 | ['1', '1', '1', '1', '0', '1'], 33 | ['1', '1', '1', '1', '0', '1']]) == 8 -------------------------------------------------------------------------------- /python/088 Merge Sorted Array.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array. 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 | class Solution(object): 9 | def merge(self, nums1, m, nums2, n): 10 | """ 11 | :type nums1: List[int] 12 | :type m: int 13 | :type nums2: List[int] 14 | :type n: int 15 | :rtype: void Do not return anything, modify nums1 in-place instead. 16 | """ 17 | index = m + n - 1 18 | m -= 1 19 | n -= 1 20 | while m >= 0 and n >= 0: 21 | if nums1[m] > nums2[n]: 22 | nums1[index] = nums1[m] 23 | m -= 1 24 | else: 25 | nums1[index] = nums2[n] 26 | n -= 1 27 | index -= 1 28 | if m < 0: 29 | nums1[:n + 1] = nums2[:n + 1] 30 | 31 | 32 | if __name__ == "__main__": 33 | num1 = [1, 1, 2, 2, 4, 0, 0, 0, 0] 34 | num2 = [0, 0, 2, 3] 35 | Solution().merge(num1, 5, num2, 4) 36 | assert num1 == [0, 0, 1, 1, 2, 2, 2, 3, 4] -------------------------------------------------------------------------------- /python/089 Gray Code.py: -------------------------------------------------------------------------------- 1 | ''' 2 | The gray code is a binary numeral system where two successive values differ in only one bit. 3 | 4 | Given a non-negative integer n representing the total number of bits in the code, print the sequence of gray code. A gray code sequence must begin with 0. 5 | 6 | For example, given n = 2, return [0,1,3,2]. Its gray code sequence is: 7 | 8 | 00 - 0 9 | 01 - 1 10 | 11 - 3 11 | 10 - 2 12 | Note: 13 | For a given n, a gray code sequence is not uniquely defined. 14 | 15 | For example, [0,2,3,1] is also a valid gray code sequence according to the above definition. 16 | 17 | For now, the judge is able to judge based on one instance of gray code sequence. Sorry about that. 18 | ''' 19 | 20 | class Solution(object): 21 | def grayCode(self, n): 22 | """ 23 | :type n: int 24 | :rtype: List[int] 25 | """ 26 | result = [(i >> 1) ^ i for i in range(pow(2, n))] 27 | return result 28 | 29 | 30 | if __name__ == "__main__": 31 | assert Solution().grayCode(2) == [0, 1, 3, 2] -------------------------------------------------------------------------------- /python/090 Subsets II.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a collection of integers that might contain duplicates, nums, return all possible subsets. 3 | 4 | Note: 5 | Elements in a subset must be in non-descending order. 6 | The solution set must not contain duplicate subsets. 7 | For example, 8 | If nums = [1,2,2], a solution is: 9 | 10 | [ 11 | [2], 12 | [1], 13 | [1,2,2], 14 | [2,2], 15 | [1,2], 16 | [] 17 | ] 18 | Subscribe to see which companies asked this question 19 | ''' 20 | 21 | class Solution(object): 22 | def subsetsWithDup(self, nums): 23 | """ 24 | :type nums: List[int] 25 | :rtype: List[List[int]] 26 | """ 27 | result = [[]] 28 | nums.sort() 29 | temp_size = 0 30 | for i in range(len(nums)): 31 | start = temp_size if i >= 1 and nums[i] == nums[i - 1] else 0 32 | temp_size = len(result) 33 | for j in range(start, temp_size): 34 | result.append(result[j] + [nums[i]]) 35 | return result 36 | 37 | 38 | if __name__ == "__main__": 39 | assert Solution().subsetsWithDup([1, 2, 2]) == [[], [1], [2], [1, 2], [2, 2], [1, 2, 2]] -------------------------------------------------------------------------------- /python/091 Decode Ways.py: -------------------------------------------------------------------------------- 1 | ''' 2 | A message containing letters from A-Z is being encoded to numbers using the following mapping: 3 | 4 | 'A' -> 1 5 | 'B' -> 2 6 | ... 7 | 'Z' -> 26 8 | Given an encoded message containing digits, determine the total number of ways to decode it. 9 | 10 | For example, 11 | Given encoded message "12", it could be decoded as "AB" (1 2) or "L" (12). 12 | 13 | The number of ways decoding "12" is 2. 14 | ''' 15 | 16 | class Solution(object): 17 | def numDecodings(self, s): 18 | """ 19 | :type s: str 20 | :rtype: int 21 | """ 22 | length = len(s) 23 | if length == 0: 24 | return 0 25 | dp = [0 for __ in range(length + 1)] 26 | dp[length] = 1 27 | dp[length - 1] = 1 if s[length - 1] != '0' else 0 28 | for i in range(length - 2, -1, -1): 29 | if s[i] != '0': 30 | dp[i] = dp[i + 1] + dp[i + 2] if int(s[i:i + 2]) <= 26 else dp[i + 1] 31 | return dp[0] 32 | 33 | 34 | if __name__ == "__main__": 35 | assert Solution().numDecodings("110") == 1 36 | assert Solution().numDecodings("40") == 0 -------------------------------------------------------------------------------- /python/092 Reverse Linked List II.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Reverse a linked list from position m to n. Do it in-place and in one-pass. 3 | 4 | For example: 5 | Given 1->2->3->4->5->NULL, m = 2 and n = 4, 6 | 7 | return 1->4->3->2->5->NULL. 8 | 9 | Note: 10 | Given m, n satisfy the following condition: 11 | 1 ≤ m ≤ n ≤ length of list. 12 | ''' 13 | 14 | # Definition for singly-linked list. 15 | class ListNode(object): 16 | def __init__(self, x): 17 | self.val = x 18 | self.next = None 19 | 20 | def to_list(self): 21 | return [self.val] + self.next.to_list() if self.next else [self.val] 22 | 23 | 24 | class Solution(object): 25 | def reverseBetween(self, head, m, n): 26 | """ 27 | :type head: ListNode 28 | :type m: int 29 | :type n: int 30 | :rtype: ListNode 31 | """ 32 | dummy = ListNode(-1) 33 | dummy.next = head 34 | node = dummy 35 | for __ in range(m - 1): 36 | node = node.next 37 | prev = node.next 38 | curr = prev.next 39 | for __ in range(n - m): 40 | next = curr.next 41 | curr.next = prev 42 | prev = curr 43 | curr = next 44 | node.next.next = curr 45 | node.next = prev 46 | return dummy.next 47 | 48 | 49 | if __name__ == "__main__": 50 | n1 = ListNode(1) 51 | n2 = ListNode(2) 52 | n3 = ListNode(3) 53 | n4 = ListNode(4) 54 | n5 = ListNode(5) 55 | n1.next = n2 56 | n2.next = n3 57 | n3.next = n4 58 | n4.next = n5 59 | r = Solution().reverseBetween(n1, 2, 4) 60 | assert r.to_list() == [1, 4, 3, 2, 5] -------------------------------------------------------------------------------- /python/093 Restore IP Addresses.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a string containing only digits, restore it by returning all possible valid IP address combinations. 3 | 4 | For example: 5 | Given "25525511135", 6 | 7 | return ["255.255.11.135", "255.255.111.35"]. (Order does not matter) 8 | ''' 9 | 10 | class Solution(object): 11 | def restoreIpAddresses(self, s): 12 | """ 13 | :type s: str 14 | :rtype: List[str] 15 | """ 16 | result = [] 17 | self._restoreIpAddresses(0, s, [], result) 18 | return result 19 | 20 | def _restoreIpAddresses(self, length, s, ips, result): 21 | if not s: 22 | if length == 4: 23 | result.append('.'.join(ips)) 24 | return 25 | elif length == 4: 26 | return 27 | self._restoreIpAddresses(length + 1, s[1:], ips + [s[:1]], result) 28 | if s[0] != '0': 29 | if len(s) >= 2: 30 | self._restoreIpAddresses(length + 1, s[2:], ips + [s[:2]], result) 31 | if len(s) >= 3 and int(s[:3]) <= 255: 32 | self._restoreIpAddresses(length + 1, s[3:], ips + [s[:3]], result) 33 | 34 | 35 | if __name__ == "__main__": 36 | assert Solution().restoreIpAddresses("25525511135") == ['255.255.11.135', '255.255.111.35'] -------------------------------------------------------------------------------- /python/094 Binary Tree Inorder Traversal.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a binary tree, return the inorder traversal of its nodes' values. 3 | 4 | For example: 5 | Given binary tree {1,#,2,3}, 6 | 1 7 | \ 8 | 2 9 | / 10 | 3 11 | return [1,3,2]. 12 | 13 | Note: Recursive solution is trivial, could you do it iteratively? 14 | ''' 15 | 16 | # Definition for a binary tree node. 17 | class TreeNode(object): 18 | def __init__(self, x): 19 | self.val = x 20 | self.left = None 21 | self.right = None 22 | 23 | 24 | class Solution(object): 25 | def inorderTraversal(self, root): 26 | """ 27 | :type root: TreeNode 28 | :rtype: List[int] 29 | """ 30 | result = [] 31 | stack = [] 32 | p = root 33 | while p or stack: 34 | # Save the nodes which have left child 35 | while p: 36 | stack.append(p) 37 | p = p.left 38 | if stack: 39 | p = stack.pop() 40 | # Visit the middle node 41 | result.append(p.val) 42 | # Visit the right subtree 43 | p = p.right 44 | return result 45 | 46 | 47 | if __name__ == "__main__": 48 | n1 = TreeNode(1) 49 | n2 = TreeNode(2) 50 | n3 = TreeNode(3) 51 | n1.right = n2 52 | n2.left = n3 53 | assert Solution().inorderTraversal(n1) == [1, 3, 2] -------------------------------------------------------------------------------- /python/095 Unique Binary Search Trees II.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given n, generate all structurally unique BST's (binary search trees) that store values 1...n. 3 | 4 | For example, 5 | Given n = 3, your program should return all 5 unique BST's shown below. 6 | 7 | 1 3 3 2 1 8 | \ / / / \ \ 9 | 3 2 1 1 3 2 10 | / / \ \ 11 | 2 1 2 3 12 | ''' 13 | 14 | # Definition for a binary tree node. 15 | class TreeNode(object): 16 | def __init__(self, x): 17 | self.val = x 18 | self.left = None 19 | self.right = None 20 | 21 | 22 | class Solution(object): 23 | def generateTrees(self, n): 24 | """ 25 | :type n: int 26 | :rtype: List[TreeNode] 27 | """ 28 | if n == 0: 29 | return [] 30 | self.cache = {} 31 | return self._generateTrees(1, n) 32 | 33 | def _generateTrees(self, start, end): 34 | if (start, end) not in self.cache: 35 | roots = [] 36 | for root in range(start, end + 1): 37 | for left in self._generateTrees(start, root - 1): 38 | for right in self._generateTrees(root + 1, end): 39 | node = TreeNode(root) 40 | node.left = left 41 | node.right = right 42 | roots.append(node) 43 | self.cache[(start, end)] = roots 44 | return self.cache[(start, end)] or [None] 45 | 46 | 47 | if __name__ == "__main__": 48 | None -------------------------------------------------------------------------------- /python/096 Unique Binary Search Trees.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given n, how many structurally unique BST's (binary search trees) that store values 1...n? 3 | 4 | For example, 5 | Given n = 3, there are a total of 5 unique BST's. 6 | 7 | 1 3 3 2 1 8 | \ / / / \ \ 9 | 3 2 1 1 3 2 10 | / / \ \ 11 | 2 1 2 3 12 | ''' 13 | 14 | class Solution(object): 15 | def numTrees(self, n): 16 | """ 17 | :type n: int 18 | :rtype: int 19 | """ 20 | dp = [1 for __ in range(n + 1)] 21 | for i in range(2, n + 1): 22 | s = 0 23 | for j in range(i): 24 | s += dp[j] * dp[i - 1 - j] 25 | dp[i] = s 26 | return dp[-1] 27 | 28 | 29 | if __name__ == "__main__": 30 | assert Solution().numTrees(5) == 42 -------------------------------------------------------------------------------- /python/097 Interleaving String.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2. 3 | 4 | For example, 5 | Given: 6 | s1 = "aabcc", 7 | s2 = "dbbca", 8 | 9 | When s3 = "aadbbcbcac", return true. 10 | When s3 = "aadbbbaccc", return false. 11 | ''' 12 | 13 | class Solution(object): 14 | def isInterleave(self, s1, s2, s3): 15 | """ 16 | :type s1: str 17 | :type s2: str 18 | :type s3: str 19 | :rtype: bool 20 | """ 21 | m = len(s1) 22 | n = len(s2) 23 | l = len(s3) 24 | if m + n != l: 25 | return False 26 | dp = [True for __ in range(m + 1)] 27 | for i in range(m): 28 | dp[i + 1] = dp[i] and s1[i] == s3[i] 29 | for j in range(n): 30 | dp[0] = dp[0] and s2[j] == s3[j] 31 | for i in range(m): 32 | dp[i + 1] = (dp[i] and s1[i] == s3[i + j + 1]) or (dp[i + 1] and s2[j] == s3[i + j + 1]) 33 | return dp[m] 34 | 35 | 36 | if __name__ == "__main__": 37 | assert Solution().isInterleave("aabcc", "dbbca", "aadbbcbcac") == True 38 | assert Solution().isInterleave("aabcc", "dbbca", "aadbbbaccc") == False -------------------------------------------------------------------------------- /python/098 Validate Binary Search Tree.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a binary tree, determine if it is a valid binary search tree (BST). 3 | 4 | Assume a BST is defined as follows: 5 | 6 | The left subtree of a node contains only nodes with keys less than the node's key. 7 | The right subtree of a node contains only nodes with keys greater than the node's key. 8 | Both the left and right subtrees must also be binary search trees. 9 | ''' 10 | 11 | # Definition for a binary tree node. 12 | class TreeNode(object): 13 | def __init__(self, x): 14 | self.val = x 15 | self.left = None 16 | self.right = None 17 | 18 | 19 | class Solution(object): 20 | def isValidBST(self, root): 21 | """ 22 | :type root: TreeNode 23 | :rtype: bool 24 | """ 25 | stack = [] 26 | curr = root 27 | prev = None 28 | while curr or stack: 29 | while curr: 30 | stack.append(curr) 31 | curr = curr.left 32 | 33 | if stack: 34 | curr = stack.pop() 35 | if prev and curr.val <= prev.val: 36 | return False 37 | prev = curr 38 | curr = curr.right 39 | return True 40 | 41 | 42 | if __name__ == "__main__": 43 | None -------------------------------------------------------------------------------- /python/099 Recover Binary Search Tree.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Two elements of a binary search tree (BST) are swapped by mistake. 3 | 4 | Recover the tree without changing its structure. 5 | 6 | Note: 7 | A solution using O(n) space is pretty straight forward. Could you devise a constant space solution? 8 | ''' 9 | 10 | # Definition for a binary tree node. 11 | class TreeNode(object): 12 | def __init__(self, x): 13 | self.val = x 14 | self.left = None 15 | self.right = None 16 | 17 | 18 | class Solution(object): 19 | def __init__(self): 20 | self.node1 = None 21 | self.node2 = None 22 | self.pre = None 23 | 24 | def recoverTree(self, root): 25 | """ 26 | :type root: TreeNode 27 | :rtype: void Do not return anything, modify root in-place instead. 28 | """ 29 | self.__scan(root) 30 | self.node1.val, self.node2.val = self.node2.val, self.node1.val 31 | 32 | def __scan(self, root): 33 | if root is None: 34 | return 35 | self.__scan(root.left) 36 | if self.pre is not None: 37 | if root.val < self.pre.val: 38 | if self.node1 is None: 39 | self.node1 = self.pre 40 | self.node2 = root 41 | else: 42 | self.node2 = root 43 | self.pre = root 44 | self.__scan(root.right) 45 | 46 | 47 | if __name__ == "__main__": 48 | None -------------------------------------------------------------------------------- /python/100 Same Tree.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given two binary trees, write a function to check if they are equal or not. 3 | 4 | Two binary trees are considered equal if they are structurally identical and the nodes have the same value. 5 | ''' 6 | 7 | # Definition for a binary tree node. 8 | class TreeNode(object): 9 | def __init__(self, x): 10 | self.val = x 11 | self.left = None 12 | self.right = None 13 | 14 | 15 | class Solution(object): 16 | def isSameTree(self, p, q): 17 | """ 18 | :type p: TreeNode 19 | :type q: TreeNode 20 | :rtype: bool 21 | """ 22 | if not q and not p: 23 | return True 24 | elif not p or not q: 25 | return False 26 | elif p.val != q.val: 27 | return False 28 | else: 29 | return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right) 30 | 31 | 32 | if __name__ == "__main__": 33 | None -------------------------------------------------------------------------------- /python/102 Binary Tree Level Order Traversal.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level). 3 | 4 | For example: 5 | Given binary tree {3,9,20,#,#,15,7}, 6 | 3 7 | / \ 8 | 9 20 9 | / \ 10 | 15 7 11 | return its level order traversal as: 12 | [ 13 | [3], 14 | [9,20], 15 | [15,7] 16 | ] 17 | ''' 18 | 19 | # Definition for a binary tree node. 20 | class TreeNode(object): 21 | def __init__(self, x): 22 | self.val = x 23 | self.left = None 24 | self.right = None 25 | 26 | 27 | class Solution(object): 28 | def levelOrder(self, root): 29 | """ 30 | :type root: TreeNode 31 | :rtype: List[List[int]] 32 | """ 33 | result = [] 34 | if not root: 35 | return result 36 | curr_level = [root] 37 | while curr_level: 38 | level_result = [] 39 | next_level = [] 40 | for temp in curr_level: 41 | level_result.append(temp.val) 42 | if temp.left: 43 | next_level.append(temp.left) 44 | if temp.right: 45 | next_level.append(temp.right) 46 | result.append(level_result) 47 | curr_level = next_level 48 | return result 49 | 50 | 51 | if __name__ == "__main__": 52 | None -------------------------------------------------------------------------------- /python/104 Maximum Depth of Binary Tree.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a binary tree, find its maximum depth. 3 | 4 | The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. 5 | ''' 6 | 7 | # Definition for a binary tree node. 8 | class TreeNode(object): 9 | def __init__(self, x): 10 | self.val = x 11 | self.left = None 12 | self.right = None 13 | 14 | 15 | class Solution(object): 16 | def maxDepth(self, root): 17 | """ 18 | :type root: TreeNode 19 | :rtype: int 20 | """ 21 | if not root: 22 | return 0 23 | return max(self.maxDepth(root.left), self.maxDepth(root.right)) + 1 24 | 25 | 26 | if __name__ == "__main__": 27 | None -------------------------------------------------------------------------------- /python/106 Construct Binary Tree from Inorder and Postorder Traversal.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given inorder and postorder traversal of a tree, construct the binary tree. 3 | ''' 4 | 5 | # Definition for a binary tree node. 6 | class TreeNode(object): 7 | def __init__(self, x): 8 | self.val = x 9 | self.left = None 10 | self.right = None 11 | 12 | 13 | class Solution(object): 14 | def buildTree(self, inorder, postorder): 15 | """ 16 | :type inorder: List[int] 17 | :type postorder: List[int] 18 | :rtype: TreeNode 19 | """ 20 | self.postorder = postorder 21 | self.inorder = inorder 22 | return self._buildTree(0, len(inorder)) 23 | 24 | def _buildTree(self, start, end): 25 | if start < end: 26 | root = TreeNode(self.postorder.pop()) 27 | index = self.inorder.index(root.val) 28 | root.right = self._buildTree(index + 1, end) 29 | root.left = self._buildTree(start, index) 30 | return root 31 | 32 | 33 | if __name__ == "__main__": 34 | None -------------------------------------------------------------------------------- /python/107 Binary Tree Level Order Traversal II.py: -------------------------------------------------------------------------------- 1 | ''' 2 | 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). 3 | 4 | For example: 5 | Given binary tree {3,9,20,#,#,15,7}, 6 | 3 7 | / \ 8 | 9 20 9 | / \ 10 | 15 7 11 | return its bottom-up level order traversal as: 12 | [ 13 | [15,7], 14 | [9,20], 15 | [3] 16 | ] 17 | ''' 18 | 19 | # Definition for a binary tree node. 20 | class TreeNode(object): 21 | def __init__(self, x): 22 | self.val = x 23 | self.left = None 24 | self.right = None 25 | 26 | 27 | class Solution(object): 28 | def levelOrderBottom(self, root): 29 | """ 30 | :type root: TreeNode 31 | :rtype: List[List[int]] 32 | """ 33 | result = [] 34 | if not root: 35 | return result 36 | curr_level = [root] 37 | while curr_level: 38 | level_result = [] 39 | next_level = [] 40 | for temp in curr_level: 41 | level_result.append(temp.val) 42 | if temp.left: 43 | next_level.append(temp.left) 44 | if temp.right: 45 | next_level.append(temp.right) 46 | result.append(level_result) 47 | curr_level = next_level 48 | result.reverse() 49 | return result 50 | 51 | 52 | if __name__ == "__main__": 53 | None -------------------------------------------------------------------------------- /python/108 Convert Sorted Array to Binary Search Tree.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an array where elements are sorted in ascending order, convert it to a height balanced BST. 3 | ''' 4 | 5 | # Definition for a binary tree node. 6 | class TreeNode(object): 7 | def __init__(self, x): 8 | self.val = x 9 | self.left = None 10 | self.right = None 11 | 12 | 13 | class Solution(object): 14 | def sortedArrayToBST(self, nums): 15 | """ 16 | :type nums: List[int] 17 | :rtype: TreeNode 18 | """ 19 | return self._sortedArrayToBST(nums, 0, len(nums)) 20 | 21 | def _sortedArrayToBST(self, nums, left, right): 22 | if left == right: 23 | return None 24 | mid = (left + right) >> 1 25 | root = TreeNode(nums[mid]) 26 | root.left = self._sortedArrayToBST(nums, left, mid) 27 | root.right = self._sortedArrayToBST(nums, mid + 1, right) 28 | return root 29 | 30 | 31 | if __name__ == "__main__": 32 | None -------------------------------------------------------------------------------- /python/109 Convert Sorted List to Binary Search Tree.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST. 3 | ''' 4 | 5 | # Definition for singly-linked list. 6 | class ListNode(object): 7 | def __init__(self, x): 8 | self.val = x 9 | self.next = None 10 | 11 | 12 | # Definition for a binary tree node. 13 | class TreeNode(object): 14 | def __init__(self, x): 15 | self.val = x 16 | self.left = None 17 | self.right = None 18 | 19 | 20 | class Solution(object): 21 | def sortedListToBST(self, head): 22 | """ 23 | :type head: ListNode 24 | :rtype: TreeNode 25 | """ 26 | node, length = head, 0 27 | while node: 28 | node = node.next 29 | length += 1 30 | self.curr = head 31 | return self._sortedListToBST(0, length - 1) 32 | 33 | def _sortedListToBST(self, left, right): 34 | if left > right: 35 | return None 36 | mid = (left + right) // 2 37 | left = self._sortedListToBST(left, mid - 1) 38 | root = TreeNode(self.curr.val) 39 | root.left = left 40 | self.curr = self.curr.next 41 | root.right = self._sortedListToBST(mid + 1, right) 42 | return root 43 | 44 | 45 | if __name__ == "__main__": 46 | None -------------------------------------------------------------------------------- /python/110 Balanced Binary Tree.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a binary tree, determine if it is height-balanced. 3 | 4 | For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1. 5 | ''' 6 | 7 | # Definition for a binary tree node. 8 | class TreeNode(object): 9 | def __init__(self, x): 10 | self.val = x 11 | self.left = None 12 | self.right = None 13 | 14 | 15 | class Solution(object): 16 | def isBalanced(self, root): 17 | """ 18 | :type root: TreeNode 19 | :rtype: bool 20 | """ 21 | return self._isBalanced(root) >= 0 22 | 23 | def _isBalanced(self, root): 24 | if not root: 25 | return 0 26 | left, right = self._isBalanced(root.left), self._isBalanced(root.right) 27 | if left >= 0 and right >= 0 and abs(left - right) <= 1: 28 | return 1 + max(left, right) 29 | else: 30 | return -1 31 | 32 | 33 | if __name__ == "__main__": 34 | None -------------------------------------------------------------------------------- /python/111 Minimum Depth of Binary Tree.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a binary tree, find its minimum depth. 3 | 4 | The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. 5 | ''' 6 | 7 | # Definition for a binary tree node. 8 | class TreeNode(object): 9 | def __init__(self, x): 10 | self.val = x 11 | self.left = None 12 | self.right = None 13 | 14 | 15 | class Solution(object): 16 | def minDepth(self, root): 17 | """ 18 | :type root: TreeNode 19 | :rtype: int 20 | """ 21 | if root is None: 22 | return 0 23 | depth, curr_level = 0, [root] 24 | while curr_level: 25 | depth += 1 26 | next_level = [] 27 | for n in curr_level: 28 | left, right = n.left, n.right 29 | if left is None and right is None: 30 | return depth 31 | if left: 32 | next_level.append(left) 33 | if right: 34 | next_level.append(right) 35 | curr_level = next_level 36 | return depth 37 | 38 | 39 | if __name__ == "__main__": 40 | None -------------------------------------------------------------------------------- /python/112 Path Sum.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum. 3 | 4 | For example: 5 | Given the below binary tree and sum = 22, 6 | 5 7 | / \ 8 | 4 8 9 | / / \ 10 | 11 13 4 11 | / \ \ 12 | 7 2 1 13 | return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22. 14 | ''' 15 | 16 | # Definition for a binary tree node. 17 | class TreeNode(object): 18 | def __init__(self, x): 19 | self.val = x 20 | self.left = None 21 | self.right = None 22 | 23 | 24 | class Solution(object): 25 | def hasPathSum(self, root, sum): 26 | """ 27 | :type root: TreeNode 28 | :type sum: int 29 | :rtype: bool 30 | """ 31 | if not root: 32 | return False 33 | sum -= root.val 34 | if sum == 0 and root.left is None and root.right is None: 35 | return True 36 | return self.hasPathSum(root.left, sum) or self.hasPathSum(root.right, sum) 37 | 38 | 39 | if __name__ == "__main__": 40 | None -------------------------------------------------------------------------------- /python/113 Path Sum II.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum. 3 | 4 | For example: 5 | Given the below binary tree and sum = 22, 6 | 5 7 | / \ 8 | 4 8 9 | / / \ 10 | 11 13 4 11 | / \ / \ 12 | 7 2 5 1 13 | return 14 | [ 15 | [5,4,11,2], 16 | [5,8,4,5] 17 | ] 18 | ''' 19 | 20 | # Definition for a binary tree node. 21 | class TreeNode(object): 22 | def __init__(self, x): 23 | self.val = x 24 | self.left = None 25 | self.right = None 26 | 27 | 28 | class Solution(object): 29 | def pathSum(self, root, sum): 30 | """ 31 | :type root: TreeNode 32 | :type sum: int 33 | :rtype: List[List[int]] 34 | """ 35 | result = [] 36 | self._pathSum(root, sum, [], result) 37 | return result 38 | 39 | def _pathSum(self, root, sum, curr, result): 40 | if not root: 41 | return 42 | sum -= root.val 43 | if sum == 0 and root.left is None and root.right is None: 44 | result.append(curr + [root.val]) 45 | if root.left: 46 | self._pathSum(root.left, sum, curr + [root.val], result) 47 | if root.right: 48 | self._pathSum(root.right, sum, curr + [root.val], result) 49 | 50 | 51 | if __name__ == "__main__": 52 | None -------------------------------------------------------------------------------- /python/114 Flatten Binary Tree to Linked List.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a binary tree, flatten it to a linked list in-place. 3 | 4 | For example, 5 | Given 6 | 7 | 1 8 | / \ 9 | 2 5 10 | / \ \ 11 | 3 4 6 12 | The flattened tree should look like: 13 | 1 14 | \ 15 | 2 16 | \ 17 | 3 18 | \ 19 | 4 20 | \ 21 | 5 22 | \ 23 | 6 24 | 25 | Hints: 26 | If you notice carefully in the flattened tree, each node's right child points to the next node of a pre-order traversal. 27 | ''' 28 | 29 | # Definition for a binary tree node. 30 | class TreeNode(object): 31 | def __init__(self, x): 32 | self.val = x 33 | self.left = None 34 | self.right = None 35 | 36 | 37 | class Solution(object): 38 | def flatten(self, root): 39 | """ 40 | :type root: TreeNode 41 | :rtype: void Do not return anything, modify root in-place instead. 42 | """ 43 | stack = [] 44 | while root: 45 | if root.left: 46 | if root.right: 47 | stack.append(root.right) 48 | root.right, root.left = root.left, None 49 | if not root.right and stack: 50 | root.right = stack.pop() 51 | root = root.right 52 | 53 | 54 | if __name__ == "__main__": 55 | None -------------------------------------------------------------------------------- /python/115 Distinct Subsequences.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a string S and a string T, count the number of distinct subsequences of T in S. 3 | 4 | A subsequence of a string is a new string which is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, "ACE" is a subsequence of "ABCDE" while "AEC" is not). 5 | 6 | Here is an example: 7 | S = "rabbbit", T = "rabbit" 8 | 9 | Return 3. 10 | ''' 11 | 12 | class Solution(object): 13 | def numDistinct(self, s, t): 14 | """ 15 | :type s: str 16 | :type t: str 17 | :rtype: int 18 | """ 19 | m = len(s) 20 | n = len(t) 21 | dp = [0 for __ in range(n + 1)] 22 | dp[0] = 1 23 | for i in range(m): 24 | for j in range(n - 1, -1, -1): 25 | if t[j] == s[i]: 26 | dp[j + 1] += dp[j] 27 | return dp[-1] 28 | 29 | 30 | if __name__ == "__main__": 31 | assert Solution().numDistinct("rabbbit", "rabbit") == 3 -------------------------------------------------------------------------------- /python/117 Populating Next Right Pointers in Each Node II.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Follow up for problem "Populating Next Right Pointers in Each Node". 3 | 4 | What if the given tree could be any binary tree? Would your previous solution still work? 5 | 6 | Note: 7 | 8 | You may only use constant extra space. 9 | For example, 10 | Given the following binary tree, 11 | 1 12 | / \ 13 | 2 3 14 | / \ \ 15 | 4 5 7 16 | After calling your function, the tree should look like: 17 | 1 -> NULL 18 | / \ 19 | 2 -> 3 -> NULL 20 | / \ \ 21 | 4-> 5 -> 7 -> NULL 22 | ''' 23 | 24 | # Definition for binary tree with next pointer. 25 | class TreeLinkNode(object): 26 | def __init__(self, x): 27 | self.val = x 28 | self.left = None 29 | self.right = None 30 | self.next = None 31 | 32 | 33 | class Solution(object): 34 | def connect(self, root): 35 | """ 36 | :type root: TreeLinkNode 37 | :rtype: nothing 38 | """ 39 | dummy = TreeLinkNode(-1) 40 | node = dummy 41 | while root: 42 | while root: 43 | node.next = root.left 44 | node = node.next or node 45 | node.next = root.right 46 | node = node.next or node 47 | root = root.next 48 | root, node = dummy.next, dummy 49 | 50 | 51 | if __name__ == "__main__": 52 | None -------------------------------------------------------------------------------- /python/118 Pascal's Triangle.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given numRows, generate the first numRows of Pascal's triangle. 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 | class Solution(object): 17 | def generate(self, numRows): 18 | """ 19 | :type numRows: int 20 | :rtype: List[List[int]] 21 | """ 22 | if not numRows: 23 | return [] 24 | result = [[1]] 25 | while numRows > 1: 26 | result.append([1] + [a + b for a, b in zip(result[-1][:-1], result[-1][1:])] + [1]) 27 | numRows -= 1 28 | return result 29 | 30 | 31 | if __name__ == "__main__": 32 | assert Solution().generate(4) == [[1], [1, 1], [1, 2, 1], [1, 3, 3, 1]] -------------------------------------------------------------------------------- /python/119 Pascal's Triangle II.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an index k, return the kth row of the Pascal's triangle. 3 | 4 | For example, given k = 3, 5 | Return [1,3,3,1]. 6 | 7 | Note: 8 | Could you optimize your algorithm to use only O(k) extra space? 9 | ''' 10 | 11 | class Solution(object): 12 | def getRow(self, rowIndex): 13 | """ 14 | :type rowIndex: int 15 | :rtype: List[int] 16 | """ 17 | result = [1] * (rowIndex + 1) 18 | for i in range(2, rowIndex + 1): 19 | for j in range(1, i): 20 | result[i - j] += result[i - j - 1] 21 | return result 22 | 23 | 24 | if __name__ == "__main__": 25 | assert Solution().getRow(3) == [1, 3, 3, 1] -------------------------------------------------------------------------------- /python/120 Triangle.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below. 3 | 4 | For example, given the following triangle 5 | [ 6 | [2], 7 | [3,4], 8 | [6,5,7], 9 | [4,1,8,3] 10 | ] 11 | The minimum path sum from top to bottom is 11 (i.e., 2 + 3 + 5 + 1 = 11). 12 | 13 | Note: 14 | Bonus point if you are able to do this using only O(n) extra space, where n is the total number of rows in the triangle. 15 | ''' 16 | 17 | class Solution(object): 18 | def minimumTotal(self, triangle): 19 | """ 20 | :type triangle: List[List[int]] 21 | :rtype: int 22 | """ 23 | n = len(triangle) 24 | dp = triangle[-1] 25 | for i in range(n - 2, -1, -1): 26 | for j in range(i + 1): 27 | dp[j] = triangle[i][j] + min(dp[j], dp[j + 1]) 28 | return dp[0] 29 | 30 | 31 | if __name__ == "__main__": 32 | assert Solution().minimumTotal([ 33 | [2], 34 | [3, 4], 35 | [6, 5, 7], 36 | [4, 1, 8, 3] 37 | ]) == 11 -------------------------------------------------------------------------------- /python/121 Best Time to Buy and Sell Stock.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Say you have an array for which the ith element is the price of a given stock on day i. 3 | 4 | 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. 5 | ''' 6 | 7 | class Solution(object): 8 | def maxProfit(self, prices): 9 | """ 10 | :type prices: List[int] 11 | :rtype: int 12 | """ 13 | if len(prices) < 2: 14 | return 0 15 | min_price = prices[0] 16 | max_profit = 0 17 | for price in prices: 18 | if price < min_price: 19 | min_price = price 20 | if price - min_price > max_profit: 21 | max_profit = price - min_price 22 | return max_profit 23 | 24 | 25 | if __name__ == "__main__": 26 | assert Solution().maxProfit([2, 4, 6, 1, 3, 8, 3]) == 7 -------------------------------------------------------------------------------- /python/122 Best Time to Buy and Sell Stock II.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Say you have an array for which the ith element is the price of a given stock on day i. 3 | 4 | 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). 5 | ''' 6 | 7 | class Solution(object): 8 | def maxProfit(self, prices): 9 | """ 10 | :type prices: List[int] 11 | :rtype: int 12 | """ 13 | if not prices: 14 | return 0 15 | low = high = prices[0] 16 | profit = 0 17 | for i in range(1, len(prices)): 18 | if prices[i] >= prices[i - 1]: 19 | high = prices[i] 20 | else: 21 | profit += high - low 22 | low = high = prices[i] 23 | profit += high - low 24 | return profit 25 | 26 | 27 | if __name__ == "__main__": 28 | assert Solution().maxProfit([2, 4, 6, 1, 3, 8, 3]) == 11 -------------------------------------------------------------------------------- /python/123 Best Time to Buy and Sell Stock III.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Say you have an array for which the ith element is the price of a given stock on day i. 3 | 4 | Design an algorithm to find the maximum profit. You may complete at most two transactions. 5 | 6 | Note: 7 | You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again). 8 | ''' 9 | 10 | class Solution(object): 11 | def maxProfit(self, prices): 12 | """ 13 | :type prices: List[int] 14 | :rtype: int 15 | """ 16 | total_max_profit = 0 17 | n = len(prices) 18 | first_profits = [0] * n 19 | min_price = float('inf') 20 | 21 | for i in range(n): 22 | min_price = min(min_price, prices[i]) 23 | total_max_profit = max(total_max_profit, prices[i] - min_price) 24 | first_profits[i] = total_max_profit 25 | 26 | max_profit = 0 27 | max_price = float('-inf') 28 | for i in range(n - 1, 0, -1): 29 | max_price = max(max_price, prices[i]) 30 | max_profit = max(max_profit, max_price - prices[i]) 31 | total_max_profit = max(total_max_profit, max_profit + first_profits[i - 1]) 32 | return total_max_profit 33 | 34 | 35 | if __name__ == "__main__": 36 | assert Solution().maxProfit([2, 4, 6, 1, 3, 8, 3]) == 11 37 | assert Solution().maxProfit([1, 2]) == 1 -------------------------------------------------------------------------------- /python/124 Binary Tree Maximum Path Sum.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a binary tree, find the maximum path sum. 3 | 4 | For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path does not need to go through the root. 5 | 6 | For example: 7 | Given the below binary tree, 8 | 9 | 1 10 | / \ 11 | 2 3 12 | Return 6. 13 | ''' 14 | 15 | # Definition for a binary tree node. 16 | class TreeNode(object): 17 | def __init__(self, x): 18 | self.val = x 19 | self.left = None 20 | self.right = None 21 | 22 | 23 | class Solution(object): 24 | def maxPathSum(self, root): 25 | """ 26 | :type root: TreeNode 27 | :rtype: int 28 | """ 29 | self.maxSum = float('-inf') 30 | self._maxPathSum(root) 31 | return self.maxSum 32 | 33 | def _maxPathSum(self, root): 34 | if root is None: 35 | return 0 36 | left = self._maxPathSum(root.left) 37 | right = self._maxPathSum(root.right) 38 | left = left if left > 0 else 0 39 | right = right if right > 0 else 0 40 | self.maxSum = max(self.maxSum, root.val + left + right) 41 | return max(left, right) + root.val -------------------------------------------------------------------------------- /python/125 Valid Palindrome.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases. 3 | 4 | For example, 5 | "A man, a plan, a canal: Panama" is a palindrome. 6 | "race a car" is not a palindrome. 7 | 8 | Note: 9 | Have you consider that the string might be empty? This is a good question to ask during an interview. 10 | 11 | For the purpose of this problem, we define empty string as valid palindrome. 12 | ''' 13 | 14 | class Solution(object): 15 | def isPalindrome(self, s): 16 | """ 17 | :type s: str 18 | :rtype: bool 19 | """ 20 | alphanumericS = [c for c in s.lower() if c.isalnum()] 21 | return alphanumericS == alphanumericS[::-1] 22 | 23 | 24 | if __name__ == "__main__": 25 | assert Solution().isPalindrome("A man, a plan, a canal: Panama") == True 26 | assert Solution().isPalindrome("race a car") == False -------------------------------------------------------------------------------- /python/128 Longest Consecutive Sequence.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an unsorted array of integers, find the length of the longest consecutive elements sequence. 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 | Your algorithm should run in O(n) complexity. 9 | ''' 10 | 11 | class Solution(object): 12 | def longestConsecutive(self, nums): 13 | """ 14 | :type nums: List[int] 15 | :rtype: int 16 | """ 17 | numset, maxlen = set(nums), 0 18 | for n in set(nums): 19 | currlen, tmp = 1, n + 1 20 | while tmp in numset: 21 | currlen += 1 22 | numset.discard(tmp) 23 | tmp += 1 24 | tmp = n - 1 25 | while tmp in numset: 26 | currlen += 1 27 | numset.discard(tmp) 28 | tmp -= 1 29 | maxlen = max(maxlen, currlen) 30 | return maxlen 31 | 32 | 33 | if __name__ == "__main__": 34 | assert Solution().longestConsecutive([100, 4, 200, 1, 3, 2]) == 4 -------------------------------------------------------------------------------- /python/129 Sum Root to Leaf Numbers.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number. 3 | 4 | An example is the root-to-leaf path 1->2->3 which represents the number 123. 5 | 6 | Find the total sum of all root-to-leaf numbers. 7 | 8 | For example, 9 | 10 | 1 11 | / \ 12 | 2 3 13 | The root-to-leaf path 1->2 represents the number 12. 14 | The root-to-leaf path 1->3 represents the number 13. 15 | 16 | Return the sum = 12 + 13 = 25. 17 | ''' 18 | 19 | # Definition for a binary tree node. 20 | class TreeNode(object): 21 | def __init__(self, x): 22 | self.val = x 23 | self.left = None 24 | self.right = None 25 | 26 | 27 | class Solution(object): 28 | def sumNumbers(self, root): 29 | """ 30 | :type root: TreeNode 31 | :rtype: int 32 | """ 33 | return self._sumNumbers(root, 0) 34 | 35 | def _sumNumbers(self, root, s): 36 | if root is None: 37 | return 0 38 | s = s * 10 + root.val 39 | return sum([self._sumNumbers(r, s) for r in (root.left, root.right)]) or s 40 | 41 | if __name__ == "__main__": 42 | None -------------------------------------------------------------------------------- /python/131 Palindrome Partitioning.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a string s, partition s such that every substring of the partition is a palindrome. 3 | 4 | Return all possible palindrome partitioning of s. 5 | 6 | For example, given s = "aab", 7 | Return 8 | 9 | [ 10 | ["aa","b"], 11 | ["a","a","b"] 12 | ] 13 | ''' 14 | 15 | class Solution(object): 16 | def partition(self, s): 17 | """ 18 | :type s: str 19 | :rtype: List[List[str]] 20 | """ 21 | if not s: 22 | return [[]] 23 | result = [] 24 | for i in range(len(s)): 25 | if self.isPalindrome(s[:i + 1]): 26 | for r in self.partition(s[i + 1:]): 27 | result.append([s[:i + 1]] + r) 28 | return result 29 | 30 | def isPalindrome(self, s): 31 | return s == s[::-1] 32 | 33 | 34 | if __name__ == "__main__": 35 | assert Solution().partition("aab") == [ 36 | ["a", "a", "b"], 37 | ["aa", "b"] 38 | ] -------------------------------------------------------------------------------- /python/132 Palindrome Partitioning II.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a string s, partition s such that every substring of the partition is a palindrome. 3 | 4 | Return the minimum cuts needed for a palindrome partitioning of s. 5 | 6 | For example, given s = "aab", 7 | Return 1 since the palindrome partitioning ["aa","b"] could be produced using 1 cut. 8 | ''' 9 | 10 | class Solution(object): 11 | def minCut(self, s): 12 | """ 13 | :type s: str 14 | :rtype: List[List[str]] 15 | """ 16 | n = len(s) 17 | dp = [0 for __ in range(n)] 18 | isPal = [[False for __ in range(n)] for __ in range(n)] 19 | for i in range(n): 20 | m = i 21 | for j in range(i + 1): 22 | if s[j] == s[i] and (j + 1 > i - 1 or isPal[j + 1][i - 1]): 23 | isPal[j][i] = True 24 | m = 0 if j == 0 else min(m, dp[j - 1] + 1) 25 | dp[i] = m 26 | return dp[-1] 27 | 28 | 29 | if __name__ == "__main__": 30 | assert Solution().minCut("aab") == 1 -------------------------------------------------------------------------------- /python/134 Gas Station.py: -------------------------------------------------------------------------------- 1 | ''' 2 | There are N gas stations along a circular route, where the amount of gas at station i is gas[i]. 3 | 4 | You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from station i to its next station (i+1). You begin the journey with an empty tank at one of the gas stations. 5 | 6 | Return the starting gas station's index if you can travel around the circuit once, otherwise return -1. 7 | 8 | Note: 9 | The solution is guaranteed to be unique. 10 | ''' 11 | 12 | class Solution(object): 13 | def canCompleteCircuit(self, gas, cost): 14 | """ 15 | :type gas: List[int] 16 | :type cost: List[int] 17 | :rtype: int 18 | """ 19 | if sum(gas) < sum(cost): 20 | return -1 21 | min_sum, min_index, total = 0, 0, 0 22 | for i in range(len(gas)): 23 | total += gas[i] - cost[i] 24 | if min_sum > total: 25 | min_sum, min_index = total, i + 1 26 | return -1 if total < 0 else min_index 27 | 28 | 29 | if __name__ == "__main__": 30 | assert Solution().canCompleteCircuit([5], [4]) == 0 31 | assert Solution().canCompleteCircuit([5, 1, 2, 3, 4], [4, 4, 1, 5, 1]) == 4 -------------------------------------------------------------------------------- /python/135 Candy.py: -------------------------------------------------------------------------------- 1 | ''' 2 | There are N children standing in a line. Each child is assigned a rating value. 3 | 4 | You are giving candies to these children subjected to the following requirements: 5 | 6 | Each child must have at least one candy. 7 | Children with a higher rating get more candies than their neighbors. 8 | What is the minimum candies you must give? 9 | ''' 10 | 11 | class Solution(object): 12 | def candy(self, ratings): 13 | """ 14 | :type ratings: List[int] 15 | :rtype: int 16 | """ 17 | n = len(ratings) 18 | candy = [1] * n 19 | for i in range(1, n): 20 | if ratings[i] > ratings[i - 1]: 21 | candy[i] = candy[i - 1] + 1 22 | for i in range(n - 2, -1, -1): 23 | if ratings[i] > ratings[i + 1]: 24 | candy[i] = max(candy[i], candy[i + 1] + 1) 25 | return sum(candy) 26 | 27 | 28 | if __name__ == "__main__": 29 | assert Solution().candy([1, 2, 3, 7, 4, 3, 2, 1]) == 21 -------------------------------------------------------------------------------- /python/136 Single Number.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an array of integers, every element appears twice except for one. Find that single one. 3 | 4 | Note: 5 | Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? 6 | ''' 7 | 8 | class Solution(object): 9 | def singleNumber(self, nums): 10 | """ 11 | :type nums: List[int] 12 | :rtype: int 13 | """ 14 | result = nums[0] 15 | for i in nums[1:]: 16 | result ^= i 17 | return result 18 | 19 | 20 | if __name__ == "__main__": 21 | assert Solution().singleNumber([1, 2, 3, 4, 3, 2, 1]) == 4 -------------------------------------------------------------------------------- /python/137 Single Number II.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an array of integers, every element appears three times except for one. Find that single one. 3 | 4 | Note: 5 | Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? 6 | ''' 7 | 8 | class Solution(object): 9 | def singleNumber(self, nums): 10 | """ 11 | :type nums: List[int] 12 | :rtype: int 13 | """ 14 | one, two, three = 0, 0, 0 15 | for num in nums: 16 | # calculate the count of the each bit 17 | three = two & num 18 | two = two | one & num 19 | one = one | num 20 | # clear the count for the bit which has achieved three 21 | one = one & ~three 22 | two = two & ~three 23 | return one 24 | 25 | def singleNumber_normal(self, nums): 26 | result = 0 27 | for i in range(32): 28 | count = 0 29 | for num in nums: 30 | count += (num >> i) & 1 31 | rem = count % 3 32 | # deal with the negative situation 33 | if i == 31 and rem: 34 | result -= 1 << 31 35 | else: 36 | result |= rem << i 37 | return result 38 | 39 | 40 | if __name__ == "__main__": 41 | assert Solution().singleNumber([1, 1, 1, 2, 3, 3, 3]) == 2 42 | assert Solution().singleNumber([-2, -2, 1, 1, -3, 1, -3, -3, -4, -2]) == -4 43 | assert Solution().singleNumber_normal([1, 1, 1, 2, 3, 3, 3]) == 2 44 | assert Solution().singleNumber_normal([-2, -2, 1, 1, -3, 1, -3, -3, -4, -2]) == -4 -------------------------------------------------------------------------------- /python/138 Copy List with Random Pointer.py: -------------------------------------------------------------------------------- 1 | ''' 2 | A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null. 3 | 4 | Return a deep copy of the list. 5 | ''' 6 | 7 | # Definition for singly-linked list with a random pointer. 8 | class RandomListNode(object): 9 | def __init__(self, x): 10 | self.label = x 11 | self.next = None 12 | self.random = None 13 | 14 | 15 | class Solution(object): 16 | def copyRandomList(self, head): 17 | """ 18 | :type head: RandomListNode 19 | :rtype: RandomListNode 20 | """ 21 | if not head: 22 | return None 23 | visited = dict() 24 | node = head 25 | while node: 26 | visited[node] = RandomListNode(node.label) 27 | node = node.next 28 | 29 | visited[None] = None 30 | node = head 31 | while node: 32 | visited[node].next = visited[node.next] 33 | visited[node].random = visited[node.random] 34 | node = node.next 35 | return visited[head] 36 | 37 | 38 | if __name__ == "__main__": 39 | None -------------------------------------------------------------------------------- /python/139 Word Break.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separated sequence of one or more dictionary words. 3 | 4 | For example, given 5 | s = "leetcode", 6 | dict = ["leet", "code"]. 7 | 8 | Return true because "leetcode" can be segmented as "leet code". 9 | ''' 10 | 11 | class Solution(object): 12 | def wordBreak(self, s, wordDict): 13 | """ 14 | :type s: str 15 | :type wordDict: Set[str] 16 | :rtype: bool 17 | """ 18 | n = len(s) 19 | dp = [False] * (n + 1) 20 | dp[0] = True 21 | for i in range(n): 22 | for j in range(i, -1, -1): 23 | if dp[j] and s[j:i + 1] in wordDict: 24 | dp[i + 1] = True 25 | break 26 | return dp[n] 27 | 28 | 29 | if __name__ == "__main__": 30 | assert Solution().wordBreak("leetcode", {"leet", "code"}) == True -------------------------------------------------------------------------------- /python/140 Word Break II.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a string s and a dictionary of words dict, add spaces in s to construct a sentence where each word is a valid dictionary word. 3 | 4 | Return all such possible sentences. 5 | 6 | For example, given 7 | s = "catsanddog", 8 | dict = ["cat", "cats", "and", "sand", "dog"]. 9 | 10 | A solution is ["cats and dog", "cat sand dog"]. 11 | ''' 12 | 13 | import collections 14 | 15 | 16 | class Solution(object): 17 | def wordBreak(self, s, wordDict): 18 | """ 19 | :type s: str 20 | :type wordDict: Set[str] 21 | :rtype: List[str] 22 | """ 23 | dic = collections.defaultdict(list) 24 | 25 | def dfs(s): 26 | if not s: 27 | return [None] 28 | if s in dic: 29 | return dic[s] 30 | res = [] 31 | for word in wordDict: 32 | n = len(word) 33 | if s[:n] == word: 34 | for r in dfs(s[n:]): 35 | if r: 36 | res.append(word + " " + r) 37 | else: 38 | res.append(word) 39 | dic[s] = res 40 | return res 41 | 42 | return dfs(s) 43 | 44 | 45 | if __name__ == "__main__": 46 | assert Solution().wordBreak("catsanddog", {"cat", "cats", "and", "sand", "dog"}) == ['cat sand dog', 'cats and dog'] -------------------------------------------------------------------------------- /python/141 Linked List Cycle.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a linked list, determine if it has a cycle in it. 3 | 4 | Follow up: 5 | Can you solve it without using extra space? 6 | ''' 7 | 8 | # Definition for singly-linked list. 9 | class ListNode(object): 10 | def __init__(self, x): 11 | self.val = x 12 | self.next = None 13 | 14 | 15 | class Solution(object): 16 | def hasCycle(self, head): 17 | """ 18 | :type head: ListNode 19 | :rtype: bool 20 | """ 21 | slow = fast = head 22 | while fast and fast.next: 23 | slow = slow.next 24 | fast = fast.next.next 25 | if slow == fast: 26 | return True 27 | return False 28 | 29 | 30 | if __name__ == "__main__": 31 | None -------------------------------------------------------------------------------- /python/142 Linked List Cycle II.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a linked list, return the node where the cycle begins. If there is no cycle, return null. 3 | 4 | Note: Do not modify the linked list. 5 | 6 | Follow up: 7 | Can you solve it without using extra space? 8 | ''' 9 | 10 | # Definition for singly-linked list. 11 | class ListNode(object): 12 | def __init__(self, x): 13 | self.val = x 14 | self.next = None 15 | 16 | 17 | class Solution(object): 18 | def detectCycle(self, head): 19 | """ 20 | :type head: ListNode 21 | :rtype: ListNode 22 | """ 23 | slow = fast = head 24 | while fast and fast.next: 25 | slow = slow.next 26 | fast = fast.next.next 27 | if slow == fast: 28 | node = head 29 | while node != slow: 30 | node = node.next 31 | slow = slow.next 32 | return node 33 | return None 34 | 35 | 36 | if __name__ == "__main__": 37 | None -------------------------------------------------------------------------------- /python/143 Reorder List.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a singly linked list L: L0→L1→…→Ln-1→Ln, 3 | reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→… 4 | 5 | You must do this in-place without altering the nodes' values. 6 | 7 | For example, 8 | Given {1,2,3,4}, reorder it to {1,4,2,3}. 9 | ''' 10 | 11 | # Definition for singly-linked list. 12 | class ListNode(object): 13 | def __init__(self, x): 14 | self.val = x 15 | self.next = None 16 | 17 | 18 | class Solution(object): 19 | def reorderList(self, head): 20 | """ 21 | :type head: ListNode 22 | :rtype: void Do not return anything, modify head in-place instead. 23 | """ 24 | if not head: 25 | return 26 | # split 27 | fast = slow = head 28 | while fast and fast.next: 29 | slow = slow.next 30 | fast = fast.next.next 31 | head1, head2 = head, slow.next 32 | slow.next = None 33 | # reverse 34 | cur, pre = head2, None 35 | while cur: 36 | nex = cur.next 37 | cur.next = pre 38 | pre = cur 39 | cur = nex 40 | # merge 41 | cur1, cur2 = head1, pre 42 | while cur2: 43 | nex1, nex2 = cur1.next, cur2.next 44 | cur1.next = cur2 45 | cur2.next = nex1 46 | cur1, cur2 = nex1, nex2 47 | 48 | 49 | if __name__ == "__main__": 50 | None -------------------------------------------------------------------------------- /python/144 Binary Tree Preorder Traversal.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a binary tree, return the preorder traversal of its nodes' values. 3 | 4 | For example: 5 | Given binary tree {1,#,2,3}, 6 | 1 7 | \ 8 | 2 9 | / 10 | 3 11 | return [1,2,3]. 12 | 13 | Note: Recursive solution is trivial, could you do it iteratively? 14 | ''' 15 | 16 | # Definition for a binary tree node. 17 | class TreeNode(object): 18 | def __init__(self, x): 19 | self.val = x 20 | self.left = None 21 | self.right = None 22 | 23 | 24 | class Solution(object): 25 | def preorderTraversal(self, root): 26 | """ 27 | :type root: TreeNode 28 | :rtype: List[int] 29 | """ 30 | stack = [] 31 | result = [] 32 | while root or stack: 33 | if not root: 34 | root = stack.pop() 35 | result.append(root.val) 36 | if root.right: 37 | stack.append(root.right) 38 | root = root.left 39 | return result 40 | 41 | 42 | if __name__ == "__main__": 43 | None -------------------------------------------------------------------------------- /python/145 Binary Tree Postorder Traversal.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a binary tree, return the postorder traversal of its nodes' values. 3 | 4 | For example: 5 | Given binary tree {1,#,2,3}, 6 | 1 7 | \ 8 | 2 9 | / 10 | 3 11 | return [3,2,1]. 12 | 13 | Note: Recursive solution is trivial, could you do it iteratively? 14 | ''' 15 | 16 | # Definition for a binary tree node. 17 | class TreeNode(object): 18 | def __init__(self, x): 19 | self.val = x 20 | self.left = None 21 | self.right = None 22 | 23 | class Solution(object): 24 | def postorderTraversal(self, root): 25 | """ 26 | :type root: TreeNode 27 | :rtype: List[int] 28 | """ 29 | if not root: 30 | return [] 31 | result = [] 32 | stack = [(root, 'visit')] 33 | while stack: 34 | node, label = stack.pop() 35 | if label == 'visit': 36 | stack.append((node, 'get')) 37 | if node.right: 38 | stack.append((node.right, 'visit')) 39 | if node.left: 40 | stack.append((node.left, 'visit')) 41 | else: 42 | result.append(node.val) 43 | return result 44 | 45 | 46 | if __name__ == "__main__": 47 | None -------------------------------------------------------------------------------- /python/147 Insertion Sort List.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Sort a linked list using insertion sort. 3 | ''' 4 | 5 | # Definition for singly-linked list. 6 | class ListNode(object): 7 | def __init__(self, x): 8 | self.val = x 9 | self.next = None 10 | 11 | 12 | class Solution(object): 13 | def insertionSortList(self, head): 14 | """ 15 | :type head: ListNode 16 | :rtype: ListNode 17 | """ 18 | dummy = ListNode(-1) 19 | cur = dummy 20 | while head: 21 | # check if it is needed to reset the cur pointer 22 | if cur and cur.val > head.val: 23 | cur = dummy 24 | # find the place to insert 25 | while cur.next and cur.next.val < head.val: 26 | cur = cur.next 27 | # insert and sort the next element 28 | cur.next, cur.next.next, head = head, cur.next, head.next 29 | return dummy.next 30 | 31 | 32 | if __name__ == "__main__": 33 | None -------------------------------------------------------------------------------- /python/149 Max Points on a Line.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given n points on a 2D plane, find the maximum number of points that lie on the same straight line. 3 | ''' 4 | 5 | # Definition for a point. 6 | class Point(object): 7 | def __init__(self, a=0, b=0): 8 | self.x = a 9 | self.y = b 10 | 11 | 12 | class Solution(object): 13 | def maxPoints(self, points): 14 | """ 15 | :type points: List[Point] 16 | :rtype: int 17 | """ 18 | n = len(points) 19 | slope_map = {} 20 | result = 0 21 | for i in range(n): 22 | slope_map.clear() 23 | same, vertical = 1, 0 24 | slope_max = 0 25 | for j in range(i + 1, n): 26 | dx, dy = points[i].x - points[j].x, points[i].y - points[j].y 27 | if dx == dy == 0: 28 | same += 1 29 | elif dx == 0: 30 | vertical += 1 31 | else: 32 | slope = float(dy) / float(dx) 33 | slope_map[slope] = slope_map.get(slope, 0) + 1 34 | slope_max = max(slope_max, slope_map[slope]) 35 | result = max(result, max(slope_max, vertical) + same) 36 | return result 37 | 38 | 39 | if __name__ == "__main__": 40 | None -------------------------------------------------------------------------------- /python/150 Evaluate Reverse Polish Notation.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Evaluate the value of an arithmetic expression in Reverse Polish Notation. 3 | 4 | Valid operators are +, -, *, /. Each operand may be an integer or another expression. 5 | 6 | Some examples: 7 | ["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9 8 | ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6 9 | ''' 10 | 11 | class Solution(object): 12 | def evalRPN(self, tokens): 13 | """ 14 | :type tokens: List[str] 15 | :rtype: int 16 | """ 17 | stack = [] 18 | for token in tokens: 19 | if token not in ("+", "-", "*", "/"): 20 | stack.append(int(token)) 21 | else: 22 | second = stack.pop() 23 | first = stack.pop() 24 | if token == "+": 25 | stack.append(first + second) 26 | elif token == "-": 27 | stack.append(first - second) 28 | elif token == '*': 29 | stack.append(first * second) 30 | else: 31 | if first * second < 0: 32 | stack.append(-(abs(first) // abs(second))) 33 | else: 34 | stack.append(first // second) 35 | return stack.pop() 36 | 37 | 38 | if __name__ == "__main__": 39 | assert Solution().evalRPN(["2", "1", "+", "3", "*"]) == 9 40 | assert Solution().evalRPN(["4", "13", "5", "/", "+"]) == 6 41 | assert Solution().evalRPN(["10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"]) == 22 -------------------------------------------------------------------------------- /python/151 Reverse Words in a String.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an input string, reverse the string word by word. 3 | 4 | For example, 5 | Given s = "the sky is blue", 6 | return "blue is sky the". 7 | 8 | Update (2015-02-12): 9 | For C programmers: Try to solve it in-place in O(1) space. 10 | 11 | Clarification: 12 | What constitutes a word? 13 | A sequence of non-space characters constitutes a word. 14 | Could the input string contain leading or trailing spaces? 15 | Yes. However, your reversed string should not contain leading or trailing spaces. 16 | How about multiple spaces between two words? 17 | Reduce them to a single space in the reversed string. 18 | ''' 19 | 20 | class Solution(object): 21 | def reverseWords(self, s): 22 | """ 23 | :type s: str 24 | :rtype: str 25 | """ 26 | return " ".join(s.split()[::-1]) 27 | 28 | 29 | if __name__ == "__main__": 30 | assert Solution().reverseWords("the sky is blue ") == "blue is sky the" -------------------------------------------------------------------------------- /python/152 Maximum Product Subarray.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Find the contiguous subarray within an array (containing at least one number) which has the largest product. 3 | 4 | For example, given the array [2,3,-2,4], 5 | the contiguous subarray [2,3] has the largest product = 6. 6 | ''' 7 | 8 | class Solution(object): 9 | def maxProduct(self, nums): 10 | """ 11 | :type nums: List[int] 12 | :rtype: int 13 | """ 14 | positive, negative = nums[0], nums[0] 15 | result = nums[0] 16 | for num in nums[1:]: 17 | positive, negative = max(num, positive * num, negative * num), min(num, 18 | positive * num, negative * num) 19 | result = max(result, positive) 20 | return result 21 | 22 | 23 | if __name__ == "__main__": 24 | assert Solution().maxProduct([2, 3, -2, 4]) == 6 -------------------------------------------------------------------------------- /python/153 Find Minimum in Rotated Sorted Array.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Suppose a sorted array is rotated at some pivot unknown to you beforehand. 3 | 4 | (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2). 5 | 6 | Find the minimum element. 7 | 8 | You may assume no duplicate exists in the array. 9 | ''' 10 | 11 | class Solution(object): 12 | def findMin(self, nums): 13 | """ 14 | :type nums: List[int] 15 | :rtype: int 16 | """ 17 | left, right = 0, len(nums) - 1 18 | mid = 0 19 | while left < right: 20 | mid = (left + right) // 2 21 | if nums[mid] > nums[mid + 1]: 22 | return nums[mid + 1] 23 | elif nums[mid] > nums[right]: 24 | left = mid + 1 25 | else: 26 | right = mid 27 | return nums[mid] 28 | 29 | 30 | if __name__ == "__main__": 31 | assert Solution().findMin([1, 2, 3, 4, 5]) == 1 32 | assert Solution().findMin([2, 3, 4, 5, 1]) == 1 33 | assert Solution().findMin([5, 1, 2, 3, 4]) == 1 -------------------------------------------------------------------------------- /python/162 Find Peak Element.py: -------------------------------------------------------------------------------- 1 | ''' 2 | A peak element is an element that is greater than its neighbors. 3 | 4 | Given an input array where num[i] ≠ num[i+1], find a peak element and return its index. 5 | 6 | The array may contain multiple peaks, in that case return the index to any one of the peaks is fine. 7 | 8 | You may imagine that num[-1] = num[n] = -∞. 9 | 10 | For example, in array [1, 2, 3, 1], 3 is a peak element and your function should return the index number 2. 11 | 12 | Note: 13 | Your solution should be in logarithmic complexity. 14 | ''' 15 | 16 | class Solution(object): 17 | def findPeakElement(self, nums): 18 | """ 19 | :type nums: List[int] 20 | :rtype: int 21 | """ 22 | left, right = 0, len(nums) - 1 23 | while left < right: 24 | mid = (right + left) // 2 25 | if nums[mid] < nums[mid + 1]: 26 | left = mid + 1 27 | else: 28 | right = mid 29 | return left 30 | 31 | 32 | if __name__ == "__main__": 33 | assert Solution().findPeakElement([1, 2, 3, 1]) == 2 -------------------------------------------------------------------------------- /python/164 Maximum Gap.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an unsorted array, find the maximum difference between the successive elements in its sorted form. 3 | 4 | Try to solve it in linear time/space. 5 | 6 | Return 0 if the array contains less than 2 elements. 7 | 8 | You may assume all elements in the array are non-negative integers and fit in the 32-bit signed integer range. 9 | ''' 10 | 11 | class Solution(object): 12 | def maximumGap(self, nums): 13 | """ 14 | :type nums: List[int] 15 | :rtype: int 16 | """ 17 | 18 | def radix_sort(nums): 19 | max_num = max(nums) 20 | i = 1 21 | while max_num // i: 22 | buckets = [[] for __ in range(10)] 23 | for num in nums: 24 | buckets[((num // i) % 10)].append(num) 25 | nums = [num for bucket in buckets for num in bucket] 26 | i *= 10 27 | return nums 28 | 29 | n = len(nums) 30 | if n < 2: 31 | return 0 32 | nums = radix_sort(nums) 33 | max_gap = 0 34 | for i in range(1, n): 35 | max_gap = max(max_gap, nums[i] - nums[i - 1]) 36 | return max_gap 37 | 38 | 39 | if __name__ == "__main__": 40 | assert Solution().maximumGap([99, 50, 3, 18, 28]) == 49 -------------------------------------------------------------------------------- /python/165 Compare Version Numbers.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Compare two version numbers version1 and version2. 3 | If version1 > version2 return 1, if version1 < version2 return -1, otherwise return 0. 4 | 5 | You may assume that the version strings are non-empty and contain only digits and the . character. 6 | The . character does not represent a decimal point and is used to separate number sequences. 7 | For instance, 2.5 is not "two and a half" or "half way to version three", it is the fifth second-level revision of the second first-level revision. 8 | 9 | Here is an example of version numbers ordering: 10 | 11 | 0.1 < 1.1 < 1.2 < 13.37 12 | ''' 13 | 14 | class Solution(object): 15 | def compareVersion(self, version1, version2): 16 | """ 17 | :type version1: str 18 | :type version2: str 19 | :rtype: int 20 | """ 21 | version1_list = version1.split(".") 22 | version2_list = version2.split(".") 23 | len1 = len(version1_list) 24 | len2 = len(version2_list) 25 | for i in range(max(len1, len2)): 26 | v1 = int(version1_list[i]) if i < len1 else 0 27 | v2 = int(version2_list[i]) if i < len2 else 0 28 | if v1 != v2: 29 | return 1 if v1 > v2 else -1 30 | return 0 31 | 32 | 33 | if __name__ == "__main__": 34 | assert Solution().compareVersion("0.1", "1.1") == -1 35 | assert Solution().compareVersion("01.2", "1.1") == 1 36 | assert Solution().compareVersion("2.3", "2.3") == 0 -------------------------------------------------------------------------------- /python/168 Excel Sheet Column Title.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a positive integer, return its corresponding column title as appear in an Excel sheet. 3 | 4 | For example: 5 | 6 | 1 -> A 7 | 2 -> B 8 | 3 -> C 9 | ... 10 | 26 -> Z 11 | 27 -> AA 12 | 28 -> AB 13 | ''' 14 | 15 | class Solution(object): 16 | def convertToTitle(self, n): 17 | """ 18 | :type n: int 19 | :rtype: str 20 | """ 21 | result = [] 22 | base = ord('A') 23 | while n: 24 | n, r = divmod(n - 1, 26) 25 | result.append(chr(base + r)) 26 | return ''.join(result[::-1]) 27 | 28 | 29 | if __name__ == "__main__": 30 | assert Solution().convertToTitle(1) == 'A' 31 | assert Solution().convertToTitle(28) == 'AB' -------------------------------------------------------------------------------- /python/169 Majority Element.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times. 3 | 4 | You may assume that the array is non-empty and the majority element always exist in the array. 5 | ''' 6 | 7 | class Solution(object): 8 | def majorityElement(self, nums): 9 | """ 10 | :type nums: List[int] 11 | :rtype: int 12 | """ 13 | result = None 14 | count = 0 15 | for num in nums: 16 | if count == 0: 17 | result = num 18 | if result == num: 19 | count += 1 20 | else: 21 | count -= 1 22 | return result 23 | 24 | 25 | if __name__ == "__main__": 26 | assert Solution().majorityElement([1, 2, 2, 3, 3, 3, 3]) == 3 27 | assert Solution().majorityElement([3, 3, 3, 3, 1, 1, 2]) == 3 -------------------------------------------------------------------------------- /python/171 Excel Sheet Column Number.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Related to question Excel Sheet Column Title 3 | 4 | Given a column title as appear in an Excel sheet, return its corresponding column number. 5 | 6 | For example: 7 | 8 | A -> 1 9 | B -> 2 10 | C -> 3 11 | ... 12 | Z -> 26 13 | AA -> 27 14 | AB -> 28 15 | ''' 16 | 17 | class Solution(object): 18 | def titleToNumber(self, s): 19 | """ 20 | :type s: str 21 | :rtype: int 22 | """ 23 | base = ord('A') - 1 24 | n = len(s) 25 | result = 0 26 | for i in range(n): 27 | result += (ord(s[n - 1 - i]) - base) * pow(26, i) 28 | return result 29 | 30 | 31 | if __name__ == "__main__": 32 | assert Solution().titleToNumber('A') == 1 33 | assert Solution().titleToNumber('AB') == 28 -------------------------------------------------------------------------------- /python/172 Factorial Trailing Zeroes.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an integer n, return the number of trailing zeroes in n!. 3 | 4 | Note: Your solution should be in logarithmic time complexity. 5 | ''' 6 | 7 | class Solution(object): 8 | def trailingZeroes(self, n): 9 | """ 10 | :type n: int 11 | :rtype: int 12 | """ 13 | count = 0 14 | while n: 15 | n //= 5 16 | count += n 17 | return count 18 | 19 | 20 | if __name__ == "__main__": 21 | assert Solution().trailingZeroes(25) == 6 -------------------------------------------------------------------------------- /python/173 Binary Search Tree Iterator.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST. 3 | 4 | Calling next() will return the next smallest number in the BST. 5 | 6 | Note: next() and hasNext() should run in average O(1) time and uses O(h) memory, where h is the height of the tree. 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 BSTIterator(object): 17 | def __init__(self, root): 18 | """ 19 | :type root: TreeNode 20 | """ 21 | self.stack = [] 22 | self._pushLeft(root) 23 | 24 | def hasNext(self): 25 | """ 26 | :rtype: bool 27 | """ 28 | return self.stack 29 | 30 | def next(self): 31 | """ 32 | :rtype: int 33 | """ 34 | node = self.stack.pop() 35 | self._pushLeft(node.right) 36 | return node.val 37 | 38 | def _pushLeft(self, node): 39 | while node: 40 | self.stack.append(node) 41 | node = node.left 42 | 43 | 44 | # Your BSTIterator will be called like this: 45 | # i, v = BSTIterator(root), [] 46 | # while i.hasNext(): v.append(i.next()) 47 | 48 | 49 | if __name__ == "__main__": 50 | None -------------------------------------------------------------------------------- /python/179 Largest Number.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a list of non negative integers, arrange them such that they form the largest number. 3 | 4 | For example, given [3, 30, 34, 5, 9], the largest formed number is 9534330. 5 | 6 | Note: The result may be very large, so you need to return a string instead of an integer. 7 | ''' 8 | 9 | from functools import cmp_to_key 10 | 11 | 12 | class Solution: 13 | # @param {integer[]} nums 14 | # @return {string} 15 | def largestNumber(self, nums): 16 | sorted_nums = sorted(map(str, nums), key=cmp_to_key(lambda x, y: int(y + x) - int(x + y))) 17 | result = ''.join(sorted_nums).lstrip('0') 18 | return result or '0' 19 | 20 | 21 | if __name__ == "__main__": 22 | assert Solution().largestNumber([3, 30, 34, 5, 9]) == '9534330' 23 | assert Solution().largestNumber([0, 0]) == '0' -------------------------------------------------------------------------------- /python/189 Rotate Array.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Rotate an array of n elements to the right by k steps. 3 | 4 | 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]. 5 | 6 | Note: 7 | Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem. 8 | ''' 9 | 10 | class Solution(object): 11 | def rotate(self, nums, k): 12 | """ 13 | :type nums: List[int] 14 | :type k: int 15 | :rtype: void Do not return anything, modify nums in-place instead. 16 | """ 17 | 18 | def reverse(nums, start, end): 19 | while start < end: 20 | nums[start], nums[end] = nums[end], nums[start] 21 | start += 1 22 | end -= 1 23 | 24 | n = len(nums) 25 | k %= n 26 | reverse(nums, 0, n - k - 1) 27 | reverse(nums, n - k, n - 1) 28 | reverse(nums, 0, n - 1) 29 | 30 | 31 | if __name__ == "__main__": 32 | nums = [1, 2, 3, 4, 5, 6, 7] 33 | Solution().rotate(nums, 10) 34 | assert nums == [5, 6, 7, 1, 2, 3, 4] -------------------------------------------------------------------------------- /python/190 Reverse Bits.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Reverse bits of a given 32 bits unsigned integer. 3 | 4 | For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), return 964176192 (represented in binary as 00111001011110000010100101000000). 5 | 6 | Follow up: 7 | If this function is called many times, how would you optimize it? 8 | ''' 9 | 10 | class Solution(object): 11 | def reverseBits(self, n): 12 | """ 13 | :type n: int 14 | :rtype: int 15 | """ 16 | n = ((n & 0x55555555) << 1) | ((n >> 1) & 0x55555555) 17 | n = ((n & 0x33333333) << 2) | ((n >> 2) & 0x33333333) 18 | n = ((n & 0x0f0f0f0f) << 4) | ((n >> 4) & 0x0f0f0f0f) 19 | n = (n << 24) | ((n & 0xff00) << 8) | ((n >> 8) & 0xff00) | (n >> 24) 20 | return n & 0xffffffff 21 | 22 | 23 | if __name__ == "__main__": 24 | assert Solution().reverseBits(43261596) == 964176192 -------------------------------------------------------------------------------- /python/191 Number of 1 Bits.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also known as the Hamming weight). 3 | 4 | For example, the 32-bit integer ’11' has binary representation 00000000000000000000000000001011, so the function should return 3. 5 | ''' 6 | 7 | class Solution(object): 8 | def hammingWeight(self, n): 9 | """ 10 | :type n: int 11 | :rtype: int 12 | """ 13 | n -= (n >> 1) & 0x55555555 14 | n = (n & 0x33333333) + ((n >> 2) & 0x33333333) 15 | n = (n + (n >> 4)) & 0x0f0f0f0f 16 | n += (n >> 8) 17 | n += (n >> 16) 18 | return n & 0x3f 19 | 20 | 21 | if __name__ == "__main__": 22 | assert Solution().hammingWeight(4294967295) == 32 23 | assert Solution().hammingWeight(11) == 3 -------------------------------------------------------------------------------- /python/198 House Robber.py: -------------------------------------------------------------------------------- 1 | ''' 2 | 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. 3 | 4 | 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. 5 | ''' 6 | 7 | class Solution(object): 8 | def rob(self, nums): 9 | """ 10 | :type nums: List[int] 11 | :rtype: int 12 | """ 13 | if not nums: 14 | return 0 15 | n = len(nums) 16 | if n < 2: 17 | return nums[0] 18 | dp = [0] * n 19 | dp[0] = nums[0] 20 | dp[1] = max(nums[0], nums[1]) 21 | for i in range(2, n): 22 | dp[i] = max(dp[i - 1], dp[i - 2] + nums[i]) 23 | return dp[-1] 24 | 25 | 26 | if __name__ == "__main__": 27 | assert Solution().rob([1, 2, 3, 4, 5, 6, 7]) == 16 -------------------------------------------------------------------------------- /python/199 Binary Tree Right Side View.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom. 3 | 4 | For example: 5 | Given the following binary tree, 6 | 1 <--- 7 | / \ 8 | 2 3 <--- 9 | \ \ 10 | 5 4 <--- 11 | You should return [1, 3, 4]. 12 | ''' 13 | 14 | # Definition for a binary tree node. 15 | class TreeNode(object): 16 | def __init__(self, x): 17 | self.val = x 18 | self.left = None 19 | self.right = None 20 | 21 | 22 | class Solution(object): 23 | def rightSideView(self, root): 24 | """ 25 | :type root: TreeNode 26 | :rtype: List[int] 27 | """ 28 | result = [] 29 | 30 | def dfs(node, level): 31 | if node is None: 32 | return 33 | if len(result) == level: 34 | result.append(node.val) 35 | if node.right: 36 | dfs(node.right, level + 1) 37 | if node.left: 38 | dfs(node.left, level + 1) 39 | 40 | dfs(root, 0) 41 | return result 42 | 43 | 44 | if __name__ == "__main__": 45 | None -------------------------------------------------------------------------------- /python/200 Number of Islands.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water. 3 | 4 | Example 1: 5 | 6 | 11110 7 | 11010 8 | 11000 9 | 00000 10 | Answer: 1 11 | 12 | Example 2: 13 | 14 | 11000 15 | 11000 16 | 00100 17 | 00011 18 | Answer: 3 19 | ''' 20 | 21 | class Solution(object): 22 | def numIslands(self, grid): 23 | """ 24 | :type grid: List[List[str]] 25 | :rtype: int 26 | """ 27 | if not grid: 28 | return 0 29 | n = len(grid) 30 | m = len(grid[0]) 31 | 32 | def dfs(i, j): 33 | if 0 <= i < n and 0 <= j < m and grid[i][j] == '1': 34 | grid[i][j] = '0' 35 | dfs(i, j - 1) 36 | dfs(i, j + 1) 37 | dfs(i - 1, j) 38 | dfs(i + 1, j) 39 | return 1 40 | return 0 41 | 42 | count = sum(dfs(i, j) for i in range(n) for j in range(m)) 43 | return count 44 | 45 | 46 | if __name__ == "__main__": 47 | assert Solution().numIslands([['1', '1', '0', '0', '0'], 48 | ['1', '1', '0', '0', '0'], 49 | ['0', '0', '1', '0', '0'], 50 | ['0', '0', '0', '1', '1']]) == 3 -------------------------------------------------------------------------------- /python/201 Bitwise AND of Numbers Range.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a range [m, n] where 0 <= m <= n <= 2147483647, return the bitwise AND of all numbers in this range, inclusive. 3 | 4 | For example, given the range [5, 7], you should return 4. 5 | ''' 6 | 7 | class Solution(object): 8 | def rangeBitwiseAnd(self, m, n): 9 | """ 10 | :type m: int 11 | :type n: int 12 | :rtype: int 13 | """ 14 | while n > m: 15 | n &= n - 1 16 | return n 17 | 18 | 19 | if __name__ == "__main__": 20 | assert Solution().rangeBitwiseAnd(5, 7) == 4 21 | assert Solution().rangeBitwiseAnd(7, 15) == 0 -------------------------------------------------------------------------------- /python/202 Happy Number.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Write an algorithm to determine if a number is "happy". 3 | 4 | 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. 5 | 6 | Example: 19 is a happy number 7 | 8 | 1^2 + 9^2 = 82 9 | 8^2 + 2^2 = 68 10 | 6^2 + 8^2 = 100 11 | 1^2 + 0^2 + 0^2 = 1 12 | ''' 13 | 14 | class Solution(object): 15 | def isHappy(self, n): 16 | """ 17 | :type n: int 18 | :rtype: bool 19 | """ 20 | visited = [] 21 | while n != 1: 22 | if n in visited: 23 | return False 24 | visited.append(n) 25 | n = sum([int(i) ** 2 for i in str(n)]) 26 | return True 27 | 28 | 29 | if __name__ == "__main__": 30 | assert Solution().isHappy(19) == True -------------------------------------------------------------------------------- /python/203 Remove Linked List Elements.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Remove all elements from a linked list of integers that have value val. 3 | 4 | Example 5 | Given: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6 6 | Return: 1 --> 2 --> 3 --> 4 --> 5 7 | ''' 8 | 9 | # Definition for singly-linked list. 10 | class ListNode(object): 11 | def __init__(self, x): 12 | self.val = x 13 | self.next = None 14 | 15 | 16 | class Solution(object): 17 | def removeElements(self, head, val): 18 | """ 19 | :type head: ListNode 20 | :type val: int 21 | :rtype: ListNode 22 | """ 23 | dummy = ListNode(-1) 24 | dummy.next = head 25 | node = dummy 26 | while node.next: 27 | if node.next.val == val: 28 | node.next = node.next.next 29 | else: 30 | node = node.next 31 | return dummy.next 32 | 33 | 34 | if __name__ == "__main__": 35 | None -------------------------------------------------------------------------------- /python/205 Isomorphic Strings.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given two strings s and t, determine if they are isomorphic. 3 | 4 | Two strings are isomorphic if the characters in s can be replaced to get t. 5 | 6 | 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. 7 | 8 | For example, 9 | Given "egg", "add", return true. 10 | 11 | Given "foo", "bar", return false. 12 | 13 | Given "paper", "title", return true. 14 | 15 | Note: 16 | You may assume both s and t have the same length. 17 | ''' 18 | 19 | class Solution(object): 20 | def isIsomorphic(self, s, t): 21 | """ 22 | :type s: str 23 | :type t: str 24 | :rtype: bool 25 | """ 26 | found = {} 27 | for c1, c2 in zip(s, t): 28 | if c1 in found: 29 | if not found[c1] == c2: 30 | return False 31 | else: 32 | if c2 in found.values(): 33 | return False 34 | found[c1] = c2 35 | return True 36 | 37 | 38 | if __name__ == "__main__": 39 | assert Solution().isIsomorphic("egg", "add") == True 40 | assert Solution().isIsomorphic("foo", "bar") == False 41 | assert Solution().isIsomorphic("paper", "title") == True -------------------------------------------------------------------------------- /python/206 Reverse Linked List.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Reverse a singly linked list. 3 | ''' 4 | 5 | # Definition for singly-linked list. 6 | class ListNode(object): 7 | def __init__(self, x): 8 | self.val = x 9 | self.next = None 10 | 11 | def to_list(self): 12 | return [self.val] + self.next.to_list() if self.next else [self.val] 13 | 14 | 15 | class Solution(object): 16 | def reverseList(self, head): 17 | """ 18 | :type head: ListNode 19 | :rtype: ListNode 20 | """ 21 | if not head: 22 | return None 23 | prev = head 24 | curr = prev.next 25 | while curr: 26 | next = curr.next 27 | curr.next = prev 28 | prev = curr 29 | curr = next 30 | head.next = None 31 | return prev 32 | 33 | 34 | if __name__ == "__main__": 35 | n1 = ListNode(1) 36 | n2 = ListNode(2) 37 | n3 = ListNode(3) 38 | n1.next = n2 39 | n2.next = n3 40 | r = Solution().reverseList(n1) 41 | assert r.to_list() == [3, 2, 1] -------------------------------------------------------------------------------- /python/217 Contains Duplicate.py: -------------------------------------------------------------------------------- 1 | ''' 2 | 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. 3 | ''' 4 | 5 | class Solution(object): 6 | def containsDuplicate(self, nums): 7 | """ 8 | :type nums: List[int] 9 | :rtype: bool 10 | """ 11 | return len(nums) != len(set(nums)) 12 | 13 | 14 | if __name__ == "__main__": 15 | assert Solution().containsDuplicate([1, 2, 3, 4]) == False 16 | assert Solution().containsDuplicate([1, 2, 3, 1]) == True -------------------------------------------------------------------------------- /python/219 Contains Duplicate II.py: -------------------------------------------------------------------------------- 1 | ''' 2 | 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. 3 | ''' 4 | 5 | class Solution(object): 6 | def containsNearbyDuplicate(self, nums, k): 7 | """ 8 | :type nums: List[int] 9 | :type k: int 10 | :rtype: bool 11 | """ 12 | if not nums: 13 | return False 14 | m = {} 15 | for i in range(len(nums)): 16 | if nums[i] in m: 17 | if i - m.get(nums[i]) <= k: 18 | return True 19 | m[nums[i]] = i 20 | return False 21 | 22 | 23 | if __name__ == "__main__": 24 | assert Solution().containsNearbyDuplicate([1, 2, 3, 4], 1) == False 25 | assert Solution().containsNearbyDuplicate([1, 1, 2, 3], 2) == True 26 | assert Solution().containsNearbyDuplicate([1, 2, 3, 1], 2) == False -------------------------------------------------------------------------------- /python/233 Number of Digit One.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an integer n, count the total number of digit 1 appearing in all non-negative integers less than or equal to n. 3 | 4 | For example: 5 | Given n = 13, 6 | Return 6, because digit 1 occurred in the following numbers: 1, 10, 11, 12, 13. 7 | ''' 8 | 9 | class Solution(object): 10 | def countDigitOne(self, n): 11 | """ 12 | :type n: int 13 | :rtype: int 14 | """ 15 | x, m, count = n, 1, 0 16 | while x > 0: 17 | lastDigit = x % 10 18 | x //= 10 19 | count += x * m 20 | if lastDigit == 1: 21 | count += n % m + 1 22 | elif lastDigit > 1: 23 | count += m 24 | m *= 10 25 | return count 26 | 27 | 28 | if __name__ == "__main__": 29 | assert Solution().countDigitOne(13) == 6 30 | -------------------------------------------------------------------------------- /python/234 Palindrome Linked List.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a singly linked list, determine if it is a palindrome. 3 | 4 | Follow up: 5 | Could you do it in O(n) time and O(1) space? 6 | ''' 7 | 8 | # Definition for singly-linked list. 9 | class ListNode(object): 10 | def __init__(self, x): 11 | self.val = x 12 | self.next = None 13 | 14 | 15 | class Solution(object): 16 | def isPalindrome(self, head): 17 | """ 18 | :type head: ListNode 19 | :rtype: bool 20 | """ 21 | # split the list into two parts, we can reverse the first part at meantime 22 | fast = slow = head 23 | reverse = None 24 | while fast and fast.next: 25 | fast = fast.next.next 26 | reverse, reverse.next, slow = slow, reverse, slow.next 27 | # if the total number is odd, skip the centre point 28 | if fast: 29 | slow = slow.next 30 | # compare the reversed first part and normal second part 31 | while reverse: 32 | if reverse.val != slow.val: 33 | return False 34 | else: 35 | reverse = reverse.next 36 | slow = slow.next 37 | return True 38 | 39 | 40 | if __name__ == "__main__": 41 | n1 = ListNode(1) 42 | n2 = ListNode(2) 43 | n3 = ListNode(1) 44 | n1.next = n2 45 | n2.next = n3 46 | assert Solution().isPalindrome(n1) == True 47 | assert Solution().isPalindrome(n2) == False 48 | n1.next = n3 49 | assert Solution().isPalindrome(n1) == True 50 | -------------------------------------------------------------------------------- /python/237 Delete Node in a Linked List.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Write a function to delete a node (except the tail) in a singly linked list, 3 | given only access to that node. 4 | 5 | Supposed the linked list is 1 -> 2 -> 3 -> 4 and you are given the third node 6 | with value 3, the linked list should become 1 -> 2 -> 4 after calling your 7 | function. 8 | ''' 9 | 10 | # Definition for singly-linked list. 11 | class ListNode(object): 12 | def __init__(self, x): 13 | self.val = x 14 | self.next = None 15 | 16 | class Solution(object): 17 | def deleteNode(self, node): 18 | """ 19 | :type node: ListNode 20 | :rtype: void Do not return anything, modify node in-place instead. 21 | """ 22 | node.val = node.next.val 23 | node.next = node.next.next 24 | 25 | 26 | if __name__=="__main__": 27 | n1 = ListNode(1) 28 | n2 = ListNode(2) 29 | n3 = ListNode(3) 30 | n4 = ListNode(4) 31 | n1.next = n2 32 | n2.next = n3 33 | n3.next = n4 34 | Solution().deleteNode(n3) 35 | assert n2.next.val == 4 36 | -------------------------------------------------------------------------------- /python/238 Product of Array Except Self.py: -------------------------------------------------------------------------------- 1 | ''' 2 | 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]. 3 | 4 | Solve it without division and in O(n). 5 | 6 | For example, given [1,2,3,4], return [24,12,8,6]. 7 | 8 | Follow up: 9 | 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.) 10 | ''' 11 | 12 | class Solution(object): 13 | def productExceptSelf(self, nums): 14 | """ 15 | :type nums: List[int] 16 | :rtype: List[int] 17 | """ 18 | n = len(nums) 19 | result = [1] * n 20 | for i in range(1, n): 21 | result[i] = result[i - 1] * nums[i - 1] 22 | temp = 1 23 | for i in range(n - 1, -1, -1): 24 | result[i] *= temp 25 | temp *= nums[i] 26 | return result 27 | 28 | 29 | if __name__ == "__main__": 30 | assert Solution().productExceptSelf([1, 2, 3, 4]) == [24, 12, 8, 6] 31 | -------------------------------------------------------------------------------- /python/242 Valid Anagram.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given two strings s and t, write a function to determine if t is an anagram of s. 3 | 4 | For example, 5 | s = "anagram", t = "nagaram", return true. 6 | s = "rat", t = "car", return false. 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 | class Solution(object): 16 | def isAnagram(self, s, t): 17 | """ 18 | :type s: str 19 | :type t: str 20 | :rtype: bool 21 | """ 22 | m = {} 23 | if len(s) != len(t): 24 | return False 25 | for c in s: 26 | m[c] = m.get(c, 0) + 1 27 | for c in t: 28 | if c not in m or m[c] == 0: 29 | return False 30 | else: 31 | m[c] -= 1 32 | return True 33 | 34 | 35 | if __name__ == "__main__": 36 | s, t = "anagram", "nagaram" 37 | assert Solution().isAnagram(s, t) == True 38 | s, t = 'rat', 'car' 39 | assert Solution().isAnagram(s, t) == False 40 | --------------------------------------------------------------------------------