Skip to content

Commit

Permalink
Add more Leetcode solutions.
Browse files Browse the repository at this point in the history
Add more comments and refactoring.
  • Loading branch information
Tzu Hsiang Lin committed Nov 28, 2019
1 parent eae0d1c commit 8204997
Show file tree
Hide file tree
Showing 6 changed files with 73 additions and 14 deletions.
6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,15 @@ Something I have learned...
## [Algorithm](./algorithm/)
| Title | Solution |
| ----- | -------- |
| Array | <ol><li>[20.py](./algorithm/Array/20.py) Valid Parentheses _(elegant coding)_</li><li>[38.py](./algorithm/Array/38.py) Count and Say _(count consecutive elements)_</li><li>[42.py](./algorithm/Array/42.py) Trapping Rain Water _(two pointers)_</li><li>[45.py](./algorithm/Array/45.py) Jump Game II _(till and farest reach)_</li><li>[155.py](./algorithm/Array/155.py) Min Stack</li><li>[209.py](./algorithm/Array/209.py) Summary Ranges _(left pointer and accumulate)_</li><li>[217.py](./algorithm/Array/217.py) Contains Duplicate _(set)_</li><li>[219.py](./algorithm/Array/219.py) Contains Duplicate II _(just cares last)_</li><li>[228.py](./algorithm/Array/228.py) Summary Ranges _(count consecutive elements)_</li><li>[238.py](./algorithm/Array/238.py) Product of Array Except Self _(left2right, right2left)_</li><li>[242.py](./algorithm/Array/242.py) Valid Anagram _(counter equality)_</li><li>[348.py](./algorithm/Array/348.py) Design Tic-Tac-Toe _(diagonal math, sum, loop else)_</li><li>[349.py](./algorithm/Array/349.py) Intersection of Two Arrays _(set & set)_</li><li>[350.py](./algorithm/Array/350.py) Intersection of Two Arrays II _(counter & counter)_</li><li>[388.py](./algorithm/Array/388.py) Longest Absolute File Path _(split, lstrip, memorization)_</li><li>[838.py](./algorithm/Array/838.py) Push Dominoes _(force propagate/reset)_</li><li>[859.py](./algorithm/Array/859.py) Buddy Strings _(enumerate cases)_</li><li>[1002.py](./algorithm/Array/1002.py) Find Common Characters _(counter & counter)_</li><li>[1169.py](./algorithm/Array/1169.py) Invalid Transactions _(permutations)_</li><li>[1170.py](./algorithm/Array/1170.py) Compare Strings by Frequency of the Smallest Character _(minmal counting)_</li><li>[1172.py](./algorithm/Array/1172.py) Dinner Plate Stacks _(heap, responsibilities)_</li><li>[1224.py](./algorithm/Array/1224.py) Maximum Equal Frequency</li><li>[1239.py](./algorithm/Array/1239.py) Maximum Length of a Concatenated String with Unique Characters _(set operation)_</li><li>[1247.py](./algorithm/Array/1247.py) Minimum Swaps to Make Strings Equal _(meaning of swap)_</li><li>[1260.py](./algorithm/Array/1260.py) Shift 2D Grid _(serialize and shift)_</li><li>[5181.py](./algorithm/Array/5181.py) Distance Between Bus Stops</li><li>[5222.py](./algorithm/Array/5222.py) Split a String in Balanced Strings</li></ol> |
| Array | <ol><li>[20.py](./algorithm/Array/20.py) Valid Parentheses _(elegant coding)_</li><li>[38.py](./algorithm/Array/38.py) Count and Say _(count consecutive elements)_</li><li>[42.py](./algorithm/Array/42.py) Trapping Rain Water _(two pointers)_</li><li>[45.py](./algorithm/Array/45.py) Jump Game II _(till and farest reach)_</li><li>[155.py](./algorithm/Array/155.py) Min Stack</li><li>[209.py](./algorithm/Array/209.py) Summary Ranges _(left pointer and accumulate)_</li><li>[217.py](./algorithm/Array/217.py) Contains Duplicate _(set)_</li><li>[219.py](./algorithm/Array/219.py) Contains Duplicate II _(just cares last)_</li><li>[228.py](./algorithm/Array/228.py) Summary Ranges _(count consecutive elements)_</li><li>[238.py](./algorithm/Array/238.py) Product of Array Except Self _(left2right, right2left)_</li><li>[242.py](./algorithm/Array/242.py) Valid Anagram _(counter equality)_</li><li>[348.py](./algorithm/Array/348.py) Design Tic-Tac-Toe _(diagonal math, sum, loop else)_</li><li>[349.py](./algorithm/Array/349.py) Intersection of Two Arrays _(set & set)_</li><li>[350.py](./algorithm/Array/350.py) Intersection of Two Arrays II _(counter & counter)_</li><li>[388.py](./algorithm/Array/388.py) Longest Absolute File Path _(split, lstrip, memorization)_</li><li>[838.py](./algorithm/Array/838.py) Push Dominoes _(force propagate/reset)_</li><li>[859.py](./algorithm/Array/859.py) Buddy Strings _(enumerate cases)_</li><li>[1002.py](./algorithm/Array/1002.py) Find Common Characters _(counter & counter)_</li><li>[1122.py](./algorithm/Array/1122.py) Relative Sort Array _(counter, sort)_</li><li>[1169.py](./algorithm/Array/1169.py) Invalid Transactions _(permutations)_</li><li>[1170.py](./algorithm/Array/1170.py) Compare Strings by Frequency of the Smallest Character _(minmal counting)_</li><li>[1172.py](./algorithm/Array/1172.py) Dinner Plate Stacks _(heap, responsibilities)_</li><li>[1224.py](./algorithm/Array/1224.py) Maximum Equal Frequency</li><li>[1239.py](./algorithm/Array/1239.py) Maximum Length of a Concatenated String with Unique Characters _(set operation)_</li><li>[1247.py](./algorithm/Array/1247.py) Minimum Swaps to Make Strings Equal _(meaning of swap)_</li><li>[1260.py](./algorithm/Array/1260.py) Shift 2D Grid _(serialize and shift)_</li><li>[5181.py](./algorithm/Array/5181.py) Distance Between Bus Stops</li><li>[5222.py](./algorithm/Array/5222.py) Split a String in Balanced Strings</li></ol> |
| Sort | <ol><li>[Sorting.py](./algorithm/Sort/Sorting.py)</li><li>[15.py](./algorithm/Sort/15.py) 3Sum _(two pointers)_</li><li>[41.py](./algorithm/Sort/41.py) First Missing Positive</li><li>[49.py](./algorithm/Sort/49.py) Group Anagrams</li><li>[56.py](./algorithm/Sort/56.py) Merge Intervals _(lambda sort key)_</li><li>[75.py](./algorithm/Sort/75.py) Sort Colors</li><li>[220.py](./algorithm/Sort/220.py) Contains Duplicate III</li><li>[253.py](./algorithm/Sort/253.py) Meeting Rooms II</li><li>[295.py](./algorithm/Sort/295.py) Find Median from Data Stream</li><li>[539.py](./algorithm/Sort/539.py) Minimum Time Difference</li><li>[953.py](./algorithm/Sort/953.py) Verifying an Alien Dictionary</li><li>[1051.py](./algorithm/Sort/1051.py) Height Checker</li></ol> |
| Tree | <ol><li>[Traversal.py](./algorithm/Tree/Traversal.py) / [BinarySearchTree.py](./algorithm/Tree/BinarySearchTree.py) / [BinaryTreeProperty.py](./algorithm/Tree/BinaryTreeProperty.py)</li><li>[98.py](./algorithm/Tree/98.py) Validate Binary Search Tree _(DFS min,max propagation)_</li><li>[102.py](./algorithm/Tree/102.py) Binary Tree Level Order Traversal _(BFS level propagation)_</li><li>[104.py](./algorithm/Tree/104.py) Maximum Depth of Binary Tree _(BFS level propagation)_</li><li>[105.py](./algorithm/Tree/105.py) Construct Binary Tree from Preorder and Inorder Traversal _(DFS .index and slice)_</li><li>[108.py](./algorithm/Tree/108.py) Convert Sorted Array to Binary Search Tree _(DFS mid and slice)_</li><li>[226.py](./algorithm/Tree/226.py) Invert Binary Tree _(DFS/BFS traversal)_</li><li>[250.py](./algorithm/Tree/250.py) Count Univalue Subtrees _(BFS&DFS check each subtrees)_</li><li>[333.py](./algorithm/Tree/333.py) Largest BST Subtree _(BFS&DFS check each subtrees, size in DFS/root in BFS)_</li><li>[863.py](./algorithm/Tree/863.py) All Nodes Distance K in Binary Tree _(DFS annotate parent, BFS condition traversal)_</li></ol> |
| Graph | <ol><li>[Graph.py](./algorithm/Graph/Graph.py)</li><li>[200.py](./algorithm/Graph/200.py) Number of Islands</li><li>[1222.py](./algorithm/Graph/1222.py) Queens That Can Attack the King</li></ol> |
| LinkedList | <ol><li>[19.py](./algorithm/LinkedList/19.py) Remove Nth Node From End of List</li><li>[141.py](./algorithm/LinkedList/141.py) Linked List Cycle _(slow/fast pointers)_</li><li>[206.py](./algorithm/LinkedList/206.py) Reverse Linked List _(prev/curr pointers)_</li><li>[160.py](./algorithm/LinkedList/160.py) Intersection of Two Linked Lists</li><li>[1171.py](./algorithm/LinkedList/1171.py) Remove Zero Sum Consecutive Nodes from Linked List</li></ol> |
| Dynamic Programming | <ol><li>[55.py](./algorithm/DP/55.py) Jump Game</li><li>[62.py](./algorithm/DP/62.py) Unique Paths</li><li>[70.py](./algorithm/DP/70.py) Climbing Stairs</li><li>[72.py](./algorithm/DP/72.py) Edit Distance</li><li>[1223.py](./algorithm/DP/1223.py) Dice Roll Simulation</li></ol> |
| Sub Array<br>Sub String | <ol><li>[53.py](./algorithm/Sub/53.py) Maximum Subarray _(add or new sum)_</li><li>[121.py](./algorithm/Sub/121.py) Best Time to Buy and Sell Stock _(just cares last)_</li><li>[152.py](./algorithm/Sub/152.py) Maximum Product Subarray _(min * negative)_</li><li>[386.py](./algorithm/Sub/386.py) Longest Substring with At Most K Distinct Characters _(just cares last, idx-left+1)_</li><li>[1233.py](./algorithm/Sub/1233.py) Remove Sub-Folders from the Filesystem _(rfind, set lookup)_</li><li>[1248.py](./algorithm/Sub/1248.py) Count Number of Nice Subarrays _(idx-left+1)_</li></ol> |
| Sub Array<br>Sub String | <ol><li>[53.py](./algorithm/Sub/53.py) Maximum Subarray _(add or new subsum)_</li><li>[121.py](./algorithm/Sub/121.py) Best Time to Buy and Sell Stock _(just cares last)_</li><li>[152.py](./algorithm/Sub/152.py) Maximum Product Subarray _(min * negative)_</li><li>[386.py](./algorithm/Sub/386.py) Longest Substring with At Most K Distinct Characters _(just cares last, idx-left+1)_</li><li>[1233.py](./algorithm/Sub/1233.py) Remove Sub-Folders from the Filesystem _(rfind, set lookup)_</li><li>[1248.py](./algorithm/Sub/1248.py) Count Number of Nice Subarrays _(atMost(k)-atMost(k - 1))_</li></ol> |
| Binary Search | <ol><li>[BinarySearchVariants.py](./algorithm/BinarySearch/BinarySearchVariants.py)</li><li>[33.py](./algorithm/BinarySearch/33.py) Search in Rotated Sorted Array _(check sorted part)_</li><li>[1237.py](./algorithm/BinarySearch/1237.py) Find Positive Integer Solution for a Given Equation _(search in constraint range)_</li></ol> |
| Math | <ol><li>[The Aggregate Magic Algorithms](http://aggregate.org/MAGIC/)</li><li>[1.py](./algorithm/Math/1.py) Two Sum</li><li>[7.py](./algorithm/Math/7.py) Reverse Integer</li><li>[172.py](./algorithm/Math/172.py) Factorial Trailing Zeroes</li><li>[224.py](./algorithm/Math/224.py) Basic Calculator</li><li>[1071.py](./algorithm/Math/1071.py) Greatest Common Divisor of Strings _(GCD(b, a%b))_</li><li>[1232.py](./algorithm/Math/1232.py) Check If It Is a Straight Line _(dx1*dy2=dy1*dx2)_</li><li>[1238.py](./algorithm/Math/1238.py) Circular Permutation in Binary Representation _(gray code x ^ x>>1)_</li><li>[1262.py](./algorithm/Math/1262.py) Greatest Sum Divisible by Three _(modulo removal)_</li><li>[5183.py](./algorithm/Math/5183.py) Day of the Week</li></ol> |
| Math | <ol><li>[The Aggregate Magic Algorithms](http://aggregate.org/MAGIC/)</li><li>[1.py](./algorithm/Math/1.py) Two Sum</li><li>[7.py](./algorithm/Math/7.py) Reverse Integer _(while != 0)_</li><li>[172.py](./algorithm/Math/172.py) Factorial Trailing Zeroes _(while != 0)_</li><li>[224.py](./algorithm/Math/224.py) Basic Calculator</li><li>[1071.py](./algorithm/Math/1071.py) Greatest Common Divisor of Strings _(GCD(b, a%b))_</li><li>[1232.py](./algorithm/Math/1232.py) Check If It Is a Straight Line _(dx1*dy2=dy1*dx2)_</li><li>[1238.py](./algorithm/Math/1238.py) Circular Permutation in Binary Representation _(gray code x ^ x>>1)_</li><li>[1262.py](./algorithm/Math/1262.py) Greatest Sum Divisible by Three _(modulo removal)_</li><li>[5183.py](./algorithm/Math/5183.py) Day of the Week</li></ol> |

## [Bash](./bash/)
* Bash Reference Manual: [link](https://www.gnu.org/software/bash/manual/bash.html)
Expand Down
48 changes: 48 additions & 0 deletions algorithm/Array/1122.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
'''
1122. Relative Sort Array
https://leetcode.com/problems/relative-sort-array/
Given two arrays arr1 and arr2,
the elements of arr2 are distinct,
and all elements in arr2 are also in arr1.
Sort the elements of arr1 such that
the relative ordering of items in arr1 are the same as in arr2.
Elements that don't appear in arr2 should be
placed at the end of arr1 in ascending order.
Example 1:
Input: arr1 = [2,3,1,3,2,4,6,7,9,2,19], arr2 = [2,1,4,3,9,6]
Output: [2,2,2,1,4,3,3,9,6,7,19]
Constraints:
arr1.length, arr2.length <= 1000
0 <= arr1[i], arr2[i] <= 1000
Each arr2[i] is distinct.
Each arr2[i] is in arr1.
'''
from typing import *
import collections

class Solution:
def relativeSortArray(self, arr1: List[int], arr2: List[int]) -> List[int]:
ans = []
c1 = collections.Counter(arr1)
for num in arr2:
ans.extend([num] * c1[num])
del c1[num]
remain = list(c1.keys())
for num in sorted(remain):
# remain num should appear the same times
ans.extend([num] * c1[num])
return ans

arr1 = [2,3,1,3,2,4,6,7,9,2,19]
arr2 = [2,1,4,3,9,6]
print(Solution().relativeSortArray(arr1, arr2))
# [2,2,2,1,4,3,3,9,6,7,19]

arr1 = [2,21,43,38,0,42,33,7,24,13,12,27,12,24,5,23,29,48,30,31]
arr2 = [2,42,38,0,43,21]
print(Solution().relativeSortArray(arr1, arr2))
# [2,42,38,0,43,21,5,7,12,12,13,23,24,24,27,29,30,31,33,48]
19 changes: 11 additions & 8 deletions algorithm/Sub/121.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,15 +26,18 @@

class Solution:
def maxProfit(self, prices: List[int]) -> int:
# check not empty
# avoid array index out of range for prices[0]
if not prices:
return 0
profit = 0
if prices:
minPrice = prices[0]
for pidx in range(1, len(prices)):
# ONLY cares largest peak
# following the smallest valley,
# keep updating valid result
minPrice = min(minPrice, prices[pidx])
profit = max(profit, prices[pidx]-minPrice)
minPrice = prices[0]
for pidx in range(1, len(prices)):
# ONLY cares largest peak
# following the smallest valley,
# keep updating valid result
minPrice = min(minPrice, prices[pidx])
profit = max(profit, prices[pidx]-minPrice)
return profit

print(Solution().maxProfit([7,1,5,3,6,4]))
Expand Down
5 changes: 3 additions & 2 deletions algorithm/Sub/1233.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,16 +40,17 @@
class Solution:
def removeSubfolders(self, folder: List[str]) -> List[str]:
ans = []
set = { f for f in folder }
folderSet = set(folder)
for f in folder:
path = f
while path:
# Cut down last ..."/xx" to move
# upper level and look for it in set
path = path[:path.rfind('/')]
if path in set:
if path in folderSet:
break
else:
# Append if no break
ans.append(f)
return ans

Expand Down
4 changes: 4 additions & 0 deletions algorithm/Sub/152.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,10 @@

class Solution:
def maxSubProduct(self, nums: List[int]) -> int:
# check not empty
# avoid array index out of range for prices[0]
if not nums:
return 0
subMax = subMin = maxSubProd = nums[0]
#print("maxSubProd:{0}".format(maxSubProd))
for i in range(1, len(nums)):
Expand Down
5 changes: 4 additions & 1 deletion algorithm/Sub/53.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@
class Solution:

def maxSubArray(self, nums: List[int]) -> int:
# check not empty
# avoid array index out of range for nums[0]
if not nums:
return 0
maxSubSum = nums[0]
Expand All @@ -39,4 +41,5 @@ def maxSubArray(self, nums: List[int]) -> int:
dp[i] = max(dp[i-1]+nums[i], nums[i])
return max(dp)

print(Solution().maxSubArray([-2,1,-3,4,-1,2,1,-5,4]))
print(Solution().maxSubArray([-2,1,-3,4,-1,2,1,-5,4]))
# 6

0 comments on commit 8204997

Please sign in to comment.