Monday, November 10, 2014

Leetcode: Min Stack @Python

Use another stack to keep track of the min value so far.
class MinStack:
    # @param x, an integer
    def __init__(self):
        # the stack it self
        self.A = []
        self.minS=[]
    # @return an integer
    def push(self, x):
        n=len(self.A)
        if n==0:
            self.minS.append(x)
        else:
            lastmin=self.minS[-1]
            if x%lt;=lastmin:
                self.minS.append(x)
        self.A.append(x)
    # @return nothing
    def pop(self):
        if len(self.A)>0 and self.A.pop()==self.minS[-1]:
            self.minS.pop()
    # @return an integer
    def top(self):
        return self.A[-1]
        

    # @return an integer
    def getMin(self):
        return self.minS[-1]
 

Wednesday, October 22, 2014

Leetcode: Find Minimum in Rotated Sorted Array @Python

Pay attention to the ending condition and edge cases.
class Solution:
    # @param num, a list of integer
    # @return an integer
    def findMin(self, num):
        n=len(num)
        strt=0
        nd=n-1
        while num[strt]>num[nd]:
            mid=(strt+nd)//2
            if num[strt]>num[mid]:
                nd=mid
            elif num[strt]<num[mid]:
                strt=mid
            else:
                return num[nd]
        return num[strt]

Leetcode: Find Minimum in Rotated Sorted Array II @Python

class Solution:
    # @param num, a list of integer
    # @return an integer
    def findMin(self, num):
        n=len(num)
        strt=0
        nd=n-1
        while nd-strt>1:
            mid=(strt+nd)//2
            if num[strt]<num[nd]:
                return num[strt]
            elif num[strt]>num[nd]:
                if num[strt]>num[mid]:
                    nd=mid
                else:
                    strt=mid
            else:
                strt+=1
        return num[strt] if num[strt]<num[nd] else num[nd]

Wednesday, October 8, 2014

Leetcode: Maximum Product Subarray @Python

Dynamic Programming, O(n) time complexity and O(1) space complexity.
Scan the list once,keep updating two variables mincrt and maxcrt.
mincrt is the minimum product end with the last element scanned. maxcrt is the maximum counterpart.
rst is used to store the maximal product so far.
Every time when updating with the new element, mincrt and maxcrt are from either the product with the new element ,or breaking up multiplication and starting from the new element.
class Solution:
    # @param A, a list of integers
    # @return an integer
    def maxProduct(self, A):
        mincrt=maxcrt=rst=A[0]
        for i in range(1,len(A)):
            mincrt,maxcrt=min(A[i],A[i]*mincrt,A[i]*maxcrt),max(A[i],A[i]*mincrt,A[i]*maxcrt)
            rst=max(rst,maxcrt)
        return rst

Friday, September 19, 2014

Solutions to All Leetcode Problems with Python

