├── .editorconfig ├── .gitignore ├── .vscode └── settings.json ├── Array ├── 1065.My Calendar I │ ├── README.md │ ├── Solution_Array.py │ ├── Solution_SweepLine.py │ └── Solution_TreeMap.py ├── 1287.Increasing Triplet Subsequence │ ├── README.md │ └── Solution.py ├── 138.Subarray Sum │ ├── README.md │ └── Solution.py ├── 139.Subarray Sum Closest │ ├── README.md │ └── Solution.py ├── 149.Best Time to Buy and Sell Stock │ ├── README.md │ └── Solution.py ├── 150.Best Time to Buy and Sell Stock II │ ├── README.md │ └── Solution.py ├── 151.Best Time to Buy and Sell Stock III │ ├── README.md │ └── Solution.py ├── 156.Merge Intervals │ ├── README.md │ ├── Solution.cpp │ └── Solution.py ├── 402.Continuous Subarray Sum │ ├── README.md │ └── Solution.py ├── 403.Continuous Subarray Sum II │ ├── README.md │ └── Solution.py ├── 41.Maximum Subarray │ ├── README.md │ ├── Solution.java │ └── Solution.py ├── 547.Intersection of Two Arrays │ ├── README.md │ ├── Solution.py │ ├── Solution_HashMap.java │ ├── Solution_Sort_BinarySearch.java │ └── Solution_Sort_Merge.java └── 839.Merge Two Sorted Interval Lists │ ├── README.md │ └── Solution_Deque.py ├── BFS ├── 120.Word Ladder │ ├── README.md │ ├── Solution_BFS.py │ └── Solution_Bidirectional_BFS.py ├── 121.Word Ladder II │ ├── README.md │ └── Solution.py ├── 127.Topological Sorting │ ├── README.md │ ├── Solution.java │ ├── Solution_BFS.py │ └── Solution_DFS.py ├── 137.Clone Graph │ ├── README.md │ ├── Solution.java │ └── Solution.py ├── 1374.Shortest Distance in 3D Space │ ├── README.md │ └── Solution.py ├── 1446.01 Matrix Walking Problem │ ├── README.md │ ├── Solution.java │ └── Solution.py ├── 1479.Can Reach The Endpoint │ ├── README.md │ └── Solution_BFS.py ├── 178.Graph Valid Tree │ ├── README.md │ ├── Solution_BFS.cpp │ ├── Solution_BFS.java │ ├── Solution_BFS.py │ ├── Solution_UnionFind.cpp │ └── Solution_UnionFind.py ├── 242.Convert Binary Tree to Linked Lists by Depth │ ├── README.md │ ├── Solution_BFS.py │ └── Solution_DFS.py ├── 375.Clone Binary Tree │ ├── README.md │ ├── Solution_BFS.py │ └── Solution_DFS.py ├── 431.Connected Component in Undirected Graph │ ├── README.md │ ├── Solution_BFS.py │ ├── Solution_UnionFind_1.py │ └── Solution_UnionFind_2.py ├── 433.Number of Islands │ ├── README.md │ ├── Solution_BFS.java │ ├── Solution_BFS.py │ ├── Solution_DFS.py │ └── Solution_Union_Find.py ├── 477.Surrounded Regions │ ├── README.md │ ├── Solution_BFS.py │ └── Solution_UnionFind.py ├── 573.Build Post Office II │ ├── README.md │ └── Solution.py ├── 598.Zombie in Matrix │ ├── README.md │ └── Solution.py ├── 605.Sequence Reconstruction │ ├── README.md │ ├── Solution.java │ └── Solution.py ├── 611.Knight Shortest Path │ ├── README.md │ └── Solution.py ├── 615.Course Schedule │ ├── README.md │ ├── Solution.java │ └── Solution.py ├── 616.Course Schedule II │ ├── README.md │ ├── Solution.java │ └── Solution.py ├── 618.Search Graph Nodes │ ├── README.md │ ├── Solution.java │ └── Solution.py ├── 630.Knight Shortest Path II │ ├── README.md │ └── Solution.py ├── 663.Walls and Gates │ ├── README.md │ └── Solution.py ├── 677.Number of Big Islands │ ├── README.md │ └── Solution.py ├── 69.Binary Tree Level Order Traversal │ ├── README.md │ ├── Solution.java │ └── Solution.py ├── 7.Serialize and Deserialize Binary Tree │ ├── README.md │ ├── Solution.java │ ├── Solution_BFS.py │ └── Solution_DFS.py ├── 70.Binary Tree Level Order Traversal II │ ├── README.md │ ├── Solution.java │ └── Solution.py ├── 71.Binary Tree Zigzag Level Order Traversal │ ├── README.md │ ├── Solution.java │ └── Solution.py ├── 794.Sliding Puzzle II │ ├── README.md │ └── Solution.py ├── 872.Kill Process │ ├── README.md │ └── Solution_BFS.py └── 941.Sliding Puzzle │ ├── README.md │ └── Solution.py ├── Binary_Search ├── 1183.Single Element in a Sorted Array │ ├── README.md │ └── Solution.py ├── 14.First Position of Target │ ├── README.md │ ├── Solution.java │ └── Solution.py ├── 141.sqrt(x) │ ├── README.md │ ├── Solution.java │ └── Solution.py ├── 159.Find Minimum in Rotated Sorted Array │ ├── README.md │ ├── Solution.java │ └── Solution.py ├── 160.Find Minimum in Rotated Sorted Array II │ ├── README.md │ └── Solution.py ├── 1623.Minimal Distance In The Array │ ├── README.md │ └── Solution.py ├── 1626.Salary Adjustment │ ├── README.md │ └── Solution.py ├── 1629.Find the nearest store │ ├── README.md │ └── Solution.py ├── 1791.Simple queries │ ├── README.md │ └── Solution.py ├── 183.Wood Cut │ ├── README.md │ ├── Solution.java │ └── Solution.py ├── 248.Count of Smaller Number │ ├── README.md │ ├── Solution_binary_search.py │ └── Solution_segment_tree.py ├── 28.Search a 2D Matrix │ ├── README.md │ ├── Solution.java │ ├── Solution_one_pass_binary_search.py │ └── Solution_two_pass_binary_search.py ├── 38.Search a 2D Matrix II │ ├── README.md │ ├── Solution.java │ └── Solution.py ├── 390.Find Peak Element II │ ├── README.md │ ├── Solution.py │ ├── Solution_BFS.py │ └── Solution_BinarySearch.py ├── 437.Copy Books │ ├── README.md │ ├── Solution_binary_search.py │ └── Solution_dynamic_programming.py ├── 447.Search in a Big Sorted Array │ ├── README.md │ └── Solution.py ├── 457.Classical Binary Search │ ├── README.md │ └── Solution.py ├── 458.Last Position of Target │ ├── README.md │ └── Solution.py ├── 459.Closest Number in Sorted Array │ ├── README.md │ └── Solution_Binary_Search.py ├── 460.Find K Closest Elements │ ├── README.md │ ├── Solution.cpp │ ├── Solution.java │ ├── Solution.py │ └── Solution_binary_search_and_two_pointers.py ├── 462.Total Occurrence of Target │ ├── README.md │ └── Solution.py ├── 585.Maximum Number in Mountain Sequence │ ├── README.md │ └── Solution.py ├── 586.Sqrt(x) II │ ├── README.md │ └── Solution.py ├── 60.Search Insert Position │ ├── README.md │ ├── Solution.java │ └── Solution.py ├── 600.Smallest Rectangle Enclosing Black Pixels │ ├── README.md │ ├── Solution_BFS.py │ └── Solution_Binary_Search.py ├── 602.Russian Doll Envelopes │ ├── README.md │ └── Solution_BinarySearch.py ├── 61.Search for a Range │ ├── README.md │ └── Solution.py ├── 62.Search in Rotated Sorted Array │ ├── README.md │ ├── Solution.java │ ├── Solution_one_pass_binary_search.py │ └── Solution_two_pass_binary_search.py ├── 633.Find the Duplicate Number │ ├── README.md │ └── Solution.py ├── 65.Median of two Sorted Arrays │ ├── README.md │ ├── Solution.java │ └── Solution.py ├── 74.First Bad Version │ ├── README.md │ └── Solution.py ├── 75.Find Peak Element │ ├── README.md │ ├── Solution.java │ └── Solution.py ├── 76.Longest Increasing Subsequence │ ├── README.md │ ├── Solution.py │ └── Solution_BinarySearch.java ├── 937.How Many Problem Can I Accept │ ├── README.md │ └── Solution.py └── 940.Maximum Absolute Value │ ├── README.md │ └── Solution.py ├── Bit_Manipulation ├── 1. A + B Problem │ ├── README.md │ └── Solution.java ├── 82.Single Number │ ├── README.md │ ├── Solution_BinarySearch.py │ ├── Solution_Counter.py │ └── Solution_XOR.java ├── 824.Single Number IV │ ├── README.md │ └── Solution.py ├── 83.Single Number II │ ├── README.md │ ├── Solution.java │ └── Solution.py └── 84.Single Number III │ ├── README.md │ └── Solution.py ├── DFS ├── 1031.Is Graph Bipartite │ ├── README.md │ ├── Solution_BFS.java │ ├── Solution_BFS.py │ └── Solution_DFS.py ├── 106.Convert Sorted List to Binary Search Tree │ ├── README.md │ └── Solution.py ├── 1106.Maximum Binary Tree │ ├── README.md │ └── Solution.py ├── 1308.Factor Combinations │ ├── README.md │ └── Solution.py ├── 135.Combination Sum │ ├── README.md │ ├── Solution.java │ └── Solution.py ├── 1353.Sum Root to Leaf Numbers │ ├── README.md │ └── Solution.py ├── 136.Palindrome Partitioning │ ├── README.md │ ├── Solution.java │ └── Solution.py ├── 15.Permutations │ ├── README.md │ ├── Solution.java │ ├── Solution.py │ └── Solution_non_recursion.java ├── 152.Combinations │ ├── README.md │ └── Solution.py ├── 153.Combination Sum II │ ├── README.md │ ├── Solution.java │ └── Solution.py ├── 16.Permutations II │ ├── README.md │ ├── Solution.java │ └── Solution.py ├── 17.Subsets │ ├── README.md │ ├── Solution.java │ ├── Solution.py │ ├── Solution_non_recursion.java │ └── Subsets.cpp ├── 18.Subsets II │ ├── README.md │ └── Solution.py ├── 33.N-Queens │ ├── README.md │ ├── Solution.java │ └── Solution.py ├── 388.Permutation Sequence │ ├── README.md │ ├── Solution.py │ └── Solution_2.py ├── 425.Letter Combinations of a Phone Number │ ├── README.md │ └── Solution.py ├── 426.Restore IP Addresses │ ├── README.md │ └── Solution.py ├── 582.Word Break II │ ├── README.md │ └── Solution.py ├── 652.Factorization │ ├── README.md │ ├── Solution.py │ └── Solution_2.py ├── 790.Parser │ ├── README.md │ └── Solution.py └── 90.k Sum II │ ├── README.md │ ├── Solution_DFS.py │ └── Solution_DP.java ├── Deque ├── 22.Flatten List │ ├── README.md │ ├── Solution_DFS.py │ └── Solution_Deque.py └── 362.Sliding Window Maximum │ ├── README.md │ ├── Solution.py │ ├── Solution_BST.cpp │ ├── Solution_BruteForce.py │ └── Solution_MonotonicQueue.py ├── Dynamic_Programming ├── 107.Word Break │ ├── README.md │ └── Solution.py ├── 108.Palindrome Partitioning II │ ├── README.md │ ├── Solution.java │ └── Solution.py ├── 109.Triangle │ ├── README.md │ ├── Solution_DP1.py │ ├── Solution_DP2.py │ └── Solution_DivideConquer.py ├── 110.Minimum Path Sum │ ├── README.md │ └── Solution.py ├── 111.Climbing Stairs │ ├── README.md │ └── Solution.py ├── 114.Unique Paths │ ├── README.md │ ├── Solution_DP1.py │ └── Solution_DP2.py ├── 115.Unique Paths II │ ├── README.md │ └── Solution.py ├── 116.Jump Game │ ├── README.md │ └── Solution.py ├── 117.Jump Game II │ ├── README.md │ ├── Solution_DP.py │ ├── Solution_Greedy.cpp │ └── Solution_Greedy.java ├── 125.Backpack II │ ├── README.md │ └── Solution.py ├── 1259.Integer Replacement │ ├── README.md │ ├── Solution_BFS.py │ └── Solution_DFS.py ├── 254.Drop Eggs │ ├── README.md │ └── Solution.py ├── 272.Climbing Stairs II │ ├── README.md │ ├── Solution_Backpack.py │ └── Solution_DP.py ├── 514.Paint Fence │ ├── README.md │ └── Solution.py ├── 564.Combination Sum IV │ ├── README.md │ └── Solution.py ├── 679.Unique Paths III │ ├── README.md │ ├── Solution_DP1.py │ └── Solution_DP2.py ├── 76.Longest Increasing Subsequence │ ├── README.md │ ├── Solution.js │ ├── Solution_BinarySearch.java │ ├── Solution_DP.java │ ├── Solution_DP.py │ └── Solution_DP_PrintPath.py ├── 89.k Sum │ ├── README.md │ └── Solution.py ├── 91.Minimum Adjustment Cost │ ├── README.md │ └── Solution.py └── 92.Backpack │ ├── README.md │ └── Solution.py ├── Easy ├── 1. A + B Problem │ ├── README.md │ └── Solution.java ├── 100. Remove Duplicates from Sorted Array │ ├── README.md │ └── Solution.java ├── 101. Remove Duplicates from Sorted Array II │ ├── README.md │ └── Solution.java ├── 1038. Jewels and Stones │ ├── README.md │ ├── Solution.java │ ├── Solution.js │ └── Solution.py ├── 111. Climbing Stairs │ ├── README.md │ └── Solution.py ├── 112. Remove Duplicates from Sorted List │ ├── README.md │ ├── Solution.java │ └── Solution.py ├── 114. Unique Paths │ ├── README.md │ └── Solution.java ├── 1219. Heaters │ ├── README.md │ ├── Solution.java │ └── Solution.py ├── 1231. Minimum Moves to Equal Array Elements │ ├── README.md │ ├── Solution.cpp │ └── Solution.py ├── 13. Implement strStr() │ ├── README.md │ └── Solution.java ├── 1314. Power of Two │ ├── README.md │ └── Solution.java ├── 138. Subarray Sum │ ├── README.md │ ├── Solution.java │ └── Solution.py ├── 14. First Position of Target │ ├── README.md │ ├── Solution.java │ └── Solution.py ├── 141. Sqrt(x) │ ├── README.md │ ├── Solution.java │ └── Solution.py ├── 142. O(1) Check Power of 2 │ ├── README.md │ ├── Solution.cpp │ └── Solution.java ├── 155. Minimum Depth of Binary Tree │ ├── README.md │ └── Solution.py ├── 156. Merge Intervals │ ├── README.md │ └── Solution.java ├── 158. Valid Anagram │ ├── README.md │ ├── Solution.cpp │ ├── Solution.java │ └── Solution.py ├── 1617. Array Maximum Difference │ ├── README.md │ └── Solution.py ├── 165. Merge Two Sorted Lists │ ├── README.md │ └── Solution.py ├── 166. Nth to Last Node in List │ ├── README.md │ └── Solution.py ├── 167. Add Two Numbers │ ├── README.md │ └── Solution.py ├── 172. Remove Element │ ├── README.md │ └── Solution.java ├── 174. Remove Nth Node From End of List │ ├── README.md │ └── Solution.py ├── 175. Invert Binary Tree │ ├── README.md │ ├── Solution.java │ └── Solution.py ├── 181. Flip Bits │ ├── README.md │ └── Solution.java ├── 2. Trailing Zeros │ ├── README.md │ └── Solution.py ├── 209. First Unique Character in a String │ ├── README.md │ └── Solution.py ├── 213. String Compression │ ├── README.md │ └── Solution.py ├── 242. Convert Binary Tree to Linked Lists by Depth │ └── Solution.java ├── 28. Search a 2D Matrix │ ├── README.md │ ├── Solution.java │ └── Solution.py ├── 30. Insert Interval │ ├── README.md │ └── Solution.java ├── 372. Delete Node in a Linked List │ ├── README.md │ └── Solution.java ├── 373. Partition Array by Odd and Even │ ├── README.md │ └── Solution.java ├── 376. Binary Tree Path Sum │ ├── README.md │ └── Solution.java ├── 41. Maximum Subarray │ ├── README.md │ └── Solution.java ├── 413. Reverse Integer │ ├── README.md │ └── Solution.py ├── 415. Valid Palindrome │ ├── README.md │ ├── Solution.cpp │ └── Solution.java ├── 423. Valid Parentheses │ ├── README.md │ ├── Solution.cpp │ └── Solution.py ├── 433. Number of Islands │ ├── README.md │ ├── Solution.java │ └── jiuzhang_solution.java ├── 453. Flatten Binary Tree to Linked List │ ├── README.md │ ├── Solution.java │ └── Solution.py ├── 457. Classical Binary Search │ └── Solution.java ├── 46. Majority Element │ ├── README.md │ └── Solution.py ├── 464. Sort Integers II │ ├── HeapSort.py │ ├── MergeSort.py │ ├── QuickSort.py │ └── README.md ├── 480. Binary Tree Paths │ ├── README.md │ ├── Solution.java │ └── Solution.py ├── 491. Palindrome Number │ ├── README.md │ └── Solution.py ├── 494. Implement Stack by Two Queues │ ├── README.md │ └── Solution.java ├── 50. Product of Array Exclude Itself │ ├── README.md │ └── Solution.java ├── 517. Ugly Number │ └── Soluion.java ├── 521. Remove Duplicate Numbers in Array │ ├── README.md │ └── Solution.java ├── 539. Move Zeroes │ ├── README.md │ └── Solution.java ├── 548. Intersection of Two Arrays II │ ├── README.md │ └── Solution.java ├── 55. Compare Strings │ ├── README.md │ └── Solution.java ├── 56. Two Sum │ ├── README.md │ ├── Solution.java │ └── Solution.py ├── 595. Binary Tree Longest Consecutive Sequence │ ├── README.md │ ├── Solution.java │ └── Solution.py ├── 596. Minimum Subtree │ ├── README.md │ ├── Solution.java │ └── Solution.py ├── 597. Subtree with Maximum Average │ └── Solution.java ├── 6. Merge Two Sorted Arrays │ ├── README.md │ └── Solution.java ├── 60. Search Insert Position │ ├── README.md │ ├── Solution.java │ └── Solution.py ├── 604. Window Sum │ ├── README.md │ └── Solution.java ├── 627. Longest Palindrome │ ├── README.md │ └── Solution.py ├── 661. Convert BST to Greater Tree │ ├── README.md │ ├── Solution.java │ └── Solution.py ├── 662. Guess Number Higher or Lower │ ├── README.md │ ├── Solution.java │ └── Solution.py ├── 764. Calculate Circumference And Area │ └── Solution.java ├── 8. Rotate String │ ├── README.md │ └── Solution.java ├── 82. Single Number │ ├── README.md │ ├── Solution.java │ └── Solution.py ├── 85. Insert Node in a Binary Search Tree │ ├── README.md │ └── Solution.py ├── 9. Fizz Buzz │ ├── README.md │ └── Solution.java ├── 900. Closest Binary Search Tree Value │ ├── README.md │ └── Solution.py ├── 93. Balanced Binary Tree │ ├── README.md │ ├── Solution.java │ └── Solution.py ├── 96. Partition List │ ├── README.md │ ├── Solution.java │ └── Solution.py ├── 97. Maximum Depth of Binary Tree │ ├── README.md │ ├── Solution.java │ └── Solution.py ├── 988. Arranging Coins │ ├── README.md │ ├── Solution.java │ └── Solution.py └── README.txt ├── Greedy └── 871.Minimum Factorization │ ├── README.md │ └── Solution.py ├── Hard ├── 103. Linked List Cycle II │ ├── README.md │ └── Solution.py ├── 180. Binary Representation │ ├── README.md │ └── Solution.java ├── 54. String to Integer (atoi) │ ├── README.md │ └── Solution.java ├── 65. Median of two Sorted Arrays │ ├── README.md │ └── Solution.java ├── 87. Remove Node in Binary Search Tree │ ├── README.md │ └── Solution.py └── README.txt ├── Hash ├── 124.Longest Consecutive Sequence │ ├── README.md │ └── Solution.py ├── 129.Rehashing │ ├── README.md │ └── Solution.py ├── 1318.Contains Duplicate III │ ├── README.md │ ├── Solution_Deque.py │ └── Solution_Hash.py ├── 1319.Contains Duplicate II │ ├── README.md │ └── Solution.py ├── 1320.Contains Duplicate │ ├── README.md │ └── Solution.py ├── 134.LRU Cache │ ├── README.md │ ├── Solution.py │ ├── Solution_DoublyLinkedList.py │ └── Solution_OrderedDict.py ├── 171.Anagrams │ ├── README.md │ └── Solution.py └── 526.Load Balancer │ ├── README.md │ └── Solution.py ├── Heap ├── 104.Merge K Sorted Lists │ ├── README.md │ ├── Solution.java │ ├── Solution_Heap1.py │ └── Solution_Heap2.py ├── 1272.Kth Smallest Element in a Sorted Matrix │ ├── README.md │ └── Solution.py ├── 1281.Top K Frequent Elements │ ├── README.md │ └── Solution.py ├── 130.Heapify │ ├── README.md │ ├── Solution.java │ └── Solution.py ├── 360.Sliding Window Median │ ├── README.md │ ├── Solution_HashHeap.py │ └── Solution_heapq.py ├── 364.Trapping Rain Water II │ ├── README.md │ └── Solution.py ├── 4.Ugly Number II │ ├── README.md │ └── Solution.py ├── 401.Kth Smallest Number in Sorted Matrix │ ├── README.md │ └── Solution.py ├── 465.Kth Smallest Sum In Two Sorted Arrays │ ├── README.md │ └── Solution.py ├── 471.Top K Frequent Words │ ├── README.md │ ├── Solution_MaxHeap.py │ └── Solution_MinHeap.py ├── 486.Merge K Sorted Arrays │ ├── README.md │ ├── Solution_DivideConquer.py │ └── Solution_heapq.py ├── 543.Kth Largest in N Arrays │ ├── README.md │ ├── Solution_MaxHeap.py │ └── Solution_MinHeap.py ├── 544.Top k Largest Numbers │ ├── README.md │ ├── Solution_Heap.java │ ├── Solution_QuickSelect.py │ ├── Solution_QuickSort.java │ └── Solution_heapq.py ├── 545.Top k Largest Numbers II │ ├── README.md │ └── Solution.py ├── 577.Merge K Sorted Interval Lists │ ├── README.md │ ├── Solution_DivideConquer.java │ ├── Solution_DivideConquer.py │ └── Solution_Heap.py ├── 612.K Closest Points │ ├── README.md │ └── Solution.py ├── 613.High Five │ ├── README.md │ └── Solution.py ├── 791.Merge Number │ ├── README.md │ └── Solution.py └── 81.Find Median from Data Stream │ ├── README.md │ ├── Solution_Heap.py │ └── Solution_Heap2.py ├── Interviews ├── amazon │ ├── 1165.Subtree of Another Tree │ │ ├── README.md │ │ └── Solution.py │ ├── 1797.optimalUtilization │ │ ├── README.md │ │ ├── Solution_BinarySearch.py │ │ ├── Solution_BruteForce.java │ │ └── Solution_TwoPointers.py │ ├── 787.The Maze │ │ ├── README.md │ │ └── Solution.py │ └── Treasure Island │ │ ├── README.md │ │ └── Solution_BFS.py └── goldmansachs │ ├── 1134.Find Duplicate File in System │ ├── README.md │ └── Solution.py │ ├── 1375.Substring With At Least K Distinct Characters │ ├── README.md │ └── Solution.py │ ├── 1790.Rotate String II │ ├── README.md │ └── Solution.py │ ├── 1802.Grid Game │ ├── README.md │ └── Solution.py │ ├── 1804.Find The Rank │ ├── README.md │ ├── Solution_Heap.py │ └── Solution_Sort.py │ └── 769.Spiral Array │ ├── README.md │ └── Solution.java ├── LICENSE ├── Linked_List ├── 102.Linked List Cycle │ ├── README.md │ ├── Solution.java │ └── Solution.py ├── 105.Copy List with Random Pointer │ ├── README.md │ ├── Solution.java │ ├── Solution_O1.py │ └── Solution_On.py ├── 106.Convert Sorted List to Binary Search Tree │ ├── README.md │ └── Solution.py ├── 1292.Odd Even Linked List │ ├── README.md │ └── Solution.py ├── 165.Merge Two Sorted Lists │ ├── README.md │ └── Solution.py ├── 170.Rotate List │ ├── README.md │ ├── Solution.java │ └── Solution.py ├── 35.Reverse Linked List │ ├── README.md │ ├── Solution.cpp │ ├── Solution.java │ └── Solution.py ├── 36.Reverse Linked List II │ ├── README.md │ ├── Solution.java │ └── Solution.py ├── 372.Delete Node in a Linked List │ ├── README.md │ └── Solution.py ├── 380.Intersection of Two Linked Lists │ ├── README.md │ ├── Solution.java │ └── Solution.py ├── 450.Reverse Nodes in k-Group │ ├── README.md │ ├── Solution.java │ └── Solution.py ├── 511.Swap Two Nodes in Linked List │ ├── README.md │ └── Solution.py ├── 96.Partition List │ ├── README.md │ └── Solution.py ├── 98.Sort List │ ├── README.md │ └── Solution.py └── 99.Reorder List │ ├── README.md │ └── Solution.py ├── Math ├── 1095.Maximum Swap │ ├── README.md │ ├── Solution_1.py │ └── Solution_2.py ├── 1277.Water and Jug Problem │ ├── README.md │ └── Solution.py └── 730.Sum of All Subsets │ ├── README.md │ └── Solution.py ├── Medium ├── 105. Copy List with Random Pointer │ ├── README.md │ ├── Solution.java │ └── Solution.py ├── 106. Convert Sorted List to Binary Search Tree │ ├── README.md │ └── Solution.py ├── 11. Search Range in Binary Search Tree │ ├── README.md │ └── Solution.py ├── 113. Remove Duplicates from Sorted List II │ ├── README.md │ ├── Solution.java │ └── Solution.py ├── 116. Jump Game │ ├── README.md │ ├── Solution.java │ └── Solution.py ├── 117. Jump Game II │ ├── README.md │ ├── Solution.java │ └── Solution.py ├── 127. Topological Sorting │ ├── README.md │ └── Solution.java ├── 130. Heapify │ ├── README.md │ ├── Solution.java │ └── Solution.py ├── 135. Combination Sum │ └── Solution.java ├── 137. Clone Graph │ ├── JiuZhang_Solution.java │ ├── README.md │ └── Solution.java ├── 139. Subarray Sum Closest │ ├── README.md │ └── Solution.java ├── 140. Fast Power │ ├── README.md │ └── Solution.java ├── 143. Sort Colors II │ ├── README.md │ └── Solution.java ├── 144. Interleaving Positive and Negative Numbers │ ├── README.md │ └── Solution.java ├── 148. Sort Colors │ ├── README.md │ └── Solution.java ├── 153. Combination Sum II │ ├── README.md │ └── Solution.java ├── 159. Find Minimum in Rotated Sorted Array │ ├── README.md │ ├── Solution.java │ └── Solution.py ├── 160. Find Minimum in Rotated Sorted Array II │ ├── README.md │ ├── Solution.java │ └── Solution.py ├── 163. Unique Binary Search Trees │ ├── README.md │ ├── Solution.cpp │ └── Solution.py ├── 164. Unique Binary Search Trees II │ ├── README.md │ ├── Solution.java │ └── Solution.py ├── 170. Rotate List │ ├── README.md │ ├── Solution.java │ └── Solution.py ├── 171. Anagrams │ ├── README.md │ └── Solution.java ├── 178. Graph Valid Tree │ ├── README.md │ └── Solution.java ├── 179. Update Bits │ ├── README.md │ ├── Solution.cpp │ └── Solution.java ├── 182. Delete Digits │ ├── README.md │ ├── Solution.cpp │ └── Solution.py ├── 184. Largest Number │ ├── README.md │ └── Solution.java ├── 187. Gas Station │ ├── README.md │ ├── Solution.cpp │ └── Solution.py ├── 189. First Missing Positive │ ├── README.md │ ├── Solution.java │ └── Solution.py ├── 31. Partition Array │ ├── README.md │ └── Solution.java ├── 33. N-Queens │ ├── README.md │ └── Solution.java ├── 363. Trapping Rain Water │ ├── README.md │ └── Solution.py ├── 38. Search a 2D Matrix II │ ├── README.md │ └── Solution.py ├── 380. Intersection of Two Linked Lists │ ├── README.md │ └── Solution.java ├── 384. Longest Substring Without Repeating Characters │ ├── README.md │ └── Solution.go ├── 414. Divide Two Integers │ ├── README.md │ └── Solution.py ├── 427. Generate Parentheses │ ├── README.md │ └── Solution.java ├── 428. Pow(x, n) │ ├── README.md │ └── Solution.py ├── 443. Two Sum - Greater than target │ ├── README.md │ └── Solution.java ├── 461. Kth Smallest Numbers in Unsorted Array │ ├── README.md │ └── Solution.java ├── 47. Majority Element II │ ├── README.md │ └── Solution.py ├── 48. Majority Number III │ ├── README.md │ └── Solution.py ├── 49. Sort Letters by Case │ ├── README.md │ └── Solution.java ├── 51. Previous Permutation │ ├── README.md │ ├── Solution.java │ └── Solution.py ├── 52. Next Permutation │ ├── README.md │ ├── Solution.cpp │ ├── Solution.java │ └── Solution.py ├── 57. 3Sum │ ├── README.md │ ├── Solution.java │ └── Solution.py ├── 575. Decode String │ ├── README.md │ └── Solution.java ├── 58. 4Sum │ ├── README.md │ └── Solution.java ├── 59. 3Sum Closest │ ├── README.md │ └── Solution.java ├── 598. Zombie in Matrix │ ├── README.md │ └── Solution.java ├── 605. Sequence Reconstruction │ ├── README.md │ └── Solution.java ├── 608. Two Sum II - Input array is sorted │ ├── README.md │ └── Solution.java ├── 609. Two Sum - Less than or equal to target │ ├── README.md │ └── Solution.java ├── 61. Search for a Range │ ├── README.md │ ├── Solution.java │ └── Solution.py ├── 614. Binary Tree Longest Consecutive Sequence II │ └── Solution.java ├── 615. Course Schedule │ ├── README.md │ └── Solution.java ├── 616. Course Schedule II │ ├── README.md │ └── Solution.java ├── 618. Search Graph Nodes │ └── Solution.java ├── 62. Search in Rotated Sorted Array │ ├── README.md │ ├── Solution.java │ └── Solution.py ├── 63. Search in Rotated Sorted Array II │ ├── README.md │ └── Solution.py ├── 669. Coin Change │ ├── README.md │ ├── Solution.java │ └── Solution.py ├── 7. Serialize and Deserialize Binary Tree │ ├── README.md │ ├── Solution.java │ └── Solution.py ├── 70. Binary Tree Level Order Traversal II │ ├── README.md │ ├── Solution.java │ └── Solution.py ├── 71. Binary Tree Zigzag Level Order Traversal │ ├── README.md │ ├── Solution.java │ └── Solution.py ├── 72. Construct Binary Tree from Inorder and Postorder Traversal │ ├── README.md │ └── Solution.java ├── 73. Construct Binary Tree from Preorder and Inorder Traversal │ ├── README.md │ └── Solution.java ├── 74. First Bad Version │ ├── README.md │ ├── Solution.java │ └── Solution.py ├── 75. Find Peak Element │ ├── README.md │ ├── Solution.java │ └── Solution.py ├── 76. Longest Increasing Subsequence │ ├── README.md │ └── Solution.java ├── 77. Longest Common Subsequence │ ├── README.md │ ├── Solution.java │ └── lcs.png ├── 78. Longest Common Prefix │ ├── README.md │ └── Solution.java ├── 79. Longest Common Substring │ ├── README.md │ └── Solution.java ├── 83. Single Number II │ ├── README.md │ └── Solution.java ├── 84. Single Number III │ ├── README.md │ └── Solution.py ├── 840. Range Sum Query - Mutable │ ├── README.md │ └── Solution.cpp ├── 88. Lowest Common Ancestor of a Binary Tree │ └── Solution.java ├── 95. Validate Binary Search Tree │ ├── README.md │ └── Solution.py ├── 98. Sort List │ ├── README.md │ └── Solution.py ├── 99. Reorder List │ ├── README.md │ └── Solution.py └── README.txt ├── Naive ├── 145.Lowercase to Uppercase │ ├── README.md │ └── Solution.java ├── 366.Fibonacci │ ├── README.md │ └── Solution.java ├── 37.Reverse 3-digit Integer │ ├── README.md │ └── Solution.java ├── 452.Remove Linked List Elements │ └── Solution.java ├── 454.Rectangle Area │ └── Solution.java ├── 463.Sort Integers │ └── Solution.java ├── 466.Count Linked List Nodes │ └── Solution.java ├── 479.Second Max of Array │ └── Solution.java ├── 484.Swap Two Integers in Array │ └── Solution.java ├── 632.Binary Tree Maximum Node │ └── Solution.java └── 763.Hex Conversion │ ├── README.md │ └── Solution.java ├── Others ├── 1022.Valid Tic-Tac-Toe State │ ├── README.md │ └── Solution.py └── 842.Origami │ ├── README.md │ └── Solution.py ├── README.md ├── Sort ├── 5.Kth Largest Element │ ├── README.md │ └── Solution.py ├── 80.Median │ ├── README.md │ └── Solution.py └── 894.Pancake Sorting │ ├── README.md │ └── Solution.py ├── Stack ├── 1116.Exclusive Time of Functions │ ├── README.md │ └── Solution.py ├── 12.Min Stack │ ├── README.md │ ├── Solution.py │ ├── Solution_1.cpp │ ├── Solution_2.cpp │ ├── Solution_3.cpp │ └── Solution_SingleStack.py ├── 122.Largest Rectangle in Histogram │ ├── README.md │ ├── Solution_MonotonousStack_1.py │ ├── Solution_MonotonousStack_2.py │ └── Solution_On2.java ├── 126.Max Tree │ ├── README.md │ ├── Solution_DFS.py │ ├── Solution_Stack.java │ └── Solution_Stack.py ├── 224.Implement Three Stacks by Single Array │ ├── README.md │ └── Solution.py ├── 229.Stack Sorting │ ├── README.md │ └── Solution.py ├── 40.Implement Queue by Two Stacks │ ├── README.md │ └── Solution.py ├── 494.Implement Stack by Two Queues │ ├── README.md │ └── Solution.py ├── 495.Implement Stack │ ├── README.md │ └── Solution.py ├── 510.Maximal Rectangle │ ├── README.md │ └── Solution.py ├── 528.Flatten Nested List Iterator │ ├── README.md │ ├── Solution_Deque.py │ └── Solution_Stack.py ├── 540.Zigzag Iterator │ ├── README.md │ └── Solution.py ├── 541.Zigzag Iterator II │ ├── README.md │ └── Solution.py ├── 575.Decode String │ ├── README.md │ ├── Solution_DFS.py │ └── Solution_Stack.py ├── 601.Flatten 2D Vector │ ├── README.md │ ├── Solution_Deque.py │ └── Solution_Stack.py ├── 955.Implement Queue by Circular Array │ ├── README.md │ └── Solution.py └── 978.Basic Calculator │ ├── README.md │ └── Solution.py ├── String ├── 1041.Reorganize String │ ├── README.md │ ├── Solution.java │ └── Solution.py ├── 1173.Reverse Words in a String III │ ├── README.md │ └── Solution.py ├── 1176.Optimal Division │ ├── README.md │ └── Solution.py ├── 1190.Longest Word in Dictionary through Deleting │ ├── README.md │ └── Solution.py ├── 53.Reverse Words in a String │ ├── README.md │ └── Solution.py ├── 640.One Edit Distance │ ├── README.md │ ├── Solution.py │ └── Solution_DP.py ├── 646.First Position Unique Character │ ├── README.md │ └── Solution.py ├── 78.Longest Common Prefix │ ├── README.md │ ├── Solution.py │ └── Solution_Trie.py ├── 784.The Longest Common Prefix II │ ├── README.md │ └── Solution.py ├── 8.Rotate String │ ├── README.md │ └── Solution.py └── 927.Reverse Words in a String II │ ├── README.md │ ├── Solution.java │ └── Solution.py ├── Sweep_Line ├── 131.The Skyline Problem │ ├── README.md │ ├── Solution.HashHeap.py │ ├── Solution.py │ ├── Solution_Multiset.cpp │ └── Solution_TreeSet.java ├── 391.Number of Airplanes in the Sky │ ├── README.md │ └── Solution.py ├── 821.Time Intersection │ ├── README.md │ └── Solution.py ├── 919.Meeting Rooms II │ ├── README.md │ └── Solution.py └── 920.Meeting Rooms │ ├── README.md │ └── Solution.py ├── Tree ├── 1003.Binary Tree Pruning │ ├── README.md │ └── Solution.py ├── 11.Search Range in Binary Search Tree │ ├── README.md │ └── Solution.py ├── 1101.Maximum Width of Binary Tree │ ├── README.md │ ├── Solution_BFS.py │ └── Solution_DFS.py ├── 1197.Find Bottom Left Tree Value │ ├── README.md │ └── Solution.py ├── 1311.Lowest Common Ancestor of a Binary Search Tree │ ├── README.md │ ├── Solution_DFS.py │ └── Solution_DFS_Pruning.py ├── 1357.Path Sum II │ ├── README.md │ └── Solution.py ├── 246.Binary Tree Path Sum II │ ├── README.md │ └── Solution.py ├── 376.Binary Tree Path Sum │ ├── README.md │ ├── Solution.java │ └── Solution.py ├── 378.Convert Binary Tree to Doubly Linked List │ ├── README.md │ └── Solution.py ├── 448.Inorder Successor in BST │ ├── README.md │ └── Solution.py ├── 453.Flatten Binary Tree to Linked List │ ├── README.md │ ├── Solution.java │ └── Solution.py ├── 468.Symmetric Binary Tree │ ├── README.md │ ├── Solution.java │ └── Solution_BFS.py ├── 470.Tweaked Identical Binary Tree │ ├── README.md │ └── Solution.py ├── 472.Binary Tree Path Sum III │ ├── README.md │ └── Solution.py ├── 474.Lowest Common Ancestor II │ ├── README.md │ └── Solution.py ├── 480.Binary Tree Paths │ ├── README.md │ └── Solution.py ├── 578.Lowest Common Ancestor III │ ├── README.md │ └── Solution.py ├── 595.Binary Tree Longest Consecutive Sequence │ ├── README.md │ ├── Solution.java │ └── Solution.py ├── 596.Minimum Subtree │ ├── README.md │ ├── Solution.java │ └── Solution.py ├── 597.Subtree with Maximum Average │ ├── README.md │ ├── Solution.java │ └── Solution.py ├── 614.Binary Tree Longest Consecutive Sequence II │ ├── README.md │ ├── Solution.java │ └── Solution.py ├── 619.Binary Tree Longest Consecutive Sequence III │ ├── README.md │ └── Solution.py ├── 628.Maximum Subtree │ ├── README.md │ └── Solution.py ├── 649.Binary Tree Upside Down │ ├── README.md │ └── Solution.py ├── 650.Find Leaves of Binary Tree │ ├── README.md │ └── Solution.py ├── 66.Binary Tree Preorder Traversal │ ├── README.md │ ├── Solution.java │ └── Solution.py ├── 67.Binary Tree Inorder Traversal │ ├── README.md │ ├── Solution.java │ └── Solution.py ├── 68.Binary Tree Postorder Traversal │ ├── README.md │ ├── Solution.java │ └── Solution.py ├── 85.Insert Node in a Binary Search Tree │ ├── README.md │ ├── Solution_Non_Recursion.py │ └── Solution_Recursion.py ├── 86.Binary Search Tree Iterator │ ├── README.md │ └── Solution.py ├── 863.Binary Tree Path Sum IV │ ├── README.md │ ├── Solution_2darray.py │ └── Solution_hashmap.py ├── 87.Remove Node in Binary Search Tree │ ├── README.md │ └── Solution.py ├── 88.Lowest Common Ancestor of a Binary Tree │ ├── README.md │ ├── Solution.java │ └── Solution.py ├── 93.Balanced Binary Tree │ ├── README.md │ └── Solution.py ├── 939.Binary Tree Kth Floor Node │ ├── README.md │ └── Solution.py ├── 94.Binary Tree Maximum Path Sum │ ├── README.md │ ├── Solution.java │ └── Solution.py ├── 95.Validate Binary Search Tree │ ├── README.md │ └── Solution.py └── 97.Maximum Depth of Binary Tree │ ├── README.md │ ├── Solution_divide_conquer.py │ └── Solution_traverse.py ├── Trie ├── 1090.Map Sum Pairs │ ├── README.md │ ├── Solution_HashMap.py │ └── Soution_Trie.py ├── 1110.Replace Words │ ├── README.md │ └── Solution.py ├── 132.Word Search II │ ├── README.md │ └── Solution.py ├── 442.Implement Trie (Prefix Tree) │ ├── README.md │ └── Solution.py ├── 473.Add and Search Word - Data structure design │ ├── README.md │ └── Solution.py ├── 559.Trie Service │ ├── README.md │ └── Solution.py └── 634.Word Squares │ ├── README.md │ └── Solution.py ├── Two_Pointers ├── 100.Remove Duplicates from Sorted Array │ ├── README.md │ ├── Solution.java │ └── Solution.py ├── 101.Remove Duplicates from Sorted Array II │ ├── README.md │ ├── Solution.java │ └── Solution.py ├── 1132.Valid Triangle Number │ ├── README.md │ └── Solution.py ├── 1169.Permutation in String │ ├── README.md │ ├── Solution.py │ └── Solution_DFS.py ├── 143.Sort Colors II │ ├── README.md │ └── Solution.py ├── 144.Interleaving Positive and Negative Numbers │ ├── README.md │ └── Solution.py ├── 148.Sort Colors │ ├── README.md │ └── Solution.py ├── 1487.Judging Triangle │ ├── README.md │ └── Solution.py ├── 1636.Aerial Movie │ ├── README.md │ └── Solution.py ├── 32.Minimum Window Substring │ ├── README.md │ └── Solution.py ├── 363.Trapping Rain Water │ ├── README.md │ ├── Solution_Traversal.py │ └── Solution_TwoPointers.py ├── 373.Partition Array by Odd and Even │ ├── README.md │ └── Solution.py ├── 384.Longest Substring Without Repeating Characters │ ├── README.md │ ├── Solution.py │ └── Solution_2.py ├── 386.Longest Substring with At Most K Distinct Characters │ ├── README.md │ └── Solution.py ├── 39.Recover Rotated Sorted Array │ ├── README.md │ └── Solution.py ├── 404.Subarray Sum II │ ├── README.md │ └── Solution.py ├── 406.Minimum Size Subarray Sum │ ├── README.md │ ├── Solution_1.py │ └── Solution_2.py ├── 415.Valid Palindrome │ ├── README.md │ └── Solution.py ├── 443.Two Sum - Greater than target │ ├── README.md │ └── Solution.py ├── 461.Kth Smallest Numbers in Unsorted Array │ ├── README.md │ └── Solution.py ├── 49.Sort Letters by Case │ ├── README.md │ ├── Solution.java │ └── Solution.py ├── 507.Wiggle Sort II │ ├── README.md │ └── Solution.py ├── 521.Remove Duplicate Numbers in Array │ ├── README.md │ ├── Solution_On.py │ └── Solution_Onlogn.py ├── 533.Two Sum - Closest to target │ ├── README.md │ └── Solution.py ├── 539.Move Zeroes │ ├── README.md │ └── Solution.py ├── 56.Two Sum │ ├── README.md │ ├── Solution_HashMap.py │ └── Solution_TwoPointers.py ├── 57.3Sum │ ├── README.md │ └── Solution.py ├── 58.4Sum │ ├── README.md │ └── Solution.py ├── 587.Two Sum - Unique pairs │ ├── README.md │ └── Solution.py ├── 59.3Sum Closest │ ├── README.md │ └── Solution.py ├── 6.Merge Two Sorted Arrays (Merge Sorted Array II) │ ├── README.md │ ├── Solution.java │ └── Solution.py ├── 607.Two Sum III - Data structure design │ ├── README.md │ └── Solution.py ├── 609.Two Sum - Less than or equal to target │ ├── README.md │ └── Solution.py ├── 610.Two Sum - Difference equals to target │ ├── README.md │ └── Solution.py └── 64.Merge Sorted Array │ ├── README.md │ ├── Solution.java │ └── Solution.py ├── Union_Find ├── 1070.Accounts Merge │ ├── README.md │ └── Solution.py ├── 1088.Redundant Connection │ ├── README.md │ └── Solution.py ├── 1257.Evaluate Division │ ├── README.md │ ├── Solution.py │ ├── Solution_BFS.py │ └── Solution_DFS.py ├── 1396.Set Union │ ├── README.md │ └── Solution.py ├── 1569.Social Network │ ├── README.md │ └── Solution.py ├── 434.Number of Islands II │ ├── README.md │ └── Solution.py ├── 589.Connecting Graph │ ├── README.md │ └── Solution_UnionFind.py ├── 590.Connecting Graph II │ ├── README.md │ └── Solution.py ├── 591.Connecting Graph III │ ├── README.md │ └── Solution.py └── 805.Maximum Association Set │ ├── README.md │ └── Solution.py ├── assets └── proj.png ├── big-o-cheatsheet.pdf ├── complexityjava.txt ├── complexitypython.txt └── todolist.md /.editorconfig: -------------------------------------------------------------------------------- 1 | # EditorConfig is awesome: https://EditorConfig.org 2 | 3 | # top-most EditorConfig file 4 | root = true 5 | 6 | # Unix-style newlines with a newline ending every file 7 | [*] 8 | end_of_line = lf 9 | insert_final_newline = true 10 | 11 | # Matches multiple files with brace expansion notation 12 | # Set default charset 13 | [*.{js,py,java}] 14 | charset = utf-8 15 | 16 | # 4 space indentation 17 | [*.py] 18 | indent_style = space 19 | indent_size = 4 20 | 21 | [*.java] 22 | indent_style = space 23 | indent_size = 4 24 | -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "files.exclude": { 3 | "**/.classpath": true, 4 | "**/.project": true, 5 | "**/.settings": true, 6 | "**/.factorypath": true 7 | } 8 | } -------------------------------------------------------------------------------- /Array/1065.My Calendar I/Solution_Array.py: -------------------------------------------------------------------------------- 1 | class MyCalendar: 2 | 3 | def __init__(self): 4 | self.events = [] 5 | 6 | def book(self, start, end): 7 | """ 8 | :type start: int 9 | :type end: int 10 | :rtype: bool 11 | """ 12 | if len(self.events) == 0: 13 | self.events.append([start, end]) 14 | return True 15 | 16 | else: 17 | for event in self.events: 18 | if not (event[1] <= start or event[0] >= end): 19 | return False 20 | 21 | self.events.append([start, end]) 22 | self.events.sort() 23 | return True 24 | 25 | 26 | # Your MyCalendar object will be instantiated and called as such: 27 | # obj = MyCalendar() 28 | # param_1 = obj.book(start,end) -------------------------------------------------------------------------------- /Array/1287.Increasing Triplet Subsequence/README.md: -------------------------------------------------------------------------------- 1 | # 1287. Increasing Triplet Subsequence 2 | 3 | **Description** 4 | 5 | Given an unsorted array return whether an increasing subsequence of length `3` exists or not in the array. 6 | 7 | Formally the function should: 8 | 9 | - Return true if there exists `i`, `j`, `k` 10 | - such that `arr[i] < arr[j] < arr[k]` given `0 <= i < j < k <= n - 1` else return false. 11 | - Your algorithm should run in `O(n)` time complexity and `O(1)` space complexity. 12 | 13 | **Example** 14 | 15 | Example 1 16 | 17 | ``` 18 | Input: [1, 2, 3, 4, 5] 19 | Output: true 20 | ``` 21 | 22 | Example 2 23 | 24 | ``` 25 | Input: [5, 4, 3, 2, 1] 26 | Output: false 27 | ``` -------------------------------------------------------------------------------- /Array/1287.Increasing Triplet Subsequence/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | @param nums: a list of integers 4 | @return: return a boolean 5 | """ 6 | 7 | def increasingTriplet(self, nums): 8 | # write your code 9 | if not nums or len(nums) < 3: 10 | return False 11 | 12 | smallest, second_smallest = sys.maxsize, sys.maxsize 13 | for num in nums: 14 | if num <= smallest: 15 | second_smallest = smallest 16 | smallest = num 17 | 18 | elif num <= second_smallest: 19 | second_smallest = num 20 | 21 | else: 22 | return True 23 | 24 | return False 25 | -------------------------------------------------------------------------------- /Array/138.Subarray Sum/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | @param nums: A list of integers 4 | @return: A list of integers includes the index of the first number and the index of the last number 5 | """ 6 | 7 | def subarraySum(self, nums): 8 | # write your code here 9 | prefix_sum = {0: -1} 10 | total = 0 11 | for i, num in enumerate(nums): 12 | total += num 13 | if total in prefix_sum: 14 | return prefix_sum[total] + 1, i 15 | prefix_sum[total] = i 16 | 17 | return -1, -1 18 | -------------------------------------------------------------------------------- /Array/149.Best Time to Buy and Sell Stock/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | @param prices: Given an integer array 4 | @return: Maximum profit 5 | """ 6 | def maxProfit(self, prices): 7 | # write your code here 8 | if not prices or len(prices) == 0: 9 | return 0 10 | 11 | min_price, res = sys.maxsize, 0 12 | for price in prices: 13 | min_price = min(min_price, price) 14 | res = max(res, price - min_price) 15 | 16 | return res 17 | -------------------------------------------------------------------------------- /Array/150.Best Time to Buy and Sell Stock II/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | @param prices: Given an integer array 4 | @return: Maximum profit 5 | """ 6 | def maxProfit(self, prices): 7 | # write your code here 8 | if not prices or len(prices) == 0: 9 | return 0 10 | 11 | res = 0 12 | for i in range(1, len(prices)): 13 | if prices[i] > prices[i - 1]: 14 | res = res + (prices[i] - prices[i - 1]) 15 | 16 | return res -------------------------------------------------------------------------------- /Array/156.Merge Intervals/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | Definition of Interval. 3 | class Interval(object): 4 | def __init__(self, start, end): 5 | self.start = start 6 | self.end = end 7 | """ 8 | 9 | class Solution: 10 | """ 11 | @param intervals: interval list. 12 | @return: A new interval list. 13 | """ 14 | def merge(self, intervals): 15 | # write your code here 16 | merged = [] 17 | if not intervals or len(intervals) == 0: 18 | return merged 19 | 20 | intervals = sorted(intervals, key=lambda interval: (interval.start, interval.end)) 21 | for i in range(len(intervals)): 22 | if len(merged) == 0 or merged[-1].end < intervals[i].start: 23 | merged.append(intervals[i]) 24 | else: 25 | merged[-1].end = max(merged[-1].end, intervals[i].end) 26 | 27 | return merged 28 | -------------------------------------------------------------------------------- /Array/402.Continuous Subarray Sum/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | @param: nums: An integer array 4 | @return: A list of integers includes the index of the first number and the index of the last number 5 | """ 6 | def continuousSubarraySum(self, nums): 7 | # write your code here 8 | if not nums or len(nums) == 0: 9 | return [0, 0] 10 | 11 | prefix_sum, min_sum, max_sum = 0, 0, -sys.maxsize 12 | i, j, min_idx = -1, -1, -1 13 | for idx, num in enumerate(nums): 14 | prefix_sum += num 15 | if prefix_sum - min_sum > max_sum: 16 | max_sum = prefix_sum - min_sum 17 | i, j = min_idx + 1, idx 18 | if prefix_sum < min_sum: 19 | min_sum = prefix_sum 20 | min_idx = idx 21 | 22 | return [i, j] 23 | -------------------------------------------------------------------------------- /Array/41.Maximum Subarray/Solution.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | /** 3 | * @param nums: A list of integers 4 | * @return: A integer indicate the sum of max subarray 5 | */ 6 | public int maxSubArray(int[] nums) { 7 | // write your code here 8 | if (nums == null || nums.length == 0) { 9 | return 0; 10 | } 11 | 12 | int max = Integer.MIN_VALUE, minSum = 0, sum = 0, length = nums.length; 13 | 14 | // Prefix Sum 15 | for (int i = 0; i < length; i++) { 16 | sum += nums[i]; 17 | max = Math.max(max, sum - minSum); 18 | minSum = Math.min(minSum, sum); 19 | } 20 | 21 | return max; 22 | } 23 | 24 | } -------------------------------------------------------------------------------- /Array/41.Maximum Subarray/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | @param nums: A list of integers 4 | @return: A integer indicate the sum of max subarray 5 | """ 6 | def maxSubArray(self, nums): 7 | # write your code here 8 | if not nums or len(nums) == 0: 9 | return None 10 | 11 | min_sum, max_sum = 0, -sys.maxsize 12 | prefix_sum = 0 13 | 14 | for num in nums: 15 | prefix_sum += num 16 | max_sum = max(max_sum, prefix_sum - min_sum) 17 | min_sum = min(min_sum, prefix_sum) 18 | 19 | return max_sum 20 | -------------------------------------------------------------------------------- /Array/547.Intersection of Two Arrays/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | @param nums1: an integer array 4 | @param nums2: an integer array 5 | @return: an integer array 6 | """ 7 | def intersection(self, nums1, nums2): 8 | # write your code here 9 | return list(set(nums1) & set(nums2)) -------------------------------------------------------------------------------- /BFS/127.Topological Sorting/Solution_DFS.py: -------------------------------------------------------------------------------- 1 | def topSortDFS(self, graph): 2 | 3 | def dfs(indegree, g, ans): 4 | ans.append(g) 5 | indegree[g] = -1 6 | 7 | for c in g.neighbors: 8 | indegree[c] -= 1 9 | if indegree[c] == 0: 10 | dfs(indegree, c, ans) 11 | 12 | indegree = {} 13 | ans = [] 14 | 15 | for g in graph: 16 | for n in g.neighbors: 17 | if n not in indegree: 18 | indegree[n] = 1 19 | else: 20 | indegree[n] += 1 21 | 22 | for g in graph: 23 | if g not in indegree or indegree[g] == 0: 24 | dfs(indegree, g, ans) 25 | return ans 26 | -------------------------------------------------------------------------------- /BFS/178.Graph Valid Tree/Solution_BFS.cpp: -------------------------------------------------------------------------------- 1 | // bfs version 2 | class Solution { 3 | public: 4 | bool validTree(int n, vector>& edges) { 5 | vector> g(n, unordered_set()); 6 | unordered_set v; 7 | queue q; 8 | q.push(0); 9 | v.insert(0); 10 | for (auto a : edges) { 11 | g[a.first].insert(a.second); 12 | g[a.second].insert(a.first); 13 | } 14 | while (!q.empty()) { 15 | int t = q.front(); q.pop(); 16 | for (auto a : g[t]) { 17 | if (v.find(a) != v.end()) return false; 18 | v.insert(a); 19 | q.push(a); 20 | g[a].erase(t); 21 | } 22 | } 23 | return v.size() == n; 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /BFS/178.Graph Valid Tree/Solution_UnionFind.cpp: -------------------------------------------------------------------------------- 1 | // union find version 2 | class Solution { 3 | public: 4 | /** 5 | * @param n an integer 6 | * @param edges a list of undirected edges 7 | * @return true if it's a valid tree, or false 8 | */ 9 | bool validTree(int n, vector>& edges) { 10 | // Write your code here 11 | vector root(n, -1); 12 | for(int i = 0; i < edges.size(); i++) { 13 | int root1 = find(root, edges[i][0]); 14 | int root2 = find(root, edges[i][1]); 15 | if(root1 == root2) 16 | return false; 17 | root[root1] = root2; 18 | } 19 | return edges.size() == n - 1; 20 | } 21 | int find(vector &root, int e) { 22 | if(root[e] == -1) 23 | return e; 24 | else 25 | return root[e] = find(root, root[e]); 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /BFS/375.Clone Binary Tree/Solution_DFS.py: -------------------------------------------------------------------------------- 1 | """ 2 | Definition of TreeNode: 3 | class TreeNode: 4 | def __init__(self, val): 5 | this.val = val 6 | this.left, this.right = None, None 7 | """ 8 | class Solution: 9 | """ 10 | @param {TreeNode} root: The root of binary tree 11 | @return {TreeNode} root of new tree 12 | """ 13 | def cloneTree(self, root): 14 | # Write your code here 15 | if root is None: 16 | return None 17 | clone_root = TreeNode(root.val) 18 | clone_root.left = self.cloneTree(root.left) 19 | clone_root.right = self.cloneTree(root.right) 20 | return clone_root -------------------------------------------------------------------------------- /Binary_Search/1183.Single Element in a Sorted Array/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | @param nums: a list of integers 4 | @return: return a integer 5 | """ 6 | 7 | def singleNonDuplicate(self, nums): 8 | # write your code here 9 | start, end = 0, len(nums) - 1 10 | while start + 1 < end: 11 | mid = start + (end - start) // 2 12 | if mid % 2 == 0: 13 | if nums[mid + 1] == nums[mid]: 14 | start = mid 15 | else: 16 | end = mid 17 | else: 18 | if nums[mid - 1] == nums[mid]: 19 | start = mid 20 | else: 21 | end = mid 22 | 23 | return nums[start] if start % 2 == 0 else nums[end] 24 | -------------------------------------------------------------------------------- /Binary_Search/14.First Position of Target/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | @param nums: The integer array. 4 | @param target: Target to find. 5 | @return: The first position of target. Position starts from 0. 6 | """ 7 | def binarySearch(self, nums, target): 8 | # write your code here 9 | if nums is None or len(nums) == 0: 10 | return -1 11 | 12 | start, end = 0, len(nums) - 1 13 | while start + 1 < end: 14 | mid = start + (end - start) // 2 15 | if nums[mid] == target: 16 | end = mid 17 | elif nums[mid] < target: 18 | start = mid 19 | else: 20 | end = mid 21 | 22 | if nums[start] == target: 23 | return start 24 | if nums[end] == target: 25 | return end 26 | return -1 27 | -------------------------------------------------------------------------------- /Binary_Search/141.sqrt(x)/Solution.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | /** 3 | * @param x: An integer 4 | * @return: The sqrt of x 5 | */ 6 | public int sqrt(int x) { 7 | // write your code here 8 | if (x < 0) return -1; 9 | if (x == 0) return 0; 10 | 11 | long start = 1, end = x; 12 | 13 | while (start + 1 < end) { 14 | 15 | long mid = (end - start) / 2 + start; 16 | long mul = mid * mid; 17 | 18 | if (mul < x) { 19 | start = mid; 20 | } else if (mul > x) { 21 | end = mid; 22 | } else if (mul == x) { 23 | return (int)mid; 24 | } 25 | } 26 | 27 | if (start * start <= x) { 28 | return (int)start; 29 | } else { 30 | return (int)end; 31 | } 32 | 33 | } 34 | } -------------------------------------------------------------------------------- /Binary_Search/141.sqrt(x)/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | @param x: An integer 4 | @return: The sqrt of x 5 | """ 6 | def sqrt(self, x): 7 | # write your code here 8 | if (x == 0): return x 9 | 10 | start, end = 1, x 11 | 12 | while (start + 1 < end): 13 | mid = (end - start) // 2 + start 14 | 15 | if (mid ** 2 == x): 16 | return mid 17 | elif (mid ** 2 > x): 18 | end = mid 19 | else: 20 | start = mid 21 | 22 | if (start ** 2 <= x): 23 | return start 24 | else: 25 | return end 26 | -------------------------------------------------------------------------------- /Binary_Search/159.Find Minimum in Rotated Sorted Array/Solution.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | /** 3 | * @param nums: a rotated sorted array 4 | * @return: the minimum number in the array 5 | */ 6 | public int findMin(int[] nums) { 7 | // write your code here 8 | 9 | if (nums.length == 0) return -1; 10 | 11 | int start = 0, end = nums.length - 1; 12 | int target = nums[end]; 13 | 14 | while (start + 1 < end) { 15 | int mid = (end - start) / 2 + start; 16 | 17 | if (nums[mid] < target) { 18 | end = mid; 19 | } else { 20 | start = mid; 21 | } 22 | } 23 | 24 | if (nums[start] < target) { 25 | return nums[start]; 26 | } else { 27 | return nums[end]; 28 | } 29 | 30 | 31 | } 32 | } -------------------------------------------------------------------------------- /Binary_Search/159.Find Minimum in Rotated Sorted Array/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | @param nums: a rotated sorted array 4 | @return: the minimum number in the array 5 | """ 6 | def findMin(self, nums): 7 | # write your code here 8 | if not nums or len(nums) == 0: 9 | return None 10 | 11 | start, end = 0, len(nums) - 1 12 | last_number = nums[-1] 13 | while start + 1 < end: 14 | mid = start + (end - start) // 2 15 | if nums[mid] > last_number: 16 | start = mid 17 | else: 18 | end = mid 19 | 20 | if nums[start] < nums[end]: 21 | return nums[start] 22 | return nums[end] 23 | -------------------------------------------------------------------------------- /Binary_Search/160.Find Minimum in Rotated Sorted Array II/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | @param nums: a rotated sorted array 4 | @return: the minimum number in the array 5 | """ 6 | def findMin(self, nums): 7 | # write your code here 8 | if not nums or len(nums) == 0: 9 | return None 10 | 11 | start, end = 0, len(nums) - 1 12 | while start + 1 < end: 13 | while nums[start] == nums[end]: 14 | end -= 1 15 | 16 | mid = start + (end - start) // 2 17 | if nums[mid] > nums[end]: 18 | start = mid 19 | else: 20 | end = mid 21 | 22 | if nums[start] < nums[end]: 23 | return nums[start] 24 | return nums[end] 25 | -------------------------------------------------------------------------------- /Binary_Search/1629.Find the nearest store/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | @param stores: The location of each store. 4 | @param houses: The location of each house. 5 | @return: The location of the nearest store to each house. 6 | """ 7 | 8 | def findNearestStore(self, stores, houses): 9 | sorted_stores = sorted(stores) 10 | results = [] 11 | 12 | for house in houses: 13 | results.append(self._findClosest(house, sorted_stores)) 14 | 15 | return results 16 | 17 | def _findClosest(self, target, stores): 18 | start, end = 0, len(stores) - 1 19 | while start + 1 < end: 20 | mid = start + (end - start) // 2 21 | if stores[mid] <= target: 22 | start = mid 23 | else: 24 | end = mid 25 | 26 | return stores[start] if abs(target - stores[start]) <= abs(target - stores[end]) else stores[end] 27 | -------------------------------------------------------------------------------- /Binary_Search/1791.Simple queries/README.md: -------------------------------------------------------------------------------- 1 | # 1791. Simple queries 2 | 3 | **Description** 4 | 5 | 6 | Give you two arrays, the first array may contains repeatable integers, The second array is a sub of the first array.The length of the returned array is the same as the second array. For each element a in the second array, how many numbers are in the first array `<= a`. 7 | 8 | **Example** 9 | 10 | Example 1: 11 | 12 | ``` 13 | Input: nums = [3, 2, 4, 3, 5, 1],sub = [2, 4] 14 | Output: [2, 5] 15 | Explanation: <=2 numbers are [1,2], <= 4 numbers are [1,2,3,3,4] 16 | ``` 17 | 18 | Example 2: 19 | 20 | ``` 21 | Input: nums = [3, 1, 2, 3, 3, 1], sub = [1,3] 22 | Output: [2, 6] 23 | Explanation: <= 1 numbers are [1,1], <=3 numbers are [1,1,2,3,3,3] 24 | ``` 25 | -------------------------------------------------------------------------------- /Binary_Search/183.Wood Cut/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | @param L: Given n pieces of wood with length L[i] 4 | @param k: An integer 5 | @return: The maximum length of the small pieces 6 | """ 7 | def woodCut(self, L, k): 8 | # write your code here 9 | if not L or not k or len(L) == 0: 10 | return 0 11 | 12 | start, end = 1, max(L) 13 | while start + 1 < end: 14 | mid = start + (end - start) // 2 15 | if self._compute_k(L, mid) >= k: 16 | start = mid 17 | else: 18 | end = mid 19 | 20 | if self._compute_k(L, end) >= k: 21 | return end 22 | if self._compute_k(L, start) >= k: 23 | return start 24 | return 0 25 | 26 | 27 | def _compute_k(self, L, length): 28 | return sum([l // length for l in L]) 29 | -------------------------------------------------------------------------------- /Binary_Search/248.Count of Smaller Number/README.md: -------------------------------------------------------------------------------- 1 | # 248. Count of Smaller Number 2 | 3 | **Description** 4 | 5 | Give you an integer array (index from `0` to `n-1`, where `n` is the size of this array, value from `0` to `10000`) and an query list. For each query, give you an integer, return the number of element in the array that are smaller than the given integer. 6 | 7 | > We suggest you finish problem `Segment Tree Build` and `Segment Tree Query II` first. 8 | 9 | **Example** 10 | 11 | ``` 12 | Example 1: 13 | 14 | Input: array =[1,2,7,8,5] queries =[1,8,5] 15 | Output:[0,4,2] 16 | Example 2: 17 | 18 | Input: array =[3,4,5,8] queries =[2,4] 19 | Output:[0,1] 20 | ``` 21 | 22 | **Challenge** 23 | 24 | Could you use three ways to do it. 25 | 26 | - Just loop 27 | - Sort and binary search 28 | - Build Segment Tree and Search. 29 | 30 | **Related Problems** 31 | 32 | -------------------------------------------------------------------------------- /Binary_Search/457.Classical Binary Search/README.md: -------------------------------------------------------------------------------- 1 | # 457. Classical Binary Search 2 | 3 | **Description** 4 | 5 | Find any position of a target number in a sorted array. Return `-1` if target does not exist. 6 | 7 | **Example** 8 | 9 | ``` 10 | Example 1: 11 | 12 | Input: nums = [1,2,2,4,5,5], target = 2 13 | Output: 1 or 2 14 | 15 | Example 2: 16 | 17 | Input: nums = [1,2,2,4,5,5], target = 6 18 | Output: -1 19 | ``` 20 | 21 | **Challenge** 22 | 23 | O(logn) time 24 | 25 | -------------------------------------------------------------------------------- /Binary_Search/458.Last Position of Target/README.md: -------------------------------------------------------------------------------- 1 | # 458. Last Position of Target 2 | 3 | **Description** 4 | 5 | Find the last position of a target number in a sorted array. Return -1 if target does not exist. 6 | 7 | **Example** 8 | 9 | ``` 10 | Example 1: 11 | 12 | Input: nums = [1,2,2,4,5,5], target = 2 13 | Output: 2 14 | 15 | Example 2: 16 | 17 | Input: nums = [1,2,2,4,5,5], target = 6 18 | Output: -1 19 | ``` 20 | -------------------------------------------------------------------------------- /Binary_Search/458.Last Position of Target/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | @param nums: An integer array sorted in ascending order 4 | @param target: An integer 5 | @return: An integer 6 | """ 7 | def lastPosition(self, nums, target): 8 | # write your code here 9 | if nums is None or len(nums) == 0: 10 | return -1 11 | 12 | start, end = 0, len(nums) - 1 13 | while start + 1 < end: 14 | mid = start + (end - start) // 2 15 | if nums[mid] == target: 16 | start = mid 17 | elif nums[mid] < target: 18 | start = mid 19 | else: 20 | end = mid 21 | 22 | if nums[end] == target: 23 | return end 24 | if nums[start] == target: 25 | return start 26 | return -1 -------------------------------------------------------------------------------- /Binary_Search/460.Find K Closest Elements/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | @param A: an integer array 4 | @param target: An integer 5 | @param k: An integer 6 | @return: an integer array 7 | """ 8 | def kClosestNumbers(self, A, target, k): 9 | # write your code here 10 | if not A or len(A) == 0: 11 | return None 12 | 13 | diff = [abs(e - target) for e in A] 14 | results = [a for _, a in sorted(zip(diff, A))] 15 | return results[:k] 16 | -------------------------------------------------------------------------------- /Binary_Search/462.Total Occurrence of Target/README.md: -------------------------------------------------------------------------------- 1 | # 462. Total Occurrence of Target 2 | 3 | **Description** 4 | 5 | Given a target number and an integer array sorted in ascending order. Find the total number of occurrences of target in the array. 6 | 7 | Have you met this question in a real interview? 8 | Example 9 | Example1: 10 | 11 | Input: [1, 3, 3, 4, 5] and target = 3, 12 | Output: 2. 13 | Example2: 14 | 15 | Input: [2, 2, 3, 4, 6] and target = 4, 16 | Output: 1. 17 | Example3: 18 | 19 | Input: [1, 2, 3, 4, 5] and target = 6, 20 | Output: 0. 21 | Challenge 22 | Time complexity in O(logn) 23 | 24 | -------------------------------------------------------------------------------- /Binary_Search/585.Maximum Number in Mountain Sequence/README.md: -------------------------------------------------------------------------------- 1 | # 585. Maximum Number in Mountain Sequence 2 | 3 | https://www.lintcode.com/problem/maximum-number-in-mountain-sequence/description 4 | 5 | **Description** 6 | 7 | Given a mountain sequence of `n` integers which increase firstly and then decrease, find the mountain top. 8 | 9 | **Example** 10 | 11 | ``` 12 | Example 1: 13 | 14 | Input: nums = [1, 2, 4, 8, 6, 3] 15 | Output: 8 16 | Example 2: 17 | 18 | Input: nums = [10, 9, 8, 7], 19 | Output: 10 20 | ``` 21 | 22 | **Related Problems** 23 | 24 | 75.Find Peak Elements 25 | 26 | 27 | 先上升在下降中间一定存在峰值, 没说有没有 duplicate numbers 哦 -------------------------------------------------------------------------------- /Binary_Search/585.Maximum Number in Mountain Sequence/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | @param nums: a mountain sequence which increase firstly and then decrease 4 | @return: then mountain top 5 | """ 6 | def mountainSequence(self, nums): 7 | # write your code here 8 | if not nums or len(nums) == 0: 9 | return None 10 | 11 | start, end = 0, len(nums) - 1 12 | while start + 1 < end: 13 | mid = start + (end - start) // 2 14 | if nums[mid] > nums[mid - 1] and nums[mid] > nums[mid + 1]: 15 | return nums[mid] 16 | elif nums[mid] > nums[mid - 1] and nums[mid] < nums[mid + 1]: 17 | start = mid 18 | else: 19 | end = mid 20 | 21 | if nums[start] > nums[end]: 22 | return nums[start] 23 | return nums[end] 24 | -------------------------------------------------------------------------------- /Binary_Search/586.Sqrt(x) II/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | @param x: a double 4 | @return: the square root of x 5 | """ 6 | def sqrt(self, x): 7 | # write your code here 8 | if not x: 9 | return 10 | 11 | left, right = 0, max(1, x) 12 | while right - left > 1e-10: 13 | mid = left + (right - left) / 2 14 | if mid * mid == x: 15 | return mid 16 | elif mid * mid < x: 17 | left = mid 18 | else: 19 | right = mid 20 | 21 | return left -------------------------------------------------------------------------------- /Binary_Search/60.Search Insert Position/README.md: -------------------------------------------------------------------------------- 1 | # 60. Search Insert Position 2 | 3 | **Description** 4 | 5 | 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. 6 | 7 | You may assume **NO** duplicates in the array. 8 | 9 | 10 | **Example** 11 | 12 | ``` 13 | [1,3,5,6], 5 -> 2 14 | 15 | [1,3,5,6], 2 -> 1 16 | 17 | [1,3,5,6], 7 -> 4 18 | 19 | [1,3,5,6], 0 -> 0 20 | ``` 21 | 22 | **Challenge** 23 | 24 | `O(log(n))` time -------------------------------------------------------------------------------- /Binary_Search/60.Search Insert Position/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | @param A: an integer sorted array 4 | @param target: an integer to be inserted 5 | @return: An integer 6 | """ 7 | def searchInsert(self, A, target): 8 | # write your code here 9 | # find the index where A[index] is the first number greater than target. 10 | if A is None or len(A) == 0: 11 | return 0 12 | 13 | start, end = 0, len(A) - 1 14 | while start + 1 < end: 15 | mid = start + (end - start) // 2 16 | if A[mid] >= target: 17 | end = mid 18 | else: 19 | start = mid 20 | 21 | if A[start] >= target: 22 | return start 23 | if A[end] >= target: 24 | return end 25 | return len(A) 26 | -------------------------------------------------------------------------------- /Binary_Search/602.Russian Doll Envelopes/Solution_BinarySearch.py: -------------------------------------------------------------------------------- 1 | from bisect import bisect_left 2 | 3 | class Solution: 4 | """ 5 | @param: envelopes: a number of envelopes with widths and heights 6 | @return: the maximum number of envelopes 7 | """ 8 | def maxEnvelopes(self, envelopes): 9 | # write your code here 10 | if not envelopes or len(envelopes) == 0: 11 | return 0 12 | 13 | sorted_envelopes = sorted(envelopes, key=lambda x: (x[0], -x[1])) 14 | 15 | lis, length = [0 for _ in range(len(envelopes))], 0 16 | for w, h in sorted_envelopes: 17 | idx = bisect_left(lis, h, 0, length) 18 | lis[idx] = h 19 | 20 | if idx == length: 21 | length += 1 22 | 23 | return length 24 | -------------------------------------------------------------------------------- /Binary_Search/61.Search for a Range/README.md: -------------------------------------------------------------------------------- 1 | 61. Search for a Range 2 | 3 | **Description** 4 | 5 | Given a sorted array of n integers, find the starting and ending position of a given target value. 6 | 7 | If the target is not found in the array, return [-1, -1]. 8 | 9 | **Example** 10 | 11 | ``` 12 | Example 1: 13 | 14 | Input: 15 | [] 16 | 9 17 | Output: 18 | [-1,-1] 19 | 20 | Example 2: 21 | 22 | Input: 23 | [5, 7, 7, 8, 8, 10] 24 | 8 25 | Output: 26 | [3, 4] 27 | ``` 28 | 29 | **Challenge** 30 | 31 | `O(log n)` time. -------------------------------------------------------------------------------- /Binary_Search/633.Find the Duplicate Number/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | @param nums: an array containing n + 1 integers which is between 1 and n 4 | @return: the duplicate one 5 | """ 6 | def findDuplicate(self, nums): 7 | # write your code here 8 | if not nums or len(nums) == 0: 9 | return 0 10 | 11 | lo, hi = 1, len(nums) - 1 12 | while lo + 1 < hi: 13 | mid = lo + (hi - lo) // 2 14 | if self.count(nums, mid) <= mid: 15 | lo = mid 16 | else: 17 | hi = mid 18 | 19 | if self.count(nums, lo) <= lo: 20 | return hi 21 | return lo 22 | 23 | def count(self, nums, target): 24 | cnt = 0 25 | for num in nums: 26 | if num <= target: 27 | cnt += 1 28 | return cnt 29 | -------------------------------------------------------------------------------- /Binary_Search/74.First Bad Version/Solution.py: -------------------------------------------------------------------------------- 1 | # class SVNRepo: 2 | # @classmethod 3 | # def isBadVersion(cls, id) 4 | # # Run unit tests to check whether verison `id` is a bad version 5 | # # return true if unit tests passed else false. 6 | # You can use SVNRepo.isBadVersion(10) to check whether version 10 is a 7 | # bad version. 8 | class Solution: 9 | """ 10 | @param n: An integer 11 | @return: An integer which is the first bad version. 12 | """ 13 | def findFirstBadVersion(self, n): 14 | # write your code here 15 | start, end = 1, n 16 | while start + 1 < end: 17 | mid = start + (end - start) // 2 18 | 19 | if SVNRepo.isBadVersion(mid): 20 | end = mid 21 | else: 22 | start = mid 23 | 24 | if SVNRepo.isBadVersion(start): 25 | return start 26 | return end 27 | -------------------------------------------------------------------------------- /Binary_Search/75.Find Peak Element/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | @param: A: An integers array. 4 | @return: return any of peek positions. 5 | """ 6 | def findPeak(self, A): 7 | # write your code here 8 | start, end = 0, len(A) - 1 9 | while (start + 1 < end): 10 | P = (start + end) // 2 11 | 12 | # A[mid] is one of peaks 13 | if A[P] > A[P - 1] and A[P] > A[P + 1]: 14 | return P 15 | # Ascending area 16 | elif A[P] > A[P - 1] and A[P] < A[P + 1]: 17 | start = P 18 | # Descending area 19 | else: 20 | end = P 21 | 22 | return start if A[start] >= A[end] else end 23 | -------------------------------------------------------------------------------- /Binary_Search/76.Longest Increasing Subsequence/Solution.py: -------------------------------------------------------------------------------- 1 | from bisect import bisect_left 2 | 3 | class Solution: 4 | """ 5 | @param nums: An integer array 6 | @return: The length of LIS (longest increasing subsequence) 7 | """ 8 | def longestIncreasingSubsequence(self, nums): 9 | # write your code here 10 | if not nums or len(nums) == 0: 11 | return 0 12 | 13 | arr = [0 for _ in range(len(nums))] 14 | 15 | length = 0 16 | for num in nums: 17 | idx = bisect_left(arr, num, 0, length) 18 | 19 | arr[idx] = num 20 | 21 | if idx == length: 22 | length += 1 23 | 24 | return length 25 | -------------------------------------------------------------------------------- /Binary_Search/937.How Many Problem Can I Accept/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | @param n: an integer 4 | @param k: an integer 5 | @return: how many problem can you accept 6 | """ 7 | 8 | def canAccept(self, n, k): 9 | # Write your code here 10 | # range of number of problems can be solved 11 | self.k = k 12 | start, end = 0, n 13 | while start + 1 < end: 14 | mid = start + (end - start) // 2 15 | if self._computeSum(mid) <= n: 16 | start = mid 17 | else: 18 | end = mid 19 | 20 | if self._computeSum(end) <= n: 21 | return end 22 | if self._computeSum(start) <= n: 23 | return start 24 | 25 | return -1 26 | 27 | def _computeSum(self, endIndex): 28 | return endIndex * (endIndex + 1) / 2 * self.k 29 | -------------------------------------------------------------------------------- /Bit_Manipulation/1. A + B Problem/Solution.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | /** 3 | * @param a: An integer 4 | * @param b: An integer 5 | * @return: The sum of a and b 6 | */ 7 | public int aplusb(int a, int b) { 8 | // write your code here 9 | int result = a ^ b; // + without carry 0+0=0, 0+1=1+0=1, 1+1=0 10 | int carry = (a & b) << 1; // 1 + 1 = 2 11 | if (carry != 0) { 12 | return aplusb(result, carry); 13 | } 14 | return result; 15 | } 16 | } -------------------------------------------------------------------------------- /Bit_Manipulation/82.Single Number/Solution_BinarySearch.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | @param A: An integer array 4 | @return: An integer 5 | """ 6 | def singleNumber(self, A): 7 | # write your code here 8 | if not A or len(A) == 0: 9 | return -1 10 | 11 | A.sort() 12 | 13 | left, right = 0, len(A) - 1 14 | while left + 1 < right: 15 | mid = left + (right - left) // 2 16 | if mid % 2 == 0: 17 | if A[mid] != A[mid + 1]: 18 | right = mid 19 | else: 20 | left = mid 21 | else: 22 | if mid >= 1 and A[mid] != A[mid - 1]: 23 | right = mid 24 | else: 25 | left = mid 26 | 27 | return A[left] if left % 2 == 0 else A[right] 28 | -------------------------------------------------------------------------------- /Bit_Manipulation/82.Single Number/Solution_Counter.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | @param A: An integer array 4 | @return: An integer 5 | """ 6 | def singleNumber(self, A): 7 | # write your code here 8 | dict = collections.Counter(A) 9 | for key in dict: 10 | if dict[key] == 1: 11 | return key 12 | -------------------------------------------------------------------------------- /Bit_Manipulation/82.Single Number/Solution_XOR.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | /** 3 | * @param A: An integer array 4 | * @return: An integer 5 | */ 6 | public int singleNumber(int[] A) { 7 | // write your code here 8 | int result = 0, n = A.length; 9 | for (int i = 0; i < n; i++) { 10 | result ^= A[i]; 11 | } 12 | return result; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /Bit_Manipulation/824.Single Number IV/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | @param nums: The number array 4 | @return: Return the single number 5 | """ 6 | def getSingleNumber(self, nums): 7 | # Write your code here 8 | if not nums or len(nums) == 0: 9 | return -1 10 | 11 | left, right = 0, len(nums) - 1 12 | while left + 1 < right: 13 | mid = left + (right - left) // 2 14 | if mid % 2 == 0: 15 | if nums[mid] != nums[mid + 1]: 16 | right = mid 17 | else: 18 | left = mid 19 | else: 20 | if mid >= 1 and nums[mid] != nums[mid - 1]: 21 | right = mid 22 | else: 23 | left = mid 24 | 25 | return nums[left] if left % 2 == 0 else nums[right] 26 | -------------------------------------------------------------------------------- /Bit_Manipulation/83.Single Number II/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | @param A: An integer array 4 | @return: An integer 5 | """ 6 | def singleNumberII(self, A): 7 | # write your code here 8 | if not A or len(A) % 3 != 1: 9 | return -1 10 | 11 | bits = [0 for _ in range(32)] 12 | for a in A: 13 | for j in range(32): 14 | if ((1 << j) & a) > 0: 15 | bits[j] += 1 16 | 17 | ans = 0 18 | for i in range(32): 19 | t = bits[i] % 3 20 | if t == 1: 21 | ans = ans + (1 << i) 22 | 23 | return ans -------------------------------------------------------------------------------- /Bit_Manipulation/84.Single Number III/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | @param A: An integer array 4 | @return: An integer array 5 | """ 6 | def singleNumberIII(self, A): 7 | # write your code here 8 | if A is None or len(A) % 2 != 0: 9 | return [] 10 | 11 | xor = 0 12 | for num in A: 13 | xor ^= num 14 | 15 | diff = xor & (~ (xor - 1)) 16 | res = [0] * 2 17 | for num in A: 18 | if num & diff == 0: 19 | res[0] ^= num 20 | else: 21 | res[1] ^= num 22 | 23 | return res 24 | -------------------------------------------------------------------------------- /DFS/1031.Is Graph Bipartite/Solution_DFS.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | @param graph: the given undirected graph 4 | @return: return true if and only if it is bipartite 5 | """ 6 | def isBipartite(self, graph): 7 | # Write your code here 8 | if not graph or len(graph) == 0: 9 | return False 10 | 11 | n = len(graph) 12 | self.colors = [0 for _ in range(n)] 13 | 14 | for i in range(n): 15 | if self.colors[i] == 0 and not self._colorize(i, 1, graph): 16 | return False 17 | 18 | return True 19 | 20 | 21 | def _colorize(self, current, color, graph): 22 | if self.colors[current] != 0: 23 | return self.colors[current] == color 24 | 25 | self.colors[current] = color 26 | for neighbor in graph[current]: 27 | if not self._colorize(neighbor, - color, graph): 28 | return False 29 | return True 30 | -------------------------------------------------------------------------------- /DFS/1106.Maximum Binary Tree/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | Definition of TreeNode: 3 | class TreeNode: 4 | def __init__(self, val): 5 | self.val = val 6 | self.left, self.right = None, None 7 | """ 8 | 9 | class Solution: 10 | """ 11 | @param nums: an array 12 | @return: the maximum tree 13 | """ 14 | def constructMaximumBinaryTree(self, nums): 15 | # Write your code here 16 | if not nums or len(nums) == 0: 17 | return None 18 | 19 | return self._dfs(nums) 20 | 21 | def _dfs(self, nums): 22 | if not nums or len(nums) == 0: 23 | return 24 | 25 | 26 | rootNum = max(nums) 27 | left = nums[:nums.index(rootNum)] 28 | right = nums[nums.index(rootNum) + 1: ] 29 | 30 | 31 | root = TreeNode(rootNum) 32 | root.right = self._dfs(right) 33 | root.left = self._dfs(left) 34 | 35 | return root -------------------------------------------------------------------------------- /DFS/1308.Factor Combinations/README.md: -------------------------------------------------------------------------------- 1 | # 1308. Factor Combinations 2 | 3 | **Description** 4 | 5 | Numbers can be regarded as product of its factors. For example, 6 | 7 | ``` 8 | 8 = 2 x 2 x 2; 9 | = 2 x 4. 10 | ``` 11 | 12 | Write a function that takes an integer `n` and return all possible combinations of its factors. 13 | 14 | ``` 15 | You may assume that n is always positive. 16 | Factors should be greater than 1 and less than n. 17 | ``` 18 | 19 | **Example** 20 | 21 | Example 1 22 | 23 | ``` 24 | Input: 12 25 | Output: 26 | [ 27 | [2, 6], 28 | [2, 2, 3], 29 | [3, 4] 30 | ] 31 | Explanation: 32 | 2*6 = 12 33 | 2*2*3 = 12 34 | 3*4 = 12 35 | ``` 36 | 37 | Example 2 38 | 39 | ``` 40 | Input: 32 41 | Output: 42 | [ 43 | [2, 16], 44 | [2, 2, 8], 45 | [2, 2, 2, 4], 46 | [2, 2, 2, 2, 2], 47 | [2, 4, 4], 48 | [4, 8] 49 | ] 50 | Explanation: 51 | 2*16=32 52 | 2*2*8=32 53 | 2*2*2*4=32 54 | 2*2*2*2*2=32 55 | 2*4*4=32 56 | 4*8=32 57 | ``` 58 | -------------------------------------------------------------------------------- /DFS/1308.Factor Combinations/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | @param n: a integer 4 | @return: return a 2D array 5 | """ 6 | 7 | def getFactors(self, n): 8 | # write your code here 9 | self.combinations = [] 10 | if not n or n < 0: 11 | return [] 12 | 13 | self.dfs(2, [], n) 14 | return self.combinations 15 | 16 | def dfs(self, start, current, target): 17 | if current: 18 | current.append(target) 19 | self.combinations.append(sorted(current[:])) 20 | current.pop() 21 | 22 | for factor in range(start, int(math.sqrt(target) + 1)): 23 | 24 | if target % factor != 0: 25 | continue 26 | 27 | current.append(factor) 28 | self.dfs(factor, current, target // factor) 29 | current.pop() 30 | -------------------------------------------------------------------------------- /DFS/1353.Sum Root to Leaf Numbers/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | Definition of TreeNode: 3 | class TreeNode: 4 | def __init__(self, val): 5 | self.val = val 6 | self.left, self.right = None, None 7 | """ 8 | 9 | class Solution: 10 | """ 11 | @param root: the root of the tree 12 | @return: the total sum of all root-to-leaf numbers 13 | """ 14 | def sumNumbers(self, root): 15 | # write your code here 16 | return self._dfs(root, 0) 17 | 18 | def _dfs(self, root, total): 19 | if root is None: 20 | return 0 21 | 22 | total = total * 10 + root.val 23 | if root.left is None and root.right is None: 24 | return total 25 | 26 | return self._dfs(root.left, total) + self._dfs(root.right, total) 27 | -------------------------------------------------------------------------------- /DFS/136.Palindrome Partitioning/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | @param: s: A string 4 | @return: A list of lists of string 5 | """ 6 | 7 | def partition(self, s): 8 | # write your code here 9 | results = [] 10 | if not s or len(s) == 0: 11 | return results 12 | 13 | self._dfs(s, [], results) 14 | return results 15 | 16 | def _dfs(self, s, tmp, results): 17 | if len(s) == 0: 18 | results.append(tmp[:]) 19 | return 20 | 21 | for i in range(1, len(s) + 1): 22 | if self.isPalindrome(s[:i]): 23 | tmp.append(s[:i]) 24 | self._dfs(s[i:], tmp, results) 25 | tmp.pop() 26 | 27 | def isPalindrome(self, s): 28 | return s == s[::-1] 29 | -------------------------------------------------------------------------------- /DFS/152.Combinations/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | @param n: Given the range of numbers 4 | @param k: Given the numbers of combinations 5 | @return: All the combinations of k numbers out of 1..n 6 | """ 7 | def combine(self, n, k): 8 | # write your code here 9 | if not n or n == 0 or not k or k == 0: 10 | return [[]] 11 | 12 | self.n = n 13 | self.k = k 14 | combinations = [] 15 | self._find_combinations(combinations, [], 1) 16 | return combinations 17 | 18 | def _find_combinations(self, combinations, tmp, start): 19 | if len(tmp) == self.k: 20 | combinations.append(tmp[:]) 21 | return 22 | 23 | for i in range(start, self.n + 1): 24 | tmp.append(i) 25 | self._find_combinations(combinations, tmp, i + 1) 26 | tmp.pop() 27 | -------------------------------------------------------------------------------- /DFS/17.Subsets/Solution.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | /** 3 | * @param nums: A set of numbers 4 | * @return: A list of lists 5 | */ 6 | public List> subsets(int[] nums) { 7 | // write your code here 8 | List> result = new ArrayList>(); 9 | Arrays.sort(nums); 10 | helper(nums, result, new ArrayList(), 0); 11 | return result; 12 | } 13 | 14 | public void helper(int[] nums, List> res, List cur, int start) { 15 | List subset = new ArrayList<>(cur); 16 | res.add(subset); 17 | 18 | // DFS 19 | for (int i = start; i <= nums.length - 1; i += 1) { 20 | cur.add(nums[i]); 21 | helper(nums, res, cur, i + 1); 22 | cur.remove(cur.size() - 1); 23 | } 24 | 25 | } 26 | 27 | } 28 | -------------------------------------------------------------------------------- /DFS/17.Subsets/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | @param nums: A set of numbers 4 | @return: A list of lists 5 | """ 6 | def subsets(self, nums): 7 | # write your code here 8 | if not nums or len(nums) == 0: 9 | return [[]] 10 | 11 | subsets = [] 12 | nums.sort() 13 | self._find_subsets(subsets, [], nums, 0) 14 | return subsets 15 | 16 | def _find_subsets(self, subsets, subset, nums, start): 17 | subsets.append(subset[:]) 18 | 19 | for i in range(start, len(nums)): 20 | subset.append(nums[i]) 21 | self._find_subsets(subsets, subset, nums, i + 1) 22 | subset.pop() 23 | -------------------------------------------------------------------------------- /DFS/17.Subsets/Subsets.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | private: 3 | void helper(vector > &results, 4 | vector &subset, 5 | vector &nums, 6 | int start) { 7 | results.push_back(subset); 8 | 9 | for (int i = start; i < nums.size(); i++) { 10 | subset.push_back(nums[i]); 11 | helper(results, subset, nums, i + 1); 12 | subset.pop_back(); 13 | } 14 | } 15 | 16 | public: 17 | vector > subsets(vector &nums) { 18 | vector > results; 19 | vector subset; 20 | 21 | sort(nums.begin(), nums.end()); 22 | helper(results, subset, nums, 0); 23 | 24 | return results; 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /DFS/18.Subsets II/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | @param nums: A set of numbers. 4 | @return: A list of lists. All valid subsets. 5 | """ 6 | def subsetsWithDup(self, nums): 7 | # write your code here 8 | if not nums or len(nums) == 0: 9 | return [[]] 10 | subsets = [] 11 | nums.sort() 12 | self._find_subsets(nums, subsets, [], 0) 13 | return subsets 14 | 15 | def _find_subsets(self, nums, subsets, subset, start): 16 | subsets.append(subset[:]) 17 | 18 | for i in range(start, len(nums)): 19 | if i > start and nums[i] == nums[i - 1]: 20 | continue 21 | 22 | subset.append(nums[i]) 23 | self._find_subsets(nums, subsets, subset, i + 1) 24 | subset.pop() 25 | -------------------------------------------------------------------------------- /DFS/388.Permutation Sequence/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | @param n: n 4 | @param k: the k th permutation 5 | @return: return the k-th permutation 6 | """ 7 | def getPermutation(self, n, k): 8 | # write your code here 9 | nums = [str(i) for i in range(1, n + 1)] 10 | self.permutations = [] 11 | self.dfs(nums, []) 12 | 13 | return self.permutations[k - 1] 14 | 15 | def dfs(self, nums, current): 16 | if len(current) == len(nums): 17 | self.permutations.append(''.join(current[:])) 18 | return 19 | 20 | for num in nums: 21 | if num not in current: 22 | current.append(num) 23 | self.dfs(nums, current) 24 | current.pop() 25 | -------------------------------------------------------------------------------- /DFS/388.Permutation Sequence/Solution_2.py: -------------------------------------------------------------------------------- 1 | # 本参考程序来自九章算法,由 @九章算法 提供。版权所有,转发请注明出处。 2 | # - 九章算法致力于帮助更多中国人找到好的工作,教师团队均来自硅谷和国内的一线大公司在职工程师。 3 | # - 现有的面试培训课程包括:九章算法班,系统设计班,算法强化班,Java入门与基础算法班,Android 项目实战班, 4 | # - Big Data 项目实战班,算法面试高频题班, 动态规划专题班 5 | # - 更多详情请见官方网站:http://www.jiuzhang.com/?source=code 6 | 7 | 8 | class Solution: 9 | """ 10 | @param n: n 11 | @param k: the k-th permutation 12 | @return: the k-th permutation 13 | """ 14 | 15 | def getPermutation(self, n, k): 16 | fac = [1] 17 | for i in range(1, n + 1): 18 | fac.append(fac[-1] * i) 19 | 20 | elegible = range(1, n + 1) 21 | per = [] 22 | for i in range(n): 23 | digit = (k - 1) / fac[n - i - 1] 24 | per.append(elegible[digit]) 25 | elegible.remove(elegible[digit]) 26 | k = (k - 1) % fac[n - i - 1] + 1 27 | 28 | return "".join([str(x) for x in per]) 29 | -------------------------------------------------------------------------------- /DFS/426.Restore IP Addresses/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | @param s: the IP string 4 | @return: All possible valid IP addresses 5 | """ 6 | def restoreIpAddresses(self, s): 7 | # write your code here 8 | if not s or len(s) < 4: 9 | return [] 10 | 11 | ips = [] 12 | self._find_all_ips(s, 0, "", ips) 13 | return ips 14 | 15 | def _find_all_ips(self, s, partition, ip, ips): 16 | 17 | if partition == 4 and s == "": 18 | ips.append(ip[1:]) 19 | return 20 | 21 | for i in range(1, 4): 22 | if i <= len(s): 23 | 24 | if int(s[:i]) <= 255: 25 | self._find_all_ips(s[i:], partition + 1, ip + "." + s[:i], ips) 26 | 27 | if s[0] == '0': 28 | break 29 | -------------------------------------------------------------------------------- /DFS/652.Factorization/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | @param n: An integer 4 | @return: a list of combination 5 | """ 6 | def getFactors(self, n): 7 | # write your code here 8 | self.results = [] 9 | if not n or n <= 1: 10 | return self.results 11 | 12 | self._find_factors(n, 2, []) 13 | return self.results 14 | 15 | def _find_factors(self, n, start, factor): 16 | if factor: 17 | factor.append(n) 18 | self.results.append(factor[:]) 19 | factor.pop() 20 | 21 | for i in range(start, int(math.sqrt(n) + 1)): 22 | if n % i != 0: 23 | continue 24 | 25 | factor.append(i) 26 | self._find_factors(n // i, i, factor) 27 | factor.pop() 28 | -------------------------------------------------------------------------------- /Deque/22.Flatten List/Solution_DFS.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Zhenye-Na/lintcode/afd79d790d0a7495d75e6650f80adaa99bd0ff07/Deque/22.Flatten List/Solution_DFS.py -------------------------------------------------------------------------------- /Deque/22.Flatten List/Solution_Deque.py: -------------------------------------------------------------------------------- 1 | from collections import deque 2 | 3 | class Solution(object): 4 | 5 | # @param nestedList a list, each element in the list can be a list or integer, for example [1,2,[1,2]] 6 | # @return {int[]} a list of integer 7 | def flatten(self, nestedList): 8 | # Write your code here 9 | if not nestedList or len(nestedList) == 0: 10 | return nestedList 11 | 12 | queue = deque(nestedList) 13 | res = [] 14 | while queue: 15 | ele = queue.popleft() 16 | if isinstance(ele, list): 17 | for e in reversed(ele): 18 | queue.appendleft(e) 19 | else: 20 | res.append(ele) 21 | 22 | return res 23 | -------------------------------------------------------------------------------- /Deque/362.Sliding Window Maximum/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | Author: Huahua 3 | Running time: 238 ms 4 | """ 5 | 6 | 7 | class MaxQueue: 8 | def __init__(self): 9 | self.q_ = collections.deque() 10 | 11 | def push(self, e): 12 | while self.q_ and e > self.q_[-1]: 13 | self.q_.pop() 14 | self.q_.append(e) 15 | 16 | def pop(self): 17 | self.q_.popleft() 18 | 19 | def max(self): 20 | return self.q_[0] 21 | 22 | 23 | class Solution: 24 | def maxSlidingWindow(self, nums, k): 25 | q = MaxQueue() 26 | ans = [] 27 | for i in range(len(nums)): 28 | q.push(nums[i]) 29 | if i >= k - 1: 30 | ans.append(q.max()) 31 | if nums[i - k + 1] == q.max(): 32 | q.pop() 33 | return ans 34 | -------------------------------------------------------------------------------- /Deque/362.Sliding Window Maximum/Solution_BST.cpp: -------------------------------------------------------------------------------- 1 | // Author: Huahua 2 | // Running time: 82 ms 3 | class Solution { 4 | public: 5 | vector maxSlidingWindow(vector& nums, int k) { 6 | vector ans; 7 | if (nums.empty()) return ans; 8 | multiset window(nums.begin(), nums.begin() + k - 1); 9 | for (int i = k - 1; i < nums.size(); ++i) { 10 | window.insert(nums[i]); 11 | ans.push_back(*window.rbegin()); 12 | if (i - k + 1 >= 0) 13 | window.erase(window.equal_range(nums[i - k + 1]).first); 14 | } 15 | return ans; 16 | } 17 | }; -------------------------------------------------------------------------------- /Deque/362.Sliding Window Maximum/Solution_BruteForce.py: -------------------------------------------------------------------------------- 1 | """ 2 | Author: Huahua 3 | Running time: 1044 ms 4 | """ 5 | class Solution: 6 | def maxSlidingWindow(self, nums, k): 7 | if not nums: 8 | return [] 9 | return [max(nums[i:i+k]) for i in range(len(nums) - k + 1)] 10 | -------------------------------------------------------------------------------- /Deque/362.Sliding Window Maximum/Solution_MonotonicQueue.py: -------------------------------------------------------------------------------- 1 | from collections import deque 2 | 3 | 4 | class Solution: 5 | """ 6 | @param nums: A list of integers. 7 | @param k: An integer 8 | @return: The maximum number inside the window at each moving. 9 | """ 10 | def maxSlidingWindow(self, nums, k): 11 | # write your code here 12 | if not nums or len(nums) == 0: 13 | return [] 14 | 15 | max_queue, res = deque([]), [] 16 | for i in range(len(nums)): 17 | 18 | while max_queue and nums[i] >= nums[max_queue[-1]]: 19 | max_queue.pop() 20 | max_queue.append(i) 21 | 22 | if i + 1 >= k: 23 | res.append(nums[max_queue[0]]) 24 | 25 | if i + 1 - k == max_queue[0]: 26 | max_queue.popleft() 27 | 28 | return res 29 | -------------------------------------------------------------------------------- /Dynamic_Programming/109.Triangle/Solution_DivideConquer.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | @param triangle: a list of lists of integers 4 | @return: An integer, minimum path sum 5 | """ 6 | def minimumTotal(self, triangle): 7 | return self.divide_conquer(triangle, 0, 0, {}) 8 | 9 | # 函数返回从 x, y 出发,走到最底层的最短路径值 10 | # memo 中 key 为二元组 (x, y) 11 | # memo 中 value 为从 x, y 走到最底层的最短路径值 12 | def divide_conquer(self, triangle, x, y, memo): 13 | if x == len(triangle): 14 | return 0 15 | 16 | # 如果找过了,就不要再找了,直接把之前找到的值返回 17 | if (x, y) in memo: 18 | return memo[(x, y)] 19 | 20 | left = self.divide_conquer(triangle, x + 1, y, memo) 21 | right = self.divide_conquer(triangle, x + 1, y + 1, memo) 22 | 23 | # 在 return 之前先把这次找到的最短路径值记录下来 24 | # 避免之后重复搜索 25 | memo[(x, y)] = min(left, right) + triangle[x][y] 26 | return memo[(x, y)] -------------------------------------------------------------------------------- /Dynamic_Programming/111.Climbing Stairs/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | @param n: An integer 4 | @return: An integer 5 | """ 6 | 7 | def climbStairs(self, n): 8 | # write your code here 9 | # initialization: 10 | dp = [0 for _ in range(n + 1)] 11 | dp[0] = 1 12 | dp[1] = 1 13 | 14 | # state: dp[i] represents how many ways to reach step i 15 | # function: dp[i] = dp[i - 1] + dp[i - 2] 16 | for i in range(2, n + 1): 17 | dp[i] = dp[i - 1] + dp[i - 2] 18 | 19 | # answer: dp[n] represents the number of ways to reach n 20 | return dp[n] 21 | -------------------------------------------------------------------------------- /Dynamic_Programming/114.Unique Paths/Solution_DP2.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | 3 | def uniquePaths(self, m, n) -> int: 4 | 5 | steps = [1 for _ in range(n)] 6 | 7 | for _ in range(1, m): 8 | for i in range(1, n): 9 | steps[i] = steps[i-1] + steps[i] 10 | 11 | return steps[-1] 12 | -------------------------------------------------------------------------------- /Dynamic_Programming/116.Jump Game/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | @param A: A list of integers 4 | @return: A boolean 5 | """ 6 | 7 | def canJump(self, A): 8 | # write your code here 9 | # initialization: we can jump to the first position 10 | # dp[i] represents whether we can jump to the i-th position 11 | dp = [False for _ in range(len(A))] 12 | dp[0] = True 13 | 14 | # Sequence DP 15 | # function: f[i] <- f[j] j < i, dp[j] == True, j + A[j] >= i 16 | for i in range(1, len(A)): 17 | for j in range(0, i): 18 | if dp[j] and j + A[j] >= i: 19 | dp[i] = True 20 | break # no longer need to change value of dp[i], break 21 | 22 | # answer: dp[-1] 23 | return dp[-1] 24 | -------------------------------------------------------------------------------- /Dynamic_Programming/117.Jump Game II/Solution_DP.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | @param A: A list of integers 4 | @return: An integer 5 | """ 6 | 7 | def jump(self, A): 8 | # write your code here 9 | # initialization: f[i] represents the min steps to reach i-th index 10 | f = [sys.maxsize for _ in range(len(A))] 11 | f[0] = 0 12 | 13 | # function f[i] = min(f[j] + 1) for j in [0, i), if constraints 14 | for i in range(1, len(A)): 15 | for j in range(0, i): 16 | if f[j] != sys.maxsize and j + A[j] >= i: 17 | f[i] = min(f[i], f[j] + 1) 18 | 19 | # answer: f[-1] if we can jump to the last index else 0 20 | return f[-1] if f[-1] != sys.maxsize else 0 21 | -------------------------------------------------------------------------------- /Dynamic_Programming/117.Jump Game II/Solution_Greedy.cpp: -------------------------------------------------------------------------------- 1 | // Author: Huahua, running time: 12 ms / 10.3 MB 2 | class Solution { 3 | public: 4 | int jump(vector& nums) { 5 | int steps = 0; 6 | int near = 0; 7 | int far = 0; 8 | for (int i = 0; i < nums.size(); ++i) { 9 | if (i > near) { 10 | ++steps; 11 | near = far; 12 | } 13 | far = max(far, i + nums[i]); 14 | } 15 | return steps; 16 | } 17 | }; -------------------------------------------------------------------------------- /Dynamic_Programming/117.Jump Game II/Solution_Greedy.java: -------------------------------------------------------------------------------- 1 | // version 2: Greedy 2 | public class Solution { 3 | public int jump(int[] A) { 4 | if (A == null || A.length == 0) { 5 | return -1; 6 | } 7 | 8 | int start = 0, end = 0, jumps = 0; 9 | while (end < A.length - 1) { 10 | jumps++; 11 | int farthest = end; 12 | for (int i = start; i <= end; i++) { 13 | if (A[i] + i > farthest) { 14 | farthest = A[i] + i; 15 | } 16 | } 17 | start = end + 1; 18 | end = farthest; 19 | } 20 | 21 | return jumps; 22 | } 23 | } -------------------------------------------------------------------------------- /Dynamic_Programming/1259.Integer Replacement/Solution_BFS.py: -------------------------------------------------------------------------------- 1 | from collections import deque 2 | 3 | 4 | class Solution: 5 | """ 6 | @param n: a positive integer 7 | @return: the minimum number of replacements 8 | """ 9 | 10 | def integerReplacement(self, n): 11 | # Write your code here 12 | steps = 0 13 | if n == 1: 14 | return steps 15 | 16 | queue = deque([n]) 17 | while queue: 18 | size = len(queue) 19 | print(queue, steps) 20 | for _ in range(size): 21 | num = queue.popleft() 22 | if num == 1: 23 | return steps 24 | if num % 2 == 0: 25 | queue.append(num // 2) 26 | else: 27 | queue.append(num + 1) 28 | queue.append(num - 1) 29 | steps += 1 30 | 31 | return 0 32 | -------------------------------------------------------------------------------- /Dynamic_Programming/1259.Integer Replacement/Solution_DFS.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | @param n: a positive integer 4 | @return: the minimum number of replacements 5 | """ 6 | 7 | def integerReplacement(self, n): 8 | # Write your code here 9 | ans = {} 10 | return self.dfs(ans, n) 11 | 12 | def dfs(self, ans, n): 13 | if n == 1: 14 | return 0 15 | 16 | if n in ans: 17 | return ans[n] 18 | 19 | if n % 2 == 0: 20 | ans[n] = self.dfs(ans, n // 2) + 1 21 | else: 22 | ans[n] = min(self.dfs(ans, n + 1), self.dfs(ans, n - 1)) + 1 23 | 24 | return ans[n] 25 | -------------------------------------------------------------------------------- /Dynamic_Programming/254.Drop Eggs/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | @param n: An integer 4 | @return: An integer 5 | """ 6 | 7 | def dropEggs(self, n): 8 | # write your code here 9 | return math.ceil((math.sqrt(8 * n) - 1) / 2) 10 | -------------------------------------------------------------------------------- /Dynamic_Programming/272.Climbing Stairs II/Solution_Backpack.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | 3 | def climbStairs2(self, num_of_stairs): 4 | 5 | different_steps_could_be_taken = [1, 2, 3] 6 | 7 | num_of_ways = [1] + [0 for _ in range(num_of_stairs)] 8 | for stairs_to_climb in range(1, len(num_of_ways)): 9 | for steps in different_steps_could_be_taken: 10 | if stairs_to_climb < steps: 11 | continue 12 | num_of_ways[stairs_to_climb] += num_of_ways[stairs_to_climb - steps] 13 | 14 | return num_of_ways[-1] 15 | -------------------------------------------------------------------------------- /Dynamic_Programming/272.Climbing Stairs II/Solution_DP.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | @param n: An integer 4 | @return: An Integer 5 | """ 6 | 7 | def climbStairs2(self, n): 8 | # write your code here 9 | # initialization: 10 | if n == 0 or n == 1: 11 | return 1 12 | 13 | if n == 2: 14 | return 2 15 | 16 | dp = [0 for _ in range(n + 1)] 17 | dp[0] = 1 18 | dp[1] = 1 19 | dp[2] = 2 20 | 21 | # state: dp[i] represents how many steps can reach step i 22 | # function: dp[i] = dp[i - 1] + dp[i - 2] + dp[i - 3] 23 | for i in range(3, n + 1): 24 | dp[i] = dp[i - 1] + dp[i - 2] + dp[i - 3] 25 | 26 | return dp[n] 27 | -------------------------------------------------------------------------------- /Dynamic_Programming/514.Paint Fence/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | @param n: non-negative integer, n posts 4 | @param k: non-negative integer, k colors 5 | @return: an integer, the total number of ways 6 | """ 7 | 8 | def numWays(self, n, k): 9 | # write your code here 10 | if n == 1: 11 | return k 12 | 13 | if n == 2: 14 | return k * k 15 | 16 | if k == 1: 17 | return 0 18 | 19 | # initialization 20 | # f[i] represents the number of ways to paint first i posts 21 | f = [0 for _ in range(n + 1)] 22 | f[0] = 0 23 | f[1] = k 24 | f[2] = k * k 25 | 26 | # function: (k - 1) * f[i - 1] + (k - 1) * f[i - 2] 27 | for i in range(3, n + 1): 28 | f[i] = (k - 1) * f[i - 1] + (k - 1) * f[i - 2] 29 | 30 | return f[-1] 31 | -------------------------------------------------------------------------------- /Dynamic_Programming/564.Combination Sum IV/Solution.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Zhenye-Na/lintcode/afd79d790d0a7495d75e6650f80adaa99bd0ff07/Dynamic_Programming/564.Combination Sum IV/Solution.py -------------------------------------------------------------------------------- /Dynamic_Programming/76.Longest Increasing Subsequence/Solution.js: -------------------------------------------------------------------------------- 1 | /** 2 | * 本参考程序来自九章算法,由 @华助教 提供。版权所有,转发请注明出处。 3 | * - 九章算法致力于帮助更多中国人找到好的工作,教师团队均来自硅谷和国内的一线大公司在职工程师。 4 | * - 现有的面试培训课程包括:九章算法班,系统设计班,算法强化班,Java入门与基础算法班,Android 项目实战班, 5 | * - Big Data 项目实战班,算法面试高频题班, 动态规划专题班 6 | * - 更多详情请见官方网站:http://www.jiuzhang.com/?source=code 7 | */ 8 | 9 | /** 10 | * @param nums: An integer array 11 | * @return: The length of LIS (longest increasing subsequence) 12 | */ 13 | const longestIncreasingSubsequence = function(nums) { 14 | var f = new Array(nums.length); 15 | var max = 0; 16 | var i, j; 17 | for (i = 0; i < nums.length; i++) { 18 | f[i] = 1; 19 | for (j = 0; j < i; j++) { 20 | if (nums[j] < nums[i]) { 21 | f[i] = f[i] > f[j] + 1 ? f[i] : f[j] + 1; 22 | } 23 | } 24 | if (f[i] > max) { 25 | max = f[i]; 26 | } 27 | } 28 | return max; 29 | }; 30 | -------------------------------------------------------------------------------- /Dynamic_Programming/76.Longest Increasing Subsequence/Solution_DP.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | @param nums: An integer array 4 | @return: The length of LIS (longest increasing subsequence) 5 | """ 6 | 7 | def longestIncreasingSubsequence(self, nums): 8 | # write your code here 9 | if not nums or len(nums) == 0: 10 | return 0 11 | 12 | # initialization 13 | # f[i] represents the max length of increasing subsequence which ends with nums[i] 14 | n = len(nums) 15 | f = [1 for _ in range(n)] 16 | 17 | # function: f[i] <- f[j] with contraints on j < i, nums[i] > nums[j] 18 | for i in range(1, n): 19 | for j in range(0, i): 20 | if nums[i] > nums[j]: 21 | f[i] = max(f[i], f[j] + 1) 22 | 23 | return max(f) 24 | -------------------------------------------------------------------------------- /Easy/1. A + B Problem/Solution.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | /** 3 | * @param a: An integer 4 | * @param b: An integer 5 | * @return: The sum of a and b 6 | */ 7 | public int aplusb(int a, int b) { 8 | // write your code here 9 | int result = a ^ b; // + without carry 0+0=0, 0+1=1+0=1, 1+1=0 10 | int carry = (a & b) << 1; // 1 + 1 = 2 11 | if (carry != 0) { 12 | return aplusb(result, carry); 13 | } 14 | return result; 15 | } 16 | } -------------------------------------------------------------------------------- /Easy/100. Remove Duplicates from Sorted Array/Solution.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | /* 3 | * @param nums: An ineger array 4 | * @return: An integer 5 | */ 6 | public int removeDuplicates(int[] nums) { 7 | // write your code here 8 | if (nums == null || nums.length == 0) { 9 | return 0; 10 | } 11 | 12 | int start = 0, end = nums.length; 13 | for (int i = 0; i < end; i++) { 14 | if (nums[i] != nums[start]) { 15 | nums[++start] = nums[i]; 16 | } 17 | } 18 | return start + 1; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /Easy/1038. Jewels and Stones/Solution.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | /** 3 | * @param J: the types of stones that are jewels 4 | * @param S: representing the stones you have 5 | * @return: how many of the stones you have are also jewels 6 | */ 7 | public int numJewelsInStones(String J, String S) { 8 | // Write your code here 9 | if (J == null || J.length() == 0) { 10 | return 0; 11 | } 12 | 13 | Set set = new HashSet<>(); 14 | for (int i = 0; i < J.length(); i++) { 15 | set.add(J.charAt(i)); 16 | } 17 | 18 | int num = 0; 19 | for (int j = 0; j < S.length(); j++) { 20 | if (set.contains(S.charAt(j))) { 21 | num++; 22 | } 23 | } 24 | 25 | return num; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Easy/1038. Jewels and Stones/Solution.js: -------------------------------------------------------------------------------- 1 | const numJewelsInStones = function (J, S) { 2 | let [jewels, cnt] = [new Set(J), 0] 3 | for (let i in S) { 4 | if (jewels.has(S[i])) cnt++ 5 | } 6 | return cnt 7 | } 8 | -------------------------------------------------------------------------------- /Easy/1038. Jewels and Stones/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | @param J: the types of stones that are jewels 4 | @param S: representing the stones you have 5 | @return: how many of the stones you have are also jewels 6 | """ 7 | def numJewelsInStones(self, J, S): 8 | # Write your code here 9 | J = set(J) 10 | return sum(c in J for c in S) 11 | -------------------------------------------------------------------------------- /Easy/111. Climbing Stairs/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | @param n: An integer 4 | @return: An integer 5 | """ 6 | def climbStairs(self, n): 7 | # write your code here 8 | if n == 1: 9 | return 1 10 | 11 | if n == 0: 12 | return 0 13 | 14 | dp = [sys.maxint] * (n + 1) 15 | dp[1], dp[2] = 1, 2 16 | 17 | for i in xrange(3, n + 1): 18 | dp[i] = dp[i - 1] + dp[i - 2] 19 | 20 | return dp[n] 21 | -------------------------------------------------------------------------------- /Easy/112. Remove Duplicates from Sorted List/Solution.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 本参考程序来自九章算法,由 @九章算法 提供。版权所有,转发请注明出处。 3 | * - 九章算法致力于帮助更多中国人找到好的工作,教师团队均来自硅谷和国内的一线大公司在职工程师。 4 | * - 现有的面试培训课程包括:九章算法班,系统设计班,算法强化班,Java入门与基础算法班,Android 项目实战班, 5 | * - Big Data 项目实战班,算法面试高频题班, 动态规划专题班 6 | * - 更多详情请见官方网站:http://www.jiuzhang.com/?source=code 7 | */ 8 | 9 | public class Solution { 10 | public ListNode deleteDuplicates(ListNode head) { 11 | if (head == null) { 12 | return null; 13 | } 14 | 15 | ListNode node = head; 16 | while (node.next != null) { 17 | if (node.val == node.next.val) { 18 | node.next = node.next.next; 19 | } else { 20 | node = node.next; 21 | } 22 | } 23 | return head; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Easy/112. Remove Duplicates from Sorted List/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | Definition of ListNode 3 | class ListNode(object): 4 | def __init__(self, val, next=None): 5 | self.val = val 6 | self.next = next 7 | """ 8 | 9 | class Solution: 10 | """ 11 | @param head: head is the head of the linked list 12 | @return: head of linked list 13 | """ 14 | def deleteDuplicates(self, head): 15 | # write your code here 16 | if not head: 17 | return head 18 | prev = head 19 | curr = head 20 | result = head 21 | while curr: 22 | if curr.val != prev.val: 23 | prev.next.val = curr.val 24 | prev = prev.next 25 | curr = curr.next 26 | 27 | prev.next = None 28 | return result 29 | -------------------------------------------------------------------------------- /Easy/114. Unique Paths/Solution.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | /** 3 | * @param m: positive integer (1 <= m <= 100) 4 | * @param n: positive integer (1 <= n <= 100) 5 | * @return: An integer 6 | */ 7 | public int uniquePaths(int m, int n) { 8 | // write your code here 9 | 10 | int[][] f = new int[m][n]; 11 | 12 | for (int i = 0; i < m; i++) { 13 | for (int j = 0; j < n; j++) { 14 | 15 | if (i == 0 || j == 0) { 16 | f[i][j] = 1; 17 | continue; 18 | } 19 | 20 | f[i][j] = f[i - 1][j] + f[i][j - 1]; 21 | } 22 | } 23 | 24 | return f[m - 1][n - 1]; 25 | 26 | } 27 | 28 | 29 | } -------------------------------------------------------------------------------- /Easy/1219. Heaters/Solution.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | /** 3 | * @param houses: positions of houses 4 | * @param heaters: positions of heaters 5 | * @return: the minimum radius standard of heaters 6 | */ 7 | public int findRadius(int[] houses, int[] heaters) { 8 | // Write your code here 9 | Arrays.sort(houses); 10 | Arrays.sort(heaters); 11 | 12 | int i = 0; 13 | int radius = 0; 14 | 15 | for (int house : houses) { 16 | while (i < heaters.length - 1 && heaters[i] + heaters[i + 1] <= house * 2) { 17 | i++; 18 | } 19 | radius = Math.max(radius, Math.abs(heaters[i] - house)); 20 | } 21 | return radius; 22 | 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /Easy/1219. Heaters/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | @param houses: positions of houses 4 | @param heaters: positions of heaters 5 | @return: the minimum radius standard of heaters 6 | """ 7 | def findRadius(self, houses, heaters): 8 | # Write your code here 9 | houses.sort() 10 | heaters.sort() 11 | 12 | i, radius = 0, 0 13 | 14 | for house in houses: 15 | while i < len(heaters) - 1 and heaters[i] + heaters[i + 1] <= house * 2: 16 | i += 1 17 | 18 | radius = max(radius, abs(heaters[i] - house)) 19 | 20 | return radius 21 | -------------------------------------------------------------------------------- /Easy/1231. Minimum Moves to Equal Array Elements/Solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | /** 4 | * @param nums: an array 5 | * @return: the minimum number of moves required to make all array elements equal 6 | */ 7 | int minMoves(vector &nums) { 8 | // Write your code here 9 | int mn = INT_MAX, res = 0; 10 | for (int num : nums) mn = min(mn, num); 11 | for (int num : nums) res += num - mn; 12 | return res; 13 | } 14 | }; 15 | 16 | 17 | 18 | 19 | class Solution { 20 | public: 21 | int minMoves(vector& nums) { 22 | int mn = INT_MAX, sum = 0, res = 0; 23 | for (int num : nums) { 24 | mn = min(mn, num); 25 | sum += num; 26 | } 27 | return sum - mn * nums.size(); 28 | } 29 | }; 30 | -------------------------------------------------------------------------------- /Easy/1231. Minimum Moves to Equal Array Elements/Solution.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | class Solution: 4 | """ 5 | @param nums: an array 6 | @return: the minimum number of moves required to make all array elements equal 7 | """ 8 | def minMoves(self, nums): 9 | # Write your code here 10 | result = 0 11 | minimum = min(nums) 12 | result = sum([num - minimum for num in nums]) 13 | return result 14 | -------------------------------------------------------------------------------- /Easy/1314. Power of Two/README.md: -------------------------------------------------------------------------------- 1 | # 1314. Power of Two 2 | 3 | - **Description** 4 | - Given an integer, write a function to determine if it is a power of two. 5 | 6 | ## Solution 7 | 8 | 满足要求的`N`有两个条件: 9 | 10 | - N > 0 11 | - N 的二进制表示有且只有一个1 12 | 13 | ```java 14 | x & (x - 1) // 消去 x 最后一位的 1,比如 x = 12,那么在二进制下就是 (1100)2 15 | ​ 16 | x = 1100 17 | x - 1 = 1011 18 | x & (x - 1) = 1000 19 | ``` 20 | 21 | ### Java 22 | 23 | ```java 24 | public class Solution { 25 | /** 26 | * @param n: an integer 27 | * @return: if n is a power of two 28 | */ 29 | public boolean isPowerOfTwo(int n) { 30 | // Write your code here 31 | return (n > 0) && ((n & (n - 1)) == 0); 32 | } 33 | } 34 | ``` 35 | -------------------------------------------------------------------------------- /Easy/1314. Power of Two/Solution.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | /** 3 | * @param n: an integer 4 | * @return: if n is a power of two 5 | */ 6 | public boolean isPowerOfTwo(int n) { 7 | // Write your code here 8 | return (n > 0) && ((n & (n - 1)) == 0); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /Easy/138. Subarray Sum/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | @param nums: A list of integers 4 | @return: A list of integers includes the index of the first number and the index of the last number 5 | """ 6 | def subarraySum(self, nums): 7 | # write your code here 8 | # First prefix sum is 0, index is -1 9 | mapping = {0: -1} 10 | prefixSum = 0 11 | 12 | for idx, num in enumerate(nums): 13 | prefixSum += num 14 | if prefixSum in mapping: 15 | # subarray start from first index + 1 16 | return [mapping[prefixSum] + 1, idx] 17 | else: 18 | mapping[prefixSum] = idx 19 | # if not found, return [-1, -1] 20 | return [-1, -1] 21 | -------------------------------------------------------------------------------- /Easy/14. First Position of Target/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | @param nums: The integer array. 4 | @param target: Target to find. 5 | @return: The first position of target. Position starts from 0. 6 | """ 7 | def binarySearch(self, nums, target): 8 | # write your code here 9 | if nums == None or len(nums) == 0 or target == None: 10 | return 0 11 | 12 | start, end = 0, len(nums) - 1 13 | while (start + 1 < end): 14 | mid = (start + end) // 2 15 | 16 | if nums[mid] >= target: 17 | end = mid 18 | elif nums[mid] < target: 19 | start = mid 20 | 21 | if nums[start] == target: 22 | return start 23 | elif nums[end] == target: 24 | return end 25 | else: 26 | return -1 27 | -------------------------------------------------------------------------------- /Easy/141. Sqrt(x)/Solution.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | /** 3 | * @param x: An integer 4 | * @return: The sqrt of x 5 | */ 6 | public int sqrt(int x) { 7 | // write your code here 8 | if (x < 0) return -1; 9 | if (x == 0) return 0; 10 | 11 | long start = 1, end = x; 12 | 13 | while (start + 1 < end) { 14 | 15 | long mid = (end - start) / 2 + start; 16 | long mul = mid * mid; 17 | 18 | if (mul < x) { 19 | start = mid; 20 | } else if (mul > x) { 21 | end = mid; 22 | } else if (mul == x) { 23 | return (int)mid; 24 | } 25 | } 26 | 27 | if (start * start <= x) { 28 | return (int)start; 29 | } else { 30 | return (int)end; 31 | } 32 | 33 | } 34 | } -------------------------------------------------------------------------------- /Easy/141. Sqrt(x)/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | @param x: An integer 4 | @return: The sqrt of x 5 | """ 6 | def sqrt(self, x): 7 | # write your code here 8 | if (x == 0): return x 9 | 10 | start, end = 1, x 11 | 12 | while (start + 1 < end): 13 | mid = (end - start) // 2 + start 14 | 15 | if (mid ** 2 == x): 16 | return mid 17 | elif (mid ** 2 > x): 18 | end = mid 19 | else: 20 | start = mid 21 | 22 | if (start ** 2 <= x): 23 | return start 24 | else: 25 | return end 26 | -------------------------------------------------------------------------------- /Easy/142. O(1) Check Power of 2/README.md: -------------------------------------------------------------------------------- 1 | # 142. O(1) Check Power of 2 2 | 3 | - **Description** 4 | - Using O(1) time to check whether an integer n is a power of 2. 5 | - **Example** 6 | - For n=4, return true; 7 | - For n=5, return false; 8 | - **Challenge** 9 | - `O(1)` time 10 | 11 | 12 | ## Solution 13 | 14 | `N`如果是`2`的幂次,则`N`满足两个条件。 15 | 16 | - `N > 0` 17 | - N的二进制表示中只有一个`1`, 注意只能有`1`个。 18 | 19 | 因为`N`的二进制表示中只有一个`1`,所以使用`N & (N - 1)`将`N`唯一的一个`1`消去,应该返回`0`。 20 | 21 | ```java 22 | x & (x - 1) // 用于消去x最后一位的1, 比如x = 12, 那么在二进制下就是(1100)2 23 | 24 | x = 1100 25 | x - 1 = 1011 26 | x & (x - 1) = 1000 27 | ``` 28 | 29 | 30 | 31 | ```java 32 | public class Solution { 33 | /** 34 | * @param n: An integer 35 | * @return: True or false 36 | */ 37 | public boolean checkPowerOf2(int n) { 38 | // write your code here 39 | return (n > 0) && ((n & (n - 1)) == 0); 40 | } 41 | } 42 | ``` 43 | -------------------------------------------------------------------------------- /Easy/142. O(1) Check Power of 2/Solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | /* 4 | * @param n: An integer 5 | * @return: True or false 6 | */ 7 | bool checkPowerOf2(int n) { 8 | // write your code here 9 | return n > 0 && (n & (n - 1)) == 0; 10 | } 11 | }; 12 | -------------------------------------------------------------------------------- /Easy/142. O(1) Check Power of 2/Solution.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | /** 3 | * @param n: An integer 4 | * @return: True or false 5 | */ 6 | public boolean checkPowerOf2(int n) { 7 | // write your code here 8 | return (n > 0) && ((n & (n - 1)) == 0); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /Easy/155. Minimum Depth of Binary Tree/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | Definition of TreeNode: 3 | class TreeNode: 4 | def __init__(self, val): 5 | self.val = val 6 | self.left, self.right = None, None 7 | """ 8 | import sys 9 | class Solution: 10 | """ 11 | @param root: The root of binary tree 12 | @return: An integer 13 | """ 14 | def minDepth(self, root): 15 | # write your code here 16 | if not root: 17 | return 0 18 | return self.helper(root) 19 | 20 | 21 | def helper(self, root): 22 | # base case 23 | if not root: 24 | return sys.maxint 25 | 26 | # recursive case 27 | else: 28 | # leaf node 29 | if not root.left and not root.right: 30 | return 1 31 | 32 | # recursively compare minDepth of left and right subtree 33 | return min(self.helper(root.left), self.helper(root.right)) + 1 34 | -------------------------------------------------------------------------------- /Easy/156. Merge Intervals/README.md: -------------------------------------------------------------------------------- 1 | # 156. Merge Intervals 2 | Description 3 | Given a collection of intervals, merge all overlapping intervals. 4 | Example 5 | Given intervals => merged intervals: 6 | 7 | [ [ 8 | (1, 3), (1, 6), 9 | (2, 6), => (8, 10), 10 | (8, 10), (15, 18) 11 | (15, 18) ] 12 | ] 13 | 14 | Challenge 15 | O(n log n) time and O(1) extra space. 16 | 17 | Related Problems 18 | - 920. Meeting Rooms 19 | - 919. Meeting Rooms II 20 | 21 | ## Solution 22 | -------------------------------------------------------------------------------- /Easy/156. Merge Intervals/Solution.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Zhenye-Na/lintcode/afd79d790d0a7495d75e6650f80adaa99bd0ff07/Easy/156. Merge Intervals/Solution.java -------------------------------------------------------------------------------- /Easy/158. Valid Anagram/Solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | /** 4 | * @param s: The first string 5 | * @param t: The second string 6 | * @return: true or false 7 | */ 8 | bool anagram(string &s, string &t) { 9 | // write your code here 10 | string sorted_s = s; 11 | string sorted_t = t; 12 | sort(sorted_s.begin(), sorted_s.end()); 13 | sort(sorted_t.begin(), sorted_t.end()); 14 | return sorted_t == sorted_s; 15 | } 16 | }; -------------------------------------------------------------------------------- /Easy/158. Valid Anagram/Solution.py: -------------------------------------------------------------------------------- 1 | # 本参考程序来自九章算法,由 @J同学 提供。版权所有,转发请注明出处。 2 | # - 九章算法致力于帮助更多中国人找到好的工作,教师团队均来自硅谷和国内的一线大公司在职工程师。 3 | # - 现有的面试培训课程包括:九章算法班,系统设计班,算法强化班,Java入门与基础算法班,Android 项目实战班, 4 | # - Big Data 项目实战班,算法面试高频题班, 动态规划专题班 5 | # - 更多详情请见官方网站:http://www.jiuzhang.com/?source=code 6 | 7 | 8 | class Solution: 9 | """ 10 | @param s: The first string 11 | @param t: The second string 12 | @return: true or false 13 | """ 14 | def anagram(self, s, t): 15 | return collections.Counter(s) == collections.Counter(t) 16 | -------------------------------------------------------------------------------- /Easy/1617. Array Maximum Difference/README.md: -------------------------------------------------------------------------------- 1 | # 1617. Array Maximum Difference 2 | 3 | - **Description** 4 | - Given an array a, output the maximum value of `a[j] - a[i]`, where `i < j`, `a[i] 0 else -1 10 | x = abs(x) 11 | 12 | stack = [] 13 | while x != 0: 14 | stack.append(x % 10) 15 | x /= 10 16 | 17 | while stack: 18 | result = (result * 10) + stack.pop(0) 19 | 20 | return result * flag if (result * flag) < 2 ** 31 - 1 and (result * flag) > -2 ** 31 else 0 21 | -------------------------------------------------------------------------------- /Easy/415. Valid Palindrome/Solution.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | /** 3 | * @param s: A string 4 | * @return: Whether the string is a valid palindrome 5 | */ 6 | public boolean isPalindrome(String s) { 7 | // write your code here 8 | s = rmSigns(s); 9 | if (s == null || s.length() == 0 || s.length() == 1) { 10 | return true; 11 | } 12 | 13 | int left = 0, right = s.length() - 1; 14 | while (left < right) { 15 | if (s.charAt(left) != s.charAt(right)) { 16 | return false; 17 | } 18 | left++; 19 | right--; 20 | } 21 | return true; 22 | } 23 | 24 | private String rmSigns(String s) { 25 | String wow = s.replaceAll("[^a-zA-Z0-9]", "").trim().toUpperCase(); 26 | return wow; 27 | } 28 | 29 | 30 | } -------------------------------------------------------------------------------- /Easy/423. Valid Parentheses/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | @param s: A string 4 | @return: whether the string is a valid parentheses 5 | """ 6 | def isValidParentheses(self, s): 7 | # write your code here 8 | if s is None or len(s) == 0: 9 | return True 10 | if len(s) % 2 != 0: 11 | return False 12 | 13 | stack = [] 14 | for symbol in s: 15 | if symbol == '(' or symbol == '[' or symbol == '{': 16 | stack.append(symbol) 17 | else: 18 | if not stack: 19 | return False 20 | 21 | if (symbol == ')' and stack[-1] != '(') or (symbol == '}' and stack[-1] != '{') or (symbol == ']' and stack[-1] != '['): 22 | return False 23 | 24 | stack.pop() 25 | 26 | return not stack 27 | -------------------------------------------------------------------------------- /Easy/46. Majority Element/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | @param: nums: a list of integers 4 | @return: find a majority number 5 | """ 6 | def majorityNumber(self, nums): 7 | # write your code here 8 | counts = collections.Counter(nums) 9 | return max(counts.keys(), key=counts.get) 10 | -------------------------------------------------------------------------------- /Easy/491. Palindrome Number/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | @param num: a positive number 4 | @return: true if it's a palindrome or false 5 | """ 6 | def isPalindrome(self, num): 7 | # write your code here 8 | if num / 10 == 0: 9 | return True 10 | 11 | numString = str(num) 12 | start, end = 0, len(numString) - 1 13 | while start < end: 14 | if numString[start] != numString[end]: 15 | return False 16 | start += 1 17 | end -= 1 18 | 19 | return True 20 | -------------------------------------------------------------------------------- /Easy/494. Implement Stack by Two Queues/Solution.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Zhenye-Na/lintcode/afd79d790d0a7495d75e6650f80adaa99bd0ff07/Easy/494. Implement Stack by Two Queues/Solution.java -------------------------------------------------------------------------------- /Easy/517. Ugly Number/Soluion.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | /** 3 | * @param num: An integer 4 | * @return: true if num is an ugly number or false 5 | */ 6 | public boolean isUgly(int num) { 7 | // write your code here 8 | if (num == 0) return false; 9 | if (num == 1) return true; 10 | 11 | int[] factor = new int[]{2, 3, 5}; 12 | 13 | for (int i = 0; i < factor.length; i++) { 14 | while (num % factor[i] == 0) { 15 | num = num / factor[i]; 16 | } 17 | } 18 | return num == 1; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /Easy/539. Move Zeroes/Solution.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | /** 3 | * @param nums: an integer array 4 | * @return: nothing 5 | */ 6 | public void moveZeroes(int[] nums) { 7 | // write your code here 8 | if (nums == null || nums.length == 0) return; 9 | 10 | int left = 0, right = 0, length = nums.length; 11 | while (right < length) { 12 | if (nums[right] != 0) { 13 | int temp = nums[left]; 14 | nums[left++] = nums[right]; 15 | nums[right] = temp; 16 | } 17 | right++; 18 | } 19 | 20 | } 21 | } -------------------------------------------------------------------------------- /Easy/56. Two Sum/Solution.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | /** 3 | * @param numbers: An array of Integer 4 | * @param target: target = numbers[index1] + numbers[index2] 5 | * @return: [index1, index2] (index1 < index2) 6 | */ 7 | public int[] twoSum(int[] numbers, int target) { 8 | // write your code here 9 | 10 | HashMap map = new HashMap<>(); 11 | 12 | for (int i = 0; i < numbers.length; i++) { 13 | if (map.get(numbers[i]) != null) { 14 | int[] result = {map.get(numbers[i]), i}; 15 | return result; 16 | } 17 | map.put(target - numbers[i], i); 18 | } 19 | 20 | int[] result = {}; 21 | return result; 22 | 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Easy/60. Search Insert Position/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | @param A: an integer sorted array 4 | @param target: an integer to be inserted 5 | @return: An integer 6 | """ 7 | def searchInsert(self, A, target): 8 | # write your code here 9 | if (A == None or len(A) == 0): 10 | return 0 11 | 12 | start, end = 0, len(A) - 1 13 | while (start + 1 < end): 14 | mid = (end - start) // 2 + start 15 | 16 | if (A[mid] == target): 17 | return mid 18 | elif (A[mid] < target): 19 | start = mid 20 | else: 21 | end = mid 22 | 23 | if A[start] >= target: 24 | return start 25 | if A[end] >= target: 26 | return end 27 | return len(A) 28 | -------------------------------------------------------------------------------- /Easy/604. Window Sum/Solution.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | /** 3 | * @param nums: a list of integers. 4 | * @param k: length of window. 5 | * @return: the sum of the element inside the window at each moving. 6 | */ 7 | public int[] winSum(int[] nums, int k) { 8 | // write your code here 9 | if (nums == null || nums.length < k || k <= 0) return new int[0]; 10 | 11 | int length = nums.length; 12 | int[] prefixSum = new int[length + 1]; 13 | int sum = 0; 14 | 15 | // Prefix Sum array 16 | for (int i = 0; i < length; i++) { 17 | sum += nums[i]; 18 | prefixSum[i + 1] = sum; 19 | } 20 | 21 | 22 | int[] result = new int[length - k + 1]; 23 | for (int i = 0; i < length - k + 1; i++) { 24 | result[i] = prefixSum[i + k] - prefixSum[i]; 25 | } 26 | 27 | return result; 28 | } 29 | } -------------------------------------------------------------------------------- /Easy/627. Longest Palindrome/Solution.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Zhenye-Na/lintcode/afd79d790d0a7495d75e6650f80adaa99bd0ff07/Easy/627. Longest Palindrome/Solution.py -------------------------------------------------------------------------------- /Easy/662. Guess Number Higher or Lower/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | The guess API is already defined for you. 3 | @param num, your guess 4 | @return -1 if my number is lower, 1 if my number is higher, otherwise return 0 5 | you can call Guess.guess(num) 6 | """ 7 | 8 | 9 | class Solution: 10 | # @param {int} n an integer 11 | # @return {int} the number you guess 12 | def guessNumber(self, n): 13 | # Write your code here 14 | start, end = 1, n 15 | while start + 1 < end: 16 | mid = (end - start) / 2 + start 17 | 18 | if Guess.guess(mid) == 0: 19 | return mid 20 | elif Guess.guess(mid) > 0: 21 | start = mid 22 | else: 23 | end = mid 24 | 25 | if Guess.guess(start) == 0: 26 | return start 27 | if Guess.guess(end) == 0: 28 | return end 29 | return -1 30 | -------------------------------------------------------------------------------- /Easy/764. Calculate Circumference And Area/Solution.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | /** 3 | * @param r: a Integer represent radius 4 | * @return: the circle's circumference nums[0] and area nums[1] 5 | */ 6 | public double[] calculate(int r) { 7 | // write your code here 8 | return new double[]{3.14 * r * 2, 3.14 * r * r}; 9 | } 10 | } -------------------------------------------------------------------------------- /Easy/82. Single Number/Solution.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | /** 3 | * @param A: An integer array 4 | * @return: An integer 5 | */ 6 | public int singleNumber(int[] A) { 7 | // write your code here 8 | int result = 0, n = A.length; 9 | for (int i = 0; i < n; i++) { 10 | result ^= A[i]; 11 | } 12 | return result; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /Easy/82. Single Number/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | @param A: An integer array 4 | @return: An integer 5 | """ 6 | def singleNumber(self, A): 7 | # write your code here 8 | dict = collections.Counter(A) 9 | for key in dict: 10 | if dict[key] == 1: 11 | return key 12 | -------------------------------------------------------------------------------- /Easy/9. Fizz Buzz/Solution.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | /** 3 | * @param n: An integer 4 | * @return: A list of strings. 5 | */ 6 | public List fizzBuzz(int n) { 7 | // write your code here 8 | List result = new ArrayList<>(); 9 | if (n < 1) return result; 10 | 11 | for (int i = 1; i <= n; i++) { 12 | if (i % 3 == 0 && i % 5 == 0) { 13 | result.add("fizz buzz"); 14 | } else if (i % 3 == 0) { 15 | result.add("fizz"); 16 | } else if (i % 5 == 0) { 17 | result.add("buzz"); 18 | } else { 19 | result.add(String.valueOf(i)); 20 | } 21 | } 22 | 23 | return result; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Easy/900. Closest Binary Search Tree Value/Solution.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Zhenye-Na/lintcode/afd79d790d0a7495d75e6650f80adaa99bd0ff07/Easy/900. Closest Binary Search Tree Value/Solution.py -------------------------------------------------------------------------------- /Easy/988. Arranging Coins/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | @param n: a non-negative integer 4 | @return: the total number of full staircase rows that can be formed 5 | """ 6 | def arrangeCoins(self, n): 7 | # Write your code here 8 | start, end = 0, n 9 | while start + 1 < end: 10 | mid = (end - start) / 2 + start 11 | 12 | if n - self.summation(1, mid) == mid or n - self.summation(1, mid) == mid - 1: 13 | return mid 14 | elif n - self.summation(1, mid) > mid: 15 | start = mid 16 | else: 17 | end = mid 18 | 19 | if n - self.summation(1, start) == start or n - self.summation(1, start) == start - 1: 20 | return start 21 | else: 22 | return end 23 | 24 | 25 | def summation(self, start, end): 26 | return (start + end) * (end - start + 1) / 2; 27 | -------------------------------------------------------------------------------- /Greedy/871.Minimum Factorization/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | @param a: a positive integer 4 | @return: the smallest positive integer whose multiplication of each digit equals to a 5 | """ 6 | 7 | def smallestFactorization(self, a): 8 | # Write your code here 9 | res = '' 10 | for i in range(9, 1, -1): 11 | while a % i == 0: 12 | res = str(i) + res 13 | a //= i 14 | 15 | if a != 1: 16 | return 0 17 | 18 | res = int(res) 19 | 20 | if res > 0x7fffffff: 21 | return 0 22 | else: 23 | return res 24 | -------------------------------------------------------------------------------- /Hash/124.Longest Consecutive Sequence/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | @param num: A list of integers 4 | @return: An integer 5 | """ 6 | def longestConsecutive(self, num): 7 | # write your code here 8 | max_len = 0 9 | if not num or len(num) == 0: 10 | return max_len 11 | 12 | mapping = {number:True for number in num} 13 | for i in range(len(num)): 14 | if num[i] - 1 not in mapping: 15 | left, right = num[i], num[i] + 1 16 | while right in mapping: 17 | right += 1 18 | max_len = max(max_len, right - left) 19 | 20 | return max_len 21 | -------------------------------------------------------------------------------- /Hash/1319.Contains Duplicate II/README.md: -------------------------------------------------------------------------------- 1 | # 1319. Contains Duplicate II 2 | 3 | **Description** 4 | 5 | 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 absolute difference between `i` and `j` is at most `k`. 6 | 7 | **Example** 8 | 9 | Example 1: 10 | 11 | ``` 12 | Input: nums = [1,2,1], k = 0 13 | Output: False 14 | ``` 15 | 16 | Example 2: 17 | 18 | ``` 19 | Input: nums = [1,2,1], k = 2 20 | Output: True 21 | Explanation: nums[0] = nums[2] and 2 - 0 <= 2 22 | ``` -------------------------------------------------------------------------------- /Hash/1319.Contains Duplicate II/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | @param nums: the given array 4 | @param k: the given number 5 | @return: whether there are two distinct indices i and j in the array such that nums[i] = nums[j] and the absolute difference between i and j is at most k 6 | """ 7 | 8 | def containsNearbyDuplicate(self, nums, k): 9 | # Write your code here 10 | if not nums or len(nums) == 0 or k <= 0: 11 | return False 12 | 13 | # map from value to index 14 | mapping = {} 15 | for i in range(len(nums)): 16 | if nums[i] not in mapping: 17 | mapping[nums[i]] = i 18 | else: 19 | if abs(i - mapping[nums[i]]) <= k: 20 | return True 21 | else: 22 | mapping[nums[i]] = i 23 | 24 | return False 25 | -------------------------------------------------------------------------------- /Hash/1320.Contains Duplicate/README.md: -------------------------------------------------------------------------------- 1 | # 1320. Contains Duplicate 2 | 3 | **Description** 4 | 5 | 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. 6 | 7 | **Example** 8 | 9 | Example 1 10 | 11 | ``` 12 | Input: nums = [1, 1] 13 | Output: True 14 | ``` 15 | 16 | Example 2 17 | 18 | ``` 19 | Input: nums = [1, 2, 3] 20 | Output: False 21 | ``` 22 | -------------------------------------------------------------------------------- /Hash/1320.Contains Duplicate/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | @param nums: the given array 4 | @return: if any value appears at least twice in the array 5 | """ 6 | 7 | def containsDuplicate(self, nums): 8 | # Write your code here 9 | return len(nums) != len(set(nums)) 10 | -------------------------------------------------------------------------------- /Hash/171.Anagrams/Solution.py: -------------------------------------------------------------------------------- 1 | from collections import defaultdict 2 | 3 | 4 | class Solution: 5 | """ 6 | @param strs: A list of strings 7 | @return: A list of strings 8 | """ 9 | def anagrams(self, strs): 10 | # write your code here 11 | result = [] 12 | if not strs or len(strs) == 0: 13 | return result 14 | 15 | mapping = defaultdict(list) 16 | for word in strs: 17 | word_set = "".join(sorted(word)) 18 | mapping[word_set].append(word) 19 | 20 | for key in mapping: 21 | if len(mapping[key]) >= 2: 22 | result += mapping[key] 23 | 24 | return result 25 | -------------------------------------------------------------------------------- /Heap/104.Merge K Sorted Lists/Solution_Heap1.py: -------------------------------------------------------------------------------- 1 | import heapq 2 | 3 | """ 4 | Definition of ListNode 5 | class ListNode(object): 6 | 7 | def __init__(self, val, next=None): 8 | self.val = val 9 | self.next = next 10 | """ 11 | class Solution: 12 | """ 13 | @param lists: a list of ListNode 14 | @return: The head of one sorted list. 15 | """ 16 | def mergeKLists(self, lists): 17 | # write your code here 18 | if not lists or len(lists) == 0: 19 | return None 20 | 21 | pq = [] 22 | for l in lists: 23 | while l: 24 | heapq.heappush(pq, l.val) 25 | l = l.next 26 | 27 | dummy = ListNode(0) 28 | p = dummy 29 | while len(pq) > 0: 30 | p.next = ListNode(heapq.heappop(pq)) 31 | p = p.next 32 | 33 | return dummy.next 34 | -------------------------------------------------------------------------------- /Heap/1281.Top K Frequent Elements/Solution.py: -------------------------------------------------------------------------------- 1 | from heapq import heappush, heappop 2 | from collections import Counter 3 | 4 | 5 | class Solution: 6 | """ 7 | @param nums: the given array 8 | @param k: the given k 9 | @return: the k most frequent elements 10 | """ 11 | 12 | def topKFrequent(self, nums, k): 13 | # Write your code here 14 | if not nums or len(nums) == 0: 15 | return [] 16 | 17 | counter = Counter(nums) 18 | candidates = [] 19 | for ele in counter: 20 | if len(candidates) < k: 21 | heappush(candidates, (counter[ele], ele)) 22 | else: 23 | heappush(candidates, (counter[ele], ele)) 24 | heappop(candidates) 25 | 26 | res = [] 27 | for count, ele in candidates: 28 | res.append(ele) 29 | 30 | return res 31 | -------------------------------------------------------------------------------- /Heap/130.Heapify/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | @param: A: Given an integer array 4 | @return: nothing 5 | """ 6 | def heapify(self, A): 7 | # write your code here 8 | n = len(A) 9 | for i in range(n, -1, -1): 10 | self.helper(A, i) 11 | 12 | def helper(self, A, i): 13 | lowest = i # root is the smallest element 14 | left = i * 2 + 1 # left child 15 | right = i * 2 + 2 # right child 16 | 17 | # Find smallest in left / right / root 18 | if left < len(A) and A[i] > A[left]: 19 | lowest = left 20 | 21 | if right < len(A) and A[lowest] > A[right]: 22 | lowest = right 23 | 24 | if lowest != i: 25 | 26 | # Swap with the smallest 27 | A[i], A[lowest] = A[lowest], A[i] 28 | 29 | # Re-heapify again 30 | self.helper(A, lowest) 31 | -------------------------------------------------------------------------------- /Heap/4.Ugly Number II/Solution.py: -------------------------------------------------------------------------------- 1 | from heapq import heappush, heappop 2 | 3 | 4 | class Solution: 5 | """ 6 | @param n: An integer 7 | @return: return a integer as description. 8 | """ 9 | def nthUglyNumber(self, n): 10 | # write your code here 11 | pq = [] 12 | history = set() 13 | history.add(1) 14 | heappush(pq, 1) 15 | 16 | count, res = 0, -1 17 | while count < n: 18 | res = heappop(pq) 19 | count += 1 20 | nums = [res * 2, res * 3, res * 5] 21 | for i in nums: 22 | if i not in history: 23 | history.add(i) 24 | heappush(pq, i) 25 | 26 | return res 27 | -------------------------------------------------------------------------------- /Heap/486.Merge K Sorted Arrays/Solution_heapq.py: -------------------------------------------------------------------------------- 1 | import heapq 2 | 3 | 4 | class Solution: 5 | """ 6 | @param arrays: k sorted integer arrays 7 | @return: a sorted array 8 | """ 9 | def mergekSortedArrays(self, arrays): 10 | # write your code here 11 | result = [] 12 | heap = [] 13 | for index, array in enumerate(arrays): 14 | if len(array) == 0: 15 | continue 16 | heapq.heappush(heap, (array[0], index, 0)) 17 | 18 | while len(heap): 19 | val, x, y = heap[0] 20 | heapq.heappop(heap) 21 | result.append(val) 22 | if y + 1 < len(arrays[x]): 23 | heapq.heappush(heap, (arrays[x][y + 1], x, y + 1)) 24 | 25 | return result 26 | -------------------------------------------------------------------------------- /Heap/543.Kth Largest in N Arrays/Solution_MinHeap.py: -------------------------------------------------------------------------------- 1 | from heapq import heappush, heapreplace 2 | 3 | class Solution: 4 | """ 5 | @param arrays: a list of array 6 | @param k: An integer 7 | @return: an integer, K-th largest element in N arrays 8 | """ 9 | def KthInArrays(self, arrays, k): 10 | # write your code here 11 | if not arrays or len(arrays) == 0: 12 | return None 13 | 14 | heap = [] 15 | for array in arrays: 16 | if not array or len(array) == 0: 17 | continue 18 | 19 | for num in array: 20 | if len(heap) >= k: 21 | if num > heap[0]: 22 | heapreplace(heap, num) 23 | else: 24 | heappush(heap, num) 25 | 26 | return heap[0] 27 | -------------------------------------------------------------------------------- /Heap/544.Top k Largest Numbers/Solution_Heap.java: -------------------------------------------------------------------------------- 1 | // base on heap 2 | class Solution { 3 | /* 4 | * @param nums an integer array 5 | * @param k an integer 6 | * @return the top k largest numbers in array 7 | */ 8 | public int[] topk(int[] nums, int k) { 9 | PriorityQueue minheap = new PriorityQueue (k, new Comparator() { 10 | public int compare(Integer o1, Integer o2) { 11 | return o1 - o2; 12 | } 13 | }); 14 | 15 | for (int i: nums) { 16 | minheap.add(i); 17 | if (minheap.size() > k) { 18 | minheap.poll(); 19 | } 20 | } 21 | 22 | int[] result = new int[k]; 23 | for (int i = 0; i < result.length; i++) { 24 | result[k - i - 1] = minheap.poll(); 25 | } 26 | return result; 27 | } 28 | } -------------------------------------------------------------------------------- /Heap/544.Top k Largest Numbers/Solution_heapq.py: -------------------------------------------------------------------------------- 1 | import heapq 2 | 3 | class Solution: 4 | """ 5 | @param nums: an integer array 6 | @param k: An integer 7 | @return: the top k largest numbers in array 8 | """ 9 | def topk(self, nums, k): 10 | # write your code here 11 | return heapq.nlargest(k, nums) 12 | -------------------------------------------------------------------------------- /Heap/545.Top k Largest Numbers II/Solution.py: -------------------------------------------------------------------------------- 1 | import heapq 2 | 3 | 4 | class Solution: 5 | """ 6 | @param: k: An integer 7 | """ 8 | def __init__(self, k): 9 | # do intialization if necessary 10 | self.pq = [] 11 | self.k = k 12 | 13 | """ 14 | @param: num: Number to be added 15 | @return: nothing 16 | """ 17 | def add(self, num): 18 | # write your code here 19 | heapq.heappush(self.pq, num) 20 | 21 | """ 22 | @return: Top k element 23 | """ 24 | def topk(self): 25 | # write your code here 26 | return heapq.nlargest(self.k, self.pq) 27 | -------------------------------------------------------------------------------- /Heap/791.Merge Number/Solution.py: -------------------------------------------------------------------------------- 1 | from heapq import heappush, heappop 2 | 3 | 4 | class Solution: 5 | """ 6 | @param numbers: the numbers 7 | @return: the minimum cost 8 | """ 9 | 10 | def mergeNumber(self, numbers): 11 | # Write your code here 12 | if not numbers or len(numbers) == 0: 13 | return 0 14 | 15 | heap = [] 16 | for num in numbers: 17 | heappush(heap, num) 18 | 19 | ans = 0 20 | while len(heap) >= 2: 21 | num1 = heappop(heap) 22 | num2 = heappop(heap) 23 | ans += num1 + num2 24 | heappush(heap, num1 + num2) 25 | 26 | return ans 27 | -------------------------------------------------------------------------------- /Interviews/amazon/1797.optimalUtilization/Solution_TwoPointers.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | @param A: a integer sorted array 4 | @param B: a integer sorted array 5 | @param K: a integer 6 | @return: return a pair of index 7 | """ 8 | def optimalUtilization(self, A, B, K): 9 | # write your code here 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /Interviews/goldmansachs/1375.Substring With At Least K Distinct Characters/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | @param s: a string 4 | @param k: an integer 5 | @return: the number of substrings there are that contain at least k distinct characters 6 | """ 7 | 8 | def kDistinctCharacters(self, s, k): 9 | # Write your code here 10 | res = 0 11 | if not s or len(s) < k: 12 | return res 13 | 14 | for left in range(len(s)): 15 | right = left 16 | counter = set([]) 17 | while right < len(s) and len(counter) < k: 18 | counter.add(s[right]) 19 | right += 1 20 | 21 | if len(counter) == k: 22 | res += len(s) - right + 1 23 | 24 | return res 25 | -------------------------------------------------------------------------------- /Interviews/goldmansachs/1790.Rotate String II/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | @param string: An array of char 4 | @param left: a left offset 5 | @param right: a right offset 6 | @return: return a rotate string 7 | """ 8 | def RotateString2(self, string, left, right): 9 | # write your code here 10 | if not string or len(string) == 0: 11 | return string 12 | 13 | left, right = left % len(string), right % len(string) 14 | offset = 0 15 | if left >= right: 16 | offset = left - right 17 | else: 18 | offset = len(string) - (right - left) 19 | 20 | prefix = string[:offset][::-1] 21 | postfix = string[offset:][::-1] 22 | newString = prefix + postfix 23 | return newString[::-1] 24 | -------------------------------------------------------------------------------- /Interviews/goldmansachs/1804.Find The Rank/Solution_Heap.py: -------------------------------------------------------------------------------- 1 | from heapq import heappush, heappop 2 | 3 | 4 | class Solution: 5 | """ 6 | @param scores: two dimensional array 7 | @param K: a integer 8 | @return: return a integer 9 | """ 10 | 11 | def FindTheRank(self, scores, K): 12 | # write your code here 13 | heap = [] 14 | for idx, score in enumerate(scores): 15 | # keep a min-heap with size K 16 | total = sum(score) 17 | if len(heap) < K: 18 | heappush(heap, (total, idx)) 19 | else: 20 | # len(heap) >= K 21 | if total >= heap[0][0]: 22 | heappop(heap) 23 | heappush(heap, (total, idx)) 24 | 25 | return heap[0][1] 26 | -------------------------------------------------------------------------------- /Interviews/goldmansachs/1804.Find The Rank/Solution_Sort.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | @param scores: two dimensional array 4 | @param K: a integer 5 | @return: return a integer 6 | """ 7 | 8 | def FindTheRank(self, scores, K): 9 | # write your code here 10 | tuple_scores = [] 11 | for idx, score in enumerate(scores): 12 | tuple_scores.append([score, idx]) 13 | 14 | sorted_scores = sorted(tuple_scores, key=lambda x: sum(x[0])) 15 | 16 | return sorted_scores[::-1][K - 1][1] 17 | -------------------------------------------------------------------------------- /Interviews/goldmansachs/769.Spiral Array/README.md: -------------------------------------------------------------------------------- 1 | # 769. Spiral Array 2 | 3 | **Description** 4 | 5 | Given an integer `n`, return a spiral array of `n * n` sizes. 6 | 7 | **Example** 8 | 9 | Example 1: 10 | 11 | ``` 12 | Input : n = 3 13 | Output : 14 | [ 15 | [1,2,3] 16 | [8,9,4] 17 | [7,6,5] 18 | ] 19 | ``` 20 | 21 | Example 2: 22 | 23 | ``` 24 | Input: n = 5 25 | Output: 26 | [ 27 | [1,2,3,4,5] 28 | [16,17,18,19,6] 29 | [15,24,25,20,7] 30 | [14,23,22,21,8] 31 | [13,12,11,10,9] 32 | ] 33 | ``` -------------------------------------------------------------------------------- /Linked_List/102.Linked List Cycle/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | Definition of ListNode 3 | class ListNode(object): 4 | def __init__(self, val, next=None): 5 | self.val = val 6 | self.next = next 7 | """ 8 | 9 | class Solution: 10 | """ 11 | @param head: The first node of linked list. 12 | @return: True if it has a cycle, or false 13 | """ 14 | def hasCycle(self, head): 15 | # write your code here 16 | if not head: 17 | return False 18 | 19 | slow, fast = head, head.next 20 | 21 | while slow != fast: 22 | # fast pointer is None -> no cycle 23 | if not fast or not fast.next: 24 | return False 25 | slow = slow.next 26 | fast = fast.next.next 27 | 28 | # If slow and fast pointers point to the same element after loop -> cycle exists 29 | return True 30 | -------------------------------------------------------------------------------- /Linked_List/1292.Odd Even Linked List/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | Definition of ListNode 3 | class ListNode(object): 4 | def __init__(self, val, next=None): 5 | self.val = val 6 | self.next = next 7 | """ 8 | 9 | class Solution: 10 | """ 11 | @param head: a singly linked list 12 | @return: Modified linked list 13 | """ 14 | def oddEvenList(self, head): 15 | # write your code here 16 | if not head: 17 | return head 18 | 19 | odd = head 20 | even = head.next 21 | 22 | o, e = odd, even 23 | while e and e.next: 24 | o.next = e.next 25 | o = o.next 26 | e.next = o.next 27 | e = e.next 28 | 29 | o.next = even 30 | return head 31 | -------------------------------------------------------------------------------- /Linked_List/35.Reverse Linked List/Solution.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition of singly-linked-list: 3 | * 4 | * class ListNode { 5 | * public: 6 | * int val; 7 | * ListNode *next; 8 | * ListNode(int val) { 9 | * this->val = val; 10 | * this->next = NULL; 11 | * } 12 | * } 13 | */ 14 | 15 | class Solution { 16 | public: 17 | /** 18 | * @param head: n 19 | * @return: The new head of reversed linked list. 20 | */ 21 | ListNode * reverse(ListNode * head) { 22 | // write your code here 23 | ListNode *new_head = NULL; 24 | while (head) { 25 | ListNode *next = head->next; 26 | head->next = new_head; 27 | new_head = head; 28 | head = next; 29 | } 30 | return new_head; 31 | } 32 | }; -------------------------------------------------------------------------------- /Linked_List/35.Reverse Linked List/Solution.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for ListNode 3 | * public class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode(int x) { 7 | * val = x; 8 | * next = null; 9 | * } 10 | * } 11 | */ 12 | 13 | public class Solution { 14 | /** 15 | * @param head: n 16 | * @return: The new head of reversed linked list. 17 | */ 18 | public ListNode reverse(ListNode head) { 19 | // write your code here 20 | ListNode prev = null; 21 | 22 | while (head != null) { 23 | ListNode tmp = head.next; 24 | head.next = prev; 25 | prev = head; 26 | head = tmp; 27 | } 28 | 29 | return prev; 30 | } 31 | } -------------------------------------------------------------------------------- /Linked_List/35.Reverse Linked List/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | Definition of ListNode 3 | 4 | class ListNode(object): 5 | 6 | def __init__(self, val, next=None): 7 | self.val = val 8 | self.next = next 9 | """ 10 | 11 | class Solution: 12 | """ 13 | @param head: n 14 | @return: The new head of reversed linked list. 15 | """ 16 | def reverse(self, head): 17 | # write your code here 18 | prev = None 19 | while head: 20 | # mark next list node 21 | tmp = head.next 22 | 23 | # swap order 24 | head.next = prev 25 | 26 | # update pointers 27 | prev = head 28 | head = tmp 29 | 30 | return prev 31 | -------------------------------------------------------------------------------- /Linked_List/372.Delete Node in a Linked List/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | Definition of ListNode 3 | class ListNode(object): 4 | 5 | def __init__(self, val, next=None): 6 | self.val = val 7 | self.next = next 8 | """ 9 | 10 | 11 | class Solution: 12 | """ 13 | @param: node: the node in the list should be deleted 14 | @return: nothing 15 | """ 16 | def deleteNode(self, node): 17 | # write your code here 18 | if not node or not node.next: 19 | node = None 20 | return 21 | 22 | node.val = node.next.val 23 | node.next = node.next.next -------------------------------------------------------------------------------- /Math/1095.Maximum Swap/Solution_1.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | @param num: a non-negative intege 4 | @return: the maximum valued number 5 | """ 6 | def maximumSwap(self, num): 7 | # Write your code here 8 | digits = list(reversed([i for i in str(num)])) 9 | 10 | swappingFrom, swappingTo = 0, 0 11 | runningMaxIndex, runningMax = 0, digits[0] 12 | for i in range(1, len(digits)): 13 | print(swappingFrom, swappingTo) 14 | if digits[i] < runningMax: 15 | swappingFrom = runningMaxIndex 16 | swappingTo = i 17 | elif digits[i] > runningMax: 18 | runningMaxIndex, runningMax = i, digits[i] 19 | 20 | if swappingTo != 0: 21 | digits[swappingTo], digits[swappingFrom] = digits[swappingFrom], digits[swappingTo] 22 | 23 | return int("".join(reversed(digits))) 24 | -------------------------------------------------------------------------------- /Math/1095.Maximum Swap/Solution_2.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | @param num: a non-negative intege 4 | @return: the maximum valued number 5 | """ 6 | def maximumSwap(self, num): 7 | # Write your code here 8 | res, num = num, list(str(num)) 9 | for i in range(len(num) - 1): 10 | for j in range(i + 1, len(num)): 11 | if int(num[j]) > int(num[i]): 12 | # swap 13 | tmp = int("".join(num[:i] + [num[j]] + num[i + 1:j] + [num[i]] + num[j + 1:])) 14 | res = max(res, tmp) 15 | return res -------------------------------------------------------------------------------- /Math/1277.Water and Jug Problem/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | @param x: the given number x 4 | @param y: the given number y 5 | @param z: the given number z 6 | @return: whether it is possible to measure exactly z litres using these two jugs 7 | """ 8 | 9 | def canMeasureWater(self, x, y, z): 10 | # Write your code here 11 | if z < 0 or x + y < z: 12 | return False 13 | 14 | def gcd(x, y): 15 | # Using Euclidean Algorithm 16 | while y: 17 | x, y = y, x % y 18 | return x 19 | 20 | gcd = gcd(x, y) 21 | if z % gcd == 0: 22 | return True 23 | return False 24 | -------------------------------------------------------------------------------- /Math/730.Sum of All Subsets/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | @param n: the given number 4 | @return: Sum of elements in subsets 5 | """ 6 | def subSum(self, n): 7 | # write your code here 8 | if not n or n == 0: 9 | return 0 10 | 11 | self.total = 0 12 | self._find_all_subsets(n, [], 1) 13 | return self.total 14 | 15 | def _find_all_subsets(self, n, tmp, start): 16 | self.total += sum(tmp) 17 | 18 | for i in range(start, n + 1): 19 | tmp.append(i) 20 | self._find_all_subsets(n, tmp, i + 1) 21 | tmp.pop() 22 | -------------------------------------------------------------------------------- /Medium/116. Jump Game/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | @param A: A list of integers 4 | @return: A boolean 5 | """ 6 | def canJump(self, A): 7 | # write your code here 8 | dp = [False] * (len(A)) 9 | dp[0] = True 10 | 11 | for i in range(1, len(A)): 12 | dp[i] = False 13 | 14 | for j in range(i): 15 | if (dp[j] == True and j + A[j] >= i): 16 | dp[i] = True 17 | break 18 | 19 | return dp[-1] 20 | -------------------------------------------------------------------------------- /Medium/117. Jump Game II/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | @param A: A list of integers 4 | @return: An integer 5 | """ 6 | def jump(self, A): 7 | # write your code here 8 | jumps = [len(A)] * len(A) 9 | jumps[0] = 0 10 | 11 | for i in range(1, len(A)): 12 | for j in range(i): 13 | if A[j] + j >= i: 14 | jumps[i] = min(jumps[i], jumps[j] + 1) 15 | 16 | return jumps[-1] 17 | -------------------------------------------------------------------------------- /Medium/130. Heapify/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | @param: A: Given an integer array 4 | @return: nothing 5 | """ 6 | def heapify(self, A): 7 | # write your code here 8 | n = len(A) 9 | for i in range(n, -1, -1): 10 | self.helper(A, i) 11 | 12 | 13 | 14 | def helper(self, A, i): 15 | lowest = i # root is the smallest element 16 | left = i * 2 + 1 # left child 17 | right = i * 2 + 2 # right child 18 | 19 | # Find smallest in left / right / root 20 | if left < len(A) and A[i] > A[left]: 21 | lowest = left 22 | 23 | if right < len(A) and A[lowest] > A[right]: 24 | lowest = right 25 | 26 | if lowest != i: 27 | 28 | # Swap with the smallest 29 | A[i], A[lowest] = A[lowest], A[i] 30 | 31 | # Re-heapify again 32 | self.helper(A, lowest) 33 | -------------------------------------------------------------------------------- /Medium/139. Subarray Sum Closest/Solution.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Zhenye-Na/lintcode/afd79d790d0a7495d75e6650f80adaa99bd0ff07/Medium/139. Subarray Sum Closest/Solution.java -------------------------------------------------------------------------------- /Medium/143. Sort Colors II/Solution.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Zhenye-Na/lintcode/afd79d790d0a7495d75e6650f80adaa99bd0ff07/Medium/143. Sort Colors II/Solution.java -------------------------------------------------------------------------------- /Medium/148. Sort Colors/Solution.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | /** 3 | * @param nums: A list of integer which is 0, 1 or 2 4 | * @return: nothing 5 | */ 6 | public void sortColors(int[] nums) { 7 | // write your code here 8 | if (nums == null || nums.length == 0) { 9 | return; 10 | } 11 | 12 | int left = 0, right = nums.length - 1, length = nums.length; 13 | 14 | for (int i = 0; i < length; i++) { 15 | if (nums[i] < 1) { 16 | swap(nums, left, i); 17 | left++; 18 | } else if (nums[i] > 1) { 19 | swap(nums, right, i); 20 | i--; 21 | right--; 22 | } 23 | } 24 | } 25 | 26 | 27 | private void swap(int[] nums, int left, int right) { 28 | int temp = nums[left]; 29 | nums[left] = nums[right]; 30 | nums[right] = temp; 31 | } 32 | 33 | } -------------------------------------------------------------------------------- /Medium/159. Find Minimum in Rotated Sorted Array/Solution.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | /** 3 | * @param nums: a rotated sorted array 4 | * @return: the minimum number in the array 5 | */ 6 | public int findMin(int[] nums) { 7 | // write your code here 8 | 9 | if (nums.length == 0) return -1; 10 | 11 | int start = 0, end = nums.length - 1; 12 | int target = nums[end]; 13 | 14 | while (start + 1 < end) { 15 | int mid = (end - start) / 2 + start; 16 | 17 | if (nums[mid] < target) { 18 | end = mid; 19 | } else { 20 | start = mid; 21 | } 22 | } 23 | 24 | if (nums[start] < target) { 25 | return nums[start]; 26 | } else { 27 | return nums[end]; 28 | } 29 | 30 | 31 | } 32 | } -------------------------------------------------------------------------------- /Medium/159. Find Minimum in Rotated Sorted Array/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | @param nums: a rotated sorted array 4 | @return: the minimum number in the array 5 | """ 6 | def findMin(self, nums): 7 | # write your code here 8 | start, end = 0, len(nums) - 1 9 | target = nums[-1] 10 | while (start + 1 < end): 11 | mid = (start + end) // 2 12 | 13 | if (nums[mid] > target): 14 | start = mid 15 | elif (nums[mid] < target): 16 | end = mid 17 | 18 | 19 | if nums[start] < nums[end]: 20 | return nums[start] 21 | else: 22 | return nums[end] 23 | -------------------------------------------------------------------------------- /Medium/160. Find Minimum in Rotated Sorted Array II/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | @param nums: a rotated sorted array 4 | @return: the minimum number in the array 5 | """ 6 | def findMin(self, nums): 7 | # write your code here 8 | start, end = 0, len(nums) - 1 9 | 10 | while (start + 1 < end): 11 | mid = (start + end) / 2 12 | 13 | if (nums[mid] > nums[end]): 14 | start = mid 15 | elif (nums[mid] < nums[end]): 16 | end = mid 17 | else: 18 | end = end - 1 19 | 20 | return nums[start] if nums[start] < nums[end] else nums[end] 21 | -------------------------------------------------------------------------------- /Medium/163. Unique Binary Search Trees/Solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | /** 4 | * @param n: An integer 5 | * @return: An integer 6 | */ 7 | int numTrees(int n) { 8 | // write your code here 9 | // Table to store results of subproblems 10 | unsigned long int catalan[n+1]; 11 | 12 | // Initialize first two values in table 13 | catalan[0] = catalan[1] = 1; 14 | 15 | // Fill entries in catalan[] using recursive formula 16 | for (int i=2; i<=n; i++) 17 | { 18 | catalan[i] = 0; 19 | for (int j=0; j i ~ j is 1, other positions are 0's 16 | int mask = ~(((ones << (31 - j)) >>> (31 - j + i)) << i); 17 | 18 | // Keep other position the same, reset ith ~ jth in m and copy m to n 19 | return (mask & n) | (m << i); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /Medium/182. Delete Digits/Solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | /** 4 | * @param A: A positive integer which has N digits, A is a string 5 | * @param k: Remove k digits 6 | * @return: A string 7 | */ 8 | string DeleteDigits(string &A, int k) { 9 | // write your code here 10 | string res; 11 | int keep = A.size() - k; 12 | for (int i=0; i0 && res.back()>A[i] && k>0) { 14 | res.pop_back(); 15 | k--; 16 | } 17 | res.push_back(A[i]); 18 | } 19 | res.erase(keep, string::npos); 20 | 21 | // trim leading zeros 22 | int s = 0; 23 | while (s<(int)res.size()-1 && res[s]=='0') s++; 24 | res.erase(0, s); 25 | 26 | return res=="" ? "0" : res; 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /Medium/182. Delete Digits/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | @param A: A positive integer which has N digits, A is a string 4 | @param k: Remove k digits 5 | @return: A string 6 | """ 7 | def DeleteDigits(self, A, k): 8 | # write your code here 9 | A = list(A) 10 | while k > 0: 11 | f = True 12 | for i in xrange(len(A)-1): 13 | if A[i] > A[i+1]: 14 | del A[i] 15 | f = False 16 | break 17 | if f and len(A)>1: 18 | A.pop() 19 | k -= 1 20 | while len(A) > 1 and A[0]=='0': 21 | del A[0] 22 | return ''.join(A) 23 | -------------------------------------------------------------------------------- /Medium/187. Gas Station/Solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | /** 4 | * @param gas: An array of integers 5 | * @param cost: An array of integers 6 | * @return: An integer 7 | */ 8 | int canCompleteCircuit(vector &gas, vector &cost) { 9 | // write your code here 10 | int start = 0; // 起始位置 11 | int remain = 0; // 当前剩余燃料 12 | int debt = 0; // 前面没能走完的路上欠的债 13 | 14 | for (int i = 0; i < gas.size(); i++) { 15 | remain += gas[i] - cost[i]; 16 | if (remain < 0) { 17 | debt += remain; 18 | start = i + 1; 19 | remain = 0; 20 | } 21 | } 22 | 23 | return remain + debt >= 0 ? start : -1; 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /Medium/187. Gas Station/Solution.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Zhenye-Na/lintcode/afd79d790d0a7495d75e6650f80adaa99bd0ff07/Medium/187. Gas Station/Solution.py -------------------------------------------------------------------------------- /Medium/189. First Missing Positive/Solution.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | /** 3 | * @param nums: An array of integers 4 | * @return: An integer 5 | */ 6 | public int firstMissingPositive(int[] nums) { 7 | // write your code here 8 | if (nums == null || nums.length == 0) return 1; 9 | 10 | int length = nums.length; 11 | for (int i = 0; i < length; i++) { 12 | while (nums[i] > 0 && nums[i] <= length && nums[i] != nums[nums[i] - 1]) { 13 | int tmp = nums[nums[i] - 1]; 14 | nums[nums[i] - 1] = nums[i]; 15 | nums[i] = tmp; 16 | } 17 | } 18 | 19 | for (int j = 0; j < length; j++) { 20 | if (nums[j] != j + 1) { 21 | return j + 1; 22 | } 23 | } 24 | return length + 1; 25 | 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Medium/363. Trapping Rain Water/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | @param heights: a list of integers 4 | @return: a integer 5 | """ 6 | def trapRainWater(self, heights): 7 | # write your code here 8 | if not heights: 9 | return 0 10 | 11 | left, right = 0, len(heights) - 1 12 | leftMax, rightMax = 0, 0 13 | result = 0 14 | 15 | while left < right: 16 | if heights[left] < heights[right]: 17 | leftMax = max(heights[left], leftMax) 18 | result += leftMax - heights[left] 19 | left += 1 20 | else: 21 | rightMax = max(heights[right], rightMax) 22 | result += rightMax - heights[right] 23 | right -= 1 24 | 25 | return result -------------------------------------------------------------------------------- /Medium/38. Search a 2D Matrix II/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | @param matrix: A list of lists of integers 4 | @param target: An integer you want to search in matrix 5 | @return: An integer indicate the total occurrence of target in the given matrix 6 | """ 7 | def searchMatrix(self, matrix, target): 8 | # write your code here 9 | if matrix == [] or matrix[0] == []: 10 | return 0 11 | 12 | number = 0 13 | for row in matrix: 14 | if row[0] > target: 15 | continue 16 | for elem in row: 17 | if elem == target: 18 | number += 1 19 | 20 | return number 21 | -------------------------------------------------------------------------------- /Medium/384. Longest Substring Without Repeating Characters/README.md: -------------------------------------------------------------------------------- 1 | # 384. Longest Substring Without Repeating Characters 2 | 3 | - **Description** 4 | - Given a string, find the length of the longest substring without repeating characters. 5 | 6 | - **Example** 7 | - For example, the longest substring without repeating letters for `"abcabcbb"` is `"abc"`, which the length is `3`. 8 | - For `"bbbbb"` the longest substring is `"b"`, with the length of `1`. 9 | 10 | - **Challenge** 11 | - `O(n)` time -------------------------------------------------------------------------------- /Medium/428. Pow(x, n)/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | @param: x: the base number 4 | @param: n: the power number 5 | @return: the result 6 | """ 7 | def myPow(self, x, n): 8 | # write your code here 9 | if (x == 0): 10 | return 0 11 | 12 | if (n == 0): 13 | return 1 14 | 15 | if (n == 1): 16 | return x 17 | 18 | if n < 0: 19 | x = 1 / x 20 | n = - n 21 | 22 | tmp = self.myPow(x, n / 2) 23 | 24 | if (n % 2 == 0): 25 | return tmp * tmp 26 | else: 27 | return x * tmp * tmp -------------------------------------------------------------------------------- /Medium/48. Majority Number III/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | 48. Majority Number III 3 | """ 4 | 5 | # O(n) time 6 | # O(n) extra space 7 | 8 | class Solution: 9 | """ 10 | @param nums: A list of integers 11 | @param k: An integer 12 | @return: The majority number 13 | """ 14 | def majorityNumber(self, nums, k): 15 | # write your code here 16 | limit = len(nums) / k 17 | dict = {} 18 | 19 | for num in nums: 20 | dict[num] = dict.get(num, 0) + 1 21 | 22 | if dict[num] > limit: 23 | return num 24 | -------------------------------------------------------------------------------- /Medium/575. Decode String/README.md: -------------------------------------------------------------------------------- 1 | # 575. Decode String (Expression Expand) 2 | 3 | - **Description** 4 | - Given an expression s includes numbers, letters and brackets. Number represents the number of repetitions inside the brackets(can be a string or another expression).Please expand expression to be a string. 5 | - **Example** 6 | - `s = abc3[a]`, return `abcaaa` 7 | - `s = 3[abc]`, return `abcabcabc` 8 | - `s = 4[ac]dy`, return `acacacacdy` 9 | - `s = 3[2[ad]3[pf]]xyz`, return `adadpfpfpfadadpfpfpfadadpfpfpfxyz` 10 | - **Challenge** 11 | - Can you do it without recursion? 12 | 13 | 14 | ## Solution 15 | 16 | 17 | 18 | ### Code 19 | 20 | ```java 21 | public class Solution { 22 | /** 23 | * @param s: an expression includes numbers, letters and brackets 24 | * @return: a string 25 | */ 26 | public String expressionExpand(String s) { 27 | // write your code here 28 | } 29 | } 30 | ``` -------------------------------------------------------------------------------- /Medium/575. Decode String/Solution.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Zhenye-Na/lintcode/afd79d790d0a7495d75e6650f80adaa99bd0ff07/Medium/575. Decode String/Solution.java -------------------------------------------------------------------------------- /Medium/58. 4Sum/Solution.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Zhenye-Na/lintcode/afd79d790d0a7495d75e6650f80adaa99bd0ff07/Medium/58. 4Sum/Solution.java -------------------------------------------------------------------------------- /Medium/609. Two Sum - Less than or equal to target/Solution.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | /** 3 | * @param nums: an array of integer 4 | * @param target: an integer 5 | * @return: an integer 6 | */ 7 | public int twoSum5(int[] nums, int target) { 8 | // write your code here 9 | if (nums == null || nums.length == 0) { 10 | return 0; 11 | } 12 | 13 | Arrays.sort(nums); 14 | 15 | int left = 0, right = nums.length - 1, length = nums.length - 1, count = 0; 16 | 17 | while (left < right) { 18 | 19 | while (left < right && nums[left] + nums[right] <= target) { 20 | count++; 21 | left++; 22 | } 23 | left = 0; 24 | right--; 25 | } 26 | return count; 27 | 28 | } 29 | } -------------------------------------------------------------------------------- /Medium/74. First Bad Version/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | class SVNRepo: 3 | @classmethod 4 | def isBadVersion(cls, id) 5 | # Run unit tests to check whether verison `id` is a bad version 6 | # return true if unit tests passed else false. 7 | You can use SVNRepo.isBadVersion(10) to check whether version 10 is a 8 | bad version. 9 | """ 10 | 11 | 12 | class Solution: 13 | """ 14 | @param: n: An integer 15 | @return: An integer which is the first bad version. 16 | """ 17 | def findFirstBadVersion(self, n): 18 | # write your code here 19 | start, end = 1, n 20 | 21 | while (start + 1 < end): 22 | mid = (start + end) / 2 23 | 24 | if SVNRepo.isBadVersion(mid): 25 | end = mid 26 | else: 27 | start = mid 28 | 29 | return start if SVNRepo.isBadVersion(start) else end 30 | -------------------------------------------------------------------------------- /Medium/75. Find Peak Element/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | @param: A: An integers array. 4 | @return: return any of peek positions. 5 | """ 6 | def findPeak(self, A): 7 | # write your code here 8 | start, end = 0, len(A) - 1 9 | while (start + 1 < end): 10 | P = (start + end) // 2 11 | 12 | # A[mid] is one of peaks 13 | if A[P] > A[P - 1] and A[P] > A[P + 1]: 14 | return P 15 | # Ascending area 16 | elif A[P] > A[P - 1] and A[P] < A[P + 1]: 17 | start = P 18 | # Descending area 19 | else: 20 | end = P 21 | 22 | return start if A[start] >= A[end] else end 23 | -------------------------------------------------------------------------------- /Medium/77. Longest Common Subsequence/lcs.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Zhenye-Na/lintcode/afd79d790d0a7495d75e6650f80adaa99bd0ff07/Medium/77. Longest Common Subsequence/lcs.png -------------------------------------------------------------------------------- /Medium/79. Longest Common Substring/Solution.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Zhenye-Na/lintcode/afd79d790d0a7495d75e6650f80adaa99bd0ff07/Medium/79. Longest Common Substring/Solution.java -------------------------------------------------------------------------------- /Medium/84. Single Number III/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | @param A: An integer array 4 | @return: An integer array 5 | """ 6 | def singleNumberIII(self, A): 7 | # write your code here 8 | if A is None or len(A) % 2 != 0: 9 | return [] 10 | 11 | xor = 0 12 | for num in A: 13 | xor ^= num 14 | 15 | diff = xor & (~ (xor - 1)) 16 | res = [0] * 2 17 | for num in A: 18 | if num & diff == 0: 19 | res[0] ^= num 20 | else: 21 | res[1] ^= num 22 | 23 | return res 24 | -------------------------------------------------------------------------------- /Medium/95. Validate Binary Search Tree/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | Definition of TreeNode: 3 | class TreeNode: 4 | def __init__(self, val): 5 | self.val = val 6 | self.left, self.right = None, None 7 | """ 8 | 9 | class Solution: 10 | """ 11 | @param root: The root of binary tree. 12 | @return: True if the binary tree is BST, or false 13 | """ 14 | def isValidBST(self, root): 15 | # write your code here 16 | if root is None: 17 | return True 18 | 19 | MAX = sys.maxsize 20 | MIN = -sys.maxsize-1 21 | 22 | return self.dfs(root, MIN, MAX) 23 | 24 | def dfs(self, root, Min, Max): 25 | 26 | if root is None: 27 | return True 28 | if root.val >= Max or root.val <= Min : 29 | return False 30 | 31 | return self.dfs(root.left, Min, root.val) and self.dfs(root.right, root.val, Max) 32 | -------------------------------------------------------------------------------- /Naive/145.Lowercase to Uppercase/README.md: -------------------------------------------------------------------------------- 1 | # 145. Lowercase to Uppercase -------------------------------------------------------------------------------- /Naive/145.Lowercase to Uppercase/Solution.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by Zhenye Na on Jun, 2018 3 | */ 4 | 5 | 6 | // 3926 ms 7 | public class Solution { 8 | /** 9 | * @param character: a character 10 | * @return: a character 11 | */ 12 | public char lowercaseToUppercase(char character) { 13 | // write your code here 14 | return (char) (character - 32); 15 | } 16 | } -------------------------------------------------------------------------------- /Naive/366.Fibonacci/README.md: -------------------------------------------------------------------------------- 1 | # 366. Fibonacci -------------------------------------------------------------------------------- /Naive/37.Reverse 3-digit Integer/README.md: -------------------------------------------------------------------------------- 1 | # 37. Reverse 3-digit Integer -------------------------------------------------------------------------------- /Naive/454.Rectangle Area/Solution.java: -------------------------------------------------------------------------------- 1 | public class Rectangle { 2 | /* 3 | * Define two public attributes width and height of type int. 4 | */ 5 | // write your code here 6 | public int width; 7 | public int heiht; 8 | 9 | /* 10 | * Define a constructor which expects two parameters width and height here. 11 | */ 12 | // write your code here 13 | public Rectangle(int w, int h) { 14 | width = w; 15 | height = h; 16 | } 17 | /* 18 | * Define a public method `getArea` which can calculate the area of the 19 | * rectangle and return. 20 | */ 21 | // write your code here 22 | public int getArea() { 23 | return width * height; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Naive/463.Sort Integers/Solution.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | /** 3 | * @param A: an integer array 4 | * @return: nothing 5 | */ 6 | public void sortIntegers(int[] A) { 7 | // write your code here 8 | 9 | for (int i = 0; i < A.length; i++) { 10 | int min = A[i]; 11 | int pos = i; 12 | for (int j = i; j < A.length; j++) { 13 | if (min > A[j]) { 14 | min = A[j]; 15 | pos = j; 16 | } 17 | } 18 | 19 | int tmp = A[i]; 20 | A[i] = A[pos]; 21 | A[pos] = tmp; 22 | 23 | } 24 | 25 | } 26 | } -------------------------------------------------------------------------------- /Naive/466.Count Linked List Nodes/Solution.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for ListNode 3 | * public class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode(int x) { 7 | * val = x; 8 | * next = null; 9 | * } 10 | * } 11 | */ 12 | 13 | public class Solution { 14 | /** 15 | * @param head: the first node of linked list. 16 | * @return: An integer 17 | */ 18 | public int countNodes(ListNode head) { 19 | // write your code here 20 | 21 | int count = 0; 22 | 23 | ListNode p = head; 24 | while (p != null) { 25 | count++; 26 | p = p.next; 27 | } 28 | 29 | return count; 30 | 31 | } 32 | } -------------------------------------------------------------------------------- /Naive/484.Swap Two Integers in Array/Solution.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | /** 3 | * @param A: An integer array 4 | * @param index1: the first index 5 | * @param index2: the second index 6 | * @return: nothing 7 | */ 8 | public void swapIntegers(int[] A, int index1, int index2) { 9 | // write your code here 10 | int tmp = A[index1]; 11 | A[index1] = A[index2]; 12 | A[index2] = tmp; 13 | } 14 | } -------------------------------------------------------------------------------- /Others/842.Origami/Solution.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Zhenye-Na/lintcode/afd79d790d0a7495d75e6650f80adaa99bd0ff07/Others/842.Origami/Solution.py -------------------------------------------------------------------------------- /Sort/894.Pancake Sorting/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | @param array: an integer array 4 | @return: nothing 5 | """ 6 | def pancakeSort(self, array): 7 | # Write your code here 8 | if not array or len(array) == 0: 9 | return 10 | 11 | n = len(array) 12 | for i in range(n - 1, -1, -1): 13 | max_idx = self.findMax(array[: i + 1]) 14 | if max_idx != i: 15 | FlipTool.flip(array, max_idx) 16 | FlipTool.flip(array, i) 17 | 18 | def findMax(self, array): 19 | max_num, max_idx = - sys.maxsize, -1 20 | for i in range(len(array)): 21 | if array[i] > max_num: 22 | max_idx = i 23 | max_num = array[i] 24 | 25 | return max_idx 26 | -------------------------------------------------------------------------------- /Stack/1116.Exclusive Time of Functions/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | @param n: a integer 4 | @param logs: a list of integers 5 | @return: return a list of integers 6 | """ 7 | def exclusiveTime(self, n, logs): 8 | # write your code here 9 | stack = [] 10 | result = [0 for _ in range(n)] 11 | last_timestamp = 0 12 | 13 | for log in logs: 14 | log = log.split(":") 15 | thread_id, status, timestamp = int(log[0]), log[1], int(log[2]) 16 | 17 | if status == "start": 18 | if stack: 19 | result[stack[-1]] += timestamp - last_timestamp 20 | stack.append(thread_id) 21 | else: 22 | timestamp += 1 23 | result[stack.pop()] += timestamp - last_timestamp 24 | 25 | last_timestamp = timestamp 26 | 27 | return result 28 | -------------------------------------------------------------------------------- /Stack/12.Min Stack/Solution_SingleStack.py: -------------------------------------------------------------------------------- 1 | class MinStack: 2 | 3 | def __init__(self): 4 | self.stack = [] 5 | 6 | def push(self, num): 7 | 8 | min_val = min(num, self.stack[-1][1] if self.stack else num) 9 | self.stack.append((num, min_val)) 10 | 11 | def pop(self) -> int: 12 | 13 | val, _ = self.stack.pop() 14 | return val 15 | 16 | def min(self) -> int: 17 | 18 | _, min_val = self.stack[-1] 19 | return min_val 20 | -------------------------------------------------------------------------------- /Stack/122.Largest Rectangle in Histogram/Solution_MonotonousStack_1.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | @param height: A list of integer 4 | @return: The area of largest rectangle in the histogram 5 | """ 6 | 7 | def largestRectangleArea(self, height): 8 | # write your code here 9 | if not height or len(height) == 0: 10 | return 0 11 | 12 | area = 0 13 | stack = [] 14 | for i in range(len(height) + 1): 15 | cur = -1 if i == len(height) else height[i] 16 | while stack and height[stack[-1]] >= cur: 17 | h = height[stack.pop()] 18 | w = i if len(stack) == 0 else i - stack[-1] - 1 19 | area = max(area, h * w) 20 | 21 | stack.append(i) 22 | 23 | return area 24 | -------------------------------------------------------------------------------- /Stack/122.Largest Rectangle in Histogram/Solution_MonotonousStack_2.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | @param height: A list of integer 4 | @return: The area of largest rectangle in the histogram 5 | """ 6 | 7 | def largestRectangleArea(self, heights): 8 | indices_stack = [] 9 | area = 0 10 | 11 | for index, height in enumerate(heights + [0]): 12 | while indices_stack and heights[indices_stack[-1]] >= height: 13 | # 如果列表尾部高度大于当前高度 14 | popped_index = indices_stack.pop() 15 | left_index = indices_stack[-1] if indices_stack else -1 16 | 17 | # 如果列表为空,则宽度为index,否则为 index- indices_stack[-1] - 1 18 | width = index - left_index - 1 19 | area = max(area, width * heights[popped_index]) 20 | 21 | # 压入列表中 22 | indices_stack.append(index) 23 | 24 | return area 25 | -------------------------------------------------------------------------------- /Stack/229.Stack Sorting/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | In python, you can use list as stack 3 | stack = [1,2,3,4] 4 | Get top element: stack[-1] -> 4 5 | Pop element: stack.pop() -> 4 6 | Push element: stack.append(5) 7 | check the size of stack: len(stack) 8 | """ 9 | 10 | 11 | class Solution: 12 | """ 13 | @param: stk: an integer stack 14 | @return: void 15 | """ 16 | def stackSorting(self, stk): 17 | # write your code here 18 | if not stk or len(stk) == 0: 19 | return stk 20 | 21 | stack = [] 22 | stack.append(stk.pop()) 23 | 24 | while stk: 25 | temp = stk.pop() 26 | while stack and temp > stack[-1]: 27 | stk.append(stack.pop()) 28 | stack.append(temp) 29 | 30 | while stack: 31 | stk.append(stack.pop()) -------------------------------------------------------------------------------- /Stack/495.Implement Stack/Solution.py: -------------------------------------------------------------------------------- 1 | class Stack: 2 | s = [] 3 | 4 | """ 5 | @param: x: An integer 6 | @return: nothing 7 | """ 8 | def push(self, x): 9 | # write your code here 10 | self.s.append(x) 11 | 12 | """ 13 | @return: nothing 14 | """ 15 | def pop(self): 16 | # write your code here 17 | self.s.pop() 18 | 19 | """ 20 | @return: An integer 21 | """ 22 | def top(self): 23 | # write your code here 24 | return self.s[-1] 25 | 26 | """ 27 | @return: True if the stack is empty 28 | """ 29 | def isEmpty(self): 30 | # write your code here 31 | return len(self.s) == 0 32 | -------------------------------------------------------------------------------- /String/1041.Reorganize String/README.md: -------------------------------------------------------------------------------- 1 | 1041. Reorganize String 2 | Description 3 | 中文 4 | English 5 | Given a string S, check if the letters can be rearranged so that two characters that are adjacent to each other are not the same. 6 | 7 | If possible, output any possible result. If not possible, return the empty string. 8 | 9 | S will consist of lowercase letters and have length in range [1, 500]. 10 | 11 | Have you met this question in a real interview? 12 | Example 13 | Example 1: 14 | 15 | Input: S = "aab" 16 | Output: "aba" 17 | Example 2: 18 | 19 | Input: S = "aaab" 20 | Output: "" 21 | 22 | 23 | 先统计每个字母出现的数,如果有一个超过一半了,直接返回空;不然进行交错排列即可 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /String/1041.Reorganize String/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public String reorganizeString(String S) { 3 | int N = S.length(); 4 | int[] counts = new int[26]; 5 | for (char c: S.toCharArray()) counts[c-'a'] += 100; 6 | for (int i = 0; i < 26; ++i) counts[i] += i; 7 | //Encoded counts[i] = 100*(actual count) + (i) 8 | Arrays.sort(counts); 9 | 10 | char[] ans = new char[N]; 11 | int t = 1; 12 | for (int code: counts) { 13 | int ct = code / 100; 14 | char ch = (char) ('a' + (code % 100)); 15 | if (ct > (N+1) / 2) return ""; 16 | for (int i = 0; i < ct; ++i) { 17 | if (t >= N) t = 0; 18 | ans[t] = ch; 19 | t += 2; 20 | } 21 | } 22 | 23 | return String.valueOf(ans); 24 | } 25 | } -------------------------------------------------------------------------------- /String/1173.Reverse Words in a String III/README.md: -------------------------------------------------------------------------------- 1 | # 1173. Reverse Words in a String III 2 | 3 | **Description** 4 | 5 | Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order. 6 | 7 | In the string, each word is separated by single space and there will not be any extra space in the string. 8 | 9 | 10 | **Example** 11 | 12 | ``` 13 | Input: "Let's take LeetCode contest" 14 | Output: "s'teL ekat edoCteeL tsetnoc" 15 | ``` 16 | 17 | 一行代码解决 18 | 19 | ```python 20 | class Solution: 21 | """ 22 | @param s: a string 23 | @return: reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order 24 | """ 25 | def reverseWords(self, s): 26 | # Write your code here 27 | return " ".join([word[::-1] for word in s.strip().split()]) 28 | ``` -------------------------------------------------------------------------------- /String/1173.Reverse Words in a String III/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | @param s: a string 4 | @return: reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order 5 | """ 6 | def reverseWords(self, s): 7 | # Write your code here 8 | return " ".join([word[::-1] for word in s.strip().split()]) 9 | -------------------------------------------------------------------------------- /String/1176.Optimal Division/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | @param nums: an array 4 | @return: the corresponding expression in string format 5 | """ 6 | 7 | def optimalDivision(self, nums): 8 | # Write your code here 9 | if not nums or len(nums) == 0: 10 | return "" 11 | 12 | if len(nums) == 1: 13 | return str(nums[0]) 14 | 15 | if len(nums) == 2: 16 | return "/".join([str(num) for num in nums]) 17 | 18 | ans = None 19 | while len(nums) > 1: 20 | num = nums.pop() 21 | if not ans: 22 | ans = str(num) 23 | else: 24 | ans = str(num) + "/" + ans 25 | 26 | return str(nums[-1]) + "/(" + ans + ")" 27 | -------------------------------------------------------------------------------- /String/1190.Longest Word in Dictionary through Deleting/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | @param s: a string 4 | @param d: List[str] 5 | @return: return a string 6 | """ 7 | 8 | def findLongestWord(self, s, d): 9 | # write your code here 10 | for x in sorted(d, key=lambda x: (-len(x), x)): 11 | it = iter(s) 12 | if all(c in it for c in x): 13 | return x 14 | return '' 15 | -------------------------------------------------------------------------------- /String/53.Reverse Words in a String/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | @param: s: A string 4 | @return: A string 5 | """ 6 | def reverseWords(self, s): 7 | # write your code here 8 | if not s or len(s) <= 1: 9 | return s 10 | 11 | s = s.strip() 12 | s_list = s.split(" ") 13 | 14 | for i in range(len(s_list)): 15 | s_list[i] = s_list[i].strip() 16 | s_list[i] = s_list[i][::-1] 17 | 18 | s_list = filter(None, s_list) 19 | s_prime = " ".join(s_list)[::-1] 20 | 21 | return s_prime -------------------------------------------------------------------------------- /String/646.First Position Unique Character/README.md: -------------------------------------------------------------------------------- 1 | # 646. First Position Unique Character 2 | 3 | **Description** 4 | 5 | Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return `-1`. 6 | 7 | Example 8 | 9 | Example 1: 10 | 11 | ``` 12 | Input : s = "lintcode" 13 | Output : 0 14 | ``` 15 | 16 | Example 2: 17 | 18 | ``` 19 | Input : s = "lovelintcode" 20 | Output : 2 21 | ``` 22 | -------------------------------------------------------------------------------- /String/646.First Position Unique Character/Solution.py: -------------------------------------------------------------------------------- 1 | from collections import Counter 2 | 3 | 4 | class Solution: 5 | """ 6 | @param s: a string 7 | @return: it's index 8 | """ 9 | 10 | def firstUniqChar(self, s): 11 | # write your code here 12 | counter = Counter(s) 13 | 14 | for idx, char in enumerate(s): 15 | if counter[char] == 1: 16 | return idx 17 | 18 | return -1 19 | -------------------------------------------------------------------------------- /String/78.Longest Common Prefix/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | @param strs: A list of strings 4 | @return: The longest common prefix 5 | """ 6 | def longestCommonPrefix(self, strs): 7 | # write your code here 8 | if not strs or len(strs) == 0: 9 | return "" 10 | 11 | prefix = strs[0] 12 | i, j = 0, 0 13 | for word in strs[1:]: 14 | i, j = 0, 0 15 | while i < len(prefix) and j < len(word) and prefix[i] == word[j]: 16 | i += 1 17 | j += 1 18 | 19 | if j == 0: 20 | return "" 21 | elif 0 < j < len(word): 22 | prefix = prefix[:j] 23 | else: 24 | prefix = word 25 | 26 | return prefix 27 | -------------------------------------------------------------------------------- /String/784.The Longest Common Prefix II/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | @param words: the n strings 4 | @param target: the target string 5 | @return: The ans 6 | """ 7 | def the_longest_common_prefix(self, words, target): 8 | # write your code here 9 | ans = 0 10 | for word in words: 11 | same = 0 12 | 13 | for j in range(0, len(target)): 14 | if j > len(word) - 1 or target[j] != word[j]: 15 | break 16 | same += 1 17 | 18 | ans = max(ans, same) 19 | 20 | return ans -------------------------------------------------------------------------------- /String/927.Reverse Words in a String II/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | @param s: a string 4 | @return: return a string 5 | """ 6 | def reverseWords(self, s): 7 | # write your code here 8 | if not s or len(s) <= 1: 9 | return s 10 | 11 | s_list = s.strip().split() 12 | s_list = list(filter(None, s_list)) 13 | new_s = " ".join(reversed(s_list)) 14 | 15 | return new_s 16 | 17 | def reverseWordsSolution2(self, s): 18 | return " ".join(reversed(s.strip().split(" "))) 19 | -------------------------------------------------------------------------------- /Tree/1003.Binary Tree Pruning/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | Definition of TreeNode: 3 | class TreeNode: 4 | def __init__(self, val): 5 | self.val = val 6 | self.left, self.right = None, None 7 | """ 8 | 9 | 10 | class Solution: 11 | """ 12 | @param root: the root 13 | @return: the same tree where every subtree (of the given tree) not containing a 1 has been removed 14 | """ 15 | 16 | def pruneTree(self, root): 17 | # Write your code here 18 | if root is None: 19 | return None 20 | 21 | root.left = self.pruneTree(root.left) 22 | root.right = self.pruneTree(root.right) 23 | 24 | if root.val == 0 and root.left is None and root.right is None: 25 | return None 26 | else: 27 | return root 28 | -------------------------------------------------------------------------------- /Tree/1101.Maximum Width of Binary Tree/Solution_BFS.py: -------------------------------------------------------------------------------- 1 | from collections import deque 2 | 3 | # Definition for a binary tree node. 4 | # class TreeNode: 5 | # def __init__(self, x): 6 | # self.val = x 7 | # self.left = None 8 | # self.right = None 9 | 10 | 11 | class Solution: 12 | def widthOfBinaryTree(self, root: TreeNode) -> int: 13 | queue = deque([(root, 0)]) 14 | result = 0 15 | 16 | while queue: 17 | left = queue[0][1] 18 | right = left 19 | size = len(queue) 20 | for i in range(size): 21 | node, right = queue.popleft() 22 | if node.left: 23 | queue.append((node.left, right * 2)) 24 | if node.right: 25 | queue.append((node.right, right * 2 + 1)) 26 | result = max(result, right - left + 1) 27 | 28 | return result 29 | -------------------------------------------------------------------------------- /Tree/1101.Maximum Width of Binary Tree/Solution_DFS.py: -------------------------------------------------------------------------------- 1 | """ 2 | Definition of TreeNode: 3 | class TreeNode: 4 | def __init__(self, val): 5 | self.val = val 6 | self.left, self.right = None, None 7 | """ 8 | 9 | 10 | class Solution: 11 | """ 12 | @param root: the root 13 | @return: the maximum width of the given tree 14 | """ 15 | 16 | def widthOfBinaryTree(self, root): 17 | # Write your code here 18 | queue = [(root, 0, 0)] 19 | cur_depth = left = ans = 0 20 | 21 | for node, depth, pos in queue: 22 | if node: 23 | queue.append((node.left, depth + 1, pos * 2)) 24 | queue.append((node.right, depth + 1, pos * 2 + 1)) 25 | 26 | if cur_depth != depth: 27 | cur_depth = depth 28 | left = pos 29 | 30 | ans = max(pos - left + 1, ans) 31 | 32 | return ans 33 | -------------------------------------------------------------------------------- /Tree/1197.Find Bottom Left Tree Value/README.md: -------------------------------------------------------------------------------- 1 | # 1197. Find Bottom Left Tree Value 2 | 3 | **Description** 4 | 5 | Given a binary tree, find the `leftmost` value in the `last` row of the tree. 6 | 7 | You may assume the tree (i.e., the given root node) is not `NULL`. 8 | 9 | **Example** 10 | 11 | Example 1: 12 | 13 | ``` 14 | Input: {2,1,3} 15 | Output: 1 16 | 17 | Explanation: 18 | 2 19 | / \ 20 | 1 3 21 | ``` 22 | 23 | Example 2: 24 | 25 | ``` 26 | Input: {1,2,3,4,5,6,#,#,7} 27 | Output: 7 28 | 29 | Explanation: 30 | 1 31 | / \ 32 | 2 3 33 | / \ / 34 | 4 5 6 35 | \ 36 | 7 37 | ``` 38 | 39 | 40 | -------------------------------------------------------------------------------- /Tree/1197.Find Bottom Left Tree Value/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | Definition of TreeNode: 3 | class TreeNode: 4 | def __init__(self, val): 5 | self.val = val 6 | self.left, self.right = None, None 7 | """ 8 | 9 | 10 | class Solution: 11 | """ 12 | @param root: a root of tree 13 | @return: return a integer 14 | """ 15 | 16 | def findBottomLeftValue(self, root): 17 | # write your code here 18 | self.max_level = 0 19 | self.val = 0 20 | self.helper(root, 1) 21 | return self.val 22 | 23 | def helper(self, root, level): 24 | if not root: 25 | return 26 | 27 | if level > self.max_level: 28 | self.max_level = level 29 | self.val = root.val 30 | 31 | self.helper(root.left, level + 1) 32 | self.helper(root.right, level + 1) 33 | -------------------------------------------------------------------------------- /Tree/1311.Lowest Common Ancestor of a Binary Search Tree/Solution_DFS_Pruning.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def lowestCommonAncestor(self, root, p, q): 3 | # Value of current node or parent node. 4 | parent_val = root.val 5 | 6 | # Value of p 7 | p_val = p.val 8 | 9 | # Value of q 10 | q_val = q.val 11 | 12 | # If both p and q are greater than parent 13 | if p_val > parent_val and q_val > parent_val: 14 | return self.lowestCommonAncestor(root.right, p, q) 15 | # If both p and q are lesser than parent 16 | elif p_val < parent_val and q_val < parent_val: 17 | return self.lowestCommonAncestor(root.left, p, q) 18 | # We have found the split point, i.e. the LCA node. 19 | else: 20 | return root 21 | -------------------------------------------------------------------------------- /Tree/1357.Path Sum II/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | Definition of TreeNode: 3 | class TreeNode: 4 | def __init__(self, val): 5 | self.val = val 6 | self.left, self.right = None, None 7 | """ 8 | 9 | 10 | class Solution: 11 | """ 12 | @param root: a binary tree 13 | @param target: the sum 14 | @return: the scheme 15 | """ 16 | 17 | def pathSum(self, root, target): 18 | # Write your code here. 19 | self.results = [] 20 | self.dfs(root, target, []) 21 | return self.results 22 | 23 | def dfs(self, root, target, curr): 24 | if root is None: 25 | return 26 | 27 | if target == root.val and root.left is None and root.right is None: 28 | self.results.append(curr[:] + [root.val]) 29 | 30 | self.dfs(root.left, target - root.val, curr + [root.val]) 31 | self.dfs(root.right, target - root.val, curr + [root.val]) 32 | -------------------------------------------------------------------------------- /Tree/448.Inorder Successor in BST/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | Definition for a binary tree node. 3 | class TreeNode(object): 4 | def __init__(self, x): 5 | self.val = x 6 | self.left = None 7 | self.right = None 8 | """ 9 | 10 | 11 | class Solution: 12 | """ 13 | @param: root: The root of the BST. 14 | @param: p: You need find the successor node of p. 15 | @return: Successor of p. 16 | """ 17 | def inorderSuccessor(self, root, p): 18 | # write your code here 19 | if root is None: 20 | return None 21 | 22 | if root.val <= p.val: 23 | return self.inorderSuccessor(root.right, p) 24 | 25 | left = self.inorderSuccessor(root.left, p) 26 | if left is not None: 27 | return left 28 | return root 29 | -------------------------------------------------------------------------------- /Tree/628.Maximum Subtree/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | Definition of TreeNode: 3 | class TreeNode: 4 | def __init__(self, val): 5 | self.val = val 6 | self.left, self.right = None, None 7 | """ 8 | 9 | class Solution: 10 | """ 11 | @param root: the root of binary tree 12 | @return: the maximum weight node 13 | """ 14 | maximum = - sys.maxsize - 1 15 | node = None 16 | 17 | def findSubtree(self, root): 18 | # write your code here 19 | self._dfs(root) 20 | return self.node 21 | 22 | def _dfs(self, root): 23 | if not root: 24 | return 0 25 | 26 | leftTotal = self._dfs(root.left) 27 | rightTotal = self._dfs(root.right) 28 | 29 | if leftTotal + rightTotal + root.val > self.maximum: 30 | self.maximum = leftTotal + rightTotal + root.val 31 | self.node = root 32 | 33 | return leftTotal + rightTotal + root.val 34 | -------------------------------------------------------------------------------- /Tree/649.Binary Tree Upside Down/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | Definition of TreeNode: 3 | class TreeNode: 4 | def __init__(self, val): 5 | self.val = val 6 | self.left, self.right = None, None 7 | """ 8 | 9 | 10 | class Solution: 11 | """ 12 | @param root: the root of binary tree 13 | @return: new root 14 | """ 15 | 16 | def upsideDownBinaryTree(self, root): 17 | # write your code here 18 | if root is None: 19 | return None 20 | return self.dfs(root) 21 | 22 | def dfs(self, root): 23 | if root.left is None: 24 | return root 25 | 26 | newRoot = self.dfs(root.left) 27 | root.left.right = root 28 | root.left.left = root.right 29 | root.left, root.right = None, None 30 | 31 | return newRoot 32 | -------------------------------------------------------------------------------- /Tree/85.Insert Node in a Binary Search Tree/Solution_Recursion.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | @param: root: The root of the binary search tree. 4 | @param: node: insert this node into the binary search tree 5 | @return: The root of the new binary search tree. 6 | """ 7 | def insertNode(self, root, node): 8 | # write your code here 9 | return self.__helper(root, node) 10 | 11 | # helper函数定义成私有属性 12 | def __helper(self, root, node): 13 | if root is None: 14 | return node 15 | if node.val < root.val: 16 | root.left = self.__helper(root.left, node) 17 | else: 18 | root.right = self.__helper(root.right, node) 19 | return root -------------------------------------------------------------------------------- /Tree/97.Maximum Depth of Binary Tree/Solution_divide_conquer.py: -------------------------------------------------------------------------------- 1 | """ 2 | Definition of TreeNode: 3 | class TreeNode: 4 | def __init__(self, val): 5 | self.val = val 6 | self.left, self.right = None, None 7 | """ 8 | 9 | class Solution: 10 | """ 11 | @param root: The root of binary tree. 12 | @return: An integer 13 | """ 14 | def maxDepth(self, root): 15 | # write your code here 16 | return self._find_depth(root) 17 | 18 | def _find_depth(self, root): 19 | if not root: 20 | return 0 21 | 22 | return max(self._find_depth(root.left), self._find_depth(root.right)) + 1 23 | -------------------------------------------------------------------------------- /Tree/97.Maximum Depth of Binary Tree/Solution_traverse.py: -------------------------------------------------------------------------------- 1 | """ 2 | Definition of TreeNode: 3 | class TreeNode: 4 | def __init__(self, val): 5 | self.val = val 6 | self.left, self.right = None, None 7 | """ 8 | 9 | class Solution: 10 | """ 11 | @param root: The root of binary tree. 12 | @return: An integer 13 | """ 14 | def maxDepth(self, root): 15 | # write your code here 16 | self.max_depth = 0 17 | self._find_depth(root, 1) 18 | return self.max_depth 19 | 20 | def _find_depth(self, root, depth): 21 | if not root: 22 | return 23 | 24 | self.max_depth = max(self.max_depth, depth) 25 | self._find_depth(root.left, depth + 1) 26 | self._find_depth(root.right, depth + 1) 27 | -------------------------------------------------------------------------------- /Trie/1090.Map Sum Pairs/Solution_HashMap.py: -------------------------------------------------------------------------------- 1 | class MapSum(object): 2 | def __init__(self): 3 | self.map = {} 4 | self.score = collections.Counter() 5 | 6 | def insert(self, key, val): 7 | delta = val - self.map.get(key, 0) 8 | self.map[key] = val 9 | for i in xrange(len(key) + 1): 10 | prefix = key[:i] 11 | self.score[prefix] += delta 12 | 13 | def sum(self, prefix): 14 | return self.score[prefix] -------------------------------------------------------------------------------- /Two_Pointers/100.Remove Duplicates from Sorted Array/Solution.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | /* 3 | * @param nums: An ineger array 4 | * @return: An integer 5 | */ 6 | public int removeDuplicates(int[] nums) { 7 | // write your code here 8 | if (nums == null || nums.length == 0) { 9 | return 0; 10 | } 11 | 12 | int j = 0; 13 | int len = nums.length; 14 | for (int i = 1; i < len; i++) { 15 | if (nums[i] != nums[j]) { 16 | // update value 17 | j++; 18 | nums[j] = nums[i]; 19 | } 20 | } 21 | return j + 1; 22 | } 23 | } -------------------------------------------------------------------------------- /Two_Pointers/100.Remove Duplicates from Sorted Array/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | @param: nums: An ineger array 4 | @return: An integer 5 | """ 6 | def removeDuplicates(self, nums): 7 | # write your code here 8 | if not nums or len(nums) == 0: 9 | return 0 10 | 11 | length = len(nums) 12 | 13 | p1, p2 = 0, 1 14 | while p2 < length: 15 | if nums[p1] != nums[p2]: 16 | p1 += 1 17 | nums[p1] = nums[p2] 18 | p2 += 1 19 | else: 20 | while p2 < length and nums[p2] == nums[p1]: 21 | p2 += 1 22 | if p2 < length: 23 | p1 += 1 24 | nums[p1] = nums[p2] 25 | p2 += 1 26 | 27 | return p1 + 1 28 | -------------------------------------------------------------------------------- /Two_Pointers/101.Remove Duplicates from Sorted Array II/Solution.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | /** 3 | * @param nums: a array of integers 4 | * @return : return an integer 5 | */ 6 | public int removeDuplicates(int[] nums) { 7 | if (nums == null || nums.length == 0) { 8 | return 0; 9 | } 10 | 11 | int index = 0, count = 1; 12 | for (int i = 1; i < nums.length; i++) { 13 | if (nums[i] == nums[index]) { 14 | if (count < 2) { 15 | nums[++index] = nums[i]; 16 | count ++; 17 | } 18 | } else { 19 | nums[++index] = nums[i]; 20 | count = 1; 21 | } 22 | } 23 | return index + 1; 24 | } 25 | } -------------------------------------------------------------------------------- /Two_Pointers/1132.Valid Triangle Number/README.md: -------------------------------------------------------------------------------- 1 | # 1132. Valid Triangle Number 2 | 3 | Description 4 | 5 | Given an array consists of non-negative integers, your task is to count the number of triplets chosen from the array that can make triangles if we take them as side lengths of a triangle. 6 | 7 | ``` 8 | The length of the given array won't exceed 1000. 9 | The integers in the given array are in the range of [0, 1000]. 10 | ``` 11 | 12 | **Example** 13 | 14 | Example 1: 15 | 16 | ``` 17 | Input: [2,2,3,4] 18 | Output: 3 19 | Explanation: 20 | Valid combinations are: 21 | 2,3,4 (using the first 2) 22 | 2,3,4 (using the second 2) 23 | 2,2,3. 24 | ``` 25 | 26 | Example 2: 27 | 28 | ``` 29 | Input: [3,3,3] 30 | Output: 1 31 | Explanation: 32 | Valid combination is 3,3,3. 33 | ``` 34 | -------------------------------------------------------------------------------- /Two_Pointers/1132.Valid Triangle Number/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | @param nums: the given array 4 | @return: the number of triplets chosen from the array that can make triangles 5 | """ 6 | 7 | def triangleNumber(self, nums): 8 | # Write your code here 9 | if not nums or len(nums) == 0: 10 | return 0 11 | 12 | nums.sort() 13 | ans = 0 14 | 15 | for i in range(2, len(nums)): 16 | left, right = 0, i - 1 17 | while left < right: 18 | if nums[left] + nums[right] > nums[i]: 19 | ans += right - left 20 | right -= 1 21 | else: 22 | left += 1 23 | 24 | return ans 25 | -------------------------------------------------------------------------------- /Two_Pointers/148.Sort Colors/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | @param nums: A list of integer which is 0, 1 or 2 4 | @return: nothing 5 | """ 6 | def sortColors(self, nums): 7 | # write your code here 8 | if not nums or len(nums) == 0: 9 | return 10 | 11 | left, right = 0, len(nums) - 1 12 | i = 0 13 | while i <= right: 14 | if nums[i] == 0: 15 | nums[left], nums[i] = nums[i], nums[left] 16 | left += 1 17 | i += 1 18 | elif nums[i] == 2: 19 | nums[right], nums[i] = nums[i], nums[right] 20 | right -= 1 21 | else: 22 | i += 1 23 | -------------------------------------------------------------------------------- /Two_Pointers/1487.Judging Triangle/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | @param arr: The array 4 | @return: yes or no 5 | """ 6 | 7 | def judgingTriangle(self, arr): 8 | # Write your code here 9 | if not arr or len(arr) == 0: 10 | return "no" 11 | 12 | n = len(arr) 13 | for i in range(2, n): 14 | left, right = 0, i - 1 15 | while left < right: 16 | if arr[left] + arr[right] > arr[i]: 17 | return "yes" 18 | else: 19 | left += 1 20 | 21 | return "no" 22 | -------------------------------------------------------------------------------- /Two_Pointers/363.Trapping Rain Water/Solution_TwoPointers.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | @param heights: a list of integers 4 | @return: a integer 5 | """ 6 | def trapRainWater(self, heights): 7 | if not heights: 8 | return 0 9 | 10 | left, right = 0, len(heights) - 1 11 | left_max, right_max = heights[left], heights[right] 12 | water = 0 13 | 14 | while left <= right: 15 | if left_max < right_max: 16 | left_max = max(left_max, heights[left]) 17 | water += left_max - heights[left] 18 | left += 1 19 | else: 20 | right_max = max(right_max, heights[right]) 21 | water += right_max - heights[right] 22 | right -= 1 23 | 24 | return water -------------------------------------------------------------------------------- /Two_Pointers/373.Partition Array by Odd and Even/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | @param: nums: an array of integers 4 | @return: nothing 5 | """ 6 | def partitionArray(self, nums): 7 | # write your code here 8 | if not nums or len(nums) == 0: 9 | return nums 10 | 11 | left, right = 0, len(nums) - 1 12 | while left <= right: 13 | while left <= right and not self.isEven(nums[left]): 14 | left += 1 15 | while left <= right and self.isEven(nums[right]): 16 | right -= 1 17 | if left <= right: 18 | nums[left], nums[right] = nums[right], nums[left] 19 | left += 1 20 | right -= 1 21 | 22 | return nums 23 | 24 | 25 | def isEven(self, num): 26 | return num % 2 == 0 27 | -------------------------------------------------------------------------------- /Two_Pointers/384.Longest Substring Without Repeating Characters/Solution_2.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | @param s: a string 4 | @return: an integer 5 | """ 6 | def lengthOfLongestSubstring(self, s): 7 | unique_chars = set([]) 8 | j = 0 9 | n = len(s) 10 | longest = 0 11 | 12 | for i in range(n): 13 | while j < n and s[j] not in unique_chars: 14 | unique_chars.add(s[j]) 15 | j += 1 16 | longest = max(longest, j - i) 17 | unique_chars.remove(s[i]) 18 | 19 | return longest 20 | -------------------------------------------------------------------------------- /Two_Pointers/39.Recover Rotated Sorted Array/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | @param nums: An integer array 4 | @return: nothing 5 | """ 6 | def recoverRotatedSortedArray(self, nums): 7 | # write your code here 8 | if not nums or len(nums) == 0: 9 | return 10 | 11 | l = len(nums) 12 | for j in range(1, len(nums)): 13 | if nums[j - 1] > nums[j]: 14 | self.reverse(nums, 0, j - 1) 15 | self.reverse(nums, j, l - 1) 16 | self.reverse(nums, 0, l - 1) 17 | return nums 18 | 19 | def reverse(self, nums, start, end): 20 | i, j = start, end 21 | while i < j: 22 | tmp = nums[i] 23 | nums[i] = nums[j] 24 | nums[j] = tmp 25 | i += 1 26 | j -= 1 27 | -------------------------------------------------------------------------------- /Two_Pointers/406.Minimum Size Subarray Sum/Solution_1.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | @param nums: an array of integers 4 | @param s: An integer 5 | @return: an integer representing the minimum size of subarray 6 | """ 7 | def minimumSize(self, nums, s): 8 | # write your code here 9 | length = sys.maxsize 10 | total, right = 0, 0 11 | 12 | for left in range(len(nums)): 13 | while right < len(nums) and total < s: 14 | total += nums[right] 15 | right += 1 16 | 17 | if total >= s: 18 | length = min(length, right - left) 19 | 20 | total -= nums[left] 21 | 22 | return -1 if length == sys.maxsize else length -------------------------------------------------------------------------------- /Two_Pointers/406.Minimum Size Subarray Sum/Solution_2.py: -------------------------------------------------------------------------------- 1 | # 模版 2: 枚举右端点,左端点不回头 2 | class Solution: 3 | """ 4 | @param nums: an array of integers 5 | @param s: An integer 6 | @return: an integer representing the minimum size of subarray 7 | """ 8 | def minimumSize(self, nums, s): 9 | 10 | ans = sys.maxsize 11 | left = 0 12 | addup = 0 13 | 14 | for right in range(len(nums)): 15 | 16 | addup += nums[right] 17 | while addup >= s: 18 | 19 | ans = min(ans, right - left + 1) 20 | addup -= nums[left] 21 | left += 1 22 | 23 | return ans if ans != sys.maxsize else -1 -------------------------------------------------------------------------------- /Two_Pointers/415.Valid Palindrome/Solution.py: -------------------------------------------------------------------------------- 1 | import string 2 | class Solution: 3 | """ 4 | @param s: A string 5 | @return: Whether the string is a valid palindrome 6 | """ 7 | def isPalindrome(self, s): 8 | # write your code here 9 | s = s.lower() 10 | translator = str.maketrans("", "", string.punctuation + " ") 11 | s = s.translate(translator) 12 | s = "".join(s.split(" ")) 13 | return s == s[::-1] -------------------------------------------------------------------------------- /Two_Pointers/443.Two Sum - Greater than target/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | @param nums: an array of integer 4 | @param target: An integer 5 | @return: an integer 6 | """ 7 | def twoSum2(self, nums, target): 8 | # write your code here 9 | if not nums or len(nums) < 2: 10 | return 0 11 | 12 | nums.sort() 13 | count = 0 14 | left, right = 0, len(nums) - 1 15 | while left < right: 16 | if nums[left] + nums[right] <= target: 17 | left += 1 18 | else: 19 | count += right - left 20 | right -= 1 21 | 22 | return count 23 | -------------------------------------------------------------------------------- /Two_Pointers/49.Sort Letters by Case/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | @param: chars: The letter array you should sort by Case 4 | @return: nothing 5 | """ 6 | def sortLetters(self, chars): 7 | # write your code here 8 | if not chars or len(chars) == 0: 9 | return 10 | 11 | lo, hi = 0, len(chars) - 1 12 | while lo <= hi: 13 | while lo <= hi and chars[lo].islower(): 14 | lo += 1 15 | while lo <= hi and chars[hi].isupper(): 16 | hi -= 1 17 | if lo <= hi: 18 | chars[lo], chars[hi] = chars[hi], chars[lo] 19 | lo += 1 20 | hi -= 1 21 | -------------------------------------------------------------------------------- /Two_Pointers/521.Remove Duplicate Numbers in Array/Solution_On.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | @param nums: an array of integers 4 | @return: the number of unique integers 5 | """ 6 | def deduplication(self, nums): 7 | # write your code here 8 | if not nums or len(nums) == 0: 9 | return 0 10 | 11 | # O(n) Time, O(n) Space 12 | left, right = 0, 0 13 | hist = set() 14 | while right < len(nums): 15 | if nums[right] not in hist: 16 | hist.add(nums[right]) 17 | nums[left], nums[right] = nums[right], nums[left] 18 | left += 1 19 | right += 1 20 | else: 21 | # nums[right] in history 22 | while right < len(nums) and nums[right] in hist: 23 | right += 1 24 | 25 | return left 26 | -------------------------------------------------------------------------------- /Two_Pointers/521.Remove Duplicate Numbers in Array/Solution_Onlogn.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | @param nums: an array of integers 4 | @return: the number of unique integers 5 | """ 6 | def deduplication(self, nums): 7 | # write your code here 8 | if not nums or len(nums) == 0: 9 | return 0 10 | 11 | # O(nlogn) Time, O(1) Space 12 | nums.sort() 13 | result = 1 14 | for i in range(1, len(nums)): 15 | if nums[i - 1] != nums[i]: 16 | nums[result] = nums[i] 17 | result += 1 18 | 19 | return result 20 | -------------------------------------------------------------------------------- /Two_Pointers/533.Two Sum - Closest to target/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | @param nums: an integer array 4 | @param target: An integer 5 | @return: the difference between the sum and the target 6 | """ 7 | def twoSumClosest(self, nums, target): 8 | # write your code here 9 | if not nums or len(nums) < 2: 10 | return 0 11 | 12 | nums.sort() 13 | diff = sys.maxsize 14 | left, right = 0, len(nums) - 1 15 | while left < right: 16 | if nums[left] + nums[right] < target: 17 | diff = min(diff, abs(nums[left] + nums[right] - target)) 18 | left += 1 19 | else: 20 | diff = min(diff, abs(nums[left] + nums[right] - target)) 21 | right -= 1 22 | 23 | return diff 24 | -------------------------------------------------------------------------------- /Two_Pointers/539.Move Zeroes/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | @param nums: an integer array 4 | @return: nothing 5 | """ 6 | def moveZeroes(self, nums): 7 | # write your code here 8 | if not nums or len(nums) == 0: 9 | return nums 10 | 11 | first_zero = -1 12 | for i in range(len(nums)): 13 | if nums[i] == 0: 14 | first_zero = i 15 | break 16 | 17 | if first_zero == -1: 18 | return nums 19 | 20 | left = first_zero 21 | for right in range(first_zero, len(nums)): 22 | if nums[right] == 0: 23 | continue 24 | else: 25 | nums[right], nums[left] = nums[left], nums[right] 26 | left += 1 27 | right += 1 28 | 29 | return nums 30 | -------------------------------------------------------------------------------- /Two_Pointers/56.Two Sum/Solution_HashMap.py: -------------------------------------------------------------------------------- 1 | # 本参考程序来自九章算法,由 @九章算法 提供。版权所有,转发请注明出处。 2 | # - 九章算法致力于帮助更多中国人找到好的工作,教师团队均来自硅谷和国内的一线大公司在职工程师。 3 | # - 现有的面试培训课程包括:九章算法班,系统设计班,算法强化班,Java入门与基础算法班,Android 项目实战班, 4 | # - Big Data 项目实战班,算法面试高频题班, 动态规划专题班 5 | # - 更多详情请见官方网站:http://www.jiuzhang.com/?source=code 6 | 7 | 8 | class Solution(object): 9 | def twoSum(self, nums, target): 10 | # hash用于建立数值到下标的映射 11 | hash = {} 12 | # 循环 nums 数值,并添加映射 13 | for i in range(len(nums)): 14 | if target - nums[i] in hash: 15 | return [hash[target - nums[i]], i] 16 | hash[nums[i]] = i 17 | # 无解的情况 18 | return [-1, -1] 19 | -------------------------------------------------------------------------------- /Two_Pointers/56.Two Sum/Solution_TwoPointers.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | @param numbers: An array of Integer 4 | @param target: target = numbers[index1] + numbers[index2] 5 | @return: [index1, index2] (index1 < index2) 6 | """ 7 | def twoSum(self, numbers, target): 8 | # write your code here 9 | if not numbers or len(numbers) < 2: 10 | return [-1, -1] 11 | 12 | arg_nums = [x for x, y in sorted(enumerate(numbers), key = lambda x: x[1])] 13 | numbers.sort() 14 | left, right = 0, len(numbers) - 1 15 | while left <= right: 16 | if numbers[left] + numbers[right] == target: 17 | return sorted([arg_nums[left], arg_nums[right]]) 18 | elif numbers[left] + numbers[right] < target: 19 | left += 1 20 | else: 21 | right -= 1 22 | 23 | return [-1, -1] 24 | -------------------------------------------------------------------------------- /Two_Pointers/609.Two Sum - Less than or equal to target/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | @param nums: an array of integer 4 | @param target: an integer 5 | @return: an integer 6 | """ 7 | def twoSum5(self, nums, target): 8 | # write your code here 9 | if not nums or len(nums) < 2: 10 | return 0 11 | 12 | nums.sort() 13 | count = 0 14 | left, right = 0, len(nums) - 1 15 | while left < right: 16 | if nums[left] + nums[right] <= target: 17 | count += right - left 18 | left += 1 19 | 20 | elif nums[left] + nums[right] > target: 21 | right -= 1 22 | 23 | return count 24 | -------------------------------------------------------------------------------- /Two_Pointers/610.Two Sum - Difference equals to target/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | @param nums: an array of Integer 4 | @param target: an integer 5 | @return: [index1 + 1, index2 + 1] (index1 < index2) 6 | """ 7 | def twoSum7(self, nums, target): 8 | # write your code here 9 | nums = [(num, i) for i, num in enumerate(nums)] 10 | target = abs(target) 11 | n, indexs = len(nums), [] 12 | 13 | nums = sorted(nums, key=lambda x: x[0]) 14 | 15 | j = 0 16 | for i in range(n): 17 | if i == j: 18 | j += 1 19 | while j < n and nums[j][0] - nums[i][0] < target: 20 | j += 1 21 | if j < n and nums[j][0] - nums[i][0] == target: 22 | indexs = [nums[i][1] + 1, nums[j][1] + 1] 23 | return sorted(indexs) 24 | 25 | return [-1, -1] -------------------------------------------------------------------------------- /Two_Pointers/64.Merge Sorted Array/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | /** 3 | * @param A: sorted integer array A which has m elements, 4 | * but size of A is m+n 5 | * @param B: sorted integer array B which has n elements 6 | * @return: void 7 | */ 8 | public void mergeSortedArray(int[] A, int m, int[] B, int n) { 9 | int i = m-1, j = n-1, index = m + n - 1; 10 | while (i >= 0 && j >= 0) { 11 | if (A[i] > B[j]) { 12 | A[index--] = A[i--]; 13 | } else { 14 | A[index--] = B[j--]; 15 | } 16 | } 17 | while (i >= 0) { 18 | A[index--] = A[i--]; 19 | } 20 | while (j >= 0) { 21 | A[index--] = B[j--]; 22 | } 23 | } 24 | } -------------------------------------------------------------------------------- /Two_Pointers/64.Merge Sorted Array/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | @param: A: sorted integer array A which has m elements, but size of A is m+n 4 | @param: m: An integer 5 | @param: B: sorted integer array B which has n elements 6 | @param: n: An integer 7 | @return: nothing 8 | """ 9 | def mergeSortedArray(self, A, m, B, n): 10 | # write your code here 11 | ap, bp = m - 1, n - 1 12 | idx = m + n - 1 13 | 14 | while ap >= 0 and bp >= 0 and idx >= 0: 15 | if A[ap] > B[bp]: 16 | A[idx] = A[ap] 17 | ap -= 1 18 | else: 19 | A[idx] = B[bp] 20 | bp -= 1 21 | idx -= 1 22 | 23 | while ap >= 0: 24 | A[idx] = A[ap] 25 | ap -= 1 26 | idx -= 1 27 | 28 | while bp >= 0: 29 | A[idx] = B[bp] 30 | bp -= 1 31 | idx -= 1 -------------------------------------------------------------------------------- /Union_Find/1257.Evaluate Division/Solution_DFS.py: -------------------------------------------------------------------------------- 1 | """ 2 | Author: Huahua 3 | Running time: 32 ms (beats 100%) 4 | """ 5 | 6 | 7 | class Solution: 8 | def calcEquation(self, equations, values, queries): 9 | def divide(x, y, visited): 10 | if x == y: 11 | return 1.0 12 | visited.add(x) 13 | for n in g[x]: 14 | if n in visited: 15 | continue 16 | visited.add(n) 17 | d = divide(n, y, visited) 18 | if d > 0: 19 | return d * g[x][n] 20 | return -1.0 21 | 22 | g = collections.defaultdict(dict) 23 | for (x, y), v in zip(equations, values): 24 | g[x][y] = v 25 | g[y][x] = 1.0 / v 26 | 27 | ans = [divide(x, y, set()) if x in g and y in g else - 28 | 1 for x, y in queries] 29 | return ans 30 | -------------------------------------------------------------------------------- /assets/proj.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Zhenye-Na/lintcode/afd79d790d0a7495d75e6650f80adaa99bd0ff07/assets/proj.png -------------------------------------------------------------------------------- /big-o-cheatsheet.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Zhenye-Na/lintcode/afd79d790d0a7495d75e6650f80adaa99bd0ff07/big-o-cheatsheet.pdf -------------------------------------------------------------------------------- /todolist.md: -------------------------------------------------------------------------------- 1 | TODO list 2 | 3 | - [ ] segment tree 4 | - [ ] DP copy books 5 | - [ ] permutations non-recursion 6 | - [ ] morris --------------------------------------------------------------------------------