I finally finished all the 154 Leetcode problems in Python. 
In my blog, I try to post the most succinct and effective Python solutions to Leetcode problems. You are more than welcome to post your solutions in the comments if you think yours are better. 
I will add on explanations to the solutions later. 
I also want to thank the following two bloggers. 水中的鱼 explains the algorithms in a clear and succinct way. Kitt's blog is the best Python leetcode solution blog so far.
Title Algorith&Data Structure AC Rates
Single Number 45.90%
Maximum Depth of Binary Tree 43.90%
Same Tree 42.20%
Reverse Integer 40.20%
Best Time to Buy and Sell Stock II 36.80%
Unique Binary Search Trees 36.40%
Linked List Cycle 35.90%
Binary Tree Preorder Traversal 35.60%
Binary Tree Inorder Traversal 35.60%
Populating Next Right Pointers in Each Node 35.30%
Search Insert Position 35.00%
Remove Duplicates from Sorted List 35.00%
Climbing Stairs DP 34.00%
Roman to Integer 33.90%
Single Number II 33.80%
Maximum Subarray 33.80%
Integer to Roman 33.70%
Remove Element 33.40%
Merge Two Sorted Lists 33.30%
N-Queens II BFS, iterator 33.20%
Balanced Binary Tree 32.70%
Convert Sorted Array to Binary Search Tree 32.60%
Remove Duplicates from Sorted Array 32.40%
Swap Nodes in Pairs 32.40%
Symmetric Tree 32.20%
Sort Colors 32.10%
Merge Sorted Array 32.10%
Gray Code 32.00%
Pascal's Triangle 31.70%
Find Minimum in Rotated Sorted Array log(n) 31.60%
Plus One 31.60%
Generate Parentheses 31.50%
Rotate Image 31.50%
Unique Paths 31.50%
Container With Most Water 31.30%
Binary Tree Level Order Traversal II 31.30%
Permutations 31.30%
Minimum Path Sum 31.20%
Search a 2D Matrix 31.10%
Best Time to Buy and Sell Stock 31.00%
Set Matrix Zeroes 30.90%
Linked List Cycle II 30.90%
Binary Tree Postorder Traversal 30.90%
Spiral Matrix II 30.80%
Binary Tree Level Order Traversal 30.80%
Search in Rotated Sorted Array II 30.70%
Remove Duplicates from Sorted Array II 30.60%
Path Sum 30.60%
Pascal's Triangle II 30.50%
Populating Next Right Pointers in Each Node II 30.40%
Combinations 30.40%
Remove Nth Node From End of List 29.90%
Sum Root to Leaf Numbers 29.80%
Minimum Depth of Binary Tree 29.60%
Length of Last Word 29.50%
Palindrome Number 29.00%
Trapping Rain Water 28.70%
Search in Rotated Sorted Array 28.60%
Valid Parentheses 28.40%
Longest Consecutive Sequence 28.10%
Flatten Binary Tree to Linked List 28.10%
Subsets 27.90%
Valid Sudoku 27.90%
Unique Paths II 27.80%
Search for a Range 27.50%
Count and Say 27.30%
Unique Binary Search Trees II 27.30%
Convert Sorted List to Binary Search Tree 27.30%
Longest Common Prefix 27.20%
Jump Game 27.20%
3Sum Closest 27.10%
Subsets II 27.00%
Path Sum II 27.00%
Partition List 26.80%
Triangle 26.70%
Binary Tree Zigzag Level Order Traversal 26.70%
Combination Sum 26.60%
Construct Binary Tree from Preorder and Inorder Traversal 26.50%
Construct Binary Tree from Inorder and Postorder Traversal 26.40%
Letter Combinations of a Phone Number 26.30%
Reverse Linked List II 26.00%
N-Queens BFS/iterator 26.00%
Add Binary 26.00%
Pow(x, n) 25.90%
Palindrome Partitioning 25.90%
Validate Binary Search Tree 25.90%
Find Minimum in Rotated Sorted Array II log(n) 25.80%
Gas Station 25.70%
Next Permutation 25.40%
Edit Distance 25.30%
Insertion Sort List 25.30%
Permutations II 25.10%
Remove Duplicates from Sorted List II 24.90%
Reverse Nodes in k-Group 24.90%
Distinct Subsequences 24.80%
Jump Game II 24.70%
Combination Sum II 24.60%
ZigZag Conversion 23.90%
Anagrams 23.60%
Recover Binary Search Tree 23.50%
Copy List with Random Pointer 23.20%
Add Two Numbers 23.10%
Valid Palindrome 22.90%
Clone Graph 22.80%
Scramble String 22.60%
First Missing Positive 22.50%
Sqrt(x) 22.30%
Longest Substring Without Repeating Characters 22.30%
Best Time to Buy and Sell Stock III 22.20%
Rotate List 22.10%
Permutation Sequence 22.10%
Merge k Sorted Lists 21.90%
Implement strStr() 21.80%
4Sum 21.60%
Maximal Rectangle 21.60%
Largest Rectangle in Histogram 21.20%
Word Break 21.10%
Sudoku Solver 20.80%
Merge Intervals 20.80%
Longest Palindromic Substring 20.80%
Spiral Matrix 20.60%
Insert Interval 20.60%
Sort List 20.50%
Multiply Strings 20.50%
Restore IP Addresses 20.50%
Reorder List 20.30%
Binary Tree Maximum Path Sum 20.00%
Regular Expression Matching 19.90%
Evaluate Reverse Polish Notation 19.90%
Word Search 19.90%
Simplify Path 19.90%
Longest Valid Parentheses 19.60%
Interleaving String 19.20%
Candy 19.00%
Two Sum 18.50%
Word Ladder 18.30%
Palindrome Partitioning II 18.00%
Minimum Window Substring 18.00%
Substring with Concatenation of All Words 18.00%
Median of Two Sorted Arrays 17.40%
3Sum 16.90%
Word Break II 16.40%
Divide Two Integers 16.30%
Maximum Product Subarray DP/list 16.20%
Min Stack 16.20%
Decode Ways 16.10%
String to Integer (atoi) 14.70%
Surrounded Regions 14.20%
Reverse Words in a String 14.10%
LRU Cache 14.00%
Text Justification 14.00%
Wildcard Matching 13.80%
Word Ladder II 11.30%
Valid Number 11.00%
Max Points on a Line 10.90%

Leetcode: Max Points on a Line @Python

# Definition for a point
# class Point:
#     def __init__(self, a=0, b=0):
#         self.x = a
#         self.y = b

class Solution:
    # @param points, a list of Points
    # @return an integer
    def maxPoints(self, points):
        if len(points)==0: return 0
        n=len(points)
        maxnum=1
        for i in range(n):
            dic={'inf':0}
            same=0
            for j in range(n):
                if points[i].x==points[j].x and points[i].y==points[j].y:
                    same+=1
                else:
                    slope='inf' if points[i].x==points[j].x else 1.0*(points[i].y-points[j].y)/(points[i].x-points[j].x)
                    if slope not in dic:
                        dic[slope]=1
                    else:
                        dic[slope]+=1
            maxnum=max(maxnum,max(dic.values())+same)
        return maxnum

Leetcode: Valid Number @Python

Finite State Machine Solution:
class Solution:
    # @param s, a string
    # @return a boolean
    def isNumber(self, s):
        s=s.rstrip(' ')
        s=s.lstrip(' ')
        trans=[[1,2,3,-1], #state 0:start
               [1,-1,7,4], #state 1:digit
               [1,-1,3,-1], #state 2: +/-
               [7,-1,-1,-1], #state 3:.dot
               [5,6,-1,-1],  #state 4:e/E
               [5,-1,-1,-1], #state 5: exponent
               [5,-1,-1,-1], #state 6: exponent+/-
               [7,-1,-1,4]] #state 7: .digits
        state=0
        for char in s:
            if char in '0123456789':
                inputs=1
            elif char in '+-':
                inputs=2
            elif char=='.':
                inputs=3
            elif char in 'eE':
                inputs=4
            else:
                return False
            state=trans[state][inputs-1]
            if state==-1:return False
        if state==1 or state==5 or state==7:
            return True
        else:
            return False
You can use the following code to find all corner cases. Cheat Code:

class Solution:
    # @param s, a string
    # @return a boolean
    def isNumber(self, s):
        try:
            float(s)                 # If error is shown then print False else True
            return True                
        except:
            return False