From 6f08c06c4f89456ba2817594b5a1eb47e940ed5c Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 16 Jan 2015 13:27:27 +0800 Subject: [PATCH 001/345] Update README.md --- README.md | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index c7c3ea16e..ebdd7e29d 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ LeetCode ======== -Up to date (2015-01-13), there are total `180` problems on [LeetCode Online Judge](https://oj.leetcode.com/). +Up to date (2015-01-16), there are total `181` problems on [LeetCode Online Judge](https://oj.leetcode.com/). The number of problems is increasing recently. -Here is the classification of all `180` problems. +Here is the classification of all `181` problems. I'll keep updating for full summary and better solutions. Stay tuned for updates. --- @@ -717,6 +717,7 @@ Problem | Solution | Time | Space | Difficul --------------- | --------------- | --------------- | --------------- | -------------- | ----- [Combine Two Tables] | [combine-two-tables.sql] | _O(m + n)_ | _O(m + n)_ | Easy | [Consecutive Numbers] | [consecutive-numbers.sql] | _O(n)_ | _O(n)_ | Medium | +[Employees Earning More Than Their Managers] | [employees-earning-more-than-their-managers.sql] | _O(n^2)_ | _O(1)_ | Easy | [Nth Highest Salary] | [nth-highest-salary.sql] | _O(n^2)_ | _O(n)_ | Medium | [Rank Scores] | [rank-scores.sql] | _O(n^2)_ | _O(n)_ | Medium | [Second Highest Salary] | [second-highest-salary.sql] | _O(n)_ | _O(1)_ | Easy | @@ -725,6 +726,8 @@ Problem | Solution | Time | Space | Difficul [combine-two-tables.sql]:https://github.com/kamyu104/LeetCode/blob/master/MySQL/combine-two-tables.sql [Consecutive Numbers]:https://oj.leetcode.com/problems/consecutive-numbers/ [consecutive-numbers.sql]:https://github.com/kamyu104/LeetCode/blob/master/MySQL/consecutive-numbers.sql +[Employees Earning More Than Their Managers]:https://oj.leetcode.com/problems/employees-earning-more-than-their-managers/ +[employees-earning-more-than-their-managers.sql]:https://github.com/kamyu104/LeetCode/blob/master/MySQL/employees-earning-more-than-their-managers.sql [Nth Highest Salary]:https://oj.leetcode.com/problems/nth-highest-salary/ [nth-highest-salary.sql]:https://github.com/kamyu104/LeetCode/blob/master/MySQL/nth-highest-salary.sql [Rank Scores]:https://oj.leetcode.com/problems/rank-scores/ From bc454a270b4b3de317cf1d30a9c7fbe0e015bb52 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 16 Jan 2015 13:33:46 +0800 Subject: [PATCH 002/345] Create employees-earning-more-than-their-managers.sql --- ...oyees-earning-more-than-their-managers.sql | 37 +++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 MySQL/employees-earning-more-than-their-managers.sql diff --git a/MySQL/employees-earning-more-than-their-managers.sql b/MySQL/employees-earning-more-than-their-managers.sql new file mode 100644 index 000000000..414f87f53 --- /dev/null +++ b/MySQL/employees-earning-more-than-their-managers.sql @@ -0,0 +1,37 @@ +# Time: O(n^2) +# Space: O(1) +# +# The Employee table holds all employees including their managers. Every employee has an Id, and there is also a column for the manager Id. +# +# +----+-------+--------+-----------+ +# | Id | Name | Salary | ManagerId | +# +----+-------+--------+-----------+ +# | 1 | Joe | 70000 | 3 | +# | 2 | Henry | 80000 | 4 | +# | 3 | Sam | 60000 | NULL | +# | 4 | Max | 90000 | NULL | +# +----+-------+--------+-----------+ +# Given the Employee table, write a SQL query that finds out employees who earn more than their managers. For the above table, Joe is the only employee who earns more than his manager. +# +# +----------+ +# | Employee | +# +----------+ +# | Joe | +# +----------+ +# + +# Time: O(n^2) +# Space: O(n) +# Write your MySQL query statement below +SELECT e.Name AS Employee FROM Employee e LEFT JOIN Employee b + ON e.ManagerId=b.Id + WHERE e.Salary > b.Salary + +# Time: O(n^2) +# Space: O(1) +# Write your MySQL query statement below +SELECT Name AS Employee + FROM Employee e + WHERE e.Salary > (SELECT Salary + FROM Employee + WHERE e.ManagerId = Id) From 5a5f2618d14a9da61287e225815077c611c5fb58 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 16 Jan 2015 13:36:23 +0800 Subject: [PATCH 003/345] Update employees-earning-more-than-their-managers.sql --- MySQL/employees-earning-more-than-their-managers.sql | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MySQL/employees-earning-more-than-their-managers.sql b/MySQL/employees-earning-more-than-their-managers.sql index 414f87f53..eaafe2a00 100644 --- a/MySQL/employees-earning-more-than-their-managers.sql +++ b/MySQL/employees-earning-more-than-their-managers.sql @@ -32,6 +32,6 @@ SELECT e.Name AS Employee FROM Employee e LEFT JOIN Employee b # Write your MySQL query statement below SELECT Name AS Employee FROM Employee e - WHERE e.Salary > (SELECT Salary + WHERE e.ManagerId IS NOT NULL AND e.Salary > (SELECT Salary FROM Employee WHERE e.ManagerId = Id) From 7eb2f366b5d64b4f97809080db57644c28510ccb Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 18 Jan 2015 23:45:38 +0800 Subject: [PATCH 004/345] Create duplicate-emails.sql --- Python/duplicate-emails.sql | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 Python/duplicate-emails.sql diff --git a/Python/duplicate-emails.sql b/Python/duplicate-emails.sql new file mode 100644 index 000000000..836ad0490 --- /dev/null +++ b/Python/duplicate-emails.sql @@ -0,0 +1,24 @@ +# Time: O(n^2) +# Space: O(n) +# +# Write a SQL query to find all duplicate emails in a table named Person. +# +# +----+---------+ +# | Id | Email | +# +----+---------+ +# | 1 | a@b.com | +# | 2 | c@d.com | +# | 3 | a@b.com | +# +----+---------+ +# For example, your query should return the following for the above table: +# +# +---------+ +# | Email | +# +---------+ +# | a@b.com | +# +---------+ +# Note: All emails are in lowercase. +# + +# Write your MySQL query statement below +SELECT Email FROM Person GROUP BY Email HAVING COUNT(*) > 1 From c36d86db0554b1fc1b709bf6a0d28733f5bbccca Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Sun, 18 Jan 2015 23:46:24 +0800 Subject: [PATCH 005/345] update --- {Python => MySQL}/duplicate-emails.sql | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename {Python => MySQL}/duplicate-emails.sql (100%) diff --git a/Python/duplicate-emails.sql b/MySQL/duplicate-emails.sql similarity index 100% rename from Python/duplicate-emails.sql rename to MySQL/duplicate-emails.sql From c5534064db2f597aa1fa6403848a7d21b7c29c05 Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Sun, 18 Jan 2015 23:50:36 +0800 Subject: [PATCH 006/345] update --- README.md | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index ebdd7e29d..3f8e2ccea 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ LeetCode ======== -Up to date (2015-01-16), there are total `181` problems on [LeetCode Online Judge](https://oj.leetcode.com/). +Up to date (2015-01-18), there are total `182` problems on [LeetCode Online Judge](https://oj.leetcode.com/). The number of problems is increasing recently. -Here is the classification of all `181` problems. +Here is the classification of all `182` problems. I'll keep updating for full summary and better solutions. Stay tuned for updates. --- @@ -717,6 +717,7 @@ Problem | Solution | Time | Space | Difficul --------------- | --------------- | --------------- | --------------- | -------------- | ----- [Combine Two Tables] | [combine-two-tables.sql] | _O(m + n)_ | _O(m + n)_ | Easy | [Consecutive Numbers] | [consecutive-numbers.sql] | _O(n)_ | _O(n)_ | Medium | +[Duplicate Emails] | [duplicate-emails.sql] | _O(n^2)_ | _O(n)_ | Easy | [Employees Earning More Than Their Managers] | [employees-earning-more-than-their-managers.sql] | _O(n^2)_ | _O(1)_ | Easy | [Nth Highest Salary] | [nth-highest-salary.sql] | _O(n^2)_ | _O(n)_ | Medium | [Rank Scores] | [rank-scores.sql] | _O(n^2)_ | _O(n)_ | Medium | @@ -726,6 +727,8 @@ Problem | Solution | Time | Space | Difficul [combine-two-tables.sql]:https://github.com/kamyu104/LeetCode/blob/master/MySQL/combine-two-tables.sql [Consecutive Numbers]:https://oj.leetcode.com/problems/consecutive-numbers/ [consecutive-numbers.sql]:https://github.com/kamyu104/LeetCode/blob/master/MySQL/consecutive-numbers.sql +[Duplicate Emails]:https://oj.leetcode.com/problems/duplicate-emails/ +[duplicate-emails.sql]:https://github.com/kamyu104/LeetCode/blob/master/MySQL/duplicate-emails.sql [Employees Earning More Than Their Managers]:https://oj.leetcode.com/problems/employees-earning-more-than-their-managers/ [employees-earning-more-than-their-managers.sql]:https://github.com/kamyu104/LeetCode/blob/master/MySQL/employees-earning-more-than-their-managers.sql [Nth Highest Salary]:https://oj.leetcode.com/problems/nth-highest-salary/ From d857776f65ecbac0785c7c46a908b95db689222a Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 19 Jan 2015 13:41:08 +0800 Subject: [PATCH 007/345] Rename surrounded-region.py to surrounded-regions.py --- Python/{surrounded-region.py => surrounded-regions.py} | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) rename Python/{surrounded-region.py => surrounded-regions.py} (99%) diff --git a/Python/surrounded-region.py b/Python/surrounded-regions.py similarity index 99% rename from Python/surrounded-region.py rename to Python/surrounded-regions.py index a16bbee0b..bec979730 100644 --- a/Python/surrounded-region.py +++ b/Python/surrounded-regions.py @@ -57,4 +57,4 @@ def solve(self, board): ['X', 'X', 'O', 'X'], ['X', 'O', 'X', 'X']] Solution().solve(board) - print board \ No newline at end of file + print board From beae3d588f120f990f8ecb745f771b6ed193d5c5 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 21 Jan 2015 13:46:27 +0800 Subject: [PATCH 008/345] Create customers-who-never-order.sql --- MySQL/customers-who-never-order.sql | 42 +++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 MySQL/customers-who-never-order.sql diff --git a/MySQL/customers-who-never-order.sql b/MySQL/customers-who-never-order.sql new file mode 100644 index 000000000..c63d41aaa --- /dev/null +++ b/MySQL/customers-who-never-order.sql @@ -0,0 +1,42 @@ +# Time: O(n^2) +# Space: O(1) +# +# Suppose that a website contains two tables, the Customers table and the Orders table. Write a SQL query to find all customers who never order anything. +# +# Table: Customers. +# +# +----+-------+ +# | Id | Name | +# +----+-------+ +# | 1 | Joe | +# | 2 | Henry | +# | 3 | Sam | +# | 4 | Max | +# +----+-------+ +# Table: Orders. +# +# +----+------------+ +# | Id | CustomerId | +# +----+------------+ +# | 1 | 3 | +# | 2 | 1 | +# +----+------------+ +# Using the above tables as example, return the following: +# +# +-----------+ +# | Customers | +# +-----------+ +# | Henry | +# | Max | +# +-----------+ +# + +# Time: O(n^2) +# Space: O(1) +# Write your MySQL query statement below +SELECT Name AS Customers FROM Customers WHERE Id NOT IN (SELECT CustomerId FROM Orders) + +# Time: O(n^2) +# Space: O(n) +# Write your MySQL query statement below +SELECT Customers.Name AS Customers FROM (Customers LEFT JOIN Orders ON Customers.Id = Orders.CustomerId) WHERE Orders.CustomerId IS NULL From 6cfd88163c5678bd2a22d29b2aab2cae084c4ac2 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 21 Jan 2015 13:48:41 +0800 Subject: [PATCH 009/345] Update README.md --- README.md | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 3f8e2ccea..bbf33b400 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ LeetCode ======== -Up to date (2015-01-18), there are total `182` problems on [LeetCode Online Judge](https://oj.leetcode.com/). +Up to date (2015-01-21), there are total `183` problems on [LeetCode Online Judge](https://oj.leetcode.com/). The number of problems is increasing recently. -Here is the classification of all `182` problems. +Here is the classification of all `183` problems. I'll keep updating for full summary and better solutions. Stay tuned for updates. --- @@ -717,6 +717,7 @@ Problem | Solution | Time | Space | Difficul --------------- | --------------- | --------------- | --------------- | -------------- | ----- [Combine Two Tables] | [combine-two-tables.sql] | _O(m + n)_ | _O(m + n)_ | Easy | [Consecutive Numbers] | [consecutive-numbers.sql] | _O(n)_ | _O(n)_ | Medium | +[Customers Who Never Order] | [customers-who-never-order.sql] | _O(n^2)_ | _O(1)_ | Easy | [Duplicate Emails] | [duplicate-emails.sql] | _O(n^2)_ | _O(n)_ | Easy | [Employees Earning More Than Their Managers] | [employees-earning-more-than-their-managers.sql] | _O(n^2)_ | _O(1)_ | Easy | [Nth Highest Salary] | [nth-highest-salary.sql] | _O(n^2)_ | _O(n)_ | Medium | @@ -727,6 +728,8 @@ Problem | Solution | Time | Space | Difficul [combine-two-tables.sql]:https://github.com/kamyu104/LeetCode/blob/master/MySQL/combine-two-tables.sql [Consecutive Numbers]:https://oj.leetcode.com/problems/consecutive-numbers/ [consecutive-numbers.sql]:https://github.com/kamyu104/LeetCode/blob/master/MySQL/consecutive-numbers.sql +[Customers Who Never Order]:https://oj.leetcode.com/problems/customers-who-never-order/ +[customers-who-never-order.sql]:https://github.com/kamyu104/LeetCode/blob/master/MySQL/customers-who-never-order.sql [Duplicate Emails]:https://oj.leetcode.com/problems/duplicate-emails/ [duplicate-emails.sql]:https://github.com/kamyu104/LeetCode/blob/master/MySQL/duplicate-emails.sql [Employees Earning More Than Their Managers]:https://oj.leetcode.com/problems/employees-earning-more-than-their-managers/ From 21025462833cc33578e7308c622cb28d4715cb38 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 21 Jan 2015 14:50:28 +0800 Subject: [PATCH 010/345] Update median-of-two-sorted-arrays.py --- Python/median-of-two-sorted-arrays.py | 47 +++++++++++++++++++++++++-- 1 file changed, 44 insertions(+), 3 deletions(-) diff --git a/Python/median-of-two-sorted-arrays.py b/Python/median-of-two-sorted-arrays.py index 47f6c6862..644f74927 100644 --- a/Python/median-of-two-sorted-arrays.py +++ b/Python/median-of-two-sorted-arrays.py @@ -1,11 +1,52 @@ # Time: O(log(m + n)) -# Space: O(log(m + n)) +# Space: O(1) # # There are two sorted arrays A and B of size m and n respectively. # Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)). # class Solution: + # @return a float + def findMedianSortedArrays(self, A, B): + lenA, lenB = len(A), len(B) + if (lenA + lenB) % 2 == 1: + return self.getKth(A, B, (lenA + lenB)/2 + 1) + else: + return (self.getKth(A, B, (lenA + lenB)/2) + self.getKth(A, B, (lenA + lenB)/2 + 1)) * 0.5 + + def getKth(self, A, B, k): + b = max(0, k - len(B)) + t = min(len(A), k) + while b < t: + x = b + (t - b) / 2 + A_x_1, A_x, B_k_x_1, B_k_x = float("-inf"), float("inf"), float("-inf"), float("inf") + if x > 0: + A_x_1 = A[x - 1] + if x < len(A): + A_x = A[x] + if k - x > 0: + B_k_x_1 = B[k - x - 1] + if k - x < len(B): + B_k_x = B[k - x] + + if A_x < B_k_x_1: + b = x + 1 + elif A_x_1 > B_k_x: + t = x - 1 + else: + return max(A_x_1, B_k_x_1) + + A_b_1, B_k_b_1 = float("-inf"), float("-inf") + if b > 0: + A_b_1 = A[b - 1] + if k - b - 1 >= 0: + B_k_b_1 = B[k - b - 1] + + return max(A_b_1, B_k_b_1) + +# Time: O(log(m + n)) +# Space: O(log(m + n)) +class Solution2: # @return a float def findMedianSortedArrays(self, A, B): lenA, lenB = len(A), len(B) @@ -36,7 +77,7 @@ def getKth(self, A, i, B, j, k): return A[i + pa - 1] # using list slicing (O(k)) may be slower than solution1 -class Solution2: +class Solution3: # @return a float def findMedianSortedArrays(self, A, B): lenA, lenB = len(A), len(B) @@ -69,4 +110,4 @@ def getKth(self, A, B, k): if __name__ == "__main__": print Solution().findMedianSortedArrays([1, 3, 5, 7], [2, 4, 6]) print Solution().findMedianSortedArrays([1, 3, 5], [2, 4, 6]) - \ No newline at end of file + From d72a56643b64e8c268c59ac96a5c7152a995ca93 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 21 Jan 2015 14:51:30 +0800 Subject: [PATCH 011/345] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index bbf33b400..31a3d155e 100644 --- a/README.md +++ b/README.md @@ -496,7 +496,7 @@ Problem | Solution | Time | Space | Difficul [Find Minimum in Rotated Sorted Array] | [find-minimum-in-rotated-sorted-array.py] | _O(logn)_ | _O(1)_ | Medium | [Find Minimum in Rotated Sorted Array II] | [find-minimum-in-rotated-sorted-array-ii.py] | _O(logn)_ ~ _O(n)_ | _O(1)_ | Hard | [Find Peak Element] | [find-peak-element.py] | _O(logn)_ | _O(1)_ | Medium | -[Median of Two Sorted Arrays] | [median-of-two-sorted-arrays.py] | _O(log(m + n)_ | _O(log(m + n)_ | Hard | +[Median of Two Sorted Arrays] | [median-of-two-sorted-arrays.py] | _O(log(m + n)_ | _O(1)_ | Hard | [Pow(x, n)] | [powx-n.py] | _O(logn)_ | _O(logn)_ | Medium | [Search a 2D Matrix] | [search-a-2d-matrix.py] | _O(log m + logn)_ | _O(1)_ | Medium | [Search for a Range] | [search-for-a-range.py] | _O(logn)_ | _O(1)_ | Medium | From cae03ab91f32a0a6bc846aefb81f4cc78277bfb1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 21 Jan 2015 22:54:54 +0800 Subject: [PATCH 012/345] Create department-highest-salary --- MySQL/department-highest-salary | 42 +++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 MySQL/department-highest-salary diff --git a/MySQL/department-highest-salary b/MySQL/department-highest-salary new file mode 100644 index 000000000..1c5670253 --- /dev/null +++ b/MySQL/department-highest-salary @@ -0,0 +1,42 @@ +# Time: O(n^2) +# Space: O(n) +# +# The Employee table holds all employees. Every employee has an Id, a salary, and there is also a column for the department Id. +# +# +----+-------+--------+--------------+ +# | Id | Name | Salary | DepartmentId | +# +----+-------+--------+--------------+ +# | 1 | Joe | 70000 | 1 | +# | 2 | Henry | 80000 | 2 | +# | 3 | Sam | 60000 | 2 | +# | 4 | Max | 90000 | 1 | +# +----+-------+--------+--------------+ +# The Department table holds all departments of the company. +# +# +----+----------+ +# | Id | Name | +# +----+----------+ +# | 1 | IT | +# | 2 | Sales | +# +----+----------+ +# Write a SQL query to find employees who have the highest salary in each of the departments. For the above tables, Max has the highest salary in the IT department and Henry has the highest salary in the Sales department. +# +# +------------+----------+--------+ +# | Department | Employee | Salary | +# +------------+----------+--------+ +# | IT | Max | 90000 | +# | Sales | Henry | 80000 | +# +------------+----------+--------+ +# +# Write your MySQL query statement below +SELECT d.Department AS Department, e.Name AS Employee, d.Salary AS Salary +FROM (SELECT Department.Id AS DepartmentId, Department.Name AS Department, emp.Salary AS Salary + FROM Department JOIN (SELECT DepartmentId, MAX(Salary) AS Salary FROM Employee GROUP BY Employee.DepartmentId) emp + ON Department.Id = emp.DepartmentId) d + JOIN Employee e + ON e.DepartmentId = d.DepartmentId and e.Salary = d.Salary + +# Write your MySQL query statement below +SELECT Department.Name AS Department, Employee.Name AS Employee, Employee.Salary AS Salary +FROM Department JOIN Employee ON Employee.DepartmentId = Department.Id +WHERE Employee.Salary IN (SELECT MAX(e.Salary) FROM Employee e WHERE e.DepartmentId = Employee.DepartmentId) From 00103491530d2495f4118070ee1b011f783e1909 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 21 Jan 2015 22:57:33 +0800 Subject: [PATCH 013/345] Update README.md --- README.md | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 31a3d155e..323a2a7fd 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ LeetCode ======== -Up to date (2015-01-21), there are total `183` problems on [LeetCode Online Judge](https://oj.leetcode.com/). +Up to date (2015-01-21), there are total `184` problems on [LeetCode Online Judge](https://oj.leetcode.com/). The number of problems is increasing recently. -Here is the classification of all `183` problems. +Here is the classification of all `184` problems. I'll keep updating for full summary and better solutions. Stay tuned for updates. --- @@ -718,6 +718,7 @@ Problem | Solution | Time | Space | Difficul [Combine Two Tables] | [combine-two-tables.sql] | _O(m + n)_ | _O(m + n)_ | Easy | [Consecutive Numbers] | [consecutive-numbers.sql] | _O(n)_ | _O(n)_ | Medium | [Customers Who Never Order] | [customers-who-never-order.sql] | _O(n^2)_ | _O(1)_ | Easy | +[Department Highest Salary] | [department-highest-salary.sql] | _O(n^2)_ | _O(n)_ | Medium | [Duplicate Emails] | [duplicate-emails.sql] | _O(n^2)_ | _O(n)_ | Easy | [Employees Earning More Than Their Managers] | [employees-earning-more-than-their-managers.sql] | _O(n^2)_ | _O(1)_ | Easy | [Nth Highest Salary] | [nth-highest-salary.sql] | _O(n^2)_ | _O(n)_ | Medium | @@ -730,6 +731,8 @@ Problem | Solution | Time | Space | Difficul [consecutive-numbers.sql]:https://github.com/kamyu104/LeetCode/blob/master/MySQL/consecutive-numbers.sql [Customers Who Never Order]:https://oj.leetcode.com/problems/customers-who-never-order/ [customers-who-never-order.sql]:https://github.com/kamyu104/LeetCode/blob/master/MySQL/customers-who-never-order.sql +[Department Highest Salary]:https://oj.leetcode.com/problems/department-highest-salary/ +[department-highest-salary.sql]:https://github.com/kamyu104/LeetCode/blob/master/MySQL/department-highest-salary.sql [Duplicate Emails]:https://oj.leetcode.com/problems/duplicate-emails/ [duplicate-emails.sql]:https://github.com/kamyu104/LeetCode/blob/master/MySQL/duplicate-emails.sql [Employees Earning More Than Their Managers]:https://oj.leetcode.com/problems/employees-earning-more-than-their-managers/ From fa62b597a6db1f38d67ff07e68f1625a2ed99533 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 21 Jan 2015 22:58:20 +0800 Subject: [PATCH 014/345] Rename department-highest-salary to department-highest-salary.sql --- .../{department-highest-salary => department-highest-salary.sql} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename MySQL/{department-highest-salary => department-highest-salary.sql} (100%) diff --git a/MySQL/department-highest-salary b/MySQL/department-highest-salary.sql similarity index 100% rename from MySQL/department-highest-salary rename to MySQL/department-highest-salary.sql From 34052c1ffd070951e71c09ad8a6bed3ed3903e70 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 21 Jan 2015 22:59:54 +0800 Subject: [PATCH 015/345] Update department-highest-salary.sql --- MySQL/department-highest-salary.sql | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MySQL/department-highest-salary.sql b/MySQL/department-highest-salary.sql index 1c5670253..69c88f734 100644 --- a/MySQL/department-highest-salary.sql +++ b/MySQL/department-highest-salary.sql @@ -31,7 +31,7 @@ # Write your MySQL query statement below SELECT d.Department AS Department, e.Name AS Employee, d.Salary AS Salary FROM (SELECT Department.Id AS DepartmentId, Department.Name AS Department, emp.Salary AS Salary - FROM Department JOIN (SELECT DepartmentId, MAX(Salary) AS Salary FROM Employee GROUP BY Employee.DepartmentId) emp + FROM Department JOIN (SELECT DepartmentId, MAX(Salary) AS Salary FROM Employee GROUP BY DepartmentId) emp ON Department.Id = emp.DepartmentId) d JOIN Employee e ON e.DepartmentId = d.DepartmentId and e.Salary = d.Salary From f29dca95c593bcfd229bf618da20de1f6050c58b Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 22 Jan 2015 00:21:22 +0800 Subject: [PATCH 016/345] Update single-number-ii.py --- Python/single-number-ii.py | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/Python/single-number-ii.py b/Python/single-number-ii.py index e725ccf8a..a9fe759e6 100644 --- a/Python/single-number-ii.py +++ b/Python/single-number-ii.py @@ -8,6 +8,15 @@ # class Solution: + # @param A, a list of integer + # @return an integer + def singleNumber(self, A): + one, two, carry = 0, 0, 0 + for x in A: + one, two = (~x & one) | (x & ~one & ~two), (~x & two) | (x & one) + return one + +class Solution2: # @param A, a list of integer # @return an integer def singleNumber(self, A): @@ -21,4 +30,4 @@ def singleNumber(self, A): return one if __name__ == "__main__": - print Solution().singleNumber([1, 1, 1, 2, 2, 2, 3]) \ No newline at end of file + print Solution().singleNumber([1, 1, 1, 2, 2, 2, 3]) From 413554178979ef2b9da521896550da8dcbdfc687 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 22 Jan 2015 22:00:23 +0800 Subject: [PATCH 017/345] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 323a2a7fd..676d6f50b 100644 --- a/README.md +++ b/README.md @@ -273,7 +273,7 @@ Problem | Solution | Time | Space | Difficul [Longest Substring with At Most Two Distinct Characters]| [longest-substring-with-at-most-two-distinct-characters.py] | _O(n^2)_ | _O(1)_ | Hard | [Longest Substring Without Repeating Characters] | [longest-substring-without-repeating-characters.py] | _O(n)_ | _O(1)_ | Medium | [Max Points on a Line] | [max-points-on-a-line.py] | _O(n^2)_ | _O(n)_ | Hard | -[Minimum Window Substring] | [minimum-window-substring.py] | _O(n^2)_ | _O(n)_ | Hard | +[Minimum Window Substring] | [minimum-window-substring.py] | _O(n)_ | _O(k)_ | Hard | [Substring with Concatenation of All Words] | [substring-with-concatenation-of-all-words.py] | _O(m * n * k)_ | _O(n * k)_ | Hard | [Two Sum] | [two-sum.py] | _O(n)_ | _O(n)_ | Medium | [Two Sum III - Data structure design] | [two-sum-iii-data-structure-design.py] | _O(n)_ | _O(n)_ | Easy | From ee9bc351caa2b52519485fb1093a0d37a610c975 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 22 Jan 2015 22:15:24 +0800 Subject: [PATCH 018/345] Update minimum-window-substring.py --- Python/minimum-window-substring.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/minimum-window-substring.py b/Python/minimum-window-substring.py index 37a001902..03c52ff64 100644 --- a/Python/minimum-window-substring.py +++ b/Python/minimum-window-substring.py @@ -1,5 +1,5 @@ # Time: O(n) -# Space: O(1) +# Space: O(k), k is # # Given a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity O(n). # From 2cbf418847ef9943e032d33e74fb591e74eab89d Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 22 Jan 2015 22:16:28 +0800 Subject: [PATCH 019/345] Update minimum-window-substring.py --- Python/minimum-window-substring.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/minimum-window-substring.py b/Python/minimum-window-substring.py index 03c52ff64..687402e30 100644 --- a/Python/minimum-window-substring.py +++ b/Python/minimum-window-substring.py @@ -1,5 +1,5 @@ # Time: O(n) -# Space: O(k), k is +# Space: O(k), k is the number of different characters # # Given a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity O(n). # From 9dbf6e76b8b0ee555d0a43325bb1aa7991ac1eca Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 25 Jan 2015 00:22:59 +0800 Subject: [PATCH 020/345] Create department-top-three-salaries.sql --- MySQL/department-top-three-salaries.sql | 41 +++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 MySQL/department-top-three-salaries.sql diff --git a/MySQL/department-top-three-salaries.sql b/MySQL/department-top-three-salaries.sql new file mode 100644 index 000000000..337c3ff81 --- /dev/null +++ b/MySQL/department-top-three-salaries.sql @@ -0,0 +1,41 @@ +# Time: O(n^2) +# Space: O(n) +# +# The Employee table holds all employees. Every employee has an Id, and there is also a column for the department Id. +# +# +----+-------+--------+--------------+ +# | Id | Name | Salary | DepartmentId | +# +----+-------+--------+--------------+ +# | 1 | Joe | 70000 | 1 | +# | 2 | Henry | 80000 | 2 | +# | 3 | Sam | 60000 | 2 | +# | 4 | Max | 90000 | 1 | +# | 5 | Janet | 69000 | 1 | +# | 6 | Randy | 85000 | 1 | +# +----+-------+--------+--------------+ +# The Department table holds all departments of the company. +# +# +----+----------+ +# | Id | Name | +# +----+----------+ +# | 1 | IT | +# | 2 | Sales | +# +----+----------+ +# Write a SQL query to find employees who earn the top three salaries in each of the department. For the above tables, your SQL query should return the following rows. +# +# +------------+----------+--------+ +# | Department | Employee | Salary | +# +------------+----------+--------+ +# | IT | Max | 90000 | +# | IT | Randy | 85000 | +# | IT | Joe | 70000 | +# | Sales | Henry | 80000 | +# | Sales | Sam | 60000 | +# +------------+----------+--------+ + +# Write your MySQL query statement below +SELECT D.Name AS Department, E.Name AS Employee, E.Salary AS Salary +FROM Employee E INNER JOIN Department D ON E.DepartmentId = D.Id +WHERE (SELECT COUNT(DISTINCT(Salary)) FROM Employee + WHERE DepartmentId = E.DepartmentId AND Salary > E.Salary) < 3 +ORDER by E.DepartmentId, E.Salary DESC; From 41b185d9251660903c68396ea27d2fe61834d1c6 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 25 Jan 2015 00:26:25 +0800 Subject: [PATCH 021/345] Update README.md --- README.md | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 676d6f50b..a30f18cdc 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ LeetCode ======== -Up to date (2015-01-21), there are total `184` problems on [LeetCode Online Judge](https://oj.leetcode.com/). +Up to date (2015-01-24), there are total `185` problems on [LeetCode Online Judge](https://oj.leetcode.com/). The number of problems is increasing recently. -Here is the classification of all `184` problems. +Here is the classification of all `185` problems. I'll keep updating for full summary and better solutions. Stay tuned for updates. --- @@ -719,6 +719,7 @@ Problem | Solution | Time | Space | Difficul [Consecutive Numbers] | [consecutive-numbers.sql] | _O(n)_ | _O(n)_ | Medium | [Customers Who Never Order] | [customers-who-never-order.sql] | _O(n^2)_ | _O(1)_ | Easy | [Department Highest Salary] | [department-highest-salary.sql] | _O(n^2)_ | _O(n)_ | Medium | +[Department Top Three Salaries] | [department-top-three-salaries.sql] | _O(n^2)_ | _O(n)_ | Hard | [Duplicate Emails] | [duplicate-emails.sql] | _O(n^2)_ | _O(n)_ | Easy | [Employees Earning More Than Their Managers] | [employees-earning-more-than-their-managers.sql] | _O(n^2)_ | _O(1)_ | Easy | [Nth Highest Salary] | [nth-highest-salary.sql] | _O(n^2)_ | _O(n)_ | Medium | @@ -733,6 +734,8 @@ Problem | Solution | Time | Space | Difficul [customers-who-never-order.sql]:https://github.com/kamyu104/LeetCode/blob/master/MySQL/customers-who-never-order.sql [Department Highest Salary]:https://oj.leetcode.com/problems/department-highest-salary/ [department-highest-salary.sql]:https://github.com/kamyu104/LeetCode/blob/master/MySQL/department-highest-salary.sql +[Department Top Three Salaries]:https://oj.leetcode.com/problems/department-top-three-salaries/ +[department-top-three-salaries.sql]:https://github.com/kamyu104/LeetCode/blob/master/MySQL/department-top-three-salaries.sql [Duplicate Emails]:https://oj.leetcode.com/problems/duplicate-emails/ [duplicate-emails.sql]:https://github.com/kamyu104/LeetCode/blob/master/MySQL/duplicate-emails.sql [Employees Earning More Than Their Managers]:https://oj.leetcode.com/problems/employees-earning-more-than-their-managers/ From 7d880f9e79e690078dbbed8283ddd6a83ce6db91 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 29 Jan 2015 11:42:36 +0800 Subject: [PATCH 022/345] Update wildcard-matching.py --- Python/wildcard-matching.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/Python/wildcard-matching.py b/Python/wildcard-matching.py index ebd9f1c49..cf2d464b8 100644 --- a/Python/wildcard-matching.py +++ b/Python/wildcard-matching.py @@ -48,7 +48,9 @@ def isMatch(self, s, p): return p_ptr == len(p) -# dp +# dp with rolling window +# Time: O(m * n) +# Space: O(m + n) class Solution2: # @return a boolean def isMatch(self, s, p): @@ -120,4 +122,4 @@ def isMatch(self, s, p): print Solution().isMatch("aa", "a*") print Solution().isMatch("aa", "?*") print Solution().isMatch("ab", "?*") - print Solution().isMatch("aab", "c*a*b") \ No newline at end of file + print Solution().isMatch("aab", "c*a*b") From 282f51f19ebec2d10b85a417c8fa34987d1e2dc8 Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Fri, 30 Jan 2015 00:25:39 +0800 Subject: [PATCH 023/345] fix solution3 bug --- Python/regular-expression-matching.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/regular-expression-matching.py b/Python/regular-expression-matching.py index f6c6d2746..5c6b31a3e 100644 --- a/Python/regular-expression-matching.py +++ b/Python/regular-expression-matching.py @@ -74,7 +74,7 @@ def isMatch(self, s, p): return len(s) == 0 if len(p) == 1 or p[1] != '*': - if len(s) == 0 or (p[0] == s[0] or p[0] == '.'): + if len(s) > 0 and (p[0] == s[0] or p[0] == '.'): return self.isMatch(s[1:], p[1:]) else: return False From b349f841bdbb8cf6ae3722128c93d433c77ea72a Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 30 Jan 2015 00:26:25 +0800 Subject: [PATCH 024/345] Update regular-expression-matching.py --- Python/regular-expression-matching.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/regular-expression-matching.py b/Python/regular-expression-matching.py index 5c6b31a3e..28ff51e67 100644 --- a/Python/regular-expression-matching.py +++ b/Python/regular-expression-matching.py @@ -74,7 +74,7 @@ def isMatch(self, s, p): return len(s) == 0 if len(p) == 1 or p[1] != '*': - if len(s) > 0 and (p[0] == s[0] or p[0] == '.'): + if len(s) > 0 and (p[0] == s[0] or p[0] == '.'): return self.isMatch(s[1:], p[1:]) else: return False From 25867bf77aeb6c5f8f4eddc6eab92aa7a2bad54f Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Fri, 30 Jan 2015 01:04:21 +0800 Subject: [PATCH 025/345] add extended solution --- Python/single-number-ii.py | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/Python/single-number-ii.py b/Python/single-number-ii.py index a9fe759e6..0e97ce970 100644 --- a/Python/single-number-ii.py +++ b/Python/single-number-ii.py @@ -11,7 +11,7 @@ class Solution: # @param A, a list of integer # @return an integer def singleNumber(self, A): - one, two, carry = 0, 0, 0 + one, two = 0, 0 for x in A: one, two = (~x & one) | (x & ~one & ~two), (~x & two) | (x & one) return one @@ -29,5 +29,16 @@ def singleNumber(self, A): two &= ~carry return one +# every element appears 4 times except for one with 2 times +class SolutionEX: + # @param A, a list of integer + # @return an integer + # [1, 1, 1, 1, 2, 2, 2, 2, 3, 3] + def singleNumber(self, A): + one, two, three = 0, 0, 0 + for x in A: + one, two, three = (~x & one) | (x & ~one & ~two & ~three), (~x & two) | (x & one), (~x & three) | (x & two) + return two + if __name__ == "__main__": print Solution().singleNumber([1, 1, 1, 2, 2, 2, 3]) From a84d9dbac6704320b5f52c52271d8791d7d0dfa0 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 2 Feb 2015 01:24:08 +0800 Subject: [PATCH 026/345] Update word-ladder.py --- Python/word-ladder.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/word-ladder.py b/Python/word-ladder.py index 8ed2f6c97..c8aebed3d 100644 --- a/Python/word-ladder.py +++ b/Python/word-ladder.py @@ -1,5 +1,5 @@ -# Time: O((25n)^n) -# Space: O((25n)^n) +# Time: O(nd), n is length of string, d is size of dictionary +# Space: O(d) # # Given two words (start and end), and a dictionary, find the length of shortest transformation sequence from start to end, such that: # From fe953af8f1c08efb804f3cde02c58bcc3f2b605a Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 2 Feb 2015 01:27:23 +0800 Subject: [PATCH 027/345] Update word-ladder-ii.py --- Python/word-ladder-ii.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/word-ladder-ii.py b/Python/word-ladder-ii.py index 501fd94fa..2838f1da5 100644 --- a/Python/word-ladder-ii.py +++ b/Python/word-ladder-ii.py @@ -1,5 +1,5 @@ -# Time: O((25n)^n) -# Space: O((25n)^n) +# Time: O(n * d), n is length of string, d is size of dictionary +# Space: O(d) # # Given two words (start and end), and a dictionary, find all shortest transformation sequence(s) from start to end, such that: # From 0d8cb9da1242bf9aa918d16c0f0f3a6d5cdba91d Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 2 Feb 2015 01:27:45 +0800 Subject: [PATCH 028/345] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index a30f18cdc..54689951b 100644 --- a/README.md +++ b/README.md @@ -539,7 +539,7 @@ Problem | Solution | Time | Space | Difficul [Clone Graph]| [clone-graph.py] | _O(n)_ | _O(n)_ | Medium | [Populating Next Right Pointers in Each Node II]|[populating-next-right-pointers-in-each-node-ii.py]| _O(n)_ | _O(1)_ | Hard | [Surrounded Regions]|[surrounded-regions.py]| _O(m * n)_ | _O(m + n)_ | Medium | -[Word Ladder] |[word-ladder.py] | _O((25n)^n)_ | _O((25n)^n)_ | Medium | +[Word Ladder] |[word-ladder.py] | _O(n * d)_ | _O(d)_ | Medium | [Binary Tree Level Order Traversal]:https://oj.leetcode.com/problems/binary-tree-level-order-traversal/ [binary-tree-level-order-traversal.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/binary-tree-level-order-traversal.py @@ -671,7 +671,7 @@ Problem | Solution | Time | Space | Difficul ##Backtracking Problem | Solution | Time | Space | Difficulty | Notes --------------- | --------------- | --------------- | --------------- | -------------- | ----- -[Word Ladder II] |[word-ladder-ii.py] | _O((25n)^n)_ | _O((25n)^n)_ | Hard | +[Word Ladder II] |[word-ladder-ii.py] | _O(n * d)_ | _O(d)_ | Hard | [Word Ladder II]:https://oj.leetcode.com/problems/word-ladder-ii/ [word-ladder-ii.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/word-ladder-ii.py From 08be9fdf8a962b30192aabc58babd03a0a83eb6d Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 2 Feb 2015 01:28:08 +0800 Subject: [PATCH 029/345] Update word-ladder.py --- Python/word-ladder.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/word-ladder.py b/Python/word-ladder.py index c8aebed3d..17cdb9a77 100644 --- a/Python/word-ladder.py +++ b/Python/word-ladder.py @@ -1,4 +1,4 @@ -# Time: O(nd), n is length of string, d is size of dictionary +# Time: O(n * d), n is length of string, d is size of dictionary # Space: O(d) # # Given two words (start and end), and a dictionary, find the length of shortest transformation sequence from start to end, such that: From d5b052b849bde7a38d4a46edb4f3d0bc769dd4a0 Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Tue, 3 Feb 2015 22:05:40 +0800 Subject: [PATCH 030/345] update --- Python/reverse-words-in-a-string-ii.py | 34 ++++++++++++++++++++++++++ README.md | 7 ++++-- 2 files changed, 39 insertions(+), 2 deletions(-) create mode 100644 Python/reverse-words-in-a-string-ii.py diff --git a/Python/reverse-words-in-a-string-ii.py b/Python/reverse-words-in-a-string-ii.py new file mode 100644 index 000000000..09bd7f87b --- /dev/null +++ b/Python/reverse-words-in-a-string-ii.py @@ -0,0 +1,34 @@ +# Time: O(n) +# Space:O(1) +# +# Given an input string, reverse the string word by word. A word is defined as a sequence of non-space characters. +# +# The input string does not contain leading or trailing spaces and the words are always separated by a single space. +# +# For example, +# Given s = "the sky is blue", +# return "blue is sky the". +# +# Could you do it in-place without allocating extra space? +# + +class Solution: + # @param s, a list of 1 length strings, e.g., s = ['h','e','l','l','o'] + # @return nothing + def reverseWords(self, s): + self.reverse(s, 0, len(s)) + + i = 0 + for j in xrange(len(s) + 1): + if j == len(s) or s[j] == ' ': + self.reverse(s, i, j) + i = j + 1 + + def reverse(self, s, begin, end): + for i in xrange((end - begin) / 2): + s[begin + i], s[end - 1 - i] = s[end - 1 - i], s[begin + i] + +if __name__ == '__main__': + s = ['h','e','l','l','o', ' ', 'w', 'o', 'r', 'l', 'd'] + Solution().reverseWords(s) + print s \ No newline at end of file diff --git a/README.md b/README.md index 54689951b..0bb89d4e1 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ LeetCode ======== -Up to date (2015-01-24), there are total `185` problems on [LeetCode Online Judge](https://oj.leetcode.com/). +Up to date (2015-02-03), there are total `186` problems on [LeetCode Online Judge](https://oj.leetcode.com/). The number of problems is increasing recently. -Here is the classification of all `185` problems. +Here is the classification of all `186` problems. I'll keep updating for full summary and better solutions. Stay tuned for updates. --- @@ -136,6 +136,7 @@ Problem | Solution | Time | Space | Difficul [Multiply Strings] | [multiply-strings.py] | _O(m * n)_ | _O(m + n)_ | Medium | [One Edit Distance] | [one-edit-distance.py] | _O(m + n)_ | _O(1)_ | Medium | [Reverse Words in a String] | [reverse-words-in-a-string.py] | _O(n)_ | _O(n)_ | Medium | +[Reverse Words in a String II] | [reverse-words-in-a-string-ii.py] | _O(n)_ | _O(1)_ | Medium | [String to Integer (atoi)] | [string-to-integer-atoi.py] | _O(n)_ | _O(1)_ | Easy | [Text Justification] | [text-justification.py] | _O(n)_ | _O(1)_ | Hard | [Valid Palindrome] | [valid-palindrome.py] | _O(n)_ | _O(1)_ | Easy | @@ -164,6 +165,8 @@ Problem | Solution | Time | Space | Difficul [one-edit-distance.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/one-edit-distance.py [Reverse Words in a String]:https://oj.leetcode.com/problems/reverse-words-in-a-string/ [reverse-words-in-a-string.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/reverse-words-in-a-string.py +[Reverse Words in a String II]:https://oj.leetcode.com/problems/reverse-words-in-a-string-ii/ +[reverse-words-in-a-string-ii.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/reverse-words-in-a-string-ii.py [String to Integer (atoi)]:https://oj.leetcode.com/problems/string-to-integer-atoi/ [string-to-integer-atoi.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/string-to-integer-atoi.py [Text Justification]:https://oj.leetcode.com/problems/text-justification/ From 6281b0043dffb06d4c3150bd7105e6e8ccf37a76 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 3 Feb 2015 22:56:50 +0800 Subject: [PATCH 031/345] Update first-missing-positive.py --- Python/first-missing-positive.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/first-missing-positive.py b/Python/first-missing-positive.py index b2fa788f0..134baa714 100644 --- a/Python/first-missing-positive.py +++ b/Python/first-missing-positive.py @@ -1,5 +1,5 @@ # Time: O(n) -# Space: O(n) +# Space: O(1) # # Given an unsorted integer array, find the first missing positive integer. # @@ -28,4 +28,4 @@ def firstMissingPositive(self, A): if __name__ == "__main__": print Solution().firstMissingPositive([1,2,0]) - print Solution().firstMissingPositive([3,4,-1,1]) \ No newline at end of file + print Solution().firstMissingPositive([3,4,-1,1]) From 8fbe5a62645c21bc6ff0e40861506166d4fd3a96 Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Wed, 4 Feb 2015 00:38:52 +0800 Subject: [PATCH 032/345] update --- Python/best-time-to-buy-and-sell-stock-iii.py | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/Python/best-time-to-buy-and-sell-stock-iii.py b/Python/best-time-to-buy-and-sell-stock-iii.py index 7b08da290..d55083324 100644 --- a/Python/best-time-to-buy-and-sell-stock-iii.py +++ b/Python/best-time-to-buy-and-sell-stock-iii.py @@ -13,6 +13,29 @@ # class Solution: + # @param prices, a list of integer + # @return an integer + def maxProfit(self, prices): + return self.maxKPairsProfit(prices, 2) + + def maxKPairsProfit(self, prices, k): + k_sum = [float("-inf") for _ in xrange(2 * k)] + for i in xrange(len(prices)): + pre_k_sum = list(k_sum) + j, sign = 0, -1 + while j < len(k_sum) and j <= i: + diff = sign * prices[i] + + if j > 0: + diff += pre_k_sum[j - 1] + + k_sum[j] = max(diff, pre_k_sum[j]) + j += 1 + sign *= -1 + + return k_sum[-1] + +class Solution2: # @param prices, a list of integer # @return an integer def maxProfit(self, prices): From 0195c8a9ea680e18a568391dc1a53721074b6195 Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Wed, 4 Feb 2015 00:52:57 +0800 Subject: [PATCH 033/345] update --- Python/best-time-to-buy-and-sell-stock-iii.py | 22 +++++++++++-------- 1 file changed, 13 insertions(+), 9 deletions(-) diff --git a/Python/best-time-to-buy-and-sell-stock-iii.py b/Python/best-time-to-buy-and-sell-stock-iii.py index d55083324..c7c3504b9 100644 --- a/Python/best-time-to-buy-and-sell-stock-iii.py +++ b/Python/best-time-to-buy-and-sell-stock-iii.py @@ -12,29 +12,33 @@ # (ie, you must sell the stock before you buy again). # +# Time: O(k^2 * n) +# Space: O(k) class Solution: # @param prices, a list of integer # @return an integer def maxProfit(self, prices): - return self.maxKPairsProfit(prices, 2) - + result = 0 + for k in xrange(3): + result = max(result, self.maxKPairsProfit(prices, k)) + return result + def maxKPairsProfit(self, prices, k): + if k == 0 or len(prices) < 2: + return 0 + k_sum = [float("-inf") for _ in xrange(2 * k)] for i in xrange(len(prices)): - pre_k_sum = list(k_sum) - j, sign = 0, -1 + j, sign, pre_k_sum = 0, -1, list(k_sum) while j < len(k_sum) and j <= i: diff = sign * prices[i] - if j > 0: diff += pre_k_sum[j - 1] - k_sum[j] = max(diff, pre_k_sum[j]) - j += 1 - sign *= -1 + j, sign = j + 1, sign * -1 return k_sum[-1] - + class Solution2: # @param prices, a list of integer # @return an integer From 01d27c7b9578dc399bcb9a33255e5c43b6f4b903 Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Wed, 4 Feb 2015 01:01:02 +0800 Subject: [PATCH 034/345] update --- Python/best-time-to-buy-and-sell-stock-iii.py | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/Python/best-time-to-buy-and-sell-stock-iii.py b/Python/best-time-to-buy-and-sell-stock-iii.py index c7c3504b9..441daa3a2 100644 --- a/Python/best-time-to-buy-and-sell-stock-iii.py +++ b/Python/best-time-to-buy-and-sell-stock-iii.py @@ -12,9 +12,24 @@ # (ie, you must sell the stock before you buy again). # +# Time: O(n) +# Space: O(1) +class Solution: + # @param prices, a list of integer + # @return an integer + def maxProfit(self, prices): + hold1, hold2 = float("-inf"), float("-inf") + release1, release2 = 0, 0 + for i in prices: + release2 = max(release2, hold2 + i) + hold2 = max(hold2, release1 - i) + release1 = max(release1, hold1 + i) + hold1 = max(hold1, -i); + return release2 + # Time: O(k^2 * n) # Space: O(k) -class Solution: +class Solution2: # @param prices, a list of integer # @return an integer def maxProfit(self, prices): @@ -39,7 +54,7 @@ def maxKPairsProfit(self, prices, k): return k_sum[-1] -class Solution2: +class Solution3: # @param prices, a list of integer # @return an integer def maxProfit(self, prices): From ef31d85742060d53c08be9c6fc70942128b8dc85 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 4 Feb 2015 10:57:24 +0800 Subject: [PATCH 035/345] Update best-time-to-buy-and-sell-stock-iii.py --- Python/best-time-to-buy-and-sell-stock-iii.py | 29 +++++++++++++------ 1 file changed, 20 insertions(+), 9 deletions(-) diff --git a/Python/best-time-to-buy-and-sell-stock-iii.py b/Python/best-time-to-buy-and-sell-stock-iii.py index 441daa3a2..3cb8d7b86 100644 --- a/Python/best-time-to-buy-and-sell-stock-iii.py +++ b/Python/best-time-to-buy-and-sell-stock-iii.py @@ -29,20 +29,31 @@ def maxProfit(self, prices): # Time: O(k^2 * n) # Space: O(k) -class Solution2: +class Solution: # @param prices, a list of integer # @return an integer def maxProfit(self, prices): - result = 0 - for k in xrange(3): - result = max(result, self.maxKPairsProfit(prices, k)) - return result + return self.maxAtMostKPairsProfit(prices, 2) - def maxKPairsProfit(self, prices, k): - if k == 0 or len(prices) < 2: - return 0 + def maxAtMostKPairsProfit(self, prices, k): + k_sum = [float("-inf") for _ in xrange(2 * k)] + for i in xrange(1, len(k_sum), 2): + k_sum[i] = 0 + for i in xrange(len(prices)): + j, sign, pre_k_sum = 0, -1, list(k_sum) + while j < len(k_sum): + diff = sign * prices[i] + if j > 0: + diff += pre_k_sum[j - 1] + k_sum[j] = max(diff, pre_k_sum[j]) + j, sign = j + 1, sign * -1 + + return k_sum[-1] + + def maxExatclyKPairsProfit(self, prices, k): k_sum = [float("-inf") for _ in xrange(2 * k)] + for i in xrange(len(prices)): j, sign, pre_k_sum = 0, -1, list(k_sum) while j < len(k_sum) and j <= i: @@ -53,7 +64,7 @@ def maxKPairsProfit(self, prices, k): j, sign = j + 1, sign * -1 return k_sum[-1] - + class Solution3: # @param prices, a list of integer # @return an integer From cef98212de4da499abb696433193fb4a515e4e2c Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 4 Feb 2015 11:00:09 +0800 Subject: [PATCH 036/345] Update best-time-to-buy-and-sell-stock-iii.py --- Python/best-time-to-buy-and-sell-stock-iii.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/best-time-to-buy-and-sell-stock-iii.py b/Python/best-time-to-buy-and-sell-stock-iii.py index 3cb8d7b86..7ba442fad 100644 --- a/Python/best-time-to-buy-and-sell-stock-iii.py +++ b/Python/best-time-to-buy-and-sell-stock-iii.py @@ -29,7 +29,7 @@ def maxProfit(self, prices): # Time: O(k^2 * n) # Space: O(k) -class Solution: +class Solution2: # @param prices, a list of integer # @return an integer def maxProfit(self, prices): From 74b08301a1b39adf60b6688c1d3602defa2e071c Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 4 Feb 2015 21:22:44 +0800 Subject: [PATCH 037/345] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 0bb89d4e1..4ecd3760d 100644 --- a/README.md +++ b/README.md @@ -280,7 +280,7 @@ Problem | Solution | Time | Space | Difficul [Substring with Concatenation of All Words] | [substring-with-concatenation-of-all-words.py] | _O(m * n * k)_ | _O(n * k)_ | Hard | [Two Sum] | [two-sum.py] | _O(n)_ | _O(n)_ | Medium | [Two Sum III - Data structure design] | [two-sum-iii-data-structure-design.py] | _O(n)_ | _O(n)_ | Easy | -[Valid Sudoku] | [valid-sudoku.py] | _O(n)_ | _O(n)_ | Easy | +[Valid Sudoku] | [valid-sudoku.py] | _O(n^2)_ | _O(n)_ | Easy | [4 Sum]: https://oj.leetcode.com/problems/4sum/ [4sum.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/4sum.py From ab5cf0020f12317e065e18104908413079721aa1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 4 Feb 2015 23:53:00 +0800 Subject: [PATCH 038/345] Update letter-combinations-of-a-phone-number.py --- Python/letter-combinations-of-a-phone-number.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/letter-combinations-of-a-phone-number.py b/Python/letter-combinations-of-a-phone-number.py index a818ce42b..a4bbfebc8 100644 --- a/Python/letter-combinations-of-a-phone-number.py +++ b/Python/letter-combinations-of-a-phone-number.py @@ -1,4 +1,4 @@ -# Time: O(4^n) +# Time: O(n * 4^n) # Space: O(1) # # Given a digit string, return all possible letter combinations that the number could represent. @@ -29,7 +29,7 @@ def letterCombinations(self, digits): return result -# Time: O(4^n) +# Time: O(n * 4^n) # Space: O(n) # Recursive Solution class Solution2: From 0a8379ee61a49d19d2fba4c0cc61b01ff0da8d3d Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 4 Feb 2015 23:53:58 +0800 Subject: [PATCH 039/345] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 4ecd3760d..bf94b13ce 100644 --- a/README.md +++ b/README.md @@ -420,7 +420,7 @@ Problem | Solution | Time | Space | Difficul ##Brute Force Search Problem | Solution | Time | Space | Difficulty | Notes --------------- | --------------- | --------------- | --------------- | -------------- | ----- -[Letter Combinations of a Phone Number]| [letter-combinations-of-a-phone-number.py] | _O(4^n)_ | _O(1)_ | Medium | +[Letter Combinations of a Phone Number]| [letter-combinations-of-a-phone-number.py] | _O(n * 4^n)_ | _O(1)_ | Medium | [Permutations]| [permutations.py] | _O(n!)_ | _O(n)_ | Medium | [Permutations II]| [permutations-ii.py] | _O(n!)_ | _O(n)_ | Hard | [Subsets] | [subsets.py] | _O(2^n)_ | _O(1)_ | Medium | From 452da7d7b6916950349b802e42f284a09596cb94 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 4 Feb 2015 23:54:53 +0800 Subject: [PATCH 040/345] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index bf94b13ce..a917dbbed 100644 --- a/README.md +++ b/README.md @@ -420,7 +420,7 @@ Problem | Solution | Time | Space | Difficul ##Brute Force Search Problem | Solution | Time | Space | Difficulty | Notes --------------- | --------------- | --------------- | --------------- | -------------- | ----- -[Letter Combinations of a Phone Number]| [letter-combinations-of-a-phone-number.py] | _O(n * 4^n)_ | _O(1)_ | Medium | +[Letter Combinations of a Phone Number]| [letter-combinations-of-a-phone-number.py] | _O(n * 4^n)_ | _O(n)_ | Medium | [Permutations]| [permutations.py] | _O(n!)_ | _O(n)_ | Medium | [Permutations II]| [permutations-ii.py] | _O(n!)_ | _O(n)_ | Hard | [Subsets] | [subsets.py] | _O(2^n)_ | _O(1)_ | Medium | From 91926d22a5eeea5c4ece96292e1eb37c96e03949 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 4 Feb 2015 23:55:09 +0800 Subject: [PATCH 041/345] Update letter-combinations-of-a-phone-number.py --- Python/letter-combinations-of-a-phone-number.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/letter-combinations-of-a-phone-number.py b/Python/letter-combinations-of-a-phone-number.py index a4bbfebc8..c3d5e7779 100644 --- a/Python/letter-combinations-of-a-phone-number.py +++ b/Python/letter-combinations-of-a-phone-number.py @@ -1,5 +1,5 @@ # Time: O(n * 4^n) -# Space: O(1) +# Space: O(n) # # Given a digit string, return all possible letter combinations that the number could represent. # From 41f76710b33dbc4b76e98a9cc97d923ed619e6e7 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 5 Feb 2015 00:01:26 +0800 Subject: [PATCH 042/345] Update count-and-say.py --- Python/count-and-say.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/count-and-say.py b/Python/count-and-say.py index 5b55c29a4..325fdc8e5 100644 --- a/Python/count-and-say.py +++ b/Python/count-and-say.py @@ -1,5 +1,5 @@ -# Time: O(n^2) -# Space: O(n) +# Time: O(n * 2^n) +# Space: O(2^n) # # The count-and-say sequence is the sequence of integers beginning as follows: # 1, 11, 21, 1211, 111221, ... From 2caf3e52ea41eb9bfb6e09aea5dab23a4693ba71 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 5 Feb 2015 00:02:28 +0800 Subject: [PATCH 043/345] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index a917dbbed..4931a5c02 100644 --- a/README.md +++ b/README.md @@ -128,7 +128,7 @@ Problem | Solution | Time | Space | Difficul [Add Binary] | [add-binary.py] | _O(n)_ | _O(1)_ | Easy | [Anagrams] | [anagrams.py] | _O(n)_ | _O(n)_ | Medium | [Compare Version Numbers] | [compare-version-numbers.py] | _O(n)_ | _O(1)_ | Easy | -[Count and Say] | [count-and-say.py]| _O(n^2)_ | _O(n)_ | Easy | +[Count and Say] | [count-and-say.py]| _O(n * 2^n)_ | _O(2^n)_ | Easy | [Implement strStr()] | [implement-strstr.py] | _O(n + m)_ | _O(m)_ | Easy | `KMP Algorithm` [Length of Last Word] | [length-of-last-word.py] | _O(n)_ | _O(1)_ | Easy | [Longest Common Prefix] | [longest-common-prefix.py] | _O(n1 + n2 + ...)_ | _O(1)_ | Easy | From eeecfe5a6624a9a349e679dd2cea1a3942abff72 Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Thu, 5 Feb 2015 01:51:17 +0800 Subject: [PATCH 044/345] update --- Python/text-justification.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Python/text-justification.py b/Python/text-justification.py index c1a18d1e9..5ccab0e51 100644 --- a/Python/text-justification.py +++ b/Python/text-justification.py @@ -48,18 +48,18 @@ def fullJustify(self, words, L): # count space number spaceCount = L - size if i - begin - 1 > 0 and i < len(words): - everyCount = spaceCount / (i - begin - 1) + everyCount = spaceCount / (i - begin - 1) + 1 spaceCount %= i - begin - 1 else: - everyCount = 0 - + everyCount = 1 + # add space j = begin while j < i: if j == begin: s = words[j] else: - s += ' ' * (everyCount + 1) + s += ' ' * everyCount if spaceCount > 0 and i < len(words): s += ' ' spaceCount -= 1 From 302bc80c3db717627217eea3d669bf790026fb17 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 6 Feb 2015 17:13:51 +0800 Subject: [PATCH 045/345] Create repeated-dna-sequences --- Python/repeated-dna-sequences | 39 +++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 Python/repeated-dna-sequences diff --git a/Python/repeated-dna-sequences b/Python/repeated-dna-sequences new file mode 100644 index 000000000..f93278c7f --- /dev/null +++ b/Python/repeated-dna-sequences @@ -0,0 +1,39 @@ +# Time: O(n) +# Space: O(n) +# +# All DNA is composed of a series of nucleotides abbreviated as A, C, G, and T, +# for example: "ACGAATTCCG". When studying DNA, it is sometimes useful to identify repeated sequences within the DNA. +# +# Write a function to find all the 10-letter-long sequences (substrings) that occur more than once in a DNA molecule. +# +# For example, +# +# Given s = "AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT", +# +# Return: +# ["AAAAACCCCC", "CCCCCAAAAA"]. +# + +class Solution: + # @param s, a string + # @return a list of strings + def findRepeatedDnaSequences(self, s): + hash_table = {} + rolling_hash = 0 + res = [] + + for i in xrange(len(s)): + rolling_hash = rolling_hash << 3 & 0x3fffffff | ord(s[i]) & 7 + if hash_table.get(rolling_hash, None) != None: + if hash_table[rolling_hash]: + res.append(s[i - 9: i + 1]) + hash_table[rolling_hash] = False + else: + hash_table[rolling_hash] = True + + return res + +if __name__ == "__main__": + print Solution().findRepeatedDnaSequences("AAAAAAAAAA") + print Solution().findRepeatedDnaSequences("") + print Solution().findRepeatedDnaSequences("AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT") From 5184f59eec1cde1a140141fb7618de97f7c81580 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 6 Feb 2015 17:17:01 +0800 Subject: [PATCH 046/345] Update README.md --- README.md | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 4931a5c02..11d38db85 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ LeetCode ======== -Up to date (2015-02-03), there are total `186` problems on [LeetCode Online Judge](https://oj.leetcode.com/). +Up to date (2015-02-06), there are total `187` problems on [LeetCode Online Judge](https://oj.leetcode.com/). The number of problems is increasing recently. -Here is the classification of all `186` problems. +Here is the classification of all `187` problems. I'll keep updating for full summary and better solutions. Stay tuned for updates. --- @@ -277,6 +277,7 @@ Problem | Solution | Time | Space | Difficul [Longest Substring Without Repeating Characters] | [longest-substring-without-repeating-characters.py] | _O(n)_ | _O(1)_ | Medium | [Max Points on a Line] | [max-points-on-a-line.py] | _O(n^2)_ | _O(n)_ | Hard | [Minimum Window Substring] | [minimum-window-substring.py] | _O(n)_ | _O(k)_ | Hard | +[Repeated DNA Sequences] | [repeated-dna-sequences.py] | _O(n)_ | _O(n)_ | Medium | [Substring with Concatenation of All Words] | [substring-with-concatenation-of-all-words.py] | _O(m * n * k)_ | _O(n * k)_ | Hard | [Two Sum] | [two-sum.py] | _O(n)_ | _O(n)_ | Medium | [Two Sum III - Data structure design] | [two-sum-iii-data-structure-design.py] | _O(n)_ | _O(n)_ | Easy | @@ -292,6 +293,8 @@ Problem | Solution | Time | Space | Difficul [max-points-on-a-line.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/max-points-on-a-line.py [Minimum Window Substring]:https://oj.leetcode.com/problems/minimum-window-substring/ [minimum-window-substring.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/minimum-window-substring.py +[Repeated DNA Sequences]:https://oj.leetcode.com/problems/repeated-dna-sequences/ +[repeated-dna-sequences.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/repeated-dna-sequences.py [Substring with Concatenation of All Words]:https://oj.leetcode.com/problems/substring-with-concatenation-of-all-words/ [substring-with-concatenation-of-all-words.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/substring-with-concatenation-of-all-words.py [Two Sum]:https://oj.leetcode.com/problems/two-sum/ From 8844caa3d8022e94f181252ee2c3d44d58f30673 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 6 Feb 2015 17:18:52 +0800 Subject: [PATCH 047/345] Update and rename repeated-dna-sequences to repeated-dna-sequences.py --- ...ated-dna-sequences => repeated-dna-sequences.py} | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) rename Python/{repeated-dna-sequences => repeated-dna-sequences.py} (81%) diff --git a/Python/repeated-dna-sequences b/Python/repeated-dna-sequences.py similarity index 81% rename from Python/repeated-dna-sequences rename to Python/repeated-dna-sequences.py index f93278c7f..79c6fc5c3 100644 --- a/Python/repeated-dna-sequences +++ b/Python/repeated-dna-sequences.py @@ -18,19 +18,18 @@ class Solution: # @param s, a string # @return a list of strings def findRepeatedDnaSequences(self, s): - hash_table = {} + dict = {} rolling_hash = 0 res = [] for i in xrange(len(s)): rolling_hash = rolling_hash << 3 & 0x3fffffff | ord(s[i]) & 7 - if hash_table.get(rolling_hash, None) != None: - if hash_table[rolling_hash]: - res.append(s[i - 9: i + 1]) - hash_table[rolling_hash] = False + if dict.get(rolling_hash, None) is None: + dict[rolling_hash] = True else: - hash_table[rolling_hash] = True - + if dict[rolling_hash]: + res.append(s[i - 9: i + 1]) + dict[rolling_hash] = False return res if __name__ == "__main__": From 286405821b497a03d83b41d64fd36a85b7d400b4 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 6 Feb 2015 17:20:02 +0800 Subject: [PATCH 048/345] Update repeated-dna-sequences.py --- Python/repeated-dna-sequences.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/repeated-dna-sequences.py b/Python/repeated-dna-sequences.py index 79c6fc5c3..b3b926173 100644 --- a/Python/repeated-dna-sequences.py +++ b/Python/repeated-dna-sequences.py @@ -24,7 +24,7 @@ def findRepeatedDnaSequences(self, s): for i in xrange(len(s)): rolling_hash = rolling_hash << 3 & 0x3fffffff | ord(s[i]) & 7 - if dict.get(rolling_hash, None) is None: + if dict.get(rolling_hash) is None: dict[rolling_hash] = True else: if dict[rolling_hash]: From 799f29e5ea99f409191cc1ca9a1891140eafc02d Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 7 Feb 2015 00:04:57 +0800 Subject: [PATCH 049/345] Update binary-tree-inorder-traversal.py --- Python/binary-tree-inorder-traversal.py | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/Python/binary-tree-inorder-traversal.py b/Python/binary-tree-inorder-traversal.py index 5972f569b..5f68d1e39 100644 --- a/Python/binary-tree-inorder-traversal.py +++ b/Python/binary-tree-inorder-traversal.py @@ -72,9 +72,25 @@ def inorderTraversal(self, root): current = parent.right return result +class Solution3: + # @param root, a tree node + # @return a list of integers + def inorderTraversal(self, root): + result, stack, current, last_traversed = [], [], root, None + while stack or current: + if current: + stack.append(current) + current = current.left + else: + current = stack[-1] + stack.pop() + result.append(current.val) + current = current.right + return result + if __name__ == "__main__": root = TreeNode(1) root.right = TreeNode(2) root.right.left = TreeNode(3) result = Solution().inorderTraversal(root) - print result \ No newline at end of file + print result From 8b17249f535770e0341e2388c3894954cec1741c Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 7 Feb 2015 00:05:28 +0800 Subject: [PATCH 050/345] Update binary-tree-preorder-traversal.py --- Python/binary-tree-preorder-traversal.py | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/Python/binary-tree-preorder-traversal.py b/Python/binary-tree-preorder-traversal.py index 2cf998dcd..51146c7bd 100644 --- a/Python/binary-tree-preorder-traversal.py +++ b/Python/binary-tree-preorder-traversal.py @@ -70,9 +70,25 @@ def preorderTraversal(self, root): current = parent.right return result +class Solution3: + # @param root, a tree node + # @return a list of integers + def preorderTraversal(self, root): + result, stack, current, last_traversed = [], [], root, None + while stack or current: + if current: + result.append(current.val) + stack.append(current) + current = current.left + else: + current = stack[-1] + stack.pop() + current = current.right + return result + if __name__ == "__main__": root = TreeNode(1) root.right = TreeNode(2) root.right.left = TreeNode(3) result = Solution().preorderTraversal(root) - print result \ No newline at end of file + print result From dc0a2d2fc524d30351b55cacf20b1a6c31f062ac Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 8 Feb 2015 17:00:16 +0800 Subject: [PATCH 051/345] Update populating-next-right-pointers-in-each-node.py --- ...lating-next-right-pointers-in-each-node.py | 21 +++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) diff --git a/Python/populating-next-right-pointers-in-each-node.py b/Python/populating-next-right-pointers-in-each-node.py index 5223f28fb..79b50a7d8 100644 --- a/Python/populating-next-right-pointers-in-each-node.py +++ b/Python/populating-next-right-pointers-in-each-node.py @@ -1,5 +1,5 @@ # Time: O(n) -# Space: O(logn) +# Space: O(1) # # Given a binary tree # @@ -45,6 +45,23 @@ def __repr__(self): return "{} -> {}".format(self.val, repr(self.next)) class Solution: + # @param root, a tree node + # @return nothing + def connect(self, root): + head = root + while head: + prev, cur, next_head = None, head, None + while cur and cur.left: + cur.left.next = cur.right + if cur.next: + cur.right.next = cur.next.left + cur = cur.next + head = head.left + +# Time: O(n) +# Space: O(logn) +# recusion +class Solution2: # @param root, a tree node # @return nothing def connect(self, root): @@ -64,4 +81,4 @@ def connect(self, root): print root print root.left print root.left.left - \ No newline at end of file + From a93725ff75dade6a30546324cdab7f6f547e82e4 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 8 Feb 2015 17:01:03 +0800 Subject: [PATCH 052/345] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 11d38db85..ea9ea9ec4 100644 --- a/README.md +++ b/README.md @@ -455,7 +455,7 @@ Problem | Solution | Time | Space | Difficul [Flatten Binary Tree to Linked List]|[flatten-binary-tree-to-linked-list.py]| _O(n)_ | _O(logn)_ | Medium | [Maximum Depth of Binary Tree]|[maximum-depth-of-binary-tree.py]| _O(n)_ | _O(logn)_ | Easy | [Minimum Depth of Binary Tree]|[minimum-depth-of-binary-tree.py]| _O(n)_ | _O(logn)_ | Easy | -[Populating Next Right Pointers in Each Node]|[populating-next-right-pointers-in-each-node.py]| _O(n)_ | _O(logn)_ | Medium | +[Populating Next Right Pointers in Each Node]|[populating-next-right-pointers-in-each-node.py]| _O(n)_ | _O(1)_ | Medium | [Same Tree] |[same-tree.py] | _O(n)_ | _O(logn)_ | Easy | [Sum Root to Leaf Numbers] | [sum-root-to-leaf-numbers.py] | _O(n)_ | _O(logn)_ | Medium | [Unique Binary Search Trees II] | [unique-binary-search-trees-ii.py] | _O(4^n / n^(3/2)_ | _O(4^n / n^(3/2)_ | Medium | From 93d3af8baff4c122d9f46fecffdb97d362e065cb Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 9 Feb 2015 00:41:48 +0800 Subject: [PATCH 053/345] Update README.md --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index ea9ea9ec4..2cfb8a562 100644 --- a/README.md +++ b/README.md @@ -126,7 +126,6 @@ Problem | Solution | Time | Space | Difficul Problem | Solution | Time | Space | Difficulty | Notes --------------- | --------------- | --------------- | --------------- | -------------- | ----- [Add Binary] | [add-binary.py] | _O(n)_ | _O(1)_ | Easy | -[Anagrams] | [anagrams.py] | _O(n)_ | _O(n)_ | Medium | [Compare Version Numbers] | [compare-version-numbers.py] | _O(n)_ | _O(1)_ | Easy | [Count and Say] | [count-and-say.py]| _O(n * 2^n)_ | _O(2^n)_ | Easy | [Implement strStr()] | [implement-strstr.py] | _O(n + m)_ | _O(m)_ | Easy | `KMP Algorithm` @@ -144,8 +143,6 @@ Problem | Solution | Time | Space | Difficul [Add Binary]:https://oj.leetcode.com/problems/add-binary/ [add-binary.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/add-binary.py -[Anagrams]:https://oj.leetcode.com/problems/anagrams/ -[anagrams.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/anagrams.py [Count and Say]:https://oj.leetcode.com/problems/count-and-say/ [count-and-say.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/count-and-say.py [Compare Version Numbers]:https://oj.leetcode.com/problems/compare-version-numbers/ @@ -273,6 +270,7 @@ Problem | Solution | Time | Space | Difficul Problem | Solution | Time | Space | Difficulty | Notes --------------- | --------------- | --------------- | --------------- | -------------- | ----- [4 Sum] |[4sum.py] | _O(n^2)_ ~ _O(n^4)_ | _O(n^2)_ | Medium | +[Anagrams] | [anagrams.py] | _O(n)_ | _O(n)_ | Medium | [Longest Substring with At Most Two Distinct Characters]| [longest-substring-with-at-most-two-distinct-characters.py] | _O(n^2)_ | _O(1)_ | Hard | [Longest Substring Without Repeating Characters] | [longest-substring-without-repeating-characters.py] | _O(n)_ | _O(1)_ | Medium | [Max Points on a Line] | [max-points-on-a-line.py] | _O(n^2)_ | _O(n)_ | Hard | @@ -285,6 +283,8 @@ Problem | Solution | Time | Space | Difficul [4 Sum]: https://oj.leetcode.com/problems/4sum/ [4sum.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/4sum.py +[Anagrams]:https://oj.leetcode.com/problems/anagrams/ +[anagrams.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/anagrams.py [Longest Substring with At Most Two Distinct Characters]:https://oj.leetcode.com/problems/longest-substring-with-at-most-two-distinct-characters/ [longest-substring-with-at-most-two-distinct-characters.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/longest-substring-with-at-most-two-distinct-characters.py [Longest Substring Without Repeating Characters]:https://oj.leetcode.com/problems/longest-substring-without-repeating-characters/ From a5e814f51e611c12fe23d73e9b1ed0b23a9302ca Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 10 Feb 2015 00:16:57 +0800 Subject: [PATCH 054/345] Update merge-intervals.py --- Python/merge-intervals.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/merge-intervals.py b/Python/merge-intervals.py index 49641bb7d..436bbd5d3 100644 --- a/Python/merge-intervals.py +++ b/Python/merge-intervals.py @@ -1,4 +1,4 @@ -# Time: O(n^2) +# Time: O(nlogn) # Space: O(1) # # Given a collection of intervals, merge all overlapping intervals. From 79719297a394ba3e0fe3038fc04be5d2b45d2105 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 10 Feb 2015 00:17:32 +0800 Subject: [PATCH 055/345] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 2cfb8a562..e375f0f0e 100644 --- a/README.md +++ b/README.md @@ -368,7 +368,7 @@ Problem | Solution | Time | Space | Difficul [Insertion Sort List]|[insertion-sort-list.py] | _O(n^2)_ | _O(1)_ | Medium | [Largest Number] | [largest-number.py] | _O(n^2)_ | _O(n)_ | Medium | [Maximum Gap] | [maximum-gap.py]| _O(n)_ | _O(n)_ | Hard | Tricky -[Merge Intervals]| [merge-intervals.py] | _O(n^2)_ | _O(1)_ | Hard | +[Merge Intervals]| [merge-intervals.py] | _O(nlogn)_ | _O(1)_ | Hard | [Merge Sorted Array]| [merge-sorted-array.py] | _O(n)_ | _O(1)_ | Easy | [Merge Two Sorted Lists]| [merge-two-sorted-lists.py] | _O(n)_ | _O(1)_ | Easy | [Sort Colors] | [sort-colors.py] | _O(n)_ | _O(1)_ | Medium | From 566a0f27d8f2cc10a81ce4f2a1ac2f01529cc9e8 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 10 Feb 2015 01:42:53 +0800 Subject: [PATCH 056/345] Update sort-list.py --- Python/sort-list.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/sort-list.py b/Python/sort-list.py index bd56db074..5427a88bd 100644 --- a/Python/sort-list.py +++ b/Python/sort-list.py @@ -1,5 +1,5 @@ # Time: O(nlogn) -# Space: O(1) +# Space: O(logn) for stack call # # Sort a linked list in O(n log n) time using constant space complexity. # @@ -53,4 +53,4 @@ def mergeTwoLists(self, l1, l2): head.next = ListNode(4) head.next.next = ListNode(1) head.next.next.next= ListNode(2) - print Solution().sortList(head) \ No newline at end of file + print Solution().sortList(head) From 57ae6e9464729b27886fd510a683530effa5791a Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 10 Feb 2015 01:43:25 +0800 Subject: [PATCH 057/345] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index e375f0f0e..5b7338dfb 100644 --- a/README.md +++ b/README.md @@ -372,7 +372,7 @@ Problem | Solution | Time | Space | Difficul [Merge Sorted Array]| [merge-sorted-array.py] | _O(n)_ | _O(1)_ | Easy | [Merge Two Sorted Lists]| [merge-two-sorted-lists.py] | _O(n)_ | _O(1)_ | Easy | [Sort Colors] | [sort-colors.py] | _O(n)_ | _O(1)_ | Medium | -[Sort List] | [sort-list.py] | _O(nlogn)_ | _O(1)_ | Medium | +[Sort List] | [sort-list.py] | _O(nlogn)_ | _O(logn)_ | Medium | [Insert Interval]:https://oj.leetcode.com/problems/insert-interval/ [insert-interval.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/insert-interval.py From 40980253f3ea8dd03e8f14d25f9098c8c910d989 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 10 Feb 2015 03:01:43 +0800 Subject: [PATCH 058/345] Update validate-binary-search-tree.py --- Python/validate-binary-search-tree.py | 35 +++++++++++++++++++++++++-- 1 file changed, 33 insertions(+), 2 deletions(-) diff --git a/Python/validate-binary-search-tree.py b/Python/validate-binary-search-tree.py index 9af8db35d..7e329c4cf 100644 --- a/Python/validate-binary-search-tree.py +++ b/Python/validate-binary-search-tree.py @@ -1,5 +1,5 @@ # Time: O(n) -# Space: O(logn) +# Space: O(1) # # Given a binary tree, determine if it is a valid binary search tree (BST). # @@ -17,7 +17,38 @@ def __init__(self, x): self.left = None self.right = None +# Morris Traversal Solution class Solution: + # @param root, a tree node + # @return a list of integers + def isValidBST(self, root): + prev, cur = None, root + while cur: + if cur.left is None: + if prev and prev.val >= cur.val: + return False + prev = cur + cur = cur.right + else: + node = cur.left + while node.right and node.right != cur: + node = node.right + + if node.right is None: + node.right = cur + cur = cur.left + else: + if prev and prev.val >= cur.val: + return False + node.right = None + prev = cur + cur = cur.right + + return True + +# Time: O(n) +# Space: O(logn) +class Solution2: # @param root, a tree node # @return a boolean def isValidBST(self, root): @@ -35,4 +66,4 @@ def isValidBSTRecu(self, root, low, high): root = TreeNode(2) root.left = TreeNode(1) root.right = TreeNode(3) - print Solution().isValidBST(root) \ No newline at end of file + print Solution().isValidBST(root) From a4472ba47d30156400c969857a4258cd2cd47dc0 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 10 Feb 2015 03:02:12 +0800 Subject: [PATCH 059/345] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 5b7338dfb..a35067773 100644 --- a/README.md +++ b/README.md @@ -459,7 +459,7 @@ Problem | Solution | Time | Space | Difficul [Same Tree] |[same-tree.py] | _O(n)_ | _O(logn)_ | Easy | [Sum Root to Leaf Numbers] | [sum-root-to-leaf-numbers.py] | _O(n)_ | _O(logn)_ | Medium | [Unique Binary Search Trees II] | [unique-binary-search-trees-ii.py] | _O(4^n / n^(3/2)_ | _O(4^n / n^(3/2)_ | Medium | -[Validate Binary Search Tree]|[validate-binary-search-tree.py]| _O(n)_ | _O(logn)_ | Medium | +[Validate Binary Search Tree]|[validate-binary-search-tree.py]| _O(n)_ | _O(1)_ | Medium | [Balanced Binary Tree]:https://oj.leetcode.com/problems/balanced-binary-tree/ [balanced-binary-tree.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/balanced-binary-tree.py @@ -489,7 +489,7 @@ Problem | Solution | Time | Space | Difficul [sum-root-to-leaf-numbers.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/sum-root-to-leaf-numbers.py [Unique Binary Search Trees II]:https://oj.leetcode.com/problems/unique-binary-search-trees-ii/ [unique-binary-search-trees-ii.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/unique-binary-search-trees-ii.py -[Validate Binary Search Tree]:https://oj.leetcode.com/problems/validate-binary-search-tree.py/ +[Validate Binary Search Tree]:https://oj.leetcode.com/problems/validate-binary-search-tree/ [validate-binary-search-tree.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/validate-binary-search-tree.py From 8510bf50dedb8e76ba386be1ef9996ecf66f8fd4 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 11 Feb 2015 00:10:30 +0800 Subject: [PATCH 060/345] Update flatten-binary-tree-to-linked-list.py --- Python/flatten-binary-tree-to-linked-list.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/flatten-binary-tree-to-linked-list.py b/Python/flatten-binary-tree-to-linked-list.py index 8d081290a..579f2e319 100644 --- a/Python/flatten-binary-tree-to-linked-list.py +++ b/Python/flatten-binary-tree-to-linked-list.py @@ -1,5 +1,5 @@ # Time: O(n) -# Space: O(logn) +# Space: O(h), h is height of binary tree # # Given a binary tree, flatten it to a linked list in-place. # @@ -74,4 +74,4 @@ def flatten(self, root): print result.right.right.val print result.right.right.right.val print result.right.right.right.right.val - print result.right.right.right.right.right.val \ No newline at end of file + print result.right.right.right.right.right.val From d492f17edc1e7d464242942f2c786337d8687304 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 11 Feb 2015 00:11:31 +0800 Subject: [PATCH 061/345] Update binary-tree-maximum-path-sum.py --- Python/binary-tree-maximum-path-sum.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/binary-tree-maximum-path-sum.py b/Python/binary-tree-maximum-path-sum.py index 2c2705aa1..d71f6eeba 100644 --- a/Python/binary-tree-maximum-path-sum.py +++ b/Python/binary-tree-maximum-path-sum.py @@ -1,5 +1,5 @@ # Time: O(n) -# Space: O(logn) +# Space: O(h), h is height of binary tree # # Given a binary tree, find the maximum path sum. # From 372807aa57a6695f3cf835076bcb5e598cc56a41 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 11 Feb 2015 00:12:44 +0800 Subject: [PATCH 062/345] Update binary-search-tree-iterator.py --- Python/binary-search-tree-iterator.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/binary-search-tree-iterator.py b/Python/binary-search-tree-iterator.py index c198f87ec..428c8d4a3 100644 --- a/Python/binary-search-tree-iterator.py +++ b/Python/binary-search-tree-iterator.py @@ -1,5 +1,5 @@ # Time: O(1) -# Space: O(logn) +# Space: O(h), h is height of binary tree # # Implement an iterator over a binary search tree (BST). # Your iterator will be initialized with the root node of a BST. @@ -47,4 +47,4 @@ def next(self): i, v = BSTIterator(root), [] while i.hasNext(): v.append(i.next()) - print v \ No newline at end of file + print v From a0657c7fb32001f1726e11fbbebb56b14a493065 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 11 Feb 2015 00:13:29 +0800 Subject: [PATCH 063/345] Update symmetric-tree.py --- Python/symmetric-tree.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/symmetric-tree.py b/Python/symmetric-tree.py index 6b2a1c991..709864217 100644 --- a/Python/symmetric-tree.py +++ b/Python/symmetric-tree.py @@ -1,5 +1,5 @@ # Time: O(n) -# Space: O(logn) +# Space: O(h), h is height of binary tree # Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center). # # For example, this binary tree is symmetric: @@ -77,4 +77,4 @@ def isSymmetricRecu(self, left, right): root.left.left, root.right.right = TreeNode(3), TreeNode(3) root.left.right, root.right.left = TreeNode(4), TreeNode(4) print Solution().isSymmetric(root) - \ No newline at end of file + From 29f8dadfd5684e33b7a8689410e89557c27b38f7 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 11 Feb 2015 00:14:55 +0800 Subject: [PATCH 064/345] Update balanced-binary-tree.py --- Python/balanced-binary-tree.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/balanced-binary-tree.py b/Python/balanced-binary-tree.py index 532657698..fbf1326ab 100644 --- a/Python/balanced-binary-tree.py +++ b/Python/balanced-binary-tree.py @@ -1,5 +1,5 @@ # Time: O(n) -# Space: O(logn) +# Space: O(h), h is height of binary tree # # Given a binary tree, determine if it is height-balanced. # From 827c6715f9dc468183cc0cd11260b02b7fe3c2c4 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 11 Feb 2015 00:15:15 +0800 Subject: [PATCH 065/345] Update convert-sorted-array-to-binary-search-tree.py --- Python/convert-sorted-array-to-binary-search-tree.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/convert-sorted-array-to-binary-search-tree.py b/Python/convert-sorted-array-to-binary-search-tree.py index 946a2a163..2d0635d83 100644 --- a/Python/convert-sorted-array-to-binary-search-tree.py +++ b/Python/convert-sorted-array-to-binary-search-tree.py @@ -1,5 +1,5 @@ # Time: O(n) -# Space: O(logn) +# Space: O(h), h is height of binary tree # # Given an array where elements are sorted in ascending order, # convert it to a height balanced BST. From 303e940f629bcbae2f8cc4b8ed9d822f460e5109 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 11 Feb 2015 00:15:50 +0800 Subject: [PATCH 066/345] Update maximum-depth-of-binary-tree.py --- Python/maximum-depth-of-binary-tree.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/maximum-depth-of-binary-tree.py b/Python/maximum-depth-of-binary-tree.py index 14c258da1..016f720a6 100644 --- a/Python/maximum-depth-of-binary-tree.py +++ b/Python/maximum-depth-of-binary-tree.py @@ -1,5 +1,5 @@ # Time: O(n) -# Space: O(logn) +# Space: O(h), h is height of binary tree # # Given a binary tree, find its maximum depth. # @@ -27,4 +27,4 @@ def maxDepth(self, root): root.left = TreeNode(2) root.right = TreeNode(3) root.left.left = TreeNode(4) - print Solution().maxDepth(root) \ No newline at end of file + print Solution().maxDepth(root) From 9d6c6ffc9ffc9e00d2a1a849e76ffe6f29d346ea Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 11 Feb 2015 00:16:05 +0800 Subject: [PATCH 067/345] Update minimum-depth-of-binary-tree.py --- Python/minimum-depth-of-binary-tree.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/minimum-depth-of-binary-tree.py b/Python/minimum-depth-of-binary-tree.py index 5494074ec..2833dcaab 100644 --- a/Python/minimum-depth-of-binary-tree.py +++ b/Python/minimum-depth-of-binary-tree.py @@ -1,5 +1,5 @@ # Time: O(n) -# Space: O(logn) +# Space: O(h), h is height of binary tree # # Given a binary tree, find its minimum depth. # @@ -28,4 +28,4 @@ def minDepth(self, root): if __name__ == "__main__": root = TreeNode(1) root.left = TreeNode(2) - print Solution().minDepth(root) \ No newline at end of file + print Solution().minDepth(root) From 1f7514c0703cd9b9731b7cfddac2586dd53a1372 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 11 Feb 2015 00:16:20 +0800 Subject: [PATCH 068/345] Update same-tree.py --- Python/same-tree.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/same-tree.py b/Python/same-tree.py index b73333130..c7e799c94 100644 --- a/Python/same-tree.py +++ b/Python/same-tree.py @@ -1,5 +1,5 @@ # Time: O(n) -# Space: O(logn) +# Space: O(h), h is height of binary tree # # Given two binary trees, write a function to check if they are equal or not. # @@ -29,4 +29,4 @@ def isSameTree(self, p, q): if __name__ == "__main__": root1, root1.left, root1.right = TreeNode(1), TreeNode(2), TreeNode(3) root2, root2.left, root2.right = TreeNode(1), TreeNode(2), TreeNode(3) - print Solution().isSameTree(root1, root2) \ No newline at end of file + print Solution().isSameTree(root1, root2) From 39d0711fe60eac932499a75e7157a2f99e9a3d1c Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 11 Feb 2015 00:16:35 +0800 Subject: [PATCH 069/345] Update sum-root-to-leaf-numbers.py --- Python/sum-root-to-leaf-numbers.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/sum-root-to-leaf-numbers.py b/Python/sum-root-to-leaf-numbers.py index 763a9faba..775c1920b 100644 --- a/Python/sum-root-to-leaf-numbers.py +++ b/Python/sum-root-to-leaf-numbers.py @@ -1,5 +1,5 @@ # Time: O(n) -# Space: O(logn) +# Space: O(h), h is height of binary tree # # Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number. # @@ -44,4 +44,4 @@ def sumNumbersRecu(self, root, num): root = TreeNode(1) root.left = TreeNode(2) root.right = TreeNode(3) - print Solution().sumNumbers(root) \ No newline at end of file + print Solution().sumNumbers(root) From 6db2b8b13dfa530ace7dba518a50e871085d893a Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 11 Feb 2015 00:17:41 +0800 Subject: [PATCH 070/345] Update README.md --- README.md | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index a35067773..7d7db04b9 100644 --- a/README.md +++ b/README.md @@ -212,12 +212,12 @@ Problem | Solution | Time | Space | Difficul ##Stack Problem | Solution | Time | Space | Difficulty | Notes --------------- | --------------- | --------------- | --------------- | -------------- | ----- -[Binary Search Tree Iterator] | [binary-search-tree-iterator.py] | _O(1)_| _O(logn)_| Medium +[Binary Search Tree Iterator] | [binary-search-tree-iterator.py] | _O(1)_| _O(h)_| Medium [Evaluate Reverse Polish Notation]| [evaluate-reverse-polish-notation.py]| _O(n)_| _O(n)_| Medium | [Longest Valid Parentheses]| [longest-valid-parentheses.py] | _O(n)_ | _O(1)_ | Hard | [Min Stack] | [min-stack.py] | _O(n)_ | _O(1)_ | Easy | [Simplify Path]| [simplify-path.py] | _O(n)_ | _O(n)_ | Medium | -[Symmetric Tree]| [symmetric-tree.py] | _O(n)_ | _O(logn)_ | Easy | +[Symmetric Tree]| [symmetric-tree.py] | _O(n)_ | _O(h )_ | Easy | [Valid Parentheses]| [valid-parentheses.py] | _O(n)_ | _O(n)_ | Easy | [Binary Search Tree Iterator]:https://oj.leetcode.com/problems/binary-search-tree-iterator/ @@ -445,19 +445,19 @@ Problem | Solution | Time | Space | Difficul ##Divide and Conquer Problem | Solution | Time | Space | Difficulty | Notes --------------- | --------------- | --------------- | --------------- | -------------- | ----- -[Balanced Binary Tree] | [balanced-binary-tree.py] | _O(n)_| _O(logn)_| Easy | +[Balanced Binary Tree] | [balanced-binary-tree.py] | _O(n)_| _O(h)_ | Easy | [Binary Tree Maximum Path Sum]| [binary-tree-maximum-path-sum.py] | _O(n)_| _O(logn)_| Hard | [Binary Tree Upside Down] | [binary-tree-upside-down.py] | _O(n)_ | _O(1)_ | Medium | [Construct Binary Tree from Inorder and Postorder Traversal] | [construct-binary-tree-from-inorder-and-postorder-traversal.py] | _O(n)_ | _O(n)_ | Medium | [Construct Binary Tree from Preorder and Inorder Traversal] | [construct-binary-tree-from-preorder-and-inorder-traversal.py] | _O(n)_ | _O(n)_ | Medium [Convert Sorted Array to Binary Search Tree] | [convert-sorted-array-to-binary-search-tree.py] | _O(n)_ | _O(logn)_ | Medium | [Convert Sorted List to Binary Search Tree] | [convert-sorted-list-to-binary-search-tree.py] | _O(n)_ | _O(logn)_ | Medium | -[Flatten Binary Tree to Linked List]|[flatten-binary-tree-to-linked-list.py]| _O(n)_ | _O(logn)_ | Medium | -[Maximum Depth of Binary Tree]|[maximum-depth-of-binary-tree.py]| _O(n)_ | _O(logn)_ | Easy | -[Minimum Depth of Binary Tree]|[minimum-depth-of-binary-tree.py]| _O(n)_ | _O(logn)_ | Easy | +[Flatten Binary Tree to Linked List]|[flatten-binary-tree-to-linked-list.py]| _O(n)_ | _O(h)_ | Medium | +[Maximum Depth of Binary Tree]|[maximum-depth-of-binary-tree.py]| _O(n)_ | _O(h)_ | Easy | +[Minimum Depth of Binary Tree]|[minimum-depth-of-binary-tree.py]| _O(n)_ | _O(h)_ | Easy | [Populating Next Right Pointers in Each Node]|[populating-next-right-pointers-in-each-node.py]| _O(n)_ | _O(1)_ | Medium | [Same Tree] |[same-tree.py] | _O(n)_ | _O(logn)_ | Easy | -[Sum Root to Leaf Numbers] | [sum-root-to-leaf-numbers.py] | _O(n)_ | _O(logn)_ | Medium | +[Sum Root to Leaf Numbers] | [sum-root-to-leaf-numbers.py] | _O(n)_ | _O(h)_ | Medium | [Unique Binary Search Trees II] | [unique-binary-search-trees-ii.py] | _O(4^n / n^(3/2)_ | _O(4^n / n^(3/2)_ | Medium | [Validate Binary Search Tree]|[validate-binary-search-tree.py]| _O(n)_ | _O(1)_ | Medium | From b79ac662b71b31991bccf2eb30be96e7652b9640 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 11 Feb 2015 00:18:20 +0800 Subject: [PATCH 071/345] Update convert-sorted-array-to-binary-search-tree.py --- Python/convert-sorted-array-to-binary-search-tree.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/convert-sorted-array-to-binary-search-tree.py b/Python/convert-sorted-array-to-binary-search-tree.py index 2d0635d83..946a2a163 100644 --- a/Python/convert-sorted-array-to-binary-search-tree.py +++ b/Python/convert-sorted-array-to-binary-search-tree.py @@ -1,5 +1,5 @@ # Time: O(n) -# Space: O(h), h is height of binary tree +# Space: O(logn) # # Given an array where elements are sorted in ascending order, # convert it to a height balanced BST. From e2b8204c87c04e2a137e90bc78e211a9091fdcca Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 11 Feb 2015 00:19:07 +0800 Subject: [PATCH 072/345] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 7d7db04b9..7d2259b8f 100644 --- a/README.md +++ b/README.md @@ -456,7 +456,7 @@ Problem | Solution | Time | Space | Difficul [Maximum Depth of Binary Tree]|[maximum-depth-of-binary-tree.py]| _O(n)_ | _O(h)_ | Easy | [Minimum Depth of Binary Tree]|[minimum-depth-of-binary-tree.py]| _O(n)_ | _O(h)_ | Easy | [Populating Next Right Pointers in Each Node]|[populating-next-right-pointers-in-each-node.py]| _O(n)_ | _O(1)_ | Medium | -[Same Tree] |[same-tree.py] | _O(n)_ | _O(logn)_ | Easy | +[Same Tree] |[same-tree.py] | _O(n)_ | _O(h)_ | Easy | [Sum Root to Leaf Numbers] | [sum-root-to-leaf-numbers.py] | _O(n)_ | _O(h)_ | Medium | [Unique Binary Search Trees II] | [unique-binary-search-trees-ii.py] | _O(4^n / n^(3/2)_ | _O(4^n / n^(3/2)_ | Medium | [Validate Binary Search Tree]|[validate-binary-search-tree.py]| _O(n)_ | _O(1)_ | Medium | From 9fc931e9b31082d3ae3b5f874dbfa8d0391bda1e Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 11 Feb 2015 00:20:12 +0800 Subject: [PATCH 073/345] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 7d2259b8f..725800682 100644 --- a/README.md +++ b/README.md @@ -217,7 +217,7 @@ Problem | Solution | Time | Space | Difficul [Longest Valid Parentheses]| [longest-valid-parentheses.py] | _O(n)_ | _O(1)_ | Hard | [Min Stack] | [min-stack.py] | _O(n)_ | _O(1)_ | Easy | [Simplify Path]| [simplify-path.py] | _O(n)_ | _O(n)_ | Medium | -[Symmetric Tree]| [symmetric-tree.py] | _O(n)_ | _O(h )_ | Easy | +[Symmetric Tree]| [symmetric-tree.py] | _O(n)_ | _O(h)_ | Easy | [Valid Parentheses]| [valid-parentheses.py] | _O(n)_ | _O(n)_ | Easy | [Binary Search Tree Iterator]:https://oj.leetcode.com/problems/binary-search-tree-iterator/ From f0363d91e49438391dd8d0a45463911d8a6141a1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 11 Feb 2015 00:22:03 +0800 Subject: [PATCH 074/345] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 725800682..42922fbf4 100644 --- a/README.md +++ b/README.md @@ -446,7 +446,7 @@ Problem | Solution | Time | Space | Difficul Problem | Solution | Time | Space | Difficulty | Notes --------------- | --------------- | --------------- | --------------- | -------------- | ----- [Balanced Binary Tree] | [balanced-binary-tree.py] | _O(n)_| _O(h)_ | Easy | -[Binary Tree Maximum Path Sum]| [binary-tree-maximum-path-sum.py] | _O(n)_| _O(logn)_| Hard | +[Binary Tree Maximum Path Sum]| [binary-tree-maximum-path-sum.py] | _O(n)_| _O(h)_| Hard | [Binary Tree Upside Down] | [binary-tree-upside-down.py] | _O(n)_ | _O(1)_ | Medium | [Construct Binary Tree from Inorder and Postorder Traversal] | [construct-binary-tree-from-inorder-and-postorder-traversal.py] | _O(n)_ | _O(n)_ | Medium | [Construct Binary Tree from Preorder and Inorder Traversal] | [construct-binary-tree-from-preorder-and-inorder-traversal.py] | _O(n)_ | _O(n)_ | Medium From 07327bd22032832ca33da6c2ea6477d55981fc4b Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 11 Feb 2015 00:23:16 +0800 Subject: [PATCH 075/345] Update path-sum.py --- Python/path-sum.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/path-sum.py b/Python/path-sum.py index 0f686ec7f..b24c951a1 100644 --- a/Python/path-sum.py +++ b/Python/path-sum.py @@ -1,5 +1,5 @@ # Time: O(n) -# Space: O(logn) +# Space: O(h), h is height of binary tree # # Given a binary tree and a sum, determine if the tree has a root-to-leaf path # such that adding up all the values along the path equals the given sum. @@ -42,4 +42,4 @@ def hasPathSum(self, root, sum): root.right = TreeNode(8) root.left.left = TreeNode(11) root.left.left.right = TreeNode(2) - print Solution().hasPathSum(root, 22) \ No newline at end of file + print Solution().hasPathSum(root, 22) From f8f6c8ab5eb6d84fd6460cd86e05f1d95ed8982e Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 11 Feb 2015 00:23:36 +0800 Subject: [PATCH 076/345] Update path-sum-ii.py --- Python/path-sum-ii.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/path-sum-ii.py b/Python/path-sum-ii.py index a6e835dcb..df35acde8 100644 --- a/Python/path-sum-ii.py +++ b/Python/path-sum-ii.py @@ -1,5 +1,5 @@ # Time: O(n) -# Space: O(logn) +# Space: O(h), h is height of binary tree # # Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum. # @@ -51,4 +51,4 @@ def pathSumRecu(self, result, cur, root, sum): if __name__ == "__main__": root = TreeNode(5) - print Solution().pathSum(root, 5) \ No newline at end of file + print Solution().pathSum(root, 5) From 500896c1bb9eca29a5432e8fe073b60745c40707 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 11 Feb 2015 00:24:05 +0800 Subject: [PATCH 077/345] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 42922fbf4..aca3ab489 100644 --- a/README.md +++ b/README.md @@ -574,8 +574,8 @@ Problem | Solution | Time | Space | Difficul [N-Queens] | [n-queens.py] | _O(n!)_ | _O(n)_ | Hard | [N-Queens-II] | [n-queens-ii.py] | _O(n!)_ | _O(n)_ | Hard | [Palindrome Partitioning] | [palindrome-partitioning.py] | _O(n^2)_ ~ _O(2^n)_ | _O(n^2)_ | Medium | -[Path Sum] | [path-sum.py] | _O(n)_ | _O(logn)_ | Easy | -[Path Sum II] | [path-sum-ii.py] | _O(n)_ | _O(logn)_ | Medium | +[Path Sum] | [path-sum.py] | _O(n)_ | _O(h)_ | Easy | +[Path Sum II] | [path-sum-ii.py] | _O(n)_ | _O(h)_ | Medium | [Restore IP Addresses] | [restore-ip-addresses.py] | _O(n^m)_ ~ _O(3^4)_ | _O(n * m)_ ~ _O(3 * 4)_ | Medium | [Sudoku Solver] | [sudoku-solver.py] | _O((9!)^9)_ | _O(1)_ | Hard | [Word Search] | [word-search.py] | _O(m * n * 3^p)_ | _O(m * n * p)_ | Medium | From 65a49f563243567653cf3e0c4b1a9d5ba30f5123 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 12 Feb 2015 01:35:47 +0800 Subject: [PATCH 078/345] Update subsets-ii.py --- Python/subsets-ii.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/subsets-ii.py b/Python/subsets-ii.py index a22bedb27..7690e96a8 100644 --- a/Python/subsets-ii.py +++ b/Python/subsets-ii.py @@ -1,4 +1,4 @@ -# Time: O(2^n) +# Time: O(n * 2^n) # Space: O(1) # # Given a collection of integers that might contain duplicates, S, return all possible subsets. @@ -54,4 +54,4 @@ def subsetsWithDupRecu(self, result, cur, S): self.subsetsWithDupRecu(result, cur + [S[0]], S[1:]) if __name__ == "__main__": - print Solution().subsetsWithDup([1, 2, 2]) \ No newline at end of file + print Solution().subsetsWithDup([1, 2, 2]) From ba0212c301353374ad016f210d96ee914998b736 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 12 Feb 2015 01:36:08 +0800 Subject: [PATCH 079/345] Update subsets.py --- Python/subsets.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/subsets.py b/Python/subsets.py index 5143a2d62..0d274aabf 100644 --- a/Python/subsets.py +++ b/Python/subsets.py @@ -1,4 +1,4 @@ -# Time: O(2^n) +# Time: O(n * 2^n) # Space: O(1) # # Given a set of distinct integers, S, return all possible subsets. @@ -52,4 +52,4 @@ def subsetsRecu(self, cur, S): return self.subsetsRecu(cur, S[1:]) + self.subsetsRecu(cur + [S[0]], S[1:]) if __name__ == "__main__": - print Solution().subsets([1, 2, 3]) \ No newline at end of file + print Solution().subsets([1, 2, 3]) From fec46131226db1549333d548c686c7bdb20dec4a Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 12 Feb 2015 01:36:42 +0800 Subject: [PATCH 080/345] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index aca3ab489..6092464c7 100644 --- a/README.md +++ b/README.md @@ -426,8 +426,8 @@ Problem | Solution | Time | Space | Difficul [Letter Combinations of a Phone Number]| [letter-combinations-of-a-phone-number.py] | _O(n * 4^n)_ | _O(n)_ | Medium | [Permutations]| [permutations.py] | _O(n!)_ | _O(n)_ | Medium | [Permutations II]| [permutations-ii.py] | _O(n!)_ | _O(n)_ | Hard | -[Subsets] | [subsets.py] | _O(2^n)_ | _O(1)_ | Medium | -[Subsets II] | [subsets-ii.py] | _O(2^n)_ | _O(1)_ | Medium | +[Subsets] | [subsets.py] | _O(n * 2^n)_ | _O(1)_ | Medium | +[Subsets II] | [subsets-ii.py] | _O(n * 2^n)_ | _O(1)_ | Medium | [Letter Combinations of a Phone Number]:https://oj.leetcode.com/problems/letter-combinations-of-a-phone-number/ [letter-combinations-of-a-phone-number.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/letter-combinations-of-a-phone-number.py From 09ad1158ca026cc2d8ea49c77879fc7b75c5e5f8 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 12 Feb 2015 01:42:22 +0800 Subject: [PATCH 081/345] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 6092464c7..52d4e211f 100644 --- a/README.md +++ b/README.md @@ -570,7 +570,7 @@ Problem | Solution | Time | Space | Difficul [Combination Sum]| [combination-sum.py] | _O(n^m)_ | _O(m)_ | Medium | [Combination Sum II]| [combination-sum-ii.py]| _O(n! / m!(n-m)!)_| _O(m)_ | Medium | [Combinations] | [combinations.py] | _O(n!)_ | _O(n)_ | Medium | -[Generate Parentheses]| [generate-parentheses.py]| _O(4^n / n^(3/2)_ | _O(n)_ | Medium | +[Generate Parentheses]| [generate-parentheses.py]| _O(4^n / n^(3/2))_ | _O(n)_ | Medium | [N-Queens] | [n-queens.py] | _O(n!)_ | _O(n)_ | Hard | [N-Queens-II] | [n-queens-ii.py] | _O(n!)_ | _O(n)_ | Hard | [Palindrome Partitioning] | [palindrome-partitioning.py] | _O(n^2)_ ~ _O(2^n)_ | _O(n^2)_ | Medium | From 036f65f07ed59d8301127f9e4237129e90c85109 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 15 Feb 2015 16:58:19 +0800 Subject: [PATCH 082/345] Update best-time-to-buy-and-sell-stock-iii.py --- Python/best-time-to-buy-and-sell-stock-iii.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Python/best-time-to-buy-and-sell-stock-iii.py b/Python/best-time-to-buy-and-sell-stock-iii.py index 7ba442fad..59c6c2081 100644 --- a/Python/best-time-to-buy-and-sell-stock-iii.py +++ b/Python/best-time-to-buy-and-sell-stock-iii.py @@ -64,7 +64,9 @@ def maxExatclyKPairsProfit(self, prices, k): j, sign = j + 1, sign * -1 return k_sum[-1] - + +# Time: O(n) +# Space: O(n) class Solution3: # @param prices, a list of integer # @return an integer From 5a16320b622f1be5925834544a767a80fb0fd6ac Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Mon, 16 Feb 2015 23:06:14 +0800 Subject: [PATCH 083/345] update --- Python/implement-strstr.py | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/Python/implement-strstr.py b/Python/implement-strstr.py index 543835dd4..9b7149b10 100644 --- a/Python/implement-strstr.py +++ b/Python/implement-strstr.py @@ -14,17 +14,17 @@ class Solution: # @param needle, a string # @return a string or None def strStr(self, haystack, needle): + if not needle: + return 0 + if len(haystack) < len(needle): - return None - - if len(needle) == 0: - return haystack + return -1 i = self.KMP(haystack, needle) if i > -1: - return haystack[i:] + return i else: - return None + return -1 def KMP(self, text, pattern): prefix = self.getPrefix(pattern) From 035f018dfc9ce0fcc32cbd10d753623833a2000b Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 16 Feb 2015 23:08:22 +0800 Subject: [PATCH 084/345] Update insert-interval.py --- Python/insert-interval.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Python/insert-interval.py b/Python/insert-interval.py index f108a7078..82e27eb9a 100644 --- a/Python/insert-interval.py +++ b/Python/insert-interval.py @@ -31,11 +31,11 @@ def insert(self, intervals, newInterval): return self.merge(intervals + [newInterval]) def merge(self, intervals): - if len(intervals) == 0: + if not intervals: return intervals intervals.sort(key = lambda x: x.start) result = [intervals[0]] - for i in range(1, len(intervals)): + for i in xrange(1, len(intervals)): prev, current = result[-1], intervals[i] if current.start <= prev.end: prev.end = max(prev.end, current.end) @@ -44,4 +44,4 @@ def merge(self, intervals): return result if __name__ == "__main__": - print Solution().insert([Interval(1, 2), Interval(3, 5), Interval(6, 7), Interval(8, 10), Interval(12, 16)], Interval(4, 9)) \ No newline at end of file + print Solution().insert([Interval(1, 2), Interval(3, 5), Interval(6, 7), Interval(8, 10), Interval(12, 16)], Interval(4, 9)) From 89d1f419f0d414cc4e62fc7264e07ab90c3af969 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 16 Feb 2015 23:10:12 +0800 Subject: [PATCH 085/345] Update largest-rectangle-in-histogram.py --- Python/largest-rectangle-in-histogram.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Python/largest-rectangle-in-histogram.py b/Python/largest-rectangle-in-histogram.py index 2313b011f..e3dea568b 100644 --- a/Python/largest-rectangle-in-histogram.py +++ b/Python/largest-rectangle-in-histogram.py @@ -16,12 +16,12 @@ class Solution: def largestRectangleArea(self, height): increasing, area, i = [], 0, 0 while i <= len(height): - if len(increasing) == 0 or (i < len(height) and height[i] > height[increasing[-1]]): + if not increasing or (i < len(height) and height[i] > height[increasing[-1]]): increasing.append(i) i += 1 else: last = increasing.pop() - if len(increasing) == 0: + if not increasing: area = max(area, height[last] * i) else: area = max(area, height[last] * (i - increasing[-1] - 1 )) @@ -30,4 +30,4 @@ def largestRectangleArea(self, height): if __name__ == "__main__": print Solution().largestRectangleArea([2, 0, 2]) print Solution().largestRectangleArea([2, 1, 5, 6, 2, 3]) - \ No newline at end of file + From 45b4cf15128e0b422a55b905ef936ca24f7cafe5 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 16 Feb 2015 23:11:29 +0800 Subject: [PATCH 086/345] Update longest-common-prefix.py --- Python/longest-common-prefix.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/longest-common-prefix.py b/Python/longest-common-prefix.py index 2ffa96cfb..5c39975ab 100644 --- a/Python/longest-common-prefix.py +++ b/Python/longest-common-prefix.py @@ -7,7 +7,7 @@ class Solution: # @return a string def longestCommonPrefix(self, strs): - if len(strs) == 0: + if not strs: return "" longest = strs[0] for string in strs[1:]: @@ -19,4 +19,4 @@ def longestCommonPrefix(self, strs): if __name__ == "__main__": print Solution().longestCommonPrefix(["hello", "heaven", "heavy"]) - \ No newline at end of file + From dcd822a6e9ceeb25f85b492fff049f673ceb2a6b Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 16 Feb 2015 23:13:46 +0800 Subject: [PATCH 087/345] Update longest-palindromic-substring.py --- Python/longest-palindromic-substring.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/longest-palindromic-substring.py b/Python/longest-palindromic-substring.py index e882d6bf6..79abaf5af 100644 --- a/Python/longest-palindromic-substring.py +++ b/Python/longest-palindromic-substring.py @@ -35,7 +35,7 @@ def longestPalindrome(self, s): return s[start : start + max_len] def preProcess(self, s): - if len(s) == 0: + if not s: return "^$" string = "^" for i in s: @@ -44,4 +44,4 @@ def preProcess(self, s): return string if __name__ == "__main__": - print Solution().longestPalindrome("abb") \ No newline at end of file + print Solution().longestPalindrome("abb") From c07a51d19e377fa3f276f8d0958cc814778d60f5 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 16 Feb 2015 23:18:16 +0800 Subject: [PATCH 088/345] Update longest-valid-parentheses.py --- Python/longest-valid-parentheses.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/longest-valid-parentheses.py b/Python/longest-valid-parentheses.py index 8d8b1647e..559ce3e30 100644 --- a/Python/longest-valid-parentheses.py +++ b/Python/longest-valid-parentheses.py @@ -49,11 +49,11 @@ def longestValidParentheses(self, s): for i in xrange(len(s)): if s[i] == '(': indices.append(i) - elif len(indices) == 0: + elif not indices: last = i else: indices.pop() - if len(indices) == 0: + if not indices: longest = max(longest, i - last) else: longest = max(longest, i - indices[-1]) From 81ef6529fa65e74bebf2f63b107a9707704c72e7 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 16 Feb 2015 23:19:47 +0800 Subject: [PATCH 089/345] Update maximal-rectangle.py --- Python/maximal-rectangle.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/maximal-rectangle.py b/Python/maximal-rectangle.py index 05a99c943..f667a4de2 100644 --- a/Python/maximal-rectangle.py +++ b/Python/maximal-rectangle.py @@ -9,7 +9,7 @@ class Solution: # @param matrix, a list of lists of 1 length string # @return an integer def maximalRectangle(self, matrix): - if len(matrix) == 0: + if not matrix: return 0 result = 0 From 21d3dd598687bb2ae66f937f8eea803f9a438d0f Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 16 Feb 2015 23:20:57 +0800 Subject: [PATCH 090/345] Update merge-intervals.py --- Python/merge-intervals.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/merge-intervals.py b/Python/merge-intervals.py index 436bbd5d3..f62b3f0a1 100644 --- a/Python/merge-intervals.py +++ b/Python/merge-intervals.py @@ -21,7 +21,7 @@ class Solution: # @param intervals, a list of Interval # @return a list of Interval def merge(self, intervals): - if len(intervals) == 0: + if not intervals: return intervals intervals.sort(key = lambda x: x.start) result = [intervals[0]] From 6d1fafd95eeb2762e012b7cd421ecf012d6d1019 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 16 Feb 2015 23:22:12 +0800 Subject: [PATCH 091/345] Update min-stack.py --- Python/min-stack.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/min-stack.py b/Python/min-stack.py index 4036555b5..12df16163 100644 --- a/Python/min-stack.py +++ b/Python/min-stack.py @@ -17,7 +17,7 @@ def __init__(self): # @param x, an integer # @return an integer def push(self, x): - if len(self.stack) == 0: + if not self.stack: self.stack.append(0) self.min = x else: @@ -80,4 +80,4 @@ def getMin(self): stack = MinStack() stack.push(-1) print [stack.top(), stack.getMin()] - \ No newline at end of file + From d0aa70a9225e587473747b7227adf1eebbce29a1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 16 Feb 2015 23:24:24 +0800 Subject: [PATCH 092/345] Update regular-expression-matching.py --- Python/regular-expression-matching.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/regular-expression-matching.py b/Python/regular-expression-matching.py index 28ff51e67..969a92981 100644 --- a/Python/regular-expression-matching.py +++ b/Python/regular-expression-matching.py @@ -70,8 +70,8 @@ def isMatch(self, s, p): class Solution3: # @return a boolean def isMatch(self, s, p): - if len(p) == 0: - return len(s) == 0 + if not p: + return not s if len(p) == 1 or p[1] != '*': if len(s) > 0 and (p[0] == s[0] or p[0] == '.'): From caf713d24e8ced505226a4d5bc2b867f47fac187 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 16 Feb 2015 23:25:21 +0800 Subject: [PATCH 093/345] Update remove-duplicates-from-sorted-array-ii.py --- Python/remove-duplicates-from-sorted-array-ii.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/remove-duplicates-from-sorted-array-ii.py b/Python/remove-duplicates-from-sorted-array-ii.py index 527416e7f..794b192ae 100644 --- a/Python/remove-duplicates-from-sorted-array-ii.py +++ b/Python/remove-duplicates-from-sorted-array-ii.py @@ -14,7 +14,7 @@ class Solution: # @param a list of integers # @return an integer def removeDuplicates(self, A): - if len(A) == 0: + if not A: return 0 last, i, same = 0, 1, False @@ -28,4 +28,4 @@ def removeDuplicates(self, A): return last + 1 if __name__ == "__main__": - print Solution().removeDuplicates([1, 1, 1, 2, 2, 3]) \ No newline at end of file + print Solution().removeDuplicates([1, 1, 1, 2, 2, 3]) From 9b54997ae5271b55e59cefffa0bc55db7b1129bc Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 16 Feb 2015 23:25:57 +0800 Subject: [PATCH 094/345] Update remove-duplicates-from-sorted-array.py --- Python/remove-duplicates-from-sorted-array.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/remove-duplicates-from-sorted-array.py b/Python/remove-duplicates-from-sorted-array.py index 473e645fc..7ea358680 100644 --- a/Python/remove-duplicates-from-sorted-array.py +++ b/Python/remove-duplicates-from-sorted-array.py @@ -15,7 +15,7 @@ class Solution: # @param a list of integers # @return an integer def removeDuplicates(self, A): - if len(A) == 0: + if not A: return 0 last, i = 0, 1 @@ -28,4 +28,4 @@ def removeDuplicates(self, A): return last + 1 if __name__ == "__main__": - print Solution().removeDuplicates([1, 1, 2]) \ No newline at end of file + print Solution().removeDuplicates([1, 1, 2]) From 6a363e57b7f52e12ec37f4c97eaf81159b8ae814 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 16 Feb 2015 23:26:40 +0800 Subject: [PATCH 095/345] Update scramble-string.py --- Python/scramble-string.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/scramble-string.py b/Python/scramble-string.py index f75325daf..5d7d4feeb 100644 --- a/Python/scramble-string.py +++ b/Python/scramble-string.py @@ -47,7 +47,7 @@ class Solution: def isScramble(self, s1, s2): if not s1 or not s2 or len(s1) != len(s2): return False - if len(s1) == 0: + if not s1: return True result = [[[False for j in xrange(len(s2))] for i in xrange(len(s1))] for n in xrange(len(s1) + 1)] for i in xrange(len(s1)): @@ -67,4 +67,4 @@ def isScramble(self, s1, s2): return result[n][0][0] if __name__ == "__main__": - print Solution().isScramble("rgtae", "great") \ No newline at end of file + print Solution().isScramble("rgtae", "great") From ff9cf4d376b69580b4a5aa392af04d14c32f6048 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 16 Feb 2015 23:28:20 +0800 Subject: [PATCH 096/345] Update string-to-integer-atoi.py --- Python/string-to-integer-atoi.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/string-to-integer-atoi.py b/Python/string-to-integer-atoi.py index b10431638..17b23e886 100644 --- a/Python/string-to-integer-atoi.py +++ b/Python/string-to-integer-atoi.py @@ -33,7 +33,7 @@ def atoi(self, str): INT_MIN = -2147483648 result = 0 - if len(str) == 0: + if not str: return result i = 0 @@ -65,4 +65,4 @@ def atoi(self, str): print Solution().atoi("2147483647") print Solution().atoi("2147483648") print Solution().atoi("-2147483648") - print Solution().atoi("-2147483649") \ No newline at end of file + print Solution().atoi("-2147483649") From f96bc5771e3b529dc5cb057ff45ae373b5655d8c Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 16 Feb 2015 23:29:34 +0800 Subject: [PATCH 097/345] Update subsets.py --- Python/subsets.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/subsets.py b/Python/subsets.py index 0d274aabf..eefdb0a55 100644 --- a/Python/subsets.py +++ b/Python/subsets.py @@ -46,7 +46,7 @@ def subsets(self, S): return self.subsetsRecu([], sorted(S)) def subsetsRecu(self, cur, S): - if len(S) == 0: + if not S: return [cur] return self.subsetsRecu(cur, S[1:]) + self.subsetsRecu(cur + [S[0]], S[1:]) From d6d78190abd4559839aaca65723ae0c92b622cfd Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 16 Feb 2015 23:30:43 +0800 Subject: [PATCH 098/345] Update surrounded-regions.py --- Python/surrounded-regions.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/surrounded-regions.py b/Python/surrounded-regions.py index bec979730..a0badb16c 100644 --- a/Python/surrounded-regions.py +++ b/Python/surrounded-regions.py @@ -23,7 +23,7 @@ class Solution: # Capture all regions by modifying the input board in-place. # Do not return any value. def solve(self, board): - if len(board) == 0: + if not board: return current = [] From 4c426b44b47922a707ce4efcc5e20d30d353a0c4 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 16 Feb 2015 23:31:39 +0800 Subject: [PATCH 099/345] Update triangle.py --- Python/triangle.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/triangle.py b/Python/triangle.py index 40cf9c627..e05906104 100644 --- a/Python/triangle.py +++ b/Python/triangle.py @@ -20,7 +20,7 @@ class Solution: # @param triangle, a list of lists of integers # @return an integer def minimumTotal(self, triangle): - if len(triangle) == 0: + if not triangle: return 0 cur = triangle[0] + [float("inf")] @@ -35,4 +35,4 @@ def minimumTotal(self, triangle): if __name__ == "__main__": print Solution().minimumTotal([[-1], [2, 3], [1, -1, -3]]) - \ No newline at end of file + From ff1efcc3333eeb27ef2ae5667b5de8a4c6c3eb4f Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 16 Feb 2015 23:33:33 +0800 Subject: [PATCH 100/345] Update wildcard-matching.py --- Python/wildcard-matching.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Python/wildcard-matching.py b/Python/wildcard-matching.py index cf2d464b8..d930727d7 100644 --- a/Python/wildcard-matching.py +++ b/Python/wildcard-matching.py @@ -98,11 +98,11 @@ def isMatch(self, s, p): class Solution4: # @return a boolean def isMatch(self, s, p): - if len(p) == 0: - return len(s) == 0 + if not p: + return not s if p[0] != '*': - if len(s) == 0 or (p[0] == s[0] or p[0] == '?'): + if not s or (p[0] == s[0] or p[0] == '?'): return self.isMatch(s[1:], p[1:]) else: return False From 044de2a7d4e27152512e79c0b86fa0945861971f Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 16 Feb 2015 23:34:43 +0800 Subject: [PATCH 101/345] Update word-ladder-ii.py --- Python/word-ladder-ii.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/word-ladder-ii.py b/Python/word-ladder-ii.py index 2838f1da5..8d47c5806 100644 --- a/Python/word-ladder-ii.py +++ b/Python/word-ladder-ii.py @@ -55,7 +55,7 @@ def findLadders(self, start, end, dict): return result def backtrack(self, result, trace, path, word): - if len(trace[word]) == 0: + if not trace[word]: result.append([word] + path) else: for prev in trace[word]: From 25c255b5f54ccad611ee34fd273396a6d9732c1f Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Tue, 17 Feb 2015 23:25:37 +0800 Subject: [PATCH 102/345] add new solution --- Python/best-time-to-buy-and-sell-stock-iv.py | 46 ++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 Python/best-time-to-buy-and-sell-stock-iv.py diff --git a/Python/best-time-to-buy-and-sell-stock-iv.py b/Python/best-time-to-buy-and-sell-stock-iv.py new file mode 100644 index 000000000..77cf015aa --- /dev/null +++ b/Python/best-time-to-buy-and-sell-stock-iv.py @@ -0,0 +1,46 @@ +# Time: O(k * n) +# Space: O(k) +# +# Say you have an array for which the ith element is the price of a given stock on day i. +# +# Design an algorithm to find the maximum profit. You may complete at most k transactions. +# +# Note: +# You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again). +# + +class Solution: + # @return an integer as the maximum profit + def maxProfit(self, k, prices): + if k >= len(prices): + return self.maxUnlimitPairProfit(prices) + + return self.maxAtMostKPairsProfit(prices, k) + + def maxUnlimitPairProfit(self, prices): + profit = 0 + for i in xrange(len(prices) - 1): + profit += max(0, prices[i + 1] - prices[i]) + return profit + + def maxAtMostKPairsProfit(self, prices, k): + if k == 0: + return 0 + + k_sum = [float("-inf") for _ in xrange(2 * k)] + for i in xrange(1, len(k_sum), 2): + k_sum[i] = 0 + + for i in xrange(len(prices)): + j, sign, pre_k_sum = 0, -1, 0 + while j < len(k_sum): + diff = sign * prices[i] + if j > 0: + diff += pre_k_sum + pre_k_sum, k_sum[j] = k_sum[j], max(diff, k_sum[j]) + j, sign = j + 1, sign * -1 + + return k_sum[-1] + +if __name__ == "__main__": + print Solution().maxAtMostKPairsProfit([1, 2, 3, 4], 2) \ No newline at end of file From a5494d473d36bd987fa7dbf43208c6a4c019ab97 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 17 Feb 2015 23:27:16 +0800 Subject: [PATCH 103/345] Update README.md --- README.md | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 52d4e211f..2cc361fc9 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ LeetCode ======== -Up to date (2015-02-06), there are total `187` problems on [LeetCode Online Judge](https://oj.leetcode.com/). +Up to date (2015-02-17), there are total `188` problems on [LeetCode Online Judge](https://oj.leetcode.com/). The number of problems is increasing recently. -Here is the classification of all `187` problems. +Here is the classification of all `188` problems. I'll keep updating for full summary and better solutions. Stay tuned for updates. --- @@ -611,6 +611,7 @@ Problem | Solution | Time | Space | Difficul Problem | Solution | Time | Space | Difficulty | Notes --------------- | --------------- | --------------- | --------------- | -------------- | ----- [Best Time to Buy and Sell Stock III]| [best-time-to-buy-and-sell-stock-iii.py] | _O(n)_ | _O(1)_ | Hard | +[Best Time to Buy and Sell Stock III]| [best-time-to-buy-and-sell-stock-iv.py] | _O(k * n)_ | _O(k)_ | Hard | [Climbing Stairs]| [climbing-stairs.py] | _O(n)_ | _O(1)_ | Easy | [Decode Ways] | [decode-ways.py]| _O(n)_ | _O(1)_ | Medium | [Distinct Subsequences]|[distinct-subsequences.py]| _O(n^2)_ | _O(n)_ | Hard | @@ -633,6 +634,8 @@ Problem | Solution | Time | Space | Difficul [Best Time to Buy and Sell Stock III]:https://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/ [best-time-to-buy-and-sell-stock-iii.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/best-time-to-buy-and-sell-stock-iii.py +[Best Time to Buy and Sell Stock IV]:https://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/ +[best-time-to-buy-and-sell-stock-iv.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/best-time-to-buy-and-sell-stock-iv.py [Climbing Stairs]:https://oj.leetcode.com/problems/climbing-stairs/ [climbing-stairs.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/climbing-stairs.py [Decode Ways]:https://oj.leetcode.com/problems/decode-ways/ From baac19f3908dcb2114231f31a38d98eeb2752bbb Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 17 Feb 2015 23:28:05 +0800 Subject: [PATCH 104/345] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 2cc361fc9..7d73c3dfe 100644 --- a/README.md +++ b/README.md @@ -611,7 +611,7 @@ Problem | Solution | Time | Space | Difficul Problem | Solution | Time | Space | Difficulty | Notes --------------- | --------------- | --------------- | --------------- | -------------- | ----- [Best Time to Buy and Sell Stock III]| [best-time-to-buy-and-sell-stock-iii.py] | _O(n)_ | _O(1)_ | Hard | -[Best Time to Buy and Sell Stock III]| [best-time-to-buy-and-sell-stock-iv.py] | _O(k * n)_ | _O(k)_ | Hard | +[Best Time to Buy and Sell Stock IV]| [best-time-to-buy-and-sell-stock-iv.py] | _O(k * n)_ | _O(k)_ | Hard | [Climbing Stairs]| [climbing-stairs.py] | _O(n)_ | _O(1)_ | Easy | [Decode Ways] | [decode-ways.py]| _O(n)_ | _O(1)_ | Medium | [Distinct Subsequences]|[distinct-subsequences.py]| _O(n^2)_ | _O(n)_ | Hard | From 3ec86226809d5b795b583ea2519e9a121d18b36f Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 17 Feb 2015 23:29:47 +0800 Subject: [PATCH 105/345] Update best-time-to-buy-and-sell-stock-iii.py --- Python/best-time-to-buy-and-sell-stock-iii.py | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/Python/best-time-to-buy-and-sell-stock-iii.py b/Python/best-time-to-buy-and-sell-stock-iii.py index 59c6c2081..1a0d89613 100644 --- a/Python/best-time-to-buy-and-sell-stock-iii.py +++ b/Python/best-time-to-buy-and-sell-stock-iii.py @@ -35,18 +35,21 @@ class Solution2: def maxProfit(self, prices): return self.maxAtMostKPairsProfit(prices, 2) - def maxAtMostKPairsProfit(self, prices, k): + def maxAtMostKPairsProfit(self, prices, k): + if k == 0: + return 0 + k_sum = [float("-inf") for _ in xrange(2 * k)] for i in xrange(1, len(k_sum), 2): k_sum[i] = 0 for i in xrange(len(prices)): - j, sign, pre_k_sum = 0, -1, list(k_sum) + j, sign, pre_k_sum = 0, -1, 0 while j < len(k_sum): diff = sign * prices[i] if j > 0: - diff += pre_k_sum[j - 1] - k_sum[j] = max(diff, pre_k_sum[j]) + diff += pre_k_sum + pre_k_sum, k_sum[j] = k_sum[j], max(diff, k_sum[j]) j, sign = j + 1, sign * -1 return k_sum[-1] From 46c69fb182dcd5222950a3c182e89232eada3454 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 17 Feb 2015 23:45:01 +0800 Subject: [PATCH 106/345] Update best-time-to-buy-and-sell-stock-iv.py --- Python/best-time-to-buy-and-sell-stock-iv.py | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/Python/best-time-to-buy-and-sell-stock-iv.py b/Python/best-time-to-buy-and-sell-stock-iv.py index 77cf015aa..0579a43b3 100644 --- a/Python/best-time-to-buy-and-sell-stock-iv.py +++ b/Python/best-time-to-buy-and-sell-stock-iv.py @@ -34,13 +34,11 @@ def maxAtMostKPairsProfit(self, prices, k): for i in xrange(len(prices)): j, sign, pre_k_sum = 0, -1, 0 while j < len(k_sum): - diff = sign * prices[i] - if j > 0: - diff += pre_k_sum + diff = pre_k_sum + sign * prices[i] pre_k_sum, k_sum[j] = k_sum[j], max(diff, k_sum[j]) j, sign = j + 1, sign * -1 return k_sum[-1] if __name__ == "__main__": - print Solution().maxAtMostKPairsProfit([1, 2, 3, 4], 2) \ No newline at end of file + print Solution().maxAtMostKPairsProfit([1, 2, 3, 4], 2) From ea40b2b40e85f86dcc417ae33fd7ac186b606af8 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 17 Feb 2015 23:48:54 +0800 Subject: [PATCH 107/345] Update best-time-to-buy-and-sell-stock-iii.py --- Python/best-time-to-buy-and-sell-stock-iii.py | 12 ++++-------- 1 file changed, 4 insertions(+), 8 deletions(-) diff --git a/Python/best-time-to-buy-and-sell-stock-iii.py b/Python/best-time-to-buy-and-sell-stock-iii.py index 1a0d89613..8fb42ff88 100644 --- a/Python/best-time-to-buy-and-sell-stock-iii.py +++ b/Python/best-time-to-buy-and-sell-stock-iii.py @@ -46,9 +46,7 @@ def maxAtMostKPairsProfit(self, prices, k): for i in xrange(len(prices)): j, sign, pre_k_sum = 0, -1, 0 while j < len(k_sum): - diff = sign * prices[i] - if j > 0: - diff += pre_k_sum + diff = pre_k_sum + sign * prices[i] pre_k_sum, k_sum[j] = k_sum[j], max(diff, k_sum[j]) j, sign = j + 1, sign * -1 @@ -58,12 +56,10 @@ def maxExatclyKPairsProfit(self, prices, k): k_sum = [float("-inf") for _ in xrange(2 * k)] for i in xrange(len(prices)): - j, sign, pre_k_sum = 0, -1, list(k_sum) + j, sign, pre_k_sum = 0, -1, 0 while j < len(k_sum) and j <= i: - diff = sign * prices[i] - if j > 0: - diff += pre_k_sum[j - 1] - k_sum[j] = max(diff, pre_k_sum[j]) + diff = pre_k_sum + sign * prices[i] + pre_k_sum, k_sum[j] = k_sum[j], max(diff, k_sum[j]) j, sign = j + 1, sign * -1 return k_sum[-1] From 0710d947c631e059f499b8added443ef9a73d7e0 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 18 Feb 2015 00:03:29 +0800 Subject: [PATCH 108/345] Update best-time-to-buy-and-sell-stock-iv.py --- Python/best-time-to-buy-and-sell-stock-iv.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/best-time-to-buy-and-sell-stock-iv.py b/Python/best-time-to-buy-and-sell-stock-iv.py index 0579a43b3..685325fb1 100644 --- a/Python/best-time-to-buy-and-sell-stock-iv.py +++ b/Python/best-time-to-buy-and-sell-stock-iv.py @@ -12,7 +12,7 @@ class Solution: # @return an integer as the maximum profit def maxProfit(self, k, prices): - if k >= len(prices): + if k >= len(prices) / 2: return self.maxUnlimitPairProfit(prices) return self.maxAtMostKPairsProfit(prices, k) From d750bd1859345864ba97b49dbbe81cd51779bc21 Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Wed, 18 Feb 2015 01:10:07 +0800 Subject: [PATCH 109/345] update --- Python/best-time-to-buy-and-sell-stock-iv.py | 31 ++++++++++---------- 1 file changed, 15 insertions(+), 16 deletions(-) diff --git a/Python/best-time-to-buy-and-sell-stock-iv.py b/Python/best-time-to-buy-and-sell-stock-iv.py index 685325fb1..c1ce236cf 100644 --- a/Python/best-time-to-buy-and-sell-stock-iv.py +++ b/Python/best-time-to-buy-and-sell-stock-iv.py @@ -13,32 +13,31 @@ class Solution: # @return an integer as the maximum profit def maxProfit(self, k, prices): if k >= len(prices) / 2: - return self.maxUnlimitPairProfit(prices) + return self.maxAtMostNPairsProfit(prices) return self.maxAtMostKPairsProfit(prices, k) - - def maxUnlimitPairProfit(self, prices): + + def maxAtMostNPairsProfit(self, prices): profit = 0 for i in xrange(len(prices) - 1): profit += max(0, prices[i + 1] - prices[i]) return profit - + def maxAtMostKPairsProfit(self, prices, k): if k == 0: return 0 - - k_sum = [float("-inf") for _ in xrange(2 * k)] - for i in xrange(1, len(k_sum), 2): - k_sum[i] = 0 - + + max_buy = [float("-inf") for _ in xrange(k + 1)] + max_sell = [0 for _ in xrange(k + 1)] + for i in xrange(len(prices)): - j, sign, pre_k_sum = 0, -1, 0 - while j < len(k_sum): - diff = pre_k_sum + sign * prices[i] - pre_k_sum, k_sum[j] = k_sum[j], max(diff, k_sum[j]) - j, sign = j + 1, sign * -1 - - return k_sum[-1] + j = 1 + while j <= k: + max_buy[j] = max(max_buy[j], max_sell[j-1] - prices[i]) + max_sell[j] = max(max_sell[j], max_buy[j] + prices[i]) + j = j + 1 + + return max_sell[k] if __name__ == "__main__": print Solution().maxAtMostKPairsProfit([1, 2, 3, 4], 2) From 9bf205ea3fa164a59c4a8f59892992395a6b4e16 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 18 Feb 2015 01:16:55 +0800 Subject: [PATCH 110/345] Update best-time-to-buy-and-sell-stock-iv.py --- Python/best-time-to-buy-and-sell-stock-iv.py | 3 --- 1 file changed, 3 deletions(-) diff --git a/Python/best-time-to-buy-and-sell-stock-iv.py b/Python/best-time-to-buy-and-sell-stock-iv.py index c1ce236cf..ad3582488 100644 --- a/Python/best-time-to-buy-and-sell-stock-iv.py +++ b/Python/best-time-to-buy-and-sell-stock-iv.py @@ -24,9 +24,6 @@ def maxAtMostNPairsProfit(self, prices): return profit def maxAtMostKPairsProfit(self, prices, k): - if k == 0: - return 0 - max_buy = [float("-inf") for _ in xrange(k + 1)] max_sell = [0 for _ in xrange(k + 1)] From 955e7e3cfb41298ed678fc77db60f9042b61f4cd Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 18 Feb 2015 01:20:24 +0800 Subject: [PATCH 111/345] Update best-time-to-buy-and-sell-stock-iv.py --- Python/best-time-to-buy-and-sell-stock-iv.py | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/Python/best-time-to-buy-and-sell-stock-iv.py b/Python/best-time-to-buy-and-sell-stock-iv.py index ad3582488..f776524e4 100644 --- a/Python/best-time-to-buy-and-sell-stock-iv.py +++ b/Python/best-time-to-buy-and-sell-stock-iv.py @@ -28,11 +28,9 @@ def maxAtMostKPairsProfit(self, prices, k): max_sell = [0 for _ in xrange(k + 1)] for i in xrange(len(prices)): - j = 1 - while j <= k: + for j in xrange(1, k+1): max_buy[j] = max(max_buy[j], max_sell[j-1] - prices[i]) max_sell[j] = max(max_sell[j], max_buy[j] + prices[i]) - j = j + 1 return max_sell[k] From b325cfdd1955b5d734b2b5b91bc4b874d40ea4ca Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 18 Feb 2015 03:03:35 +0800 Subject: [PATCH 112/345] Update best-time-to-buy-and-sell-stock-iii.py --- Python/best-time-to-buy-and-sell-stock-iii.py | 36 ++++++------------- 1 file changed, 10 insertions(+), 26 deletions(-) diff --git a/Python/best-time-to-buy-and-sell-stock-iii.py b/Python/best-time-to-buy-and-sell-stock-iii.py index 8fb42ff88..6b207e701 100644 --- a/Python/best-time-to-buy-and-sell-stock-iii.py +++ b/Python/best-time-to-buy-and-sell-stock-iii.py @@ -36,33 +36,17 @@ def maxProfit(self, prices): return self.maxAtMostKPairsProfit(prices, 2) def maxAtMostKPairsProfit(self, prices, k): - if k == 0: - return 0 - - k_sum = [float("-inf") for _ in xrange(2 * k)] - for i in xrange(1, len(k_sum), 2): - k_sum[i] = 0 - - for i in xrange(len(prices)): - j, sign, pre_k_sum = 0, -1, 0 - while j < len(k_sum): - diff = pre_k_sum + sign * prices[i] - pre_k_sum, k_sum[j] = k_sum[j], max(diff, k_sum[j]) - j, sign = j + 1, sign * -1 - - return k_sum[-1] - - def maxExatclyKPairsProfit(self, prices, k): - k_sum = [float("-inf") for _ in xrange(2 * k)] - + max_buy = [float("-inf") for _ in xrange(k + 1)] + max_sell = [0 for _ in xrange(k + 1)] + for i in xrange(len(prices)): - j, sign, pre_k_sum = 0, -1, 0 - while j < len(k_sum) and j <= i: - diff = pre_k_sum + sign * prices[i] - pre_k_sum, k_sum[j] = k_sum[j], max(diff, k_sum[j]) - j, sign = j + 1, sign * -1 - - return k_sum[-1] + j = 1 + while j <= k and j <= i + 1: + max_buy[j] = max(max_buy[j], max_sell[j-1] - prices[i]) + max_sell[j] = max(max_sell[j], max_buy[j] + prices[i]) + j += 1 + + return max_sell[k] # Time: O(n) # Space: O(n) From 6577659a0c270dc7f3ecd7bb2d1558dac2a97928 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 18 Feb 2015 03:06:48 +0800 Subject: [PATCH 113/345] Update best-time-to-buy-and-sell-stock-iii.py --- Python/best-time-to-buy-and-sell-stock-iii.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/Python/best-time-to-buy-and-sell-stock-iii.py b/Python/best-time-to-buy-and-sell-stock-iii.py index 6b207e701..4027266ff 100644 --- a/Python/best-time-to-buy-and-sell-stock-iii.py +++ b/Python/best-time-to-buy-and-sell-stock-iii.py @@ -40,11 +40,10 @@ def maxAtMostKPairsProfit(self, prices, k): max_sell = [0 for _ in xrange(k + 1)] for i in xrange(len(prices)): - j = 1 - while j <= k and j <= i + 1: + for j in xrange(1, min(k, i+1) + 1): max_buy[j] = max(max_buy[j], max_sell[j-1] - prices[i]) max_sell[j] = max(max_sell[j], max_buy[j] + prices[i]) - j += 1 + return max_sell[k] From 70d1178714e335a714c45ea3b50d87e55991a5c1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 18 Feb 2015 03:07:03 +0800 Subject: [PATCH 114/345] Update best-time-to-buy-and-sell-stock-iii.py --- Python/best-time-to-buy-and-sell-stock-iii.py | 1 - 1 file changed, 1 deletion(-) diff --git a/Python/best-time-to-buy-and-sell-stock-iii.py b/Python/best-time-to-buy-and-sell-stock-iii.py index 4027266ff..72eeaf173 100644 --- a/Python/best-time-to-buy-and-sell-stock-iii.py +++ b/Python/best-time-to-buy-and-sell-stock-iii.py @@ -44,7 +44,6 @@ def maxAtMostKPairsProfit(self, prices, k): max_buy[j] = max(max_buy[j], max_sell[j-1] - prices[i]) max_sell[j] = max(max_sell[j], max_buy[j] + prices[i]) - return max_sell[k] # Time: O(n) From 5fee5f2f77d527dbe49f1ba5529523c0b64e631f Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 18 Feb 2015 03:07:50 +0800 Subject: [PATCH 115/345] Update best-time-to-buy-and-sell-stock-iv.py --- Python/best-time-to-buy-and-sell-stock-iv.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/best-time-to-buy-and-sell-stock-iv.py b/Python/best-time-to-buy-and-sell-stock-iv.py index f776524e4..e5ee06a0b 100644 --- a/Python/best-time-to-buy-and-sell-stock-iv.py +++ b/Python/best-time-to-buy-and-sell-stock-iv.py @@ -28,9 +28,9 @@ def maxAtMostKPairsProfit(self, prices, k): max_sell = [0 for _ in xrange(k + 1)] for i in xrange(len(prices)): - for j in xrange(1, k+1): + for j in xrange(1, min(k, i+1) + 1): max_buy[j] = max(max_buy[j], max_sell[j-1] - prices[i]) - max_sell[j] = max(max_sell[j], max_buy[j] + prices[i]) + max_sell[j] = max(max_sell[j], max_buy[j] + prices[i]) return max_sell[k] From a608d30f92752f2f75c0c6560833a45e0a126efc Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 18 Feb 2015 03:33:01 +0800 Subject: [PATCH 116/345] Update best-time-to-buy-and-sell-stock-iii.py --- Python/best-time-to-buy-and-sell-stock-iii.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/best-time-to-buy-and-sell-stock-iii.py b/Python/best-time-to-buy-and-sell-stock-iii.py index 72eeaf173..52a837896 100644 --- a/Python/best-time-to-buy-and-sell-stock-iii.py +++ b/Python/best-time-to-buy-and-sell-stock-iii.py @@ -27,7 +27,7 @@ def maxProfit(self, prices): hold1 = max(hold1, -i); return release2 -# Time: O(k^2 * n) +# Time: O(k * n) # Space: O(k) class Solution2: # @param prices, a list of integer From de58235ea9751d5845149e74be8e344774afe191 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 18 Feb 2015 15:20:18 +0800 Subject: [PATCH 117/345] Update best-time-to-buy-and-sell-stock-iv.py --- Python/best-time-to-buy-and-sell-stock-iv.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/best-time-to-buy-and-sell-stock-iv.py b/Python/best-time-to-buy-and-sell-stock-iv.py index e5ee06a0b..0235f07df 100644 --- a/Python/best-time-to-buy-and-sell-stock-iv.py +++ b/Python/best-time-to-buy-and-sell-stock-iv.py @@ -28,7 +28,7 @@ def maxAtMostKPairsProfit(self, prices, k): max_sell = [0 for _ in xrange(k + 1)] for i in xrange(len(prices)): - for j in xrange(1, min(k, i+1) + 1): + for j in xrange(1, min(k, i/2+1) + 1): max_buy[j] = max(max_buy[j], max_sell[j-1] - prices[i]) max_sell[j] = max(max_sell[j], max_buy[j] + prices[i]) From 842b24e9a282ded39cd2a8b7e9adaa7ba28391a5 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 18 Feb 2015 15:28:18 +0800 Subject: [PATCH 118/345] Update best-time-to-buy-and-sell-stock-iii.py --- Python/best-time-to-buy-and-sell-stock-iii.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/best-time-to-buy-and-sell-stock-iii.py b/Python/best-time-to-buy-and-sell-stock-iii.py index 52a837896..114c1b321 100644 --- a/Python/best-time-to-buy-and-sell-stock-iii.py +++ b/Python/best-time-to-buy-and-sell-stock-iii.py @@ -40,7 +40,7 @@ def maxAtMostKPairsProfit(self, prices, k): max_sell = [0 for _ in xrange(k + 1)] for i in xrange(len(prices)): - for j in xrange(1, min(k, i+1) + 1): + for j in xrange(1, min(k, i/2+1) + 1): max_buy[j] = max(max_buy[j], max_sell[j-1] - prices[i]) max_sell[j] = max(max_sell[j], max_buy[j] + prices[i]) From 795870e0760a985bbc10cf05aa1b16c87f464c0f Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 24 Feb 2015 22:32:39 +0800 Subject: [PATCH 119/345] Update and rename Python to Python/rotate-array.py --- Python/rotate-array.py | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 Python/rotate-array.py diff --git a/Python/rotate-array.py b/Python/rotate-array.py new file mode 100644 index 000000000..0dbfb6528 --- /dev/null +++ b/Python/rotate-array.py @@ -0,0 +1,31 @@ +# Time: O(n) +# Space: O(1) +# +# Rotate an array of n elements to the right by k steps. +# +# For example, with n = 7 and k = 3, the array [1,2,3,4,5,6,7] is rotated to [5,6,7,1,2,3,4]. +# +# Note: +# Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem. +# + +class Solution: + # @param nums, a list of integer + # @param k, num of steps + # @return nothing, please modify the nums list in-place. + def rotate(self, nums, k): + k %= len(nums) + self.reverse(nums, 0, len(nums)) + self.reverse(nums, 0, k) + self.reverse(nums, k, len(nums)) + + def reverse(self, nums, start, end): + while start < end: + nums[start], nums[end-1] = nums[end-1], nums[start] + start += 1 + end -= 1 + +if __name__ == '__main__': + nums = [1,2,3,4,5,6,7] + Solution().rotate(nums, 3) + print nums From 3b93cf00f6e42f4e2029cee03fb2dcc07a4581b8 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 24 Feb 2015 22:37:36 +0800 Subject: [PATCH 120/345] Update README.md --- README.md | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 7d73c3dfe..9ef16ae91 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ LeetCode ======== -Up to date (2015-02-17), there are total `188` problems on [LeetCode Online Judge](https://oj.leetcode.com/). +Up to date (2015-02-24), there are total `189` problems on [LeetCode Online Judge](https://oj.leetcode.com/). The number of problems is increasing recently. -Here is the classification of all `188` problems. +Here is the classification of all `189` problems. I'll keep updating for full summary and better solutions. Stay tuned for updates. --- @@ -72,6 +72,7 @@ Problem | Solution | Time | Space | Difficul [Remove Duplicates from Sorted Array]| [remove-duplicates-from-sorted-array.py] | _O(n)_ | _O(1)_ | Easy | [Remove Duplicates from Sorted Array II]| [remove-duplicates-from-sorted-array-ii.py] | _O(n)_ | _O(1)_ | Medium | [Remove Element] | [remove-element.py] | _O(n)_ | _O(1)_ | Easy | +[Rotate Array] | [rotate-array.py] | _O(n)_ | _O(1)_ | Easy | [Rotate Image] | [rotate-image.py] | _O(n^2)_ | _O(1)_ | Medium | [Set Matrix Zeroes] | [set-matrix-zeroes.py] | _O(m * n)_ | _O(1)_ | Medium | [Spiral Matrix] | [spiral-matrix.py] | _O(m * n)_ | _O(1)_ | Medium | @@ -110,6 +111,8 @@ Problem | Solution | Time | Space | Difficul [remove-duplicates-from-sorted-array-ii.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/remove-duplicates-from-sorted-array-ii.py [Remove Element]:https://oj.leetcode.com/problems/remove-element/ [remove-element.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/remove-element.py +[Rotate Array]:https://oj.leetcode.com/problems/rotate-array/ +[rotate-array.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/rotate-array.py [Rotate Image]:https://oj.leetcode.com/problems/rotate-image/ [rotate-image.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/rotate-image.py [Set Matrix Zeroes]:https://oj.leetcode.com/problems/set-matrix-zeroes/ From 4ce140ffa15a7f038882aaea5719dbab89ec438b Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Tue, 24 Feb 2015 23:08:44 +0800 Subject: [PATCH 121/345] add solution --- Python/rotate-array.py | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/Python/rotate-array.py b/Python/rotate-array.py index 0dbfb6528..2041672a9 100644 --- a/Python/rotate-array.py +++ b/Python/rotate-array.py @@ -24,7 +24,26 @@ def reverse(self, nums, start, end): nums[start], nums[end-1] = nums[end-1], nums[start] start += 1 end -= 1 - + +from fractions import gcd + +class Solution2: + # @param nums, a list of integer + # @param k, num of steps + # @return nothing, please modify the nums list in-place. + def rotate(self, nums, k): + k %= len(nums) + num_cycles = gcd(len(nums), k) + cycle_len = len(nums) / num_cycles + for i in xrange(num_cycles): + self.apply_cycle_permutation(k, i, cycle_len, nums) + + def apply_cycle_permutation(self, k, offset, cycle_len, nums): + tmp = nums[offset] + for i in xrange(1, cycle_len): + nums[(offset+i*k) % len(nums)], tmp = tmp, nums[(offset+i*k) % len(nums)] + nums[offset] = tmp + if __name__ == '__main__': nums = [1,2,3,4,5,6,7] Solution().rotate(nums, 3) From 72371e24d338a5c054ce414b4d11fa3a6965ec78 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 9 Mar 2015 22:48:02 +0800 Subject: [PATCH 122/345] Create reverse-bits.py --- Python/reverse-bits.py | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 Python/reverse-bits.py diff --git a/Python/reverse-bits.py b/Python/reverse-bits.py new file mode 100644 index 000000000..aac560942 --- /dev/null +++ b/Python/reverse-bits.py @@ -0,0 +1,29 @@ +# Time : O(n) +# Space: O(1) +# +# Reverse bits of a given 32 bits unsigned integer. +# +# For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), return 964176192 (represented in binary as 00111001011110000010100101000000). +# +# Follow up: +# If this function is called many times, how would you optimize it? +# +# Related problem: Reverse Integer +# +# Credits: +# Special thanks to @ts for adding this problem and creating all test cases. +# + +class Solution: + # @param n, an integer + # @return an integer + def reverseBits(self, n): + result = 0 + for i in xrange(32): + result <<= 1 + result |= n & 1 + n >>= 1 + return result + +if __name__ == '__main__': + print Solutoin().reverseBits(1) From 4548514f463e8e0731836984538c64d053ed85da Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 9 Mar 2015 22:49:00 +0800 Subject: [PATCH 123/345] Update reverse-bits.py --- Python/reverse-bits.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/reverse-bits.py b/Python/reverse-bits.py index aac560942..4c8a0f36d 100644 --- a/Python/reverse-bits.py +++ b/Python/reverse-bits.py @@ -26,4 +26,4 @@ def reverseBits(self, n): return result if __name__ == '__main__': - print Solutoin().reverseBits(1) + print Solution().reverseBits(1) From c0051b6832f0a0a8d7732f38ac065fec8140db9f Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 9 Mar 2015 22:51:35 +0800 Subject: [PATCH 124/345] Update README.md --- README.md | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 9ef16ae91..a0ef8a773 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ LeetCode ======== -Up to date (2015-02-24), there are total `189` problems on [LeetCode Online Judge](https://oj.leetcode.com/). +Up to date (2015-03-08), there are total `190` problems on [LeetCode Online Judge](https://oj.leetcode.com/). The number of problems is increasing recently. -Here is the classification of all `189` problems. +Here is the classification of all `190` problems. I'll keep updating for full summary and better solutions. Stay tuned for updates. --- @@ -42,9 +42,12 @@ Database ##Bit Manipulation Problem | Solution | Time | Space | Difficulty | Notes --------------- | --------------- | --------------- | --------------- | -------------- | ----- +[Reverse Bits] | [reverse-bits.py] | _O(n)_ | _O(1)_ | Easy | [Single Number] | [single-number.py] | _O(n)_ | _O(1)_ | Medium | [Single Number II] | [single-number-ii.py] | _O(n)_ | _O(1)_ | Medium | +[Reverse Bits]: https://oj.leetcode.com/problems/reverse-bits/ +[reverse-bits.py]: https://github.com/kamyu104/LeetCode/blob/master/Python/reverse-bits.py [Single Number]: https://oj.leetcode.com/problems/single-number/ [single-number.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/single-number.py [Single Number II]: https://oj.leetcode.com/problems/single-number-ii/ From a74fdffab75f94f0af84d9c0cee435ea61bae7ff Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 10 Mar 2015 22:56:17 +0800 Subject: [PATCH 125/345] Create number-of-1-bits.py --- Python/number-of-1-bits.py | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 Python/number-of-1-bits.py diff --git a/Python/number-of-1-bits.py b/Python/number-of-1-bits.py new file mode 100644 index 000000000..3be9aa774 --- /dev/null +++ b/Python/number-of-1-bits.py @@ -0,0 +1,24 @@ +# Time: O(m) +# Space: O(1) +# +# Write a function that takes an unsigned integer +# and returns the number of ’1' bits it has (also known as the Hamming weight). +# +# For example, the 32-bit integer ’11' has binary representation 00000000000000000000000000001011, +# so the function should return 3. +# +# Credits: +# Special thanks to @ts for adding this problem and creating all test cases. +# +class Solution: + # @param n, an integer + # @return an integer + def hammingWeight(self, n): + result = 0 + while n: + n &= n - 1 + result += 1 + return result + +if __name__ == '__main__': + print Solution().hammingWeight(11) From 690930bb80e5dcc8656e1c788d83490c3df7838c Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 10 Mar 2015 22:58:51 +0800 Subject: [PATCH 126/345] Update README.md --- README.md | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index a0ef8a773..92e4e7225 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ LeetCode ======== -Up to date (2015-03-08), there are total `190` problems on [LeetCode Online Judge](https://oj.leetcode.com/). +Up to date (2015-03-10), there are total `191` problems on [LeetCode Online Judge](https://oj.leetcode.com/). The number of problems is increasing recently. -Here is the classification of all `190` problems. +Here is the classification of all `191` problems. I'll keep updating for full summary and better solutions. Stay tuned for updates. --- @@ -42,10 +42,13 @@ Database ##Bit Manipulation Problem | Solution | Time | Space | Difficulty | Notes --------------- | --------------- | --------------- | --------------- | -------------- | ----- +[Number of 1 Bits] | [number-of-1-bits.py] | _O(m)_ | _O(1)_ | Easy | [Reverse Bits] | [reverse-bits.py] | _O(n)_ | _O(1)_ | Easy | [Single Number] | [single-number.py] | _O(n)_ | _O(1)_ | Medium | [Single Number II] | [single-number-ii.py] | _O(n)_ | _O(1)_ | Medium | +[Number of 1 Bits]: https://oj.leetcode.com/problems/number-of-1-bits/ +[number-of-1-bits.py]: https://github.com/kamyu104/LeetCode/blob/master/Python/number-of-1-bits.py [Reverse Bits]: https://oj.leetcode.com/problems/reverse-bits/ [reverse-bits.py]: https://github.com/kamyu104/LeetCode/blob/master/Python/reverse-bits.py [Single Number]: https://oj.leetcode.com/problems/single-number/ From db8fb0a8503588f2e7d01f79f6b13bfb8af11f3c Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Tue, 10 Mar 2015 23:00:52 +0800 Subject: [PATCH 127/345] update --- Python/number-of-1-bits.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/number-of-1-bits.py b/Python/number-of-1-bits.py index 3be9aa774..2b34a304f 100644 --- a/Python/number-of-1-bits.py +++ b/Python/number-of-1-bits.py @@ -2,9 +2,9 @@ # Space: O(1) # # Write a function that takes an unsigned integer -# and returns the number of ’1' bits it has (also known as the Hamming weight). +# and returns the number of '1' bits it has (also known as the Hamming weight). # -# For example, the 32-bit integer ’11' has binary representation 00000000000000000000000000001011, +# For example, the 32-bit integer '11' has binary representation 00000000000000000000000000001011, # so the function should return 3. # # Credits: From a852298c50d7129625e4f493a3bef2edb7c77dda Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 18 Mar 2015 00:18:02 +0800 Subject: [PATCH 128/345] Update median-of-two-sorted-arrays.py --- Python/median-of-two-sorted-arrays.py | 37 +++++++++++++++++++++++++-- 1 file changed, 35 insertions(+), 2 deletions(-) diff --git a/Python/median-of-two-sorted-arrays.py b/Python/median-of-two-sorted-arrays.py index 644f74927..89caa92dc 100644 --- a/Python/median-of-two-sorted-arrays.py +++ b/Python/median-of-two-sorted-arrays.py @@ -14,6 +14,39 @@ def findMedianSortedArrays(self, A, B): else: return (self.getKth(A, B, (lenA + lenB)/2) + self.getKth(A, B, (lenA + lenB)/2 + 1)) * 0.5 + def getKth(self, A, B, k): + m, n = len(A), len(B) + if m > n: + return self.getKth(B, A, k) + + left, right = 0, m + while left < right: + mid = left + (right - left) / 2 + j = k - 1 - mid + if j >= n or A[mid] < B[j]: + left = mid + 1 + else: + right = mid + + Ai_minus_1, Bj = float("-inf"), float("-inf") + if left - 1 >= 0: + Ai_minus_1 = A[left - 1] + if k - 1 - left >= 0: + Bj = B[k - 1 - left] + + return max(Ai_minus_1, Bj) + +# Time: O(log(m + n)) +# Space: O(1) +class Solution2: + # @return a float + def findMedianSortedArrays(self, A, B): + lenA, lenB = len(A), len(B) + if (lenA + lenB) % 2 == 1: + return self.getKth(A, B, (lenA + lenB)/2 + 1) + else: + return (self.getKth(A, B, (lenA + lenB)/2) + self.getKth(A, B, (lenA + lenB)/2 + 1)) * 0.5 + def getKth(self, A, B, k): b = max(0, k - len(B)) t = min(len(A), k) @@ -46,7 +79,7 @@ def getKth(self, A, B, k): # Time: O(log(m + n)) # Space: O(log(m + n)) -class Solution2: +class Solution3: # @return a float def findMedianSortedArrays(self, A, B): lenA, lenB = len(A), len(B) @@ -77,7 +110,7 @@ def getKth(self, A, i, B, j, k): return A[i + pa - 1] # using list slicing (O(k)) may be slower than solution1 -class Solution3: +class Solution4: # @return a float def findMedianSortedArrays(self, A, B): lenA, lenB = len(A), len(B) From 6fcc8dcb117d18c7478c19dce252a0c940344b14 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 1 Apr 2015 23:01:07 +0800 Subject: [PATCH 129/345] Create house-robber.py --- Python/house-robber.py | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 Python/house-robber.py diff --git a/Python/house-robber.py b/Python/house-robber.py new file mode 100644 index 000000000..db2379811 --- /dev/null +++ b/Python/house-robber.py @@ -0,0 +1,30 @@ +# Time: O(n) +# Space: O(1) +# +# You are a professional robber planning to rob houses along a street. +# Each house has a certain amount of money stashed, the only constraint stopping you +# from robbing each of them is that adjacent houses have security system connected +# and it will automatically contact the police if two adjacent houses were broken into on the same night. +# +# Given a list of non-negative integers representing the amount of money of each house, +# determine the maximum amount of money you can rob tonight without alerting the police. +# +class Solution: + # @param num, a list of integer + # @return an integer + def rob(self, num): + if len(num) == 0: + return 0 + + if len(num) == 1: + return num[0] + + num_i, num_i_1 = max(num[1], num[0]), num[0] + for i in xrange(2, len(num)): + num_i_1, num_i_2 = num_i, num_i_1 + num_i = max(num[i] + num_i_2, num_i_1); + + return num_i + +if __name__ == '__main__': + print Solution().rob([8,4,8,5,9,6,5,4,4,10]) From 0d02f04547445ad424cb087731123e6fb3f4e97f Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 1 Apr 2015 23:03:58 +0800 Subject: [PATCH 130/345] Update README.md --- README.md | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 92e4e7225..ee2828151 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ LeetCode ======== -Up to date (2015-03-10), there are total `191` problems on [LeetCode Online Judge](https://oj.leetcode.com/). +Up to date (2015-04-01), there are total `198` problems on [LeetCode Online Judge](https://oj.leetcode.com/). The number of problems is increasing recently. -Here is the classification of all `191` problems. +Here is the classification of all `192` problems. I'll keep updating for full summary and better solutions. Stay tuned for updates. --- @@ -626,6 +626,7 @@ Problem | Solution | Time | Space | Difficul [Distinct Subsequences]|[distinct-subsequences.py]| _O(n^2)_ | _O(n)_ | Hard | [Dungeon Game] | [dungeon-game.py]| _O(m * n)_ | _O(m + n)_ | Hard | [Edit Distance]|[edit-distance.py]| _O(m * n)_ | _O(m + n)_ | Hard | +[House Robber]| [house-robber.py] | _O(n)_ | _O(1)_ | Easy | [Interleaving String]|[interleaving-string.py]| _O(m * n)_ | _O(m + n)_ | Hard | [Maximal Rectangle]|[maximal-rectangle.py]| _O(n^2)_ | _O(n)_ | Hard | [Maximum Product Subarray]|[maximum-product-subarray.py]| _O(n)_ | _O(1)_ | Medium | @@ -655,6 +656,8 @@ Problem | Solution | Time | Space | Difficul [dungeon-game.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/dungeon-game.py [Edit Distance]:https://oj.leetcode.com/problems/edit-distance/ [edit-distance.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/edit-distance.py +[House Robber]:https://oj.leetcode.com/problems/house-robber/ +[house-robber.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/house-robber.py [Interleaving String]:https://oj.leetcode.com/problems/interleaving-string/ [interleaving-string.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/interleaving-string.py [Maximal Rectangle]:https://oj.leetcode.com/problems/maximal-rectangle/ From 4913a84c928eb82c72c462a4f1c6efe992307f3a Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 1 Apr 2015 23:21:40 +0800 Subject: [PATCH 131/345] Create rising-temperature.sql --- MySQL/rising-temperature.sql | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 MySQL/rising-temperature.sql diff --git a/MySQL/rising-temperature.sql b/MySQL/rising-temperature.sql new file mode 100644 index 000000000..91c25d228 --- /dev/null +++ b/MySQL/rising-temperature.sql @@ -0,0 +1,28 @@ +# Time: O(n^2) +# Space: O(n) +# +# Given a Weather table, write a SQL query to find all dates' +# Ids with higher temperature compared to its previous (yesterday's) dates. +# +# +---------+------------+------------------+ +# | Id(INT) | Date(DATE) | Temperature(INT) | +# +---------+------------+------------------+ +# | 1 | 2015-01-01 | 10 | +# | 2 | 2015-01-02 | 25 | +# | 3 | 2015-01-03 | 20 | +# | 4 | 2015-01-04 | 30 | +# +---------+------------+------------------+ +# For example, return the following Ids for the above Weather table: +# +----+ +# | Id | +# +----+ +# | 2 | +# | 4 | +# +----+ +# + +# Write your MySQL query statement below +SELECT wt1.Id +FROM Weather wt1, Weather wt2 +WHERE wt1.Temperature > wt2.Temperature AND + TO_DAYS(wt1.DATE)-TO_DAYS(wt2.DATE)=1; From e9bff6a2eb0efb239ddd26c0329794946cc800fa Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 1 Apr 2015 23:23:39 +0800 Subject: [PATCH 132/345] Create delete-duplicate-emails.sql --- MySQL/delete-duplicate-emails.sql | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 MySQL/delete-duplicate-emails.sql diff --git a/MySQL/delete-duplicate-emails.sql b/MySQL/delete-duplicate-emails.sql new file mode 100644 index 000000000..b098426ca --- /dev/null +++ b/MySQL/delete-duplicate-emails.sql @@ -0,0 +1,28 @@ +# Time: O(n^2) +# Space: O(n) +# +# Write a SQL query to delete all duplicate email entries in a table named Person, +# keeping only unique emails based on its smallest Id. +# +# +----+------------------+ +# | Id | Email | +# +----+------------------+ +# | 1 | john@example.com | +# | 2 | bob@example.com | +# | 3 | john@example.com | +# +----+------------------+ +# Id is the primary key column for this table. +# For example, after running your query, the above Person table should have the following rows: +# +# +----+------------------+ +# | Id | Email | +# +----+------------------+ +# | 1 | john@example.com | +# | 2 | bob@example.com | +# +----+------------------+ +# + +# Write your MySQL query statement below +DELETE p1 +FROM Person p1, Person p2 +WHERE p1.Email = p2.Email AND p1.Id > p2.Id From abc2545d9f961708c351c75c5dff7786d2c931fe Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Wed, 1 Apr 2015 23:35:30 +0800 Subject: [PATCH 133/345] add more solutions --- Shell/tenth-line.sh | 26 ++++++++++++++++++++++++++ Shell/transpose-file.sh | 35 +++++++++++++++++++++++++++++++++++ Shell/valid-phone-numbers.sh | 33 +++++++++++++++++++++++++++++++++ Shell/word-frequency.sh | 29 +++++++++++++++++++++++++++++ 4 files changed, 123 insertions(+) create mode 100644 Shell/tenth-line.sh create mode 100644 Shell/transpose-file.sh create mode 100644 Shell/valid-phone-numbers.sh create mode 100644 Shell/word-frequency.sh diff --git a/Shell/tenth-line.sh b/Shell/tenth-line.sh new file mode 100644 index 000000000..b8ca175d2 --- /dev/null +++ b/Shell/tenth-line.sh @@ -0,0 +1,26 @@ +# Time: O(n) +# Space: O(1) +# +# How would you print just the 10th line of a file? +# +# For example, assume that file.txt has the following content: +# +# Line 1 +# Line 2 +# Line 3 +# Line 4 +# Line 5 +# Line 6 +# Line 7 +# Line 8 +# Line 9 +# Line 10 +# Your script should output the tenth line, which is: +# Line 10 +# +# Hint: +# 1. If the file contains less than 10 lines, what should you output? +# 2. There's at least three different solutions. Try to explore all possibilities. +# +# Read from the file file.txt and output the tenth line to stdout. +awk '{if(NR==10) print $0}' file.txt diff --git a/Shell/transpose-file.sh b/Shell/transpose-file.sh new file mode 100644 index 000000000..e912f219d --- /dev/null +++ b/Shell/transpose-file.sh @@ -0,0 +1,35 @@ +# Time: O(n^2) +# Space: O(n^2) +# +# Given a text file file.txt, transpose its content. +# +# You may assume that each row has the same number of +# columns and each field is separated by the ' ' character. +# +# For example, if file.txt has the following content: +# +# name age +# alice 21 +# ryan 30 +# Output the following: +# +# name alice ryan +# age 21 30 +# + +# Read from the file file.txt and print its transposed content to stdout. +awk ' +{ + for (i = 1; i <= NF; i++) { + if(NR == 1) { + s[i] = $i; + } else { + s[i] = s[i] " " $i; + } + } +} +END { + for (i = 1; s[i] != ""; i++) { + print s[i]; + } +}' file.txt diff --git a/Shell/valid-phone-numbers.sh b/Shell/valid-phone-numbers.sh new file mode 100644 index 000000000..561fde3a0 --- /dev/null +++ b/Shell/valid-phone-numbers.sh @@ -0,0 +1,33 @@ +# Time: O(n) +# Space: O(1) +# +# Given a text file file.txt that contains list of +# phone numbers (one per line), write a one liner +# bash script to print all valid phone numbers. +# +# You may assume that a valid phone number must +# appear in one of the following two formats: +# (xxx) xxx-xxxx or xxx-xxx-xxxx. (x means a digit) +# +# You may also assume each line in the text file +# must not contain leading or trailing white spaces. +# +# For example, assume that file.txt has the following content: +# +# 987-123-4567 +# 123 456 7890 +# (123) 456-7890 +# Your script should output the following valid phone numbers: +# 987-123-4567 +# (123) 456-7890 +# +# +# Read from the file file.txt and output all valid phone numbers to stdout. +# Using grep: +grep -P '^(\d{3}-|\(\d{3}\) )\d{3}-\d{4}$' file.txt + +# Using sed: +sed -n -E '/^([0-9]{3}-|\([0-9]{3}\) )[0-9]{3}-[0-9]{4}$/p' file.txt + +# Using awk: +awk '/^([0-9]{3}-|\([0-9]{3}\) )[0-9]{3}-[0-9]{4}$/' file.txt diff --git a/Shell/word-frequency.sh b/Shell/word-frequency.sh new file mode 100644 index 000000000..1775f0504 --- /dev/null +++ b/Shell/word-frequency.sh @@ -0,0 +1,29 @@ +# Time: O(n) +# Space: O(k), k is number of words +# +# Write a bash script to calculate the frequency of each word in a text file words.txt. +# +# For simplicity sake, you may assume: +# +# words.txt contains only lowercase characters and +# space ' ' characters. +# Each word must consist of lowercase characters only. +# Words are separated by one or more whitespace characters. +# For example, assume that words.txt has the following content: +# +# the day is sunny the the +# the sunny is is +# Your script should output the following, +# sorted by descending frequency: +# the 4 +# is 3 +# sunny 2 +# day 1 +# Note: +# Don't worry about handling ties, +# it is guaranteed that each word's frequency count is unique. +# + +# Read from the file words.txt and output the word frequency list to stdout. +awk '{for(i=1;i<=NF;i++) a[$i]++} END {for(k in a) print k,a[k]}' words.txt | sort -k2 -nr + From cadd4ce23b19aa8e2473c18e2ae437dd02d125de Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 1 Apr 2015 23:51:55 +0800 Subject: [PATCH 134/345] Update README.md --- README.md | 28 ++++++++++++++++++++++++++-- 1 file changed, 26 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index ee2828151..724f12754 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ LeetCode ======== -Up to date (2015-04-01), there are total `198` problems on [LeetCode Online Judge](https://oj.leetcode.com/). +Up to date (2015-04-01), there are 182 algorithm / 12 database / 4 shell problems on [LeetCode Online Judge](https://oj.leetcode.com/). The number of problems is increasing recently. -Here is the classification of all `192` problems. +Here is the classification of all `198` problems. I'll keep updating for full summary and better solutions. Stay tuned for updates. --- @@ -37,6 +37,12 @@ Database * [SQL](https://github.com/kamyu104/LeetCode#sql) + +Shell +=== + +* [Shell](https://github.com/kamyu104/LeetCode#shell) + --- ##Bit Manipulation @@ -768,3 +774,21 @@ Problem | Solution | Time | Space | Difficul [Second Highest Salary]:https://oj.leetcode.com/problems/second-highest-salary/ [second-highest-salary.sql]:https://github.com/kamyu104/LeetCode/blob/master/MySQL/second-highest-salary.sql +--- + +##Shell +Problem | Solution | Time | Space | Difficulty | Notes +--------------- | --------------- | --------------- | --------------- | -------------- | ----- +[Tenth Line] | [tenth-line.sh] | _O(n)_ | _O(1)_ | Easy | +[Transpose File] | [transpose-file.sh] | _O(n^2)_ | _O(n^2)_ | Medium | +[Valid Phone Numbers] | [valid-phone-numbers.sh] | _O(n)_ | _O(1)_ | Easy | +[Word Frequency] | [word-frequency.sh] | _O(n)_ | _O(k)_ | Medium | + +[Tenth Line]:https://oj.leetcode.com/problems/tenth-line/ +[tenth-line.sh]:https://github.com/kamyu104/LeetCode/blob/master/Shell/tenth-line.sh +[Transpose File]:https://oj.leetcode.com/problems/transpose-file/ +[transpose-file.sh]:https://github.com/kamyu104/LeetCode/blob/master/Shell/transpose-file.sh +[Valid Phone Numbers]:https://oj.leetcode.com/problems/valid-phone-numbers/ +[valid-phone-numbers.sh]:https://github.com/kamyu104/LeetCode/blob/master/Shell/valid-phone-numbers.sh +[Word Frequency]:https://oj.leetcode.com/problems/word-frequency/ +[word-frequency.sh]:https://github.com/kamyu104/LeetCode/blob/master/Shell/word-frequency.sh From 6b219f9cbd5dd56cf870a12d7c7d2c9d9f7d8954 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 1 Apr 2015 23:58:36 +0800 Subject: [PATCH 135/345] Update README.md --- README.md | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 724f12754..3e3840a83 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ LeetCode ======== -Up to date (2015-04-01), there are 182 algorithm / 12 database / 4 shell problems on [LeetCode Online Judge](https://oj.leetcode.com/). +Up to date (2015-04-01), there are `182` Algorithm / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://oj.leetcode.com/). The number of problems is increasing recently. Here is the classification of all `198` problems. I'll keep updating for full summary and better solutions. Stay tuned for updates. @@ -745,12 +745,14 @@ Problem | Solution | Time | Space | Difficul [Combine Two Tables] | [combine-two-tables.sql] | _O(m + n)_ | _O(m + n)_ | Easy | [Consecutive Numbers] | [consecutive-numbers.sql] | _O(n)_ | _O(n)_ | Medium | [Customers Who Never Order] | [customers-who-never-order.sql] | _O(n^2)_ | _O(1)_ | Easy | +[Delete Duplicate Emails] | [delete-duplicate-emails.sql] | _O(n^2)_ | _O(n)_ | Easy | [Department Highest Salary] | [department-highest-salary.sql] | _O(n^2)_ | _O(n)_ | Medium | [Department Top Three Salaries] | [department-top-three-salaries.sql] | _O(n^2)_ | _O(n)_ | Hard | [Duplicate Emails] | [duplicate-emails.sql] | _O(n^2)_ | _O(n)_ | Easy | [Employees Earning More Than Their Managers] | [employees-earning-more-than-their-managers.sql] | _O(n^2)_ | _O(1)_ | Easy | [Nth Highest Salary] | [nth-highest-salary.sql] | _O(n^2)_ | _O(n)_ | Medium | [Rank Scores] | [rank-scores.sql] | _O(n^2)_ | _O(n)_ | Medium | +[Rising Temperature] | [customers-who-never-order.sql] | _O(n^2)_ | _O(n)_ | Easy | [Second Highest Salary] | [second-highest-salary.sql] | _O(n)_ | _O(1)_ | Easy | [Combine Two Tables]:https://oj.leetcode.com/problems/combine-two-tables/ @@ -759,6 +761,8 @@ Problem | Solution | Time | Space | Difficul [consecutive-numbers.sql]:https://github.com/kamyu104/LeetCode/blob/master/MySQL/consecutive-numbers.sql [Customers Who Never Order]:https://oj.leetcode.com/problems/customers-who-never-order/ [customers-who-never-order.sql]:https://github.com/kamyu104/LeetCode/blob/master/MySQL/customers-who-never-order.sql +[Delete Duplicate Emails]:https://oj.leetcode.com/problems/delete-duplicate-emails/ +[delete-duplicate-emails.sql]:https://github.com/kamyu104/LeetCode/blob/master/MySQL/delete-duplicate-emails.sql [Department Highest Salary]:https://oj.leetcode.com/problems/department-highest-salary/ [department-highest-salary.sql]:https://github.com/kamyu104/LeetCode/blob/master/MySQL/department-highest-salary.sql [Department Top Three Salaries]:https://oj.leetcode.com/problems/department-top-three-salaries/ @@ -771,6 +775,8 @@ Problem | Solution | Time | Space | Difficul [nth-highest-salary.sql]:https://github.com/kamyu104/LeetCode/blob/master/MySQL/nth-highest-salary.sql [Rank Scores]:https://oj.leetcode.com/problems/rank-scores/ [rank-scores.sql]:https://github.com/kamyu104/LeetCode/blob/master/MySQL/rank-scores.sql +[Rising Temperature]:https://oj.leetcode.com/problems/rising-temperature/ +[rising-temperature.sql]:https://github.com/kamyu104/LeetCode/blob/master/MySQL/rising-temperature.sql [Second Highest Salary]:https://oj.leetcode.com/problems/second-highest-salary/ [second-highest-salary.sql]:https://github.com/kamyu104/LeetCode/blob/master/MySQL/second-highest-salary.sql From f77426926da5c877a4ee82e7e77ddfe901304e70 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 1 Apr 2015 23:59:27 +0800 Subject: [PATCH 136/345] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 3e3840a83..47e32f3bd 100644 --- a/README.md +++ b/README.md @@ -752,7 +752,7 @@ Problem | Solution | Time | Space | Difficul [Employees Earning More Than Their Managers] | [employees-earning-more-than-their-managers.sql] | _O(n^2)_ | _O(1)_ | Easy | [Nth Highest Salary] | [nth-highest-salary.sql] | _O(n^2)_ | _O(n)_ | Medium | [Rank Scores] | [rank-scores.sql] | _O(n^2)_ | _O(n)_ | Medium | -[Rising Temperature] | [customers-who-never-order.sql] | _O(n^2)_ | _O(n)_ | Easy | +[Rising Temperature] | [rising-temperature.sql] | _O(n^2)_ | _O(n)_ | Easy | [Second Highest Salary] | [second-highest-salary.sql] | _O(n)_ | _O(1)_ | Easy | [Combine Two Tables]:https://oj.leetcode.com/problems/combine-two-tables/ From e27043c0459fe8047296ae74fd42555b0e69e9b1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 2 Apr 2015 00:02:31 +0800 Subject: [PATCH 137/345] Update README.md --- README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 47e32f3bd..457ae57e5 100644 --- a/README.md +++ b/README.md @@ -1,13 +1,13 @@ LeetCode ======== -Up to date (2015-04-01), there are `182` Algorithm / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://oj.leetcode.com/). +Up to date (2015-04-01), there are `182` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://oj.leetcode.com/). The number of problems is increasing recently. Here is the classification of all `198` problems. I'll keep updating for full summary and better solutions. Stay tuned for updates. --- -Algorithm +Algorithms ==== * [Bit Manipulation](https://github.com/kamyu104/LeetCode#bit-manipulation) @@ -41,7 +41,7 @@ Database Shell === -* [Shell](https://github.com/kamyu104/LeetCode#shell) +* [Bash](https://github.com/kamyu104/LeetCode#bash) --- @@ -782,7 +782,7 @@ Problem | Solution | Time | Space | Difficul --- -##Shell +##Bash Problem | Solution | Time | Space | Difficulty | Notes --------------- | --------------- | --------------- | --------------- | -------------- | ----- [Tenth Line] | [tenth-line.sh] | _O(n)_ | _O(1)_ | Easy | From b71dd3e94eb5d7a73ee50f9cb997d112f6e76e76 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 2 Apr 2015 00:03:47 +0800 Subject: [PATCH 138/345] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 457ae57e5..c82e22458 100644 --- a/README.md +++ b/README.md @@ -41,7 +41,7 @@ Database Shell === -* [Bash](https://github.com/kamyu104/LeetCode#bash) +* [Shell Script](https://github.com/kamyu104/LeetCode#shell-script) --- @@ -782,7 +782,7 @@ Problem | Solution | Time | Space | Difficul --- -##Bash +##Shell Script Problem | Solution | Time | Space | Difficulty | Notes --------------- | --------------- | --------------- | --------------- | -------------- | ----- [Tenth Line] | [tenth-line.sh] | _O(n)_ | _O(1)_ | Easy | From 8ed1e1828223ed2a198b93172b615c1ff4b4904e Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 6 Apr 2015 23:14:32 +0800 Subject: [PATCH 139/345] Create binary-tree-right-side-view.py --- Python/binary-tree-right-side-view.py | 43 +++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 Python/binary-tree-right-side-view.py diff --git a/Python/binary-tree-right-side-view.py b/Python/binary-tree-right-side-view.py new file mode 100644 index 000000000..17805d36f --- /dev/null +++ b/Python/binary-tree-right-side-view.py @@ -0,0 +1,43 @@ +# Time: O(n) +# Space: O(n) +# +# Given a binary tree, imagine yourself standing on the right side of it, +# return the values of the nodes you can see ordered from top to bottom. +# +# For example: +# Given the following binary tree, +# 1 <--- +# / \ +# 2 3 <--- +# \ \ +# 5 4 <--- +# You should return [1, 3, 4]. +# + +# Definition for a binary tree node +# class TreeNode: +# def __init__(self, x): +# self.val = x +# self.left = None +# self.right = None + +class Solution: + # @param root, a tree node + # @return a list of integers + def rightSideView(self, root): + if root is None: + return [] + + result, current = [], [root] + while current: + next_level = [] + for i, node in enumerate(current): + if node.left: + next_level.append(node.left) + if node.right: + next_level.append(node.right) + if i == len(current) - 1: + result.append(node.val) + current = next_level + + return result From 0d7ce51e998e31dc7dbf7762ac4b75b346eba28d Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 6 Apr 2015 23:21:56 +0800 Subject: [PATCH 140/345] Update binary-tree-right-side-view.py --- Python/binary-tree-right-side-view.py | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/Python/binary-tree-right-side-view.py b/Python/binary-tree-right-side-view.py index 17805d36f..5af646f51 100644 --- a/Python/binary-tree-right-side-view.py +++ b/Python/binary-tree-right-side-view.py @@ -41,3 +41,12 @@ def rightSideView(self, root): current = next_level return result + +if __name__ == "__main__": + root = TreeNode(1) + root.left = TreeNode(2) + root.right = TreeNode(3) + root.left.right = TreeNode(5) + root.right.right = TreeNode(4) + result = Solution().rightSideView(root) + print result From 57823681dcb5505c661bd2e632508bf484cabe7a Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 6 Apr 2015 23:27:43 +0800 Subject: [PATCH 141/345] Update README.md --- README.md | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index c82e22458..1925a6adb 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ LeetCode ======== -Up to date (2015-04-01), there are `182` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://oj.leetcode.com/). +Up to date (2015-04-04), there are `183` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://oj.leetcode.com/). The number of problems is increasing recently. -Here is the classification of all `198` problems. +Here is the classification of all `199` problems. I'll keep updating for full summary and better solutions. Stay tuned for updates. --- @@ -555,7 +555,8 @@ Problem | Solution | Time | Space | Difficul Problem | Solution | Time | Space | Difficulty | Notes --------------- | --------------- | --------------- | --------------- | -------------- | ----- [Binary Tree Level Order Traversal]| [binary-tree-level-order-traversal.py] | _O(n)_| _O(n)_| Easy | -[Binary Tree Level Order Traversal II]| [binary-tree-level-order-traversal-ii.py] | _O(n)_| _O(n)_| Easy | +[Binary Tree Level Order Traversal II]| [binary-tree-level-order-traversal-ii.py] | _O(n)_| _O(n)_| Easy | +[Binary Tree Right Side View] | [binary-tree-right-side-view.py] | _O(n)_ | _O(n)_ | Medium | [Binary Tree Zigzag Level Order Traversal]| [binary-tree-zigzag-level-order-traversal.py] | _O(n)_| _O(n)_| Medium | [Clone Graph]| [clone-graph.py] | _O(n)_ | _O(n)_ | Medium | [Populating Next Right Pointers in Each Node II]|[populating-next-right-pointers-in-each-node-ii.py]| _O(n)_ | _O(1)_ | Hard | @@ -564,6 +565,8 @@ Problem | Solution | Time | Space | Difficul [Binary Tree Level Order Traversal]:https://oj.leetcode.com/problems/binary-tree-level-order-traversal/ [binary-tree-level-order-traversal.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/binary-tree-level-order-traversal.py +[Binary Tree Right Side View]:https://oj.leetcode.com/problems/binary-tree-right-side-view/ +[binary-tree-right-side-view.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/binary-tree-right-side-view.py [Binary Tree Level Order Traversal II]:https://oj.leetcode.com/problems/binary-tree-level-order-traversal-ii/ [binary-tree-level-order-traversal-ii.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/binary-tree-level-order-traversal-ii.py [Binary Tree Zigzag Level Order Traversal]:https://oj.leetcode.com/problems/binary-tree-zigzag-level-order-traversal/ From 8111d7abba4663f2db6262d30d894776a3fb3b24 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 6 Apr 2015 23:39:16 +0800 Subject: [PATCH 142/345] Update binary-tree-right-side-view.py --- Python/binary-tree-right-side-view.py | 23 ++++++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/Python/binary-tree-right-side-view.py b/Python/binary-tree-right-side-view.py index 5af646f51..460ccf9ee 100644 --- a/Python/binary-tree-right-side-view.py +++ b/Python/binary-tree-right-side-view.py @@ -1,5 +1,5 @@ # Time: O(n) -# Space: O(n) +# Space: O(h) # # Given a binary tree, imagine yourself standing on the right side of it, # return the values of the nodes you can see ordered from top to bottom. @@ -22,6 +22,27 @@ # self.right = None class Solution: + # @param root, a tree node + # @return a list of integers + def rightSideView(self, root): + result = [] + self.rightSideViewDFS(root, 1, result) + return result + + def rightSideViewDFS(self, node, depth, result): + if not node: + return + + if depth > len(result): + result.append(node.val) + + self.rightSideViewDFS(node.right, depth+1, result) + self.rightSideViewDFS(node.left, depth+1, result) + +# BFS solution +# Time: O(n) +# Space: O(n) +class Solution2: # @param root, a tree node # @return a list of integers def rightSideView(self, root): From 66b8cdaaf23f0e24b4d3ffcc60cd8aeacaa608b3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 6 Apr 2015 23:41:35 +0800 Subject: [PATCH 143/345] Update README.md --- README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 1925a6adb..c5c84a491 100644 --- a/README.md +++ b/README.md @@ -555,8 +555,7 @@ Problem | Solution | Time | Space | Difficul Problem | Solution | Time | Space | Difficulty | Notes --------------- | --------------- | --------------- | --------------- | -------------- | ----- [Binary Tree Level Order Traversal]| [binary-tree-level-order-traversal.py] | _O(n)_| _O(n)_| Easy | -[Binary Tree Level Order Traversal II]| [binary-tree-level-order-traversal-ii.py] | _O(n)_| _O(n)_| Easy | -[Binary Tree Right Side View] | [binary-tree-right-side-view.py] | _O(n)_ | _O(n)_ | Medium | +[Binary Tree Level Order Traversal II]| [binary-tree-level-order-traversal-ii.py] | _O(n)_| _O(n)_| Easy | [Binary Tree Zigzag Level Order Traversal]| [binary-tree-zigzag-level-order-traversal.py] | _O(n)_| _O(n)_| Medium | [Clone Graph]| [clone-graph.py] | _O(n)_ | _O(n)_ | Medium | [Populating Next Right Pointers in Each Node II]|[populating-next-right-pointers-in-each-node-ii.py]| _O(n)_ | _O(1)_ | Hard | @@ -565,8 +564,6 @@ Problem | Solution | Time | Space | Difficul [Binary Tree Level Order Traversal]:https://oj.leetcode.com/problems/binary-tree-level-order-traversal/ [binary-tree-level-order-traversal.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/binary-tree-level-order-traversal.py -[Binary Tree Right Side View]:https://oj.leetcode.com/problems/binary-tree-right-side-view/ -[binary-tree-right-side-view.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/binary-tree-right-side-view.py [Binary Tree Level Order Traversal II]:https://oj.leetcode.com/problems/binary-tree-level-order-traversal-ii/ [binary-tree-level-order-traversal-ii.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/binary-tree-level-order-traversal-ii.py [Binary Tree Zigzag Level Order Traversal]:https://oj.leetcode.com/problems/binary-tree-zigzag-level-order-traversal/ @@ -585,6 +582,7 @@ Problem | Solution | Time | Space | Difficul ##Depth-First Search Problem | Solution | Time | Space | Difficulty | Notes --------------- | --------------- | --------------- | --------------- | -------------- | ----- +[Binary Tree Right Side View] | [binary-tree-right-side-view.py] | _O(n)_ | _O(h)_ | Medium | [Combination Sum]| [combination-sum.py] | _O(n^m)_ | _O(m)_ | Medium | [Combination Sum II]| [combination-sum-ii.py]| _O(n! / m!(n-m)!)_| _O(m)_ | Medium | [Combinations] | [combinations.py] | _O(n!)_ | _O(n)_ | Medium | @@ -598,6 +596,8 @@ Problem | Solution | Time | Space | Difficul [Sudoku Solver] | [sudoku-solver.py] | _O((9!)^9)_ | _O(1)_ | Hard | [Word Search] | [word-search.py] | _O(m * n * 3^p)_ | _O(m * n * p)_ | Medium | +[Binary Tree Right Side View]:https://oj.leetcode.com/problems/binary-tree-right-side-view/ +[binary-tree-right-side-view.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/binary-tree-right-side-view.py [Combination Sum]:https://oj.leetcode.com/problems/combination-sum/ [combination-sum.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/combination-sum.py [Combination Sum II]:https://oj.leetcode.com/problems/combination-sum-ii/ From 857272724b2706245a8ab5de972a505a661b1050 Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Tue, 7 Apr 2015 20:24:15 +0800 Subject: [PATCH 144/345] update --- Python/binary-tree-right-side-view.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/Python/binary-tree-right-side-view.py b/Python/binary-tree-right-side-view.py index 460ccf9ee..56d5e3db2 100644 --- a/Python/binary-tree-right-side-view.py +++ b/Python/binary-tree-right-side-view.py @@ -15,11 +15,11 @@ # # Definition for a binary tree node -# class TreeNode: -# def __init__(self, x): -# self.val = x -# self.left = None -# self.right = None +class TreeNode: + def __init__(self, x): + self.val = x + self.left = None + self.right = None class Solution: # @param root, a tree node From 6b74d22e50304937a4ec029c5ea0020d97e3538e Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 8 Apr 2015 21:45:48 +0800 Subject: [PATCH 145/345] Create number-of-islands.py --- Python/number-of-islands.py | 56 +++++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 Python/number-of-islands.py diff --git a/Python/number-of-islands.py b/Python/number-of-islands.py new file mode 100644 index 000000000..2528d6887 --- /dev/null +++ b/Python/number-of-islands.py @@ -0,0 +1,56 @@ +# Time: O(m * n) +# Space: O(m * n) +# +# Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. +# An island is surrounded by water and is formed by connecting adjacent lands horizontally +# or vertically. You may assume all four edges of the grid are all surrounded by water. +# +# Example 1: +# +# 11110 +# 11010 +# 11000 +# 00000 +# Answer: 1 +# +# Example 2: +# +# 11000 +# 11000 +# 00100 +# 00011 +# Answer: 3 +# + +class Solution: + # @param grid, a list of list of characters + # @return an integer + def numIslands(self, grid): + if grid == []: + return 0 + + row = len(grid) + col = len(grid[0]) + used = [[False for j in xrange(col)] for i in xrange(row)] + + count = 0 + for i in xrange(row): + for j in xrange(col): + if grid[i][j] == '1' and not used[i][j]: + self.dfs(grid, used, row, col, i, j) + count += 1 + return count + + def dfs(self, grid, used, row, col, x, y): + if grid[x][y] == '0' or used[x][y]: + return 0 + used[x][y] = True + + if x != 0: + self.dfs(grid, used, row, col, x - 1, y) + if x != row - 1: + self.dfs(grid, used, row, col, x + 1, y) + if y != 0: + self.dfs(grid, used, row, col, x, y - 1) + if y != col - 1: + self.dfs(grid, used, row, col, x, y + 1) From 09382fb2a69d6f1b4199fad0aca1279b87f9aaee Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 8 Apr 2015 21:51:25 +0800 Subject: [PATCH 146/345] Update README.md --- README.md | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index c5c84a491..88b0b5a44 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ LeetCode ======== -Up to date (2015-04-04), there are `183` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://oj.leetcode.com/). +Up to date (2015-04-09), there are `184` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://oj.leetcode.com/). The number of problems is increasing recently. -Here is the classification of all `199` problems. +Here is the classification of all `200` problems. I'll keep updating for full summary and better solutions. Stay tuned for updates. --- @@ -589,6 +589,7 @@ Problem | Solution | Time | Space | Difficul [Generate Parentheses]| [generate-parentheses.py]| _O(4^n / n^(3/2))_ | _O(n)_ | Medium | [N-Queens] | [n-queens.py] | _O(n!)_ | _O(n)_ | Hard | [N-Queens-II] | [n-queens-ii.py] | _O(n!)_ | _O(n)_ | Hard | +[Number of Islands] | [number-of-islands.py] | _O(n)_ | _O(n)_ | Medium | [Palindrome Partitioning] | [palindrome-partitioning.py] | _O(n^2)_ ~ _O(2^n)_ | _O(n^2)_ | Medium | [Path Sum] | [path-sum.py] | _O(n)_ | _O(h)_ | Easy | [Path Sum II] | [path-sum-ii.py] | _O(n)_ | _O(h)_ | Medium | @@ -610,6 +611,8 @@ Problem | Solution | Time | Space | Difficul [n-queens.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/n-queens.py [N-Queens-II]:https://oj.leetcode.com/problems/n-queens-ii/ [n-queens-ii.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/n-queens-ii.py +[Number of Islands]:https://leetcode.com/problems/number-of-islands/ +[number-of-islands.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/number-of-islands.py [Palindrome Partitioning]:https://oj.leetcode.com/problems/palindrome-partitioning/ [palindrome-partitioning.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/palindrome-partitioning.py [Path Sum]:https://oj.leetcode.com/problems/path-sum/ From c42f0d7c6337184454224778d85ae9f974f8623d Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 8 Apr 2015 22:31:53 +0800 Subject: [PATCH 147/345] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 88b0b5a44..be5284031 100644 --- a/README.md +++ b/README.md @@ -589,7 +589,7 @@ Problem | Solution | Time | Space | Difficul [Generate Parentheses]| [generate-parentheses.py]| _O(4^n / n^(3/2))_ | _O(n)_ | Medium | [N-Queens] | [n-queens.py] | _O(n!)_ | _O(n)_ | Hard | [N-Queens-II] | [n-queens-ii.py] | _O(n!)_ | _O(n)_ | Hard | -[Number of Islands] | [number-of-islands.py] | _O(n)_ | _O(n)_ | Medium | +[Number of Islands] | [number-of-islands.py] | _O(m * n)_ | _O(m * n)_| Medium | [Palindrome Partitioning] | [palindrome-partitioning.py] | _O(n^2)_ ~ _O(2^n)_ | _O(n^2)_ | Medium | [Path Sum] | [path-sum.py] | _O(n)_ | _O(h)_ | Easy | [Path Sum II] | [path-sum-ii.py] | _O(n)_ | _O(h)_ | Medium | From beec39a47e9d83c2ebf5ba60f3c52e42e9670f4c Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 18 Apr 2015 02:19:28 +0800 Subject: [PATCH 148/345] Create bitwise-and-of-numbers-range.py --- Python/bitwise-and-of-numbers-range.py | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 Python/bitwise-and-of-numbers-range.py diff --git a/Python/bitwise-and-of-numbers-range.py b/Python/bitwise-and-of-numbers-range.py new file mode 100644 index 000000000..156dbbb3a --- /dev/null +++ b/Python/bitwise-and-of-numbers-range.py @@ -0,0 +1,21 @@ +# Time: O(1) +# Space: O(1) +# +# Given a range [m, n] where 0 <= m <= n <= 2147483647, +# return the bitwise AND of all numbers in this range, inclusive. +# +# For example, given the range [5, 7], you should return 4. +# + +class Solution: + # @param m, an integer + # @param n, an integer + # @return an integer + def rangeBitwiseAnd(self, m, n): + i = 0 + while n-m >> i: + i += 1 + return n&m >> i << i + +if __name__ == '__main__': + print Solution().rangeBitwiseAnd(5, 7) From 3b3ac47f1d51fcaf67169da95661ab9d118ad89b Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 18 Apr 2015 02:23:23 +0800 Subject: [PATCH 149/345] Update README.md --- README.md | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index be5284031..0f705a401 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ LeetCode ======== -Up to date (2015-04-09), there are `184` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://oj.leetcode.com/). +Up to date (2015-04-17), there are `185` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://oj.leetcode.com/). The number of problems is increasing recently. -Here is the classification of all `200` problems. +Here is the classification of all `201` problems. I'll keep updating for full summary and better solutions. Stay tuned for updates. --- @@ -50,6 +50,7 @@ Problem | Solution | Time | Space | Difficul --------------- | --------------- | --------------- | --------------- | -------------- | ----- [Number of 1 Bits] | [number-of-1-bits.py] | _O(m)_ | _O(1)_ | Easy | [Reverse Bits] | [reverse-bits.py] | _O(n)_ | _O(1)_ | Easy | +[Bitwise AND of Numbers Range] | [bitwise-and-of-numbers-range.py] | _O(1)_ | _O(1)_ | Medium | [Single Number] | [single-number.py] | _O(n)_ | _O(1)_ | Medium | [Single Number II] | [single-number-ii.py] | _O(n)_ | _O(1)_ | Medium | @@ -57,6 +58,8 @@ Problem | Solution | Time | Space | Difficul [number-of-1-bits.py]: https://github.com/kamyu104/LeetCode/blob/master/Python/number-of-1-bits.py [Reverse Bits]: https://oj.leetcode.com/problems/reverse-bits/ [reverse-bits.py]: https://github.com/kamyu104/LeetCode/blob/master/Python/reverse-bits.py +[Bitwise AND of Numbers Range]: https://leetcode.com/problems/bitwise-and-of-numbers-range/ +[bitwise-and-of-numbers-range.py]: https://github.com/kamyu104/LeetCode/blob/master/bitwise-and-of-numbers-range.py [Single Number]: https://oj.leetcode.com/problems/single-number/ [single-number.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/single-number.py [Single Number II]: https://oj.leetcode.com/problems/single-number-ii/ From 161b1b2f54222d1bf6cb8e2235ef888516b7dbf7 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 18 Apr 2015 02:24:56 +0800 Subject: [PATCH 150/345] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 0f705a401..50db28a69 100644 --- a/README.md +++ b/README.md @@ -59,7 +59,7 @@ Problem | Solution | Time | Space | Difficul [Reverse Bits]: https://oj.leetcode.com/problems/reverse-bits/ [reverse-bits.py]: https://github.com/kamyu104/LeetCode/blob/master/Python/reverse-bits.py [Bitwise AND of Numbers Range]: https://leetcode.com/problems/bitwise-and-of-numbers-range/ -[bitwise-and-of-numbers-range.py]: https://github.com/kamyu104/LeetCode/blob/master/bitwise-and-of-numbers-range.py +[bitwise-and-of-numbers-range.py]: https://github.com/kamyu104/LeetCode/blob/master/Python/bitwise-and-of-numbers-range.py [Single Number]: https://oj.leetcode.com/problems/single-number/ [single-number.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/single-number.py [Single Number II]: https://oj.leetcode.com/problems/single-number-ii/ From 596cb4ab4338b13a38af28ab8bc14e0b2e3ea09b Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 18 Apr 2015 02:29:10 +0800 Subject: [PATCH 151/345] Update bitwise-and-of-numbers-range.py --- Python/bitwise-and-of-numbers-range.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/Python/bitwise-and-of-numbers-range.py b/Python/bitwise-and-of-numbers-range.py index 156dbbb3a..f8b269d22 100644 --- a/Python/bitwise-and-of-numbers-range.py +++ b/Python/bitwise-and-of-numbers-range.py @@ -12,8 +12,9 @@ class Solution: # @param n, an integer # @return an integer def rangeBitwiseAnd(self, m, n): - i = 0 - while n-m >> i: + i, diff = 0, n-m + while diff: + diff >>= 1 i += 1 return n&m >> i << i From f4ebc5058985946f692512a24d01d4b6763bb7cf Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 19 Apr 2015 15:10:55 +0800 Subject: [PATCH 152/345] Update find-peak-element.py --- Python/find-peak-element.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/Python/find-peak-element.py b/Python/find-peak-element.py index 84eb19221..1fe1ac83b 100644 --- a/Python/find-peak-element.py +++ b/Python/find-peak-element.py @@ -30,10 +30,9 @@ def findPeakElement(self, num): high = mid - 1 else: low = mid + 1 - mid = low + (high - low) / 2 return low if __name__ == "__main__": # print Solution().findPeakElement([1,2,1]) - print Solution().findPeakElement([1,2,3, 1]) \ No newline at end of file + print Solution().findPeakElement([1,2,3, 1]) From 8367b081a8151a1cf202027eb8ed7ac49ef8ebb2 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 19 Apr 2015 16:15:34 +0800 Subject: [PATCH 153/345] Update search-for-a-range.py --- Python/search-for-a-range.py | 20 ++++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) diff --git a/Python/search-for-a-range.py b/Python/search-for-a-range.py index 505961eed..3ac30c348 100644 --- a/Python/search-for-a-range.py +++ b/Python/search-for-a-range.py @@ -17,10 +17,12 @@ class Solution: # @param target, an integer to be searched # @return a list of length 2, [index1, index2] def searchRange(self, A, target): - left = self.binarySearch(lambda x, y: x > y, A, target) + # Find the first index where target <= A[idx] + left = self.binarySearch(lambda x, y: x <= y, A, target) if left >= len(A) or A[left] != target: return [-1, -1] - right = self.binarySearch(lambda x, y: x >= y, A, target) + # Find the first index where target < A[idx] + right = self.binarySearch(lambda x, y: x < y, A, target) return [left, right - 1] def binarySearch(self, compare, A, target): @@ -28,11 +30,21 @@ def binarySearch(self, compare, A, target): while start < end: mid = start + (end - start) / 2 if compare(target, A[mid]): + end = mid + else: start = mid + 1 + return start + + def binarySearch2(self, compare, A, target): + start, end = 0, len(A) - 1 + while start <= end: + mid = start + (end - start) / 2 + if compare(target, A[mid]): + end = mid - 1 else: - end = mid + start = mid + 1 return start if __name__ == "__main__": print Solution().searchRange([2, 2], 3) - print Solution().searchRange([5, 7, 7, 8, 8, 10], 8) \ No newline at end of file + print Solution().searchRange([5, 7, 7, 8, 8, 10], 8) From 0ad1d70d3ae1e7efae953945d227000f61e902a5 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 19 Apr 2015 22:55:19 +0800 Subject: [PATCH 154/345] Update search-for-a-range.py --- Python/search-for-a-range.py | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/Python/search-for-a-range.py b/Python/search-for-a-range.py index 3ac30c348..6e6c84d7b 100644 --- a/Python/search-for-a-range.py +++ b/Python/search-for-a-range.py @@ -44,6 +44,16 @@ def binarySearch2(self, compare, A, target): else: start = mid + 1 return start + + def binarySearch3(self, compare, A, target): + start, end = -1, len(A) + while end - start > 1: + mid = start + (end - start) / 2 + if compare(target, A[mid]): + end = mid + else: + start = mid + return end if __name__ == "__main__": print Solution().searchRange([2, 2], 3) From 5ef7272ac213bb33824de84508c0f5e567e3f5e7 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 19 Apr 2015 22:55:57 +0800 Subject: [PATCH 155/345] Update search-for-a-range.py --- Python/search-for-a-range.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/search-for-a-range.py b/Python/search-for-a-range.py index 6e6c84d7b..3a77a0a9e 100644 --- a/Python/search-for-a-range.py +++ b/Python/search-for-a-range.py @@ -46,7 +46,7 @@ def binarySearch2(self, compare, A, target): return start def binarySearch3(self, compare, A, target): - start, end = -1, len(A) + start, end = -1, len(A) - 1 while end - start > 1: mid = start + (end - start) / 2 if compare(target, A[mid]): From cdfc802af6226c7d9be48b789c6e6f878c970da7 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 19 Apr 2015 23:18:46 +0800 Subject: [PATCH 156/345] Update search-for-a-range.py --- Python/search-for-a-range.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/Python/search-for-a-range.py b/Python/search-for-a-range.py index 3a77a0a9e..4bc2e72cb 100644 --- a/Python/search-for-a-range.py +++ b/Python/search-for-a-range.py @@ -17,6 +17,9 @@ class Solution: # @param target, an integer to be searched # @return a list of length 2, [index1, index2] def searchRange(self, A, target): + # This is main For binarySearch3() + A += [float("inf")] + # Find the first index where target <= A[idx] left = self.binarySearch(lambda x, y: x <= y, A, target) if left >= len(A) or A[left] != target: From 9e83351f1f8d54eedf133b4cfef5886034644159 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 19 Apr 2015 23:34:25 +0800 Subject: [PATCH 157/345] Update search-for-a-range.py --- Python/search-for-a-range.py | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/Python/search-for-a-range.py b/Python/search-for-a-range.py index 4bc2e72cb..6e6c84d7b 100644 --- a/Python/search-for-a-range.py +++ b/Python/search-for-a-range.py @@ -17,9 +17,6 @@ class Solution: # @param target, an integer to be searched # @return a list of length 2, [index1, index2] def searchRange(self, A, target): - # This is main For binarySearch3() - A += [float("inf")] - # Find the first index where target <= A[idx] left = self.binarySearch(lambda x, y: x <= y, A, target) if left >= len(A) or A[left] != target: @@ -49,7 +46,7 @@ def binarySearch2(self, compare, A, target): return start def binarySearch3(self, compare, A, target): - start, end = -1, len(A) - 1 + start, end = -1, len(A) while end - start > 1: mid = start + (end - start) / 2 if compare(target, A[mid]): From e81f4462c54578cdbaf4c8e1e8a80521ffa90105 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 23 Apr 2015 03:28:05 +0800 Subject: [PATCH 158/345] Create happy-number.py --- Python/happy-number.py | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 Python/happy-number.py diff --git a/Python/happy-number.py b/Python/happy-number.py new file mode 100644 index 000000000..7ea4a5675 --- /dev/null +++ b/Python/happy-number.py @@ -0,0 +1,34 @@ +# Time: O(k), where k is the steps to be happy number +# Space: O(k) +# +# Write an algorithm to determine if a number is "happy". +# +# A happy number is a number defined by the following process: +# Starting with any positive integer, replace the number by the sum +# of the squares of its digits, and repeat the process until +# the number equals 1 (where it will stay), or it loops endlessly +# in a cycle which does not include 1. Those numbers for which +# this process ends in 1 are happy numbers. +# +# Example: 19 is a happy number +# +# 1^2 + 9^2 = 82 +# 8^2 + 2^2 = 68 +# 6^2 + 8^2 = 100 +# 1^2 + 0^2 + 0^2 = 1 +# +class Solution: + # @param {integer} n + # @return {boolean} + def isHappy(self, n): + lookup = {} + while n != 1 and n not in lookup: + lookup[n] = True + n = self.nextNumber(n) + return n == 1 + + def nextNumber(self, n): + new = 0 + for char in str(n): + new += int(char)**2 + return new From 4a7a0e8611e1889c08905060e76de9d469739975 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 23 Apr 2015 03:30:22 +0800 Subject: [PATCH 159/345] Update README.md --- README.md | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 50db28a69..e31adb967 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ LeetCode ======== -Up to date (2015-04-17), there are `185` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://oj.leetcode.com/). +Up to date (2015-04-22), there are `186` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://oj.leetcode.com/). The number of problems is increasing recently. -Here is the classification of all `201` problems. +Here is the classification of all `202` problems. I'll keep updating for full summary and better solutions. Stay tuned for updates. --- @@ -289,6 +289,7 @@ Problem | Solution | Time | Space | Difficul --------------- | --------------- | --------------- | --------------- | -------------- | ----- [4 Sum] |[4sum.py] | _O(n^2)_ ~ _O(n^4)_ | _O(n^2)_ | Medium | [Anagrams] | [anagrams.py] | _O(n)_ | _O(n)_ | Medium | +[Happy Number] | [happy-number.py] | _O(k)_ | _O(k)_ | Easy | [Longest Substring with At Most Two Distinct Characters]| [longest-substring-with-at-most-two-distinct-characters.py] | _O(n^2)_ | _O(1)_ | Hard | [Longest Substring Without Repeating Characters] | [longest-substring-without-repeating-characters.py] | _O(n)_ | _O(1)_ | Medium | [Max Points on a Line] | [max-points-on-a-line.py] | _O(n^2)_ | _O(n)_ | Hard | @@ -303,6 +304,8 @@ Problem | Solution | Time | Space | Difficul [4sum.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/4sum.py [Anagrams]:https://oj.leetcode.com/problems/anagrams/ [anagrams.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/anagrams.py +[Happy Number]:https://oj.leetcode.com/problems/happy-number/ +[happy-number.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/happy-number.py [Longest Substring with At Most Two Distinct Characters]:https://oj.leetcode.com/problems/longest-substring-with-at-most-two-distinct-characters/ [longest-substring-with-at-most-two-distinct-characters.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/longest-substring-with-at-most-two-distinct-characters.py [Longest Substring Without Repeating Characters]:https://oj.leetcode.com/problems/longest-substring-without-repeating-characters/ From eceacfc149948c6d5c618e8ec609c05de66d939d Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 24 Apr 2015 04:07:42 +0800 Subject: [PATCH 160/345] Update largest-number.py --- Python/largest-number.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/largest-number.py b/Python/largest-number.py index ab28367cf..8317a617b 100644 --- a/Python/largest-number.py +++ b/Python/largest-number.py @@ -1,5 +1,5 @@ -# Time: O(n^2) -# Space: O(n) +# Time: O(nlogn) +# Space: O(1) # # Given a list of non negative integers, arrange them such that they form the largest number. # From 9481800a9393b961609bbc5fdeb3683c93b43a63 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 24 Apr 2015 04:08:18 +0800 Subject: [PATCH 161/345] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index e31adb967..27106b673 100644 --- a/README.md +++ b/README.md @@ -387,7 +387,7 @@ Problem | Solution | Time | Space | Difficul --------------- | --------------- | --------------- | --------------- | -------------- | ----- [Insert Interval]| [insert-interval.py] | _O(n)_ | _O(1)_ | Hard | [Insertion Sort List]|[insertion-sort-list.py] | _O(n^2)_ | _O(1)_ | Medium | -[Largest Number] | [largest-number.py] | _O(n^2)_ | _O(n)_ | Medium | +[Largest Number] | [largest-number.py] | _O(nlogn)_ | _O(1)_ | Medium | [Maximum Gap] | [maximum-gap.py]| _O(n)_ | _O(n)_ | Hard | Tricky [Merge Intervals]| [merge-intervals.py] | _O(nlogn)_ | _O(1)_ | Hard | [Merge Sorted Array]| [merge-sorted-array.py] | _O(n)_ | _O(1)_ | Easy | From 3bd7a31356e6cca1d82f71985ad886c93277989d Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 24 Apr 2015 04:14:37 +0800 Subject: [PATCH 162/345] Create remove-linked-list-elements.py --- Python/remove-linked-list-elements.py | 35 +++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 Python/remove-linked-list-elements.py diff --git a/Python/remove-linked-list-elements.py b/Python/remove-linked-list-elements.py new file mode 100644 index 000000000..347370e88 --- /dev/null +++ b/Python/remove-linked-list-elements.py @@ -0,0 +1,35 @@ +# Time: O(n) +# Space: O(1) +# +# Remove all elements from a linked list of integers that have value val. +# +# Example +# Given: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6 +# Return: 1 --> 2 --> 3 --> 4 --> 5 +# +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, x): +# self.val = x +# self.next = None + +class Solution: + # @param {ListNode} head + # @param {integer} val + # @return {ListNode} + def removeElements(self, head, val): + dummy = ListNode(float("-inf")) + dummy.next = head + prev, curr = dummy, dummy.next + + while curr: + if curr.val == val: + prev.next = curr.next + else: + prev = curr + + curr = curr.next + + return dummy.next + + From ae67deebec189752db71b6aa62391751d7690e6c Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 24 Apr 2015 04:18:13 +0800 Subject: [PATCH 163/345] Update README.md --- README.md | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 27106b673..078e12d4b 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ LeetCode ======== -Up to date (2015-04-22), there are `186` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://oj.leetcode.com/). +Up to date (2015-04-24), there are `187` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://oj.leetcode.com/). The number of problems is increasing recently. -Here is the classification of all `202` problems. +Here is the classification of all `203` problems. I'll keep updating for full summary and better solutions. Stay tuned for updates. --- @@ -201,6 +201,7 @@ Problem | Solution | Time | Space | Difficul [Intersection of Two Linked Lists]| [intersection-of-two-linked-lists.py] | _O(m + n)_ | _O(1)_ | Easy | [Remove Duplicates from Sorted List]| [remove-duplicates-from-sorted-list.py] | _O(n)_ | _O(1)_ | Easy | [Remove Duplicates from Sorted List II]| [remove-duplicates-from-sorted-list-ii.py] | _O(n)_ | _O(1)_ | Medium | +[Remove Linked List Elements]| [remove-linked-list-elements.py] | _O(n)_ | _O(1)_ | Easy | [Reverse Linked List II]| [reverse-linked-list-ii.py] | _O(n)_ | _O(1)_ | Medium | [Reverse Nodes in k-Group]| [reverse-nodes-in-k-group.py] | _O(n)_ | _O(1)_ | Hard | [Rotate List]| [rotate-list.py] | _O(n)_ | _O(1)_ | Medium | @@ -216,6 +217,8 @@ Problem | Solution | Time | Space | Difficul [remove-duplicates-from-sorted-list.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/remove-duplicates-from-sorted-list.py [Remove Duplicates from Sorted List II]:https://oj.leetcode.com/problems/remove-duplicates-from-sorted-list-ii/ [remove-duplicates-from-sorted-list-ii.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/remove-duplicates-from-sorted-list-ii.py +[Remove Linked List Elements]:https://oj.leetcode.com/problems/remove-linked-list-elements/ +[remove-linked-list-elements.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/remove-linked-list-elements.py [Reverse Linked List II]:https://oj.leetcode.com/problems/reverse-linked-list-ii/ [reverse-linked-list-ii.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/reverse-linked-list-ii.py [Reverse Nodes in k-Group]:https://oj.leetcode.com/problems/reverse-nodes-in-k-group/ From e889814bec5c085141a4529f099060e1aa2a1187 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 27 Apr 2015 21:44:52 +0800 Subject: [PATCH 164/345] Create count-primes.py --- Python/count-primes.py | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 Python/count-primes.py diff --git a/Python/count-primes.py b/Python/count-primes.py new file mode 100644 index 000000000..8c3337efd --- /dev/null +++ b/Python/count-primes.py @@ -0,0 +1,30 @@ +# Time: O(n) +# Space: O(n) +# Description: +# +# Count the number of prime numbers less than a non-negative number, n +# +# Hint: The number n could be in the order of 100,000 to 5,000,000. +# + +from math import sqrt + +class Solution: + # @param {integer} n + # @return {integer} + def countPrimes(self, n): + if n <= 2: + return 0 + + is_prime = [True] * n + sqr = sqrt(n - 1) + + num = 0 + for i in xrange(2, n): + if is_prime[i]: + num += 1 + for j in xrange(i+i, n, i): + is_prime[j] = False + + return num + From 80e8090b39c58b9d784c216196a8e6236f98e06d Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 27 Apr 2015 21:48:43 +0800 Subject: [PATCH 165/345] Create count-primes.cpp --- C++/count-primes.cpp | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 C++/count-primes.cpp diff --git a/C++/count-primes.cpp b/C++/count-primes.cpp new file mode 100644 index 000000000..dcafc14bf --- /dev/null +++ b/C++/count-primes.cpp @@ -0,0 +1,36 @@ +// Time: O(n) +// Space: O(n) +// +// Description: +// +// Count the number of prime numbers less than a non-negative number, n +// +// Hint: The number n could be in the order of 100,000 to 5,000,000. +// + +class Solution { +public: + int countPrimes(int n) { + if (2 >= n) { + return 0; + } + bool* primes = new bool[n]; + for (int i = 2; i < n; ++i) + primes[i] = true; + + int sqr = sqrt(n - 1); + int sum = 0; + for (int i = 2; i < n; ++i) { + if (primes[i]) { + ++sum; + for (int j = i + i; j < n; j += i) { + primes[j] = false; + } + } + } + + delete[] primes; + + return sum; + } +}; From 4822a69867ca74b48f242f51058b7971dea51280 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 27 Apr 2015 21:52:23 +0800 Subject: [PATCH 166/345] Update README.md --- README.md | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 078e12d4b..487d225a9 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ LeetCode ======== -Up to date (2015-04-24), there are `187` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://oj.leetcode.com/). +Up to date (2015-04-27), there are `188` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://oj.leetcode.com/). The number of problems is increasing recently. -Here is the classification of all `203` problems. +Here is the classification of all `204` problems. I'll keep updating for full summary and better solutions. Stay tuned for updates. --- @@ -292,7 +292,8 @@ Problem | Solution | Time | Space | Difficul --------------- | --------------- | --------------- | --------------- | -------------- | ----- [4 Sum] |[4sum.py] | _O(n^2)_ ~ _O(n^4)_ | _O(n^2)_ | Medium | [Anagrams] | [anagrams.py] | _O(n)_ | _O(n)_ | Medium | -[Happy Number] | [happy-number.py] | _O(k)_ | _O(k)_ | Easy | +[Count Primes] | [count-primes.py] | _O(n)_ | _O(n)_ | Easy | +[Happy Number] | [happy-number.py] | _O(k)_ | _O(k)_ | Easy | [Longest Substring with At Most Two Distinct Characters]| [longest-substring-with-at-most-two-distinct-characters.py] | _O(n^2)_ | _O(1)_ | Hard | [Longest Substring Without Repeating Characters] | [longest-substring-without-repeating-characters.py] | _O(n)_ | _O(1)_ | Medium | [Max Points on a Line] | [max-points-on-a-line.py] | _O(n^2)_ | _O(n)_ | Hard | @@ -307,6 +308,8 @@ Problem | Solution | Time | Space | Difficul [4sum.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/4sum.py [Anagrams]:https://oj.leetcode.com/problems/anagrams/ [anagrams.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/anagrams.py +[Count Primes]:https://oj.leetcode.com/problems/count-primes/ +[count-primes.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/count-primes.py [Happy Number]:https://oj.leetcode.com/problems/happy-number/ [happy-number.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/happy-number.py [Longest Substring with At Most Two Distinct Characters]:https://oj.leetcode.com/problems/longest-substring-with-at-most-two-distinct-characters/ From 93ab11c2e4dd104b13ecbe5cf4fa0aec700f62ea Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 29 Apr 2015 16:41:48 +0800 Subject: [PATCH 167/345] Create isomorphic-strings.py --- Python/isomorphic-strings.py | 40 ++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 Python/isomorphic-strings.py diff --git a/Python/isomorphic-strings.py b/Python/isomorphic-strings.py new file mode 100644 index 000000000..d65bdb00d --- /dev/null +++ b/Python/isomorphic-strings.py @@ -0,0 +1,40 @@ +# Time: O(n) +# Space: O(1) +# +# Given two strings s and t, determine if they are isomorphic. +# +# Two strings are isomorphic if the characters in s can be replaced to get t. +# +# All occurrences of a character must be replaced with another character +# while preserving the order of characters. No two characters may map to +# the same character but a character may map to itself. +# +# For example, +# Given "egg", "add", return true. +# +# Given "foo", "bar", return false. +# +# Given "paper", "title", return true. +# +# Note: +# You may assume both s and t have the same length. +# + +class Solution: + # @param {string} s + # @param {string} t + # @return {boolean} + def isIsomorphic(self, s, t): + if len(s) != len(t): + return False + + return self.halfIsom(s, t) and self.halfIsom(t, s) + + def halfIsom(self, s, t): + res = {} + for i in xrange(len(s)): + if s[i] not in res: + res[s[i]] = t[i] + elif res[s[i]] != t[i]: + return False + return True From a37f346f73ebd97a799898c93d46a6d5014e3044 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 29 Apr 2015 16:45:20 +0800 Subject: [PATCH 168/345] Update README.md --- README.md | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 487d225a9..e6761ef74 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ LeetCode ======== -Up to date (2015-04-27), there are `188` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://oj.leetcode.com/). +Up to date (2015-04-29), there are `189` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://oj.leetcode.com/). The number of problems is increasing recently. -Here is the classification of all `204` problems. +Here is the classification of all `205` problems. I'll keep updating for full summary and better solutions. Stay tuned for updates. --- @@ -147,6 +147,7 @@ Problem | Solution | Time | Space | Difficul [Compare Version Numbers] | [compare-version-numbers.py] | _O(n)_ | _O(1)_ | Easy | [Count and Say] | [count-and-say.py]| _O(n * 2^n)_ | _O(2^n)_ | Easy | [Implement strStr()] | [implement-strstr.py] | _O(n + m)_ | _O(m)_ | Easy | `KMP Algorithm` +[Isomorphic Strings] | [isomorphic-strings.py] | _O(n)_ | _O(1)_ | Easy | [Length of Last Word] | [length-of-last-word.py] | _O(n)_ | _O(1)_ | Easy | [Longest Common Prefix] | [longest-common-prefix.py] | _O(n1 + n2 + ...)_ | _O(1)_ | Easy | [Longest Palindromic Substring] | [longest-palindromic-substring.py] | _O(n)_ | _O(n)_ | Medium | `Manacher's Algorithm` @@ -167,6 +168,8 @@ Problem | Solution | Time | Space | Difficul [compare-version-numbers.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/compare-version-numbers.py [Implement strStr()]:https://oj.leetcode.com/problems/implement-strstr/ [implement-strstr.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/implement-strstr.py +[Isomorphic Strings]:https://oj.leetcode.com/problems/isomorphic-strings/ +[isomorphic-strings.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/isomorphic-strings.py [Length of Last Word]:https://oj.leetcode.com/problems/length-of-last-word/ [length-of-last-word.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/length-of-last-word.py [Longest Common Prefix]:https://oj.leetcode.com/problems/longest-common-prefix/ @@ -175,7 +178,6 @@ Problem | Solution | Time | Space | Difficul [longest-palindromic-substring.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/longest-palindromic-substring.py [Multiply Strings]:https://oj.leetcode.com/problems/multiply-strings/ [multiply-strings.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/multiply-strings.py - [One Edit Distance]:https://oj.leetcode.com/problems/one-edit-distance/ [one-edit-distance.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/one-edit-distance.py [Reverse Words in a String]:https://oj.leetcode.com/problems/reverse-words-in-a-string/ From 1495953a6f7aa2f468a0d3d3366e760e6f8ad1f3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 29 Apr 2015 16:47:17 +0800 Subject: [PATCH 169/345] Create isomorphic-strings.cpp --- C++/isomorphic-strings.cpp | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 C++/isomorphic-strings.cpp diff --git a/C++/isomorphic-strings.cpp b/C++/isomorphic-strings.cpp new file mode 100644 index 000000000..da3e0d495 --- /dev/null +++ b/C++/isomorphic-strings.cpp @@ -0,0 +1,14 @@ +class Solution { +public: + bool isIsomorphic(string s, string t) { + vector m1(256, 0); + vector m2(256, 0); + int n = s.size(); + for (int i = 0; i < n; ++i) { + if (m1[s[i]] != m2[t[i]]) return false; + m1[s[i]] = i + 1; + m2[t[i]] = i + 1; + } + return true; + } +}; From 913fd43a08fce1419e92d2b2cfc79c1ddd9a3b2f Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 29 Apr 2015 16:47:54 +0800 Subject: [PATCH 170/345] Update isomorphic-strings.cpp --- C++/isomorphic-strings.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/C++/isomorphic-strings.cpp b/C++/isomorphic-strings.cpp index da3e0d495..e766cc2b2 100644 --- a/C++/isomorphic-strings.cpp +++ b/C++/isomorphic-strings.cpp @@ -1,6 +1,9 @@ class Solution { public: bool isIsomorphic(string s, string t) { + if (s.length() != t.length()) { + return 0; + } vector m1(256, 0); vector m2(256, 0); int n = s.size(); From fa26f59010dab83a124dea28ba59d9157f60c43d Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 29 Apr 2015 16:48:34 +0800 Subject: [PATCH 171/345] Update isomorphic-strings.cpp --- C++/isomorphic-strings.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/isomorphic-strings.cpp b/C++/isomorphic-strings.cpp index e766cc2b2..de37015b8 100644 --- a/C++/isomorphic-strings.cpp +++ b/C++/isomorphic-strings.cpp @@ -2,7 +2,7 @@ class Solution { public: bool isIsomorphic(string s, string t) { if (s.length() != t.length()) { - return 0; + return false; } vector m1(256, 0); vector m2(256, 0); From f13b445489774bfa19a3cd26f2324c1144c8f481 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 30 Apr 2015 03:23:33 +0800 Subject: [PATCH 172/345] Update word-search.py --- Python/word-search.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/word-search.py b/Python/word-search.py index 434f5dbda..3166d0b00 100644 --- a/Python/word-search.py +++ b/Python/word-search.py @@ -1,5 +1,5 @@ -# Time: O(m * n * 3^p) -# Space: O(m * n + p) +# Time: O(m * n * l) +# Space: O(l) # # Given a 2D board and a word, find if the word exists in the grid. # From d3e2d00d2b6f2bd002d5af48396a542969717f6e Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 30 Apr 2015 03:24:09 +0800 Subject: [PATCH 173/345] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index e6761ef74..3b52250ed 100644 --- a/README.md +++ b/README.md @@ -609,7 +609,7 @@ Problem | Solution | Time | Space | Difficul [Path Sum II] | [path-sum-ii.py] | _O(n)_ | _O(h)_ | Medium | [Restore IP Addresses] | [restore-ip-addresses.py] | _O(n^m)_ ~ _O(3^4)_ | _O(n * m)_ ~ _O(3 * 4)_ | Medium | [Sudoku Solver] | [sudoku-solver.py] | _O((9!)^9)_ | _O(1)_ | Hard | -[Word Search] | [word-search.py] | _O(m * n * 3^p)_ | _O(m * n * p)_ | Medium | +[Word Search] | [word-search.py] | _O(m * n * l)_ | _O(l)_ | Medium | [Binary Tree Right Side View]:https://oj.leetcode.com/problems/binary-tree-right-side-view/ [binary-tree-right-side-view.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/binary-tree-right-side-view.py From 24c62087c183af74cb000e3f79dafb5fb4b6f458 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 1 May 2015 14:23:17 +0800 Subject: [PATCH 174/345] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 3b52250ed..dc1a0266e 100644 --- a/README.md +++ b/README.md @@ -4,6 +4,7 @@ LeetCode Up to date (2015-04-29), there are `189` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://oj.leetcode.com/). The number of problems is increasing recently. Here is the classification of all `205` problems. +For extra problems and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repo. I'll keep updating for full summary and better solutions. Stay tuned for updates. --- From 8d93982fd93d6646be96555c5235f4446713ea07 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 2 May 2015 07:58:46 +0800 Subject: [PATCH 175/345] Update wildcard-matching.py --- Python/wildcard-matching.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/wildcard-matching.py b/Python/wildcard-matching.py index d930727d7..4262a1458 100644 --- a/Python/wildcard-matching.py +++ b/Python/wildcard-matching.py @@ -98,8 +98,8 @@ def isMatch(self, s, p): class Solution4: # @return a boolean def isMatch(self, s, p): - if not p: - return not s + if not p or not s: + return not s and not p if p[0] != '*': if not s or (p[0] == s[0] or p[0] == '?'): From e8db313baa3fafbbf09b17a177be31f23c854136 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 2 May 2015 08:05:08 +0800 Subject: [PATCH 176/345] Update wildcard-matching.py --- Python/wildcard-matching.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/wildcard-matching.py b/Python/wildcard-matching.py index 4262a1458..aeecdaf59 100644 --- a/Python/wildcard-matching.py +++ b/Python/wildcard-matching.py @@ -102,7 +102,7 @@ def isMatch(self, s, p): return not s and not p if p[0] != '*': - if not s or (p[0] == s[0] or p[0] == '?'): + if p[0] == s[0] or p[0] == '?': return self.isMatch(s[1:], p[1:]) else: return False From 124dc3777cbae0c00b0297ce0064964dfd6bdfb1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 2 May 2015 08:05:34 +0800 Subject: [PATCH 177/345] Update wildcard-matching.py --- Python/wildcard-matching.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/wildcard-matching.py b/Python/wildcard-matching.py index aeecdaf59..7965368aa 100644 --- a/Python/wildcard-matching.py +++ b/Python/wildcard-matching.py @@ -94,7 +94,7 @@ def isMatch(self, s, p): return result[len(s)][len(p)] -# recursive, slowest +# recursive, slowest, TLE class Solution4: # @return a boolean def isMatch(self, s, p): From 89d2e86913b5d2a2f4b0a441ac1527b7bfd5cfe5 Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Sat, 2 May 2015 10:51:14 +0800 Subject: [PATCH 178/345] update --- Python/regular-expression-matching.py | 32 ++++++++++++++++++++++++++- 1 file changed, 31 insertions(+), 1 deletion(-) diff --git a/Python/regular-expression-matching.py b/Python/regular-expression-matching.py index 969a92981..67cf4b461 100644 --- a/Python/regular-expression-matching.py +++ b/Python/regular-expression-matching.py @@ -66,8 +66,38 @@ def isMatch(self, s, p): return result[len(s)][len(p)] -# recursive +# iteration class Solution3: + # @return a boolean + def isMatch(self, s, p): + p_ptr, s_ptr, last_s_ptr, last_p_ptr = 0, 0, -1, -1 + last_ptr = [] + while s_ptr < len(s): + if p_ptr < len(p) and (p_ptr == len(p) - 1 or p[p_ptr + 1] != '*') and \ + (s_ptr < len(s) and (p[p_ptr] == s[s_ptr] or p[p_ptr] == '?')): + s_ptr += 1 + p_ptr += 1 + elif p_ptr < len(p) - 1 and (p_ptr != len(p) - 1 and p[p_ptr + 1] == '*'): + p_ptr += 2 + last_ptr.append([s_ptr, p_ptr]) + elif last_ptr: + [last_s_ptr, last_p_ptr] = last_ptr.pop() + while last_ptr and p[last_p_ptr - 2] != s[last_s_ptr] and p[last_p_ptr - 2] != '.': + [last_s_ptr, last_p_ptr] = last_ptr.pop() + last_s_ptr += 1 + s_ptr = last_s_ptr + p_ptr = last_p_ptr + last_ptr.append([s_ptr, p_ptr]) + else: + return False + + while p_ptr < len(p) and p[p_ptr] == '.' and p[p_ptr + 1] == '*': + p_ptr += 2 + + return p_ptr == len(p) + +# recursive +class Solution4: # @return a boolean def isMatch(self, s, p): if not p: From ff9c349212fb1ebfa8b1f371567274787ef070e7 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 2 May 2015 11:09:01 +0800 Subject: [PATCH 179/345] Update regular-expression-matching.py --- Python/regular-expression-matching.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/regular-expression-matching.py b/Python/regular-expression-matching.py index 67cf4b461..ce481e622 100644 --- a/Python/regular-expression-matching.py +++ b/Python/regular-expression-matching.py @@ -74,7 +74,7 @@ def isMatch(self, s, p): last_ptr = [] while s_ptr < len(s): if p_ptr < len(p) and (p_ptr == len(p) - 1 or p[p_ptr + 1] != '*') and \ - (s_ptr < len(s) and (p[p_ptr] == s[s_ptr] or p[p_ptr] == '?')): + (s_ptr < len(s) and (p[p_ptr] == s[s_ptr] or p[p_ptr] == '.')): s_ptr += 1 p_ptr += 1 elif p_ptr < len(p) - 1 and (p_ptr != len(p) - 1 and p[p_ptr + 1] == '*'): From d84bd7beb776a9bee11aa579c6f59c181e617a74 Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Sat, 2 May 2015 11:17:55 +0800 Subject: [PATCH 180/345] update --- Python/regular-expression-matching.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/regular-expression-matching.py b/Python/regular-expression-matching.py index ce481e622..6c39e84e8 100644 --- a/Python/regular-expression-matching.py +++ b/Python/regular-expression-matching.py @@ -91,7 +91,7 @@ def isMatch(self, s, p): else: return False - while p_ptr < len(p) and p[p_ptr] == '.' and p[p_ptr + 1] == '*': + while p_ptr < len(p) - 1 and p[p_ptr] == '.' and p[p_ptr + 1] == '*': p_ptr += 2 return p_ptr == len(p) From 8f500756d0d81a065d8952a72f7894ba3155b2ea Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Sat, 2 May 2015 11:35:43 +0800 Subject: [PATCH 181/345] update --- Python/regular-expression-matching.py | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/Python/regular-expression-matching.py b/Python/regular-expression-matching.py index 6c39e84e8..194fd2f25 100644 --- a/Python/regular-expression-matching.py +++ b/Python/regular-expression-matching.py @@ -84,10 +84,14 @@ def isMatch(self, s, p): [last_s_ptr, last_p_ptr] = last_ptr.pop() while last_ptr and p[last_p_ptr - 2] != s[last_s_ptr] and p[last_p_ptr - 2] != '.': [last_s_ptr, last_p_ptr] = last_ptr.pop() - last_s_ptr += 1 - s_ptr = last_s_ptr - p_ptr = last_p_ptr - last_ptr.append([s_ptr, p_ptr]) + + if p[last_p_ptr - 2] == s[last_s_ptr] or p[last_p_ptr - 2] == '.': + last_s_ptr += 1 + s_ptr = last_s_ptr + p_ptr = last_p_ptr + last_ptr.append([s_ptr, p_ptr]) + else: + return False else: return False @@ -116,7 +120,7 @@ def isMatch(self, s, p): return self.isMatch(s, p[2:]) if __name__ == "__main__": - print Solution().isMatch("abcd","d*") + print Solution3().isMatch("abab", "a*b*") print Solution().isMatch("aaaaaaaaaaaaab", "a*a*a*a*a*a*a*a*a*a*c") print Solution().isMatch("aa","a") print Solution().isMatch("aa","aa") From 5d22cadee6fadb9b14fb495bc1feef3b99cbc3f2 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 3 May 2015 22:26:31 +0800 Subject: [PATCH 182/345] Update jump-game-ii.py --- Python/jump-game-ii.py | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/Python/jump-game-ii.py b/Python/jump-game-ii.py index 6a660882e..bd771dabf 100644 --- a/Python/jump-game-ii.py +++ b/Python/jump-game-ii.py @@ -1,4 +1,4 @@ -# Time: O(n^2) +# Time: O(n) # Space: O(1) # # Given an array of non-negative integers, you are initially positioned at the first index of the array. @@ -14,6 +14,24 @@ # class Solution: + # @param A, a list of integers + # @return an integer + def jump(self, A): + jump_count = 0 + reachable = 0 + curr_reachable = 0 + for i, length in enumerate(A): + if i > reachable: + return -1 + if i > curr_reachable: + curr_reachable = reachable + jump_count += 1 + reachable = max(reachable, i + length) + return jump_count + +# Time: O(n^2) +# Space: O(1) +class Solution2: # @param A, a list of integers # @return an integer def jump(self, A): From e3ab713c6a7729675d0f6c33aaeba51f24d88949 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 3 May 2015 22:28:34 +0800 Subject: [PATCH 183/345] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index dc1a0266e..5246e03da 100644 --- a/README.md +++ b/README.md @@ -734,7 +734,7 @@ Problem | Solution | Time | Space | Difficul [Container With Most Water]| [container-with-most-water.py] | _O(n)_ | _O(1)_ | Medium | [Gas Station]| [gas-station.py] | _O(n)_ | _O(1)_ | Medium | [Jump Game] | [jump-game.py] | _O(n)_ | _O(1)_ | Medium | -[Jump Game II] | [jump-game-ii.py] | _O(n^2)_ | _O(1)_ | Hard | +[Jump Game II] | [jump-game-ii.py] | _O(n)_ | _O(1)_ | Hard | [Largest Rectangle in Histogram] | [largest-rectangle-in-histogram.py] | _O(n)_ | _O(n)_ | Hard | Tricky [Trapping Rain Water] | [trapping-rain-water.py] | _O(n)_ | _O(1)_ | Hard | Tricky [Wildcard Matching] | [wildcard-matching.py] | _O(m + n)_ | _O(1)_ | Hard | Tricky From 26276ab2bae5c200a4a30a3078008911080fd448 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 4 May 2015 14:18:20 +0800 Subject: [PATCH 184/345] Update median-of-two-sorted-arrays.py --- Python/median-of-two-sorted-arrays.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Python/median-of-two-sorted-arrays.py b/Python/median-of-two-sorted-arrays.py index 89caa92dc..e9708c058 100644 --- a/Python/median-of-two-sorted-arrays.py +++ b/Python/median-of-two-sorted-arrays.py @@ -23,10 +23,10 @@ def getKth(self, A, B, k): while left < right: mid = left + (right - left) / 2 j = k - 1 - mid - if j >= n or A[mid] < B[j]: - left = mid + 1 - else: + if 0 <= j and j < n and A[mid] >= B[j]: right = mid + else: + left = mid + 1 Ai_minus_1, Bj = float("-inf"), float("-inf") if left - 1 >= 0: From e54748e9a83844455661f5fe76980728e9d46690 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 4 May 2015 14:20:41 +0800 Subject: [PATCH 185/345] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 5246e03da..9f206eb5b 100644 --- a/README.md +++ b/README.md @@ -532,9 +532,9 @@ Problem | Solution | Time | Space | Difficul [Find Minimum in Rotated Sorted Array] | [find-minimum-in-rotated-sorted-array.py] | _O(logn)_ | _O(1)_ | Medium | [Find Minimum in Rotated Sorted Array II] | [find-minimum-in-rotated-sorted-array-ii.py] | _O(logn)_ ~ _O(n)_ | _O(1)_ | Hard | [Find Peak Element] | [find-peak-element.py] | _O(logn)_ | _O(1)_ | Medium | -[Median of Two Sorted Arrays] | [median-of-two-sorted-arrays.py] | _O(log(m + n)_ | _O(1)_ | Hard | +[Median of Two Sorted Arrays] | [median-of-two-sorted-arrays.py] | _O(log(m + n))_ | _O(1)_ | Hard | [Pow(x, n)] | [powx-n.py] | _O(logn)_ | _O(logn)_ | Medium | -[Search a 2D Matrix] | [search-a-2d-matrix.py] | _O(log m + logn)_ | _O(1)_ | Medium | +[Search a 2D Matrix] | [search-a-2d-matrix.py] | _O(logm + logn)_ | _O(1)_ | Medium | [Search for a Range] | [search-for-a-range.py] | _O(logn)_ | _O(1)_ | Medium | [Search in Rotated Sorted Array] | [search-in-rotated-sorted-array.py] | _O(logn)_ | _O(1)_ | Hard | [Search in Rotated Sorted Array II] | [search-in-rotated-sorted-array-ii.py] | _O(logn)_ | _O(1)_ | Medium | From 10dcf4e01e973185ee5bb59c04cd8bd6a167861f Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Mon, 4 May 2015 14:54:45 +0800 Subject: [PATCH 186/345] update --- Python/4sum.py | 34 ++++++++++++++++++++++++++++++++-- 1 file changed, 32 insertions(+), 2 deletions(-) diff --git a/Python/4sum.py b/Python/4sum.py index c049c577c..a1a77ef20 100644 --- a/Python/4sum.py +++ b/Python/4sum.py @@ -1,5 +1,5 @@ -# Time: O(n^2) ~ O(n^4) -# Space: O(n^2) +# Time: O(n^2 * p) +# Space: O(n^2 * p) # # Given an array S of n integers, # are there elements a, b, c, and d in S such that a + b + c + d = target? @@ -17,6 +17,36 @@ # class Solution: + # @return a list of lists of length 4, [[val1,val2,val3,val4]] + def fourSum(self, nums, target): + nums, result, lookup = sorted(nums), [], {} + for i in xrange(0, len(nums) - 1): + for j in xrange(i + 1, len(nums)): + if nums[i] + nums[j] not in lookup: + lookup[nums[i] + nums[j]] = [] + is_duplicated = False + for [x, y] in lookup[nums[i] + nums[j]]: + if nums[x] == nums[i]: + is_duplicated = True + break + if not is_duplicated: + lookup[nums[i] + nums[j]].append([i, j]) + ans = {} + for c in xrange(2, len(nums)): + for d in xrange(c+1, len(nums)): + if target - nums[c] - nums[d] in lookup: + for [a, b] in lookup[target - nums[c] - nums[d]]: + if b < c: + quad = [nums[a], nums[b], nums[c], nums[d]] + quad_hash = " ".join(str(quad)) + if quad_hash not in ans: + ans[quad_hash] = True + result.append(quad) + return result + +# Time: O(n^2 * p) ~ O(n^4) +# Space: O(n^2) +class Solution2: # @return a list of lists of length 4, [[val1,val2,val3,val4]] def fourSum(self, nums, target): nums, result, lookup = sorted(nums), [], {} From 96f209b11cf8c787b13a149845ee6cdb16e0db0e Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 4 May 2015 14:55:32 +0800 Subject: [PATCH 187/345] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 9f206eb5b..e6375ba70 100644 --- a/README.md +++ b/README.md @@ -293,7 +293,7 @@ Problem | Solution | Time | Space | Difficul ##Hash Table Problem | Solution | Time | Space | Difficulty | Notes --------------- | --------------- | --------------- | --------------- | -------------- | ----- -[4 Sum] |[4sum.py] | _O(n^2)_ ~ _O(n^4)_ | _O(n^2)_ | Medium | +[4 Sum] |[4sum.py] | _O(n^2 * p)_ | _O(n^2 * p)_ | Medium | [Anagrams] | [anagrams.py] | _O(n)_ | _O(n)_ | Medium | [Count Primes] | [count-primes.py] | _O(n)_ | _O(n)_ | Easy | [Happy Number] | [happy-number.py] | _O(k)_ | _O(k)_ | Easy | From e72894b16449e2dbf444c50722e87142381a37a2 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 4 May 2015 17:19:22 +0800 Subject: [PATCH 188/345] Update word-break.py --- Python/word-break.py | 30 +++++++++++++++++++++++++++++- 1 file changed, 29 insertions(+), 1 deletion(-) diff --git a/Python/word-break.py b/Python/word-break.py index bd39ed955..b1f9ad9ee 100644 --- a/Python/word-break.py +++ b/Python/word-break.py @@ -12,6 +12,34 @@ # class Solution: + # @param s: A string s + # @param dict: A dictionary of words dict + def wordSegmentation(self, s, dict): + if not s: + return True + + cnt = {} + for w in dict: + for c in w: + if c not in cnt: + cnt[c] = 0 + cnt[c] += 1 + for c in s: + if c not in cnt: + return False + + n = len(s) + possible = [False for _ in xrange(n)] + for i in xrange(n): + for j in reversed(xrange(i + 1)): + if (j == 0 or possible[j-1]) and s[j:i+1] in dict: + possible[i] = True + break + + return possible[n-1] + +# slower +class Solution2: # @param s, a string # @param dict, a set of string # @return a boolean @@ -29,4 +57,4 @@ def wordBreak(self, s, dict): return possible[n-1] if __name__ == "__main__": - print Solution().wordBreak("leetcode", ["leet", "code"]) \ No newline at end of file + print Solution().wordBreak("leetcode", ["leet", "code"]) From ec6bb573b3173bb80a7fc2fd7ef808096b7e4dcc Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 6 May 2015 13:59:49 +0800 Subject: [PATCH 189/345] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index e6375ba70..59a34d549 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ LeetCode ======== -Up to date (2015-04-29), there are `189` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://oj.leetcode.com/). +Up to date (2015-05-05), there are `190` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://oj.leetcode.com/). The number of problems is increasing recently. -Here is the classification of all `205` problems. +Here is the classification of all `206` problems. For extra problems and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repo. I'll keep updating for full summary and better solutions. Stay tuned for updates. From b72a81ee132abf84dc16197252559093676d28d0 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 6 May 2015 20:47:28 +0800 Subject: [PATCH 190/345] Create reverse-linked-list.py --- Python/reverse-linked-list.py | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 Python/reverse-linked-list.py diff --git a/Python/reverse-linked-list.py b/Python/reverse-linked-list.py new file mode 100644 index 000000000..40bce191a --- /dev/null +++ b/Python/reverse-linked-list.py @@ -0,0 +1,26 @@ +# Time: O(n) +# Space: O(1) +# +# Reverse a singly linked list. +# +# click to show more hints. +# +# Hint: +# A linked list can be reversed either iteratively or recursively. Could you implement both? +# + +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, x): +# self.val = x +# self.next = None + +class Solution: + # @param {ListNode} head + # @return {ListNode} + def reverseList(self, head): + dummy = ListNode(float("-inf")) + while head: + dummy.next, head.next, head = head, dummy.next, head.next + return dummy.next + From 7f0fb38158a24d9eec8071873d8d661b8ba9463f Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Wed, 6 May 2015 21:10:20 +0800 Subject: [PATCH 191/345] add solution --- Python/reverse-linked-list.py | 43 +++++++++++++++++++++++++++++++---- 1 file changed, 39 insertions(+), 4 deletions(-) diff --git a/Python/reverse-linked-list.py b/Python/reverse-linked-list.py index 40bce191a..8e8441ddc 100644 --- a/Python/reverse-linked-list.py +++ b/Python/reverse-linked-list.py @@ -10,11 +10,16 @@ # # Definition for singly-linked list. -# class ListNode: -# def __init__(self, x): -# self.val = x -# self.next = None +class ListNode: + def __init__(self, x): + self.val = x + self.next = None + + def __repr__(self): + if self: + return "{} -> {}".format(self.val, repr(self.next)) +# Iterative solution. class Solution: # @param {ListNode} head # @return {ListNode} @@ -23,4 +28,34 @@ def reverseList(self, head): while head: dummy.next, head.next, head = head, dummy.next, head.next return dummy.next + +# Time: O(n) +# Space: O(n) +# Recursive solution. +class Solution2: + # @param {ListNode} head + # @return {ListNode} + def reverseList(self, head): + [begin, end] = self.reverseListRecu(head) + return begin + + def reverseListRecu(self, head): + if not head: + return [None, None] + + [begin, end] = self.reverseListRecu(head.next) + + if end: + end.next = head + head.next = None + return [begin, head] + else: + return [head, head] +if __name__ == "__main__": + head = ListNode(1) + head.next = ListNode(2) + head.next.next = ListNode(3) + head.next.next.next = ListNode(4) + head.next.next.next.next = ListNode(5) + print Solution2().reverseList(head) \ No newline at end of file From cddf8ad6d6fddf1e9982dd6dec3c3d71259395c9 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 6 May 2015 21:14:12 +0800 Subject: [PATCH 192/345] Update README.md --- README.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/README.md b/README.md index 59a34d549..4961ce48e 100644 --- a/README.md +++ b/README.md @@ -205,6 +205,7 @@ Problem | Solution | Time | Space | Difficul [Remove Duplicates from Sorted List]| [remove-duplicates-from-sorted-list.py] | _O(n)_ | _O(1)_ | Easy | [Remove Duplicates from Sorted List II]| [remove-duplicates-from-sorted-list-ii.py] | _O(n)_ | _O(1)_ | Medium | [Remove Linked List Elements]| [remove-linked-list-elements.py] | _O(n)_ | _O(1)_ | Easy | +[Reverse Linked List]| [reverse-linked-list.py] | _O(n)_ | _O(1)_ | Easy | [Reverse Linked List II]| [reverse-linked-list-ii.py] | _O(n)_ | _O(1)_ | Medium | [Reverse Nodes in k-Group]| [reverse-nodes-in-k-group.py] | _O(n)_ | _O(1)_ | Hard | [Rotate List]| [rotate-list.py] | _O(n)_ | _O(1)_ | Medium | @@ -222,6 +223,8 @@ Problem | Solution | Time | Space | Difficul [remove-duplicates-from-sorted-list-ii.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/remove-duplicates-from-sorted-list-ii.py [Remove Linked List Elements]:https://oj.leetcode.com/problems/remove-linked-list-elements/ [remove-linked-list-elements.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/remove-linked-list-elements.py +[Reverse Linked List]:https://oj.leetcode.com/problems/reverse-linked-list/ +[reverse-linked-list.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/reverse-linked-list.py [Reverse Linked List II]:https://oj.leetcode.com/problems/reverse-linked-list-ii/ [reverse-linked-list-ii.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/reverse-linked-list-ii.py [Reverse Nodes in k-Group]:https://oj.leetcode.com/problems/reverse-nodes-in-k-group/ From f78170452f8b6d73a290a5eb69ebf52581c6ec00 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 6 May 2015 21:44:46 +0800 Subject: [PATCH 193/345] Update permutation-sequence.py --- Python/permutation-sequence.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/permutation-sequence.py b/Python/permutation-sequence.py index 2252f26ad..a3b5e1158 100644 --- a/Python/permutation-sequence.py +++ b/Python/permutation-sequence.py @@ -1,5 +1,5 @@ -# Time: O(n) -# Space: O(1) +# Time: O(n^2) +# Space: O(n) # # The set [1,2,3,...,n] contains a total of n! unique permutations. # From b8d78ffc9ed011c9e294a2422434ddbf4dd9e524 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 6 May 2015 21:45:31 +0800 Subject: [PATCH 194/345] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 4961ce48e..8cf458261 100644 --- a/README.md +++ b/README.md @@ -361,7 +361,7 @@ Problem | Solution | Time | Space | Difficul [Gray Code] | [gray-code.py] | _O(2^n)_ | _O(1)_ | Medium | [Integer to Roman] | [integer-to-roman.py] | _O(n)_ | _O(1)_ | Medium | [Palindrome Number] | [palindrome-number.py] | _O(1)_ | _O(1)_ | Easy | -[Permutation Sequence] | [permutation-sequence.py] | _O(n)_ | _O(1)_ | Medium | `Cantor Ordering` +[Permutation Sequence] | [permutation-sequence.py] | _O(n^2)_ | _O(n)_ | Medium | `Cantor Ordering` [Reverse Integer] | [reverse-integer.py] | _O(logn)_ | _O(1)_ | Easy | [Roman to Integer] | [roman-to-integer.py] | _O(n)_ | _O(1)_ | Easy | [Valid Number] | [valid-number.py] | _O(n)_ | _O(1)_ | Hard | `Automata` From 0e8406574f71bd3ace0abcec83b1d9f107969db3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 7 May 2015 22:13:43 +0800 Subject: [PATCH 195/345] Create course-schedule.cpp --- C++/course-schedule.cpp | 50 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 C++/course-schedule.cpp diff --git a/C++/course-schedule.cpp b/C++/course-schedule.cpp new file mode 100644 index 000000000..2cf78f602 --- /dev/null +++ b/C++/course-schedule.cpp @@ -0,0 +1,50 @@ +// Time: O(|V| + |E|) +// Space: O(|E|) + +// Topological sort solution. +class Solution { +public: + bool canFinish(int numCourses, vector>& prerequisites) { + // Store courses with in-degree zero. + queue zeroInDegree; + + // in-degree, out-degree + unordered_map> inDegree; + unordered_map> outDegree; + for (int i = 0; i < prerequisites.size(); ++i) { + inDegree[prerequisites[i][0]].insert(prerequisites[i][1]); + outDegree[prerequisites[i][1]].insert(prerequisites[i][0]); + } + + // Put all the courses with in-degree zero into queue. + for(int i = 0; i < numCourses; ++i) { + if(inDegree.find(i) == inDegree.end()) { + zeroInDegree.push(i); + } + } + + // V+E + while(!zeroInDegree.empty()) { + // Take the course which prerequisites are all taken. + int prerequisite = zeroInDegree.front(); + zeroInDegree.pop(); + for (const auto & course: outDegree[prerequisite]) { + // Update info of all the courses with the taken prerequisite. + inDegree[course].erase(prerequisite); + // If all the prerequisites are taken, add the course to the queue. + if (inDegree[course].empty()) { + zeroInDegree.push(course); + } + } + // Mark the course as taken. + outDegree.erase(prerequisite); + } + + // All of the courses have been taken. + if (!outDegree.empty()) { + return false; + } + + return true; + } +}; From 9cd9ab9ed05ae5ed0344ea1e7a02850999822c20 Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Thu, 7 May 2015 22:54:34 +0800 Subject: [PATCH 196/345] add solution --- Python/course-schedule.py | 69 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 69 insertions(+) create mode 100644 Python/course-schedule.py diff --git a/Python/course-schedule.py b/Python/course-schedule.py new file mode 100644 index 000000000..f152d597b --- /dev/null +++ b/Python/course-schedule.py @@ -0,0 +1,69 @@ +# Time: O(|V| + |E|) +# Space: O(|E|) +# +# There are a total of n courses you have to take, labeled from 0 to n - 1. +# +# Some courses may have prerequisites, for example to take course 0 +# you have to first take course 1, which is expressed as a pair: [0,1] +# +# Given the total number of courses and a list of prerequisite pairs, +# is it possible for you to finish all courses? +# +# For example: +# +# 2, [[1,0]] +# There are a total of 2 courses to take. To take course 1 +# you should have finished course 0. So it is possible. +# +# 2, [[1,0],[0,1]] +# There are a total of 2 courses to take. To take course 1 you should have +# finished course 0, and to take course 0 you should also have finished course 1. So it is impossible. +# +# click to show more hints. +# +# Hints: +# This problem is equivalent to finding if a cycle exists in a directed graph. +# If a cycle exists, no topological ordering exists and therefore it will be impossible to take all courses. +# There are several ways to represent a graph. For example, the input prerequisites is a graph represented by +# a list of edges. Is this graph representation appropriate? +# Topological Sort via DFS - A great video tutorial (21 minutes) on Coursera explaining the basic concepts +# of Topological Sort. +# Topological sort could also be done via BFS. +# +class Solution: + # @param {integer} numCourses + # @param {integer[][]} prerequisites + # @return {boolean} + def canFinish(self, numCourses, prerequisites): + zero_in_degree_queue, in_degree, out_degree = [], {}, {} + + for i, j in prerequisites: + if i not in in_degree: + in_degree[i] = {} + if j not in out_degree: + out_degree[j] = {} + in_degree[i][j] = True + out_degree[j][i] = True + + for i in xrange(numCourses): + if i not in in_degree: + zero_in_degree_queue.append(i) + + while zero_in_degree_queue: + prerequisite = zero_in_degree_queue.pop() + + if prerequisite in out_degree: + for course in out_degree[prerequisite]: + del (in_degree[course])[prerequisite] + if not in_degree[course]: + zero_in_degree_queue.append(course) + + del out_degree[prerequisite] + + if len(out_degree): + return False + + return True + +if __name__ == "__main__": + print Solution().canFinish(1, []) \ No newline at end of file From f90b64b7d839f3108c55921bc737e3c770e54dc9 Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Thu, 7 May 2015 22:56:03 +0800 Subject: [PATCH 197/345] update --- Python/course-schedule.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/course-schedule.py b/Python/course-schedule.py index f152d597b..80542d46f 100644 --- a/Python/course-schedule.py +++ b/Python/course-schedule.py @@ -54,7 +54,7 @@ def canFinish(self, numCourses, prerequisites): if prerequisite in out_degree: for course in out_degree[prerequisite]: - del (in_degree[course])[prerequisite] + del in_degree[course][prerequisite] if not in_degree[course]: zero_in_degree_queue.append(course) From c3291704723c9dfed1e2e3abaf3cf57c37359255 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 7 May 2015 23:01:57 +0800 Subject: [PATCH 198/345] Update README.md --- README.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 8cf458261..2c90df648 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ LeetCode ======== -Up to date (2015-05-05), there are `190` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://oj.leetcode.com/). +Up to date (2015-05-07), there are `191` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://oj.leetcode.com/). The number of problems is increasing recently. -Here is the classification of all `206` problems. +Here is the classification of all `207` problems. For extra problems and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repo. I'll keep updating for full summary and better solutions. Stay tuned for updates. @@ -576,6 +576,7 @@ Problem | Solution | Time | Space | Difficul [Binary Tree Level Order Traversal II]| [binary-tree-level-order-traversal-ii.py] | _O(n)_| _O(n)_| Easy | [Binary Tree Zigzag Level Order Traversal]| [binary-tree-zigzag-level-order-traversal.py] | _O(n)_| _O(n)_| Medium | [Clone Graph]| [clone-graph.py] | _O(n)_ | _O(n)_ | Medium | +[Course Schedule](https://oj.leetcode.com/problems/course-schedule/)| [course-schedule.py](./Python/course-schedule.py) | _O(|V| + |E|)_ | _O(|E|)_ | Medium | [Populating Next Right Pointers in Each Node II]|[populating-next-right-pointers-in-each-node-ii.py]| _O(n)_ | _O(1)_ | Hard | [Surrounded Regions]|[surrounded-regions.py]| _O(m * n)_ | _O(m + n)_ | Medium | [Word Ladder] |[word-ladder.py] | _O(n * d)_ | _O(d)_ | Medium | From 3f4f3b6b92b0757cfdc6d468960036ebb509333b Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 7 May 2015 23:02:41 +0800 Subject: [PATCH 199/345] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 2c90df648..9f5c1c573 100644 --- a/README.md +++ b/README.md @@ -576,7 +576,7 @@ Problem | Solution | Time | Space | Difficul [Binary Tree Level Order Traversal II]| [binary-tree-level-order-traversal-ii.py] | _O(n)_| _O(n)_| Easy | [Binary Tree Zigzag Level Order Traversal]| [binary-tree-zigzag-level-order-traversal.py] | _O(n)_| _O(n)_| Medium | [Clone Graph]| [clone-graph.py] | _O(n)_ | _O(n)_ | Medium | -[Course Schedule](https://oj.leetcode.com/problems/course-schedule/)| [course-schedule.py](./Python/course-schedule.py) | _O(|V| + |E|)_ | _O(|E|)_ | Medium | +[Course Schedule](https://oj.leetcode.com/problems/course-schedule/)| [course-schedule.py](./Python/course-schedule.py) | _O(\|V\| + \|E\|)_ | _O(\|E\|)_ | Medium | [Populating Next Right Pointers in Each Node II]|[populating-next-right-pointers-in-each-node-ii.py]| _O(n)_ | _O(1)_ | Hard | [Surrounded Regions]|[surrounded-regions.py]| _O(m * n)_ | _O(m + n)_ | Medium | [Word Ladder] |[word-ladder.py] | _O(n * d)_ | _O(d)_ | Medium | From 4f49b3697f6401fe1dc107097de5d3451e77d07a Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 8 May 2015 01:37:59 +0800 Subject: [PATCH 200/345] Update merge-k-sorted-lists.py --- Python/merge-k-sorted-lists.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/merge-k-sorted-lists.py b/Python/merge-k-sorted-lists.py index 0cd4e311b..8003ec215 100644 --- a/Python/merge-k-sorted-lists.py +++ b/Python/merge-k-sorted-lists.py @@ -1,5 +1,5 @@ # Time: O(nlogk) -# Space: O(1) +# Space: O(k) # # Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity. import heapq @@ -41,4 +41,4 @@ def mergeKLists(self, lists): list2 = ListNode(2) list2.next = ListNode(4) - print Solution().mergeKLists([list1, list2]) \ No newline at end of file + print Solution().mergeKLists([list1, list2]) From 0324251bb994eea6292a1195e5550000d8064943 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 8 May 2015 01:38:30 +0800 Subject: [PATCH 201/345] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 9f5c1c573..c525cf7b6 100644 --- a/README.md +++ b/README.md @@ -267,7 +267,7 @@ Problem | Solution | Time | Space | Difficul ##Heap Problem | Solution | Time | Space | Difficulty | Notes --------------- | --------------- | --------------- | --------------- | -------------- | ----- -[Merge k Sorted Lists] | [merge-k-sorted-lists.py] | _O(nlogk)_| _O(1)_| Hard | +[Merge k Sorted Lists] | [merge-k-sorted-lists.py] | _O(nlogk)_| _O(k)_| Hard | [Merge k Sorted Lists]:https://oj.leetcode.com/problems/merge-k-sorted-lists/ [merge-k-sorted-lists.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/merge-k-sorted-lists.py From 30f8f1552bcfb1dd79db6dcd9c86b81bf41f8a15 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 9 May 2015 12:49:04 +0800 Subject: [PATCH 202/345] Create implement-trie-prefix-tree.py --- Python/implement-trie-prefix-tree.py | 61 ++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 Python/implement-trie-prefix-tree.py diff --git a/Python/implement-trie-prefix-tree.py b/Python/implement-trie-prefix-tree.py new file mode 100644 index 000000000..1fc9cb47a --- /dev/null +++ b/Python/implement-trie-prefix-tree.py @@ -0,0 +1,61 @@ +# Time: O(n), per operation +# Space: O(1) +# +# Implement a trie with insert, search, and startsWith methods. +# +# Note: +# You may assume that all inputs are consist of lowercase letters a-z. +# + +class TrieNode: + # Initialize your data structure here. + def __init__(self): + self.flag = False + self.children = {} + + +class Trie: + + def __init__(self): + self.root = TrieNode() + + # @param {string} word + # @return {void} + # Inserts a word into the trie. + def insert(self, word): + cur = self.root + for c in word: + if not c in cur.children: + cur.children[c] = TrieNode() + cur = cur.children[c] + cur.flag = True + + # @param {string} word + # @return {boolean} + # Returns if the word is in the trie. + def search(self, word): + res, node = self.childSearch(word) + if res: + return node.flag + return False + + # @param {string} prefix + # @return {boolean} + # Returns if there is any word in the trie + # that starts with the given prefix. + def startsWith(self, prefix): + return self.childSearch(prefix)[0] + + def childSearch(self, word): + cur = self.root + for c in word: + if c in cur.children: + cur = cur.children[c] + else: + return False, None + return True, cur + +# Your Trie object will be instantiated and called as such: +# trie = Trie() +# trie.insert("somestring") +# trie.search("key") From 59e955592f94f8855c0978186c5b9d70c238839a Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 9 May 2015 12:53:45 +0800 Subject: [PATCH 203/345] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index c525cf7b6..21dcf2e8c 100644 --- a/README.md +++ b/README.md @@ -280,6 +280,7 @@ Problem | Solution | Time | Space | Difficul [Binary Tree Preorder Traversal] | [binary-tree-preorder-traversal.py] | _O(n)_| _O(1)_| Medium | `Morris Traversal` [Binary Tree Inorder Traversal] | [binary-tree-inorder-traversal.py] | _O(n)_| _O(1)_| Medium | `Morris Traversal` [Binary Tree Postorder Traversal]| [binary-tree-postorder-traversal.py] | _O(n)_| _O(1)_| Hard | `Morris Traversal` +[Implement Trie (Prefix Tree)](https://leetcode.com/problems/implement-trie-prefix-tree/) | [implement-trie-prefix-tree](./Python/implement-trie-prefix-tree.py) | _O(n)_ | _O(1)_ | Medium | `Trie` [Recover Binary Search Tree]| [recover-binary-search-tree.py] | _O(n)_| _O(1)_| Hard | `Morris Traversal` [Binary Tree Preorder Traversal]:https://oj.leetcode.com/problems/binary-tree-preorder-traversal/ From 1c8deb0efda6b9f45b91f06303e8b47b0e11028c Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 9 May 2015 16:00:58 +0800 Subject: [PATCH 204/345] Update README.md --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 21dcf2e8c..638d67af5 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ LeetCode ======== -Up to date (2015-05-07), there are `191` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://oj.leetcode.com/). +Up to date (2015-05-07), there are `192` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://oj.leetcode.com/). The number of problems is increasing recently. -Here is the classification of all `207` problems. +Here is the classification of all `208` problems. For extra problems and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repo. I'll keep updating for full summary and better solutions. Stay tuned for updates. @@ -280,7 +280,7 @@ Problem | Solution | Time | Space | Difficul [Binary Tree Preorder Traversal] | [binary-tree-preorder-traversal.py] | _O(n)_| _O(1)_| Medium | `Morris Traversal` [Binary Tree Inorder Traversal] | [binary-tree-inorder-traversal.py] | _O(n)_| _O(1)_| Medium | `Morris Traversal` [Binary Tree Postorder Traversal]| [binary-tree-postorder-traversal.py] | _O(n)_| _O(1)_| Hard | `Morris Traversal` -[Implement Trie (Prefix Tree)](https://leetcode.com/problems/implement-trie-prefix-tree/) | [implement-trie-prefix-tree](./Python/implement-trie-prefix-tree.py) | _O(n)_ | _O(1)_ | Medium | `Trie` +[Implement Trie (Prefix Tree)](https://leetcode.com/problems/implement-trie-prefix-tree/) | [implement-trie-prefix-tree.py](./Python/implement-trie-prefix-tree.py) | _O(n)_ | _O(1)_ | Medium | `Trie` [Recover Binary Search Tree]| [recover-binary-search-tree.py] | _O(n)_| _O(1)_| Hard | `Morris Traversal` [Binary Tree Preorder Traversal]:https://oj.leetcode.com/problems/binary-tree-preorder-traversal/ From 57d0f2a9b1ad1a26e7daaa0934c1a141c3d4c3cb Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 13 May 2015 12:06:03 +0800 Subject: [PATCH 205/345] Create minimum-size-subarray-sum.py --- Python/minimum-size-subarray-sum.py | 30 +++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 Python/minimum-size-subarray-sum.py diff --git a/Python/minimum-size-subarray-sum.py b/Python/minimum-size-subarray-sum.py new file mode 100644 index 000000000..860932c60 --- /dev/null +++ b/Python/minimum-size-subarray-sum.py @@ -0,0 +1,30 @@ +# Time: O(n) +# Space: O(1) +# +# Given an array of n positive integers and a positive integer s, +# find the minimal length of a subarray of which the sum ≥ s. If there isn't one, return 0 instead. +# +# For example, given the array [2,3,1,2,4,3] and s = 7, +# the subarray [4,3] has the minimal length under the problem constraint. +# +# More practice: +# If you have figured out the O(n) solution, try coding another solution of which the time complexity is O(n log n). +# + +class Solution: + # @param {integer} s + # @param {integer[]} nums + # @return {integer} + def minSubArrayLen(self, s, nums): + start = 0 + sum = 0 + min_len = float("inf") + for i in xrange(len(nums)): + sum += nums[i] + while sum >= s: + min_len = min(min_len, i - start + 1) + sum -= nums[start] + start += 1 + if min_len == float("inf"): + return 0 + return min_len From bc717fb19279d22f497c44d383d704669de2379b Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 13 May 2015 12:08:37 +0800 Subject: [PATCH 206/345] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 638d67af5..6050f641f 100644 --- a/README.md +++ b/README.md @@ -78,6 +78,7 @@ Problem | Solution | Time | Space | Difficul [First Missing Positive]| [first-missing-positive.py] | _O(n)_ | _O(1)_ | Hard | Tricky [Longest Consecutive Sequence]| [longest-consecutive-sequence.py] | _O(n)_ | _O(n)_ | Hard | Tricky [Majority Element] | [majority-element.py] | _O(n)_ | _O(1)_ | Easy | +[Minimum Size Subarray Sum](https://leetcode.com/problems/minimum-size-subarray-sum/) | [minimum-size-subarray-sum.py] (./Python/minimum-size-subarray-sum.py) | _O(n)_ | _O(1)_ | Medium | [Missing Ranges]| [missing-ranges.py] | _O(n)_ | _O(1)_ | Medium | [Next Permutation]| [next-permutation.py] | _O(n)_ | _O(1)_ | Medium | Tricky [Pascal's Triangle]| [pascals-triangle.py] | _O(n^2)_ | _O(n)_ | Easy | From 776a20cb34805761ba4e1482f00fdd9da7dc644b Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 14 May 2015 12:56:25 +0800 Subject: [PATCH 207/345] Create course-schedule-ii.py --- Python/course-schedule-ii.py | 72 ++++++++++++++++++++++++++++++++++++ 1 file changed, 72 insertions(+) create mode 100644 Python/course-schedule-ii.py diff --git a/Python/course-schedule-ii.py b/Python/course-schedule-ii.py new file mode 100644 index 000000000..3ae0bdc11 --- /dev/null +++ b/Python/course-schedule-ii.py @@ -0,0 +1,72 @@ +# Time: O(|V| + |E|) +# Space: O(|V|) + +# There are a total of n courses you have to take, labeled from 0 to n - 1. +# +# Some courses may have prerequisites, for example to take course 0 you have to first take course 1, +# which is expressed as a pair: [0,1] +# +# Given the total number of courses and a list of prerequisite pairs, return the ordering of courses +# you should take to finish all courses. +# +# There may be multiple correct orders, you just need to return one of them. If it is impossible +# to finish all courses, return an empty array. +# +# For example: +# +# 2, [[1,0]] +# There are a total of 2 courses to take. To take course 1 you should have finished course 0. +# So the correct course order is [0,1] +# +# 4, [[1,0],[2,0],[3,1],[3,2]] +# There are a total of 4 courses to take. To take course 3 you should have finished both courses 1 and 2. +# Both courses 1 and 2 should be taken after you finished course 0. So one correct course order is [0,1,2,3]. +# Another correct ordering is[0,2,1,3]. +# +# Note: +# The input prerequisites is a graph represented by a list of edges, not adjacency matrices. +# Read more about how a graph is represented. +# +# Hints: +# This problem is equivalent to finding the topological order in a directed graph. +# If a cycle exists, no topological ordering exists and therefore it will be impossible to take all courses. +# Topological Sort via DFS - A great video tutorial (21 minutes) on Coursera explaining +# the basic concepts of Topological Sort. +# Topological sort could also be done via BFS. +# + +class Solution: + # @param {integer} numCourses + # @param {integer[][]} prerequisites + # @return {integer[]} + def findOrder(self, numCourses, prerequisites): + res, zero_in_degree_queue, in_degree, out_degree = [], [], {}, {} + + for i, j in prerequisites: + if i not in in_degree: + in_degree[i] = {} + if j not in out_degree: + out_degree[j] = {} + in_degree[i][j] = True + out_degree[j][i] = True + + for i in xrange(numCourses): + if i not in in_degree: + zero_in_degree_queue.append(i) + + while zero_in_degree_queue: + prerequisite = zero_in_degree_queue.pop() + res.append(prerequisite) + + if prerequisite in out_degree: + for course in out_degree[prerequisite]: + del in_degree[course][prerequisite] + if not in_degree[course]: + zero_in_degree_queue.append(course) + + del out_degree[prerequisite] + + if len(out_degree): + return [] + + return res From f66dd476e9ece8f0d111040ec1b7152837d9b83e Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 14 May 2015 13:00:36 +0800 Subject: [PATCH 208/345] Update README.md --- README.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 6050f641f..979c1434a 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ LeetCode ======== -Up to date (2015-05-07), there are `192` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://oj.leetcode.com/). +Up to date (2015-05-07), there are `194` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://oj.leetcode.com/). The number of problems is increasing recently. -Here is the classification of all `208` problems. +Here is the classification of all `210` problems. For extra problems and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repo. I'll keep updating for full summary and better solutions. Stay tuned for updates. @@ -579,6 +579,7 @@ Problem | Solution | Time | Space | Difficul [Binary Tree Zigzag Level Order Traversal]| [binary-tree-zigzag-level-order-traversal.py] | _O(n)_| _O(n)_| Medium | [Clone Graph]| [clone-graph.py] | _O(n)_ | _O(n)_ | Medium | [Course Schedule](https://oj.leetcode.com/problems/course-schedule/)| [course-schedule.py](./Python/course-schedule.py) | _O(\|V\| + \|E\|)_ | _O(\|E\|)_ | Medium | +[Course Schedule II](https://oj.leetcode.com/problems/course-schedule-ii/)| [course-schedule-ii.py](./Python/course-schedule-ii.py) | _O(\|V\| + \|E\|)_ | _O(\|E\|)_ | Medium | [Populating Next Right Pointers in Each Node II]|[populating-next-right-pointers-in-each-node-ii.py]| _O(n)_ | _O(1)_ | Hard | [Surrounded Regions]|[surrounded-regions.py]| _O(m * n)_ | _O(m + n)_ | Medium | [Word Ladder] |[word-ladder.py] | _O(n * d)_ | _O(d)_ | Medium | From 215812ace3bcf625d76a51f1cc1b03ad9905ebb9 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 14 May 2015 13:01:04 +0800 Subject: [PATCH 209/345] Update course-schedule-ii.py --- Python/course-schedule-ii.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/course-schedule-ii.py b/Python/course-schedule-ii.py index 3ae0bdc11..d6701a084 100644 --- a/Python/course-schedule-ii.py +++ b/Python/course-schedule-ii.py @@ -1,5 +1,5 @@ # Time: O(|V| + |E|) -# Space: O(|V|) +# Space: O(|E|) # There are a total of n courses you have to take, labeled from 0 to n - 1. # From d4ca2724b0b1fa3ccf0d731e8ef390688bfc7a30 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 14 May 2015 13:01:35 +0800 Subject: [PATCH 210/345] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 979c1434a..c68a30285 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ LeetCode ======== -Up to date (2015-05-07), there are `194` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://oj.leetcode.com/). +Up to date (2015-05-14), there are `194` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://oj.leetcode.com/). The number of problems is increasing recently. Here is the classification of all `210` problems. For extra problems and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repo. From 335864311edd87ddfea0f279d97423e6e47dcca1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 14 May 2015 13:08:10 +0800 Subject: [PATCH 211/345] Create course-schedule-ii.cpp --- C++/course-schedule-ii.cpp | 52 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 C++/course-schedule-ii.cpp diff --git a/C++/course-schedule-ii.cpp b/C++/course-schedule-ii.cpp new file mode 100644 index 000000000..56ea5087b --- /dev/null +++ b/C++/course-schedule-ii.cpp @@ -0,0 +1,52 @@ +// Time: O(|V| + |E||) +// Space: O(1) + +// Topological sort. +class Solution { +public: + vector findOrder(int numCourses, vector>& prerequisites) { + vector res; + // Store courses with in-degree zero. + queue zeroInDegree; + + // in-degree, out-degree + unordered_map> inDegree; + unordered_map> outDegree; + for (int i = 0; i < prerequisites.size(); ++i) { + inDegree[prerequisites[i].first].insert(prerequisites[i].second); + outDegree[prerequisites[i].second].insert(prerequisites[i].first); + } + + // Put all the courses with in-degree zero into queue. + for(int i = 0; i < numCourses; ++i) { + if(inDegree.find(i) == inDegree.end()) { + zeroInDegree.push(i); + } + } + + // V+E + while(!zeroInDegree.empty()) { + // Take the course which prerequisites are all taken. + int prerequisite = zeroInDegree.front(); + res.emplace_back(prerequisite); + zeroInDegree.pop(); + for (const auto & course: outDegree[prerequisite]) { + // Update info of all the courses with the taken prerequisite. + inDegree[course].erase(prerequisite); + // If all the prerequisites are taken, add the course to the queue. + if (inDegree[course].empty()) { + zeroInDegree.push(course); + } + } + // Mark the course as taken. + outDegree.erase(prerequisite); + } + + // All of the courses have been taken. + if (!outDegree.empty()) { + return {}; + } + + return res; + } +}; From 9d1f0b8b03c97a51235757b9423748f7659f1014 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 14 May 2015 13:08:27 +0800 Subject: [PATCH 212/345] Update course-schedule-ii.cpp --- C++/course-schedule-ii.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/course-schedule-ii.cpp b/C++/course-schedule-ii.cpp index 56ea5087b..ec390a510 100644 --- a/C++/course-schedule-ii.cpp +++ b/C++/course-schedule-ii.cpp @@ -1,5 +1,5 @@ // Time: O(|V| + |E||) -// Space: O(1) +// Space: O(|E|) // Topological sort. class Solution { From 8f671a10343cb5b675dfa06ffea2d29a0f64bc5a Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 14 May 2015 13:08:50 +0800 Subject: [PATCH 213/345] Update course-schedule-ii.cpp --- C++/course-schedule-ii.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/course-schedule-ii.cpp b/C++/course-schedule-ii.cpp index ec390a510..198122315 100644 --- a/C++/course-schedule-ii.cpp +++ b/C++/course-schedule-ii.cpp @@ -1,7 +1,7 @@ // Time: O(|V| + |E||) // Space: O(|E|) -// Topological sort. +// Topological sort solution. class Solution { public: vector findOrder(int numCourses, vector>& prerequisites) { From 25bcde35cbc832fc2d94328b55d83a3f8430d864 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 16 May 2015 10:27:53 +0800 Subject: [PATCH 214/345] Create add-and-search-word-data-structure-design.py --- ...d-and-search-word-data-structure-design.py | 67 +++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 Python/add-and-search-word-data-structure-design.py diff --git a/Python/add-and-search-word-data-structure-design.py b/Python/add-and-search-word-data-structure-design.py new file mode 100644 index 000000000..1c8b80d59 --- /dev/null +++ b/Python/add-and-search-word-data-structure-design.py @@ -0,0 +1,67 @@ +# Time: O(min(n, h)), per operation +# Space: O(min(n, h)) +# +# Design a data structure that supports the following two operations: +# +# void addWord(word) +# bool search(word) +# search(word) can search a literal word or a regular expression string containing only letters a-z or .. +# A . means it can represent any one letter. +# +# For example: +# +# addWord("bad") +# addWord("dad") +# addWord("mad") +# search("pad") -> false +# search("bad") -> true +# search(".ad") -> true +# search("b..") -> true +# Note: +# You may assume that all words are consist of lowercase letters a-z. +# + +class TrieNode: + # Initialize your data structure here. + def __init__(self): + self.flag = False + self.children = {} + +class WordDictionary: + def __init__(self): + self.root = TrieNode() + + # @param {string} word + # @return {void} + # Adds a word into the data structure. + def addWord(self, word): + curr = self.root + for c in word: + if not c in curr.children: + curr.children[c] = TrieNode() + curr = curr.children[c] + curr.flag = True + + # @param {string} word + # @return {boolean} + # Returns if the word is in the data structure. A word could + # contain the dot character '.' to represent any one letter. + def search(self, word): + return self.searchHelper(word, 0, self.root) + + def searchHelper(self, word, start, curr): + if start == len(word): + return curr.flag + if word[start] in curr.children: + return self.searchHelper(word, start+1, curr.children[word[start]]) + elif word[start] == '.': + for c in curr.children: + if self.searchHelper(word, start+1, curr.children[c]): + return True + + return False + +# Your WordDictionary object will be instantiated and called as such: +# wordDictionary = WordDictionary() +# wordDictionary.addWord("word") +# wordDictionary.search("pattern") From 122e264fa388b9ad6a9ccff40d8d74c9457395ea Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 16 May 2015 10:31:06 +0800 Subject: [PATCH 215/345] Update README.md --- README.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index c68a30285..bda35ef55 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ LeetCode ======== -Up to date (2015-05-14), there are `194` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://oj.leetcode.com/). +Up to date (2015-05-16), there are `195` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://oj.leetcode.com/). The number of problems is increasing recently. -Here is the classification of all `210` problems. +Here is the classification of all `211` problems. For extra problems and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repo. I'll keep updating for full summary and better solutions. Stay tuned for updates. @@ -278,6 +278,7 @@ Problem | Solution | Time | Space | Difficul ##Tree Problem | Solution | Time | Space | Difficulty | Notes --------------- | --------------- | --------------- | --------------- | -------------- | ----- +[Add and Search Word - Data structure design ](https://leetcode.com/problems/add-and-search-word-data-structure-design/) | [Python](./Python/add-and-search-word-data-structure-design.py) | _O(min(n, h))_ | _O(min(n, h))_ | Medium | `Trie` [Binary Tree Preorder Traversal] | [binary-tree-preorder-traversal.py] | _O(n)_| _O(1)_| Medium | `Morris Traversal` [Binary Tree Inorder Traversal] | [binary-tree-inorder-traversal.py] | _O(n)_| _O(1)_| Medium | `Morris Traversal` [Binary Tree Postorder Traversal]| [binary-tree-postorder-traversal.py] | _O(n)_| _O(1)_| Hard | `Morris Traversal` From 9ce37e650a8365a66deff24b71b7fc69461367ad Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 16 May 2015 10:49:08 +0800 Subject: [PATCH 216/345] Create add-and-search-word-data-structure-design.cpp --- ...-and-search-word-data-structure-design.cpp | 57 +++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 C++/add-and-search-word-data-structure-design.cpp diff --git a/C++/add-and-search-word-data-structure-design.cpp b/C++/add-and-search-word-data-structure-design.cpp new file mode 100644 index 000000000..053516acd --- /dev/null +++ b/C++/add-and-search-word-data-structure-design.cpp @@ -0,0 +1,57 @@ +// Time: O(min(n, h)), per operation +// Space: O(min(n, h)) + +class WordDictionary { +public: + struct TrieNode{ + public: + bool isString = false; + unordered_map leaves; + }; + + WordDictionary(){ + root_ = new TrieNode(); + root_->isString = true; + } + + // Adds a word into the data structure. + void addWord(string word) { + auto* p = root_; + for (const auto& c : word) { + if (p->leaves.find(c) == p->leaves.cend()) { + p->leaves[c] = new TrieNode; + } + p = p->leaves[c]; + } + p->isString = true; + } + + // Returns if the word is in the data structure. A word could + // contain the dot character '.' to represent any one letter. + bool search(string word) { + return searchWord(word, root_, 0); + } + + bool searchWord(string word, TrieNode* node, int s) { + if (s == word.length()) { + return node->isString; + } + if (node->leaves.find(word[s]) != node->leaves.end()){ // Match the char. + return searchWord(word, node->leaves[word[s]], s + 1); + } else if (word[s] == '.') { // Skip the char. + for (const auto& i : node->leaves) { + if (searchWord(word, i.second, s + 1)) { + return true; + } + } + } + return false; + } +private: + TrieNode *root_; +}; + +// Your WordDictionary object will be instantiated and called as such: +// WordDictionary wordDictionary; +// wordDictionary.addWord("word"); +// wordDictionary.search("pattern"); From dab2b3009ade0c169105a79f0244f7094138fb7e Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 16 May 2015 10:50:03 +0800 Subject: [PATCH 217/345] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index bda35ef55..84cc9b1d8 100644 --- a/README.md +++ b/README.md @@ -278,7 +278,7 @@ Problem | Solution | Time | Space | Difficul ##Tree Problem | Solution | Time | Space | Difficulty | Notes --------------- | --------------- | --------------- | --------------- | -------------- | ----- -[Add and Search Word - Data structure design ](https://leetcode.com/problems/add-and-search-word-data-structure-design/) | [Python](./Python/add-and-search-word-data-structure-design.py) | _O(min(n, h))_ | _O(min(n, h))_ | Medium | `Trie` +[Add and Search Word - Data structure design ](https://leetcode.com/problems/add-and-search-word-data-structure-design/) | [C++](./C++/add-and-search-word-data-structure-design.cpp) [Python](./Python/add-and-search-word-data-structure-design.py) | _O(min(n, h))_ | _O(min(n, h))_ | Medium | `Trie` [Binary Tree Preorder Traversal] | [binary-tree-preorder-traversal.py] | _O(n)_| _O(1)_| Medium | `Morris Traversal` [Binary Tree Inorder Traversal] | [binary-tree-inorder-traversal.py] | _O(n)_| _O(1)_| Medium | `Morris Traversal` [Binary Tree Postorder Traversal]| [binary-tree-postorder-traversal.py] | _O(n)_| _O(1)_| Hard | `Morris Traversal` From cbc893bad1e5a93766353325656d06f3e3b0daf2 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 16 May 2015 11:00:12 +0800 Subject: [PATCH 218/345] Update README.md --- README.md | 25 ++++++++----------------- 1 file changed, 8 insertions(+), 17 deletions(-) diff --git a/README.md b/README.md index 84cc9b1d8..a2981d7de 100644 --- a/README.md +++ b/README.md @@ -276,23 +276,14 @@ Problem | Solution | Time | Space | Difficul --- ##Tree -Problem | Solution | Time | Space | Difficulty | Notes ---------------- | --------------- | --------------- | --------------- | -------------- | ----- -[Add and Search Word - Data structure design ](https://leetcode.com/problems/add-and-search-word-data-structure-design/) | [C++](./C++/add-and-search-word-data-structure-design.cpp) [Python](./Python/add-and-search-word-data-structure-design.py) | _O(min(n, h))_ | _O(min(n, h))_ | Medium | `Trie` -[Binary Tree Preorder Traversal] | [binary-tree-preorder-traversal.py] | _O(n)_| _O(1)_| Medium | `Morris Traversal` -[Binary Tree Inorder Traversal] | [binary-tree-inorder-traversal.py] | _O(n)_| _O(1)_| Medium | `Morris Traversal` -[Binary Tree Postorder Traversal]| [binary-tree-postorder-traversal.py] | _O(n)_| _O(1)_| Hard | `Morris Traversal` -[Implement Trie (Prefix Tree)](https://leetcode.com/problems/implement-trie-prefix-tree/) | [implement-trie-prefix-tree.py](./Python/implement-trie-prefix-tree.py) | _O(n)_ | _O(1)_ | Medium | `Trie` -[Recover Binary Search Tree]| [recover-binary-search-tree.py] | _O(n)_| _O(1)_| Hard | `Morris Traversal` - -[Binary Tree Preorder Traversal]:https://oj.leetcode.com/problems/binary-tree-preorder-traversal/ -[binary-tree-preorder-traversal.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/binary-tree-preorder-traversal.py -[Binary Tree Inorder Traversal]:https://oj.leetcode.com/problems/binary-tree-inorder-traversal/ -[binary-tree-inorder-traversal.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/binary-tree-inorder-traversal.py -[Binary Tree Postorder Traversal]:https://oj.leetcode.com/problems/binary-tree-postorder-traversal/ -[binary-tree-postorder-traversal.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/binary-tree-postorder-traversal.py -[Recover Binary Search Tree]:https://oj.leetcode.com/problems/recover-binary-search-tree/ -[recover-binary-search-tree.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/recover-binary-search-tree.py + # | Problem | Solution | Time | Space | Difficulty | Notes +-----|--------------- | --------------- | --------------- | --------------- | -------------- | ----- +94 | [Binary Tree Inorder Traversal](https://oj.leetcode.com/problems/binary-tree-inorder-traversal/) | [Python](./Python/binary-tree-inorder-traversal.py) | _O(n)_| _O(1)_| Medium | `Morris Traversal` | +99 | [Recover Binary Search Tree](https://oj.leetcode.com/problems/recover-binary-search-tree/) | [Python](./Python/recover-binary-search-tree.py) | _O(n)_| _O(1)_| Hard | `Morris Traversal` +144 | [Binary Tree Preorder Traversal](https://oj.leetcode.com/problems/binary-tree-preorder-traversal/) | [Python](./Python/binary-tree-preorder-traversal.py) | _O(n)_| _O(1)_| Medium | `Morris Traversal` +145 | [Binary Tree Postorder Traversal](https://oj.leetcode.com/problems/binary-tree-postorder-traversal/) | [Python](./Python/binary-tree-postorder-traversal.py) | _O(n)_| _O(1)_| Hard | `Morris Traversal` +208 | [Implement Trie (Prefix Tree)](https://leetcode.com/problems/implement-trie-prefix-tree/) | [Python](./Python/implement-trie-prefix-tree.py) | _O(n)_ | _O(1)_ | Medium | `Trie` +211 | [Add and Search Word - Data structure design ](https://leetcode.com/problems/add-and-search-word-data-structure-design/) | [Python](./Python/add-and-search-word-data-structure-design.py) | _O(min(n, h))_ | _O(min(n, h))_ | Medium | `Trie` --- From d5e2312f25cfebcdbc4865a8e765f9bbc05941e5 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 16 May 2015 11:03:03 +0800 Subject: [PATCH 219/345] Update README.md --- README.md | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index a2981d7de..75c4d3a77 100644 --- a/README.md +++ b/README.md @@ -276,14 +276,14 @@ Problem | Solution | Time | Space | Difficul --- ##Tree - # | Problem | Solution | Time | Space | Difficulty | Notes ------|--------------- | --------------- | --------------- | --------------- | -------------- | ----- -94 | [Binary Tree Inorder Traversal](https://oj.leetcode.com/problems/binary-tree-inorder-traversal/) | [Python](./Python/binary-tree-inorder-traversal.py) | _O(n)_| _O(1)_| Medium | `Morris Traversal` | -99 | [Recover Binary Search Tree](https://oj.leetcode.com/problems/recover-binary-search-tree/) | [Python](./Python/recover-binary-search-tree.py) | _O(n)_| _O(1)_| Hard | `Morris Traversal` -144 | [Binary Tree Preorder Traversal](https://oj.leetcode.com/problems/binary-tree-preorder-traversal/) | [Python](./Python/binary-tree-preorder-traversal.py) | _O(n)_| _O(1)_| Medium | `Morris Traversal` -145 | [Binary Tree Postorder Traversal](https://oj.leetcode.com/problems/binary-tree-postorder-traversal/) | [Python](./Python/binary-tree-postorder-traversal.py) | _O(n)_| _O(1)_| Hard | `Morris Traversal` -208 | [Implement Trie (Prefix Tree)](https://leetcode.com/problems/implement-trie-prefix-tree/) | [Python](./Python/implement-trie-prefix-tree.py) | _O(n)_ | _O(1)_ | Medium | `Trie` -211 | [Add and Search Word - Data structure design ](https://leetcode.com/problems/add-and-search-word-data-structure-design/) | [Python](./Python/add-and-search-word-data-structure-design.py) | _O(min(n, h))_ | _O(min(n, h))_ | Medium | `Trie` + # | Problem | Solution | Time | Space | Difficulty | Tag | Notes +-----|--------------- | --------------- | --------------- | --------------- | -------------- |--------------| ----- +94 | [Binary Tree Inorder Traversal](https://oj.leetcode.com/problems/binary-tree-inorder-traversal/) | [Python](./Python/binary-tree-inorder-traversal.py) | _O(n)_| _O(1)_| Medium || `Morris Traversal` | +99 | [Recover Binary Search Tree](https://oj.leetcode.com/problems/recover-binary-search-tree/) | [Python](./Python/recover-binary-search-tree.py) | _O(n)_| _O(1)_| Hard || `Morris Traversal` +144 | [Binary Tree Preorder Traversal](https://oj.leetcode.com/problems/binary-tree-preorder-traversal/) | [Python](./Python/binary-tree-preorder-traversal.py) | _O(n)_| _O(1)_| Medium || `Morris Traversal` +145 | [Binary Tree Postorder Traversal](https://oj.leetcode.com/problems/binary-tree-postorder-traversal/) | [Python](./Python/binary-tree-postorder-traversal.py) | _O(n)_| _O(1)_| Hard || `Morris Traversal` +208 | [Implement Trie (Prefix Tree)](https://leetcode.com/problems/implement-trie-prefix-tree/) | [Python](./Python/implement-trie-prefix-tree.py) | _O(n)_ | _O(1)_ | Medium || Trie +211 | [Add and Search Word - Data structure design ](https://leetcode.com/problems/add-and-search-word-data-structure-design/) | [Python](./Python/add-and-search-word-data-structure-design.py) | _O(min(n, h))_ | _O(min(n, h))_ | Medium || Trie, DFS --- From 3eb855840b835fe802cc3521db68c193d4050e2a Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 16 May 2015 11:04:12 +0800 Subject: [PATCH 220/345] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 75c4d3a77..694f8892c 100644 --- a/README.md +++ b/README.md @@ -283,7 +283,7 @@ Problem | Solution | Time | Space | Difficul 144 | [Binary Tree Preorder Traversal](https://oj.leetcode.com/problems/binary-tree-preorder-traversal/) | [Python](./Python/binary-tree-preorder-traversal.py) | _O(n)_| _O(1)_| Medium || `Morris Traversal` 145 | [Binary Tree Postorder Traversal](https://oj.leetcode.com/problems/binary-tree-postorder-traversal/) | [Python](./Python/binary-tree-postorder-traversal.py) | _O(n)_| _O(1)_| Hard || `Morris Traversal` 208 | [Implement Trie (Prefix Tree)](https://leetcode.com/problems/implement-trie-prefix-tree/) | [Python](./Python/implement-trie-prefix-tree.py) | _O(n)_ | _O(1)_ | Medium || Trie -211 | [Add and Search Word - Data structure design ](https://leetcode.com/problems/add-and-search-word-data-structure-design/) | [Python](./Python/add-and-search-word-data-structure-design.py) | _O(min(n, h))_ | _O(min(n, h))_ | Medium || Trie, DFS +211 | [Add and Search Word - Data structure design ](https://leetcode.com/problems/add-and-search-word-data-structure-design/) | [C++](./Python/add-and-search-word-data-structure-design.cpp) [Python](./Python/add-and-search-word-data-structure-design.py) | _O(min(n, h))_ | _O(min(n, h))_ | Medium || Trie, DFS --- From 2686786ca5132b8f47d8e92967e5530c505cbfb5 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 16 May 2015 11:11:29 +0800 Subject: [PATCH 221/345] Update README.md --- README.md | 27 ++++++++------------------- 1 file changed, 8 insertions(+), 19 deletions(-) diff --git a/README.md b/README.md index 694f8892c..f99910838 100644 --- a/README.md +++ b/README.md @@ -47,24 +47,13 @@ Shell --- ##Bit Manipulation -Problem | Solution | Time | Space | Difficulty | Notes ---------------- | --------------- | --------------- | --------------- | -------------- | ----- -[Number of 1 Bits] | [number-of-1-bits.py] | _O(m)_ | _O(1)_ | Easy | -[Reverse Bits] | [reverse-bits.py] | _O(n)_ | _O(1)_ | Easy | -[Bitwise AND of Numbers Range] | [bitwise-and-of-numbers-range.py] | _O(1)_ | _O(1)_ | Medium | -[Single Number] | [single-number.py] | _O(n)_ | _O(1)_ | Medium | -[Single Number II] | [single-number-ii.py] | _O(n)_ | _O(1)_ | Medium | - -[Number of 1 Bits]: https://oj.leetcode.com/problems/number-of-1-bits/ -[number-of-1-bits.py]: https://github.com/kamyu104/LeetCode/blob/master/Python/number-of-1-bits.py -[Reverse Bits]: https://oj.leetcode.com/problems/reverse-bits/ -[reverse-bits.py]: https://github.com/kamyu104/LeetCode/blob/master/Python/reverse-bits.py -[Bitwise AND of Numbers Range]: https://leetcode.com/problems/bitwise-and-of-numbers-range/ -[bitwise-and-of-numbers-range.py]: https://github.com/kamyu104/LeetCode/blob/master/Python/bitwise-and-of-numbers-range.py -[Single Number]: https://oj.leetcode.com/problems/single-number/ -[single-number.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/single-number.py -[Single Number II]: https://oj.leetcode.com/problems/single-number-ii/ -[single-number-ii.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/single-number-ii.py + # | Problem | Solution | Time | Space | Difficulty | Tag | Notes +-----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- +136 | [Single Number](https://oj.leetcode.com/problems/single-number/) | [Python](./Python/single-number.py) | _O(n)_ | _O(1)_ | Medium || +137 | [Single Number II](https://oj.leetcode.com/problems/single-number-ii/) | [Python](./Python/single-number-ii.py) | _O(n)_ | _O(1)_ | Medium || +190 | [Reverse Bits](https://oj.leetcode.com/problems/reverse-bits/) | [Python](./Python/reverse-bits.py) | _O(n)_ | _O(1)_ | Easy || +191 |[Number of 1 Bits](https://oj.leetcode.com/problems/number-of-1-bits/) | [Python](./Python/number-of-1-bits.py) | _O(m)_ | _O(1)_ | Easy || +201 | [Bitwise AND of Numbers Range](https://leetcode.com/problems/bitwise-and-of-numbers-range/) | [Python](./Python/bitwise-and-of-numbers-range.py) | _O(1)_ | _O(1)_ | Medium || --- @@ -277,7 +266,7 @@ Problem | Solution | Time | Space | Difficul ##Tree # | Problem | Solution | Time | Space | Difficulty | Tag | Notes ------|--------------- | --------------- | --------------- | --------------- | -------------- |--------------| ----- +-----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 94 | [Binary Tree Inorder Traversal](https://oj.leetcode.com/problems/binary-tree-inorder-traversal/) | [Python](./Python/binary-tree-inorder-traversal.py) | _O(n)_| _O(1)_| Medium || `Morris Traversal` | 99 | [Recover Binary Search Tree](https://oj.leetcode.com/problems/recover-binary-search-tree/) | [Python](./Python/recover-binary-search-tree.py) | _O(n)_| _O(1)_| Hard || `Morris Traversal` 144 | [Binary Tree Preorder Traversal](https://oj.leetcode.com/problems/binary-tree-preorder-traversal/) | [Python](./Python/binary-tree-preorder-traversal.py) | _O(n)_| _O(1)_| Medium || `Morris Traversal` From 7c9316c83036467820b8bf4480a98f0625de28e1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 16 May 2015 11:38:56 +0800 Subject: [PATCH 222/345] Update README.md --- README.md | 93 ++++++++++++++----------------------------------------- 1 file changed, 24 insertions(+), 69 deletions(-) diff --git a/README.md b/README.md index f99910838..3a1dece69 100644 --- a/README.md +++ b/README.md @@ -59,75 +59,30 @@ Shell ##Array -Problem | Solution | Time | Space | Difficulty | Notes ---------------- | --------------- | --------------- | --------------- | -------------- | ----- -[3 Sum] | [3sum.py] | _O(n^2)_ | _O(1)_ | Medium | -[3 Sum Closest] | [3sum-closest.py]| _O(n^2)_ | _O(1)_ | Medium | -[Best Time to Buy and Sell Stock]| [best-time-to-buy-and-sell-stock.py] | _O(n)_ | _O(1)_ | Medium | -[First Missing Positive]| [first-missing-positive.py] | _O(n)_ | _O(1)_ | Hard | Tricky -[Longest Consecutive Sequence]| [longest-consecutive-sequence.py] | _O(n)_ | _O(n)_ | Hard | Tricky -[Majority Element] | [majority-element.py] | _O(n)_ | _O(1)_ | Easy | -[Minimum Size Subarray Sum](https://leetcode.com/problems/minimum-size-subarray-sum/) | [minimum-size-subarray-sum.py] (./Python/minimum-size-subarray-sum.py) | _O(n)_ | _O(1)_ | Medium | -[Missing Ranges]| [missing-ranges.py] | _O(n)_ | _O(1)_ | Medium | -[Next Permutation]| [next-permutation.py] | _O(n)_ | _O(1)_ | Medium | Tricky -[Pascal's Triangle]| [pascals-triangle.py] | _O(n^2)_ | _O(n)_ | Easy | -[Pascal's Triangle II]| [pascals-triangle-ii.py] | _O(n^2)_ | _O(n)_ | Easy | -[Plus One] | [plus-one.py] | _O(n)_ | _O(1)_ | Easy | -[Read N Characters Given Read4] | [read-n-characters-given-read4.py] | _O(n)_ | _O(1)_ | Easy | -[Read N Characters Given Read4 II - Call multiple times] | [read-n-characters-given-read4-ii-call-multiple-times.py] | _O(n)_ | _O(1)_ | Hard | -[Remove Duplicates from Sorted Array]| [remove-duplicates-from-sorted-array.py] | _O(n)_ | _O(1)_ | Easy | -[Remove Duplicates from Sorted Array II]| [remove-duplicates-from-sorted-array-ii.py] | _O(n)_ | _O(1)_ | Medium | -[Remove Element] | [remove-element.py] | _O(n)_ | _O(1)_ | Easy | -[Rotate Array] | [rotate-array.py] | _O(n)_ | _O(1)_ | Easy | -[Rotate Image] | [rotate-image.py] | _O(n^2)_ | _O(1)_ | Medium | -[Set Matrix Zeroes] | [set-matrix-zeroes.py] | _O(m * n)_ | _O(1)_ | Medium | -[Spiral Matrix] | [spiral-matrix.py] | _O(m * n)_ | _O(1)_ | Medium | -[Spiral Matrix II] | [spiral-matrix-ii.py] | _O(m * n)_ | _O(1)_ | Medium | - - -[3 Sum]: https://oj.leetcode.com/problems/3sum/ -[3sum.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/3sum.py -[3 Sum Closest]: https://oj.leetcode.com/problems/3sum-closest/ -[3sum-closest.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/3sum-closest.py -[Best Time to Buy and Sell Stock]:https://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock/ -[best-time-to-buy-and-sell-stock.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/best-time-to-buy-and-sell-stock.py -[First Missing Positive]:https://oj.leetcode.com/problems/first-missing-positive/ -[first-missing-positive.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/first-missing-positive.py -[Longest Consecutive Sequence]:https://oj.leetcode.com/problems/longest-consecutive-sequence/ -[longest-consecutive-sequence.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/longest-consecutive-sequence.py -[Majority Element]: https://oj.leetcode.com/problems/majority-element/ -[majority-element.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/majority-element.py -[Missing Ranges]:https://oj.leetcode.com/problems/missing-ranges/ -[missing-ranges.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/missing-ranges.py -[Next Permutation]:https://oj.leetcode.com/problems/next-permutation/ -[next-permutation.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/next-permutation.py -[Pascal's Triangle]:https://oj.leetcode.com/problems/pascals-triangle/ -[pascals-triangle.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/pascals-triangle.py -[Pascal's Triangle II]:https://oj.leetcode.com/problems/pascals-triangle-ii/ -[pascals-triangle-ii.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/pascals-triangle-ii.py -[Plus One]:https://oj.leetcode.com/problems/plus-one/ -[plus-one.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/plus-one.py -[Read N Characters Given Read4]:https://oj.leetcode.com/problems/read-n-characters-given-read4/ -[read-n-characters-given-read4.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/read-n-characters-given-read4.py -[Read N Characters Given Read4 II - Call multiple times]:https://oj.leetcode.com/problems/read-n-characters-given-read4-ii-call-multiple-times/ -[read-n-characters-given-read4-ii-call-multiple-times.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/read-n-characters-given-read4-ii-call-multiple-times.py -[Remove Duplicates from Sorted Array]:https://oj.leetcode.com/problems/remove-duplicates-from-sorted-array/ -[remove-duplicates-from-sorted-array.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/remove-duplicates-from-sorted-array.py -[Remove Duplicates from Sorted Array II]:https://oj.leetcode.com/problems/remove-duplicates-from-sorted-array-ii/ -[remove-duplicates-from-sorted-array-ii.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/remove-duplicates-from-sorted-array-ii.py -[Remove Element]:https://oj.leetcode.com/problems/remove-element/ -[remove-element.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/remove-element.py -[Rotate Array]:https://oj.leetcode.com/problems/rotate-array/ -[rotate-array.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/rotate-array.py -[Rotate Image]:https://oj.leetcode.com/problems/rotate-image/ -[rotate-image.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/rotate-image.py -[Set Matrix Zeroes]:https://oj.leetcode.com/problems/set-matrix-zeroes/ -[set-matrix-zeroes.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/set-matrix-zeroes.py -[Spiral Matrix]:https://oj.leetcode.com/problems/spiral-matrix/ -[spiral-matrix.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/spiral-matrix.py -[Spiral Matrix II]:https://oj.leetcode.com/problems/spiral-matrix-ii/ -[spiral-matrix-ii.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/spiral-matrix-ii.py - + # | Problem | Solution | Time | Space | Difficulty | Tag | Notes +-----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- +15 | [3 Sum](https://oj.leetcode.com/problems/3sum/) | [Python](./Python/3sum.py) | _O(n^2)_ | _O(1)_ | Medium || +16 | [3 Sum Closest](https://oj.leetcode.com/problems/3sum-closest/) | [Python](./Python/3sum-closest.py)| _O(n^2)_ | _O(1)_ | Medium || +26 | [Remove Duplicates from Sorted Array](https://oj.leetcode.com/problems/remove-duplicates-from-sorted-array/)| [Python](./Python/remove-duplicates-from-sorted-array.py) | _O(n)_ | _O(1)_ | Easy || +27 | [Remove Element](https://oj.leetcode.com/problems/remove-element/) | [Python](./Python/remove-element.py) | _O(n)_ | _O(1)_ | Easy || +31 | [Next Permutation](https://oj.leetcode.com/problems/next-permutation/)| [Python](./Python/next-permutation.py) | _O(n)_ | _O(1)_ | Medium || Tricky +41 | [First Missing Positive](https://oj.leetcode.com/problems/first-missing-positive/)| [Python](./Python/first-missing-positive.py) | _O(n)_ | _O(1)_ | Hard || Tricky +48 | [Rotate Image](https://oj.leetcode.com/problems/rotate-image/) | [Python](./Python/rotate-image.py) | _O(n^2)_ | _O(1)_ | Medium || +54 | [Spiral Matrix](https://oj.leetcode.com/problems/spiral-matrix/) | [Python](./Python/spiral-matrix.py) | _O(m * n)_ | _O(1)_ | Medium || +59 | [Spiral Matrix II](https://oj.leetcode.com/problems/spiral-matrix-ii/) | [Python](./Python/spiral-matrix-ii.py) | _O(m * n)_ | _O(1)_ | Medium || +66 | [Plus One]([Plus One]:https://oj.leetcode.com/problems/plus-one/) | [Python](./Python/plus-one.py) | _O(n)_ | _O(1)_ | Easy || +73 | [Set Matrix Zeroes](https://oj.leetcode.com/problems/set-matrix-zeroes/) | [Python](./Python/set-matrix-zeroes.py) | _O(m * n)_ | _O(1)_ | Medium || +80 | [Remove Duplicates from Sorted Array II](https://oj.leetcode.com/problems/remove-duplicates-from-sorted-array-ii/)| [Python](./Python/remove-duplicates-from-sorted-array-ii.py) | _O(n)_ | _O(1)_ | Medium || +118 | [Pascal's Triangle](https://oj.leetcode.com/problems/pascals-triangle/)| [Python](./Python/pascals-triangle.py) | _O(n^2)_ | _O(n)_ | Easy || +119 | [Pascal's Triangle II](https://oj.leetcode.com/problems/pascals-triangle-ii/)| [Python](./Python/pascals-triangle-ii.py) | _O(n^2)_ | _O(n)_ | Easy || +121 | [Best Time to Buy and Sell Stock](https://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock/)| [Python](./Python/best-time-to-buy-and-sell-stock.py) | _O(n)_ | _O(1)_ | Medium || +128 | [Longest Consecutive Sequence](https://oj.leetcode.com/problems/longest-consecutive-sequence/)| [Python](./Python/longest-consecutive-sequence.py) | _O(n)_ | _O(n)_ | Hard || Tricky +157 | [Read N Characters Given Read4](https://oj.leetcode.com/problems/read-n-characters-given-read4/) | [Python](/Python/read-n-characters-given-read4.py) | _O(n)_ | _O(1)_ | Easy || +158 | [Read N Characters Given Read4 II - Call multiple times](https://oj.leetcode.com/problems/read-n-characters-given-read4-ii-call-multiple-times/) | [Python](./Python/read-n-characters-given-read4-ii-call-multiple-times.py) | _O(n)_ | _O(1)_ | Hard || +163 | [Missing Ranges](https://oj.leetcode.com/problems/missing-ranges/)| [Python](./Python/missing-ranges.py) | _O(n)_ | _O(1)_ | Medium || +169 | [Majority Element](https://oj.leetcode.com/problems/majority-element/) | [Python](./Python/majority-element.py) | _O(n)_ | _O(1)_ | Easy | +189 | [Rotate Array](https://oj.leetcode.com/problems/rotate-array/) | [Python](./Python/rotate-array.py) | _O(n)_ | _O(1)_ | Easy || +209 | [Minimum Size Subarray Sum](https://leetcode.com/problems/minimum-size-subarray-sum/) | [minimum-size-subarray-sum.py] (./Python/minimum-size-subarray-sum.py) | _O(n)_ | _O(1)_ | Medium || --- From 74573bea7ddebbc150d581917b2e2be48c1a5dc6 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 16 May 2015 11:40:22 +0800 Subject: [PATCH 223/345] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 3a1dece69..9f2688e14 100644 --- a/README.md +++ b/README.md @@ -82,7 +82,7 @@ Shell 163 | [Missing Ranges](https://oj.leetcode.com/problems/missing-ranges/)| [Python](./Python/missing-ranges.py) | _O(n)_ | _O(1)_ | Medium || 169 | [Majority Element](https://oj.leetcode.com/problems/majority-element/) | [Python](./Python/majority-element.py) | _O(n)_ | _O(1)_ | Easy | 189 | [Rotate Array](https://oj.leetcode.com/problems/rotate-array/) | [Python](./Python/rotate-array.py) | _O(n)_ | _O(1)_ | Easy || -209 | [Minimum Size Subarray Sum](https://leetcode.com/problems/minimum-size-subarray-sum/) | [minimum-size-subarray-sum.py] (./Python/minimum-size-subarray-sum.py) | _O(n)_ | _O(1)_ | Medium || +209 | [Minimum Size Subarray Sum](https://leetcode.com/problems/minimum-size-subarray-sum/) | [Python] (./Python/minimum-size-subarray-sum.py) | _O(n)_ | _O(1)_ | Medium || --- From a68759c333111650ded557b9c627e8e2a6c5b689 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 16 May 2015 11:48:33 +0800 Subject: [PATCH 224/345] Update README.md --- README.md | 21 ++++++--------------- 1 file changed, 6 insertions(+), 15 deletions(-) diff --git a/README.md b/README.md index 9f2688e14..568ea8ea8 100644 --- a/README.md +++ b/README.md @@ -747,18 +747,9 @@ Problem | Solution | Time | Space | Difficul --- ##Shell Script -Problem | Solution | Time | Space | Difficulty | Notes ---------------- | --------------- | --------------- | --------------- | -------------- | ----- -[Tenth Line] | [tenth-line.sh] | _O(n)_ | _O(1)_ | Easy | -[Transpose File] | [transpose-file.sh] | _O(n^2)_ | _O(n^2)_ | Medium | -[Valid Phone Numbers] | [valid-phone-numbers.sh] | _O(n)_ | _O(1)_ | Easy | -[Word Frequency] | [word-frequency.sh] | _O(n)_ | _O(k)_ | Medium | - -[Tenth Line]:https://oj.leetcode.com/problems/tenth-line/ -[tenth-line.sh]:https://github.com/kamyu104/LeetCode/blob/master/Shell/tenth-line.sh -[Transpose File]:https://oj.leetcode.com/problems/transpose-file/ -[transpose-file.sh]:https://github.com/kamyu104/LeetCode/blob/master/Shell/transpose-file.sh -[Valid Phone Numbers]:https://oj.leetcode.com/problems/valid-phone-numbers/ -[valid-phone-numbers.sh]:https://github.com/kamyu104/LeetCode/blob/master/Shell/valid-phone-numbers.sh -[Word Frequency]:https://oj.leetcode.com/problems/word-frequency/ -[word-frequency.sh]:https://github.com/kamyu104/LeetCode/blob/master/Shell/word-frequency.sh + # | Problem | Solution | Time | Space | Difficulty | Tag | Notes +-----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- +192 | [Word Frequency](https://oj.leetcode.com/problems/word-frequency/) | [Shell](./Shell/word-frequency.sh) | _O(n)_ | _O(k)_ | Medium || +193 | [Valid Phone Numbers](https://oj.leetcode.com/problems/valid-phone-numbers/) | [Shell](./Shell/valid-phone-numbers.sh) | _O(n)_ | _O(1)_ | Easy || +194 | [Transpose File](https://oj.leetcode.com/problems/transpose-file/) | [Shell](./Shell/transpose-file.sh) | _O(n^2)_ | _O(n^2)_ | Medium || +195 | [Tenth Line](https://oj.leetcode.com/problems/tenth-line/) | [Shell](./Shell/tenth-line.sh) | _O(n)_ | _O(1)_ | Easy || From 091af2f9cdcaeac322be91efb8c640f9bbbbc52e Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 16 May 2015 11:51:43 +0800 Subject: [PATCH 225/345] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 568ea8ea8..a85379e50 100644 --- a/README.md +++ b/README.md @@ -70,7 +70,7 @@ Shell 48 | [Rotate Image](https://oj.leetcode.com/problems/rotate-image/) | [Python](./Python/rotate-image.py) | _O(n^2)_ | _O(1)_ | Medium || 54 | [Spiral Matrix](https://oj.leetcode.com/problems/spiral-matrix/) | [Python](./Python/spiral-matrix.py) | _O(m * n)_ | _O(1)_ | Medium || 59 | [Spiral Matrix II](https://oj.leetcode.com/problems/spiral-matrix-ii/) | [Python](./Python/spiral-matrix-ii.py) | _O(m * n)_ | _O(1)_ | Medium || -66 | [Plus One]([Plus One]:https://oj.leetcode.com/problems/plus-one/) | [Python](./Python/plus-one.py) | _O(n)_ | _O(1)_ | Easy || +66 | [Plus One](https://oj.leetcode.com/problems/plus-one/) | [Python](./Python/plus-one.py) | _O(n)_ | _O(1)_ | Easy || 73 | [Set Matrix Zeroes](https://oj.leetcode.com/problems/set-matrix-zeroes/) | [Python](./Python/set-matrix-zeroes.py) | _O(m * n)_ | _O(1)_ | Medium || 80 | [Remove Duplicates from Sorted Array II](https://oj.leetcode.com/problems/remove-duplicates-from-sorted-array-ii/)| [Python](./Python/remove-duplicates-from-sorted-array-ii.py) | _O(n)_ | _O(1)_ | Medium || 118 | [Pascal's Triangle](https://oj.leetcode.com/problems/pascals-triangle/)| [Python](./Python/pascals-triangle.py) | _O(n^2)_ | _O(n)_ | Easy || From f9aeac95d9cffd13c3a9ee3922f465149cc9612d Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 16 May 2015 12:05:10 +0800 Subject: [PATCH 226/345] Update README.md --- README.md | 53 ++++++++++++++--------------------------------------- 1 file changed, 14 insertions(+), 39 deletions(-) diff --git a/README.md b/README.md index a85379e50..a0db4b983 100644 --- a/README.md +++ b/README.md @@ -704,45 +704,20 @@ Problem | Solution | Time | Space | Difficul --- ##SQL -Problem | Solution | Time | Space | Difficulty | Notes ---------------- | --------------- | --------------- | --------------- | -------------- | ----- -[Combine Two Tables] | [combine-two-tables.sql] | _O(m + n)_ | _O(m + n)_ | Easy | -[Consecutive Numbers] | [consecutive-numbers.sql] | _O(n)_ | _O(n)_ | Medium | -[Customers Who Never Order] | [customers-who-never-order.sql] | _O(n^2)_ | _O(1)_ | Easy | -[Delete Duplicate Emails] | [delete-duplicate-emails.sql] | _O(n^2)_ | _O(n)_ | Easy | -[Department Highest Salary] | [department-highest-salary.sql] | _O(n^2)_ | _O(n)_ | Medium | -[Department Top Three Salaries] | [department-top-three-salaries.sql] | _O(n^2)_ | _O(n)_ | Hard | -[Duplicate Emails] | [duplicate-emails.sql] | _O(n^2)_ | _O(n)_ | Easy | -[Employees Earning More Than Their Managers] | [employees-earning-more-than-their-managers.sql] | _O(n^2)_ | _O(1)_ | Easy | -[Nth Highest Salary] | [nth-highest-salary.sql] | _O(n^2)_ | _O(n)_ | Medium | -[Rank Scores] | [rank-scores.sql] | _O(n^2)_ | _O(n)_ | Medium | -[Rising Temperature] | [rising-temperature.sql] | _O(n^2)_ | _O(n)_ | Easy | -[Second Highest Salary] | [second-highest-salary.sql] | _O(n)_ | _O(1)_ | Easy | - -[Combine Two Tables]:https://oj.leetcode.com/problems/combine-two-tables/ -[combine-two-tables.sql]:https://github.com/kamyu104/LeetCode/blob/master/MySQL/combine-two-tables.sql -[Consecutive Numbers]:https://oj.leetcode.com/problems/consecutive-numbers/ -[consecutive-numbers.sql]:https://github.com/kamyu104/LeetCode/blob/master/MySQL/consecutive-numbers.sql -[Customers Who Never Order]:https://oj.leetcode.com/problems/customers-who-never-order/ -[customers-who-never-order.sql]:https://github.com/kamyu104/LeetCode/blob/master/MySQL/customers-who-never-order.sql -[Delete Duplicate Emails]:https://oj.leetcode.com/problems/delete-duplicate-emails/ -[delete-duplicate-emails.sql]:https://github.com/kamyu104/LeetCode/blob/master/MySQL/delete-duplicate-emails.sql -[Department Highest Salary]:https://oj.leetcode.com/problems/department-highest-salary/ -[department-highest-salary.sql]:https://github.com/kamyu104/LeetCode/blob/master/MySQL/department-highest-salary.sql -[Department Top Three Salaries]:https://oj.leetcode.com/problems/department-top-three-salaries/ -[department-top-three-salaries.sql]:https://github.com/kamyu104/LeetCode/blob/master/MySQL/department-top-three-salaries.sql -[Duplicate Emails]:https://oj.leetcode.com/problems/duplicate-emails/ -[duplicate-emails.sql]:https://github.com/kamyu104/LeetCode/blob/master/MySQL/duplicate-emails.sql -[Employees Earning More Than Their Managers]:https://oj.leetcode.com/problems/employees-earning-more-than-their-managers/ -[employees-earning-more-than-their-managers.sql]:https://github.com/kamyu104/LeetCode/blob/master/MySQL/employees-earning-more-than-their-managers.sql -[Nth Highest Salary]:https://oj.leetcode.com/problems/nth-highest-salary/ -[nth-highest-salary.sql]:https://github.com/kamyu104/LeetCode/blob/master/MySQL/nth-highest-salary.sql -[Rank Scores]:https://oj.leetcode.com/problems/rank-scores/ -[rank-scores.sql]:https://github.com/kamyu104/LeetCode/blob/master/MySQL/rank-scores.sql -[Rising Temperature]:https://oj.leetcode.com/problems/rising-temperature/ -[rising-temperature.sql]:https://github.com/kamyu104/LeetCode/blob/master/MySQL/rising-temperature.sql -[Second Highest Salary]:https://oj.leetcode.com/problems/second-highest-salary/ -[second-highest-salary.sql]:https://github.com/kamyu104/LeetCode/blob/master/MySQL/second-highest-salary.sql + # | Problem | Solution | Time | Space | Difficulty | Tag | Notes +-----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- +175| [Combine Two Tables](https://oj.leetcode.com/problems/combine-two-tables/) | [MySQL](./MySQL/combine-two-tables.sql) | _O(m + n)_ | _O(m + n)_ | Easy || +176| [Second Highest Salary](https://oj.leetcode.com/problems/second-highest-salary/) | [MySQL](./MySQL/second-highest-salary.sql) | _O(n)_ | _O(1)_ | Easy || +177| [Nth Highest Salary](https://oj.leetcode.com/problems/nth-highest-salary/) | [MySQL](./MySQL/nth-highest-salary.sql) | _O(n^2)_ | _O(n)_ | Medium || +178| [Rank Scores](https://oj.leetcode.com/problems/rank-scores/) | [MySQL](./MySQL/rank-scores.sql) | _O(n^2)_ | _O(n)_ | Medium || +180| [Consecutive Numbers](https://oj.leetcode.com/problems/consecutive-numbers/) | [MySQL](./MySQL/consecutive-numbers.sql) | _O(n)_ | _O(n)_ | Medium || +181| [Employees Earning More Than Their Managers](https://oj.leetcode.com/problems/employees-earning-more-than-their-managers/) | [MySQL](./MySQL/employees-earning-more-than-their-managers.sql) | _O(n^2)_ | _O(1)_ | Easy || +182| [Duplicate Emails](https://oj.leetcode.com/problems/duplicate-emails/) | [MySQL](./MySQL/duplicate-emails.sql) | _O(n^2)_ | _O(n)_ | Easy || +183| [Customers Who Never Order](https://oj.leetcode.com/problems/customers-who-never-order/) | [MySQL](./MySQL/customers-who-never-order.sql) | _O(n^2)_ | _O(1)_ | Easy || +184| [Department Highest Salary](https://oj.leetcode.com/problems/department-highest-salary/) | [MySQL](./MySQL/department-highest-salary.sql) | _O(n^2)_ | _O(n)_ | Medium || +185| [Department Top Three Salaries](https://oj.leetcode.com/problems/department-top-three-salaries/) | [MySQL](./MySQL/department-top-three-salaries.sql) | _O(n^2)_ | _O(n)_ | Hard || +196| [Delete Duplicate Emails](https://oj.leetcode.com/problems/delete-duplicate-emails/) | [MySQL](./MySQL/delete-duplicate-emails.sql) | _O(n^2)_ | _O(n)_ | Easy || +197| [Rising Temperature](https://oj.leetcode.com/problems/rising-temperature/) | [MySQL](./MySQL/rising-temperature.sql) | _O(n^2)_ | _O(n)_ | Easy || --- From f25b46b97585377a058d8ca5acc13aa1fc202ea3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 16 May 2015 12:28:23 +0800 Subject: [PATCH 227/345] Update README.md --- README.md | 69 +++++++++++++++---------------------------------------- 1 file changed, 18 insertions(+), 51 deletions(-) diff --git a/README.md b/README.md index a0db4b983..5832e7bc4 100644 --- a/README.md +++ b/README.md @@ -87,57 +87,24 @@ Shell --- ##String -Problem | Solution | Time | Space | Difficulty | Notes ---------------- | --------------- | --------------- | --------------- | -------------- | ----- -[Add Binary] | [add-binary.py] | _O(n)_ | _O(1)_ | Easy | -[Compare Version Numbers] | [compare-version-numbers.py] | _O(n)_ | _O(1)_ | Easy | -[Count and Say] | [count-and-say.py]| _O(n * 2^n)_ | _O(2^n)_ | Easy | -[Implement strStr()] | [implement-strstr.py] | _O(n + m)_ | _O(m)_ | Easy | `KMP Algorithm` -[Isomorphic Strings] | [isomorphic-strings.py] | _O(n)_ | _O(1)_ | Easy | -[Length of Last Word] | [length-of-last-word.py] | _O(n)_ | _O(1)_ | Easy | -[Longest Common Prefix] | [longest-common-prefix.py] | _O(n1 + n2 + ...)_ | _O(1)_ | Easy | -[Longest Palindromic Substring] | [longest-palindromic-substring.py] | _O(n)_ | _O(n)_ | Medium | `Manacher's Algorithm` -[Multiply Strings] | [multiply-strings.py] | _O(m * n)_ | _O(m + n)_ | Medium | -[One Edit Distance] | [one-edit-distance.py] | _O(m + n)_ | _O(1)_ | Medium | -[Reverse Words in a String] | [reverse-words-in-a-string.py] | _O(n)_ | _O(n)_ | Medium | -[Reverse Words in a String II] | [reverse-words-in-a-string-ii.py] | _O(n)_ | _O(1)_ | Medium | -[String to Integer (atoi)] | [string-to-integer-atoi.py] | _O(n)_ | _O(1)_ | Easy | -[Text Justification] | [text-justification.py] | _O(n)_ | _O(1)_ | Hard | -[Valid Palindrome] | [valid-palindrome.py] | _O(n)_ | _O(1)_ | Easy | -[ZigZag Conversion] | [zigzag-conversion.py] | _O(n)_ | _O(1)_ | Easy | - -[Add Binary]:https://oj.leetcode.com/problems/add-binary/ -[add-binary.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/add-binary.py -[Count and Say]:https://oj.leetcode.com/problems/count-and-say/ -[count-and-say.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/count-and-say.py -[Compare Version Numbers]:https://oj.leetcode.com/problems/compare-version-numbers/ -[compare-version-numbers.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/compare-version-numbers.py -[Implement strStr()]:https://oj.leetcode.com/problems/implement-strstr/ -[implement-strstr.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/implement-strstr.py -[Isomorphic Strings]:https://oj.leetcode.com/problems/isomorphic-strings/ -[isomorphic-strings.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/isomorphic-strings.py -[Length of Last Word]:https://oj.leetcode.com/problems/length-of-last-word/ -[length-of-last-word.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/length-of-last-word.py -[Longest Common Prefix]:https://oj.leetcode.com/problems/longest-common-prefix/ -[longest-common-prefix.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/longest-common-prefix.py -[Longest Palindromic Substring]:https://oj.leetcode.com/problems/longest-palindromic-substring/ -[longest-palindromic-substring.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/longest-palindromic-substring.py -[Multiply Strings]:https://oj.leetcode.com/problems/multiply-strings/ -[multiply-strings.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/multiply-strings.py -[One Edit Distance]:https://oj.leetcode.com/problems/one-edit-distance/ -[one-edit-distance.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/one-edit-distance.py -[Reverse Words in a String]:https://oj.leetcode.com/problems/reverse-words-in-a-string/ -[reverse-words-in-a-string.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/reverse-words-in-a-string.py -[Reverse Words in a String II]:https://oj.leetcode.com/problems/reverse-words-in-a-string-ii/ -[reverse-words-in-a-string-ii.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/reverse-words-in-a-string-ii.py -[String to Integer (atoi)]:https://oj.leetcode.com/problems/string-to-integer-atoi/ -[string-to-integer-atoi.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/string-to-integer-atoi.py -[Text Justification]:https://oj.leetcode.com/problems/text-justification/ -[text-justification.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/text-justification.py -[Valid Palindrome]:https://oj.leetcode.com/problems/valid-palindrome/ -[valid-palindrome.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/valid-palindrome.py -[ZigZag Conversion]:https://oj.leetcode.com/problems/zigzag-conversion/ -[zigzag-conversion.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/zigzag-conversion.py + # | Problem | Solution | Time | Space | Difficulty | Tag | Notes +-----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- +5| [Longest Palindromic Substring](https://oj.leetcode.com/problems/longest-palindromic-substring/) | [Python](./Python/longest-palindromic-substring.py) | _O(n)_ | _O(n)_ | Medium || `Manacher's Algorithm` +6| [ZigZag Conversion](https://oj.leetcode.com/problems/zigzag-conversion/) | [Python](./Python/zigzag-conversion.py) | _O(n)_ | _O(1)_ | Easy || +8| [String to Integer (atoi)](https://oj.leetcode.com/problems/string-to-integer-atoi/) | [Python](./Python/string-to-integer-atoi.py) | _O(n)_ | _O(1)_ | Easy || +14| [Longest Common Prefix](https://oj.leetcode.com/problems/longest-common-prefix/) | [Python](./Python/longest-common-prefix.py) | _O(n1 + n2 + ...)_ | _O(1)_ | Easy || +20| [Valid Palindrome](https://oj.leetcode.com/problems/valid-palindrome/) | [Python](./Python/valid-palindrome.py) | _O(n)_ | _O(1)_ | Easy || +28| [Implement strStr()](https://oj.leetcode.com/problems/implement-strstr/) | [Python](./Python/implement-strstr.py) | _O(n + m)_ | _O(m)_ | Easy || `KMP Algorithm` +38| [Count and Say](https://oj.leetcode.com/problems/compare-version-numbers/) | [Python](./Python/compare-version-numbers.py)| _O(n * 2^n)_ | _O(2^n)_ | Easy || +43| [Multiply Strings](https://oj.leetcode.com/problems/multiply-strings/) | [Python](./Python/multiply-strings.py) | _O(m * n)_ | _O(m + n)_ | Medium || +58| [Length of Last Word](https://oj.leetcode.com/problems/length-of-last-word/) | [Python](./Python/length-of-last-word.py) | _O(n)_ | _O(1)_ | Easy || +67| [Add Binary](https://oj.leetcode.com/problems/add-binary/) | [Python](./Python/add-binary.py) | _O(n)_ | _O(1)_ | Easy || +68| [Text Justification](https://oj.leetcode.com/problems/text-justification/) | [Python](./Python/text-justification.py) | _O(n)_ | _O(1)_ | Hard || +151| [Reverse Words in a String](https://oj.leetcode.com/problems/reverse-words-in-a-string/) | [Python](./Python/reverse-words-in-a-string.py) | _O(n)_ | _O(n)_ | Medium || +161| [One Edit Distance](https://oj.leetcode.com/problems/one-edit-distance/) | [Python](./Python/one-edit-distance.py) | _O(m + n)_ | _O(1)_ | Medium || +165| [Compare Version Numbers](https://oj.leetcode.com/problems/count-and-say/) | [Python](./Python/count-and-say.py) | _O(n)_ | _O(1)_ | Easy || +186| [Reverse Words in a String II](https://oj.leetcode.com/problems/reverse-words-in-a-string-ii/) | [Python](./Python/reverse-words-in-a-string-ii.py) | _O(n)_ | _O(1)_ | Medium || +205| [Isomorphic Strings](https://oj.leetcode.com/problems/isomorphic-strings/) | [Python](./Python/isomorphic-strings.py) | _O(n)_ | _O(1)_ | Easy || --- From eaaee1179be4273090f93d4a57d78d34029e7f2e Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 16 May 2015 12:43:32 +0800 Subject: [PATCH 228/345] Update README.md --- README.md | 49 +++++++++++++------------------------------------ 1 file changed, 13 insertions(+), 36 deletions(-) diff --git a/README.md b/README.md index 5832e7bc4..fdbd30b3e 100644 --- a/README.md +++ b/README.md @@ -109,42 +109,19 @@ Shell --- ##Linked List -Problem | Solution | Time | Space | Difficulty | Notes ---------------- | --------------- | --------------- | --------------- | -------------- | ----- -[Add Two Numbers] | [add-two-numbers.py] | _O(n)_ | _O(1)_ | Medium | -[Copy List with Random Pointer] | [copy-list-with-random-pointer.py] | _O(n)_ | _O(1)_ | Hard | -[Intersection of Two Linked Lists]| [intersection-of-two-linked-lists.py] | _O(m + n)_ | _O(1)_ | Easy | -[Remove Duplicates from Sorted List]| [remove-duplicates-from-sorted-list.py] | _O(n)_ | _O(1)_ | Easy | -[Remove Duplicates from Sorted List II]| [remove-duplicates-from-sorted-list-ii.py] | _O(n)_ | _O(1)_ | Medium | -[Remove Linked List Elements]| [remove-linked-list-elements.py] | _O(n)_ | _O(1)_ | Easy | -[Reverse Linked List]| [reverse-linked-list.py] | _O(n)_ | _O(1)_ | Easy | -[Reverse Linked List II]| [reverse-linked-list-ii.py] | _O(n)_ | _O(1)_ | Medium | -[Reverse Nodes in k-Group]| [reverse-nodes-in-k-group.py] | _O(n)_ | _O(1)_ | Hard | -[Rotate List]| [rotate-list.py] | _O(n)_ | _O(1)_ | Medium | -[Swap Nodes in Pairs]| [swap-nodes-in-pairs.py] | _O(n)_ | _O(1)_ | Medium | - -[Add Two Numbers]:https://oj.leetcode.com/problems/add-two-numbers/ -[add-two-numbers.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/add-two-numbers.py -[Copy List with Random Pointer]:https://oj.leetcode.com/problems/copy-list-with-random-pointer/ -[copy-list-with-random-pointer.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/copy-list-with-random-pointer.py -[Intersection of Two Linked Lists]:https://oj.leetcode.com/problems/intersection-of-two-linked-lists/ -[intersection-of-two-linked-lists.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/intersection-of-two-linked-lists.py -[Remove Duplicates from Sorted List]:https://oj.leetcode.com/problems/remove-duplicates-from-sorted-list/ -[remove-duplicates-from-sorted-list.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/remove-duplicates-from-sorted-list.py -[Remove Duplicates from Sorted List II]:https://oj.leetcode.com/problems/remove-duplicates-from-sorted-list-ii/ -[remove-duplicates-from-sorted-list-ii.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/remove-duplicates-from-sorted-list-ii.py -[Remove Linked List Elements]:https://oj.leetcode.com/problems/remove-linked-list-elements/ -[remove-linked-list-elements.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/remove-linked-list-elements.py -[Reverse Linked List]:https://oj.leetcode.com/problems/reverse-linked-list/ -[reverse-linked-list.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/reverse-linked-list.py -[Reverse Linked List II]:https://oj.leetcode.com/problems/reverse-linked-list-ii/ -[reverse-linked-list-ii.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/reverse-linked-list-ii.py -[Reverse Nodes in k-Group]:https://oj.leetcode.com/problems/reverse-nodes-in-k-group/ -[reverse-nodes-in-k-group.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/reverse-nodes-in-k-group.py -[Rotate List]:https://oj.leetcode.com/problems/rotate-list/ -[rotate-list.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/rotate-list.py -[Swap Nodes in Pairs]:https://oj.leetcode.com/problems/swap-nodes-in-pairs/ -[swap-nodes-in-pairs.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/swap-nodes-in-pairs.py + # | Problem | Solution | Time | Space | Difficulty | Tag | Notes +-----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- +2| [Add Two Numbers](https://oj.leetcode.com/problems/add-two-numbers/) | [Python](./Python/add-two-numbers.py) | _O(n)_ | _O(1)_ | Medium || +24| [Swap Nodes in Pairs](https://oj.leetcode.com/problems/swap-nodes-in-pairs/)| [Python](./Python/swap-nodes-in-pairs.py) | _O(n)_ | _O(1)_ | Medium || +25| [Reverse Nodes in k-Group](https://oj.leetcode.com/problems/reverse-nodes-in-k-group/)| [Python](./Python/reverse-nodes-in-k-group.py) | _O(n)_ | _O(1)_ | Hard || +61| [Rotate List](https://oj.leetcode.com/problems/rotate-list/)| [Python](./Python/rotate-list.py) | _O(n)_ | _O(1)_ | Medium || +82| [Remove Duplicates from Sorted List II](https://oj.leetcode.com/problems/remove-duplicates-from-sorted-list-ii/)| [Python](./Python/remove-duplicates-from-sorted-list-ii.py) | _O(n)_ | _O(1)_ | Medium || +83| [Remove Duplicates from Sorted List](https://oj.leetcode.com/problems/remove-duplicates-from-sorted-list/)| [Python](./Python/remove-duplicates-from-sorted-list.py) | _O(n)_ | _O(1)_ | Easy || +92| [Reverse Linked List II](https://oj.leetcode.com/problems/reverse-linked-list-ii/)| [Python](./Python/reverse-linked-list-ii.py) | _O(n)_ | _O(1)_ | Medium || +138| [Copy List with Random Pointer](https://oj.leetcode.com/problems/copy-list-with-random-pointer/) | [Python](./Python/copy-list-with-random-pointer.py) | _O(n)_ | _O(1)_ | Hard || +160| [Intersection of Two Linked Lists](https://oj.leetcode.com/problems/intersection-of-two-linked-lists/)| [Python](./Python/intersection-of-two-linked-lists.py) | _O(m + n)_ | _O(1)_ | Easy || +203| [Remove Linked List Elements](https://oj.leetcode.com/problems/remove-linked-list-elements/)| [Python](./Python/remove-linked-list-elements.py) | _O(n)_ | _O(1)_ | Easy || +206| [Reverse Linked List](https://oj.leetcode.com/problems/reverse-linked-list/)| [Python](./Python/reverse-linked-list.py) | _O(n)_ | _O(1)_ | Easy || --- From 7a6f95fde5c3d8797a640ec72c5fc548a607a225 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 16 May 2015 12:57:23 +0800 Subject: [PATCH 229/345] Update README.md --- README.md | 42 ++++++++++++------------------------------ 1 file changed, 12 insertions(+), 30 deletions(-) diff --git a/README.md b/README.md index fdbd30b3e..456d5de5e 100644 --- a/README.md +++ b/README.md @@ -126,40 +126,22 @@ Shell --- ##Stack -Problem | Solution | Time | Space | Difficulty | Notes ---------------- | --------------- | --------------- | --------------- | -------------- | ----- -[Binary Search Tree Iterator] | [binary-search-tree-iterator.py] | _O(1)_| _O(h)_| Medium -[Evaluate Reverse Polish Notation]| [evaluate-reverse-polish-notation.py]| _O(n)_| _O(n)_| Medium | -[Longest Valid Parentheses]| [longest-valid-parentheses.py] | _O(n)_ | _O(1)_ | Hard | -[Min Stack] | [min-stack.py] | _O(n)_ | _O(1)_ | Easy | -[Simplify Path]| [simplify-path.py] | _O(n)_ | _O(n)_ | Medium | -[Symmetric Tree]| [symmetric-tree.py] | _O(n)_ | _O(h)_ | Easy | -[Valid Parentheses]| [valid-parentheses.py] | _O(n)_ | _O(n)_ | Easy | - -[Binary Search Tree Iterator]:https://oj.leetcode.com/problems/binary-search-tree-iterator/ -[binary-search-tree-iterator.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/binary-search-tree-iterator.py -[Evaluate Reverse Polish Notation]:https://oj.leetcode.com/problems/evaluate-reverse-polish-notation/ -[evaluate-reverse-polish-notation.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/evaluate-reverse-polish-notation.py -[Longest Valid Parentheses]:https://oj.leetcode.com/problems/longest-valid-parentheses/ -[longest-valid-parentheses.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/longest-valid-parentheses.py -[Min Stack]:https://oj.leetcode.com/problems/min-stack/ -[min-stack.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/min-stack.py -[Simplify Path]:https://oj.leetcode.com/problems/simplify-path/ -[simplify-path.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/simplify-path.py -[Symmetric Tree]:https://oj.leetcode.com/problems/symmetric-tree/ -[symmetric-tree.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/symmetric-tree.py -[Valid Parentheses]:https://oj.leetcode.com/problems/valid-parentheses/ -[valid-parentheses.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/valid-parentheses.py + # | Problem | Solution | Time | Space | Difficulty | Tag | Notes +-----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- +20| [Valid Parentheses](https://oj.leetcode.com/problems/valid-parentheses/)| [Python](./Python/valid-parentheses.py) | _O(n)_ | _O(n)_ | Easy || +32| [Longest Valid Parentheses](https://oj.leetcode.com/problems/longest-valid-parentheses/)| [Python](./Python/longest-valid-parentheses.py) | _O(n)_ | _O(1)_ | Hard || +71| [Simplify Path](https://oj.leetcode.com/problems/simplify-path/)| [Python](./Python/simplify-path.py) | _O(n)_ | _O(n)_ | Medium || +101| [Symmetric Tree](https://oj.leetcode.com/problems/symmetric-tree/)| [Python](./Python/symmetric-tree.py) | _O(n)_ | _O(h)_ | Easy || +150| [Evaluate Reverse Polish Notation](https://oj.leetcode.com/problems/evaluate-reverse-polish-notation/)| [Python](./Python/evaluate-reverse-polish-notation.py)| _O(n)_| _O(n)_| Medium || +155| [Min Stack](https://oj.leetcode.com/problems/min-stack/) | [Python](./Python/min-stack.py) | _O(n)_ | _O(1)_ | Easy || +173| [Binary Search Tree Iterator](https://oj.leetcode.com/problems/binary-search-tree-iterator/) | [Python](./Python/binary-search-tree-iterator.py) | _O(1)_| _O(h)_| Medium || --- ##Heap -Problem | Solution | Time | Space | Difficulty | Notes ---------------- | --------------- | --------------- | --------------- | -------------- | ----- -[Merge k Sorted Lists] | [merge-k-sorted-lists.py] | _O(nlogk)_| _O(k)_| Hard | - -[Merge k Sorted Lists]:https://oj.leetcode.com/problems/merge-k-sorted-lists/ -[merge-k-sorted-lists.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/merge-k-sorted-lists.py + # | Problem | Solution | Time | Space | Difficulty | Tag | Notes +-----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- +23| [Merge k Sorted Lists](https://oj.leetcode.com/problems/merge-k-sorted-lists/) | [Python](./Python/merge-k-sorted-lists.py) | _O(nlogk)_| _O(k)_| Hard || --- From 68e93ed2be4d7aac56488277a4fe12e33d5332d4 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 16 May 2015 13:22:52 +0800 Subject: [PATCH 230/345] Update README.md --- README.md | 57 +++++++++++++++---------------------------------------- 1 file changed, 15 insertions(+), 42 deletions(-) diff --git a/README.md b/README.md index 456d5de5e..f68de3937 100644 --- a/README.md +++ b/README.md @@ -158,48 +158,21 @@ Shell --- ##Hash Table -Problem | Solution | Time | Space | Difficulty | Notes ---------------- | --------------- | --------------- | --------------- | -------------- | ----- -[4 Sum] |[4sum.py] | _O(n^2 * p)_ | _O(n^2 * p)_ | Medium | -[Anagrams] | [anagrams.py] | _O(n)_ | _O(n)_ | Medium | -[Count Primes] | [count-primes.py] | _O(n)_ | _O(n)_ | Easy | -[Happy Number] | [happy-number.py] | _O(k)_ | _O(k)_ | Easy | -[Longest Substring with At Most Two Distinct Characters]| [longest-substring-with-at-most-two-distinct-characters.py] | _O(n^2)_ | _O(1)_ | Hard | -[Longest Substring Without Repeating Characters] | [longest-substring-without-repeating-characters.py] | _O(n)_ | _O(1)_ | Medium | -[Max Points on a Line] | [max-points-on-a-line.py] | _O(n^2)_ | _O(n)_ | Hard | -[Minimum Window Substring] | [minimum-window-substring.py] | _O(n)_ | _O(k)_ | Hard | -[Repeated DNA Sequences] | [repeated-dna-sequences.py] | _O(n)_ | _O(n)_ | Medium | -[Substring with Concatenation of All Words] | [substring-with-concatenation-of-all-words.py] | _O(m * n * k)_ | _O(n * k)_ | Hard | -[Two Sum] | [two-sum.py] | _O(n)_ | _O(n)_ | Medium | -[Two Sum III - Data structure design] | [two-sum-iii-data-structure-design.py] | _O(n)_ | _O(n)_ | Easy | -[Valid Sudoku] | [valid-sudoku.py] | _O(n^2)_ | _O(n)_ | Easy | - -[4 Sum]: https://oj.leetcode.com/problems/4sum/ -[4sum.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/4sum.py -[Anagrams]:https://oj.leetcode.com/problems/anagrams/ -[anagrams.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/anagrams.py -[Count Primes]:https://oj.leetcode.com/problems/count-primes/ -[count-primes.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/count-primes.py -[Happy Number]:https://oj.leetcode.com/problems/happy-number/ -[happy-number.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/happy-number.py -[Longest Substring with At Most Two Distinct Characters]:https://oj.leetcode.com/problems/longest-substring-with-at-most-two-distinct-characters/ -[longest-substring-with-at-most-two-distinct-characters.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/longest-substring-with-at-most-two-distinct-characters.py -[Longest Substring Without Repeating Characters]:https://oj.leetcode.com/problems/longest-substring-without-repeating-characters/ -[longest-substring-without-repeating-characters.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/longest-substring-without-repeating-characters.py -[Max Points on a Line]:https://oj.leetcode.com/problems/max-points-on-a-line/ -[max-points-on-a-line.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/max-points-on-a-line.py -[Minimum Window Substring]:https://oj.leetcode.com/problems/minimum-window-substring/ -[minimum-window-substring.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/minimum-window-substring.py -[Repeated DNA Sequences]:https://oj.leetcode.com/problems/repeated-dna-sequences/ -[repeated-dna-sequences.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/repeated-dna-sequences.py -[Substring with Concatenation of All Words]:https://oj.leetcode.com/problems/substring-with-concatenation-of-all-words/ -[substring-with-concatenation-of-all-words.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/substring-with-concatenation-of-all-words.py -[Two Sum]:https://oj.leetcode.com/problems/two-sum/ -[two-sum.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/two-sum.py -[Two Sum III - Data structure design]:https://oj.leetcode.com/problems/two-sum-iii-data-structure-design/ -[two-sum-iii-data-structure-design.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/two-sum-iii-data-structure-design.py -[Valid Sudoku]:https://oj.leetcode.com/problems/valid-sudoku/ -[valid-sudoku.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/valid-sudoku.py + # | Problem | Solution | Time | Space | Difficulty | Tag | Notes +-----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- +1| [Two Sum](https://oj.leetcode.com/problems/two-sum/) | [Python](./Python/two-sum.py) | _O(n)_ | _O(n)_ | Medium || +3| [Longest Substring Without Repeating Characters](https://oj.leetcode.com/problems/longest-substring-without-repeating-characters/) | [Python](./Python/longest-substring-without-repeating-characters.py) | _O(n)_ | _O(1)_ | Medium || +18| [4 Sum](https://oj.leetcode.com/problems/4sum/) |[Python](./Python/4sum.py) | _O(n^2 * p)_ | _O(n^2 * p)_ | Medium || +30| [Substring with Concatenation of All Words](https://oj.leetcode.com/problems/substring-with-concatenation-of-all-words/) | [Python](./Python/substring-with-concatenation-of-all-words.py) | _O(m * n * k)_ | _O(n * k)_ | Hard || +36| [Valid Sudoku](https://oj.leetcode.com/problems/valid-sudoku/) | [Python](./Python/valid-sudoku.py) | _O(n^2)_ | _O(n)_ | Easy || +49| [Anagrams](https://oj.leetcode.com/problems/anagrams/) | [Python](./Python/anagrams.py) | _O(n)_ | _O(n)_ | Medium || +76| [Minimum Window Substring](https://oj.leetcode.com/problems/minimum-window-substring/) | [Python](./Python/minimum-window-substring.py) | _O(n)_ | _O(k)_ | Hard || +149| [Max Points on a Line](https://oj.leetcode.com/problems/max-points-on-a-line/) | [Python](./Python/max-points-on-a-line.py) | _O(n^2)_ | _O(n)_ | Hard || +159| [Longest Substring with At Most Two Distinct Characters](https://oj.leetcode.com/problems/longest-substring-with-at-most-two-distinct-characters/)| [Python](./Python/longest-substring-with-at-most-two-distinct-characters.py) | _O(n^2)_ | _O(1)_ | Hard || +167| [Two Sum III - Data structure design](https://oj.leetcode.com/problems/two-sum-iii-data-structure-design/) | [Python](./Python/two-sum-iii-data-structure-design.py) | _O(n)_ | _O(n)_ | Easy || +187| [Repeated DNA Sequences](https://oj.leetcode.com/problems/repeated-dna-sequences/) | [Python](./Python/repeated-dna-sequences.py) | _O(n)_ | _O(n)_ | Medium || +202| [Happy Number](https://oj.leetcode.com/problems/happy-number/) | [Python](./Python/happy-number.py) | _O(k)_ | _O(k)_ | Easy || +204| [Count Primes](https://oj.leetcode.com/problems/count-primes/) | [Python](./Python/count-primes.py) | _O(n)_ | _O(n)_ | Easy || --- From 5e98fb39f2f89b1ce457cfe9d4e3290d6ed44240 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 16 May 2015 13:25:20 +0800 Subject: [PATCH 231/345] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index f68de3937..365fb263f 100644 --- a/README.md +++ b/README.md @@ -153,7 +153,7 @@ Shell 144 | [Binary Tree Preorder Traversal](https://oj.leetcode.com/problems/binary-tree-preorder-traversal/) | [Python](./Python/binary-tree-preorder-traversal.py) | _O(n)_| _O(1)_| Medium || `Morris Traversal` 145 | [Binary Tree Postorder Traversal](https://oj.leetcode.com/problems/binary-tree-postorder-traversal/) | [Python](./Python/binary-tree-postorder-traversal.py) | _O(n)_| _O(1)_| Hard || `Morris Traversal` 208 | [Implement Trie (Prefix Tree)](https://leetcode.com/problems/implement-trie-prefix-tree/) | [Python](./Python/implement-trie-prefix-tree.py) | _O(n)_ | _O(1)_ | Medium || Trie -211 | [Add and Search Word - Data structure design ](https://leetcode.com/problems/add-and-search-word-data-structure-design/) | [C++](./Python/add-and-search-word-data-structure-design.cpp) [Python](./Python/add-and-search-word-data-structure-design.py) | _O(min(n, h))_ | _O(min(n, h))_ | Medium || Trie, DFS +211 | [Add and Search Word - Data structure design ](https://leetcode.com/problems/add-and-search-word-data-structure-design/) | [C++](./C++/add-and-search-word-data-structure-design.cpp) [Python](./Python/add-and-search-word-data-structure-design.py) | _O(min(n, h))_ | _O(min(n, h))_ | Medium || Trie, DFS --- From af3e3eac49fe9186eeee966bfb025648aeb80d11 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 16 May 2015 15:36:03 +0800 Subject: [PATCH 232/345] Update README.md --- README.md | 64 +++++++++++++++---------------------------------------- 1 file changed, 17 insertions(+), 47 deletions(-) diff --git a/README.md b/README.md index 365fb263f..d8384d9cf 100644 --- a/README.md +++ b/README.md @@ -177,57 +177,27 @@ Shell --- ##Data Structure -Problem | Solution | Time | Space | Difficulty | Notes ---------------- | --------------- | --------------- | --------------- | -------------- | ----- -[LRU Cache] | [lru-cache.py] | _O(1)_ | _O(n)_ | Hard | - - -[LRU Cache]:https://oj.leetcode.com/problems/lru-cache/ -[lru-cache.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/lru-cache.py + # | Problem | Solution | Time | Space | Difficulty | Tag | Notes +-----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- +146| [LRU Cache](https://oj.leetcode.com/problems/lru-cache/) | [Python](./Python/lru-cache.py) | _O(1)_ | _O(n)_ | Hard || --- ##Math -Problem | Solution | Time | Space | Difficulty | Notes ---------------- | --------------- | --------------- | --------------- | -------------- | ----- -[Divide Two Integers] | [divide-two-integers.py] | _O(logn)_ | _O(1)_ | Medium | -[Excel Sheet Column Title] | [excel-sheet-column-title.py] | _O(logn)_ | _O(1)_ | Easy | -[Excel Sheet Column Number] | [excel-sheet-column-number.py] | _O(n)_ | _O(1)_ | Easy | -[Factorial Trailing Zeroes] | [factorial-trailing-zeroes.py] | _O(logn)_ | _O(1)_ | Easy | -[Fraction to Recurring Decimal] | [fraction-to-recurring-decimal.py] | _O(logn)_ | _O(1)_ | Medium | -[Gray Code] | [gray-code.py] | _O(2^n)_ | _O(1)_ | Medium | -[Integer to Roman] | [integer-to-roman.py] | _O(n)_ | _O(1)_ | Medium | -[Palindrome Number] | [palindrome-number.py] | _O(1)_ | _O(1)_ | Easy | -[Permutation Sequence] | [permutation-sequence.py] | _O(n^2)_ | _O(n)_ | Medium | `Cantor Ordering` -[Reverse Integer] | [reverse-integer.py] | _O(logn)_ | _O(1)_ | Easy | -[Roman to Integer] | [roman-to-integer.py] | _O(n)_ | _O(1)_ | Easy | -[Valid Number] | [valid-number.py] | _O(n)_ | _O(1)_ | Hard | `Automata` - -[Divide Two Integers]:https://oj.leetcode.com/problems/divide-two-integers/ -[divide-two-integers.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/divide-two-integers.py -[Excel Sheet Column Title]:https://oj.leetcode.com/problems/excel-sheet-column-title/ -[excel-sheet-column-title.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/excel-sheet-column-title.py -[Excel Sheet Column Number]:https://oj.leetcode.com/problems/excel-sheet-column-number/ -[excel-sheet-column-number.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/excel-sheet-column-number.py -[Factorial Trailing Zeroes]:https://oj.leetcode.com/problems/factorial-trailing-zeroes/ -[factorial-trailing-zeroes.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/factorial-trailing-zeroes.py -[Fraction to Recurring Decimal]:https://oj.leetcode.com/problems/fraction-to-recurring-decimal/ -[fraction-to-recurring-decimal.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/fraction-to-recurring-decimal.py -[Gray Code]:https://oj.leetcode.com/problems/gray-code/ -[gray-code.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/gray-code.py -[Integer to Roman]:https://oj.leetcode.com/problems/integer-to-roman/ -[integer-to-roman.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/integer-to-roman.py -[Palindrome Number]:https://oj.leetcode.com/problems/palindrome-number/ -[palindrome-number.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/palindrome-number.py -[Permutation Sequence]:https://oj.leetcode.com/problems/permutation-sequence/ -[permutation-sequence.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/permutation-sequence.py -[Reverse Integer]:https://oj.leetcode.com/problems/reverse-integer/ -[reverse-integer.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/reverse-integer.py -[Roman to Integer]:https://oj.leetcode.com/problems/roman-to-integer/ -[roman-to-integer.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/roman-to-integer.py -[Valid Number]:https://oj.leetcode.com/problems/valid-number/ -[valid-number.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/valid-number.py - + # | Problem | Solution | Time | Space | Difficulty | Tag | Notes +-----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- +7| [Reverse Integer](https://oj.leetcode.com/problems/reverse-integer/) | [Python](./Python/reverse-integer.py) | _O(logn)_ | _O(1)_ | Easy | +9| [Palindrome Number](https://oj.leetcode.com/problems/palindrome-number/) | [Python](./Python/palindrome-number.py) | _O(1)_ | _O(1)_ | Easy | +12| [Integer to Roman](https://oj.leetcode.com/problems/integer-to-roman/) | [Python](./Python/integer-to-roman.py) | _O(n)_ | _O(1)_ | Medium | +13| [Roman to Integer](https://oj.leetcode.com/problems/roman-to-integer/) | [Python](./Python/roman-to-integer.py) | _O(n)_ | _O(1)_ | Easy | +29| [Divide Two Integers](https://oj.leetcode.com/problems/divide-two-integers/) | [Python](./Python/divide-two-integers.py) | _O(logn)_ | _O(1)_ | Medium | +60| [Permutation Sequence](https://oj.leetcode.com/problems/permutation-sequence/) | [Python](./Python/permutation-sequence.py) | _O(n^2)_ | _O(n)_ | Medium | `Cantor Ordering` +65| [Valid Number](https://oj.leetcode.com/problems/valid-number/) | [Python](./Python/valid-number.py) | _O(n)_ | _O(1)_ | Hard | `Automata` +89| [Gray Code](https://oj.leetcode.com/problems/gray-code/) | [Python](./Python/gray-code.py) | _O(2^n)_ | _O(1)_ | Medium | +166| [Fraction to Recurring Decimal](https://oj.leetcode.com/problems/fraction-to-recurring-decimal/) | [Python](./Python/fraction-to-recurring-decimal.py) | _O(logn)_ | _O(1)_ | Medium | +168| [Excel Sheet Column Title](https://oj.leetcode.com/problems/excel-sheet-column-title/) | [Python](./Python/excel-sheet-column-title.py) | _O(logn)_ | _O(1)_ | Easy | +171| [Excel Sheet Column Number](https://oj.leetcode.com/problems/excel-sheet-column-number/) | [Python](./Python/excel-sheet-column-number.py) | _O(n)_ | _O(1)_ | Easy | +172| [Factorial Trailing Zeroes](https://oj.leetcode.com/problems/factorial-trailing-zeroes/) | [Python](./Python/factorial-trailing-zeroes.py) | _O(logn)_ | _O(1)_ | Easy | --- From 8fb78741bdc0ac601f76cea116b5384707f2d2b5 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 16 May 2015 15:37:30 +0800 Subject: [PATCH 233/345] Update README.md --- README.md | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/README.md b/README.md index d8384d9cf..4aa1f6ad8 100644 --- a/README.md +++ b/README.md @@ -186,18 +186,18 @@ Shell ##Math # | Problem | Solution | Time | Space | Difficulty | Tag | Notes -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- -7| [Reverse Integer](https://oj.leetcode.com/problems/reverse-integer/) | [Python](./Python/reverse-integer.py) | _O(logn)_ | _O(1)_ | Easy | -9| [Palindrome Number](https://oj.leetcode.com/problems/palindrome-number/) | [Python](./Python/palindrome-number.py) | _O(1)_ | _O(1)_ | Easy | -12| [Integer to Roman](https://oj.leetcode.com/problems/integer-to-roman/) | [Python](./Python/integer-to-roman.py) | _O(n)_ | _O(1)_ | Medium | -13| [Roman to Integer](https://oj.leetcode.com/problems/roman-to-integer/) | [Python](./Python/roman-to-integer.py) | _O(n)_ | _O(1)_ | Easy | -29| [Divide Two Integers](https://oj.leetcode.com/problems/divide-two-integers/) | [Python](./Python/divide-two-integers.py) | _O(logn)_ | _O(1)_ | Medium | -60| [Permutation Sequence](https://oj.leetcode.com/problems/permutation-sequence/) | [Python](./Python/permutation-sequence.py) | _O(n^2)_ | _O(n)_ | Medium | `Cantor Ordering` -65| [Valid Number](https://oj.leetcode.com/problems/valid-number/) | [Python](./Python/valid-number.py) | _O(n)_ | _O(1)_ | Hard | `Automata` -89| [Gray Code](https://oj.leetcode.com/problems/gray-code/) | [Python](./Python/gray-code.py) | _O(2^n)_ | _O(1)_ | Medium | -166| [Fraction to Recurring Decimal](https://oj.leetcode.com/problems/fraction-to-recurring-decimal/) | [Python](./Python/fraction-to-recurring-decimal.py) | _O(logn)_ | _O(1)_ | Medium | -168| [Excel Sheet Column Title](https://oj.leetcode.com/problems/excel-sheet-column-title/) | [Python](./Python/excel-sheet-column-title.py) | _O(logn)_ | _O(1)_ | Easy | -171| [Excel Sheet Column Number](https://oj.leetcode.com/problems/excel-sheet-column-number/) | [Python](./Python/excel-sheet-column-number.py) | _O(n)_ | _O(1)_ | Easy | -172| [Factorial Trailing Zeroes](https://oj.leetcode.com/problems/factorial-trailing-zeroes/) | [Python](./Python/factorial-trailing-zeroes.py) | _O(logn)_ | _O(1)_ | Easy | +7| [Reverse Integer](https://oj.leetcode.com/problems/reverse-integer/) | [Python](./Python/reverse-integer.py) | _O(logn)_ | _O(1)_ | Easy || +9| [Palindrome Number](https://oj.leetcode.com/problems/palindrome-number/) | [Python](./Python/palindrome-number.py) | _O(1)_ | _O(1)_ | Easy || +12| [Integer to Roman](https://oj.leetcode.com/problems/integer-to-roman/) | [Python](./Python/integer-to-roman.py) | _O(n)_ | _O(1)_ | Medium || +13| [Roman to Integer](https://oj.leetcode.com/problems/roman-to-integer/) | [Python](./Python/roman-to-integer.py) | _O(n)_ | _O(1)_ | Easy || +29| [Divide Two Integers](https://oj.leetcode.com/problems/divide-two-integers/) | [Python](./Python/divide-two-integers.py) | _O(logn)_ | _O(1)_ | Medium || +60| [Permutation Sequence](https://oj.leetcode.com/problems/permutation-sequence/) | [Python](./Python/permutation-sequence.py) | _O(n^2)_ | _O(n)_ | Medium || `Cantor Ordering` +65| [Valid Number](https://oj.leetcode.com/problems/valid-number/) | [Python](./Python/valid-number.py) | _O(n)_ | _O(1)_ | Hard || `Automata` +89| [Gray Code](https://oj.leetcode.com/problems/gray-code/) | [Python](./Python/gray-code.py) | _O(2^n)_ | _O(1)_ | Medium || +166| [Fraction to Recurring Decimal](https://oj.leetcode.com/problems/fraction-to-recurring-decimal/) | [Python](./Python/fraction-to-recurring-decimal.py) | _O(logn)_ | _O(1)_ | Medium || +168| [Excel Sheet Column Title](https://oj.leetcode.com/problems/excel-sheet-column-title/) | [Python](./Python/excel-sheet-column-title.py) | _O(logn)_ | _O(1)_ | Easy || +171| [Excel Sheet Column Number](https://oj.leetcode.com/problems/excel-sheet-column-number/) | [Python](./Python/excel-sheet-column-number.py) | _O(n)_ | _O(1)_ | Easy || +172| [Factorial Trailing Zeroes](https://oj.leetcode.com/problems/factorial-trailing-zeroes/) | [Python](./Python/factorial-trailing-zeroes.py) | _O(logn)_ | _O(1)_ | Easy || --- From 5bd50bc4fd710f23e5e0a83f7adf199c9e861e07 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 16 May 2015 15:54:17 +0800 Subject: [PATCH 234/345] Update README.md --- README.md | 41 +++++++++++------------------------------ 1 file changed, 11 insertions(+), 30 deletions(-) diff --git a/README.md b/README.md index 4aa1f6ad8..94dcf9796 100644 --- a/README.md +++ b/README.md @@ -202,36 +202,17 @@ Shell --- ##Sort -Problem | Solution | Time | Space | Difficulty | Notes ---------------- | --------------- | --------------- | --------------- | -------------- | ----- -[Insert Interval]| [insert-interval.py] | _O(n)_ | _O(1)_ | Hard | -[Insertion Sort List]|[insertion-sort-list.py] | _O(n^2)_ | _O(1)_ | Medium | -[Largest Number] | [largest-number.py] | _O(nlogn)_ | _O(1)_ | Medium | -[Maximum Gap] | [maximum-gap.py]| _O(n)_ | _O(n)_ | Hard | Tricky -[Merge Intervals]| [merge-intervals.py] | _O(nlogn)_ | _O(1)_ | Hard | -[Merge Sorted Array]| [merge-sorted-array.py] | _O(n)_ | _O(1)_ | Easy | -[Merge Two Sorted Lists]| [merge-two-sorted-lists.py] | _O(n)_ | _O(1)_ | Easy | -[Sort Colors] | [sort-colors.py] | _O(n)_ | _O(1)_ | Medium | -[Sort List] | [sort-list.py] | _O(nlogn)_ | _O(logn)_ | Medium | - -[Insert Interval]:https://oj.leetcode.com/problems/insert-interval/ -[insert-interval.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/insert-interval.py -[Insertion Sort List]:https://oj.leetcode.com/problems/insertion-sort-list/ -[insertion-sort-list.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/insertion-sort-list.py -[Largest Number]:https://oj.leetcode.com/problems/largest-number/ -[largest-number.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/largest-number.py -[Maximum Gap]:https://oj.leetcode.com/problems/maximum-gap/ -[maximum-gap.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/maximum-gap.py -[Merge Intervals]:https://oj.leetcode.com/problems/merge-intervals/ -[merge-intervals.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/merge-intervals.py -[Merge Sorted Array]:https://oj.leetcode.com/problems/merge-sorted-array/ -[merge-sorted-array.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/merge-sorted-array.py -[Merge Two Sorted Lists]:https://oj.leetcode.com/problems/merge-two-sorted-lists/ -[merge-two-sorted-lists.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/merge-two-sorted-lists.py -[Sort Colors]:https://oj.leetcode.com/problems/sort-colors/ -[sort-colors.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/sort-colors.py -[Sort List]:https://oj.leetcode.com/problems/sort-list/ -[sort-list.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/sort-list.py + # | Problem | Solution | Time | Space | Difficulty | Tag | Notes +-----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- +21| [Merge Two Sorted Lists](https://oj.leetcode.com/problems/merge-two-sorted-lists/)| [Python](./Python/merge-two-sorted-lists.py) | _O(n)_ | _O(1)_ | Easy || +56| [Merge Intervals](https://oj.leetcode.com/problems/merge-intervals/)| [Python](./Python/merge-intervals.py) | _O(nlogn)_ | _O(1)_ | Hard || +57| [Insert Interval](https://oj.leetcode.com/problems/insert-interval/)| [Python](./Python/insert-interval.py) | _O(n)_ | _O(1)_ | Hard || +75| [Sort Colors](https://oj.leetcode.com/problems/sort-colors/) | [Python](./Python/sort-colors.py) | _O(n)_ | _O(1)_ | Medium || +88| [Merge Sorted Array](https://oj.leetcode.com/problems/merge-sorted-array/)| [Python](./Python/merge-sorted-array.py) | _O(n)_ | _O(1)_ | Easy || +147| [Insertion Sort List](https://oj.leetcode.com/problems/insertion-sort-list/)|[Python](./Python/insertion-sort-list.py) | _O(n^2)_ | _O(1)_ | Medium || +148| [Sort List](https://oj.leetcode.com/problems/sort-list/) | [Python](./Python/sort-list.py) | _O(nlogn)_ | _O(logn)_ | Medium || +164| [Maximum Gap](https://oj.leetcode.com/problems/maximum-gap/) | [Python](./Python/maximum-gap.py)| _O(n)_ | _O(n)_ | Hard || Tricky +179| [Largest Number](https://oj.leetcode.com/problems/largest-number/) | [Python](./Python/largest-number.py) | _O(nlogn)_ | _O(1)_ | Medium || --- From ff4efe82715a82a93037c7b3f52aa33f6bc089e3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 16 May 2015 16:01:22 +0800 Subject: [PATCH 235/345] Update README.md --- README.md | 29 ++++++++--------------------- 1 file changed, 8 insertions(+), 21 deletions(-) diff --git a/README.md b/README.md index 94dcf9796..18fbf8cfa 100644 --- a/README.md +++ b/README.md @@ -217,27 +217,14 @@ Shell --- ##Two Pointer -Problem | Solution | Time | Space | Difficulty | Notes ---------------- | --------------- | --------------- | --------------- | -------------- | ----- -[Linked List Cycle]| [linked-list-cycle.py] | _O(n)_ | _O(1)_ | Medium | -[Linked List Cycle II]| [linked-list-cycle-ii.py] | _O(n)_ | _O(1)_ | Medium | -[Partition List]| [partition-list.py] | _O(n)_ | _O(1)_ | Medium | -[Remove Nth Node From End of List]| [remove-nth-node-from-end-of-list.py] | _O(n)_ | _O(1)_ | Easy | -[Reorder List]| [reorder-list.py] | _O(n)_ | _O(1)_ | Medium | -[Two Sum II - Input array is sorted] | [two-sum-ii-input-array-is-sorted.py] | _O(n)_ | _O(1)_ | Medium | - -[Linked List Cycle]:https://oj.leetcode.com/problems/linked-list-cycle/ -[linked-list-cycle.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/linked-list-cycle.py -[Linked List Cycle II]:https://oj.leetcode.com/problems/linked-list-cycle-ii/ -[linked-list-cycle-ii.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/linked-list-cycle-ii.py -[Partition List]:https://oj.leetcode.com/problems/partition-list/ -[partition-list.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/partition-list.py -[Remove Nth Node From End of List]:https://oj.leetcode.com/problems/remove-nth-node-from-end-of-list/ -[remove-nth-node-from-end-of-list.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/remove-nth-node-from-end-of-list.py -[Reorder List]:https://oj.leetcode.com/problems/reorder-list/ -[reorder-list.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/reorder-list.py -[Two Sum II - Input array is sorted]:https://oj.leetcode.com/problems/two-sum-ii-input-array-is-sorted/ -[two-sum-ii-input-array-is-sorted.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/two-sum-ii-input-array-is-sorted.py + # | Problem | Solution | Time | Space | Difficulty | Tag | Notes +-----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- +19| [Remove Nth Node From End of List](https://oj.leetcode.com/problems/remove-nth-node-from-end-of-list/)| [Python](./Python/remove-nth-node-from-end-of-list.py) | _O(n)_ | _O(1)_ | Easy || +86| [Partition List](https://oj.leetcode.com/problems/partition-list/)| [Python](./Python/partition-list.py) | _O(n)_ | _O(1)_ | Medium || +141| [Linked List Cycle](https://oj.leetcode.com/problems/linked-list-cycle/)| [Python](./Python/linked-list-cycle.py) | _O(n)_ | _O(1)_ | Medium || +142| [Linked List Cycle II](https://oj.leetcode.com/problems/linked-list-cycle-ii/)| [Python](./Python/linked-list-cycle-ii.py) | _O(n)_ | _O(1)_ | Medium || +143| [Reorder List](https://oj.leetcode.com/problems/reorder-list/)| [Python](./Python/reorder-list.py) | _O(n)_ | _O(1)_ | Medium || +167| [Two Sum II - Input array is sorted](https://oj.leetcode.com/problems/two-sum-ii-input-array-is-sorted/) | [Python](./Python/two-sum-ii-input-array-is-sorted.py) | _O(n)_ | _O(1)_ | Medium || --- From f264f01d2bb42c6f7765de0c81578528b84e3948 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 16 May 2015 16:12:30 +0800 Subject: [PATCH 236/345] Update README.md --- README.md | 25 +++++++------------------ 1 file changed, 7 insertions(+), 18 deletions(-) diff --git a/README.md b/README.md index 18fbf8cfa..da4212955 100644 --- a/README.md +++ b/README.md @@ -229,24 +229,13 @@ Shell --- ##Brute Force Search -Problem | Solution | Time | Space | Difficulty | Notes ---------------- | --------------- | --------------- | --------------- | -------------- | ----- -[Letter Combinations of a Phone Number]| [letter-combinations-of-a-phone-number.py] | _O(n * 4^n)_ | _O(n)_ | Medium | -[Permutations]| [permutations.py] | _O(n!)_ | _O(n)_ | Medium | -[Permutations II]| [permutations-ii.py] | _O(n!)_ | _O(n)_ | Hard | -[Subsets] | [subsets.py] | _O(n * 2^n)_ | _O(1)_ | Medium | -[Subsets II] | [subsets-ii.py] | _O(n * 2^n)_ | _O(1)_ | Medium | - -[Letter Combinations of a Phone Number]:https://oj.leetcode.com/problems/letter-combinations-of-a-phone-number/ -[letter-combinations-of-a-phone-number.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/letter-combinations-of-a-phone-number.py -[Permutations]:https://oj.leetcode.com/problems/permutations/ -[permutations.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/permutations.py -[Permutations II]:https://oj.leetcode.com/problems/permutations-ii/ -[permutations-ii.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/permutations-ii.py -[Subsets]:https://oj.leetcode.com/problems/subsets/ -[subsets.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/subsets.py -[Subsets II]:https://oj.leetcode.com/problems/subsets-ii/ -[subsets-ii.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/subsets-ii.py + # | Problem | Solution | Time | Space | Difficulty | Tag | Notes +-----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- +17| [Letter Combinations of a Phone Number](https://oj.leetcode.com/problems/letter-combinations-of-a-phone-number/)| [Python](./Python/letter-combinations-of-a-phone-number.py) | _O(n * 4^n)_ | _O(n)_ | Medium || +46| [Permutations](https://oj.leetcode.com/problems/permutations/)| [Python](./Python/permutations.py) | _O(n!)_ | _O(n)_ | Medium || +47| [Permutations II](https://oj.leetcode.com/problems/permutations-ii/)| [Python](./Python/permutations-ii.py) | _O(n!)_ | _O(n)_ | Hard || +78| [Subsets](https://oj.leetcode.com/problems/subsets/) | [Python](./Python/subsets.py) | _O(n * 2^n)_ | _O(1)_ | Medium || +90| [Subsets II](https://oj.leetcode.com/problems/subsets-ii/) | [Python](./Python/subsets-ii.py) | _O(n * 2^n)_ | _O(1)_ | Medium || --- From e04d2fca94ea0d7dfdf559c06b84e0273a1ab50d Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 16 May 2015 16:33:44 +0800 Subject: [PATCH 237/345] Update README.md --- README.md | 66 ++++++++++++++----------------------------------------- 1 file changed, 17 insertions(+), 49 deletions(-) diff --git a/README.md b/README.md index da4212955..f5d935d04 100644 --- a/README.md +++ b/README.md @@ -240,55 +240,23 @@ Shell --- ##Divide and Conquer -Problem | Solution | Time | Space | Difficulty | Notes ---------------- | --------------- | --------------- | --------------- | -------------- | ----- -[Balanced Binary Tree] | [balanced-binary-tree.py] | _O(n)_| _O(h)_ | Easy | -[Binary Tree Maximum Path Sum]| [binary-tree-maximum-path-sum.py] | _O(n)_| _O(h)_| Hard | -[Binary Tree Upside Down] | [binary-tree-upside-down.py] | _O(n)_ | _O(1)_ | Medium | -[Construct Binary Tree from Inorder and Postorder Traversal] | [construct-binary-tree-from-inorder-and-postorder-traversal.py] | _O(n)_ | _O(n)_ | Medium | -[Construct Binary Tree from Preorder and Inorder Traversal] | [construct-binary-tree-from-preorder-and-inorder-traversal.py] | _O(n)_ | _O(n)_ | Medium -[Convert Sorted Array to Binary Search Tree] | [convert-sorted-array-to-binary-search-tree.py] | _O(n)_ | _O(logn)_ | Medium | -[Convert Sorted List to Binary Search Tree] | [convert-sorted-list-to-binary-search-tree.py] | _O(n)_ | _O(logn)_ | Medium | -[Flatten Binary Tree to Linked List]|[flatten-binary-tree-to-linked-list.py]| _O(n)_ | _O(h)_ | Medium | -[Maximum Depth of Binary Tree]|[maximum-depth-of-binary-tree.py]| _O(n)_ | _O(h)_ | Easy | -[Minimum Depth of Binary Tree]|[minimum-depth-of-binary-tree.py]| _O(n)_ | _O(h)_ | Easy | -[Populating Next Right Pointers in Each Node]|[populating-next-right-pointers-in-each-node.py]| _O(n)_ | _O(1)_ | Medium | -[Same Tree] |[same-tree.py] | _O(n)_ | _O(h)_ | Easy | -[Sum Root to Leaf Numbers] | [sum-root-to-leaf-numbers.py] | _O(n)_ | _O(h)_ | Medium | -[Unique Binary Search Trees II] | [unique-binary-search-trees-ii.py] | _O(4^n / n^(3/2)_ | _O(4^n / n^(3/2)_ | Medium | -[Validate Binary Search Tree]|[validate-binary-search-tree.py]| _O(n)_ | _O(1)_ | Medium | - -[Balanced Binary Tree]:https://oj.leetcode.com/problems/balanced-binary-tree/ -[balanced-binary-tree.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/balanced-binary-tree.py -[Binary Tree Maximum Path Sum]:https://oj.leetcode.com/problems/binary-tree-maximum-path-sum/ -[binary-tree-maximum-path-sum.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/binary-tree-maximum-path-sum.py -[Binary Tree Upside Down]:https://oj.leetcode.com/problems/binary-tree-upside-down/ -[binary-tree-upside-down.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/binary-tree-upside-down.py -[Construct Binary Tree from Inorder and Postorder Traversal]:https://oj.leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/ -[construct-binary-tree-from-inorder-and-postorder-traversal.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/construct-binary-tree-from-inorder-and-postorder-traversal.py -[Construct Binary Tree from Preorder and Inorder Traversal]:https://oj.leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/ -[construct-binary-tree-from-preorder-and-inorder-traversal.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/construct-binary-tree-from-preorder-and-inorder-traversal.py -[Convert Sorted Array to Binary Search Tree]:https://oj.leetcode.com/problems/convert-sorted-array-to-binary-search-tree/ -[convert-sorted-array-to-binary-search-tree.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/convert-sorted-array-to-binary-search-tree.py -[Convert Sorted List to Binary Search Tree]:https://oj.leetcode.com/problems/convert-sorted-list-to-binary-search-tree/ -[convert-sorted-list-to-binary-search-tree.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/convert-sorted-list-to-binary-search-tree.py -[Flatten Binary Tree to Linked List]:https://oj.leetcode.com/problems/flatten-binary-tree-to-linked-list/ -[flatten-binary-tree-to-linked-list.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/flatten-binary-tree-to-linked-list.py -[Maximum Depth of Binary Tree]:https://oj.leetcode.com/problems/maximum-depth-of-binary-tree/ -[maximum-depth-of-binary-tree.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/maximum-depth-of-binary-tree.py -[Minimum Depth of Binary Tree]:https://oj.leetcode.com/problems/minimum-depth-of-binary-tree/ -[minimum-depth-of-binary-tree.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/minimum-depth-of-binary-tree.py -[Populating Next Right Pointers in Each Node]:https://oj.leetcode.com/problems/populating-next-right-pointers-in-each-node/ -[populating-next-right-pointers-in-each-node.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/populating-next-right-pointers-in-each-node.py -[Same Tree]:https://oj.leetcode.com/problems/same-tree/ -[same-tree.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/same-tree.py -[Sum Root to Leaf Numbers]:https://oj.leetcode.com/problems/sum-root-to-leaf-numbers/ -[sum-root-to-leaf-numbers.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/sum-root-to-leaf-numbers.py -[Unique Binary Search Trees II]:https://oj.leetcode.com/problems/unique-binary-search-trees-ii/ -[unique-binary-search-trees-ii.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/unique-binary-search-trees-ii.py -[Validate Binary Search Tree]:https://oj.leetcode.com/problems/validate-binary-search-tree/ -[validate-binary-search-tree.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/validate-binary-search-tree.py - + # | Problem | Solution | Time | Space | Difficulty | Tag | Notes +-----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- +95| [Unique Binary Search Trees II](https://oj.leetcode.com/problems/unique-binary-search-trees-ii/) | [Python](./Python/unique-binary-search-trees-ii.py) | _O(4^n / n^(3/2)_ | _O(4^n / n^(3/2)_ | Medium || +98| [Validate Binary Search Tree](https://oj.leetcode.com/problems/validate-binary-search-tree/)|[Python](./Python/validate-binary-search-tree.py)| _O(n)_ | _O(1)_ | Medium || +100| [Same Tree](https://oj.leetcode.com/problems/same-tree/) |[Python](./Python/same-tree.py) | _O(n)_ | _O(h)_ | Easy || +104| [Maximum Depth of Binary Tree](https://oj.leetcode.com/problems/maximum-depth-of-binary-tree/)|[Python](./Python/maximum-depth-of-binary-tree.py)| _O(n)_ | _O(h)_ | Easy || +105| [Construct Binary Tree from Preorder and Inorder Traversal](https://oj.leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/) | [Python](./Python/construct-binary-tree-from-preorder-and-inorder-traversal.py) | _O(n)_ | _O(n)_ | Medium || +106| [Construct Binary Tree from Inorder and Postorder Traversal](https://oj.leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/) | [Python](./Python/construct-binary-tree-from-inorder-and-postorder-traversal.py) | _O(n)_ | _O(n)_ | Medium || +108| [Convert Sorted Array to Binary Search Tree](https://oj.leetcode.com/problems/convert-sorted-array-to-binary-search-tree/) | [Python](./Python/convert-sorted-array-to-binary-search-tree.py) | _O(n)_ | _O(logn)_ | Medium || +109| [Convert Sorted List to Binary Search Tree](https://oj.leetcode.com/problems/convert-sorted-list-to-binary-search-tree/) | [Python](./Python/convert-sorted-list-to-binary-search-tree.py) | _O(n)_ | _O(logn)_ | Medium || +110| [Balanced Binary Tree](https://oj.leetcode.com/problems/balanced-binary-tree/) | [Python](./Python/balanced-binary-tree.py) | _O(n)_| _O(h)_ | Easy || +111| [Minimum Depth of Binary Tree](https://oj.leetcode.com/problems/minimum-depth-of-binary-tree/)|[Python](./Python/minimum-depth-of-binary-tree.py)| _O(n)_ | _O(h)_ | Easy || +114| [Flatten Binary Tree to Linked List](https://oj.leetcode.com/problems/flatten-binary-tree-to-linked-list/)|[Python](./Python/flatten-binary-tree-to-linked-list.py)| _O(n)_ | _O(h)_ | Medium || +116| [Populating Next Right Pointers in Each Node](https://oj.leetcode.com/problems/populating-next-right-pointers-in-each-node/)|[Python](./Python/populating-next-right-pointers-in-each-node.py)| _O(n)_ | _O(1)_ | Medium || +124| [Binary Tree Maximum Path Sum](https://oj.leetcode.com/problems/binary-tree-maximum-path-sum/)| [Python](./Python/binary-tree-maximum-path-sum.py) | _O(n)_| _O(h)_| Hard || +129| [Sum Root to Leaf Numbers](https://oj.leetcode.com/problems/sum-root-to-leaf-numbers/) | [Python](./Python/sum-root-to-leaf-numbers.py) | _O(n)_ | _O(h)_ | Medium || +156| [Binary Tree Upside Down](https://oj.leetcode.com/problems/binary-tree-upside-down/) | [Python](./Python/binary-tree-upside-down.py) | _O(n)_ | _O(1)_ | Medium || --- From 9abf8ad8f9e2df67afe308c3e5d0498e80cd7daf Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 16 May 2015 16:46:47 +0800 Subject: [PATCH 238/345] Update README.md --- README.md | 50 +++++++++++++------------------------------------- 1 file changed, 13 insertions(+), 37 deletions(-) diff --git a/README.md b/README.md index f5d935d04..111cb54c8 100644 --- a/README.md +++ b/README.md @@ -261,43 +261,19 @@ Shell --- ##Binary Search - -Problem | Solution | Time | Space | Difficulty | Notes ---------------- | --------------- | --------------- | --------------- | -------------- | ----- -[Find Minimum in Rotated Sorted Array] | [find-minimum-in-rotated-sorted-array.py] | _O(logn)_ | _O(1)_ | Medium | -[Find Minimum in Rotated Sorted Array II] | [find-minimum-in-rotated-sorted-array-ii.py] | _O(logn)_ ~ _O(n)_ | _O(1)_ | Hard | -[Find Peak Element] | [find-peak-element.py] | _O(logn)_ | _O(1)_ | Medium | -[Median of Two Sorted Arrays] | [median-of-two-sorted-arrays.py] | _O(log(m + n))_ | _O(1)_ | Hard | -[Pow(x, n)] | [powx-n.py] | _O(logn)_ | _O(logn)_ | Medium | -[Search a 2D Matrix] | [search-a-2d-matrix.py] | _O(logm + logn)_ | _O(1)_ | Medium | -[Search for a Range] | [search-for-a-range.py] | _O(logn)_ | _O(1)_ | Medium | -[Search in Rotated Sorted Array] | [search-in-rotated-sorted-array.py] | _O(logn)_ | _O(1)_ | Hard | -[Search in Rotated Sorted Array II] | [search-in-rotated-sorted-array-ii.py] | _O(logn)_ | _O(1)_ | Medium | -[Search Insert Position] | [search-insert-position.py] | _O(logn)_ | _O(1)_ | Medium | -[Sqrt(x)] | [sqrtx.py] | _O(logn)_ | _O(1)_ | Medium | - -[Find Minimum in Rotated Sorted Array]:https://oj.leetcode.com/problems/find-minimum-in-rotated-sorted-array/ -[find-minimum-in-rotated-sorted-array.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/find-minimum-in-rotated-sorted-array.py -[Find Minimum in Rotated Sorted Array II]:https://oj.leetcode.com/problems/find-minimum-in-rotated-sorted-array-ii/ -[find-minimum-in-rotated-sorted-array-ii.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/find-minimum-in-rotated-sorted-array-ii.py -[Find Peak Element]:https://oj.leetcode.com/problems/find-peak-element/ -[find-peak-element.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/find-peak-element.py -[Median of Two Sorted Arrays]:https://oj.leetcode.com/problems/median-of-two-sorted-arrays/ -[median-of-two-sorted-arrays.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/median-of-two-sorted-arrays.py -[Pow(x, n)]:https://oj.leetcode.com/problems/powx-n/ -[powx-n.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/powx-n.py -[Search a 2D Matrix]:https://oj.leetcode.com/problems/search-a-2d-matrix/ -[search-a-2d-matrix.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/search-a-2d-matrix.py -[Search for a Range]:https://oj.leetcode.com/problems/search-for-a-range/ -[search-for-a-range.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/search-for-a-range.py -[Search in Rotated Sorted Array]:https://oj.leetcode.com/problems/search-in-rotated-sorted-array/ -[search-in-rotated-sorted-array.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/search-in-rotated-sorted-array.py -[Search in Rotated Sorted Array II]:https://oj.leetcode.com/problems/search-in-rotated-sorted-array-ii/ -[search-in-rotated-sorted-array-ii.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/search-in-rotated-sorted-array-ii.py -[Search Insert Position]:https://oj.leetcode.com/problems/search-insert-position/ -[search-insert-position.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/search-insert-position.py -[Sqrt(x)]:https://oj.leetcode.com/problems/sqrtx/ -[sqrtx.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/sqrtx.py + # | Problem | Solution | Time | Space | Difficulty | Tag | Notes +-----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- +4| [Median of Two Sorted Arrays](https://oj.leetcode.com/problems/median-of-two-sorted-arrays/) | [Python](./Python/median-of-two-sorted-arrays.py) | _O(log(m + n))_ | _O(1)_ | Hard || +33| [Search in Rotated Sorted Array](https://oj.leetcode.com/problems/search-in-rotated-sorted-array/) | [Python](./Python/search-in-rotated-sorted-array.py) | _O(logn)_ | _O(1)_ | Hard || +34| [Search for a Range](https://oj.leetcode.com/problems/search-for-a-range/) | [Python](./Python/search-for-a-range.py) | _O(logn)_ | _O(1)_ | Medium || +35| [Search Insert Position](https://oj.leetcode.com/problems/search-insert-position/) | [Python](./Python/search-insert-position.py) | _O(logn)_ | _O(1)_ | Medium || +50| [Pow(x, n)](https://oj.leetcode.com/problems/powx-n/) | [Python](./Python/powx-n.py) | _O(logn)_ | _O(logn)_ | Medium || +69| [Sqrt(x)](https://oj.leetcode.com/problems/sqrtx/) | [Python](./Python/sqrtx.py) | _O(logn)_ | _O(1)_ | Medium || +74| [Search a 2D Matrix](https://oj.leetcode.com/problems/search-a-2d-matrix/) | [Python](./Python/search-a-2d-matrix.py) | _O(logm + logn)_ | _O(1)_ | Medium || +81| [Search in Rotated Sorted Array II](https://oj.leetcode.com/problems/search-in-rotated-sorted-array-ii/) | [Python](./Python/search-in-rotated-sorted-array-ii.py) | _O(logn)_ | _O(1)_ | Medium || +153| [Find Minimum in Rotated Sorted Array](https://oj.leetcode.com/problems/find-minimum-in-rotated-sorted-array/) | [Python](./Python/find-minimum-in-rotated-sorted-array.py) | _O(logn)_ | _O(1)_ | Medium || +154| [Find Minimum in Rotated Sorted Array II](https://oj.leetcode.com/problems/find-minimum-in-rotated-sorted-array-ii/) | [Python](./Python/find-minimum-in-rotated-sorted-array-ii.py) | _O(logn)_ ~ _O(n)_ | _O(1)_ | Hard || +162| [Find Peak Element](https://oj.leetcode.com/problems/find-peak-element/) | [Python](./Python/find-peak-element.py) | _O(logn)_ | _O(1)_ | Medium || --- From 177eb77c61d0334f6f5e77550f916225c1c0628e Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 16 May 2015 16:57:01 +0800 Subject: [PATCH 239/345] Update README.md --- README.md | 37 +++++++++++-------------------------- 1 file changed, 11 insertions(+), 26 deletions(-) diff --git a/README.md b/README.md index 111cb54c8..11110b3be 100644 --- a/README.md +++ b/README.md @@ -278,32 +278,17 @@ Shell --- ##Breadth-First Search -Problem | Solution | Time | Space | Difficulty | Notes ---------------- | --------------- | --------------- | --------------- | -------------- | ----- -[Binary Tree Level Order Traversal]| [binary-tree-level-order-traversal.py] | _O(n)_| _O(n)_| Easy | -[Binary Tree Level Order Traversal II]| [binary-tree-level-order-traversal-ii.py] | _O(n)_| _O(n)_| Easy | -[Binary Tree Zigzag Level Order Traversal]| [binary-tree-zigzag-level-order-traversal.py] | _O(n)_| _O(n)_| Medium | -[Clone Graph]| [clone-graph.py] | _O(n)_ | _O(n)_ | Medium | -[Course Schedule](https://oj.leetcode.com/problems/course-schedule/)| [course-schedule.py](./Python/course-schedule.py) | _O(\|V\| + \|E\|)_ | _O(\|E\|)_ | Medium | -[Course Schedule II](https://oj.leetcode.com/problems/course-schedule-ii/)| [course-schedule-ii.py](./Python/course-schedule-ii.py) | _O(\|V\| + \|E\|)_ | _O(\|E\|)_ | Medium | -[Populating Next Right Pointers in Each Node II]|[populating-next-right-pointers-in-each-node-ii.py]| _O(n)_ | _O(1)_ | Hard | -[Surrounded Regions]|[surrounded-regions.py]| _O(m * n)_ | _O(m + n)_ | Medium | -[Word Ladder] |[word-ladder.py] | _O(n * d)_ | _O(d)_ | Medium | - -[Binary Tree Level Order Traversal]:https://oj.leetcode.com/problems/binary-tree-level-order-traversal/ -[binary-tree-level-order-traversal.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/binary-tree-level-order-traversal.py -[Binary Tree Level Order Traversal II]:https://oj.leetcode.com/problems/binary-tree-level-order-traversal-ii/ -[binary-tree-level-order-traversal-ii.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/binary-tree-level-order-traversal-ii.py -[Binary Tree Zigzag Level Order Traversal]:https://oj.leetcode.com/problems/binary-tree-zigzag-level-order-traversal/ -[binary-tree-zigzag-level-order-traversal.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/binary-tree-zigzag-level-order-traversal.py -[Clone Graph]:https://oj.leetcode.com/problems/clone-graph/ -[clone-graph.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/clone-graph.py -[Populating Next Right Pointers in Each Node II]:https://oj.leetcode.com/problems/populating-next-right-pointers-in-each-node-ii/ -[populating-next-right-pointers-in-each-node-ii.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/populating-next-right-pointers-in-each-node-ii.py -[Surrounded Regions]:https://oj.leetcode.com/problems/surrounded-regions/ -[surrounded-regions.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/surrounded-regions.py -[Word Ladder]:https://oj.leetcode.com/problems/word-ladder/ -[word-ladder.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/word-ladder.py + # | Problem | Solution | Time | Space | Difficulty | Tag | Notes +-----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- +102| [Binary Tree Level Order Traversal](https://oj.leetcode.com/problems/binary-tree-level-order-traversal/)| [Python](./Python/binary-tree-level-order-traversal.py)| _O(n)_| _O(n)_| Easy || +107| [Binary Tree Level Order Traversal II](https://oj.leetcode.com/problems/binary-tree-level-order-traversal-ii/)| [Python](./Python/binary-tree-level-order-traversal-ii.py) | _O(n)_| _O(n)_| Easy || +103| [Binary Tree Zigzag Level Order Traversal](https://oj.leetcode.com/problems/binary-tree-zigzag-level-order-traversal/)| [Python](./Python/binary-tree-zigzag-level-order-traversal.py) | _O(n)_| _O(n)_| Medium || +117| [Populating Next Right Pointers in Each Node II](https://oj.leetcode.com/problems/populating-next-right-pointers-in-each-node-ii/)|[Python](./Python/populating-next-right-pointers-in-each-node-ii.py)| _O(n)_ | _O(1)_ | Hard || +127| [Word Ladder](https://oj.leetcode.com/problems/word-ladder/)|[Python](./Python/word-ladder.py) | _O(n * d)_ | _O(d)_ | Medium || +130| [Surrounded Regions](https://oj.leetcode.com/problems/surrounded-regions/)|[Python](./Python/surrounded-regions.py)| _O(m * n)_ | _O(m + n)_ | Medium || +133| [Clone Graph](https://oj.leetcode.com/problems/clone-graph/)| [Python](./Python/clone-graph.py) | _O(n)_ | _O(n)_ | Medium || +207| [Course Schedule](https://oj.leetcode.com/problems/course-schedule/)| [course-schedule.py](./Python/course-schedule.py) | _O(\|V\| + \|E\|)_ | _O(\|E\|)_ | Medium || +210| [Course Schedule II](https://oj.leetcode.com/problems/course-schedule-ii/)| [course-schedule-ii.py](./Python/course-schedule-ii.py) | _O(\|V\| + \|E\|)_ | _O(\|E\|)_ | Medium || --- From d5a1cc7001b9e97d295fd5c6454548b9d5ac39e3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 16 May 2015 17:12:42 +0800 Subject: [PATCH 240/345] Update README.md --- README.md | 61 +++++++++++++++---------------------------------------- 1 file changed, 16 insertions(+), 45 deletions(-) diff --git a/README.md b/README.md index 11110b3be..47ecbe979 100644 --- a/README.md +++ b/README.md @@ -293,51 +293,22 @@ Shell --- ##Depth-First Search -Problem | Solution | Time | Space | Difficulty | Notes ---------------- | --------------- | --------------- | --------------- | -------------- | ----- -[Binary Tree Right Side View] | [binary-tree-right-side-view.py] | _O(n)_ | _O(h)_ | Medium | -[Combination Sum]| [combination-sum.py] | _O(n^m)_ | _O(m)_ | Medium | -[Combination Sum II]| [combination-sum-ii.py]| _O(n! / m!(n-m)!)_| _O(m)_ | Medium | -[Combinations] | [combinations.py] | _O(n!)_ | _O(n)_ | Medium | -[Generate Parentheses]| [generate-parentheses.py]| _O(4^n / n^(3/2))_ | _O(n)_ | Medium | -[N-Queens] | [n-queens.py] | _O(n!)_ | _O(n)_ | Hard | -[N-Queens-II] | [n-queens-ii.py] | _O(n!)_ | _O(n)_ | Hard | -[Number of Islands] | [number-of-islands.py] | _O(m * n)_ | _O(m * n)_| Medium | -[Palindrome Partitioning] | [palindrome-partitioning.py] | _O(n^2)_ ~ _O(2^n)_ | _O(n^2)_ | Medium | -[Path Sum] | [path-sum.py] | _O(n)_ | _O(h)_ | Easy | -[Path Sum II] | [path-sum-ii.py] | _O(n)_ | _O(h)_ | Medium | -[Restore IP Addresses] | [restore-ip-addresses.py] | _O(n^m)_ ~ _O(3^4)_ | _O(n * m)_ ~ _O(3 * 4)_ | Medium | -[Sudoku Solver] | [sudoku-solver.py] | _O((9!)^9)_ | _O(1)_ | Hard | -[Word Search] | [word-search.py] | _O(m * n * l)_ | _O(l)_ | Medium | - -[Binary Tree Right Side View]:https://oj.leetcode.com/problems/binary-tree-right-side-view/ -[binary-tree-right-side-view.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/binary-tree-right-side-view.py -[Combination Sum]:https://oj.leetcode.com/problems/combination-sum/ -[combination-sum.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/combination-sum.py -[Combination Sum II]:https://oj.leetcode.com/problems/combination-sum-ii/ -[combination-sum-ii.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/combination-sum-ii.py -[Combinations]:https://oj.leetcode.com/problems/combinations/ -[combinations.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/combinations.py -[Generate Parentheses]:https://oj.leetcode.com/problems/generate-parentheses/ -[generate-parentheses.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/generate-parentheses.py -[N-Queens]:https://oj.leetcode.com/problems/n-queens/ -[n-queens.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/n-queens.py -[N-Queens-II]:https://oj.leetcode.com/problems/n-queens-ii/ -[n-queens-ii.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/n-queens-ii.py -[Number of Islands]:https://leetcode.com/problems/number-of-islands/ -[number-of-islands.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/number-of-islands.py -[Palindrome Partitioning]:https://oj.leetcode.com/problems/palindrome-partitioning/ -[palindrome-partitioning.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/palindrome-partitioning.py -[Path Sum]:https://oj.leetcode.com/problems/path-sum/ -[path-sum.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/path-sum.py -[Path Sum II]:https://oj.leetcode.com/problems/path-sum-ii/ -[path-sum-ii.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/path-sum-ii.py -[Restore IP Addresses]:https://oj.leetcode.com/problems/restore-ip-addresses/ -[restore-ip-addresses.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/restore-ip-addresses.py -[Sudoku Solver]:https://oj.leetcode.com/problems/sudoku-solver/ -[sudoku-solver.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/sudoku-solver.py -[Word Search]:https://oj.leetcode.com/problems/word-search/ -[word-search.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/word-search.py + # | Problem | Solution | Time | Space | Difficulty | Tag | Notes +-----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- +22| [Generate Parentheses](https://oj.leetcode.com/problems/generate-parentheses/)| [Python](./Python/generate-parentheses.py)| _O(4^n / n^(3/2))_ | _O(n)_ | Medium || +37| [Sudoku Solver](https://oj.leetcode.com/problems/sudoku-solver/) | [Python](./Python/sudoku-solver.py) | _O((9!)^9)_ | _O(1)_ | Hard || +39| [Combination Sum](https://oj.leetcode.com/problems/combination-sum/)| [Python](./Python/combination-sum.py) | _O(n^m)_ | _O(m)_ | Medium || +40| [Combination Sum II](https://oj.leetcode.com/problems/combination-sum-ii/)| [Python](./Python/combination-sum-ii.py)| _O(n! / m!(n-m)!)_| _O(m)_ | Medium || +51| [N-Queens](https://oj.leetcode.com/problems/n-queens/) | [Python](./Python/n-queens.py) | _O(n!)_ | _O(n)_ | Hard || +52| [N-Queens-II](https://oj.leetcode.com/problems/n-queens-ii/) | [Python](./Python/n-queens-ii.py) | _O(n!)_ | _O(n)_ | Hard || +77| [Combinations](https://oj.leetcode.com/problems/combinations/) | [Python](./Python/combinations.py) | _O(n!)_ | _O(n)_ | Medium || +79| [Word Search](https://oj.leetcode.com/problems/word-search/) | [Python](./Python/word-search.py) | _O(m * n * l)_ | _O(l)_ | Medium || +93| [Restore IP Addresses](https://oj.leetcode.com/problems/restore-ip-addresses/) | [Python](./Python/restore-ip-addresses.py) | _O(n^m)_ ~ _O(3^4)_ | _O(n * m)_ ~ _O(3 * 4)_ | Medium || +112| [Path Sum](https://oj.leetcode.com/problems/path-sum/) | [Python](./Python/path-sum.py) | _O(n)_ | _O(h)_ | Easy || +113| [Path Sum II](https://oj.leetcode.com/problems/path-sum-ii/) | [Python](./Python/path-sum-ii.py) | _O(n)_ | _O(h)_ | Medium || +131| [Palindrome Partitioning](https://oj.leetcode.com/problems/palindrome-partitioning/) | [Python](./Python/palindrome-partitioning.py) | _O(n^2)_ ~ _O(2^n)_ | _O(n^2)_ | Medium || +199| [Binary Tree Right Side View](https://oj.leetcode.com/problems/binary-tree-right-side-view/) | [Python](./Python/binary-tree-right-side-view.py) | _O(n)_ | _O(h)_ | Medium || +200| [Number of Islands](https://leetcode.com/problems/number-of-islands/) | [Python](./Python/number-of-islands.py) | _O(m * n)_ | _O(m * n)_| Medium || --- From 443ea06805c4dfcaf1b98ce5f8b1380b34b905a6 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 16 May 2015 17:13:59 +0800 Subject: [PATCH 241/345] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 47ecbe979..ec387f29b 100644 --- a/README.md +++ b/README.md @@ -287,8 +287,8 @@ Shell 127| [Word Ladder](https://oj.leetcode.com/problems/word-ladder/)|[Python](./Python/word-ladder.py) | _O(n * d)_ | _O(d)_ | Medium || 130| [Surrounded Regions](https://oj.leetcode.com/problems/surrounded-regions/)|[Python](./Python/surrounded-regions.py)| _O(m * n)_ | _O(m + n)_ | Medium || 133| [Clone Graph](https://oj.leetcode.com/problems/clone-graph/)| [Python](./Python/clone-graph.py) | _O(n)_ | _O(n)_ | Medium || -207| [Course Schedule](https://oj.leetcode.com/problems/course-schedule/)| [course-schedule.py](./Python/course-schedule.py) | _O(\|V\| + \|E\|)_ | _O(\|E\|)_ | Medium || -210| [Course Schedule II](https://oj.leetcode.com/problems/course-schedule-ii/)| [course-schedule-ii.py](./Python/course-schedule-ii.py) | _O(\|V\| + \|E\|)_ | _O(\|E\|)_ | Medium || +207| [Course Schedule](https://oj.leetcode.com/problems/course-schedule/)| [Python](./Python/course-schedule.py) | _O(\|V\| + \|E\|)_ | _O(\|E\|)_ | Medium || +210| [Course Schedule II](https://oj.leetcode.com/problems/course-schedule-ii/)| [Python](./Python/course-schedule-ii.py) | _O(\|V\| + \|E\|)_ | _O(\|E\|)_ | Medium || --- From ca8b46e1dfd3d400da0b98ae9f9ef2169a569958 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 16 May 2015 17:36:02 +0800 Subject: [PATCH 242/345] Update README.md --- README.md | 93 ++++++++++++++----------------------------------------- 1 file changed, 24 insertions(+), 69 deletions(-) diff --git a/README.md b/README.md index ec387f29b..c3e6b73c5 100644 --- a/README.md +++ b/README.md @@ -313,75 +313,30 @@ Shell --- ##Dynamic Programming -Problem | Solution | Time | Space | Difficulty | Notes ---------------- | --------------- | --------------- | --------------- | -------------- | ----- -[Best Time to Buy and Sell Stock III]| [best-time-to-buy-and-sell-stock-iii.py] | _O(n)_ | _O(1)_ | Hard | -[Best Time to Buy and Sell Stock IV]| [best-time-to-buy-and-sell-stock-iv.py] | _O(k * n)_ | _O(k)_ | Hard | -[Climbing Stairs]| [climbing-stairs.py] | _O(n)_ | _O(1)_ | Easy | -[Decode Ways] | [decode-ways.py]| _O(n)_ | _O(1)_ | Medium | -[Distinct Subsequences]|[distinct-subsequences.py]| _O(n^2)_ | _O(n)_ | Hard | -[Dungeon Game] | [dungeon-game.py]| _O(m * n)_ | _O(m + n)_ | Hard | -[Edit Distance]|[edit-distance.py]| _O(m * n)_ | _O(m + n)_ | Hard | -[House Robber]| [house-robber.py] | _O(n)_ | _O(1)_ | Easy | -[Interleaving String]|[interleaving-string.py]| _O(m * n)_ | _O(m + n)_ | Hard | -[Maximal Rectangle]|[maximal-rectangle.py]| _O(n^2)_ | _O(n)_ | Hard | -[Maximum Product Subarray]|[maximum-product-subarray.py]| _O(n)_ | _O(1)_ | Medium | -[Maximum Subarray]|[maximum-subarray.py]| _O(n)_ | _O(1)_ | Medium | -[Minimum Path Sum]|[minimum-path-sum.py]| _O(m * n)_ | _O(m + n)_ | Medium | -[Palindrome Partitioning II] | [palindrome-partitioning-ii.py] | _O(n^2)_ | _O(n^2)_ | Hard | -[Regular Expression Matching] | [regular-expression-matching.py] | _O(m * n)_ | _O(n)_ | Hard | -[Scramble String] | [scramble-string.py] | _O(n^4)_ | _O(n^3)_ | Hard | -[Triangle] | [triangle.py] | _O(m * n)_ | _O(n)_ | Medium | -[Unique Binary Search Trees] | [unique-binary-search-trees.py] | _O(n^2)_ | _O(n)_ | Medium | -[Unique Paths] | [unique-paths.py]| _O(m * n)_ | _O(m + n)_ | Medium | -[Unique Paths II] | [unique-paths-ii.py] | _O(m * n)_ | _O(m + n)_ | Medium | -[Word Break] | [word-break.py] | _O(n^2)_ | _O(n)_ | Medium | -[Word Break II] | [word-break-ii.py] | _O(n^2)_ | _O(n)_ | Hard | - -[Best Time to Buy and Sell Stock III]:https://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/ -[best-time-to-buy-and-sell-stock-iii.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/best-time-to-buy-and-sell-stock-iii.py -[Best Time to Buy and Sell Stock IV]:https://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/ -[best-time-to-buy-and-sell-stock-iv.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/best-time-to-buy-and-sell-stock-iv.py -[Climbing Stairs]:https://oj.leetcode.com/problems/climbing-stairs/ -[climbing-stairs.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/climbing-stairs.py -[Decode Ways]:https://oj.leetcode.com/problems/decode-ways/ -[decode-ways.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/decode-ways.py -[Distinct Subsequences]:https://oj.leetcode.com/problems/distinct-subsequences/ -[distinct-subsequences.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/distinct-subsequences.py -[Dungeon Game]:https://oj.leetcode.com/problems/dungeon-game/ -[dungeon-game.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/dungeon-game.py -[Edit Distance]:https://oj.leetcode.com/problems/edit-distance/ -[edit-distance.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/edit-distance.py -[House Robber]:https://oj.leetcode.com/problems/house-robber/ -[house-robber.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/house-robber.py -[Interleaving String]:https://oj.leetcode.com/problems/interleaving-string/ -[interleaving-string.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/interleaving-string.py -[Maximal Rectangle]:https://oj.leetcode.com/problems/maximal-rectangle/ -[maximal-rectangle.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/maximal-rectangle.py -[Maximum Product Subarray]:https://oj.leetcode.com/problems/maximum-product-subarray/ -[maximum-product-subarray.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/maximum-product-subarray.py -[Maximum Subarray]:https://oj.leetcode.com/problems/maximum-subarray/ -[maximum-subarray.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/maximum-subarray.py -[Minimum Path Sum]:https://oj.leetcode.com/problems/minimum-path-sum/ -[minimum-path-sum.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/minimum-path-sum.py -[Palindrome Partitioning II]:https://oj.leetcode.com/problems/palindrome-partitioning-ii/ -[palindrome-partitioning-ii.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/palindrome-partitioning-ii.py -[Regular Expression Matching]:https://oj.leetcode.com/problems/regular-expression-matching/ -[regular-expression-matching.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/regular-expression-matching.py -[Scramble String]:https://oj.leetcode.com/problems/scramble-string/ -[scramble-string.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/scramble-string.py -[Triangle]:https://oj.leetcode.com/problems/triangle/ -[triangle.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/triangle.py -[Unique Binary Search Trees]:https://oj.leetcode.com/problems/unique-binary-search-trees/ -[unique-binary-search-trees.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/unique-binary-search-trees.py -[Unique Paths]:https://oj.leetcode.com/problems/unique-paths/ -[unique-paths.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/unique-paths.py -[Unique Paths II]:https://oj.leetcode.com/problems/unique-paths-ii/ -[unique-paths-ii.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/unique-paths-ii.py -[Word Break]:https://oj.leetcode.com/problems/word-break/ -[word-break.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/word-break.py -[Word Break II]:https://oj.leetcode.com/problems/word-break-ii/ -[word-break-ii.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/word-break-ii.py + # | Problem | Solution | Time | Space | Difficulty | Tag | Notes +-----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- +10| [Regular Expression Matching](https://oj.leetcode.com/problems/regular-expression-matching/) | [Python](./Python/regular-expression-matching.py) | _O(m * n)_ | _O(n)_ | Hard || +53| [Maximum Subarray](https://oj.leetcode.com/problems/maximum-subarray/)|[Python](./Python/maximum-subarray.py)| _O(n)_ | _O(1)_ | Medium || +62| [Unique Paths](https://oj.leetcode.com/problems/unique-paths/) | [Python](./Python/unique-paths.py)| _O(m * n)_ | _O(m + n)_ | Medium || +63| [Unique Paths II](https://oj.leetcode.com/problems/unique-paths-ii/) | [Python](./Python/unique-paths-ii.py) | _O(m * n)_ | _O(m + n)_ | Medium || +64| [Minimum Path Sum](https://oj.leetcode.com/problems/minimum-path-sum/)|[Python](./Python/minimum-path-sum.py)| _O(m * n)_ | _O(m + n)_ | Medium || +70| [Climbing Stairs](https://oj.leetcode.com/problems/climbing-stairs/)| [Python](./Python/climbing-stairs.py) | _O(n)_ | _O(1)_ | Easy || +72| [Edit Distance](https://oj.leetcode.com/problems/edit-distance/)|[Python](./Python/edit-distance.py)| _O(m * n)_ | _O(m + n)_ | Hard || +85| [Maximal Rectangle](https://oj.leetcode.com/problems/maximal-rectangle/)|[Python](./Python/maximal-rectangle.py)| _O(n^2)_ | _O(n)_ | Hard || +87| [Scramble String](https://oj.leetcode.com/problems/scramble-string/) | [Python](./Python/scramble-string.py) | _O(n^4)_ | _O(n^3)_ | Hard || +91| [Decode Ways](https://oj.leetcode.com/problems/decode-ways/) | [Python](./Python/decode-ways.py)| _O(n)_ | _O(1)_ | Medium || +96| [Unique Binary Search Trees](https://oj.leetcode.com/problems/unique-binary-search-trees/) | [Python](./Python/unique-binary-search-trees.py) | _O(n^2)_ | _O(n)_ | Medium || +97| [Interleaving String](https://oj.leetcode.com/problems/interleaving-string/)|[Python](./Python/interleaving-string.py)| _O(m * n)_ | _O(m + n)_ | Hard || +115| [Distinct Subsequences](https://oj.leetcode.com/problems/distinct-subsequences/)|[Python](./Python/distinct-subsequences.py)| _O(n^2)_ | _O(n)_ | Hard || +120| [Triangle](https://oj.leetcode.com/problems/triangle/) | [Python](./Python/triangle.py) | _O(m * n)_ | _O(n)_ | Medium || +123| [Best Time to Buy and Sell Stock III](https://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/)| | [Python](./Python/best-time-to-buy-and-sell-stock-iii.py) | _O(n)_ | _O(1)_ | Hard || +132| [Palindrome Partitioning II](https://oj.leetcode.com/problems/palindrome-partitioning-ii/) | [Python](./Python/palindrome-partitioning-ii.py) | _O(n^2)_ | _O(n^2)_ | Hard || +139| [Word Break](https://oj.leetcode.com/problems/word-break/) | [Python](./Python/word-break.py) | _O(n^2)_ | _O(n)_ | Medium || +140| [Word Break II](https://oj.leetcode.com/problems/word-break-ii/) | [Python](./Python/word-break-ii.py) | _O(n^2)_ | _O(n)_ | Hard || +152| [Maximum Product Subarray](https://oj.leetcode.com/problems/maximum-product-subarray/)|[Python](./Python/maximum-product-subarray.py)| _O(n)_ | _O(1)_ | Medium || +174| [Dungeon Game](https://oj.leetcode.com/problems/dungeon-game/) | [Python](./Python/dungeon-game.py)| _O(m * n)_ | _O(m + n)_ | Hard || +188| [Best Time to Buy and Sell Stock IV](https://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/)| [Python](./Python/best-time-to-buy-and-sell-stock-iv.py) | _O(k * n)_ | _O(k)_ | Hard || +198| [House Robber](https://oj.leetcode.com/problems/house-robber/)| [Python](./Python/house-robber.py) | _O(n)_ | _O(1)_ | Easy || --- From c3d40ccc182965fb311491419691ad1bda409d24 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 16 May 2015 17:37:00 +0800 Subject: [PATCH 243/345] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index c3e6b73c5..59c38d245 100644 --- a/README.md +++ b/README.md @@ -329,7 +329,7 @@ Shell 97| [Interleaving String](https://oj.leetcode.com/problems/interleaving-string/)|[Python](./Python/interleaving-string.py)| _O(m * n)_ | _O(m + n)_ | Hard || 115| [Distinct Subsequences](https://oj.leetcode.com/problems/distinct-subsequences/)|[Python](./Python/distinct-subsequences.py)| _O(n^2)_ | _O(n)_ | Hard || 120| [Triangle](https://oj.leetcode.com/problems/triangle/) | [Python](./Python/triangle.py) | _O(m * n)_ | _O(n)_ | Medium || -123| [Best Time to Buy and Sell Stock III](https://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/)| | [Python](./Python/best-time-to-buy-and-sell-stock-iii.py) | _O(n)_ | _O(1)_ | Hard || +123| [Best Time to Buy and Sell Stock III](https://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/) | [Python](./Python/best-time-to-buy-and-sell-stock-iii.py) | _O(n)_ | _O(1)_ | Hard || 132| [Palindrome Partitioning II](https://oj.leetcode.com/problems/palindrome-partitioning-ii/) | [Python](./Python/palindrome-partitioning-ii.py) | _O(n^2)_ | _O(n^2)_ | Hard || 139| [Word Break](https://oj.leetcode.com/problems/word-break/) | [Python](./Python/word-break.py) | _O(n^2)_ | _O(n)_ | Medium || 140| [Word Break II](https://oj.leetcode.com/problems/word-break-ii/) | [Python](./Python/word-break-ii.py) | _O(n^2)_ | _O(n)_ | Hard || From dbe5eb1fe346bf1b99e843d3429238b486d10805 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 16 May 2015 17:46:13 +0800 Subject: [PATCH 244/345] Update README.md --- README.md | 52 +++++++++++++++------------------------------------- 1 file changed, 15 insertions(+), 37 deletions(-) diff --git a/README.md b/README.md index 59c38d245..3cc5eefc7 100644 --- a/README.md +++ b/README.md @@ -77,7 +77,7 @@ Shell 119 | [Pascal's Triangle II](https://oj.leetcode.com/problems/pascals-triangle-ii/)| [Python](./Python/pascals-triangle-ii.py) | _O(n^2)_ | _O(n)_ | Easy || 121 | [Best Time to Buy and Sell Stock](https://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock/)| [Python](./Python/best-time-to-buy-and-sell-stock.py) | _O(n)_ | _O(1)_ | Medium || 128 | [Longest Consecutive Sequence](https://oj.leetcode.com/problems/longest-consecutive-sequence/)| [Python](./Python/longest-consecutive-sequence.py) | _O(n)_ | _O(n)_ | Hard || Tricky -157 | [Read N Characters Given Read4](https://oj.leetcode.com/problems/read-n-characters-given-read4/) | [Python](/Python/read-n-characters-given-read4.py) | _O(n)_ | _O(1)_ | Easy || +157 | [Read N Characters Given Read4](https://oj.leetcode.com/problems/read-n-characters-given-read4/) | [Python](./Python/read-n-characters-given-read4.py) | _O(n)_ | _O(1)_ | Easy || 158 | [Read N Characters Given Read4 II - Call multiple times](https://oj.leetcode.com/problems/read-n-characters-given-read4-ii-call-multiple-times/) | [Python](./Python/read-n-characters-given-read4-ii-call-multiple-times.py) | _O(n)_ | _O(1)_ | Hard || 163 | [Missing Ranges](https://oj.leetcode.com/problems/missing-ranges/)| [Python](./Python/missing-ranges.py) | _O(n)_ | _O(1)_ | Medium || 169 | [Majority Element](https://oj.leetcode.com/problems/majority-element/) | [Python](./Python/majority-element.py) | _O(n)_ | _O(1)_ | Easy | @@ -341,46 +341,24 @@ Shell --- ##Backtracking -Problem | Solution | Time | Space | Difficulty | Notes ---------------- | --------------- | --------------- | --------------- | -------------- | ----- -[Word Ladder II] |[word-ladder-ii.py] | _O(n * d)_ | _O(d)_ | Hard | - -[Word Ladder II]:https://oj.leetcode.com/problems/word-ladder-ii/ -[word-ladder-ii.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/word-ladder-ii.py + # | Problem | Solution | Time | Space | Difficulty | Tag | Notes +-----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- +126| [Word Ladder II](https://oj.leetcode.com/problems/word-ladder-ii/) |[Python](./Python/word-ladder-ii.py) | _O(n * d)_ | _O(d)_ | Hard || --- ##Greedy -Problem | Solution | Time | Space | Difficulty | Notes ---------------- | --------------- | --------------- | --------------- | -------------- | ----- -[Best Time to Buy and Sell Stock II]| [best-time-to-buy-and-sell-stock-ii.py] | _O(n)_ | _O(1)_ | Medium | -[Candy]| [candy.py] | _O(n)_ | _O(n)_ | Hard | -[Container With Most Water]| [container-with-most-water.py] | _O(n)_ | _O(1)_ | Medium | -[Gas Station]| [gas-station.py] | _O(n)_ | _O(1)_ | Medium | -[Jump Game] | [jump-game.py] | _O(n)_ | _O(1)_ | Medium | -[Jump Game II] | [jump-game-ii.py] | _O(n)_ | _O(1)_ | Hard | -[Largest Rectangle in Histogram] | [largest-rectangle-in-histogram.py] | _O(n)_ | _O(n)_ | Hard | Tricky -[Trapping Rain Water] | [trapping-rain-water.py] | _O(n)_ | _O(1)_ | Hard | Tricky -[Wildcard Matching] | [wildcard-matching.py] | _O(m + n)_ | _O(1)_ | Hard | Tricky - -[Best Time to Buy and Sell Stock II]:https://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/ -[best-time-to-buy-and-sell-stock-ii.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/best-time-to-buy-and-sell-stock-ii.py -[Candy]:https://oj.leetcode.com/problems/candy/ -[candy.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/candy.py -[Container With Most Water]:https://oj.leetcode.com/problems/container-with-most-water/ -[container-with-most-water.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/container-with-most-water.py -[Gas Station]:https://oj.leetcode.com/problems/gas-station/ -[gas-station.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/gas-station.py -[Jump Game]:https://oj.leetcode.com/problems/jump-game/ -[jump-game.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/jump-game.py -[Jump Game II]:https://oj.leetcode.com/problems/jump-game-ii/ -[jump-game-ii.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/jump-game-ii.py -[Largest Rectangle in Histogram]:https://oj.leetcode.com/problems/largest-rectangle-in-histogram/ -[largest-rectangle-in-histogram.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/largest-rectangle-in-histogram.py -[Trapping Rain Water]:https://oj.leetcode.com/problems/trapping-rain-water/ -[trapping-rain-water.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/trapping-rain-water.py -[Wildcard Matching]:https://oj.leetcode.com/problems/wildcard-matching/ -[wildcard-matching.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/wildcard-matching.py + # | Problem | Solution | Time | Space | Difficulty | Tag | Notes +-----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- +11| [Container With Most Water](https://oj.leetcode.com/problems/container-with-most-water/)| [Python](./Python/container-with-most-water.py) | _O(n)_ | _O(1)_ | Medium || +42| [Trapping Rain Water](https://oj.leetcode.com/problems/trapping-rain-water/) | [Python](./Python/trapping-rain-water.py) | _O(n)_ | _O(1)_ | Hard || Tricky +44| [Wildcard Matching](https://oj.leetcode.com/problems/wildcard-matching/) | [Python](./Python/wildcard-matching.py) | _O(m + n)_ | _O(1)_ | Hard || Tricky +45| [Jump Game II](https://oj.leetcode.com/problems/jump-game-ii/) | [Python](./Python/jump-game-ii.py) | _O(n)_ | _O(1)_ | Hard || +55| [Jump Game](https://oj.leetcode.com/problems/jump-game/) | [Python](./Python/jump-game.py) | _O(n)_ | _O(1)_ | Medium || +84| [Largest Rectangle in Histogram](https://oj.leetcode.com/problems/largest-rectangle-in-histogram/) | [Python](./Python/largest-rectangle-in-histogram.py) | _O(n)_ | _O(n)_ | Hard || Tricky +122| [Best Time to Buy and Sell Stock II](https://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/)| [Python](./Python/best-time-to-buy-and-sell-stock-ii.py) | _O(n)_ | _O(1)_ | Medium || +134| [Gas Station](https://oj.leetcode.com/problems/gas-station/)| [Python](./Python/gas-station.py) | _O(n)_ | _O(1)_ | Medium || +135| [Candy](https://oj.leetcode.com/problems/candy/)| [Python](./Python/candy.py) | _O(n)_ | _O(n)_ | Hard || --- From 3563f768ab109b4af517198f6a1ea8a5c30ee1b1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 16 May 2015 17:48:09 +0800 Subject: [PATCH 245/345] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 3cc5eefc7..c1caad566 100644 --- a/README.md +++ b/README.md @@ -169,7 +169,7 @@ Shell 76| [Minimum Window Substring](https://oj.leetcode.com/problems/minimum-window-substring/) | [Python](./Python/minimum-window-substring.py) | _O(n)_ | _O(k)_ | Hard || 149| [Max Points on a Line](https://oj.leetcode.com/problems/max-points-on-a-line/) | [Python](./Python/max-points-on-a-line.py) | _O(n^2)_ | _O(n)_ | Hard || 159| [Longest Substring with At Most Two Distinct Characters](https://oj.leetcode.com/problems/longest-substring-with-at-most-two-distinct-characters/)| [Python](./Python/longest-substring-with-at-most-two-distinct-characters.py) | _O(n^2)_ | _O(1)_ | Hard || -167| [Two Sum III - Data structure design](https://oj.leetcode.com/problems/two-sum-iii-data-structure-design/) | [Python](./Python/two-sum-iii-data-structure-design.py) | _O(n)_ | _O(n)_ | Easy || +170| [Two Sum III - Data structure design](https://oj.leetcode.com/problems/two-sum-iii-data-structure-design/) | [Python](./Python/two-sum-iii-data-structure-design.py) | _O(n)_ | _O(n)_ | Easy || 187| [Repeated DNA Sequences](https://oj.leetcode.com/problems/repeated-dna-sequences/) | [Python](./Python/repeated-dna-sequences.py) | _O(n)_ | _O(n)_ | Medium || 202| [Happy Number](https://oj.leetcode.com/problems/happy-number/) | [Python](./Python/happy-number.py) | _O(k)_ | _O(k)_ | Easy || 204| [Count Primes](https://oj.leetcode.com/problems/count-primes/) | [Python](./Python/count-primes.py) | _O(n)_ | _O(n)_ | Easy || From cc79e6cfd0ab9c1fc9de1a33a220b8a72a66a371 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 16 May 2015 17:49:50 +0800 Subject: [PATCH 246/345] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index c1caad566..6e0e2164f 100644 --- a/README.md +++ b/README.md @@ -93,13 +93,13 @@ Shell 6| [ZigZag Conversion](https://oj.leetcode.com/problems/zigzag-conversion/) | [Python](./Python/zigzag-conversion.py) | _O(n)_ | _O(1)_ | Easy || 8| [String to Integer (atoi)](https://oj.leetcode.com/problems/string-to-integer-atoi/) | [Python](./Python/string-to-integer-atoi.py) | _O(n)_ | _O(1)_ | Easy || 14| [Longest Common Prefix](https://oj.leetcode.com/problems/longest-common-prefix/) | [Python](./Python/longest-common-prefix.py) | _O(n1 + n2 + ...)_ | _O(1)_ | Easy || -20| [Valid Palindrome](https://oj.leetcode.com/problems/valid-palindrome/) | [Python](./Python/valid-palindrome.py) | _O(n)_ | _O(1)_ | Easy || 28| [Implement strStr()](https://oj.leetcode.com/problems/implement-strstr/) | [Python](./Python/implement-strstr.py) | _O(n + m)_ | _O(m)_ | Easy || `KMP Algorithm` 38| [Count and Say](https://oj.leetcode.com/problems/compare-version-numbers/) | [Python](./Python/compare-version-numbers.py)| _O(n * 2^n)_ | _O(2^n)_ | Easy || 43| [Multiply Strings](https://oj.leetcode.com/problems/multiply-strings/) | [Python](./Python/multiply-strings.py) | _O(m * n)_ | _O(m + n)_ | Medium || 58| [Length of Last Word](https://oj.leetcode.com/problems/length-of-last-word/) | [Python](./Python/length-of-last-word.py) | _O(n)_ | _O(1)_ | Easy || 67| [Add Binary](https://oj.leetcode.com/problems/add-binary/) | [Python](./Python/add-binary.py) | _O(n)_ | _O(1)_ | Easy || 68| [Text Justification](https://oj.leetcode.com/problems/text-justification/) | [Python](./Python/text-justification.py) | _O(n)_ | _O(1)_ | Hard || +125| [Valid Palindrome](https://oj.leetcode.com/problems/valid-palindrome/) | [Python](./Python/valid-palindrome.py) | _O(n)_ | _O(1)_ | Easy || 151| [Reverse Words in a String](https://oj.leetcode.com/problems/reverse-words-in-a-string/) | [Python](./Python/reverse-words-in-a-string.py) | _O(n)_ | _O(n)_ | Medium || 161| [One Edit Distance](https://oj.leetcode.com/problems/one-edit-distance/) | [Python](./Python/one-edit-distance.py) | _O(m + n)_ | _O(1)_ | Medium || 165| [Compare Version Numbers](https://oj.leetcode.com/problems/count-and-say/) | [Python](./Python/count-and-say.py) | _O(n)_ | _O(1)_ | Easy || From 9614fc143ba0ef7af0e8d9bace8400fa5f79d6d3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 16 May 2015 18:14:55 +0800 Subject: [PATCH 247/345] Update README.md --- README.md | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index 6e0e2164f..736fd492e 100644 --- a/README.md +++ b/README.md @@ -77,9 +77,9 @@ Shell 119 | [Pascal's Triangle II](https://oj.leetcode.com/problems/pascals-triangle-ii/)| [Python](./Python/pascals-triangle-ii.py) | _O(n^2)_ | _O(n)_ | Easy || 121 | [Best Time to Buy and Sell Stock](https://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock/)| [Python](./Python/best-time-to-buy-and-sell-stock.py) | _O(n)_ | _O(1)_ | Medium || 128 | [Longest Consecutive Sequence](https://oj.leetcode.com/problems/longest-consecutive-sequence/)| [Python](./Python/longest-consecutive-sequence.py) | _O(n)_ | _O(n)_ | Hard || Tricky -157 | [Read N Characters Given Read4](https://oj.leetcode.com/problems/read-n-characters-given-read4/) | [Python](./Python/read-n-characters-given-read4.py) | _O(n)_ | _O(1)_ | Easy || -158 | [Read N Characters Given Read4 II - Call multiple times](https://oj.leetcode.com/problems/read-n-characters-given-read4-ii-call-multiple-times/) | [Python](./Python/read-n-characters-given-read4-ii-call-multiple-times.py) | _O(n)_ | _O(1)_ | Hard || -163 | [Missing Ranges](https://oj.leetcode.com/problems/missing-ranges/)| [Python](./Python/missing-ranges.py) | _O(n)_ | _O(1)_ | Medium || +157 | [Read N Characters Given Read4](https://oj.leetcode.com/problems/read-n-characters-given-read4/) | [Python](./Python/read-n-characters-given-read4.py) | _O(n)_ | _O(1)_ | Easy |📖| +158 | [Read N Characters Given Read4 II - Call multiple times](https://oj.leetcode.com/problems/read-n-characters-given-read4-ii-call-multiple-times/) | [Python](./Python/read-n-characters-given-read4-ii-call-multiple-times.py) | _O(n)_ | _O(1)_ | Hard |📖| +163 | [Missing Ranges](https://oj.leetcode.com/problems/missing-ranges/)| [Python](./Python/missing-ranges.py) | _O(n)_ | _O(1)_ | Medium | 📖 | 169 | [Majority Element](https://oj.leetcode.com/problems/majority-element/) | [Python](./Python/majority-element.py) | _O(n)_ | _O(1)_ | Easy | 189 | [Rotate Array](https://oj.leetcode.com/problems/rotate-array/) | [Python](./Python/rotate-array.py) | _O(n)_ | _O(1)_ | Easy || 209 | [Minimum Size Subarray Sum](https://leetcode.com/problems/minimum-size-subarray-sum/) | [Python] (./Python/minimum-size-subarray-sum.py) | _O(n)_ | _O(1)_ | Medium || @@ -101,7 +101,7 @@ Shell 68| [Text Justification](https://oj.leetcode.com/problems/text-justification/) | [Python](./Python/text-justification.py) | _O(n)_ | _O(1)_ | Hard || 125| [Valid Palindrome](https://oj.leetcode.com/problems/valid-palindrome/) | [Python](./Python/valid-palindrome.py) | _O(n)_ | _O(1)_ | Easy || 151| [Reverse Words in a String](https://oj.leetcode.com/problems/reverse-words-in-a-string/) | [Python](./Python/reverse-words-in-a-string.py) | _O(n)_ | _O(n)_ | Medium || -161| [One Edit Distance](https://oj.leetcode.com/problems/one-edit-distance/) | [Python](./Python/one-edit-distance.py) | _O(m + n)_ | _O(1)_ | Medium || +161| [One Edit Distance](https://oj.leetcode.com/problems/one-edit-distance/) | [Python](./Python/one-edit-distance.py) | _O(m + n)_ | _O(1)_ | Medium |📖| 165| [Compare Version Numbers](https://oj.leetcode.com/problems/count-and-say/) | [Python](./Python/count-and-say.py) | _O(n)_ | _O(1)_ | Easy || 186| [Reverse Words in a String II](https://oj.leetcode.com/problems/reverse-words-in-a-string-ii/) | [Python](./Python/reverse-words-in-a-string-ii.py) | _O(n)_ | _O(1)_ | Medium || 205| [Isomorphic Strings](https://oj.leetcode.com/problems/isomorphic-strings/) | [Python](./Python/isomorphic-strings.py) | _O(n)_ | _O(1)_ | Easy || @@ -168,8 +168,8 @@ Shell 49| [Anagrams](https://oj.leetcode.com/problems/anagrams/) | [Python](./Python/anagrams.py) | _O(n)_ | _O(n)_ | Medium || 76| [Minimum Window Substring](https://oj.leetcode.com/problems/minimum-window-substring/) | [Python](./Python/minimum-window-substring.py) | _O(n)_ | _O(k)_ | Hard || 149| [Max Points on a Line](https://oj.leetcode.com/problems/max-points-on-a-line/) | [Python](./Python/max-points-on-a-line.py) | _O(n^2)_ | _O(n)_ | Hard || -159| [Longest Substring with At Most Two Distinct Characters](https://oj.leetcode.com/problems/longest-substring-with-at-most-two-distinct-characters/)| [Python](./Python/longest-substring-with-at-most-two-distinct-characters.py) | _O(n^2)_ | _O(1)_ | Hard || -170| [Two Sum III - Data structure design](https://oj.leetcode.com/problems/two-sum-iii-data-structure-design/) | [Python](./Python/two-sum-iii-data-structure-design.py) | _O(n)_ | _O(n)_ | Easy || +159| [Longest Substring with At Most Two Distinct Characters](https://oj.leetcode.com/problems/longest-substring-with-at-most-two-distinct-characters/)| [Python](./Python/longest-substring-with-at-most-two-distinct-characters.py) | _O(n^2)_ | _O(1)_ | Hard |📖| +170| [Two Sum III - Data structure design](https://oj.leetcode.com/problems/two-sum-iii-data-structure-design/) | [Python](./Python/two-sum-iii-data-structure-design.py) | _O(n)_ | _O(n)_ | Easy | 📖 | 187| [Repeated DNA Sequences](https://oj.leetcode.com/problems/repeated-dna-sequences/) | [Python](./Python/repeated-dna-sequences.py) | _O(n)_ | _O(n)_ | Medium || 202| [Happy Number](https://oj.leetcode.com/problems/happy-number/) | [Python](./Python/happy-number.py) | _O(k)_ | _O(k)_ | Easy || 204| [Count Primes](https://oj.leetcode.com/problems/count-primes/) | [Python](./Python/count-primes.py) | _O(n)_ | _O(n)_ | Easy || @@ -224,7 +224,7 @@ Shell 141| [Linked List Cycle](https://oj.leetcode.com/problems/linked-list-cycle/)| [Python](./Python/linked-list-cycle.py) | _O(n)_ | _O(1)_ | Medium || 142| [Linked List Cycle II](https://oj.leetcode.com/problems/linked-list-cycle-ii/)| [Python](./Python/linked-list-cycle-ii.py) | _O(n)_ | _O(1)_ | Medium || 143| [Reorder List](https://oj.leetcode.com/problems/reorder-list/)| [Python](./Python/reorder-list.py) | _O(n)_ | _O(1)_ | Medium || -167| [Two Sum II - Input array is sorted](https://oj.leetcode.com/problems/two-sum-ii-input-array-is-sorted/) | [Python](./Python/two-sum-ii-input-array-is-sorted.py) | _O(n)_ | _O(1)_ | Medium || +167| [Two Sum II - Input array is sorted](https://oj.leetcode.com/problems/two-sum-ii-input-array-is-sorted/) | [Python](./Python/two-sum-ii-input-array-is-sorted.py) | _O(n)_ | _O(1)_ | Medium | 📖 | --- @@ -256,7 +256,7 @@ Shell 116| [Populating Next Right Pointers in Each Node](https://oj.leetcode.com/problems/populating-next-right-pointers-in-each-node/)|[Python](./Python/populating-next-right-pointers-in-each-node.py)| _O(n)_ | _O(1)_ | Medium || 124| [Binary Tree Maximum Path Sum](https://oj.leetcode.com/problems/binary-tree-maximum-path-sum/)| [Python](./Python/binary-tree-maximum-path-sum.py) | _O(n)_| _O(h)_| Hard || 129| [Sum Root to Leaf Numbers](https://oj.leetcode.com/problems/sum-root-to-leaf-numbers/) | [Python](./Python/sum-root-to-leaf-numbers.py) | _O(n)_ | _O(h)_ | Medium || -156| [Binary Tree Upside Down](https://oj.leetcode.com/problems/binary-tree-upside-down/) | [Python](./Python/binary-tree-upside-down.py) | _O(n)_ | _O(1)_ | Medium || +156| [Binary Tree Upside Down](https://oj.leetcode.com/problems/binary-tree-upside-down/) | [Python](./Python/binary-tree-upside-down.py) | _O(n)_ | _O(1)_ | Medium |📖| --- From 3951e5b103e1b32596e752c77d31d5af5b642c9b Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 16 May 2015 18:18:59 +0800 Subject: [PATCH 248/345] Update README.md --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 736fd492e..478200dd7 100644 --- a/README.md +++ b/README.md @@ -6,6 +6,7 @@ The number of problems is increasing recently. Here is the classification of all `211` problems. For extra problems and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repo. I'll keep updating for full summary and better solutions. Stay tuned for updates. +(Notes: "📖" means you have to buy the book from LeetCode. ) --- Algorithms @@ -103,7 +104,7 @@ Shell 151| [Reverse Words in a String](https://oj.leetcode.com/problems/reverse-words-in-a-string/) | [Python](./Python/reverse-words-in-a-string.py) | _O(n)_ | _O(n)_ | Medium || 161| [One Edit Distance](https://oj.leetcode.com/problems/one-edit-distance/) | [Python](./Python/one-edit-distance.py) | _O(m + n)_ | _O(1)_ | Medium |📖| 165| [Compare Version Numbers](https://oj.leetcode.com/problems/count-and-say/) | [Python](./Python/count-and-say.py) | _O(n)_ | _O(1)_ | Easy || -186| [Reverse Words in a String II](https://oj.leetcode.com/problems/reverse-words-in-a-string-ii/) | [Python](./Python/reverse-words-in-a-string-ii.py) | _O(n)_ | _O(1)_ | Medium || +186| [Reverse Words in a String II](https://oj.leetcode.com/problems/reverse-words-in-a-string-ii/) | [Python](./Python/reverse-words-in-a-string-ii.py) | _O(n)_ | _O(1)_ | Medium | 📖 | 205| [Isomorphic Strings](https://oj.leetcode.com/problems/isomorphic-strings/) | [Python](./Python/isomorphic-strings.py) | _O(n)_ | _O(1)_ | Easy || --- From 059ed13953da1b7c384acf937dcf8334045c2eeb Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 17 May 2015 13:38:20 +0800 Subject: [PATCH 249/345] Update rotate-image.py --- Python/rotate-image.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/rotate-image.py b/Python/rotate-image.py index c434dffa5..dabc2734f 100644 --- a/Python/rotate-image.py +++ b/Python/rotate-image.py @@ -20,12 +20,12 @@ def rotate(self, matrix): # anti-diagonal mirror for i in xrange(n): for j in xrange(n - i): - matrix[i][j], matrix[n - 1 - j][n - 1 -i] = matrix[n - 1 - j][n - 1 -i], matrix[i][j] + matrix[i][j], matrix[n-1-j][n-1-i] = matrix[n-1-j][n-1-i], matrix[i][j] # horizontal mirror for i in xrange(n / 2): for j in xrange(n): - matrix[i][j], matrix[n - 1 - i][j] = matrix[n - 1 - i][j], matrix[i][j] + matrix[i][j], matrix[n-1-i][j] = matrix[n-1-i][j], matrix[i][j] return matrix From 3565d7fad5cbf96e964f9cb391803bd7e8e77711 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 19 May 2015 13:30:41 +0800 Subject: [PATCH 250/345] Create word-search-ii.cpp --- C++/word-search-ii.cpp | 101 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 101 insertions(+) create mode 100644 C++/word-search-ii.cpp diff --git a/C++/word-search-ii.cpp b/C++/word-search-ii.cpp new file mode 100644 index 000000000..768f0264d --- /dev/null +++ b/C++/word-search-ii.cpp @@ -0,0 +1,101 @@ +// Time: O(m * n * h), h is height of trie +// Space: O(26^h) + +class Solution { +private: + struct TrieNode { + bool isString = false; + unordered_map leaves; + + bool Insert(const string& s) { + auto* p = this; + for (const auto& c : s) { + if (p->leaves.find(c) == p->leaves.cend()) { + p->leaves[c] = new TrieNode; + } + p = p->leaves[c]; + } + + // s already existed in this trie. + if (p->isString) { + return false; + } else { + p->isString = true; + return true; + } + } + + ~TrieNode() { + for (auto& kv : leaves) { + if (kv.second) { + kv.second->~TrieNode(); + } + } + } + }; + +public: + /** + * @param board: A list of lists of character + * @param words: A list of string + * @return: A list of string + */ + vector findWords(vector>& board, vector& words) { + unordered_set ret; + vector> visited(board.size(), vector(board[0].size(), false)); + string curr; + TrieNode trie; + for (const auto& word : words) { + trie.Insert(word); + } + + for (int i = 0; i < board.size(); ++i) { + for (int j = 0; j < board[0].size(); ++j) { + findWordsDFS(board, visited, &trie, i, j, curr, ret); + } + } + + return vector(ret.begin(), ret.end()); + } + + void findWordsDFS(vector> &grid, + vector> &visited, + TrieNode *trie, + int i, + int j, + string curr, + unordered_set &ret) { + // Invalid state. + if (!trie || i < 0 || i >= grid.size() || j < 0 || j >= grid[0].size()) { + return; + } + + // Not in trie or visited. + if (!trie->leaves[grid[i][j] ] || visited[i][j]) { + return; + } + + // Get next trie nodes. + TrieNode *nextNode = trie->leaves[grid[i][j]]; + + // Update current string. + curr.push_back(grid[i][j]); + + // Find the string, add to the answers. + if (nextNode->isString) { + ret.insert(curr); + } + + // Marked as visited. + visited[i][j] = true; + + // Try each direction. + vector> direction{{0, -1}, {0, 1}, {-1, 0}, {1, 0}}; + for (int k = 0; k < 4; ++k) { + findWordsDFS(grid, visited, nextNode, + i + direction[k].first, j + direction[k].second, curr, ret); + } + + visited[i][j] = false; + } +}; From b3bc5f56cb3fb59c3f618ad516e3a8fc66ddd74e Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 19 May 2015 13:31:57 +0800 Subject: [PATCH 251/345] Update README.md --- README.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 478200dd7..ced0ae0d8 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ LeetCode ======== -Up to date (2015-05-16), there are `195` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://oj.leetcode.com/). +Up to date (2015-05-16), there are `196` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://oj.leetcode.com/). The number of problems is increasing recently. -Here is the classification of all `211` problems. +Here is the classification of all `212` problems. For extra problems and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repo. I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "📖" means you have to buy the book from LeetCode. ) @@ -155,6 +155,7 @@ Shell 145 | [Binary Tree Postorder Traversal](https://oj.leetcode.com/problems/binary-tree-postorder-traversal/) | [Python](./Python/binary-tree-postorder-traversal.py) | _O(n)_| _O(1)_| Hard || `Morris Traversal` 208 | [Implement Trie (Prefix Tree)](https://leetcode.com/problems/implement-trie-prefix-tree/) | [Python](./Python/implement-trie-prefix-tree.py) | _O(n)_ | _O(1)_ | Medium || Trie 211 | [Add and Search Word - Data structure design ](https://leetcode.com/problems/add-and-search-word-data-structure-design/) | [C++](./C++/add-and-search-word-data-structure-design.cpp) [Python](./Python/add-and-search-word-data-structure-design.py) | _O(min(n, h))_ | _O(min(n, h))_ | Medium || Trie, DFS +212| [Word Search II](https://oj.leetcode.com/problems/word-search-ii/) | [C++](./Python/word-search-ii.cpp) | _O(m * n * l)_ | _O(l)_ | Medium || --- From 72e51f270d7547291e458ed04a9d1f78a951ab7c Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 19 May 2015 13:33:37 +0800 Subject: [PATCH 252/345] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index ced0ae0d8..dc59542c0 100644 --- a/README.md +++ b/README.md @@ -155,7 +155,7 @@ Shell 145 | [Binary Tree Postorder Traversal](https://oj.leetcode.com/problems/binary-tree-postorder-traversal/) | [Python](./Python/binary-tree-postorder-traversal.py) | _O(n)_| _O(1)_| Hard || `Morris Traversal` 208 | [Implement Trie (Prefix Tree)](https://leetcode.com/problems/implement-trie-prefix-tree/) | [Python](./Python/implement-trie-prefix-tree.py) | _O(n)_ | _O(1)_ | Medium || Trie 211 | [Add and Search Word - Data structure design ](https://leetcode.com/problems/add-and-search-word-data-structure-design/) | [C++](./C++/add-and-search-word-data-structure-design.cpp) [Python](./Python/add-and-search-word-data-structure-design.py) | _O(min(n, h))_ | _O(min(n, h))_ | Medium || Trie, DFS -212| [Word Search II](https://oj.leetcode.com/problems/word-search-ii/) | [C++](./Python/word-search-ii.cpp) | _O(m * n * l)_ | _O(l)_ | Medium || +212| [Word Search II](https://oj.leetcode.com/problems/word-search-ii/) | [C++](./Python/word-search-ii.cpp) | _O(m * n * l)_ | _O(l)_ | Hard | LintCode | Trie, DFS --- From e32f5d65d9a02845b49a29c64dfc21b51ba5bb2d Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 19 May 2015 15:07:56 +0800 Subject: [PATCH 253/345] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index dc59542c0..ff4eb9ebb 100644 --- a/README.md +++ b/README.md @@ -155,7 +155,7 @@ Shell 145 | [Binary Tree Postorder Traversal](https://oj.leetcode.com/problems/binary-tree-postorder-traversal/) | [Python](./Python/binary-tree-postorder-traversal.py) | _O(n)_| _O(1)_| Hard || `Morris Traversal` 208 | [Implement Trie (Prefix Tree)](https://leetcode.com/problems/implement-trie-prefix-tree/) | [Python](./Python/implement-trie-prefix-tree.py) | _O(n)_ | _O(1)_ | Medium || Trie 211 | [Add and Search Word - Data structure design ](https://leetcode.com/problems/add-and-search-word-data-structure-design/) | [C++](./C++/add-and-search-word-data-structure-design.cpp) [Python](./Python/add-and-search-word-data-structure-design.py) | _O(min(n, h))_ | _O(min(n, h))_ | Medium || Trie, DFS -212| [Word Search II](https://oj.leetcode.com/problems/word-search-ii/) | [C++](./Python/word-search-ii.cpp) | _O(m * n * l)_ | _O(l)_ | Hard | LintCode | Trie, DFS +212| [Word Search II](https://oj.leetcode.com/problems/word-search-ii/) | [C++](./C++/word-search-ii.cpp) | _O(m * n * l)_ | _O(l)_ | Hard | LintCode | Trie, DFS --- From b6e8693890b594f4c4f61d65d61aea1a9e525ebf Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 19 May 2015 16:01:19 +0800 Subject: [PATCH 254/345] Create word-search-ii.py --- Python/word-search-ii.py | 74 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 Python/word-search-ii.py diff --git a/Python/word-search-ii.py b/Python/word-search-ii.py new file mode 100644 index 000000000..3b2ca2499 --- /dev/null +++ b/Python/word-search-ii.py @@ -0,0 +1,74 @@ +# Time: O(m * n * l) +# Space: O(l) +# +# Given a 2D board and a list of words from the dictionary, find all words in the board. +# +# Each word must be constructed from letters of sequentially adjacent cell, where "adjacent" cells +# are those horizontally or vertically neighboring. The same letter cell may not be used more than once in a word. +# +# For example, +# Given words = ["oath","pea","eat","rain"] and board = +# +# [ +# ['o','a','a','n'], +# ['e','t','a','e'], +# ['i','h','k','r'], +# ['i','f','l','v'] +# ] +# Return ["eat","oath"]. +# Note: +# You may assume that all inputs are consist of lowercase letters a-z. +# +class TrieNode: + # Initialize your data structure here. + def __init__(self): + self.flag = False + self.children = {} + + # Inserts a word into the trie. + def insert(self, word): + cur = self + for c in word: + if not c in cur.children: + cur.children[c] = TrieNode() + cur = cur.children[c] + cur.flag = True + +class Solution: + # @param {character[][]} board + # @param {string[]} words + # @return {string[]} + def findWords(self, board, words): + visited = [[False for j in xrange(len(board[0]))] for i in xrange(len(board))] + result = {} + trie = TrieNode() + for word in words: + trie.insert(word) + + for i in xrange(len(board)): + for j in xrange(len(board[0])): + if self.existRecu(board, trie, 0, i, j, visited, [], result): + return True + + return result.keys() + + def existRecu(self, board, trie, cur, i, j, visited, cur_word, result): + if not trie or i < 0 or i >= len(board) or j < 0 or j >= len(board[0]) or visited[i][j]: + return + + if board[i][j] not in trie.children: + return + + cur_word.append(board[i][j]) + next_node = trie.children[board[i][j]] + if next_node.flag: + result["".join(cur_word)] = True + + visited[i][j] = True + self.existRecu(board, next_node, cur + 1, i + 1, j, visited, cur_word, result) + self.existRecu(board, next_node, cur + 1, i - 1, j, visited, cur_word, result) + self.existRecu(board, next_node, cur + 1, i, j + 1, visited, cur_word, result) + self.existRecu(board, next_node, cur + 1, i, j - 1, visited, cur_word, result) + visited[i][j] = False + cur_word.pop() + From 77e2036be5bdad85e3511d0062288d4e88f68a0e Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 19 May 2015 16:01:49 +0800 Subject: [PATCH 255/345] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index ff4eb9ebb..aab0242ef 100644 --- a/README.md +++ b/README.md @@ -155,7 +155,7 @@ Shell 145 | [Binary Tree Postorder Traversal](https://oj.leetcode.com/problems/binary-tree-postorder-traversal/) | [Python](./Python/binary-tree-postorder-traversal.py) | _O(n)_| _O(1)_| Hard || `Morris Traversal` 208 | [Implement Trie (Prefix Tree)](https://leetcode.com/problems/implement-trie-prefix-tree/) | [Python](./Python/implement-trie-prefix-tree.py) | _O(n)_ | _O(1)_ | Medium || Trie 211 | [Add and Search Word - Data structure design ](https://leetcode.com/problems/add-and-search-word-data-structure-design/) | [C++](./C++/add-and-search-word-data-structure-design.cpp) [Python](./Python/add-and-search-word-data-structure-design.py) | _O(min(n, h))_ | _O(min(n, h))_ | Medium || Trie, DFS -212| [Word Search II](https://oj.leetcode.com/problems/word-search-ii/) | [C++](./C++/word-search-ii.cpp) | _O(m * n * l)_ | _O(l)_ | Hard | LintCode | Trie, DFS +212| [Word Search II](https://oj.leetcode.com/problems/word-search-ii/) | [C++](./C++/word-search-ii.cpp) [Python](./C++/word-search-ii.py) | _O(m * n * l)_ | _O(l)_ | Hard | LintCode | Trie, DFS --- From c270af60c717fb1ae2eeb75cf5ccdfd02c9a5118 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 19 May 2015 16:02:48 +0800 Subject: [PATCH 256/345] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index aab0242ef..6e91321b9 100644 --- a/README.md +++ b/README.md @@ -155,7 +155,7 @@ Shell 145 | [Binary Tree Postorder Traversal](https://oj.leetcode.com/problems/binary-tree-postorder-traversal/) | [Python](./Python/binary-tree-postorder-traversal.py) | _O(n)_| _O(1)_| Hard || `Morris Traversal` 208 | [Implement Trie (Prefix Tree)](https://leetcode.com/problems/implement-trie-prefix-tree/) | [Python](./Python/implement-trie-prefix-tree.py) | _O(n)_ | _O(1)_ | Medium || Trie 211 | [Add and Search Word - Data structure design ](https://leetcode.com/problems/add-and-search-word-data-structure-design/) | [C++](./C++/add-and-search-word-data-structure-design.cpp) [Python](./Python/add-and-search-word-data-structure-design.py) | _O(min(n, h))_ | _O(min(n, h))_ | Medium || Trie, DFS -212| [Word Search II](https://oj.leetcode.com/problems/word-search-ii/) | [C++](./C++/word-search-ii.cpp) [Python](./C++/word-search-ii.py) | _O(m * n * l)_ | _O(l)_ | Hard | LintCode | Trie, DFS +212| [Word Search II](https://oj.leetcode.com/problems/word-search-ii/) | [C++](./C++/word-search-ii.cpp) [Python](./Python/word-search-ii.py) | _O(m * n * l)_ | _O(l)_ | Hard | LintCode | Trie, DFS --- From 89de62ff5fda0afc77e94ae8195479c5740159de Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 19 May 2015 16:04:11 +0800 Subject: [PATCH 257/345] Update word-search-ii.py --- Python/word-search-ii.py | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/Python/word-search-ii.py b/Python/word-search-ii.py index 3b2ca2499..dd806f75f 100644 --- a/Python/word-search-ii.py +++ b/Python/word-search-ii.py @@ -47,12 +47,12 @@ def findWords(self, board, words): for i in xrange(len(board)): for j in xrange(len(board[0])): - if self.existRecu(board, trie, 0, i, j, visited, [], result): + if self.findWordsRecu(board, trie, 0, i, j, visited, [], result): return True return result.keys() - def existRecu(self, board, trie, cur, i, j, visited, cur_word, result): + def findWordsRecu(self, board, trie, cur, i, j, visited, cur_word, result): if not trie or i < 0 or i >= len(board) or j < 0 or j >= len(board[0]) or visited[i][j]: return @@ -65,10 +65,10 @@ def existRecu(self, board, trie, cur, i, j, visited, cur_word, result): result["".join(cur_word)] = True visited[i][j] = True - self.existRecu(board, next_node, cur + 1, i + 1, j, visited, cur_word, result) - self.existRecu(board, next_node, cur + 1, i - 1, j, visited, cur_word, result) - self.existRecu(board, next_node, cur + 1, i, j + 1, visited, cur_word, result) - self.existRecu(board, next_node, cur + 1, i, j - 1, visited, cur_word, result) + self.findWordsRecu(board, next_node, cur + 1, i + 1, j, visited, cur_word, result) + self.findWordsRecu(board, next_node, cur + 1, i - 1, j, visited, cur_word, result) + self.findWordsRecu(board, next_node, cur + 1, i, j + 1, visited, cur_word, result) + self.findWordsRecu(board, next_node, cur + 1, i, j - 1, visited, cur_word, result) visited[i][j] = False cur_word.pop() From 580a84353eb45297ffbfd5a105cd55c03ac8ca47 Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Tue, 19 May 2015 20:52:03 +0800 Subject: [PATCH 258/345] update --- ...d-and-search-word-data-structure-design.py | 22 +++++++++---------- Python/implement-trie-prefix-tree.py | 18 +++++++-------- Python/word-search-ii.py | 18 +++++++-------- 3 files changed, 29 insertions(+), 29 deletions(-) diff --git a/Python/add-and-search-word-data-structure-design.py b/Python/add-and-search-word-data-structure-design.py index 1c8b80d59..384b97d64 100644 --- a/Python/add-and-search-word-data-structure-design.py +++ b/Python/add-and-search-word-data-structure-design.py @@ -24,8 +24,8 @@ class TrieNode: # Initialize your data structure here. def __init__(self): - self.flag = False - self.children = {} + self.is_string = False + self.leaves = {} class WordDictionary: def __init__(self): @@ -37,10 +37,10 @@ def __init__(self): def addWord(self, word): curr = self.root for c in word: - if not c in curr.children: - curr.children[c] = TrieNode() - curr = curr.children[c] - curr.flag = True + if not c in curr.leaves: + curr.leaves[c] = TrieNode() + curr = curr.leaves[c] + curr.is_string = True # @param {string} word # @return {boolean} @@ -51,12 +51,12 @@ def search(self, word): def searchHelper(self, word, start, curr): if start == len(word): - return curr.flag - if word[start] in curr.children: - return self.searchHelper(word, start+1, curr.children[word[start]]) + return curr.is_string + if word[start] in curr.leaves: + return self.searchHelper(word, start+1, curr.leaves[word[start]]) elif word[start] == '.': - for c in curr.children: - if self.searchHelper(word, start+1, curr.children[c]): + for c in curr.leaves: + if self.searchHelper(word, start+1, curr.leaves[c]): return True return False diff --git a/Python/implement-trie-prefix-tree.py b/Python/implement-trie-prefix-tree.py index 1fc9cb47a..c52003ae3 100644 --- a/Python/implement-trie-prefix-tree.py +++ b/Python/implement-trie-prefix-tree.py @@ -10,8 +10,8 @@ class TrieNode: # Initialize your data structure here. def __init__(self): - self.flag = False - self.children = {} + self.is_string = False + self.leaves = {} class Trie: @@ -25,10 +25,10 @@ def __init__(self): def insert(self, word): cur = self.root for c in word: - if not c in cur.children: - cur.children[c] = TrieNode() - cur = cur.children[c] - cur.flag = True + if not c in cur.leaves: + cur.leaves[c] = TrieNode() + cur = cur.leaves[c] + cur.is_string = True # @param {string} word # @return {boolean} @@ -36,7 +36,7 @@ def insert(self, word): def search(self, word): res, node = self.childSearch(word) if res: - return node.flag + return node.is_string return False # @param {string} prefix @@ -49,8 +49,8 @@ def startsWith(self, prefix): def childSearch(self, word): cur = self.root for c in word: - if c in cur.children: - cur = cur.children[c] + if c in cur.leaves: + cur = cur.leaves[c] else: return False, None return True, cur diff --git a/Python/word-search-ii.py b/Python/word-search-ii.py index dd806f75f..36b7afe93 100644 --- a/Python/word-search-ii.py +++ b/Python/word-search-ii.py @@ -22,17 +22,17 @@ class TrieNode: # Initialize your data structure here. def __init__(self): - self.flag = False - self.children = {} + self.is_string = False + self.leaves = {} # Inserts a word into the trie. def insert(self, word): cur = self for c in word: - if not c in cur.children: - cur.children[c] = TrieNode() - cur = cur.children[c] - cur.flag = True + if not c in cur.leaves: + cur.leaves[c] = TrieNode() + cur = cur.leaves[c] + cur.is_string = True class Solution: # @param {character[][]} board @@ -56,12 +56,12 @@ def findWordsRecu(self, board, trie, cur, i, j, visited, cur_word, result): if not trie or i < 0 or i >= len(board) or j < 0 or j >= len(board[0]) or visited[i][j]: return - if board[i][j] not in trie.children: + if board[i][j] not in trie.leaves: return cur_word.append(board[i][j]) - next_node = trie.children[board[i][j]] - if next_node.flag: + next_node = trie.leaves[board[i][j]] + if next_node.is_string: result["".join(cur_word)] = True visited[i][j] = True From fc35e0e95c7020b0a2cf5a8c4a94751ae08f6b66 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 20 May 2015 11:31:00 +0800 Subject: [PATCH 259/345] Create house-robber-ii.py --- Python/house-robber-ii.py | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 Python/house-robber-ii.py diff --git a/Python/house-robber-ii.py b/Python/house-robber-ii.py new file mode 100644 index 000000000..554ed4828 --- /dev/null +++ b/Python/house-robber-ii.py @@ -0,0 +1,37 @@ +# Time: O(n) +# Space: O(1) +# +# Note: This is an extension of House Robber. +# +# After robbing those houses on that street, the thief has found himself a new place +# for his thievery so that he will not get too much attention. This time, all houses +# at this place are arranged in a circle. That means the first house is the neighbor +# of the last one. Meanwhile, the security system for these houses remain the same as +# for those in the previous street. +# +# Given a list of non-negative integers representing the amount of money of each house, +# determine the maximum amount of money you can rob tonight without alerting the police. +# +class Solution: + # @param {integer[]} nums + # @return {integer} + def rob(self, nums): + if len(nums) == 0: + return 0 + + if len(nums) == 1: + return nums[0] + + return max(self.robRange(nums, 0, len(nums) - 1),\ + self.robRange(nums, 1, len(nums))) + + def robRange(self, nums, start, end): + num_i, num_i_1 = nums[start], 0 + for i in xrange(start + 1, end): + num_i_1, num_i_2 = num_i, num_i_1 + num_i = max(nums[i] + num_i_2, num_i_1); + + return num_i + +if __name__ == '__main__': + print Solution().rob([8,4,8,5,9,6,5,4,4,10]) From 63eb6e72c3243a8cb15706ed42502e49a41e6189 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 20 May 2015 11:32:10 +0800 Subject: [PATCH 260/345] Update README.md --- README.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 6e91321b9..8ae25980d 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ LeetCode ======== -Up to date (2015-05-16), there are `196` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://oj.leetcode.com/). +Up to date (2015-05-20), there are `197` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://oj.leetcode.com/). The number of problems is increasing recently. -Here is the classification of all `212` problems. +Here is the classification of all `213` problems. For extra problems and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repo. I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "📖" means you have to buy the book from LeetCode. ) @@ -339,6 +339,7 @@ Shell 174| [Dungeon Game](https://oj.leetcode.com/problems/dungeon-game/) | [Python](./Python/dungeon-game.py)| _O(m * n)_ | _O(m + n)_ | Hard || 188| [Best Time to Buy and Sell Stock IV](https://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/)| [Python](./Python/best-time-to-buy-and-sell-stock-iv.py) | _O(k * n)_ | _O(k)_ | Hard || 198| [House Robber](https://oj.leetcode.com/problems/house-robber/)| [Python](./Python/house-robber.py) | _O(n)_ | _O(1)_ | Easy || +213| [House Robber II](https://oj.leetcode.com/problems/house-robber-ii/)| [Python](./Python/house-robber-ii.py) | _O(n)_ | _O(1)_ | Medium || --- From 39355ee045cc9282b131ac55d3694b03afe6ff20 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 20 May 2015 11:41:20 +0800 Subject: [PATCH 261/345] Create house-robber-ii.cpp --- C++/house-robber-ii.cpp | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 C++/house-robber-ii.cpp diff --git a/C++/house-robber-ii.cpp b/C++/house-robber-ii.cpp new file mode 100644 index 000000000..4648bfa2c --- /dev/null +++ b/C++/house-robber-ii.cpp @@ -0,0 +1,25 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + int rob(vector& nums) { + if (nums.size() == 0) { + return 0; + } + if (nums.size() == 1) { + return nums[0]; + } + + return max(robRange(nums, 0, nums.size() - 1), robRange(nums, 1, nums.size())); + } + int robRange(vector& nums, int start, int end) { + int num_i = nums[start], num_i_1 = 0, num_i_2 = 0; + for (int i = start + 1; i < end; ++i) { + num_i_2 = num_i_1; + num_i_1 = num_i; + num_i = max(nums[i] + num_i_2, num_i_1); + } + return num_i; + } +}; From b3d6a96550612d3f7e8751d44e37ce90545c8681 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 20 May 2015 11:41:53 +0800 Subject: [PATCH 262/345] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 8ae25980d..9605b65ba 100644 --- a/README.md +++ b/README.md @@ -339,7 +339,7 @@ Shell 174| [Dungeon Game](https://oj.leetcode.com/problems/dungeon-game/) | [Python](./Python/dungeon-game.py)| _O(m * n)_ | _O(m + n)_ | Hard || 188| [Best Time to Buy and Sell Stock IV](https://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/)| [Python](./Python/best-time-to-buy-and-sell-stock-iv.py) | _O(k * n)_ | _O(k)_ | Hard || 198| [House Robber](https://oj.leetcode.com/problems/house-robber/)| [Python](./Python/house-robber.py) | _O(n)_ | _O(1)_ | Easy || -213| [House Robber II](https://oj.leetcode.com/problems/house-robber-ii/)| [Python](./Python/house-robber-ii.py) | _O(n)_ | _O(1)_ | Medium || +213| [House Robber II](https://oj.leetcode.com/problems/house-robber-ii/)| [C++](./C++/house-robber-ii.cpp) [Python](./Python/house-robber-ii.py) | _O(n)_ | _O(1)_ | Medium || --- From d721ca8bf5a2b02f43e3d269e1de2af5a43cf830 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 20 May 2015 11:43:25 +0800 Subject: [PATCH 263/345] Update house-robber-ii.cpp --- C++/house-robber-ii.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/C++/house-robber-ii.cpp b/C++/house-robber-ii.cpp index 4648bfa2c..7a11fb883 100644 --- a/C++/house-robber-ii.cpp +++ b/C++/house-robber-ii.cpp @@ -11,7 +11,8 @@ class Solution { return nums[0]; } - return max(robRange(nums, 0, nums.size() - 1), robRange(nums, 1, nums.size())); + return max(robRange(nums, 0, nums.size() - 1), // Include the first one of nums without the last one. + robRange(nums, 1, nums.size())); // Include the last one of nums without the first one. } int robRange(vector& nums, int start, int end) { int num_i = nums[start], num_i_1 = 0, num_i_2 = 0; From e91e5107ffa1b837d78a21b379e7b78a2c83e2ed Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 20 May 2015 11:43:38 +0800 Subject: [PATCH 264/345] Update house-robber-ii.cpp --- C++/house-robber-ii.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/house-robber-ii.cpp b/C++/house-robber-ii.cpp index 7a11fb883..10d119522 100644 --- a/C++/house-robber-ii.cpp +++ b/C++/house-robber-ii.cpp @@ -12,7 +12,7 @@ class Solution { } return max(robRange(nums, 0, nums.size() - 1), // Include the first one of nums without the last one. - robRange(nums, 1, nums.size())); // Include the last one of nums without the first one. + robRange(nums, 1, nums.size())); // Include the last one of nums without the first one. } int robRange(vector& nums, int start, int end) { int num_i = nums[start], num_i_1 = 0, num_i_2 = 0; From 41ac3c00c6a69b78c1c4b64abfbd49a487f024d9 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 20 May 2015 11:43:50 +0800 Subject: [PATCH 265/345] Update house-robber-ii.cpp --- C++/house-robber-ii.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/C++/house-robber-ii.cpp b/C++/house-robber-ii.cpp index 10d119522..6aa8f6039 100644 --- a/C++/house-robber-ii.cpp +++ b/C++/house-robber-ii.cpp @@ -14,6 +14,7 @@ class Solution { return max(robRange(nums, 0, nums.size() - 1), // Include the first one of nums without the last one. robRange(nums, 1, nums.size())); // Include the last one of nums without the first one. } + int robRange(vector& nums, int start, int end) { int num_i = nums[start], num_i_1 = 0, num_i_2 = 0; for (int i = start + 1; i < end; ++i) { From c9be7622681509b9e602a90d07feb663117299cc Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 20 May 2015 11:44:00 +0800 Subject: [PATCH 266/345] Update house-robber-ii.cpp --- C++/house-robber-ii.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/house-robber-ii.cpp b/C++/house-robber-ii.cpp index 6aa8f6039..5050a55f2 100644 --- a/C++/house-robber-ii.cpp +++ b/C++/house-robber-ii.cpp @@ -12,7 +12,7 @@ class Solution { } return max(robRange(nums, 0, nums.size() - 1), // Include the first one of nums without the last one. - robRange(nums, 1, nums.size())); // Include the last one of nums without the first one. + robRange(nums, 1, nums.size())); // Include the last one of nums without the first one. } int robRange(vector& nums, int start, int end) { From 79cbd4b6a81f59739aecb35b8d03dd9049f73e76 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 23 May 2015 20:27:22 +0800 Subject: [PATCH 267/345] Create shortest-palindrome.cpp --- C++/shortest-palindrome.cpp | 53 +++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 C++/shortest-palindrome.cpp diff --git a/C++/shortest-palindrome.cpp b/C++/shortest-palindrome.cpp new file mode 100644 index 000000000..3a547b834 --- /dev/null +++ b/C++/shortest-palindrome.cpp @@ -0,0 +1,53 @@ +class Solution { +public: + string shortestPalindrome(string s) { + string T = preProcess(s); + int n = T.length(); + vector P(n); + int C = 0, R = 0; + for (int i = 1; i < n - 1; ++i) { + int i_mirror = 2*C-i; // equals to i' = C - (i-C) + + P[i] = (R > i) ? min(R - i, P[i_mirror]) : 0; + + // Attempt to expand palindrome centered at i + while (T[i + 1 + P[i]] == T[i - 1 - P[i]]) { + ++P[i]; + } + + // If palindrome centered at i expand past R, + // adjust center based on expanded palindrome. + if (i + P[i] > R) { + C = i; + R = i + P[i]; + } + } + + // Find the max len of palindrome which starts with the first char of s. + int max_len = 0; + for (int i = 1; i < n - 1; ++i) { + if (i - P[i] == 1) { + max_len = P[i]; + } + } + + // Assume s is (Palindrome)abc + string ans = s.substr(max_len); // abc. + reverse(ans.begin(), ans.end()); // cba. + ans.append(s); // cba(Palindrome)abc. + return ans; + } + private: + string preProcess(string s) { + int n = s.length(); + if (n == 0) { + return "^$"; + } + string ret = "^"; + for (int i = 0; i < n; i++) + ret += "#" + s.substr(i, 1); + + ret += "#$"; + return ret; + } +}; From e53d687dbd40f80b0f397a24207ab080d50ea993 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 23 May 2015 20:30:38 +0800 Subject: [PATCH 268/345] Update README.md --- README.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 9605b65ba..64e57766a 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ LeetCode ======== -Up to date (2015-05-20), there are `197` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://oj.leetcode.com/). +Up to date (2015-05-23), there are `199` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://oj.leetcode.com/). The number of problems is increasing recently. -Here is the classification of all `213` problems. +Here is the classification of all `215` problems. For extra problems and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repo. I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "📖" means you have to buy the book from LeetCode. ) @@ -106,6 +106,7 @@ Shell 165| [Compare Version Numbers](https://oj.leetcode.com/problems/count-and-say/) | [Python](./Python/count-and-say.py) | _O(n)_ | _O(1)_ | Easy || 186| [Reverse Words in a String II](https://oj.leetcode.com/problems/reverse-words-in-a-string-ii/) | [Python](./Python/reverse-words-in-a-string-ii.py) | _O(n)_ | _O(1)_ | Medium | 📖 | 205| [Isomorphic Strings](https://oj.leetcode.com/problems/isomorphic-strings/) | [Python](./Python/isomorphic-strings.py) | _O(n)_ | _O(1)_ | Easy || +214| [Shortest Palindromic Substring](https://oj.leetcode.com/problems/shortest-palindrome/) | [C++](./C++/shortest-palindrome.cpp) | _O(n)_ | _O(n)_ | Hard || `Manacher's Algorithm` --- From 17353621a5e474f886872b7b0134c9238ace6520 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 23 May 2015 20:46:10 +0800 Subject: [PATCH 269/345] Create kth-largest-element-in-an-array.cpp --- C++/kth-largest-element-in-an-array.cpp | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 C++/kth-largest-element-in-an-array.cpp diff --git a/C++/kth-largest-element-in-an-array.cpp b/C++/kth-largest-element-in-an-array.cpp new file mode 100644 index 000000000..caabd1846 --- /dev/null +++ b/C++/kth-largest-element-in-an-array.cpp @@ -0,0 +1,10 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + int findKthLargest(vector& nums, int k) { + nth_element(nums.begin(), next(nums.begin(), k - 1), nums.end(), greater()); + return *next(nums.begin(), k - 1); + } +}; From f99a27c0722e187c0cdeffb8ba10263461476e47 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 23 May 2015 20:50:11 +0800 Subject: [PATCH 270/345] Update kth-largest-element-in-an-array.cpp --- C++/kth-largest-element-in-an-array.cpp | 37 +++++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/C++/kth-largest-element-in-an-array.cpp b/C++/kth-largest-element-in-an-array.cpp index caabd1846..095b917e6 100644 --- a/C++/kth-largest-element-in-an-array.cpp +++ b/C++/kth-largest-element-in-an-array.cpp @@ -2,6 +2,43 @@ // Space: O(1) class Solution { +public: + int findKthLargest(vector& nums, int k) { + int left = 0, right = nums.size() - 1; + default_random_engine gen((random_device())()); + while (left <= right) { + // Generates a random int in [left, right]. + uniform_int_distribution dis(left, right); + int pivot_idx = dis(gen); + int new_pivot_idx = PartitionAroundPivot(left, right, pivot_idx, &nums); + if (new_pivot_idx == k - 1) { + return nums[new_pivot_idx]; + } else if (new_pivot_idx > k - 1) { + right = new_pivot_idx - 1; + } else { // new_pivot_idx < k - 1. + left = new_pivot_idx + 1; + } + } + } + + int PartitionAroundPivot(int left, int right, int pivot_idx, vector* nums) { + auto& nums_ref = *nums; + int pivot_value = nums_ref[pivot_idx]; + int new_pivot_idx = left; + swap(nums_ref[pivot_idx], nums_ref[right]); + for (int i = left; i < right; ++i) { + if (nums_ref[i] > pivot_value) { + swap(nums_ref[i], nums_ref[new_pivot_idx++]); + } + } + swap(nums_ref[right], nums_ref[new_pivot_idx]); + return new_pivot_idx; + } +}; + +// Time: O(n) +// Space: O(1) +class Solution2 { public: int findKthLargest(vector& nums, int k) { nth_element(nums.begin(), next(nums.begin(), k - 1), nums.end(), greater()); From 52a4756cba832da4b84b14ae8522710afe8d2072 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 23 May 2015 20:52:37 +0800 Subject: [PATCH 271/345] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 64e57766a..fedbb3550 100644 --- a/README.md +++ b/README.md @@ -84,6 +84,7 @@ Shell 169 | [Majority Element](https://oj.leetcode.com/problems/majority-element/) | [Python](./Python/majority-element.py) | _O(n)_ | _O(1)_ | Easy | 189 | [Rotate Array](https://oj.leetcode.com/problems/rotate-array/) | [Python](./Python/rotate-array.py) | _O(n)_ | _O(1)_ | Easy || 209 | [Minimum Size Subarray Sum](https://leetcode.com/problems/minimum-size-subarray-sum/) | [Python] (./Python/minimum-size-subarray-sum.py) | _O(n)_ | _O(1)_ | Medium || +215 | [Kth Largest Element in an Array](https://leetcode.com/problems/kth-largest-element-in-an-array/) | [C++] (./C++/kth-largest-element-in-an-array.cpp) | _O(n)_ | _O(1)_ | Medium | EPI| --- From b9ec186dd8419f01877db17b9e5d045de3f44e6f Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 23 May 2015 20:56:28 +0800 Subject: [PATCH 272/345] Update README.md --- README.md | 420 +++++++++++++++++++++++++++--------------------------- 1 file changed, 210 insertions(+), 210 deletions(-) diff --git a/README.md b/README.md index fedbb3550..db7d1b8a9 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ LeetCode ======== -Up to date (2015-05-23), there are `199` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://oj.leetcode.com/). +Up to date (2015-05-23), there are `199` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://leetcode.com/). The number of problems is increasing recently. Here is the classification of all `215` problems. For extra problems and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repo. @@ -50,10 +50,10 @@ Shell ##Bit Manipulation # | Problem | Solution | Time | Space | Difficulty | Tag | Notes -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- -136 | [Single Number](https://oj.leetcode.com/problems/single-number/) | [Python](./Python/single-number.py) | _O(n)_ | _O(1)_ | Medium || -137 | [Single Number II](https://oj.leetcode.com/problems/single-number-ii/) | [Python](./Python/single-number-ii.py) | _O(n)_ | _O(1)_ | Medium || -190 | [Reverse Bits](https://oj.leetcode.com/problems/reverse-bits/) | [Python](./Python/reverse-bits.py) | _O(n)_ | _O(1)_ | Easy || -191 |[Number of 1 Bits](https://oj.leetcode.com/problems/number-of-1-bits/) | [Python](./Python/number-of-1-bits.py) | _O(m)_ | _O(1)_ | Easy || +136 | [Single Number](https://leetcode.com/problems/single-number/) | [Python](./Python/single-number.py) | _O(n)_ | _O(1)_ | Medium || +137 | [Single Number II](https://leetcode.com/problems/single-number-ii/) | [Python](./Python/single-number-ii.py) | _O(n)_ | _O(1)_ | Medium || +190 | [Reverse Bits](https://leetcode.com/problems/reverse-bits/) | [Python](./Python/reverse-bits.py) | _O(n)_ | _O(1)_ | Easy || +191 |[Number of 1 Bits](https://leetcode.com/problems/number-of-1-bits/) | [Python](./Python/number-of-1-bits.py) | _O(m)_ | _O(1)_ | Easy || 201 | [Bitwise AND of Numbers Range](https://leetcode.com/problems/bitwise-and-of-numbers-range/) | [Python](./Python/bitwise-and-of-numbers-range.py) | _O(1)_ | _O(1)_ | Medium || --- @@ -62,27 +62,27 @@ Shell # | Problem | Solution | Time | Space | Difficulty | Tag | Notes -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- -15 | [3 Sum](https://oj.leetcode.com/problems/3sum/) | [Python](./Python/3sum.py) | _O(n^2)_ | _O(1)_ | Medium || -16 | [3 Sum Closest](https://oj.leetcode.com/problems/3sum-closest/) | [Python](./Python/3sum-closest.py)| _O(n^2)_ | _O(1)_ | Medium || -26 | [Remove Duplicates from Sorted Array](https://oj.leetcode.com/problems/remove-duplicates-from-sorted-array/)| [Python](./Python/remove-duplicates-from-sorted-array.py) | _O(n)_ | _O(1)_ | Easy || -27 | [Remove Element](https://oj.leetcode.com/problems/remove-element/) | [Python](./Python/remove-element.py) | _O(n)_ | _O(1)_ | Easy || -31 | [Next Permutation](https://oj.leetcode.com/problems/next-permutation/)| [Python](./Python/next-permutation.py) | _O(n)_ | _O(1)_ | Medium || Tricky -41 | [First Missing Positive](https://oj.leetcode.com/problems/first-missing-positive/)| [Python](./Python/first-missing-positive.py) | _O(n)_ | _O(1)_ | Hard || Tricky -48 | [Rotate Image](https://oj.leetcode.com/problems/rotate-image/) | [Python](./Python/rotate-image.py) | _O(n^2)_ | _O(1)_ | Medium || -54 | [Spiral Matrix](https://oj.leetcode.com/problems/spiral-matrix/) | [Python](./Python/spiral-matrix.py) | _O(m * n)_ | _O(1)_ | Medium || -59 | [Spiral Matrix II](https://oj.leetcode.com/problems/spiral-matrix-ii/) | [Python](./Python/spiral-matrix-ii.py) | _O(m * n)_ | _O(1)_ | Medium || -66 | [Plus One](https://oj.leetcode.com/problems/plus-one/) | [Python](./Python/plus-one.py) | _O(n)_ | _O(1)_ | Easy || -73 | [Set Matrix Zeroes](https://oj.leetcode.com/problems/set-matrix-zeroes/) | [Python](./Python/set-matrix-zeroes.py) | _O(m * n)_ | _O(1)_ | Medium || -80 | [Remove Duplicates from Sorted Array II](https://oj.leetcode.com/problems/remove-duplicates-from-sorted-array-ii/)| [Python](./Python/remove-duplicates-from-sorted-array-ii.py) | _O(n)_ | _O(1)_ | Medium || -118 | [Pascal's Triangle](https://oj.leetcode.com/problems/pascals-triangle/)| [Python](./Python/pascals-triangle.py) | _O(n^2)_ | _O(n)_ | Easy || -119 | [Pascal's Triangle II](https://oj.leetcode.com/problems/pascals-triangle-ii/)| [Python](./Python/pascals-triangle-ii.py) | _O(n^2)_ | _O(n)_ | Easy || -121 | [Best Time to Buy and Sell Stock](https://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock/)| [Python](./Python/best-time-to-buy-and-sell-stock.py) | _O(n)_ | _O(1)_ | Medium || -128 | [Longest Consecutive Sequence](https://oj.leetcode.com/problems/longest-consecutive-sequence/)| [Python](./Python/longest-consecutive-sequence.py) | _O(n)_ | _O(n)_ | Hard || Tricky -157 | [Read N Characters Given Read4](https://oj.leetcode.com/problems/read-n-characters-given-read4/) | [Python](./Python/read-n-characters-given-read4.py) | _O(n)_ | _O(1)_ | Easy |📖| -158 | [Read N Characters Given Read4 II - Call multiple times](https://oj.leetcode.com/problems/read-n-characters-given-read4-ii-call-multiple-times/) | [Python](./Python/read-n-characters-given-read4-ii-call-multiple-times.py) | _O(n)_ | _O(1)_ | Hard |📖| -163 | [Missing Ranges](https://oj.leetcode.com/problems/missing-ranges/)| [Python](./Python/missing-ranges.py) | _O(n)_ | _O(1)_ | Medium | 📖 | -169 | [Majority Element](https://oj.leetcode.com/problems/majority-element/) | [Python](./Python/majority-element.py) | _O(n)_ | _O(1)_ | Easy | -189 | [Rotate Array](https://oj.leetcode.com/problems/rotate-array/) | [Python](./Python/rotate-array.py) | _O(n)_ | _O(1)_ | Easy || +15 | [3 Sum](https://leetcode.com/problems/3sum/) | [Python](./Python/3sum.py) | _O(n^2)_ | _O(1)_ | Medium || +16 | [3 Sum Closest](https://leetcode.com/problems/3sum-closest/) | [Python](./Python/3sum-closest.py)| _O(n^2)_ | _O(1)_ | Medium || +26 | [Remove Duplicates from Sorted Array](https://leetcode.com/problems/remove-duplicates-from-sorted-array/)| [Python](./Python/remove-duplicates-from-sorted-array.py) | _O(n)_ | _O(1)_ | Easy || +27 | [Remove Element](https://leetcode.com/problems/remove-element/) | [Python](./Python/remove-element.py) | _O(n)_ | _O(1)_ | Easy || +31 | [Next Permutation](https://leetcode.com/problems/next-permutation/)| [Python](./Python/next-permutation.py) | _O(n)_ | _O(1)_ | Medium || Tricky +41 | [First Missing Positive](https://leetcode.com/problems/first-missing-positive/)| [Python](./Python/first-missing-positive.py) | _O(n)_ | _O(1)_ | Hard || Tricky +48 | [Rotate Image](https://leetcode.com/problems/rotate-image/) | [Python](./Python/rotate-image.py) | _O(n^2)_ | _O(1)_ | Medium || +54 | [Spiral Matrix](https://leetcode.com/problems/spiral-matrix/) | [Python](./Python/spiral-matrix.py) | _O(m * n)_ | _O(1)_ | Medium || +59 | [Spiral Matrix II](https://leetcode.com/problems/spiral-matrix-ii/) | [Python](./Python/spiral-matrix-ii.py) | _O(m * n)_ | _O(1)_ | Medium || +66 | [Plus One](https://leetcode.com/problems/plus-one/) | [Python](./Python/plus-one.py) | _O(n)_ | _O(1)_ | Easy || +73 | [Set Matrix Zeroes](https://leetcode.com/problems/set-matrix-zeroes/) | [Python](./Python/set-matrix-zeroes.py) | _O(m * n)_ | _O(1)_ | Medium || +80 | [Remove Duplicates from Sorted Array II](https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/)| [Python](./Python/remove-duplicates-from-sorted-array-ii.py) | _O(n)_ | _O(1)_ | Medium || +118 | [Pascal's Triangle](https://leetcode.com/problems/pascals-triangle/)| [Python](./Python/pascals-triangle.py) | _O(n^2)_ | _O(n)_ | Easy || +119 | [Pascal's Triangle II](https://leetcode.com/problems/pascals-triangle-ii/)| [Python](./Python/pascals-triangle-ii.py) | _O(n^2)_ | _O(n)_ | Easy || +121 | [Best Time to Buy and Sell Stock](https://leetcode.com/problems/best-time-to-buy-and-sell-stock/)| [Python](./Python/best-time-to-buy-and-sell-stock.py) | _O(n)_ | _O(1)_ | Medium || +128 | [Longest Consecutive Sequence](https://leetcode.com/problems/longest-consecutive-sequence/)| [Python](./Python/longest-consecutive-sequence.py) | _O(n)_ | _O(n)_ | Hard || Tricky +157 | [Read N Characters Given Read4](https://leetcode.com/problems/read-n-characters-given-read4/) | [Python](./Python/read-n-characters-given-read4.py) | _O(n)_ | _O(1)_ | Easy |📖| +158 | [Read N Characters Given Read4 II - Call multiple times](https://leetcode.com/problems/read-n-characters-given-read4-ii-call-multiple-times/) | [Python](./Python/read-n-characters-given-read4-ii-call-multiple-times.py) | _O(n)_ | _O(1)_ | Hard |📖| +163 | [Missing Ranges](https://leetcode.com/problems/missing-ranges/)| [Python](./Python/missing-ranges.py) | _O(n)_ | _O(1)_ | Medium | 📖 | +169 | [Majority Element](https://leetcode.com/problems/majority-element/) | [Python](./Python/majority-element.py) | _O(n)_ | _O(1)_ | Easy | +189 | [Rotate Array](https://leetcode.com/problems/rotate-array/) | [Python](./Python/rotate-array.py) | _O(n)_ | _O(1)_ | Easy || 209 | [Minimum Size Subarray Sum](https://leetcode.com/problems/minimum-size-subarray-sum/) | [Python] (./Python/minimum-size-subarray-sum.py) | _O(n)_ | _O(1)_ | Medium || 215 | [Kth Largest Element in an Array](https://leetcode.com/problems/kth-largest-element-in-an-array/) | [C++] (./C++/kth-largest-element-in-an-array.cpp) | _O(n)_ | _O(1)_ | Medium | EPI| @@ -91,227 +91,227 @@ Shell ##String # | Problem | Solution | Time | Space | Difficulty | Tag | Notes -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- -5| [Longest Palindromic Substring](https://oj.leetcode.com/problems/longest-palindromic-substring/) | [Python](./Python/longest-palindromic-substring.py) | _O(n)_ | _O(n)_ | Medium || `Manacher's Algorithm` -6| [ZigZag Conversion](https://oj.leetcode.com/problems/zigzag-conversion/) | [Python](./Python/zigzag-conversion.py) | _O(n)_ | _O(1)_ | Easy || -8| [String to Integer (atoi)](https://oj.leetcode.com/problems/string-to-integer-atoi/) | [Python](./Python/string-to-integer-atoi.py) | _O(n)_ | _O(1)_ | Easy || -14| [Longest Common Prefix](https://oj.leetcode.com/problems/longest-common-prefix/) | [Python](./Python/longest-common-prefix.py) | _O(n1 + n2 + ...)_ | _O(1)_ | Easy || -28| [Implement strStr()](https://oj.leetcode.com/problems/implement-strstr/) | [Python](./Python/implement-strstr.py) | _O(n + m)_ | _O(m)_ | Easy || `KMP Algorithm` -38| [Count and Say](https://oj.leetcode.com/problems/compare-version-numbers/) | [Python](./Python/compare-version-numbers.py)| _O(n * 2^n)_ | _O(2^n)_ | Easy || -43| [Multiply Strings](https://oj.leetcode.com/problems/multiply-strings/) | [Python](./Python/multiply-strings.py) | _O(m * n)_ | _O(m + n)_ | Medium || -58| [Length of Last Word](https://oj.leetcode.com/problems/length-of-last-word/) | [Python](./Python/length-of-last-word.py) | _O(n)_ | _O(1)_ | Easy || -67| [Add Binary](https://oj.leetcode.com/problems/add-binary/) | [Python](./Python/add-binary.py) | _O(n)_ | _O(1)_ | Easy || -68| [Text Justification](https://oj.leetcode.com/problems/text-justification/) | [Python](./Python/text-justification.py) | _O(n)_ | _O(1)_ | Hard || -125| [Valid Palindrome](https://oj.leetcode.com/problems/valid-palindrome/) | [Python](./Python/valid-palindrome.py) | _O(n)_ | _O(1)_ | Easy || -151| [Reverse Words in a String](https://oj.leetcode.com/problems/reverse-words-in-a-string/) | [Python](./Python/reverse-words-in-a-string.py) | _O(n)_ | _O(n)_ | Medium || -161| [One Edit Distance](https://oj.leetcode.com/problems/one-edit-distance/) | [Python](./Python/one-edit-distance.py) | _O(m + n)_ | _O(1)_ | Medium |📖| -165| [Compare Version Numbers](https://oj.leetcode.com/problems/count-and-say/) | [Python](./Python/count-and-say.py) | _O(n)_ | _O(1)_ | Easy || -186| [Reverse Words in a String II](https://oj.leetcode.com/problems/reverse-words-in-a-string-ii/) | [Python](./Python/reverse-words-in-a-string-ii.py) | _O(n)_ | _O(1)_ | Medium | 📖 | -205| [Isomorphic Strings](https://oj.leetcode.com/problems/isomorphic-strings/) | [Python](./Python/isomorphic-strings.py) | _O(n)_ | _O(1)_ | Easy || -214| [Shortest Palindromic Substring](https://oj.leetcode.com/problems/shortest-palindrome/) | [C++](./C++/shortest-palindrome.cpp) | _O(n)_ | _O(n)_ | Hard || `Manacher's Algorithm` +5| [Longest Palindromic Substring](https://leetcode.com/problems/longest-palindromic-substring/) | [Python](./Python/longest-palindromic-substring.py) | _O(n)_ | _O(n)_ | Medium || `Manacher's Algorithm` +6| [ZigZag Conversion](https://leetcode.com/problems/zigzag-conversion/) | [Python](./Python/zigzag-conversion.py) | _O(n)_ | _O(1)_ | Easy || +8| [String to Integer (atoi)](https://leetcode.com/problems/string-to-integer-atoi/) | [Python](./Python/string-to-integer-atoi.py) | _O(n)_ | _O(1)_ | Easy || +14| [Longest Common Prefix](https://leetcode.com/problems/longest-common-prefix/) | [Python](./Python/longest-common-prefix.py) | _O(n1 + n2 + ...)_ | _O(1)_ | Easy || +28| [Implement strStr()](https://leetcode.com/problems/implement-strstr/) | [Python](./Python/implement-strstr.py) | _O(n + m)_ | _O(m)_ | Easy || `KMP Algorithm` +38| [Count and Say](https://leetcode.com/problems/compare-version-numbers/) | [Python](./Python/compare-version-numbers.py)| _O(n * 2^n)_ | _O(2^n)_ | Easy || +43| [Multiply Strings](https://leetcode.com/problems/multiply-strings/) | [Python](./Python/multiply-strings.py) | _O(m * n)_ | _O(m + n)_ | Medium || +58| [Length of Last Word](https://leetcode.com/problems/length-of-last-word/) | [Python](./Python/length-of-last-word.py) | _O(n)_ | _O(1)_ | Easy || +67| [Add Binary](https://leetcode.com/problems/add-binary/) | [Python](./Python/add-binary.py) | _O(n)_ | _O(1)_ | Easy || +68| [Text Justification](https://leetcode.com/problems/text-justification/) | [Python](./Python/text-justification.py) | _O(n)_ | _O(1)_ | Hard || +125| [Valid Palindrome](https://leetcode.com/problems/valid-palindrome/) | [Python](./Python/valid-palindrome.py) | _O(n)_ | _O(1)_ | Easy || +151| [Reverse Words in a String](https://leetcode.com/problems/reverse-words-in-a-string/) | [Python](./Python/reverse-words-in-a-string.py) | _O(n)_ | _O(n)_ | Medium || +161| [One Edit Distance](https://leetcode.com/problems/one-edit-distance/) | [Python](./Python/one-edit-distance.py) | _O(m + n)_ | _O(1)_ | Medium |📖| +165| [Compare Version Numbers](https://leetcode.com/problems/count-and-say/) | [Python](./Python/count-and-say.py) | _O(n)_ | _O(1)_ | Easy || +186| [Reverse Words in a String II](https://leetcode.com/problems/reverse-words-in-a-string-ii/) | [Python](./Python/reverse-words-in-a-string-ii.py) | _O(n)_ | _O(1)_ | Medium | 📖 | +205| [Isomorphic Strings](https://leetcode.com/problems/isomorphic-strings/) | [Python](./Python/isomorphic-strings.py) | _O(n)_ | _O(1)_ | Easy || +214| [Shortest Palindrome](https://leetcode.com/problems/shortest-palindrome/) | [C++](./C++/shortest-palindrome.cpp) | _O(n)_ | _O(n)_ | Hard || `Manacher's Algorithm` --- ##Linked List # | Problem | Solution | Time | Space | Difficulty | Tag | Notes -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- -2| [Add Two Numbers](https://oj.leetcode.com/problems/add-two-numbers/) | [Python](./Python/add-two-numbers.py) | _O(n)_ | _O(1)_ | Medium || -24| [Swap Nodes in Pairs](https://oj.leetcode.com/problems/swap-nodes-in-pairs/)| [Python](./Python/swap-nodes-in-pairs.py) | _O(n)_ | _O(1)_ | Medium || -25| [Reverse Nodes in k-Group](https://oj.leetcode.com/problems/reverse-nodes-in-k-group/)| [Python](./Python/reverse-nodes-in-k-group.py) | _O(n)_ | _O(1)_ | Hard || -61| [Rotate List](https://oj.leetcode.com/problems/rotate-list/)| [Python](./Python/rotate-list.py) | _O(n)_ | _O(1)_ | Medium || -82| [Remove Duplicates from Sorted List II](https://oj.leetcode.com/problems/remove-duplicates-from-sorted-list-ii/)| [Python](./Python/remove-duplicates-from-sorted-list-ii.py) | _O(n)_ | _O(1)_ | Medium || -83| [Remove Duplicates from Sorted List](https://oj.leetcode.com/problems/remove-duplicates-from-sorted-list/)| [Python](./Python/remove-duplicates-from-sorted-list.py) | _O(n)_ | _O(1)_ | Easy || -92| [Reverse Linked List II](https://oj.leetcode.com/problems/reverse-linked-list-ii/)| [Python](./Python/reverse-linked-list-ii.py) | _O(n)_ | _O(1)_ | Medium || -138| [Copy List with Random Pointer](https://oj.leetcode.com/problems/copy-list-with-random-pointer/) | [Python](./Python/copy-list-with-random-pointer.py) | _O(n)_ | _O(1)_ | Hard || -160| [Intersection of Two Linked Lists](https://oj.leetcode.com/problems/intersection-of-two-linked-lists/)| [Python](./Python/intersection-of-two-linked-lists.py) | _O(m + n)_ | _O(1)_ | Easy || -203| [Remove Linked List Elements](https://oj.leetcode.com/problems/remove-linked-list-elements/)| [Python](./Python/remove-linked-list-elements.py) | _O(n)_ | _O(1)_ | Easy || -206| [Reverse Linked List](https://oj.leetcode.com/problems/reverse-linked-list/)| [Python](./Python/reverse-linked-list.py) | _O(n)_ | _O(1)_ | Easy || +2| [Add Two Numbers](https://leetcode.com/problems/add-two-numbers/) | [Python](./Python/add-two-numbers.py) | _O(n)_ | _O(1)_ | Medium || +24| [Swap Nodes in Pairs](https://leetcode.com/problems/swap-nodes-in-pairs/)| [Python](./Python/swap-nodes-in-pairs.py) | _O(n)_ | _O(1)_ | Medium || +25| [Reverse Nodes in k-Group](https://leetcode.com/problems/reverse-nodes-in-k-group/)| [Python](./Python/reverse-nodes-in-k-group.py) | _O(n)_ | _O(1)_ | Hard || +61| [Rotate List](https://leetcode.com/problems/rotate-list/)| [Python](./Python/rotate-list.py) | _O(n)_ | _O(1)_ | Medium || +82| [Remove Duplicates from Sorted List II](https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/)| [Python](./Python/remove-duplicates-from-sorted-list-ii.py) | _O(n)_ | _O(1)_ | Medium || +83| [Remove Duplicates from Sorted List](https://leetcode.com/problems/remove-duplicates-from-sorted-list/)| [Python](./Python/remove-duplicates-from-sorted-list.py) | _O(n)_ | _O(1)_ | Easy || +92| [Reverse Linked List II](https://leetcode.com/problems/reverse-linked-list-ii/)| [Python](./Python/reverse-linked-list-ii.py) | _O(n)_ | _O(1)_ | Medium || +138| [Copy List with Random Pointer](https://leetcode.com/problems/copy-list-with-random-pointer/) | [Python](./Python/copy-list-with-random-pointer.py) | _O(n)_ | _O(1)_ | Hard || +160| [Intersection of Two Linked Lists](https://leetcode.com/problems/intersection-of-two-linked-lists/)| [Python](./Python/intersection-of-two-linked-lists.py) | _O(m + n)_ | _O(1)_ | Easy || +203| [Remove Linked List Elements](https://leetcode.com/problems/remove-linked-list-elements/)| [Python](./Python/remove-linked-list-elements.py) | _O(n)_ | _O(1)_ | Easy || +206| [Reverse Linked List](https://leetcode.com/problems/reverse-linked-list/)| [Python](./Python/reverse-linked-list.py) | _O(n)_ | _O(1)_ | Easy || --- ##Stack # | Problem | Solution | Time | Space | Difficulty | Tag | Notes -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- -20| [Valid Parentheses](https://oj.leetcode.com/problems/valid-parentheses/)| [Python](./Python/valid-parentheses.py) | _O(n)_ | _O(n)_ | Easy || -32| [Longest Valid Parentheses](https://oj.leetcode.com/problems/longest-valid-parentheses/)| [Python](./Python/longest-valid-parentheses.py) | _O(n)_ | _O(1)_ | Hard || -71| [Simplify Path](https://oj.leetcode.com/problems/simplify-path/)| [Python](./Python/simplify-path.py) | _O(n)_ | _O(n)_ | Medium || -101| [Symmetric Tree](https://oj.leetcode.com/problems/symmetric-tree/)| [Python](./Python/symmetric-tree.py) | _O(n)_ | _O(h)_ | Easy || -150| [Evaluate Reverse Polish Notation](https://oj.leetcode.com/problems/evaluate-reverse-polish-notation/)| [Python](./Python/evaluate-reverse-polish-notation.py)| _O(n)_| _O(n)_| Medium || -155| [Min Stack](https://oj.leetcode.com/problems/min-stack/) | [Python](./Python/min-stack.py) | _O(n)_ | _O(1)_ | Easy || -173| [Binary Search Tree Iterator](https://oj.leetcode.com/problems/binary-search-tree-iterator/) | [Python](./Python/binary-search-tree-iterator.py) | _O(1)_| _O(h)_| Medium || +20| [Valid Parentheses](https://leetcode.com/problems/valid-parentheses/)| [Python](./Python/valid-parentheses.py) | _O(n)_ | _O(n)_ | Easy || +32| [Longest Valid Parentheses](https://leetcode.com/problems/longest-valid-parentheses/)| [Python](./Python/longest-valid-parentheses.py) | _O(n)_ | _O(1)_ | Hard || +71| [Simplify Path](https://leetcode.com/problems/simplify-path/)| [Python](./Python/simplify-path.py) | _O(n)_ | _O(n)_ | Medium || +101| [Symmetric Tree](https://leetcode.com/problems/symmetric-tree/)| [Python](./Python/symmetric-tree.py) | _O(n)_ | _O(h)_ | Easy || +150| [Evaluate Reverse Polish Notation](https://leetcode.com/problems/evaluate-reverse-polish-notation/)| [Python](./Python/evaluate-reverse-polish-notation.py)| _O(n)_| _O(n)_| Medium || +155| [Min Stack](https://leetcode.com/problems/min-stack/) | [Python](./Python/min-stack.py) | _O(n)_ | _O(1)_ | Easy || +173| [Binary Search Tree Iterator](https://leetcode.com/problems/binary-search-tree-iterator/) | [Python](./Python/binary-search-tree-iterator.py) | _O(1)_| _O(h)_| Medium || --- ##Heap # | Problem | Solution | Time | Space | Difficulty | Tag | Notes -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- -23| [Merge k Sorted Lists](https://oj.leetcode.com/problems/merge-k-sorted-lists/) | [Python](./Python/merge-k-sorted-lists.py) | _O(nlogk)_| _O(k)_| Hard || +23| [Merge k Sorted Lists](https://leetcode.com/problems/merge-k-sorted-lists/) | [Python](./Python/merge-k-sorted-lists.py) | _O(nlogk)_| _O(k)_| Hard || --- ##Tree # | Problem | Solution | Time | Space | Difficulty | Tag | Notes -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- -94 | [Binary Tree Inorder Traversal](https://oj.leetcode.com/problems/binary-tree-inorder-traversal/) | [Python](./Python/binary-tree-inorder-traversal.py) | _O(n)_| _O(1)_| Medium || `Morris Traversal` | -99 | [Recover Binary Search Tree](https://oj.leetcode.com/problems/recover-binary-search-tree/) | [Python](./Python/recover-binary-search-tree.py) | _O(n)_| _O(1)_| Hard || `Morris Traversal` -144 | [Binary Tree Preorder Traversal](https://oj.leetcode.com/problems/binary-tree-preorder-traversal/) | [Python](./Python/binary-tree-preorder-traversal.py) | _O(n)_| _O(1)_| Medium || `Morris Traversal` -145 | [Binary Tree Postorder Traversal](https://oj.leetcode.com/problems/binary-tree-postorder-traversal/) | [Python](./Python/binary-tree-postorder-traversal.py) | _O(n)_| _O(1)_| Hard || `Morris Traversal` +94 | [Binary Tree Inorder Traversal](https://leetcode.com/problems/binary-tree-inorder-traversal/) | [Python](./Python/binary-tree-inorder-traversal.py) | _O(n)_| _O(1)_| Medium || `Morris Traversal` | +99 | [Recover Binary Search Tree](https://leetcode.com/problems/recover-binary-search-tree/) | [Python](./Python/recover-binary-search-tree.py) | _O(n)_| _O(1)_| Hard || `Morris Traversal` +144 | [Binary Tree Preorder Traversal](https://leetcode.com/problems/binary-tree-preorder-traversal/) | [Python](./Python/binary-tree-preorder-traversal.py) | _O(n)_| _O(1)_| Medium || `Morris Traversal` +145 | [Binary Tree Postorder Traversal](https://leetcode.com/problems/binary-tree-postorder-traversal/) | [Python](./Python/binary-tree-postorder-traversal.py) | _O(n)_| _O(1)_| Hard || `Morris Traversal` 208 | [Implement Trie (Prefix Tree)](https://leetcode.com/problems/implement-trie-prefix-tree/) | [Python](./Python/implement-trie-prefix-tree.py) | _O(n)_ | _O(1)_ | Medium || Trie 211 | [Add and Search Word - Data structure design ](https://leetcode.com/problems/add-and-search-word-data-structure-design/) | [C++](./C++/add-and-search-word-data-structure-design.cpp) [Python](./Python/add-and-search-word-data-structure-design.py) | _O(min(n, h))_ | _O(min(n, h))_ | Medium || Trie, DFS -212| [Word Search II](https://oj.leetcode.com/problems/word-search-ii/) | [C++](./C++/word-search-ii.cpp) [Python](./Python/word-search-ii.py) | _O(m * n * l)_ | _O(l)_ | Hard | LintCode | Trie, DFS +212| [Word Search II](https://leetcode.com/problems/word-search-ii/) | [C++](./C++/word-search-ii.cpp) [Python](./Python/word-search-ii.py) | _O(m * n * l)_ | _O(l)_ | Hard | LintCode | Trie, DFS --- ##Hash Table # | Problem | Solution | Time | Space | Difficulty | Tag | Notes -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- -1| [Two Sum](https://oj.leetcode.com/problems/two-sum/) | [Python](./Python/two-sum.py) | _O(n)_ | _O(n)_ | Medium || -3| [Longest Substring Without Repeating Characters](https://oj.leetcode.com/problems/longest-substring-without-repeating-characters/) | [Python](./Python/longest-substring-without-repeating-characters.py) | _O(n)_ | _O(1)_ | Medium || -18| [4 Sum](https://oj.leetcode.com/problems/4sum/) |[Python](./Python/4sum.py) | _O(n^2 * p)_ | _O(n^2 * p)_ | Medium || -30| [Substring with Concatenation of All Words](https://oj.leetcode.com/problems/substring-with-concatenation-of-all-words/) | [Python](./Python/substring-with-concatenation-of-all-words.py) | _O(m * n * k)_ | _O(n * k)_ | Hard || -36| [Valid Sudoku](https://oj.leetcode.com/problems/valid-sudoku/) | [Python](./Python/valid-sudoku.py) | _O(n^2)_ | _O(n)_ | Easy || -49| [Anagrams](https://oj.leetcode.com/problems/anagrams/) | [Python](./Python/anagrams.py) | _O(n)_ | _O(n)_ | Medium || -76| [Minimum Window Substring](https://oj.leetcode.com/problems/minimum-window-substring/) | [Python](./Python/minimum-window-substring.py) | _O(n)_ | _O(k)_ | Hard || -149| [Max Points on a Line](https://oj.leetcode.com/problems/max-points-on-a-line/) | [Python](./Python/max-points-on-a-line.py) | _O(n^2)_ | _O(n)_ | Hard || -159| [Longest Substring with At Most Two Distinct Characters](https://oj.leetcode.com/problems/longest-substring-with-at-most-two-distinct-characters/)| [Python](./Python/longest-substring-with-at-most-two-distinct-characters.py) | _O(n^2)_ | _O(1)_ | Hard |📖| -170| [Two Sum III - Data structure design](https://oj.leetcode.com/problems/two-sum-iii-data-structure-design/) | [Python](./Python/two-sum-iii-data-structure-design.py) | _O(n)_ | _O(n)_ | Easy | 📖 | -187| [Repeated DNA Sequences](https://oj.leetcode.com/problems/repeated-dna-sequences/) | [Python](./Python/repeated-dna-sequences.py) | _O(n)_ | _O(n)_ | Medium || -202| [Happy Number](https://oj.leetcode.com/problems/happy-number/) | [Python](./Python/happy-number.py) | _O(k)_ | _O(k)_ | Easy || -204| [Count Primes](https://oj.leetcode.com/problems/count-primes/) | [Python](./Python/count-primes.py) | _O(n)_ | _O(n)_ | Easy || +1| [Two Sum](https://leetcode.com/problems/two-sum/) | [Python](./Python/two-sum.py) | _O(n)_ | _O(n)_ | Medium || +3| [Longest Substring Without Repeating Characters](https://leetcode.com/problems/longest-substring-without-repeating-characters/) | [Python](./Python/longest-substring-without-repeating-characters.py) | _O(n)_ | _O(1)_ | Medium || +18| [4 Sum](https://leetcode.com/problems/4sum/) |[Python](./Python/4sum.py) | _O(n^2 * p)_ | _O(n^2 * p)_ | Medium || +30| [Substring with Concatenation of All Words](https://leetcode.com/problems/substring-with-concatenation-of-all-words/) | [Python](./Python/substring-with-concatenation-of-all-words.py) | _O(m * n * k)_ | _O(n * k)_ | Hard || +36| [Valid Sudoku](https://leetcode.com/problems/valid-sudoku/) | [Python](./Python/valid-sudoku.py) | _O(n^2)_ | _O(n)_ | Easy || +49| [Anagrams](https://leetcode.com/problems/anagrams/) | [Python](./Python/anagrams.py) | _O(n)_ | _O(n)_ | Medium || +76| [Minimum Window Substring](https://leetcode.com/problems/minimum-window-substring/) | [Python](./Python/minimum-window-substring.py) | _O(n)_ | _O(k)_ | Hard || +149| [Max Points on a Line](https://leetcode.com/problems/max-points-on-a-line/) | [Python](./Python/max-points-on-a-line.py) | _O(n^2)_ | _O(n)_ | Hard || +159| [Longest Substring with At Most Two Distinct Characters](https://leetcode.com/problems/longest-substring-with-at-most-two-distinct-characters/)| [Python](./Python/longest-substring-with-at-most-two-distinct-characters.py) | _O(n^2)_ | _O(1)_ | Hard |📖| +170| [Two Sum III - Data structure design](https://leetcode.com/problems/two-sum-iii-data-structure-design/) | [Python](./Python/two-sum-iii-data-structure-design.py) | _O(n)_ | _O(n)_ | Easy | 📖 | +187| [Repeated DNA Sequences](https://leetcode.com/problems/repeated-dna-sequences/) | [Python](./Python/repeated-dna-sequences.py) | _O(n)_ | _O(n)_ | Medium || +202| [Happy Number](https://leetcode.com/problems/happy-number/) | [Python](./Python/happy-number.py) | _O(k)_ | _O(k)_ | Easy || +204| [Count Primes](https://leetcode.com/problems/count-primes/) | [Python](./Python/count-primes.py) | _O(n)_ | _O(n)_ | Easy || --- ##Data Structure # | Problem | Solution | Time | Space | Difficulty | Tag | Notes -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- -146| [LRU Cache](https://oj.leetcode.com/problems/lru-cache/) | [Python](./Python/lru-cache.py) | _O(1)_ | _O(n)_ | Hard || +146| [LRU Cache](https://leetcode.com/problems/lru-cache/) | [Python](./Python/lru-cache.py) | _O(1)_ | _O(n)_ | Hard || --- ##Math # | Problem | Solution | Time | Space | Difficulty | Tag | Notes -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- -7| [Reverse Integer](https://oj.leetcode.com/problems/reverse-integer/) | [Python](./Python/reverse-integer.py) | _O(logn)_ | _O(1)_ | Easy || -9| [Palindrome Number](https://oj.leetcode.com/problems/palindrome-number/) | [Python](./Python/palindrome-number.py) | _O(1)_ | _O(1)_ | Easy || -12| [Integer to Roman](https://oj.leetcode.com/problems/integer-to-roman/) | [Python](./Python/integer-to-roman.py) | _O(n)_ | _O(1)_ | Medium || -13| [Roman to Integer](https://oj.leetcode.com/problems/roman-to-integer/) | [Python](./Python/roman-to-integer.py) | _O(n)_ | _O(1)_ | Easy || -29| [Divide Two Integers](https://oj.leetcode.com/problems/divide-two-integers/) | [Python](./Python/divide-two-integers.py) | _O(logn)_ | _O(1)_ | Medium || -60| [Permutation Sequence](https://oj.leetcode.com/problems/permutation-sequence/) | [Python](./Python/permutation-sequence.py) | _O(n^2)_ | _O(n)_ | Medium || `Cantor Ordering` -65| [Valid Number](https://oj.leetcode.com/problems/valid-number/) | [Python](./Python/valid-number.py) | _O(n)_ | _O(1)_ | Hard || `Automata` -89| [Gray Code](https://oj.leetcode.com/problems/gray-code/) | [Python](./Python/gray-code.py) | _O(2^n)_ | _O(1)_ | Medium || -166| [Fraction to Recurring Decimal](https://oj.leetcode.com/problems/fraction-to-recurring-decimal/) | [Python](./Python/fraction-to-recurring-decimal.py) | _O(logn)_ | _O(1)_ | Medium || -168| [Excel Sheet Column Title](https://oj.leetcode.com/problems/excel-sheet-column-title/) | [Python](./Python/excel-sheet-column-title.py) | _O(logn)_ | _O(1)_ | Easy || -171| [Excel Sheet Column Number](https://oj.leetcode.com/problems/excel-sheet-column-number/) | [Python](./Python/excel-sheet-column-number.py) | _O(n)_ | _O(1)_ | Easy || -172| [Factorial Trailing Zeroes](https://oj.leetcode.com/problems/factorial-trailing-zeroes/) | [Python](./Python/factorial-trailing-zeroes.py) | _O(logn)_ | _O(1)_ | Easy || +7| [Reverse Integer](https://leetcode.com/problems/reverse-integer/) | [Python](./Python/reverse-integer.py) | _O(logn)_ | _O(1)_ | Easy || +9| [Palindrome Number](https://leetcode.com/problems/palindrome-number/) | [Python](./Python/palindrome-number.py) | _O(1)_ | _O(1)_ | Easy || +12| [Integer to Roman](https://leetcode.com/problems/integer-to-roman/) | [Python](./Python/integer-to-roman.py) | _O(n)_ | _O(1)_ | Medium || +13| [Roman to Integer](https://leetcode.com/problems/roman-to-integer/) | [Python](./Python/roman-to-integer.py) | _O(n)_ | _O(1)_ | Easy || +29| [Divide Two Integers](https://leetcode.com/problems/divide-two-integers/) | [Python](./Python/divide-two-integers.py) | _O(logn)_ | _O(1)_ | Medium || +60| [Permutation Sequence](https://leetcode.com/problems/permutation-sequence/) | [Python](./Python/permutation-sequence.py) | _O(n^2)_ | _O(n)_ | Medium || `Cantor Ordering` +65| [Valid Number](https://leetcode.com/problems/valid-number/) | [Python](./Python/valid-number.py) | _O(n)_ | _O(1)_ | Hard || `Automata` +89| [Gray Code](https://leetcode.com/problems/gray-code/) | [Python](./Python/gray-code.py) | _O(2^n)_ | _O(1)_ | Medium || +166| [Fraction to Recurring Decimal](https://leetcode.com/problems/fraction-to-recurring-decimal/) | [Python](./Python/fraction-to-recurring-decimal.py) | _O(logn)_ | _O(1)_ | Medium || +168| [Excel Sheet Column Title](https://leetcode.com/problems/excel-sheet-column-title/) | [Python](./Python/excel-sheet-column-title.py) | _O(logn)_ | _O(1)_ | Easy || +171| [Excel Sheet Column Number](https://leetcode.com/problems/excel-sheet-column-number/) | [Python](./Python/excel-sheet-column-number.py) | _O(n)_ | _O(1)_ | Easy || +172| [Factorial Trailing Zeroes](https://leetcode.com/problems/factorial-trailing-zeroes/) | [Python](./Python/factorial-trailing-zeroes.py) | _O(logn)_ | _O(1)_ | Easy || --- ##Sort # | Problem | Solution | Time | Space | Difficulty | Tag | Notes -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- -21| [Merge Two Sorted Lists](https://oj.leetcode.com/problems/merge-two-sorted-lists/)| [Python](./Python/merge-two-sorted-lists.py) | _O(n)_ | _O(1)_ | Easy || -56| [Merge Intervals](https://oj.leetcode.com/problems/merge-intervals/)| [Python](./Python/merge-intervals.py) | _O(nlogn)_ | _O(1)_ | Hard || -57| [Insert Interval](https://oj.leetcode.com/problems/insert-interval/)| [Python](./Python/insert-interval.py) | _O(n)_ | _O(1)_ | Hard || -75| [Sort Colors](https://oj.leetcode.com/problems/sort-colors/) | [Python](./Python/sort-colors.py) | _O(n)_ | _O(1)_ | Medium || -88| [Merge Sorted Array](https://oj.leetcode.com/problems/merge-sorted-array/)| [Python](./Python/merge-sorted-array.py) | _O(n)_ | _O(1)_ | Easy || -147| [Insertion Sort List](https://oj.leetcode.com/problems/insertion-sort-list/)|[Python](./Python/insertion-sort-list.py) | _O(n^2)_ | _O(1)_ | Medium || -148| [Sort List](https://oj.leetcode.com/problems/sort-list/) | [Python](./Python/sort-list.py) | _O(nlogn)_ | _O(logn)_ | Medium || -164| [Maximum Gap](https://oj.leetcode.com/problems/maximum-gap/) | [Python](./Python/maximum-gap.py)| _O(n)_ | _O(n)_ | Hard || Tricky -179| [Largest Number](https://oj.leetcode.com/problems/largest-number/) | [Python](./Python/largest-number.py) | _O(nlogn)_ | _O(1)_ | Medium || +21| [Merge Two Sorted Lists](https://leetcode.com/problems/merge-two-sorted-lists/)| [Python](./Python/merge-two-sorted-lists.py) | _O(n)_ | _O(1)_ | Easy || +56| [Merge Intervals](https://leetcode.com/problems/merge-intervals/)| [Python](./Python/merge-intervals.py) | _O(nlogn)_ | _O(1)_ | Hard || +57| [Insert Interval](https://leetcode.com/problems/insert-interval/)| [Python](./Python/insert-interval.py) | _O(n)_ | _O(1)_ | Hard || +75| [Sort Colors](https://leetcode.com/problems/sort-colors/) | [Python](./Python/sort-colors.py) | _O(n)_ | _O(1)_ | Medium || +88| [Merge Sorted Array](https://leetcode.com/problems/merge-sorted-array/)| [Python](./Python/merge-sorted-array.py) | _O(n)_ | _O(1)_ | Easy || +147| [Insertion Sort List](https://leetcode.com/problems/insertion-sort-list/)|[Python](./Python/insertion-sort-list.py) | _O(n^2)_ | _O(1)_ | Medium || +148| [Sort List](https://leetcode.com/problems/sort-list/) | [Python](./Python/sort-list.py) | _O(nlogn)_ | _O(logn)_ | Medium || +164| [Maximum Gap](https://leetcode.com/problems/maximum-gap/) | [Python](./Python/maximum-gap.py)| _O(n)_ | _O(n)_ | Hard || Tricky +179| [Largest Number](https://leetcode.com/problems/largest-number/) | [Python](./Python/largest-number.py) | _O(nlogn)_ | _O(1)_ | Medium || --- ##Two Pointer # | Problem | Solution | Time | Space | Difficulty | Tag | Notes -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- -19| [Remove Nth Node From End of List](https://oj.leetcode.com/problems/remove-nth-node-from-end-of-list/)| [Python](./Python/remove-nth-node-from-end-of-list.py) | _O(n)_ | _O(1)_ | Easy || -86| [Partition List](https://oj.leetcode.com/problems/partition-list/)| [Python](./Python/partition-list.py) | _O(n)_ | _O(1)_ | Medium || -141| [Linked List Cycle](https://oj.leetcode.com/problems/linked-list-cycle/)| [Python](./Python/linked-list-cycle.py) | _O(n)_ | _O(1)_ | Medium || -142| [Linked List Cycle II](https://oj.leetcode.com/problems/linked-list-cycle-ii/)| [Python](./Python/linked-list-cycle-ii.py) | _O(n)_ | _O(1)_ | Medium || -143| [Reorder List](https://oj.leetcode.com/problems/reorder-list/)| [Python](./Python/reorder-list.py) | _O(n)_ | _O(1)_ | Medium || -167| [Two Sum II - Input array is sorted](https://oj.leetcode.com/problems/two-sum-ii-input-array-is-sorted/) | [Python](./Python/two-sum-ii-input-array-is-sorted.py) | _O(n)_ | _O(1)_ | Medium | 📖 | +19| [Remove Nth Node From End of List](https://leetcode.com/problems/remove-nth-node-from-end-of-list/)| [Python](./Python/remove-nth-node-from-end-of-list.py) | _O(n)_ | _O(1)_ | Easy || +86| [Partition List](https://leetcode.com/problems/partition-list/)| [Python](./Python/partition-list.py) | _O(n)_ | _O(1)_ | Medium || +141| [Linked List Cycle](https://leetcode.com/problems/linked-list-cycle/)| [Python](./Python/linked-list-cycle.py) | _O(n)_ | _O(1)_ | Medium || +142| [Linked List Cycle II](https://leetcode.com/problems/linked-list-cycle-ii/)| [Python](./Python/linked-list-cycle-ii.py) | _O(n)_ | _O(1)_ | Medium || +143| [Reorder List](https://leetcode.com/problems/reorder-list/)| [Python](./Python/reorder-list.py) | _O(n)_ | _O(1)_ | Medium || +167| [Two Sum II - Input array is sorted](https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/) | [Python](./Python/two-sum-ii-input-array-is-sorted.py) | _O(n)_ | _O(1)_ | Medium | 📖 | --- ##Brute Force Search # | Problem | Solution | Time | Space | Difficulty | Tag | Notes -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- -17| [Letter Combinations of a Phone Number](https://oj.leetcode.com/problems/letter-combinations-of-a-phone-number/)| [Python](./Python/letter-combinations-of-a-phone-number.py) | _O(n * 4^n)_ | _O(n)_ | Medium || -46| [Permutations](https://oj.leetcode.com/problems/permutations/)| [Python](./Python/permutations.py) | _O(n!)_ | _O(n)_ | Medium || -47| [Permutations II](https://oj.leetcode.com/problems/permutations-ii/)| [Python](./Python/permutations-ii.py) | _O(n!)_ | _O(n)_ | Hard || -78| [Subsets](https://oj.leetcode.com/problems/subsets/) | [Python](./Python/subsets.py) | _O(n * 2^n)_ | _O(1)_ | Medium || -90| [Subsets II](https://oj.leetcode.com/problems/subsets-ii/) | [Python](./Python/subsets-ii.py) | _O(n * 2^n)_ | _O(1)_ | Medium || +17| [Letter Combinations of a Phone Number](https://leetcode.com/problems/letter-combinations-of-a-phone-number/)| [Python](./Python/letter-combinations-of-a-phone-number.py) | _O(n * 4^n)_ | _O(n)_ | Medium || +46| [Permutations](https://leetcode.com/problems/permutations/)| [Python](./Python/permutations.py) | _O(n!)_ | _O(n)_ | Medium || +47| [Permutations II](https://leetcode.com/problems/permutations-ii/)| [Python](./Python/permutations-ii.py) | _O(n!)_ | _O(n)_ | Hard || +78| [Subsets](https://leetcode.com/problems/subsets/) | [Python](./Python/subsets.py) | _O(n * 2^n)_ | _O(1)_ | Medium || +90| [Subsets II](https://leetcode.com/problems/subsets-ii/) | [Python](./Python/subsets-ii.py) | _O(n * 2^n)_ | _O(1)_ | Medium || --- ##Divide and Conquer # | Problem | Solution | Time | Space | Difficulty | Tag | Notes -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- -95| [Unique Binary Search Trees II](https://oj.leetcode.com/problems/unique-binary-search-trees-ii/) | [Python](./Python/unique-binary-search-trees-ii.py) | _O(4^n / n^(3/2)_ | _O(4^n / n^(3/2)_ | Medium || -98| [Validate Binary Search Tree](https://oj.leetcode.com/problems/validate-binary-search-tree/)|[Python](./Python/validate-binary-search-tree.py)| _O(n)_ | _O(1)_ | Medium || -100| [Same Tree](https://oj.leetcode.com/problems/same-tree/) |[Python](./Python/same-tree.py) | _O(n)_ | _O(h)_ | Easy || -104| [Maximum Depth of Binary Tree](https://oj.leetcode.com/problems/maximum-depth-of-binary-tree/)|[Python](./Python/maximum-depth-of-binary-tree.py)| _O(n)_ | _O(h)_ | Easy || -105| [Construct Binary Tree from Preorder and Inorder Traversal](https://oj.leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/) | [Python](./Python/construct-binary-tree-from-preorder-and-inorder-traversal.py) | _O(n)_ | _O(n)_ | Medium || -106| [Construct Binary Tree from Inorder and Postorder Traversal](https://oj.leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/) | [Python](./Python/construct-binary-tree-from-inorder-and-postorder-traversal.py) | _O(n)_ | _O(n)_ | Medium || -108| [Convert Sorted Array to Binary Search Tree](https://oj.leetcode.com/problems/convert-sorted-array-to-binary-search-tree/) | [Python](./Python/convert-sorted-array-to-binary-search-tree.py) | _O(n)_ | _O(logn)_ | Medium || -109| [Convert Sorted List to Binary Search Tree](https://oj.leetcode.com/problems/convert-sorted-list-to-binary-search-tree/) | [Python](./Python/convert-sorted-list-to-binary-search-tree.py) | _O(n)_ | _O(logn)_ | Medium || -110| [Balanced Binary Tree](https://oj.leetcode.com/problems/balanced-binary-tree/) | [Python](./Python/balanced-binary-tree.py) | _O(n)_| _O(h)_ | Easy || -111| [Minimum Depth of Binary Tree](https://oj.leetcode.com/problems/minimum-depth-of-binary-tree/)|[Python](./Python/minimum-depth-of-binary-tree.py)| _O(n)_ | _O(h)_ | Easy || -114| [Flatten Binary Tree to Linked List](https://oj.leetcode.com/problems/flatten-binary-tree-to-linked-list/)|[Python](./Python/flatten-binary-tree-to-linked-list.py)| _O(n)_ | _O(h)_ | Medium || -116| [Populating Next Right Pointers in Each Node](https://oj.leetcode.com/problems/populating-next-right-pointers-in-each-node/)|[Python](./Python/populating-next-right-pointers-in-each-node.py)| _O(n)_ | _O(1)_ | Medium || -124| [Binary Tree Maximum Path Sum](https://oj.leetcode.com/problems/binary-tree-maximum-path-sum/)| [Python](./Python/binary-tree-maximum-path-sum.py) | _O(n)_| _O(h)_| Hard || -129| [Sum Root to Leaf Numbers](https://oj.leetcode.com/problems/sum-root-to-leaf-numbers/) | [Python](./Python/sum-root-to-leaf-numbers.py) | _O(n)_ | _O(h)_ | Medium || -156| [Binary Tree Upside Down](https://oj.leetcode.com/problems/binary-tree-upside-down/) | [Python](./Python/binary-tree-upside-down.py) | _O(n)_ | _O(1)_ | Medium |📖| +95| [Unique Binary Search Trees II](https://leetcode.com/problems/unique-binary-search-trees-ii/) | [Python](./Python/unique-binary-search-trees-ii.py) | _O(4^n / n^(3/2)_ | _O(4^n / n^(3/2)_ | Medium || +98| [Validate Binary Search Tree](https://leetcode.com/problems/validate-binary-search-tree/)|[Python](./Python/validate-binary-search-tree.py)| _O(n)_ | _O(1)_ | Medium || +100| [Same Tree](https://leetcode.com/problems/same-tree/) |[Python](./Python/same-tree.py) | _O(n)_ | _O(h)_ | Easy || +104| [Maximum Depth of Binary Tree](https://leetcode.com/problems/maximum-depth-of-binary-tree/)|[Python](./Python/maximum-depth-of-binary-tree.py)| _O(n)_ | _O(h)_ | Easy || +105| [Construct Binary Tree from Preorder and Inorder Traversal](https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/) | [Python](./Python/construct-binary-tree-from-preorder-and-inorder-traversal.py) | _O(n)_ | _O(n)_ | Medium || +106| [Construct Binary Tree from Inorder and Postorder Traversal](https://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/) | [Python](./Python/construct-binary-tree-from-inorder-and-postorder-traversal.py) | _O(n)_ | _O(n)_ | Medium || +108| [Convert Sorted Array to Binary Search Tree](https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/) | [Python](./Python/convert-sorted-array-to-binary-search-tree.py) | _O(n)_ | _O(logn)_ | Medium || +109| [Convert Sorted List to Binary Search Tree](https://leetcode.com/problems/convert-sorted-list-to-binary-search-tree/) | [Python](./Python/convert-sorted-list-to-binary-search-tree.py) | _O(n)_ | _O(logn)_ | Medium || +110| [Balanced Binary Tree](https://leetcode.com/problems/balanced-binary-tree/) | [Python](./Python/balanced-binary-tree.py) | _O(n)_| _O(h)_ | Easy || +111| [Minimum Depth of Binary Tree](https://leetcode.com/problems/minimum-depth-of-binary-tree/)|[Python](./Python/minimum-depth-of-binary-tree.py)| _O(n)_ | _O(h)_ | Easy || +114| [Flatten Binary Tree to Linked List](https://leetcode.com/problems/flatten-binary-tree-to-linked-list/)|[Python](./Python/flatten-binary-tree-to-linked-list.py)| _O(n)_ | _O(h)_ | Medium || +116| [Populating Next Right Pointers in Each Node](https://leetcode.com/problems/populating-next-right-pointers-in-each-node/)|[Python](./Python/populating-next-right-pointers-in-each-node.py)| _O(n)_ | _O(1)_ | Medium || +124| [Binary Tree Maximum Path Sum](https://leetcode.com/problems/binary-tree-maximum-path-sum/)| [Python](./Python/binary-tree-maximum-path-sum.py) | _O(n)_| _O(h)_| Hard || +129| [Sum Root to Leaf Numbers](https://leetcode.com/problems/sum-root-to-leaf-numbers/) | [Python](./Python/sum-root-to-leaf-numbers.py) | _O(n)_ | _O(h)_ | Medium || +156| [Binary Tree Upside Down](https://leetcode.com/problems/binary-tree-upside-down/) | [Python](./Python/binary-tree-upside-down.py) | _O(n)_ | _O(1)_ | Medium |📖| --- ##Binary Search # | Problem | Solution | Time | Space | Difficulty | Tag | Notes -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- -4| [Median of Two Sorted Arrays](https://oj.leetcode.com/problems/median-of-two-sorted-arrays/) | [Python](./Python/median-of-two-sorted-arrays.py) | _O(log(m + n))_ | _O(1)_ | Hard || -33| [Search in Rotated Sorted Array](https://oj.leetcode.com/problems/search-in-rotated-sorted-array/) | [Python](./Python/search-in-rotated-sorted-array.py) | _O(logn)_ | _O(1)_ | Hard || -34| [Search for a Range](https://oj.leetcode.com/problems/search-for-a-range/) | [Python](./Python/search-for-a-range.py) | _O(logn)_ | _O(1)_ | Medium || -35| [Search Insert Position](https://oj.leetcode.com/problems/search-insert-position/) | [Python](./Python/search-insert-position.py) | _O(logn)_ | _O(1)_ | Medium || -50| [Pow(x, n)](https://oj.leetcode.com/problems/powx-n/) | [Python](./Python/powx-n.py) | _O(logn)_ | _O(logn)_ | Medium || -69| [Sqrt(x)](https://oj.leetcode.com/problems/sqrtx/) | [Python](./Python/sqrtx.py) | _O(logn)_ | _O(1)_ | Medium || -74| [Search a 2D Matrix](https://oj.leetcode.com/problems/search-a-2d-matrix/) | [Python](./Python/search-a-2d-matrix.py) | _O(logm + logn)_ | _O(1)_ | Medium || -81| [Search in Rotated Sorted Array II](https://oj.leetcode.com/problems/search-in-rotated-sorted-array-ii/) | [Python](./Python/search-in-rotated-sorted-array-ii.py) | _O(logn)_ | _O(1)_ | Medium || -153| [Find Minimum in Rotated Sorted Array](https://oj.leetcode.com/problems/find-minimum-in-rotated-sorted-array/) | [Python](./Python/find-minimum-in-rotated-sorted-array.py) | _O(logn)_ | _O(1)_ | Medium || -154| [Find Minimum in Rotated Sorted Array II](https://oj.leetcode.com/problems/find-minimum-in-rotated-sorted-array-ii/) | [Python](./Python/find-minimum-in-rotated-sorted-array-ii.py) | _O(logn)_ ~ _O(n)_ | _O(1)_ | Hard || -162| [Find Peak Element](https://oj.leetcode.com/problems/find-peak-element/) | [Python](./Python/find-peak-element.py) | _O(logn)_ | _O(1)_ | Medium || +4| [Median of Two Sorted Arrays](https://leetcode.com/problems/median-of-two-sorted-arrays/) | [Python](./Python/median-of-two-sorted-arrays.py) | _O(log(m + n))_ | _O(1)_ | Hard || +33| [Search in Rotated Sorted Array](https://leetcode.com/problems/search-in-rotated-sorted-array/) | [Python](./Python/search-in-rotated-sorted-array.py) | _O(logn)_ | _O(1)_ | Hard || +34| [Search for a Range](https://leetcode.com/problems/search-for-a-range/) | [Python](./Python/search-for-a-range.py) | _O(logn)_ | _O(1)_ | Medium || +35| [Search Insert Position](https://leetcode.com/problems/search-insert-position/) | [Python](./Python/search-insert-position.py) | _O(logn)_ | _O(1)_ | Medium || +50| [Pow(x, n)](https://leetcode.com/problems/powx-n/) | [Python](./Python/powx-n.py) | _O(logn)_ | _O(logn)_ | Medium || +69| [Sqrt(x)](https://leetcode.com/problems/sqrtx/) | [Python](./Python/sqrtx.py) | _O(logn)_ | _O(1)_ | Medium || +74| [Search a 2D Matrix](https://leetcode.com/problems/search-a-2d-matrix/) | [Python](./Python/search-a-2d-matrix.py) | _O(logm + logn)_ | _O(1)_ | Medium || +81| [Search in Rotated Sorted Array II](https://leetcode.com/problems/search-in-rotated-sorted-array-ii/) | [Python](./Python/search-in-rotated-sorted-array-ii.py) | _O(logn)_ | _O(1)_ | Medium || +153| [Find Minimum in Rotated Sorted Array](https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/) | [Python](./Python/find-minimum-in-rotated-sorted-array.py) | _O(logn)_ | _O(1)_ | Medium || +154| [Find Minimum in Rotated Sorted Array II](https://leetcode.com/problems/find-minimum-in-rotated-sorted-array-ii/) | [Python](./Python/find-minimum-in-rotated-sorted-array-ii.py) | _O(logn)_ ~ _O(n)_ | _O(1)_ | Hard || +162| [Find Peak Element](https://leetcode.com/problems/find-peak-element/) | [Python](./Python/find-peak-element.py) | _O(logn)_ | _O(1)_ | Medium || --- ##Breadth-First Search # | Problem | Solution | Time | Space | Difficulty | Tag | Notes -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- -102| [Binary Tree Level Order Traversal](https://oj.leetcode.com/problems/binary-tree-level-order-traversal/)| [Python](./Python/binary-tree-level-order-traversal.py)| _O(n)_| _O(n)_| Easy || -107| [Binary Tree Level Order Traversal II](https://oj.leetcode.com/problems/binary-tree-level-order-traversal-ii/)| [Python](./Python/binary-tree-level-order-traversal-ii.py) | _O(n)_| _O(n)_| Easy || -103| [Binary Tree Zigzag Level Order Traversal](https://oj.leetcode.com/problems/binary-tree-zigzag-level-order-traversal/)| [Python](./Python/binary-tree-zigzag-level-order-traversal.py) | _O(n)_| _O(n)_| Medium || -117| [Populating Next Right Pointers in Each Node II](https://oj.leetcode.com/problems/populating-next-right-pointers-in-each-node-ii/)|[Python](./Python/populating-next-right-pointers-in-each-node-ii.py)| _O(n)_ | _O(1)_ | Hard || -127| [Word Ladder](https://oj.leetcode.com/problems/word-ladder/)|[Python](./Python/word-ladder.py) | _O(n * d)_ | _O(d)_ | Medium || -130| [Surrounded Regions](https://oj.leetcode.com/problems/surrounded-regions/)|[Python](./Python/surrounded-regions.py)| _O(m * n)_ | _O(m + n)_ | Medium || -133| [Clone Graph](https://oj.leetcode.com/problems/clone-graph/)| [Python](./Python/clone-graph.py) | _O(n)_ | _O(n)_ | Medium || -207| [Course Schedule](https://oj.leetcode.com/problems/course-schedule/)| [Python](./Python/course-schedule.py) | _O(\|V\| + \|E\|)_ | _O(\|E\|)_ | Medium || -210| [Course Schedule II](https://oj.leetcode.com/problems/course-schedule-ii/)| [Python](./Python/course-schedule-ii.py) | _O(\|V\| + \|E\|)_ | _O(\|E\|)_ | Medium || +102| [Binary Tree Level Order Traversal](https://leetcode.com/problems/binary-tree-level-order-traversal/)| [Python](./Python/binary-tree-level-order-traversal.py)| _O(n)_| _O(n)_| Easy || +107| [Binary Tree Level Order Traversal II](https://leetcode.com/problems/binary-tree-level-order-traversal-ii/)| [Python](./Python/binary-tree-level-order-traversal-ii.py) | _O(n)_| _O(n)_| Easy || +103| [Binary Tree Zigzag Level Order Traversal](https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/)| [Python](./Python/binary-tree-zigzag-level-order-traversal.py) | _O(n)_| _O(n)_| Medium || +117| [Populating Next Right Pointers in Each Node II](https://leetcode.com/problems/populating-next-right-pointers-in-each-node-ii/)|[Python](./Python/populating-next-right-pointers-in-each-node-ii.py)| _O(n)_ | _O(1)_ | Hard || +127| [Word Ladder](https://leetcode.com/problems/word-ladder/)|[Python](./Python/word-ladder.py) | _O(n * d)_ | _O(d)_ | Medium || +130| [Surrounded Regions](https://leetcode.com/problems/surrounded-regions/)|[Python](./Python/surrounded-regions.py)| _O(m * n)_ | _O(m + n)_ | Medium || +133| [Clone Graph](https://leetcode.com/problems/clone-graph/)| [Python](./Python/clone-graph.py) | _O(n)_ | _O(n)_ | Medium || +207| [Course Schedule](https://leetcode.com/problems/course-schedule/)| [Python](./Python/course-schedule.py) | _O(\|V\| + \|E\|)_ | _O(\|E\|)_ | Medium || +210| [Course Schedule II](https://leetcode.com/problems/course-schedule-ii/)| [Python](./Python/course-schedule-ii.py) | _O(\|V\| + \|E\|)_ | _O(\|E\|)_ | Medium || --- ##Depth-First Search # | Problem | Solution | Time | Space | Difficulty | Tag | Notes -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- -22| [Generate Parentheses](https://oj.leetcode.com/problems/generate-parentheses/)| [Python](./Python/generate-parentheses.py)| _O(4^n / n^(3/2))_ | _O(n)_ | Medium || -37| [Sudoku Solver](https://oj.leetcode.com/problems/sudoku-solver/) | [Python](./Python/sudoku-solver.py) | _O((9!)^9)_ | _O(1)_ | Hard || -39| [Combination Sum](https://oj.leetcode.com/problems/combination-sum/)| [Python](./Python/combination-sum.py) | _O(n^m)_ | _O(m)_ | Medium || -40| [Combination Sum II](https://oj.leetcode.com/problems/combination-sum-ii/)| [Python](./Python/combination-sum-ii.py)| _O(n! / m!(n-m)!)_| _O(m)_ | Medium || -51| [N-Queens](https://oj.leetcode.com/problems/n-queens/) | [Python](./Python/n-queens.py) | _O(n!)_ | _O(n)_ | Hard || -52| [N-Queens-II](https://oj.leetcode.com/problems/n-queens-ii/) | [Python](./Python/n-queens-ii.py) | _O(n!)_ | _O(n)_ | Hard || -77| [Combinations](https://oj.leetcode.com/problems/combinations/) | [Python](./Python/combinations.py) | _O(n!)_ | _O(n)_ | Medium || -79| [Word Search](https://oj.leetcode.com/problems/word-search/) | [Python](./Python/word-search.py) | _O(m * n * l)_ | _O(l)_ | Medium || -93| [Restore IP Addresses](https://oj.leetcode.com/problems/restore-ip-addresses/) | [Python](./Python/restore-ip-addresses.py) | _O(n^m)_ ~ _O(3^4)_ | _O(n * m)_ ~ _O(3 * 4)_ | Medium || -112| [Path Sum](https://oj.leetcode.com/problems/path-sum/) | [Python](./Python/path-sum.py) | _O(n)_ | _O(h)_ | Easy || -113| [Path Sum II](https://oj.leetcode.com/problems/path-sum-ii/) | [Python](./Python/path-sum-ii.py) | _O(n)_ | _O(h)_ | Medium || -131| [Palindrome Partitioning](https://oj.leetcode.com/problems/palindrome-partitioning/) | [Python](./Python/palindrome-partitioning.py) | _O(n^2)_ ~ _O(2^n)_ | _O(n^2)_ | Medium || -199| [Binary Tree Right Side View](https://oj.leetcode.com/problems/binary-tree-right-side-view/) | [Python](./Python/binary-tree-right-side-view.py) | _O(n)_ | _O(h)_ | Medium || +22| [Generate Parentheses](https://leetcode.com/problems/generate-parentheses/)| [Python](./Python/generate-parentheses.py)| _O(4^n / n^(3/2))_ | _O(n)_ | Medium || +37| [Sudoku Solver](https://leetcode.com/problems/sudoku-solver/) | [Python](./Python/sudoku-solver.py) | _O((9!)^9)_ | _O(1)_ | Hard || +39| [Combination Sum](https://leetcode.com/problems/combination-sum/)| [Python](./Python/combination-sum.py) | _O(n^m)_ | _O(m)_ | Medium || +40| [Combination Sum II](https://leetcode.com/problems/combination-sum-ii/)| [Python](./Python/combination-sum-ii.py)| _O(n! / m!(n-m)!)_| _O(m)_ | Medium || +51| [N-Queens](https://leetcode.com/problems/n-queens/) | [Python](./Python/n-queens.py) | _O(n!)_ | _O(n)_ | Hard || +52| [N-Queens-II](https://leetcode.com/problems/n-queens-ii/) | [Python](./Python/n-queens-ii.py) | _O(n!)_ | _O(n)_ | Hard || +77| [Combinations](https://leetcode.com/problems/combinations/) | [Python](./Python/combinations.py) | _O(n!)_ | _O(n)_ | Medium || +79| [Word Search](https://leetcode.com/problems/word-search/) | [Python](./Python/word-search.py) | _O(m * n * l)_ | _O(l)_ | Medium || +93| [Restore IP Addresses](https://leetcode.com/problems/restore-ip-addresses/) | [Python](./Python/restore-ip-addresses.py) | _O(n^m)_ ~ _O(3^4)_ | _O(n * m)_ ~ _O(3 * 4)_ | Medium || +112| [Path Sum](https://leetcode.com/problems/path-sum/) | [Python](./Python/path-sum.py) | _O(n)_ | _O(h)_ | Easy || +113| [Path Sum II](https://leetcode.com/problems/path-sum-ii/) | [Python](./Python/path-sum-ii.py) | _O(n)_ | _O(h)_ | Medium || +131| [Palindrome Partitioning](https://leetcode.com/problems/palindrome-partitioning/) | [Python](./Python/palindrome-partitioning.py) | _O(n^2)_ ~ _O(2^n)_ | _O(n^2)_ | Medium || +199| [Binary Tree Right Side View](https://leetcode.com/problems/binary-tree-right-side-view/) | [Python](./Python/binary-tree-right-side-view.py) | _O(n)_ | _O(h)_ | Medium || 200| [Number of Islands](https://leetcode.com/problems/number-of-islands/) | [Python](./Python/number-of-islands.py) | _O(m * n)_ | _O(m * n)_| Medium || --- @@ -319,76 +319,76 @@ Shell ##Dynamic Programming # | Problem | Solution | Time | Space | Difficulty | Tag | Notes -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- -10| [Regular Expression Matching](https://oj.leetcode.com/problems/regular-expression-matching/) | [Python](./Python/regular-expression-matching.py) | _O(m * n)_ | _O(n)_ | Hard || -53| [Maximum Subarray](https://oj.leetcode.com/problems/maximum-subarray/)|[Python](./Python/maximum-subarray.py)| _O(n)_ | _O(1)_ | Medium || -62| [Unique Paths](https://oj.leetcode.com/problems/unique-paths/) | [Python](./Python/unique-paths.py)| _O(m * n)_ | _O(m + n)_ | Medium || -63| [Unique Paths II](https://oj.leetcode.com/problems/unique-paths-ii/) | [Python](./Python/unique-paths-ii.py) | _O(m * n)_ | _O(m + n)_ | Medium || -64| [Minimum Path Sum](https://oj.leetcode.com/problems/minimum-path-sum/)|[Python](./Python/minimum-path-sum.py)| _O(m * n)_ | _O(m + n)_ | Medium || -70| [Climbing Stairs](https://oj.leetcode.com/problems/climbing-stairs/)| [Python](./Python/climbing-stairs.py) | _O(n)_ | _O(1)_ | Easy || -72| [Edit Distance](https://oj.leetcode.com/problems/edit-distance/)|[Python](./Python/edit-distance.py)| _O(m * n)_ | _O(m + n)_ | Hard || -85| [Maximal Rectangle](https://oj.leetcode.com/problems/maximal-rectangle/)|[Python](./Python/maximal-rectangle.py)| _O(n^2)_ | _O(n)_ | Hard || -87| [Scramble String](https://oj.leetcode.com/problems/scramble-string/) | [Python](./Python/scramble-string.py) | _O(n^4)_ | _O(n^3)_ | Hard || -91| [Decode Ways](https://oj.leetcode.com/problems/decode-ways/) | [Python](./Python/decode-ways.py)| _O(n)_ | _O(1)_ | Medium || -96| [Unique Binary Search Trees](https://oj.leetcode.com/problems/unique-binary-search-trees/) | [Python](./Python/unique-binary-search-trees.py) | _O(n^2)_ | _O(n)_ | Medium || -97| [Interleaving String](https://oj.leetcode.com/problems/interleaving-string/)|[Python](./Python/interleaving-string.py)| _O(m * n)_ | _O(m + n)_ | Hard || -115| [Distinct Subsequences](https://oj.leetcode.com/problems/distinct-subsequences/)|[Python](./Python/distinct-subsequences.py)| _O(n^2)_ | _O(n)_ | Hard || -120| [Triangle](https://oj.leetcode.com/problems/triangle/) | [Python](./Python/triangle.py) | _O(m * n)_ | _O(n)_ | Medium || -123| [Best Time to Buy and Sell Stock III](https://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/) | [Python](./Python/best-time-to-buy-and-sell-stock-iii.py) | _O(n)_ | _O(1)_ | Hard || -132| [Palindrome Partitioning II](https://oj.leetcode.com/problems/palindrome-partitioning-ii/) | [Python](./Python/palindrome-partitioning-ii.py) | _O(n^2)_ | _O(n^2)_ | Hard || -139| [Word Break](https://oj.leetcode.com/problems/word-break/) | [Python](./Python/word-break.py) | _O(n^2)_ | _O(n)_ | Medium || -140| [Word Break II](https://oj.leetcode.com/problems/word-break-ii/) | [Python](./Python/word-break-ii.py) | _O(n^2)_ | _O(n)_ | Hard || -152| [Maximum Product Subarray](https://oj.leetcode.com/problems/maximum-product-subarray/)|[Python](./Python/maximum-product-subarray.py)| _O(n)_ | _O(1)_ | Medium || -174| [Dungeon Game](https://oj.leetcode.com/problems/dungeon-game/) | [Python](./Python/dungeon-game.py)| _O(m * n)_ | _O(m + n)_ | Hard || -188| [Best Time to Buy and Sell Stock IV](https://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/)| [Python](./Python/best-time-to-buy-and-sell-stock-iv.py) | _O(k * n)_ | _O(k)_ | Hard || -198| [House Robber](https://oj.leetcode.com/problems/house-robber/)| [Python](./Python/house-robber.py) | _O(n)_ | _O(1)_ | Easy || -213| [House Robber II](https://oj.leetcode.com/problems/house-robber-ii/)| [C++](./C++/house-robber-ii.cpp) [Python](./Python/house-robber-ii.py) | _O(n)_ | _O(1)_ | Medium || +10| [Regular Expression Matching](https://leetcode.com/problems/regular-expression-matching/) | [Python](./Python/regular-expression-matching.py) | _O(m * n)_ | _O(n)_ | Hard || +53| [Maximum Subarray](https://leetcode.com/problems/maximum-subarray/)|[Python](./Python/maximum-subarray.py)| _O(n)_ | _O(1)_ | Medium || +62| [Unique Paths](https://leetcode.com/problems/unique-paths/) | [Python](./Python/unique-paths.py)| _O(m * n)_ | _O(m + n)_ | Medium || +63| [Unique Paths II](https://leetcode.com/problems/unique-paths-ii/) | [Python](./Python/unique-paths-ii.py) | _O(m * n)_ | _O(m + n)_ | Medium || +64| [Minimum Path Sum](https://leetcode.com/problems/minimum-path-sum/)|[Python](./Python/minimum-path-sum.py)| _O(m * n)_ | _O(m + n)_ | Medium || +70| [Climbing Stairs](https://leetcode.com/problems/climbing-stairs/)| [Python](./Python/climbing-stairs.py) | _O(n)_ | _O(1)_ | Easy || +72| [Edit Distance](https://leetcode.com/problems/edit-distance/)|[Python](./Python/edit-distance.py)| _O(m * n)_ | _O(m + n)_ | Hard || +85| [Maximal Rectangle](https://leetcode.com/problems/maximal-rectangle/)|[Python](./Python/maximal-rectangle.py)| _O(n^2)_ | _O(n)_ | Hard || +87| [Scramble String](https://leetcode.com/problems/scramble-string/) | [Python](./Python/scramble-string.py) | _O(n^4)_ | _O(n^3)_ | Hard || +91| [Decode Ways](https://leetcode.com/problems/decode-ways/) | [Python](./Python/decode-ways.py)| _O(n)_ | _O(1)_ | Medium || +96| [Unique Binary Search Trees](https://leetcode.com/problems/unique-binary-search-trees/) | [Python](./Python/unique-binary-search-trees.py) | _O(n^2)_ | _O(n)_ | Medium || +97| [Interleaving String](https://leetcode.com/problems/interleaving-string/)|[Python](./Python/interleaving-string.py)| _O(m * n)_ | _O(m + n)_ | Hard || +115| [Distinct Subsequences](https://leetcode.com/problems/distinct-subsequences/)|[Python](./Python/distinct-subsequences.py)| _O(n^2)_ | _O(n)_ | Hard || +120| [Triangle](https://leetcode.com/problems/triangle/) | [Python](./Python/triangle.py) | _O(m * n)_ | _O(n)_ | Medium || +123| [Best Time to Buy and Sell Stock III](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/) | [Python](./Python/best-time-to-buy-and-sell-stock-iii.py) | _O(n)_ | _O(1)_ | Hard || +132| [Palindrome Partitioning II](https://leetcode.com/problems/palindrome-partitioning-ii/) | [Python](./Python/palindrome-partitioning-ii.py) | _O(n^2)_ | _O(n^2)_ | Hard || +139| [Word Break](https://leetcode.com/problems/word-break/) | [Python](./Python/word-break.py) | _O(n^2)_ | _O(n)_ | Medium || +140| [Word Break II](https://leetcode.com/problems/word-break-ii/) | [Python](./Python/word-break-ii.py) | _O(n^2)_ | _O(n)_ | Hard || +152| [Maximum Product Subarray](https://leetcode.com/problems/maximum-product-subarray/)|[Python](./Python/maximum-product-subarray.py)| _O(n)_ | _O(1)_ | Medium || +174| [Dungeon Game](https://leetcode.com/problems/dungeon-game/) | [Python](./Python/dungeon-game.py)| _O(m * n)_ | _O(m + n)_ | Hard || +188| [Best Time to Buy and Sell Stock IV](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/)| [Python](./Python/best-time-to-buy-and-sell-stock-iv.py) | _O(k * n)_ | _O(k)_ | Hard || +198| [House Robber](https://leetcode.com/problems/house-robber/)| [Python](./Python/house-robber.py) | _O(n)_ | _O(1)_ | Easy || +213| [House Robber II](https://leetcode.com/problems/house-robber-ii/)| [C++](./C++/house-robber-ii.cpp) [Python](./Python/house-robber-ii.py) | _O(n)_ | _O(1)_ | Medium || --- ##Backtracking # | Problem | Solution | Time | Space | Difficulty | Tag | Notes -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- -126| [Word Ladder II](https://oj.leetcode.com/problems/word-ladder-ii/) |[Python](./Python/word-ladder-ii.py) | _O(n * d)_ | _O(d)_ | Hard || +126| [Word Ladder II](https://leetcode.com/problems/word-ladder-ii/) |[Python](./Python/word-ladder-ii.py) | _O(n * d)_ | _O(d)_ | Hard || --- ##Greedy # | Problem | Solution | Time | Space | Difficulty | Tag | Notes -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- -11| [Container With Most Water](https://oj.leetcode.com/problems/container-with-most-water/)| [Python](./Python/container-with-most-water.py) | _O(n)_ | _O(1)_ | Medium || -42| [Trapping Rain Water](https://oj.leetcode.com/problems/trapping-rain-water/) | [Python](./Python/trapping-rain-water.py) | _O(n)_ | _O(1)_ | Hard || Tricky -44| [Wildcard Matching](https://oj.leetcode.com/problems/wildcard-matching/) | [Python](./Python/wildcard-matching.py) | _O(m + n)_ | _O(1)_ | Hard || Tricky -45| [Jump Game II](https://oj.leetcode.com/problems/jump-game-ii/) | [Python](./Python/jump-game-ii.py) | _O(n)_ | _O(1)_ | Hard || -55| [Jump Game](https://oj.leetcode.com/problems/jump-game/) | [Python](./Python/jump-game.py) | _O(n)_ | _O(1)_ | Medium || -84| [Largest Rectangle in Histogram](https://oj.leetcode.com/problems/largest-rectangle-in-histogram/) | [Python](./Python/largest-rectangle-in-histogram.py) | _O(n)_ | _O(n)_ | Hard || Tricky -122| [Best Time to Buy and Sell Stock II](https://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/)| [Python](./Python/best-time-to-buy-and-sell-stock-ii.py) | _O(n)_ | _O(1)_ | Medium || -134| [Gas Station](https://oj.leetcode.com/problems/gas-station/)| [Python](./Python/gas-station.py) | _O(n)_ | _O(1)_ | Medium || -135| [Candy](https://oj.leetcode.com/problems/candy/)| [Python](./Python/candy.py) | _O(n)_ | _O(n)_ | Hard || +11| [Container With Most Water](https://leetcode.com/problems/container-with-most-water/)| [Python](./Python/container-with-most-water.py) | _O(n)_ | _O(1)_ | Medium || +42| [Trapping Rain Water](https://leetcode.com/problems/trapping-rain-water/) | [Python](./Python/trapping-rain-water.py) | _O(n)_ | _O(1)_ | Hard || Tricky +44| [Wildcard Matching](https://leetcode.com/problems/wildcard-matching/) | [Python](./Python/wildcard-matching.py) | _O(m + n)_ | _O(1)_ | Hard || Tricky +45| [Jump Game II](https://leetcode.com/problems/jump-game-ii/) | [Python](./Python/jump-game-ii.py) | _O(n)_ | _O(1)_ | Hard || +55| [Jump Game](https://leetcode.com/problems/jump-game/) | [Python](./Python/jump-game.py) | _O(n)_ | _O(1)_ | Medium || +84| [Largest Rectangle in Histogram](https://leetcode.com/problems/largest-rectangle-in-histogram/) | [Python](./Python/largest-rectangle-in-histogram.py) | _O(n)_ | _O(n)_ | Hard || Tricky +122| [Best Time to Buy and Sell Stock II](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/)| [Python](./Python/best-time-to-buy-and-sell-stock-ii.py) | _O(n)_ | _O(1)_ | Medium || +134| [Gas Station](https://leetcode.com/problems/gas-station/)| [Python](./Python/gas-station.py) | _O(n)_ | _O(1)_ | Medium || +135| [Candy](https://leetcode.com/problems/candy/)| [Python](./Python/candy.py) | _O(n)_ | _O(n)_ | Hard || --- ##SQL # | Problem | Solution | Time | Space | Difficulty | Tag | Notes -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- -175| [Combine Two Tables](https://oj.leetcode.com/problems/combine-two-tables/) | [MySQL](./MySQL/combine-two-tables.sql) | _O(m + n)_ | _O(m + n)_ | Easy || -176| [Second Highest Salary](https://oj.leetcode.com/problems/second-highest-salary/) | [MySQL](./MySQL/second-highest-salary.sql) | _O(n)_ | _O(1)_ | Easy || -177| [Nth Highest Salary](https://oj.leetcode.com/problems/nth-highest-salary/) | [MySQL](./MySQL/nth-highest-salary.sql) | _O(n^2)_ | _O(n)_ | Medium || -178| [Rank Scores](https://oj.leetcode.com/problems/rank-scores/) | [MySQL](./MySQL/rank-scores.sql) | _O(n^2)_ | _O(n)_ | Medium || -180| [Consecutive Numbers](https://oj.leetcode.com/problems/consecutive-numbers/) | [MySQL](./MySQL/consecutive-numbers.sql) | _O(n)_ | _O(n)_ | Medium || -181| [Employees Earning More Than Their Managers](https://oj.leetcode.com/problems/employees-earning-more-than-their-managers/) | [MySQL](./MySQL/employees-earning-more-than-their-managers.sql) | _O(n^2)_ | _O(1)_ | Easy || -182| [Duplicate Emails](https://oj.leetcode.com/problems/duplicate-emails/) | [MySQL](./MySQL/duplicate-emails.sql) | _O(n^2)_ | _O(n)_ | Easy || -183| [Customers Who Never Order](https://oj.leetcode.com/problems/customers-who-never-order/) | [MySQL](./MySQL/customers-who-never-order.sql) | _O(n^2)_ | _O(1)_ | Easy || -184| [Department Highest Salary](https://oj.leetcode.com/problems/department-highest-salary/) | [MySQL](./MySQL/department-highest-salary.sql) | _O(n^2)_ | _O(n)_ | Medium || -185| [Department Top Three Salaries](https://oj.leetcode.com/problems/department-top-three-salaries/) | [MySQL](./MySQL/department-top-three-salaries.sql) | _O(n^2)_ | _O(n)_ | Hard || -196| [Delete Duplicate Emails](https://oj.leetcode.com/problems/delete-duplicate-emails/) | [MySQL](./MySQL/delete-duplicate-emails.sql) | _O(n^2)_ | _O(n)_ | Easy || -197| [Rising Temperature](https://oj.leetcode.com/problems/rising-temperature/) | [MySQL](./MySQL/rising-temperature.sql) | _O(n^2)_ | _O(n)_ | Easy || +175| [Combine Two Tables](https://leetcode.com/problems/combine-two-tables/) | [MySQL](./MySQL/combine-two-tables.sql) | _O(m + n)_ | _O(m + n)_ | Easy || +176| [Second Highest Salary](https://leetcode.com/problems/second-highest-salary/) | [MySQL](./MySQL/second-highest-salary.sql) | _O(n)_ | _O(1)_ | Easy || +177| [Nth Highest Salary](https://leetcode.com/problems/nth-highest-salary/) | [MySQL](./MySQL/nth-highest-salary.sql) | _O(n^2)_ | _O(n)_ | Medium || +178| [Rank Scores](https://leetcode.com/problems/rank-scores/) | [MySQL](./MySQL/rank-scores.sql) | _O(n^2)_ | _O(n)_ | Medium || +180| [Consecutive Numbers](https://leetcode.com/problems/consecutive-numbers/) | [MySQL](./MySQL/consecutive-numbers.sql) | _O(n)_ | _O(n)_ | Medium || +181| [Employees Earning More Than Their Managers](https://leetcode.com/problems/employees-earning-more-than-their-managers/) | [MySQL](./MySQL/employees-earning-more-than-their-managers.sql) | _O(n^2)_ | _O(1)_ | Easy || +182| [Duplicate Emails](https://leetcode.com/problems/duplicate-emails/) | [MySQL](./MySQL/duplicate-emails.sql) | _O(n^2)_ | _O(n)_ | Easy || +183| [Customers Who Never Order](https://leetcode.com/problems/customers-who-never-order/) | [MySQL](./MySQL/customers-who-never-order.sql) | _O(n^2)_ | _O(1)_ | Easy || +184| [Department Highest Salary](https://leetcode.com/problems/department-highest-salary/) | [MySQL](./MySQL/department-highest-salary.sql) | _O(n^2)_ | _O(n)_ | Medium || +185| [Department Top Three Salaries](https://leetcode.com/problems/department-top-three-salaries/) | [MySQL](./MySQL/department-top-three-salaries.sql) | _O(n^2)_ | _O(n)_ | Hard || +196| [Delete Duplicate Emails](https://leetcode.com/problems/delete-duplicate-emails/) | [MySQL](./MySQL/delete-duplicate-emails.sql) | _O(n^2)_ | _O(n)_ | Easy || +197| [Rising Temperature](https://leetcode.com/problems/rising-temperature/) | [MySQL](./MySQL/rising-temperature.sql) | _O(n^2)_ | _O(n)_ | Easy || --- ##Shell Script # | Problem | Solution | Time | Space | Difficulty | Tag | Notes -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- -192 | [Word Frequency](https://oj.leetcode.com/problems/word-frequency/) | [Shell](./Shell/word-frequency.sh) | _O(n)_ | _O(k)_ | Medium || -193 | [Valid Phone Numbers](https://oj.leetcode.com/problems/valid-phone-numbers/) | [Shell](./Shell/valid-phone-numbers.sh) | _O(n)_ | _O(1)_ | Easy || -194 | [Transpose File](https://oj.leetcode.com/problems/transpose-file/) | [Shell](./Shell/transpose-file.sh) | _O(n^2)_ | _O(n^2)_ | Medium || -195 | [Tenth Line](https://oj.leetcode.com/problems/tenth-line/) | [Shell](./Shell/tenth-line.sh) | _O(n)_ | _O(1)_ | Easy || +192 | [Word Frequency](https://leetcode.com/problems/word-frequency/) | [Shell](./Shell/word-frequency.sh) | _O(n)_ | _O(k)_ | Medium || +193 | [Valid Phone Numbers](https://leetcode.com/problems/valid-phone-numbers/) | [Shell](./Shell/valid-phone-numbers.sh) | _O(n)_ | _O(1)_ | Easy || +194 | [Transpose File](https://leetcode.com/problems/transpose-file/) | [Shell](./Shell/transpose-file.sh) | _O(n^2)_ | _O(n^2)_ | Medium || +195 | [Tenth Line](https://leetcode.com/problems/tenth-line/) | [Shell](./Shell/tenth-line.sh) | _O(n)_ | _O(1)_ | Easy || From e72a567686c0f8fc98c22d947838cdc146cf0605 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 23 May 2015 21:06:06 +0800 Subject: [PATCH 273/345] Create shortest-palindrome.py --- Python/shortest-palindrome.py | 40 +++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 Python/shortest-palindrome.py diff --git a/Python/shortest-palindrome.py b/Python/shortest-palindrome.py new file mode 100644 index 000000000..28491b939 --- /dev/null +++ b/Python/shortest-palindrome.py @@ -0,0 +1,40 @@ +# Time: O(n) +# Space: O(n) + +# TLE +class Solution: + # @param {string} s + # @return {string} + def shortestPalindrome(self, s): + string = self.preProcess(s) + palindrome = [0] * len(string) + center, right = 0, 0 + for i in xrange(1, len(string) - 1): + i_mirror = 2 * center - i + if right > i: + palindrome[i] = min(right - i, palindrome[i_mirror]) + else: + palindrome[i] = 0 + + while string[i + 1 + palindrome[i]] == string[i - 1 - palindrome[i]]: + palindrome[i] += 1 + + if i + palindrome[i] > right: + center, right = i, i + palindrome[i] + + max_len, max_center = 0, 0 + for i in xrange(1, len(string) - 1): + if i - palindrome[i] == 1: + max_len = palindrome[i] + return s[len(s)-1:max_len-1:-1] + s + + def preProcess(self, s): + + if not s: + return "^$" + string = "^" + for i in s: + string += "#" + i + string += "#$" + return string + From 08b0157d40897f83b3d179a435e12e0dbc914198 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 23 May 2015 21:06:41 +0800 Subject: [PATCH 274/345] Update shortest-palindrome.py --- Python/shortest-palindrome.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/shortest-palindrome.py b/Python/shortest-palindrome.py index 28491b939..75fb99fb1 100644 --- a/Python/shortest-palindrome.py +++ b/Python/shortest-palindrome.py @@ -22,7 +22,7 @@ def shortestPalindrome(self, s): if i + palindrome[i] > right: center, right = i, i + palindrome[i] - max_len, max_center = 0, 0 + max_len = 0 for i in xrange(1, len(string) - 1): if i - palindrome[i] == 1: max_len = palindrome[i] From d60898ee1e981d6dfd95ee87f021e40c501d9bd7 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 23 May 2015 21:07:24 +0800 Subject: [PATCH 275/345] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index db7d1b8a9..16c3331f2 100644 --- a/README.md +++ b/README.md @@ -107,7 +107,7 @@ Shell 165| [Compare Version Numbers](https://leetcode.com/problems/count-and-say/) | [Python](./Python/count-and-say.py) | _O(n)_ | _O(1)_ | Easy || 186| [Reverse Words in a String II](https://leetcode.com/problems/reverse-words-in-a-string-ii/) | [Python](./Python/reverse-words-in-a-string-ii.py) | _O(n)_ | _O(1)_ | Medium | 📖 | 205| [Isomorphic Strings](https://leetcode.com/problems/isomorphic-strings/) | [Python](./Python/isomorphic-strings.py) | _O(n)_ | _O(1)_ | Easy || -214| [Shortest Palindrome](https://leetcode.com/problems/shortest-palindrome/) | [C++](./C++/shortest-palindrome.cpp) | _O(n)_ | _O(n)_ | Hard || `Manacher's Algorithm` +214| [Shortest Palindrome](https://leetcode.com/problems/shortest-palindrome/) | [C++](./C++/shortest-palindrome.cpp) [Python](./Python/shortest-palindrome.py) | _O(n)_ | _O(n)_ | Hard || `Manacher's Algorithm` --- From 5aace18703e4b18d7b2cd013ee2191fe20ac7600 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 23 May 2015 21:08:16 +0800 Subject: [PATCH 276/345] Update shortest-palindrome.cpp --- C++/shortest-palindrome.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/C++/shortest-palindrome.cpp b/C++/shortest-palindrome.cpp index 3a547b834..00684fe84 100644 --- a/C++/shortest-palindrome.cpp +++ b/C++/shortest-palindrome.cpp @@ -1,3 +1,6 @@ +// Time: O(n) +// Space: O(n) + class Solution { public: string shortestPalindrome(string s) { From 58424d395251708a67536b2afd3cb72fc9da1796 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 23 May 2015 21:22:41 +0800 Subject: [PATCH 277/345] Create kth-largest-element-in-an-array.py --- Python/kth-largest-element-in-an-array.py | 34 +++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 Python/kth-largest-element-in-an-array.py diff --git a/Python/kth-largest-element-in-an-array.py b/Python/kth-largest-element-in-an-array.py new file mode 100644 index 000000000..fe0dfa31b --- /dev/null +++ b/Python/kth-largest-element-in-an-array.py @@ -0,0 +1,34 @@ +# Time: O(n) +# Space: O(1) + +from random import randint + +class Solution: + # @param {integer[]} nums + # @param {integer} k + # @return {integer} + def findKthLargest(self, nums, k): + left, right = 0, len(nums) - 1 + while left <= right: + pivot_idx = randint(left, right) + new_pivot_idx = self.PartitionAroundPivot(left, right, pivot_idx, nums) + if new_pivot_idx == k - 1: + return nums[new_pivot_idx] + elif new_pivot_idx > k - 1: + right = new_pivot_idx - 1 + else: # new_pivot_idx < k - 1. + left = new_pivot_idx + 1 + + + def PartitionAroundPivot(self, left, right, pivot_idx, nums): + pivot_value = nums[pivot_idx] + new_pivot_idx = left + nums[pivot_idx], nums[right] = nums[right], nums[pivot_idx] + for i in xrange(left, right): + if nums[i] > pivot_value: + nums[i], nums[new_pivot_idx] = nums[new_pivot_idx], nums[i] + new_pivot_idx += 1 + + nums[right], nums[new_pivot_idx] = nums[new_pivot_idx], nums[right] + return new_pivot_idx + From 0c7ff94f7fa62d2d4ffa67db3ace90f57e9dadb1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 23 May 2015 21:23:32 +0800 Subject: [PATCH 278/345] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 16c3331f2..6fea7f234 100644 --- a/README.md +++ b/README.md @@ -84,7 +84,7 @@ Shell 169 | [Majority Element](https://leetcode.com/problems/majority-element/) | [Python](./Python/majority-element.py) | _O(n)_ | _O(1)_ | Easy | 189 | [Rotate Array](https://leetcode.com/problems/rotate-array/) | [Python](./Python/rotate-array.py) | _O(n)_ | _O(1)_ | Easy || 209 | [Minimum Size Subarray Sum](https://leetcode.com/problems/minimum-size-subarray-sum/) | [Python] (./Python/minimum-size-subarray-sum.py) | _O(n)_ | _O(1)_ | Medium || -215 | [Kth Largest Element in an Array](https://leetcode.com/problems/kth-largest-element-in-an-array/) | [C++] (./C++/kth-largest-element-in-an-array.cpp) | _O(n)_ | _O(1)_ | Medium | EPI| +215 | [Kth Largest Element in an Array](https://leetcode.com/problems/kth-largest-element-in-an-array/) | [C++] (./C++/kth-largest-element-in-an-array.cpp) [Python] (./Python/kth-largest-element-in-an-array.py)| _O(n)_ | _O(1)_ | Medium | EPI| --- From 6b4018d4ca5bd5e1aa47ecf2a7758cdf95238f16 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 23 May 2015 21:25:02 +0800 Subject: [PATCH 279/345] Update shortest-palindrome.py --- Python/shortest-palindrome.py | 1 - 1 file changed, 1 deletion(-) diff --git a/Python/shortest-palindrome.py b/Python/shortest-palindrome.py index 75fb99fb1..70c4c7d7f 100644 --- a/Python/shortest-palindrome.py +++ b/Python/shortest-palindrome.py @@ -29,7 +29,6 @@ def shortestPalindrome(self, s): return s[len(s)-1:max_len-1:-1] + s def preProcess(self, s): - if not s: return "^$" string = "^" From 10ccae1449474ee4e8b0ca6b57885543643f49ff Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 24 May 2015 09:01:54 +0800 Subject: [PATCH 280/345] Update implement-strstr.py --- Python/implement-strstr.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/implement-strstr.py b/Python/implement-strstr.py index 9b7149b10..b57b11261 100644 --- a/Python/implement-strstr.py +++ b/Python/implement-strstr.py @@ -40,7 +40,7 @@ def KMP(self, text, pattern): def getPrefix(self, pattern): prefix = [-1] * len(pattern) - j = - 1 + j = -1 for i in xrange(1, len(pattern)): while j > -1 and pattern[j + 1] != pattern[i]: j = prefix[j] From 326e69c0af6612afba35df6b76757dcee8b7fb2e Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 24 May 2015 09:09:15 +0800 Subject: [PATCH 281/345] Update shortest-palindrome.py --- Python/shortest-palindrome.py | 26 +++++++++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) diff --git a/Python/shortest-palindrome.py b/Python/shortest-palindrome.py index 70c4c7d7f..471222f69 100644 --- a/Python/shortest-palindrome.py +++ b/Python/shortest-palindrome.py @@ -1,8 +1,32 @@ # Time: O(n) # Space: O(n) -# TLE +# KMP algorithm class Solution: + # @param {string} s + # @return {string} + def shortestPalindrome(self, s): + if not s: + return s + + A = s + s[::-1] + prefix = self.getPrefix(A) + + return s[prefix[-1]+1:][::-1] + s + + def getPrefix(self, pattern): + prefix = [-1] * len(pattern) + j = -1 + for i in xrange(1, len(pattern)): + while j > -1 and pattern[j+1] != pattern[i]: + j = prefix[j] + if pattern[j+1] == pattern[i]: + j += 1 + prefix[i] = j + return prefix + +# Manacher's Algorithm +class Solution_TLE: # @param {string} s # @return {string} def shortestPalindrome(self, s): From 13d8656bbc02ce78c8bc4ab669e8ed98aa04d7ae Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 24 May 2015 09:09:32 +0800 Subject: [PATCH 282/345] Update shortest-palindrome.py --- Python/shortest-palindrome.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/shortest-palindrome.py b/Python/shortest-palindrome.py index 471222f69..f43dada73 100644 --- a/Python/shortest-palindrome.py +++ b/Python/shortest-palindrome.py @@ -1,7 +1,7 @@ # Time: O(n) # Space: O(n) -# KMP algorithm +# KMP Algorithm class Solution: # @param {string} s # @return {string} From 74b0dbe0733abc493bed3617663f87e386971f4b Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 24 May 2015 09:10:14 +0800 Subject: [PATCH 283/345] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 6fea7f234..79c0dc06d 100644 --- a/README.md +++ b/README.md @@ -107,7 +107,7 @@ Shell 165| [Compare Version Numbers](https://leetcode.com/problems/count-and-say/) | [Python](./Python/count-and-say.py) | _O(n)_ | _O(1)_ | Easy || 186| [Reverse Words in a String II](https://leetcode.com/problems/reverse-words-in-a-string-ii/) | [Python](./Python/reverse-words-in-a-string-ii.py) | _O(n)_ | _O(1)_ | Medium | 📖 | 205| [Isomorphic Strings](https://leetcode.com/problems/isomorphic-strings/) | [Python](./Python/isomorphic-strings.py) | _O(n)_ | _O(1)_ | Easy || -214| [Shortest Palindrome](https://leetcode.com/problems/shortest-palindrome/) | [C++](./C++/shortest-palindrome.cpp) [Python](./Python/shortest-palindrome.py) | _O(n)_ | _O(n)_ | Hard || `Manacher's Algorithm` +214| [Shortest Palindrome](https://leetcode.com/problems/shortest-palindrome/) | [C++](./C++/shortest-palindrome.cpp) [Python](./Python/shortest-palindrome.py) | _O(n)_ | _O(n)_ | Hard || `KMP Algorithm` `Manacher's Algorithm` --- From 0304d526a42b205b8a7c5f62acf3713c4361c7b3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 24 May 2015 09:18:32 +0800 Subject: [PATCH 284/345] Update shortest-palindrome.cpp --- C++/shortest-palindrome.cpp | 59 +++++++++++++++++++++++++++++-------- 1 file changed, 47 insertions(+), 12 deletions(-) diff --git a/C++/shortest-palindrome.cpp b/C++/shortest-palindrome.cpp index 00684fe84..083c21e11 100644 --- a/C++/shortest-palindrome.cpp +++ b/C++/shortest-palindrome.cpp @@ -1,7 +1,42 @@ // Time: O(n) // Space: O(n) +// KMP Algorithm class Solution { +public: + string shortestPalindrome(string s) { + if (s.empty()) { + return s; + } + string rev_s(s.crbegin(), s.crend()); + string A = s + rev_s; + vector pattern(move(getPrefix(A))); + string non_palindrome = s.substr(pattern.back() + 1); + reverse(non_palindrome.begin(), non_palindrome.end()); + return non_palindrome + s; + } + +private: + vector getPrefix(const string& pattern) { + vector prefix(pattern.length(), -1); + int j = -1; + for (int i = 1; i < pattern.length(); ++i) { + while (j > -1 && pattern[j + 1] != pattern[i]) { + j = prefix[j]; + } + if (pattern[j + 1] == pattern[i]) { + ++j; + } + prefix[i] = j; + } + return prefix; + } +}; + +// Time: O(n) +// Space: O(n) +// Manacher's Algorithm +class Solution2 { public: string shortestPalindrome(string s) { string T = preProcess(s); @@ -40,17 +75,17 @@ class Solution { ans.append(s); // cba(Palindrome)abc. return ans; } - private: - string preProcess(string s) { - int n = s.length(); - if (n == 0) { - return "^$"; - } - string ret = "^"; - for (int i = 0; i < n; i++) - ret += "#" + s.substr(i, 1); - - ret += "#$"; - return ret; +private: + string preProcess(string s) { + int n = s.length(); + if (n == 0) { + return "^$"; + } + string ret = "^"; + for (int i = 0; i < n; ++i) { + ret += "#" + s.substr(i, 1); } + ret += "#$"; + return ret; + } }; From deb96a8dc2d41f1525cac1eef5e9cb193c65240c Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 24 May 2015 21:24:07 +0800 Subject: [PATCH 285/345] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 79c0dc06d..82147d190 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ LeetCode ======== -Up to date (2015-05-23), there are `199` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2015-05-24), there are `200` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://leetcode.com/). The number of problems is increasing recently. -Here is the classification of all `215` problems. +Here is the classification of all `216` problems. For extra problems and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repo. I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "📖" means you have to buy the book from LeetCode. ) From 0611e5be63cb4bf73e57140d331c0f913910b919 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 25 May 2015 18:04:26 +0800 Subject: [PATCH 286/345] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 82147d190..3f017a68c 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ LeetCode ======== -Up to date (2015-05-24), there are `200` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2015-05-25), there are `201` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://leetcode.com/). The number of problems is increasing recently. -Here is the classification of all `216` problems. +Here is the classification of all `217` problems. For extra problems and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repo. I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "📖" means you have to buy the book from LeetCode. ) From ae7e18a5f735f174d41dbaa707bfd0576b5e8a15 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 26 May 2015 02:15:56 +0800 Subject: [PATCH 287/345] Create combination-sum-iii.cpp --- C++/combination-sum-iii.cpp | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 C++/combination-sum-iii.cpp diff --git a/C++/combination-sum-iii.cpp b/C++/combination-sum-iii.cpp new file mode 100644 index 000000000..ff297a253 --- /dev/null +++ b/C++/combination-sum-iii.cpp @@ -0,0 +1,27 @@ +// Time: O(C(n, k)) +// Space: O(k) + +class Solution { +public: + vector > combinationSum3(int k, int n) { + vector> res; + vector combination; + combinationSum3(res, combination, 1, k, n); + return res; + } +private: + void combinationSum3(vector > &res, vector &combination, int start, int k, int n) { + if (!k && !n) { + res.push_back(combination); + return; + } else if (k < 0) { + return; + } + + for (int i = start; i < 10 && n >= k * i + k * (k - 1) / 2; ++i) { + combination.push_back(i); + combinationSum3(res, combination, i + 1, k - 1, n - i); + combination.pop_back(); + } + } +}; From 6d1a7a396ef00ade8485777e3ba9aa1f86e10376 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 26 May 2015 02:24:54 +0800 Subject: [PATCH 288/345] Create combination-sum-iii.py --- Python/combination-sum-iii.py | 45 +++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 Python/combination-sum-iii.py diff --git a/Python/combination-sum-iii.py b/Python/combination-sum-iii.py new file mode 100644 index 000000000..eb2ce4407 --- /dev/null +++ b/Python/combination-sum-iii.py @@ -0,0 +1,45 @@ +# Time: O(C(n, k)) +# Space: O(k) +# +# Find all possible combinations of k numbers that add up to a number n, +# given that only numbers from 1 to 9 can be used and each combination should be a unique set of numbers. +# +# Ensure that numbers within the set are sorted in ascending order. +# +# +# Example 1: +# +# Input: k = 3, n = 7 +# +# Output: +# +# [[1,2,4]] +# +# Example 2: +# +# Input: k = 3, n = 9 +# +# Output: +# +# [[1,2,6], [1,3,5], [2,3,4]] +# + +class Solution: + # @param {integer} k + # @param {integer} n + # @return {integer[][]} + def combinationSum3(self, k, n): + result = [] + self.combinationSumRecu(result, [], 1, k, n) + return result + + def combinationSumRecu(self, result, intermediate, start, k, target): + if k == 0 and target == 0: + result.append(list(intermediate)) + elif k < 0: + return + while start < 10 and start * k + k * (k - 1) / 2 <= target: + intermediate.append(start) + self.combinationSumRecu(result, intermediate, start + 1, k - 1, target - start) + intermediate.pop() + start += 1 From 48615995d7022a5bb83084fe44e85736551c9382 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 26 May 2015 02:28:32 +0800 Subject: [PATCH 289/345] Create contains-duplicate.py --- Python/contains-duplicate.py | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 Python/contains-duplicate.py diff --git a/Python/contains-duplicate.py b/Python/contains-duplicate.py new file mode 100644 index 000000000..16c26a3c3 --- /dev/null +++ b/Python/contains-duplicate.py @@ -0,0 +1,13 @@ +# Time: O(n) +# Space: O(n) +# +# 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. +# + +class Solution: + # @param {integer[]} nums + # @return {boolean} + def containsDuplicate(self, nums): + return len(nums) > len(set(nums)) From 1c2bfe859e1505202de5bcece088154c5bd5c1a8 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 26 May 2015 02:31:01 +0800 Subject: [PATCH 290/345] Create contains-duplicate.cpp --- C++/contains-duplicate.cpp | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 C++/contains-duplicate.cpp diff --git a/C++/contains-duplicate.cpp b/C++/contains-duplicate.cpp new file mode 100644 index 000000000..5d3abe2a7 --- /dev/null +++ b/C++/contains-duplicate.cpp @@ -0,0 +1,10 @@ +// Time: O(n) +// Space: O(n) + +class Solution { +public: + bool containsDuplicate(vector& nums) { + unordered_set nums_set(nums.begin(), nums.end()); + return nums_set.size() != nums.size(); + } +}; From 618769d421f87bbeea4e121c917732d7655fd6ce Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 26 May 2015 02:32:36 +0800 Subject: [PATCH 291/345] Update contains-duplicate.cpp --- C++/contains-duplicate.cpp | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/C++/contains-duplicate.cpp b/C++/contains-duplicate.cpp index 5d3abe2a7..524f4067c 100644 --- a/C++/contains-duplicate.cpp +++ b/C++/contains-duplicate.cpp @@ -8,3 +8,13 @@ class Solution { return nums_set.size() != nums.size(); } }; + +// Time: O(nlogn) +// Space: O(1) +class Solution2 { +public: + bool containsDuplicate(vector& nums) { + sort(nums.begin(), nums.end()); + return unique(nums.begin(), nums.end()) != nums.end(); + } +}; From 5ebacaa9152398d95af6c36486047336955904b2 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 26 May 2015 02:36:30 +0800 Subject: [PATCH 292/345] Update README.md --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 3f017a68c..9c027339d 100644 --- a/README.md +++ b/README.md @@ -177,6 +177,7 @@ Shell 187| [Repeated DNA Sequences](https://leetcode.com/problems/repeated-dna-sequences/) | [Python](./Python/repeated-dna-sequences.py) | _O(n)_ | _O(n)_ | Medium || 202| [Happy Number](https://leetcode.com/problems/happy-number/) | [Python](./Python/happy-number.py) | _O(k)_ | _O(k)_ | Easy || 204| [Count Primes](https://leetcode.com/problems/count-primes/) | [Python](./Python/count-primes.py) | _O(n)_ | _O(n)_ | Easy || +217| [Contains Duplicate](https://leetcode.com/problems/contains-duplicate/) | [C++](./C++/contains-duplicate.cpp) [Python](./Python/contains-duplicate.py) | _O(n)_ | _O(n)_ | Easy || --- @@ -313,6 +314,7 @@ Shell 131| [Palindrome Partitioning](https://leetcode.com/problems/palindrome-partitioning/) | [Python](./Python/palindrome-partitioning.py) | _O(n^2)_ ~ _O(2^n)_ | _O(n^2)_ | Medium || 199| [Binary Tree Right Side View](https://leetcode.com/problems/binary-tree-right-side-view/) | [Python](./Python/binary-tree-right-side-view.py) | _O(n)_ | _O(h)_ | Medium || 200| [Number of Islands](https://leetcode.com/problems/number-of-islands/) | [Python](./Python/number-of-islands.py) | _O(m * n)_ | _O(m * n)_| Medium || +216| [Combination Sum III](https://leetcode.com/problems/combination-sum-iii/)| [C++](./C++/combination-sum-iii.cpp) [Python](./Python/combination-sum-iii.py) | _O(C(n, k))_ | _O(k)_ | Medium || --- From e779ec633c0a6fe8f05da7ee881024fd1d4289b7 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 26 May 2015 02:42:48 +0800 Subject: [PATCH 293/345] Update kth-largest-element-in-an-array.py --- Python/kth-largest-element-in-an-array.py | 1 - 1 file changed, 1 deletion(-) diff --git a/Python/kth-largest-element-in-an-array.py b/Python/kth-largest-element-in-an-array.py index fe0dfa31b..fe6b8d9c0 100644 --- a/Python/kth-largest-element-in-an-array.py +++ b/Python/kth-largest-element-in-an-array.py @@ -19,7 +19,6 @@ def findKthLargest(self, nums, k): else: # new_pivot_idx < k - 1. left = new_pivot_idx + 1 - def PartitionAroundPivot(self, left, right, pivot_idx, nums): pivot_value = nums[pivot_idx] new_pivot_idx = left From 5f1fe01496c32768edc681a077586dc7eea9de91 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 26 May 2015 14:22:55 +0800 Subject: [PATCH 294/345] Create the-skyline-problem.cpp --- C++/the-skyline-problem.cpp | 47 +++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 C++/the-skyline-problem.cpp diff --git a/C++/the-skyline-problem.cpp b/C++/the-skyline-problem.cpp new file mode 100644 index 000000000..83c09ae44 --- /dev/null +++ b/C++/the-skyline-problem.cpp @@ -0,0 +1,47 @@ +// Time: O(nlogn) +// Space: O(n) + +class Solution { +public: + vector > getSkyline(vector >& buildings) { + map > start_point_to_heights; + map > end_point_to_heights; + set points; + + for (int i = 0; i < buildings.size(); ++i) { + start_point_to_heights[buildings[i][0]].push_back(buildings[i][2]); + end_point_to_heights[buildings[i][1]].push_back(buildings[i][2]); + points.insert(buildings[i][0]); + points.insert(buildings[i][1]); + } + + vector > res; + map height_to_count; + int curr_max = 0; + // Enumerate each point in increasing order. + for (auto it = points.begin(); it != points.end(); ++it) { + vector start_point_heights = start_point_to_heights[*it]; + vector end_point_heights = end_point_to_heights[*it]; + + for (int i = 0; i < start_point_heights.size(); ++i) { + ++height_to_count[start_point_heights[i]]; + } + + for (int i = 0; i < end_point_heights.size(); ++i) { + --height_to_count[end_point_heights[i]]; + if (height_to_count[end_point_heights[i]] == 0) { + height_to_count.erase(end_point_heights[i]); + } + } + + if (height_to_count.size() == 0) { + curr_max = 0; + res.emplace_back(move(make_pair(*it, curr_max))); + } else if (curr_max != height_to_count.rbegin()->first) { + curr_max = height_to_count.rbegin()->first; + res.emplace_back(move(make_pair(*it, curr_max))); + } + } + return res; + } +}; From 54c34fbaf800e3888cfc3d746519537df421a5e5 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 26 May 2015 14:33:25 +0800 Subject: [PATCH 295/345] Update README.md --- README.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 9c027339d..bb7198065 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ LeetCode ======== -Up to date (2015-05-25), there are `201` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2015-05-26), there are `202` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://leetcode.com/). The number of problems is increasing recently. -Here is the classification of all `217` problems. +Here is the classification of all `218` problems. For extra problems and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repo. I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "📖" means you have to buy the book from LeetCode. ) @@ -218,6 +218,7 @@ Shell 148| [Sort List](https://leetcode.com/problems/sort-list/) | [Python](./Python/sort-list.py) | _O(nlogn)_ | _O(logn)_ | Medium || 164| [Maximum Gap](https://leetcode.com/problems/maximum-gap/) | [Python](./Python/maximum-gap.py)| _O(n)_ | _O(n)_ | Hard || Tricky 179| [Largest Number](https://leetcode.com/problems/largest-number/) | [Python](./Python/largest-number.py) | _O(nlogn)_ | _O(1)_ | Medium || +218| [The Skyline Problem ](https://leetcode.com/problems/the-skyline-problem/) | [C++](./C++/the-skyline-problem.cpp) | _O(nlogn)_ | _O(n)_ | Hard || --- From 5966727834be79570e9ac1ad505a7fe12f942369 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 26 May 2015 14:36:32 +0800 Subject: [PATCH 296/345] Update the-skyline-problem.cpp --- C++/the-skyline-problem.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/C++/the-skyline-problem.cpp b/C++/the-skyline-problem.cpp index 83c09ae44..33a651712 100644 --- a/C++/the-skyline-problem.cpp +++ b/C++/the-skyline-problem.cpp @@ -4,8 +4,8 @@ class Solution { public: vector > getSkyline(vector >& buildings) { - map > start_point_to_heights; - map > end_point_to_heights; + map> start_point_to_heights; + map> end_point_to_heights; set points; for (int i = 0; i < buildings.size(); ++i) { @@ -15,7 +15,7 @@ class Solution { points.insert(buildings[i][1]); } - vector > res; + vector> res; map height_to_count; int curr_max = 0; // Enumerate each point in increasing order. From 9db921aeaa82ab057b813a50731cbd117eae8949 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 26 May 2015 14:36:46 +0800 Subject: [PATCH 297/345] Update the-skyline-problem.cpp --- C++/the-skyline-problem.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/the-skyline-problem.cpp b/C++/the-skyline-problem.cpp index 33a651712..d84014f76 100644 --- a/C++/the-skyline-problem.cpp +++ b/C++/the-skyline-problem.cpp @@ -34,7 +34,7 @@ class Solution { } } - if (height_to_count.size() == 0) { + if (height_to_count.empty()) { curr_max = 0; res.emplace_back(move(make_pair(*it, curr_max))); } else if (curr_max != height_to_count.rbegin()->first) { From 65456320e4feb8e6b5b6ae3e252ae8ff88f19bc3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 26 May 2015 17:38:10 +0800 Subject: [PATCH 298/345] Update the-skyline-problem.cpp --- C++/the-skyline-problem.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/C++/the-skyline-problem.cpp b/C++/the-skyline-problem.cpp index d84014f76..d82b7e74f 100644 --- a/C++/the-skyline-problem.cpp +++ b/C++/the-skyline-problem.cpp @@ -4,15 +4,15 @@ class Solution { public: vector > getSkyline(vector >& buildings) { - map> start_point_to_heights; - map> end_point_to_heights; + unordered_map> start_point_to_heights; + unordered_map> end_point_to_heights; set points; for (int i = 0; i < buildings.size(); ++i) { start_point_to_heights[buildings[i][0]].push_back(buildings[i][2]); end_point_to_heights[buildings[i][1]].push_back(buildings[i][2]); - points.insert(buildings[i][0]); - points.insert(buildings[i][1]); + points.emplace(buildings[i][0]); + points.emplace(buildings[i][1]); } vector> res; From 71f11de1f3b026c1c116194be03c0882321dedb1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 26 May 2015 18:28:02 +0800 Subject: [PATCH 299/345] Update the-skyline-problem.cpp --- C++/the-skyline-problem.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/the-skyline-problem.cpp b/C++/the-skyline-problem.cpp index d82b7e74f..247f48380 100644 --- a/C++/the-skyline-problem.cpp +++ b/C++/the-skyline-problem.cpp @@ -36,10 +36,10 @@ class Solution { if (height_to_count.empty()) { curr_max = 0; - res.emplace_back(move(make_pair(*it, curr_max))); + res.emplace_back(*it, curr_max); } else if (curr_max != height_to_count.rbegin()->first) { curr_max = height_to_count.rbegin()->first; - res.emplace_back(move(make_pair(*it, curr_max))); + res.emplace_back(*it, curr_max); } } return res; From afaa3e8733c4fd88060d2e3b26cb46060fd369d4 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 26 May 2015 19:54:27 +0800 Subject: [PATCH 300/345] Update the-skyline-problem.cpp --- C++/the-skyline-problem.cpp | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/C++/the-skyline-problem.cpp b/C++/the-skyline-problem.cpp index 247f48380..8fccc03dc 100644 --- a/C++/the-skyline-problem.cpp +++ b/C++/the-skyline-problem.cpp @@ -34,11 +34,8 @@ class Solution { } } - if (height_to_count.empty()) { - curr_max = 0; - res.emplace_back(*it, curr_max); - } else if (curr_max != height_to_count.rbegin()->first) { - curr_max = height_to_count.rbegin()->first; + if (height_to_count.empty() || curr_max != height_to_count.rbegin()->first) { + curr_max = height_to_count.empty() ? 0 : height_to_count.rbegin()->first; res.emplace_back(*it, curr_max); } } From b591a8b995b60fb56f9374c4b73e5f38c16d8f7b Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 26 May 2015 20:39:25 +0800 Subject: [PATCH 301/345] Update the-skyline-problem.cpp --- C++/the-skyline-problem.cpp | 99 +++++++++++++++++++++++++++++++++++++ 1 file changed, 99 insertions(+) diff --git a/C++/the-skyline-problem.cpp b/C++/the-skyline-problem.cpp index 8fccc03dc..21b9bdbc8 100644 --- a/C++/the-skyline-problem.cpp +++ b/C++/the-skyline-problem.cpp @@ -1,7 +1,106 @@ // Time: O(nlogn) // Space: O(n) +// Divide and Conquer. class Solution { +public: + enum {start, end, height}; + + vector> getSkyline(vector>& buildings) { + const auto intervals = move(ComputeSkylineInInterval(buildings, 0, buildings.size())); + + vector> res; + int last_end = -1; + for (const auto& interval : intervals) { + if (last_end != -1 && last_end < interval[start]) { + res.emplace_back(last_end, 0); + } + res.emplace_back(interval[start], interval[height]); + last_end = interval[end]; + } + if (last_end != -1) { + res.emplace_back(last_end, 0); + } + return res; + } + + // Divide and Conquer. + vector> ComputeSkylineInInterval(const vector>& buildings, + int left_endpoint, int right_endpoint) { + if (right_endpoint - left_endpoint <= 1) { // 0 or 1 skyline, just copy it. + return {buildings.cbegin() + left_endpoint, + buildings.cbegin() + right_endpoint}; + } + int mid = left_endpoint + ((right_endpoint - left_endpoint) / 2); + auto left_skyline = move(ComputeSkylineInInterval(buildings, left_endpoint, mid)); + auto right_skyline = move(ComputeSkylineInInterval(buildings, mid, right_endpoint)); + return MergeSkylines(left_skyline, right_skyline); + } + + // Merge Sort + vector> MergeSkylines(vector>& left_skyline, vector>& right_skyline) { + int i = 0, j = 0; + vector> merged; + + while (i < left_skyline.size() && j < right_skyline.size()) { + if (left_skyline[i][end] < right_skyline[j][start]) { + merged.emplace_back(move(left_skyline[i++])); + } else if (right_skyline[j][end] < left_skyline[i][start]) { + merged.emplace_back(move(right_skyline[j++])); + } else if (left_skyline[i][start] <= right_skyline[j][start]) { + MergeIntersectSkylines(merged, left_skyline[i], i, + right_skyline[j], j); + } else { // left_skyline[i][start] > right_skyline[j][start]. + MergeIntersectSkylines(merged, right_skyline[j], j, + left_skyline[i], i); + } + } + + // Insert the remaining skylines. + merged.insert(merged.end(), left_skyline.begin() + i, left_skyline.end()); + merged.insert(merged.end(), right_skyline.begin() + j, right_skyline.end()); + return merged; + } + + // a[start] <= b[start] + void MergeIntersectSkylines(vector>& merged, vector& a, int& a_idx, + vector& b, int& b_idx) { + if (a[end] <= b[end]) { + if (a[height] > b[height]) { // |aaa| + if (b[end] != a[end]) { // |abb|b + b[start] = a[end]; + merged.emplace_back(move(a)), ++a_idx; + } else { // aaa + ++b_idx; // abb + } + } else if (a[height] == b[height]) { // abb + b[start] = a[start], ++a_idx; // abb + } else { // a[height] < b[height]. + if (a[start] != b[start]) { // bb + merged.emplace_back(move(vector{a[start], b[start], a[height]})); // |a|bb + } + ++a_idx; + } + } else { // a[end] > b[end]. + if (a[height] >= b[height]) { // aaaa + ++b_idx; // abba + } else { + // |bb| + // |a||bb|a + if (a[start] != b[start]) { + merged.emplace_back(move(vector{a[start], b[start], a[height]})); + } + a[start] = b[end]; + merged.emplace_back(move(b)), ++b_idx; + } + } + } +}; + +// Time: O(nlogn) +// Space: O(n) +// BST Solution. +class Solution2 { public: vector > getSkyline(vector >& buildings) { unordered_map> start_point_to_heights; From c8e1270eba611f8fb94888814584dd288235c70f Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 26 May 2015 20:40:58 +0800 Subject: [PATCH 302/345] Update the-skyline-problem.cpp --- C++/the-skyline-problem.cpp | 92 ++++++++++++++++++------------------- 1 file changed, 46 insertions(+), 46 deletions(-) diff --git a/C++/the-skyline-problem.cpp b/C++/the-skyline-problem.cpp index 21b9bdbc8..b831a4f0f 100644 --- a/C++/the-skyline-problem.cpp +++ b/C++/the-skyline-problem.cpp @@ -1,7 +1,52 @@ // Time: O(nlogn) // Space: O(n) -// Divide and Conquer. +// BST solution. +class Solution { +public: + vector > getSkyline(vector >& buildings) { + unordered_map> start_point_to_heights; + unordered_map> end_point_to_heights; + set points; + + for (int i = 0; i < buildings.size(); ++i) { + start_point_to_heights[buildings[i][0]].push_back(buildings[i][2]); + end_point_to_heights[buildings[i][1]].push_back(buildings[i][2]); + points.emplace(buildings[i][0]); + points.emplace(buildings[i][1]); + } + + vector> res; + map height_to_count; + int curr_max = 0; + // Enumerate each point in increasing order. + for (auto it = points.begin(); it != points.end(); ++it) { + vector start_point_heights = start_point_to_heights[*it]; + vector end_point_heights = end_point_to_heights[*it]; + + for (int i = 0; i < start_point_heights.size(); ++i) { + ++height_to_count[start_point_heights[i]]; + } + + for (int i = 0; i < end_point_heights.size(); ++i) { + --height_to_count[end_point_heights[i]]; + if (height_to_count[end_point_heights[i]] == 0) { + height_to_count.erase(end_point_heights[i]); + } + } + + if (height_to_count.empty() || curr_max != height_to_count.rbegin()->first) { + curr_max = height_to_count.empty() ? 0 : height_to_count.rbegin()->first; + res.emplace_back(*it, curr_max); + } + } + return res; + } +}; + +// Time: O(nlogn) +// Space: O(n) +// Divide and conquer solution. class Solution { public: enum {start, end, height}; @@ -96,48 +141,3 @@ class Solution { } } }; - -// Time: O(nlogn) -// Space: O(n) -// BST Solution. -class Solution2 { -public: - vector > getSkyline(vector >& buildings) { - unordered_map> start_point_to_heights; - unordered_map> end_point_to_heights; - set points; - - for (int i = 0; i < buildings.size(); ++i) { - start_point_to_heights[buildings[i][0]].push_back(buildings[i][2]); - end_point_to_heights[buildings[i][1]].push_back(buildings[i][2]); - points.emplace(buildings[i][0]); - points.emplace(buildings[i][1]); - } - - vector> res; - map height_to_count; - int curr_max = 0; - // Enumerate each point in increasing order. - for (auto it = points.begin(); it != points.end(); ++it) { - vector start_point_heights = start_point_to_heights[*it]; - vector end_point_heights = end_point_to_heights[*it]; - - for (int i = 0; i < start_point_heights.size(); ++i) { - ++height_to_count[start_point_heights[i]]; - } - - for (int i = 0; i < end_point_heights.size(); ++i) { - --height_to_count[end_point_heights[i]]; - if (height_to_count[end_point_heights[i]] == 0) { - height_to_count.erase(end_point_heights[i]); - } - } - - if (height_to_count.empty() || curr_max != height_to_count.rbegin()->first) { - curr_max = height_to_count.empty() ? 0 : height_to_count.rbegin()->first; - res.emplace_back(*it, curr_max); - } - } - return res; - } -}; From f7b940942c9536aff3f4bf9d48b44460496244c2 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 26 May 2015 20:41:17 +0800 Subject: [PATCH 303/345] Update the-skyline-problem.cpp --- C++/the-skyline-problem.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/the-skyline-problem.cpp b/C++/the-skyline-problem.cpp index b831a4f0f..1b02c5b6a 100644 --- a/C++/the-skyline-problem.cpp +++ b/C++/the-skyline-problem.cpp @@ -47,7 +47,7 @@ class Solution { // Time: O(nlogn) // Space: O(n) // Divide and conquer solution. -class Solution { +class Solution2 { public: enum {start, end, height}; From 75853d17c5ca6c6eb0c8be2075b0cd812a2f9eab Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 26 May 2015 20:44:17 +0800 Subject: [PATCH 304/345] Update the-skyline-problem.cpp --- C++/the-skyline-problem.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/the-skyline-problem.cpp b/C++/the-skyline-problem.cpp index 1b02c5b6a..d5ca6952b 100644 --- a/C++/the-skyline-problem.cpp +++ b/C++/the-skyline-problem.cpp @@ -10,8 +10,8 @@ class Solution { set points; for (int i = 0; i < buildings.size(); ++i) { - start_point_to_heights[buildings[i][0]].push_back(buildings[i][2]); - end_point_to_heights[buildings[i][1]].push_back(buildings[i][2]); + start_point_to_heights[buildings[i][0]].emplace_back(buildings[i][2]); + end_point_to_heights[buildings[i][1]].emplace_back(buildings[i][2]); points.emplace(buildings[i][0]); points.emplace(buildings[i][1]); } From b9699108393c4d7ed734f719ca425a2789831758 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 26 May 2015 20:44:54 +0800 Subject: [PATCH 305/345] Update the-skyline-problem.cpp --- C++/the-skyline-problem.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/the-skyline-problem.cpp b/C++/the-skyline-problem.cpp index d5ca6952b..bf59a6e2d 100644 --- a/C++/the-skyline-problem.cpp +++ b/C++/the-skyline-problem.cpp @@ -121,7 +121,7 @@ class Solution2 { } else if (a[height] == b[height]) { // abb b[start] = a[start], ++a_idx; // abb } else { // a[height] < b[height]. - if (a[start] != b[start]) { // bb + if (a[start] != b[start]) { // bb merged.emplace_back(move(vector{a[start], b[start], a[height]})); // |a|bb } ++a_idx; From 9cc2e468bf5a81f436df417edb20a945759d21d6 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 26 May 2015 22:19:24 +0800 Subject: [PATCH 306/345] Create the-skyline-problem.py --- Python/the-skyline-problem.py | 114 ++++++++++++++++++++++++++++++++++ 1 file changed, 114 insertions(+) create mode 100644 Python/the-skyline-problem.py diff --git a/Python/the-skyline-problem.py b/Python/the-skyline-problem.py new file mode 100644 index 000000000..118fa8478 --- /dev/null +++ b/Python/the-skyline-problem.py @@ -0,0 +1,114 @@ +# Time: O(nlogn) +# Space: O(n) +# A city's skyline is the outer contour of the silhouette formed +# by all the buildings in that city when viewed from a distance. +# Now suppose you are given the locations and height of all the +# buildings as shown on a cityscape photo (Figure A), write a +# program to output the skyline formed by these buildings +# collectively (Figure B). +# +# The geometric information of each building is represented by a +# triplet of integers [Li, Ri, Hi], where Li and Ri are the x +# coordinates of the left and right edge of the ith building, +# respectively, and Hi is its height. It is guaranteed that 0 <= Li, +# Ri <= INT_MAX, 0 < Hi <= INT_MAX, and Ri - Li > 0. You may assume +# all buildings are perfect rectangles grounded on an absolutely +# flat surface at height 0. +# +# Notes: +# +# The number of buildings in any input list is guaranteed to be +# in the range [0, 10000]. +# The input list is already sorted in ascending order by the +# left x position Li. +# The output list must be sorted by the x position. +# There must be no consecutive horizontal lines of equal height +# in the output skyline. +# For instance, [...[2 3], [4 5], [7 5], [11 5], [12 7]...] is +# not acceptable; +# the three lines of height 5 should be merged into one +# in the final output as such: [...[2 3], [4 5], [12 7], ...] +# + +# Divide and conquer solution. +start, end, height = 0, 1, 2 +class Solution: + # @param {integer[][]} buildings + # @return {integer[][]} + def getSkyline(self, buildings): + intervals = self.ComputeSkylineInInterval(buildings, 0, len(buildings)) + + res = [] + last_end = -1 + for interval in intervals: + if last_end != -1 and last_end < interval[start]: + res.append([last_end, 0]) + res.append([interval[start], interval[height]]) + last_end = interval[end] + if last_end != -1: + res.append([last_end, 0]) + + return res + + # Divide and Conquer. + def ComputeSkylineInInterval(self, buildings, left_endpoint, right_endpoint): + if right_endpoint - left_endpoint <= 1: + return buildings[left_endpoint:right_endpoint] + mid = left_endpoint + ((right_endpoint - left_endpoint) / 2) + left_skyline = self.ComputeSkylineInInterval(buildings, left_endpoint, mid) + right_skyline = self.ComputeSkylineInInterval(buildings, mid, right_endpoint) + return self.MergeSkylines(left_skyline, right_skyline) + + # Merge Sort. + def MergeSkylines(self, left_skyline, right_skyline): + i, j = 0, 0 + merged = [] + + while i < len(left_skyline) and j < len(right_skyline): + if left_skyline[i][end] < right_skyline[j][start]: + merged.append(left_skyline[i]) + i += 1 + elif right_skyline[j][end] < left_skyline[i][start]: + merged.append(right_skyline[j]) + j += 1 + elif left_skyline[i][start] <= right_skyline[j][start]: + i, j = self.MergeIntersectSkylines(merged, left_skyline[i], i,\ + right_skyline[j], j) + else: # left_skyline[i][start] > right_skyline[j][start]. + j, i = self.MergeIntersectSkylines(merged, right_skyline[j], j, \ + left_skyline[i], i) + + # Insert the remaining skylines. + merged += left_skyline[i:] + merged += right_skyline[j:] + return merged + + # a[start] <= b[start] + def MergeIntersectSkylines(self, merged, a, a_idx, b, b_idx): + if a[end] <= b[end]: + if a[height] > b[height]: # |aaa| + if b[end] != a[end]: # |abb|b + b[start] = a[end] + merged.append(a) + a_idx += 1 + else: # aaa + b_idx += 1 # abb + elif a[height] == b[height]: # abb + b[start] = a[start] # abb + a_idx += 1 + else: # a[height] < b[height]. + if a[start] != b[start]: # bb + merged.append([a[start], b[start], a[height]]) # |a|bb + a_idx += 1 + else: # a[end] > b[end]. + if a[height] >= b[height]: # aaaa + b_idx += 1 # abba + else: + # |bb| + # |a||bb|a + if a[start] != b[start]: + merged.append([a[start], b[start], a[height]]) + a[start] = b[end] + merged.append(b) + b_idx += 1 + return a_idx, b_idx From e6db0ba6add550423f236ab90f6ac10803158b7f Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 26 May 2015 22:19:52 +0800 Subject: [PATCH 307/345] Update the-skyline-problem.py --- Python/the-skyline-problem.py | 1 + 1 file changed, 1 insertion(+) diff --git a/Python/the-skyline-problem.py b/Python/the-skyline-problem.py index 118fa8478..e7c0d00cf 100644 --- a/Python/the-skyline-problem.py +++ b/Python/the-skyline-problem.py @@ -1,5 +1,6 @@ # Time: O(nlogn) # Space: O(n) +# # A city's skyline is the outer contour of the silhouette formed # by all the buildings in that city when viewed from a distance. # Now suppose you are given the locations and height of all the From 3b85415fc6f71b43b52028dea0922df11bb993d4 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 26 May 2015 22:21:09 +0800 Subject: [PATCH 308/345] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index bb7198065..b60b09a10 100644 --- a/README.md +++ b/README.md @@ -218,7 +218,7 @@ Shell 148| [Sort List](https://leetcode.com/problems/sort-list/) | [Python](./Python/sort-list.py) | _O(nlogn)_ | _O(logn)_ | Medium || 164| [Maximum Gap](https://leetcode.com/problems/maximum-gap/) | [Python](./Python/maximum-gap.py)| _O(n)_ | _O(n)_ | Hard || Tricky 179| [Largest Number](https://leetcode.com/problems/largest-number/) | [Python](./Python/largest-number.py) | _O(nlogn)_ | _O(1)_ | Medium || -218| [The Skyline Problem ](https://leetcode.com/problems/the-skyline-problem/) | [C++](./C++/the-skyline-problem.cpp) | _O(nlogn)_ | _O(n)_ | Hard || +218| [The Skyline Problem ](https://leetcode.com/problems/the-skyline-problem/) | [C++](./C++/the-skyline-problem.cpp) [Python](./Python/the-skyline-problem.py) | _O(nlogn)_ | _O(n)_ | Hard || --- From 0655c5fe6af6a4938d55884af5b03a9cb7259c76 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 26 May 2015 22:22:20 +0800 Subject: [PATCH 309/345] Update the-skyline-problem.py --- Python/the-skyline-problem.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/the-skyline-problem.py b/Python/the-skyline-problem.py index e7c0d00cf..d7e17a89c 100644 --- a/Python/the-skyline-problem.py +++ b/Python/the-skyline-problem.py @@ -74,10 +74,10 @@ def MergeSkylines(self, left_skyline, right_skyline): j += 1 elif left_skyline[i][start] <= right_skyline[j][start]: i, j = self.MergeIntersectSkylines(merged, left_skyline[i], i,\ - right_skyline[j], j) + right_skyline[j], j) else: # left_skyline[i][start] > right_skyline[j][start]. j, i = self.MergeIntersectSkylines(merged, right_skyline[j], j, \ - left_skyline[i], i) + left_skyline[i], i) # Insert the remaining skylines. merged += left_skyline[i:] From 1c9e2a76ced71510faae87a066bde5ea1639080b Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 26 May 2015 22:23:14 +0800 Subject: [PATCH 310/345] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index b60b09a10..36edc841f 100644 --- a/README.md +++ b/README.md @@ -218,7 +218,7 @@ Shell 148| [Sort List](https://leetcode.com/problems/sort-list/) | [Python](./Python/sort-list.py) | _O(nlogn)_ | _O(logn)_ | Medium || 164| [Maximum Gap](https://leetcode.com/problems/maximum-gap/) | [Python](./Python/maximum-gap.py)| _O(n)_ | _O(n)_ | Hard || Tricky 179| [Largest Number](https://leetcode.com/problems/largest-number/) | [Python](./Python/largest-number.py) | _O(nlogn)_ | _O(1)_ | Medium || -218| [The Skyline Problem ](https://leetcode.com/problems/the-skyline-problem/) | [C++](./C++/the-skyline-problem.cpp) [Python](./Python/the-skyline-problem.py) | _O(nlogn)_ | _O(n)_ | Hard || +218| [The Skyline Problem ](https://leetcode.com/problems/the-skyline-problem/) | [C++](./C++/the-skyline-problem.cpp) [Python](./Python/the-skyline-problem.py) | _O(nlogn)_ | _O(n)_ | Hard | Sort, BST| --- From 093d513c56ccfd8ba5b4ab0a14f4f76e97a5b9e8 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 26 May 2015 22:26:56 +0800 Subject: [PATCH 311/345] Update the-skyline-problem.cpp --- C++/the-skyline-problem.cpp | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/C++/the-skyline-problem.cpp b/C++/the-skyline-problem.cpp index bf59a6e2d..7e79f2ffb 100644 --- a/C++/the-skyline-problem.cpp +++ b/C++/the-skyline-problem.cpp @@ -9,20 +9,20 @@ class Solution { unordered_map> end_point_to_heights; set points; - for (int i = 0; i < buildings.size(); ++i) { - start_point_to_heights[buildings[i][0]].emplace_back(buildings[i][2]); - end_point_to_heights[buildings[i][1]].emplace_back(buildings[i][2]); - points.emplace(buildings[i][0]); - points.emplace(buildings[i][1]); + for (const auto& building : buildings) { + start_point_to_heights[building[0]].emplace_back(building[2]); + end_point_to_heights[building[1]].emplace_back(building[2]); + points.emplace(building[0]); + points.emplace(building[1]); } vector> res; map height_to_count; int curr_max = 0; // Enumerate each point in increasing order. - for (auto it = points.begin(); it != points.end(); ++it) { - vector start_point_heights = start_point_to_heights[*it]; - vector end_point_heights = end_point_to_heights[*it]; + for (const auto& point : points) { + vector start_point_heights = start_point_to_heights[point]; + vector end_point_heights = end_point_to_heights[point]; for (int i = 0; i < start_point_heights.size(); ++i) { ++height_to_count[start_point_heights[i]]; @@ -37,7 +37,7 @@ class Solution { if (height_to_count.empty() || curr_max != height_to_count.rbegin()->first) { curr_max = height_to_count.empty() ? 0 : height_to_count.rbegin()->first; - res.emplace_back(*it, curr_max); + res.emplace_back(point, curr_max); } } return res; From b16d243ee87ad779270122403c26130ed9b6e7cc Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 26 May 2015 22:33:04 +0800 Subject: [PATCH 312/345] Update the-skyline-problem.cpp --- C++/the-skyline-problem.cpp | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/C++/the-skyline-problem.cpp b/C++/the-skyline-problem.cpp index 7e79f2ffb..1e60ce4a5 100644 --- a/C++/the-skyline-problem.cpp +++ b/C++/the-skyline-problem.cpp @@ -24,14 +24,14 @@ class Solution { vector start_point_heights = start_point_to_heights[point]; vector end_point_heights = end_point_to_heights[point]; - for (int i = 0; i < start_point_heights.size(); ++i) { - ++height_to_count[start_point_heights[i]]; + for (const auto& height : start_point_heights) { + ++height_to_count[height]; } - for (int i = 0; i < end_point_heights.size(); ++i) { - --height_to_count[end_point_heights[i]]; - if (height_to_count[end_point_heights[i]] == 0) { - height_to_count.erase(end_point_heights[i]); + for (const auto& height : end_point_heights) { + --height_to_count[height]; + if (height_to_count[height] == 0) { + height_to_count.erase(height); } } From 1c89d4f7fda7ce414f4d703e5a0021fb399c9c24 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 26 May 2015 22:34:53 +0800 Subject: [PATCH 313/345] Update the-skyline-problem.cpp --- C++/the-skyline-problem.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/the-skyline-problem.cpp b/C++/the-skyline-problem.cpp index 1e60ce4a5..2b459b17e 100644 --- a/C++/the-skyline-problem.cpp +++ b/C++/the-skyline-problem.cpp @@ -35,8 +35,8 @@ class Solution { } } - if (height_to_count.empty() || curr_max != height_to_count.rbegin()->first) { - curr_max = height_to_count.empty() ? 0 : height_to_count.rbegin()->first; + if (height_to_count.empty() || curr_max != height_to_count.crbegin()->first) { + curr_max = height_to_count.empty() ? 0 : height_to_count.crbegin()->first; res.emplace_back(point, curr_max); } } From 020d2af83e1b42fe8212a57696638818f5b5b8ca Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 26 May 2015 22:38:01 +0800 Subject: [PATCH 314/345] Update the-skyline-problem.cpp --- C++/the-skyline-problem.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/the-skyline-problem.cpp b/C++/the-skyline-problem.cpp index 2b459b17e..0c25ba545 100644 --- a/C++/the-skyline-problem.cpp +++ b/C++/the-skyline-problem.cpp @@ -7,7 +7,7 @@ class Solution { vector > getSkyline(vector >& buildings) { unordered_map> start_point_to_heights; unordered_map> end_point_to_heights; - set points; + set points; // Ordered, no duplicated. for (const auto& building : buildings) { start_point_to_heights[building[0]].emplace_back(building[2]); @@ -17,7 +17,7 @@ class Solution { } vector> res; - map height_to_count; + map height_to_count; // bst. int curr_max = 0; // Enumerate each point in increasing order. for (const auto& point : points) { From e5922d120b039f0dae494e74f4f418ddae23e6d5 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 26 May 2015 22:38:53 +0800 Subject: [PATCH 315/345] Update the-skyline-problem.cpp --- C++/the-skyline-problem.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/the-skyline-problem.cpp b/C++/the-skyline-problem.cpp index 0c25ba545..14efa0746 100644 --- a/C++/the-skyline-problem.cpp +++ b/C++/the-skyline-problem.cpp @@ -7,7 +7,7 @@ class Solution { vector > getSkyline(vector >& buildings) { unordered_map> start_point_to_heights; unordered_map> end_point_to_heights; - set points; // Ordered, no duplicated. + set points; // Ordered, no duplicates. for (const auto& building : buildings) { start_point_to_heights[building[0]].emplace_back(building[2]); @@ -17,7 +17,7 @@ class Solution { } vector> res; - map height_to_count; // bst. + map height_to_count; // BST. int curr_max = 0; // Enumerate each point in increasing order. for (const auto& point : points) { From a9a3595ebab99cafa9c9ee22a05f05ece9213fbf Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 26 May 2015 23:43:28 +0800 Subject: [PATCH 316/345] Update the-skyline-problem.cpp --- C++/the-skyline-problem.cpp | 42 +++++++++++++++++++------------------ 1 file changed, 22 insertions(+), 20 deletions(-) diff --git a/C++/the-skyline-problem.cpp b/C++/the-skyline-problem.cpp index 14efa0746..51530222d 100644 --- a/C++/the-skyline-problem.cpp +++ b/C++/the-skyline-problem.cpp @@ -4,37 +4,39 @@ // BST solution. class Solution { public: + enum {start, end, height} ; + + struct Endpoint { + int height; + bool isStart; + }; + vector > getSkyline(vector >& buildings) { - unordered_map> start_point_to_heights; - unordered_map> end_point_to_heights; - set points; // Ordered, no duplicates. - + map> point_to_height; // Ordered, no duplicates. for (const auto& building : buildings) { - start_point_to_heights[building[0]].emplace_back(building[2]); - end_point_to_heights[building[1]].emplace_back(building[2]); - points.emplace(building[0]); - points.emplace(building[1]); + point_to_height[building[start]].emplace_back(Endpoint{building[height], true}); + point_to_height[building[end]].emplace_back(Endpoint{building[height], false}); } vector> res; map height_to_count; // BST. int curr_max = 0; // Enumerate each point in increasing order. - for (const auto& point : points) { - vector start_point_heights = start_point_to_heights[point]; - vector end_point_heights = end_point_to_heights[point]; + for (auto& kvp : point_to_height) { + auto& point = kvp.first; + auto& heights = kvp.second; - for (const auto& height : start_point_heights) { - ++height_to_count[height]; - } - - for (const auto& height : end_point_heights) { - --height_to_count[height]; - if (height_to_count[height] == 0) { - height_to_count.erase(height); + for (const auto& h : heights) { + if (h.isStart) { + ++height_to_count[h.height]; + } else { + --height_to_count[h.height]; + if (height_to_count[h.height] == 0) { + height_to_count.erase(h.height); + } } } - + if (height_to_count.empty() || curr_max != height_to_count.crbegin()->first) { curr_max = height_to_count.empty() ? 0 : height_to_count.crbegin()->first; res.emplace_back(point, curr_max); From 1eed7bd98f8f04563bd09d169b5d9e95ccd98a2c Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 27 May 2015 00:17:35 +0800 Subject: [PATCH 317/345] Update README.md --- README.md | 44 ++++++++++++++++++++++---------------------- 1 file changed, 22 insertions(+), 22 deletions(-) diff --git a/README.md b/README.md index 36edc841f..52c4c2485 100644 --- a/README.md +++ b/README.md @@ -48,7 +48,7 @@ Shell --- ##Bit Manipulation - # | Problem | Solution | Time | Space | Difficulty | Tag | Notes + # | Problem | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 136 | [Single Number](https://leetcode.com/problems/single-number/) | [Python](./Python/single-number.py) | _O(n)_ | _O(1)_ | Medium || 137 | [Single Number II](https://leetcode.com/problems/single-number-ii/) | [Python](./Python/single-number-ii.py) | _O(n)_ | _O(1)_ | Medium || @@ -60,7 +60,7 @@ Shell ##Array - # | Problem | Solution | Time | Space | Difficulty | Tag | Notes + # | Problem | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 15 | [3 Sum](https://leetcode.com/problems/3sum/) | [Python](./Python/3sum.py) | _O(n^2)_ | _O(1)_ | Medium || 16 | [3 Sum Closest](https://leetcode.com/problems/3sum-closest/) | [Python](./Python/3sum-closest.py)| _O(n^2)_ | _O(1)_ | Medium || @@ -89,7 +89,7 @@ Shell --- ##String - # | Problem | Solution | Time | Space | Difficulty | Tag | Notes + # | Problem | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 5| [Longest Palindromic Substring](https://leetcode.com/problems/longest-palindromic-substring/) | [Python](./Python/longest-palindromic-substring.py) | _O(n)_ | _O(n)_ | Medium || `Manacher's Algorithm` 6| [ZigZag Conversion](https://leetcode.com/problems/zigzag-conversion/) | [Python](./Python/zigzag-conversion.py) | _O(n)_ | _O(1)_ | Easy || @@ -112,7 +112,7 @@ Shell --- ##Linked List - # | Problem | Solution | Time | Space | Difficulty | Tag | Notes + # | Problem | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 2| [Add Two Numbers](https://leetcode.com/problems/add-two-numbers/) | [Python](./Python/add-two-numbers.py) | _O(n)_ | _O(1)_ | Medium || 24| [Swap Nodes in Pairs](https://leetcode.com/problems/swap-nodes-in-pairs/)| [Python](./Python/swap-nodes-in-pairs.py) | _O(n)_ | _O(1)_ | Medium || @@ -129,7 +129,7 @@ Shell --- ##Stack - # | Problem | Solution | Time | Space | Difficulty | Tag | Notes + # | Problem | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 20| [Valid Parentheses](https://leetcode.com/problems/valid-parentheses/)| [Python](./Python/valid-parentheses.py) | _O(n)_ | _O(n)_ | Easy || 32| [Longest Valid Parentheses](https://leetcode.com/problems/longest-valid-parentheses/)| [Python](./Python/longest-valid-parentheses.py) | _O(n)_ | _O(1)_ | Hard || @@ -142,14 +142,14 @@ Shell --- ##Heap - # | Problem | Solution | Time | Space | Difficulty | Tag | Notes + # | Problem | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 23| [Merge k Sorted Lists](https://leetcode.com/problems/merge-k-sorted-lists/) | [Python](./Python/merge-k-sorted-lists.py) | _O(nlogk)_| _O(k)_| Hard || --- ##Tree - # | Problem | Solution | Time | Space | Difficulty | Tag | Notes + # | Problem | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 94 | [Binary Tree Inorder Traversal](https://leetcode.com/problems/binary-tree-inorder-traversal/) | [Python](./Python/binary-tree-inorder-traversal.py) | _O(n)_| _O(1)_| Medium || `Morris Traversal` | 99 | [Recover Binary Search Tree](https://leetcode.com/problems/recover-binary-search-tree/) | [Python](./Python/recover-binary-search-tree.py) | _O(n)_| _O(1)_| Hard || `Morris Traversal` @@ -162,7 +162,7 @@ Shell --- ##Hash Table - # | Problem | Solution | Time | Space | Difficulty | Tag | Notes + # | Problem | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 1| [Two Sum](https://leetcode.com/problems/two-sum/) | [Python](./Python/two-sum.py) | _O(n)_ | _O(n)_ | Medium || 3| [Longest Substring Without Repeating Characters](https://leetcode.com/problems/longest-substring-without-repeating-characters/) | [Python](./Python/longest-substring-without-repeating-characters.py) | _O(n)_ | _O(1)_ | Medium || @@ -182,14 +182,14 @@ Shell --- ##Data Structure - # | Problem | Solution | Time | Space | Difficulty | Tag | Notes + # | Problem | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 146| [LRU Cache](https://leetcode.com/problems/lru-cache/) | [Python](./Python/lru-cache.py) | _O(1)_ | _O(n)_ | Hard || --- ##Math - # | Problem | Solution | Time | Space | Difficulty | Tag | Notes + # | Problem | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 7| [Reverse Integer](https://leetcode.com/problems/reverse-integer/) | [Python](./Python/reverse-integer.py) | _O(logn)_ | _O(1)_ | Easy || 9| [Palindrome Number](https://leetcode.com/problems/palindrome-number/) | [Python](./Python/palindrome-number.py) | _O(1)_ | _O(1)_ | Easy || @@ -207,7 +207,7 @@ Shell --- ##Sort - # | Problem | Solution | Time | Space | Difficulty | Tag | Notes + # | Problem | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 21| [Merge Two Sorted Lists](https://leetcode.com/problems/merge-two-sorted-lists/)| [Python](./Python/merge-two-sorted-lists.py) | _O(n)_ | _O(1)_ | Easy || 56| [Merge Intervals](https://leetcode.com/problems/merge-intervals/)| [Python](./Python/merge-intervals.py) | _O(nlogn)_ | _O(1)_ | Hard || @@ -223,7 +223,7 @@ Shell --- ##Two Pointer - # | Problem | Solution | Time | Space | Difficulty | Tag | Notes + # | Problem | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 19| [Remove Nth Node From End of List](https://leetcode.com/problems/remove-nth-node-from-end-of-list/)| [Python](./Python/remove-nth-node-from-end-of-list.py) | _O(n)_ | _O(1)_ | Easy || 86| [Partition List](https://leetcode.com/problems/partition-list/)| [Python](./Python/partition-list.py) | _O(n)_ | _O(1)_ | Medium || @@ -235,7 +235,7 @@ Shell --- ##Brute Force Search - # | Problem | Solution | Time | Space | Difficulty | Tag | Notes + # | Problem | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 17| [Letter Combinations of a Phone Number](https://leetcode.com/problems/letter-combinations-of-a-phone-number/)| [Python](./Python/letter-combinations-of-a-phone-number.py) | _O(n * 4^n)_ | _O(n)_ | Medium || 46| [Permutations](https://leetcode.com/problems/permutations/)| [Python](./Python/permutations.py) | _O(n!)_ | _O(n)_ | Medium || @@ -246,7 +246,7 @@ Shell --- ##Divide and Conquer - # | Problem | Solution | Time | Space | Difficulty | Tag | Notes + # | Problem | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 95| [Unique Binary Search Trees II](https://leetcode.com/problems/unique-binary-search-trees-ii/) | [Python](./Python/unique-binary-search-trees-ii.py) | _O(4^n / n^(3/2)_ | _O(4^n / n^(3/2)_ | Medium || 98| [Validate Binary Search Tree](https://leetcode.com/problems/validate-binary-search-tree/)|[Python](./Python/validate-binary-search-tree.py)| _O(n)_ | _O(1)_ | Medium || @@ -267,7 +267,7 @@ Shell --- ##Binary Search - # | Problem | Solution | Time | Space | Difficulty | Tag | Notes + # | Problem | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 4| [Median of Two Sorted Arrays](https://leetcode.com/problems/median-of-two-sorted-arrays/) | [Python](./Python/median-of-two-sorted-arrays.py) | _O(log(m + n))_ | _O(1)_ | Hard || 33| [Search in Rotated Sorted Array](https://leetcode.com/problems/search-in-rotated-sorted-array/) | [Python](./Python/search-in-rotated-sorted-array.py) | _O(logn)_ | _O(1)_ | Hard || @@ -284,7 +284,7 @@ Shell --- ##Breadth-First Search - # | Problem | Solution | Time | Space | Difficulty | Tag | Notes + # | Problem | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 102| [Binary Tree Level Order Traversal](https://leetcode.com/problems/binary-tree-level-order-traversal/)| [Python](./Python/binary-tree-level-order-traversal.py)| _O(n)_| _O(n)_| Easy || 107| [Binary Tree Level Order Traversal II](https://leetcode.com/problems/binary-tree-level-order-traversal-ii/)| [Python](./Python/binary-tree-level-order-traversal-ii.py) | _O(n)_| _O(n)_| Easy || @@ -299,7 +299,7 @@ Shell --- ##Depth-First Search - # | Problem | Solution | Time | Space | Difficulty | Tag | Notes + # | Problem | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 22| [Generate Parentheses](https://leetcode.com/problems/generate-parentheses/)| [Python](./Python/generate-parentheses.py)| _O(4^n / n^(3/2))_ | _O(n)_ | Medium || 37| [Sudoku Solver](https://leetcode.com/problems/sudoku-solver/) | [Python](./Python/sudoku-solver.py) | _O((9!)^9)_ | _O(1)_ | Hard || @@ -320,7 +320,7 @@ Shell --- ##Dynamic Programming - # | Problem | Solution | Time | Space | Difficulty | Tag | Notes + # | Problem | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 10| [Regular Expression Matching](https://leetcode.com/problems/regular-expression-matching/) | [Python](./Python/regular-expression-matching.py) | _O(m * n)_ | _O(n)_ | Hard || 53| [Maximum Subarray](https://leetcode.com/problems/maximum-subarray/)|[Python](./Python/maximum-subarray.py)| _O(n)_ | _O(1)_ | Medium || @@ -349,14 +349,14 @@ Shell --- ##Backtracking - # | Problem | Solution | Time | Space | Difficulty | Tag | Notes + # | Problem | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 126| [Word Ladder II](https://leetcode.com/problems/word-ladder-ii/) |[Python](./Python/word-ladder-ii.py) | _O(n * d)_ | _O(d)_ | Hard || --- ##Greedy - # | Problem | Solution | Time | Space | Difficulty | Tag | Notes + # | Problem | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 11| [Container With Most Water](https://leetcode.com/problems/container-with-most-water/)| [Python](./Python/container-with-most-water.py) | _O(n)_ | _O(1)_ | Medium || 42| [Trapping Rain Water](https://leetcode.com/problems/trapping-rain-water/) | [Python](./Python/trapping-rain-water.py) | _O(n)_ | _O(1)_ | Hard || Tricky @@ -371,7 +371,7 @@ Shell --- ##SQL - # | Problem | Solution | Time | Space | Difficulty | Tag | Notes + # | Problem | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 175| [Combine Two Tables](https://leetcode.com/problems/combine-two-tables/) | [MySQL](./MySQL/combine-two-tables.sql) | _O(m + n)_ | _O(m + n)_ | Easy || 176| [Second Highest Salary](https://leetcode.com/problems/second-highest-salary/) | [MySQL](./MySQL/second-highest-salary.sql) | _O(n)_ | _O(1)_ | Easy || @@ -389,7 +389,7 @@ Shell --- ##Shell Script - # | Problem | Solution | Time | Space | Difficulty | Tag | Notes + # | Problem | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 192 | [Word Frequency](https://leetcode.com/problems/word-frequency/) | [Shell](./Shell/word-frequency.sh) | _O(n)_ | _O(k)_ | Medium || 193 | [Valid Phone Numbers](https://leetcode.com/problems/valid-phone-numbers/) | [Shell](./Shell/valid-phone-numbers.sh) | _O(n)_ | _O(1)_ | Easy || From 268468f9943e52a7e3a11241615c957225b0bbfc Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 27 May 2015 13:27:59 +0800 Subject: [PATCH 318/345] Update minimum-size-subarray-sum.py --- Python/minimum-size-subarray-sum.py | 32 +++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/Python/minimum-size-subarray-sum.py b/Python/minimum-size-subarray-sum.py index 860932c60..ab850fdec 100644 --- a/Python/minimum-size-subarray-sum.py +++ b/Python/minimum-size-subarray-sum.py @@ -11,6 +11,7 @@ # If you have figured out the O(n) solution, try coding another solution of which the time complexity is O(n log n). # +# Sliding window solution. class Solution: # @param {integer} s # @param {integer[]} nums @@ -28,3 +29,34 @@ def minSubArrayLen(self, s, nums): if min_len == float("inf"): return 0 return min_len + +# Time: O(nlogn) +# Space: O(n) +# Binary search solution. +class Solution2: + # @param {integer} s + # @param {integer[]} nums + # @return {integer} + def minSubArrayLen(self, s, nums): + min_size = float("inf") + sum_from_start = [n for n in nums] + for i in xrange(len(sum_from_start) - 1): + sum_from_start[i + 1] += sum_from_start[i] + for i in xrange(len(sum_from_start)): + end = self.binarySearch(lambda x, y: x <= y, sum_from_start, \ + i, len(sum_from_start), \ + sum_from_start[i] - nums[i] + s) + if end < len(sum_from_start): + min_size = min(min_size, end - i + 1) + if min_size == float("inf"): + return 0 + return min_size + + def binarySearch(self, compare, A, start, end, target): + while start < end: + mid = start + (end - start) / 2 + if compare(target, A[mid]): + end = mid + else: + start = mid + 1 + return start From 4679f736eb650997264022b2e77c6fede4a740bb Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 27 May 2015 13:28:42 +0800 Subject: [PATCH 319/345] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 52c4c2485..88676b0f5 100644 --- a/README.md +++ b/README.md @@ -83,7 +83,7 @@ Shell 163 | [Missing Ranges](https://leetcode.com/problems/missing-ranges/)| [Python](./Python/missing-ranges.py) | _O(n)_ | _O(1)_ | Medium | 📖 | 169 | [Majority Element](https://leetcode.com/problems/majority-element/) | [Python](./Python/majority-element.py) | _O(n)_ | _O(1)_ | Easy | 189 | [Rotate Array](https://leetcode.com/problems/rotate-array/) | [Python](./Python/rotate-array.py) | _O(n)_ | _O(1)_ | Easy || -209 | [Minimum Size Subarray Sum](https://leetcode.com/problems/minimum-size-subarray-sum/) | [Python] (./Python/minimum-size-subarray-sum.py) | _O(n)_ | _O(1)_ | Medium || +209 | [Minimum Size Subarray Sum](https://leetcode.com/problems/minimum-size-subarray-sum/) | [Python] (./Python/minimum-size-subarray-sum.py) | _O(n)_ | _O(1)_ | Medium | | Binary Search 215 | [Kth Largest Element in an Array](https://leetcode.com/problems/kth-largest-element-in-an-array/) | [C++] (./C++/kth-largest-element-in-an-array.cpp) [Python] (./Python/kth-largest-element-in-an-array.py)| _O(n)_ | _O(1)_ | Medium | EPI| --- From 382a56e5571bdb353e4b7b9a6b132ec02554bb82 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 27 May 2015 13:50:23 +0800 Subject: [PATCH 320/345] Update minimum-size-subarray-sum.py --- Python/minimum-size-subarray-sum.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/minimum-size-subarray-sum.py b/Python/minimum-size-subarray-sum.py index ab850fdec..229e07aa3 100644 --- a/Python/minimum-size-subarray-sum.py +++ b/Python/minimum-size-subarray-sum.py @@ -47,7 +47,7 @@ def minSubArrayLen(self, s, nums): i, len(sum_from_start), \ sum_from_start[i] - nums[i] + s) if end < len(sum_from_start): - min_size = min(min_size, end - i + 1) + min_size = min(min_size, end - i + 1) if min_size == float("inf"): return 0 return min_size From eb39cad5c55234040b07aa7bd9d84da39d2453a0 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 27 May 2015 20:56:08 +0800 Subject: [PATCH 321/345] Update valid-number.py --- Python/valid-number.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Python/valid-number.py b/Python/valid-number.py index c45fbaab7..e1fb1f9e8 100644 --- a/Python/valid-number.py +++ b/Python/valid-number.py @@ -21,7 +21,7 @@ class InputType: DOT = 4 EXPONENT = 5 -# regular expression: "^\s*[\+\-]?((\d+(\.\d*)?)|\.\d+)([eE][+-]?\d+)?\s*$" +# regular expression: "^\s*[+-]?((\d+(\.\d*)?)|\.\d+)([eE][+-]?\d+)?\s*$" # automata: http://images.cnitblog.com/i/627993/201405/012016243309923.png class Solution: # @param s, a string @@ -63,11 +63,11 @@ class Solution2: # @return a boolean def isNumber(self, s): import re - return bool(re.match("^\s*[\+\-]?((\d+(\.\d*)?)|\.\d+)([eE][+-]?\d+)?\s*$", s)) + return bool(re.match("^\s*[+-]?((\d+(\.\d*)?)|\.\d+)([eE][+-]?\d+)?\s*$", s)) if __name__ == "__main__": print Solution().isNumber(" 0.1 ") print Solution().isNumber("abc") print Solution().isNumber("1 a") print Solution().isNumber("2e10") - \ No newline at end of file + From fb3389711207ae7ede6f6eb67c775f455d94a827 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 27 May 2015 21:24:13 +0800 Subject: [PATCH 322/345] Update valid-number.py --- Python/valid-number.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/valid-number.py b/Python/valid-number.py index e1fb1f9e8..8a5c744e7 100644 --- a/Python/valid-number.py +++ b/Python/valid-number.py @@ -21,7 +21,7 @@ class InputType: DOT = 4 EXPONENT = 5 -# regular expression: "^\s*[+-]?((\d+(\.\d*)?)|\.\d+)([eE][+-]?\d+)?\s*$" +# regular expression: "^\s*[\+-]?((\d+(\.\d*)?)|\.\d+)([eE][\+-]?\d+)?\s*$" # automata: http://images.cnitblog.com/i/627993/201405/012016243309923.png class Solution: # @param s, a string @@ -63,7 +63,7 @@ class Solution2: # @return a boolean def isNumber(self, s): import re - return bool(re.match("^\s*[+-]?((\d+(\.\d*)?)|\.\d+)([eE][+-]?\d+)?\s*$", s)) + return bool(re.match("^\s*[\+-]?((\d+(\.\d*)?)|\.\d+)([eE][\+-]?\d+)?\s*$", s)) if __name__ == "__main__": print Solution().isNumber(" 0.1 ") From 63ba9373368d2c502d25d2db2ebdc2fd57797ea5 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 27 May 2015 21:41:30 +0800 Subject: [PATCH 323/345] Update valid-palindrome.py --- Python/valid-palindrome.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Python/valid-palindrome.py b/Python/valid-palindrome.py index b9abbfc9b..c0c562059 100644 --- a/Python/valid-palindrome.py +++ b/Python/valid-palindrome.py @@ -19,9 +19,9 @@ class Solution: def isPalindrome(self, s): i, j = 0, len(s) - 1 while i < j: - while i < j and not (s[i].isalpha() or s[i].isdigit()): + while i < j and not s[i].isalnum(): i += 1 - while i < j and not (s[j].isalpha() or s[j].isdigit()): + while i < j and not s[j].isalnum(): j -= 1 if s[i].lower() != s[j].lower(): return False @@ -29,4 +29,4 @@ def isPalindrome(self, s): return True if __name__ == "__main__": - print Solution().isPalindrome("A man, a plan, a canal: Panama") \ No newline at end of file + print Solution().isPalindrome("A man, a plan, a canal: Panama") From 4a9ef6b40f66592a7171cfc8b1688ce7a1a2455b Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 28 May 2015 04:06:00 +0800 Subject: [PATCH 324/345] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 88676b0f5..383fd46f1 100644 --- a/README.md +++ b/README.md @@ -96,7 +96,7 @@ Shell 8| [String to Integer (atoi)](https://leetcode.com/problems/string-to-integer-atoi/) | [Python](./Python/string-to-integer-atoi.py) | _O(n)_ | _O(1)_ | Easy || 14| [Longest Common Prefix](https://leetcode.com/problems/longest-common-prefix/) | [Python](./Python/longest-common-prefix.py) | _O(n1 + n2 + ...)_ | _O(1)_ | Easy || 28| [Implement strStr()](https://leetcode.com/problems/implement-strstr/) | [Python](./Python/implement-strstr.py) | _O(n + m)_ | _O(m)_ | Easy || `KMP Algorithm` -38| [Count and Say](https://leetcode.com/problems/compare-version-numbers/) | [Python](./Python/compare-version-numbers.py)| _O(n * 2^n)_ | _O(2^n)_ | Easy || +38| [Count and Say](https://leetcode.com/problems/count-and-say/) | [Python](./Python/count-and-say.py)| _O(n * 2^n)_ | _O(2^n)_ | Easy || 43| [Multiply Strings](https://leetcode.com/problems/multiply-strings/) | [Python](./Python/multiply-strings.py) | _O(m * n)_ | _O(m + n)_ | Medium || 58| [Length of Last Word](https://leetcode.com/problems/length-of-last-word/) | [Python](./Python/length-of-last-word.py) | _O(n)_ | _O(1)_ | Easy || 67| [Add Binary](https://leetcode.com/problems/add-binary/) | [Python](./Python/add-binary.py) | _O(n)_ | _O(1)_ | Easy || @@ -104,7 +104,7 @@ Shell 125| [Valid Palindrome](https://leetcode.com/problems/valid-palindrome/) | [Python](./Python/valid-palindrome.py) | _O(n)_ | _O(1)_ | Easy || 151| [Reverse Words in a String](https://leetcode.com/problems/reverse-words-in-a-string/) | [Python](./Python/reverse-words-in-a-string.py) | _O(n)_ | _O(n)_ | Medium || 161| [One Edit Distance](https://leetcode.com/problems/one-edit-distance/) | [Python](./Python/one-edit-distance.py) | _O(m + n)_ | _O(1)_ | Medium |📖| -165| [Compare Version Numbers](https://leetcode.com/problems/count-and-say/) | [Python](./Python/count-and-say.py) | _O(n)_ | _O(1)_ | Easy || +165| [Compare Version Numbers](https://leetcode.com/problems/compare-version-numbers/) | [Python](./Python/compare-version-numbers.py) | _O(n)_ | _O(1)_ | Easy || 186| [Reverse Words in a String II](https://leetcode.com/problems/reverse-words-in-a-string-ii/) | [Python](./Python/reverse-words-in-a-string-ii.py) | _O(n)_ | _O(1)_ | Medium | 📖 | 205| [Isomorphic Strings](https://leetcode.com/problems/isomorphic-strings/) | [Python](./Python/isomorphic-strings.py) | _O(n)_ | _O(1)_ | Easy || 214| [Shortest Palindrome](https://leetcode.com/problems/shortest-palindrome/) | [C++](./C++/shortest-palindrome.cpp) [Python](./Python/shortest-palindrome.py) | _O(n)_ | _O(n)_ | Hard || `KMP Algorithm` `Manacher's Algorithm` From 4e271b221e3d85cdb3d01d3670d6db810d1b1c36 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 29 May 2015 10:32:43 +0800 Subject: [PATCH 325/345] Create contains-duplicate-ii.cpp --- C++/contains-duplicate-ii.cpp | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 C++/contains-duplicate-ii.cpp diff --git a/C++/contains-duplicate-ii.cpp b/C++/contains-duplicate-ii.cpp new file mode 100644 index 000000000..b49e925ac --- /dev/null +++ b/C++/contains-duplicate-ii.cpp @@ -0,0 +1,22 @@ +// Time: O(n) +// Space: O(n) + +class Solution { +public: + bool containsNearbyDuplicate(vector& nums, int k) { + unordered_map hash; + for (int i = 0; i < nums.size(); ++i) { + if (hash.find(nums[i]) == hash.end()) { + hash[nums[i]] = i; + } else { + // It the value occurs before, check the difference. + if (i - hash[nums[i]] <= k) { + return true; + } + // Update the index of the value. + hash[nums[i]] = i; + } + } + return false; + } +}; From 8d2b0a00ca6ec4b171cbe7668c3e886ecb70a0f9 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 29 May 2015 10:34:19 +0800 Subject: [PATCH 326/345] Update README.md --- README.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 383fd46f1..f4e04a26f 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ LeetCode ======== -Up to date (2015-05-26), there are `202` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2015-05-29), there are `203` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://leetcode.com/). The number of problems is increasing recently. -Here is the classification of all `218` problems. +Here is the classification of all `219` problems. For extra problems and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repo. I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "📖" means you have to buy the book from LeetCode. ) @@ -178,6 +178,7 @@ Shell 202| [Happy Number](https://leetcode.com/problems/happy-number/) | [Python](./Python/happy-number.py) | _O(k)_ | _O(k)_ | Easy || 204| [Count Primes](https://leetcode.com/problems/count-primes/) | [Python](./Python/count-primes.py) | _O(n)_ | _O(n)_ | Easy || 217| [Contains Duplicate](https://leetcode.com/problems/contains-duplicate/) | [C++](./C++/contains-duplicate.cpp) [Python](./Python/contains-duplicate.py) | _O(n)_ | _O(n)_ | Easy || +219| [Contains DuplicateII](https://leetcode.com/problems/contains-duplicate-ii/) | [C++](./C++/contains-duplicate-ii.cpp) [Python](./Python/contains-duplicate-ii.py) | _O(n)_ | _O(n)_ | Easy || --- From e216a99682807d2b92cf6c04ebe1978cded19a7c Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 29 May 2015 10:34:49 +0800 Subject: [PATCH 327/345] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index f4e04a26f..b667af53b 100644 --- a/README.md +++ b/README.md @@ -178,7 +178,7 @@ Shell 202| [Happy Number](https://leetcode.com/problems/happy-number/) | [Python](./Python/happy-number.py) | _O(k)_ | _O(k)_ | Easy || 204| [Count Primes](https://leetcode.com/problems/count-primes/) | [Python](./Python/count-primes.py) | _O(n)_ | _O(n)_ | Easy || 217| [Contains Duplicate](https://leetcode.com/problems/contains-duplicate/) | [C++](./C++/contains-duplicate.cpp) [Python](./Python/contains-duplicate.py) | _O(n)_ | _O(n)_ | Easy || -219| [Contains DuplicateII](https://leetcode.com/problems/contains-duplicate-ii/) | [C++](./C++/contains-duplicate-ii.cpp) [Python](./Python/contains-duplicate-ii.py) | _O(n)_ | _O(n)_ | Easy || +219| [Contains Duplicate II](https://leetcode.com/problems/contains-duplicate-ii/) | [C++](./C++/contains-duplicate-ii.cpp) [Python](./Python/contains-duplicate-ii.py) | _O(n)_ | _O(n)_ | Easy || --- From 34fa53f6bb024c23c3391db4634d3c2703b5ddf0 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 29 May 2015 10:39:15 +0800 Subject: [PATCH 328/345] Update contains-duplicate-ii.cpp --- C++/contains-duplicate-ii.cpp | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/C++/contains-duplicate-ii.cpp b/C++/contains-duplicate-ii.cpp index b49e925ac..b70ad1928 100644 --- a/C++/contains-duplicate-ii.cpp +++ b/C++/contains-duplicate-ii.cpp @@ -4,17 +4,17 @@ class Solution { public: bool containsNearbyDuplicate(vector& nums, int k) { - unordered_map hash; + unordered_map lookup; for (int i = 0; i < nums.size(); ++i) { - if (hash.find(nums[i]) == hash.end()) { - hash[nums[i]] = i; + if (lookup.find(nums[i]) == lookup.end()) { + lookup[nums[i]] = i; } else { // It the value occurs before, check the difference. - if (i - hash[nums[i]] <= k) { + if (i - lookup[nums[i]] <= k) { return true; } // Update the index of the value. - hash[nums[i]] = i; + lookup[nums[i]] = i; } } return false; From b543322be3dac2c7931883c7c192e938daa9e0c4 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 29 May 2015 10:40:12 +0800 Subject: [PATCH 329/345] Create contains-duplicate-ii.py --- Python/contains-duplicate-ii.py | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 Python/contains-duplicate-ii.py diff --git a/Python/contains-duplicate-ii.py b/Python/contains-duplicate-ii.py new file mode 100644 index 000000000..451a6bdde --- /dev/null +++ b/Python/contains-duplicate-ii.py @@ -0,0 +1,24 @@ +# Time: O(n) +# Space: O(n) +# +# Given an array of integers and an integer k, return true if +# and only if there are two distinct indices i and j in the array +# such that nums[i] = nums[j] and the difference between i and j is at most k. +# + +class Solution: + # @param {integer[]} nums + # @param {integer} k + # @return {boolean} + def containsNearbyDuplicate(self, nums, k): + lookup = {} + for i, num in enumerate(nums): + if num not in lookup: + lookup[num] = i + else: + # It the value occurs before, check the difference. + if i - lookup[num] <= k: + return True + # Update the index of the value. + lookup[num] = i + return False From ee86392cd4998936e2393f75cf577b36d0e271fc Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 31 May 2015 02:52:00 +0800 Subject: [PATCH 330/345] Update maximum-gap.py --- Python/maximum-gap.py | 58 +++++++++++++++++++++---------------------- 1 file changed, 28 insertions(+), 30 deletions(-) diff --git a/Python/maximum-gap.py b/Python/maximum-gap.py index 6bc30d14f..4f3379731 100644 --- a/Python/maximum-gap.py +++ b/Python/maximum-gap.py @@ -16,46 +16,44 @@ # bucket sort class Solution: - # @param num, a list of integer - # @return an integer - def maximumGap(self, num): - if len(num) < 2: + # @param numss: a list of integers + # @return: the maximum difference + def maximumGap(self, nums): + # Linear time to get unique_nums. + unique_nums = list(set(nums)) + if len(unique_nums) < 2: return 0 - unique_num = self.removeDuplicate(num) - - max_val, min_val = max(unique_num), min(unique_num) - gap = (max_val - min_val) / (len(unique_num) - 1) + # Init bucket. + max_val, min_val = max(unique_nums), min(unique_nums) + gap = (max_val - min_val) / (len(unique_nums) - 1) bucket_size = (max_val - min_val) / gap + 1 - max_bucket = [float("-inf") for _ in xrange(bucket_size)] - min_bucket = [float("inf") for _ in xrange(bucket_size)] + bucket = [{'min':float("inf"), 'max':float("-inf")} \ + for _ in xrange(bucket_size)] - for i in unique_num: - if i in (max_val, min_val): + # Find the bucket where the n should be put. + for n in unique_nums: + # min_val / max_val is in the first / last bucket. + if n in (max_val, min_val): continue - idx = (i - min_val) / gap - max_bucket[idx] = max(max_bucket[idx], i) - min_bucket[idx] = min(min_bucket[idx], i) + i = (n - min_val) / gap + bucket[i]['min'] = min(bucket[i]['min'], n) + bucket[i]['max'] = max(bucket[i]['max'], n) - max_gap = 0 - pre = min_val + # Count each bucket gap between the first and the last bucket. + max_gap, pre_bucket_max = 0, min_val for i in xrange(bucket_size): - if max_bucket[i] == float("-inf") and min_bucket[i] == float("inf"): + # Skip the bucket it empty. + if bucket[i]['min'] == float("inf") and \ + bucket[i]['max'] == float("-inf"): continue - max_gap = max(max_gap, min_bucket[i] - pre) - pre = max_bucket[i] - max_gap = max(max_gap, max_val - pre) + max_gap = max(max_gap, bucket[i]['min'] - pre_bucket_max) + pre_bucket_max = bucket[i]['max'] + # Count the last bucket. + max_gap = max(max_gap, max_val - pre_bucket_max) return max_gap - - def removeDuplicate(self, num): - dict = {} - unique_num = [] - for i in num: - if i not in dict: - unique_num.append(i) - dict[i] = True - return unique_num + # Time: O(nlogn) # Space: O(n) From 2c6a7e3f8fae3135ce09fbf1eb878d9147027ae6 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 31 May 2015 02:58:00 +0800 Subject: [PATCH 331/345] Update maximum-gap.py --- Python/maximum-gap.py | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/Python/maximum-gap.py b/Python/maximum-gap.py index 4f3379731..fd574a9ac 100644 --- a/Python/maximum-gap.py +++ b/Python/maximum-gap.py @@ -15,24 +15,25 @@ # # bucket sort +# Time: O(n) +# Space: O(n) + class Solution: # @param numss: a list of integers # @return: the maximum difference def maximumGap(self, nums): - # Linear time to get unique_nums. - unique_nums = list(set(nums)) - if len(unique_nums) < 2: + if len(nums) < 2: return 0 # Init bucket. - max_val, min_val = max(unique_nums), min(unique_nums) - gap = (max_val - min_val) / (len(unique_nums) - 1) + max_val, min_val = max(nums), min(nums) + gap = max(1, (max_val - min_val) / (len(nums) - 1)) bucket_size = (max_val - min_val) / gap + 1 bucket = [{'min':float("inf"), 'max':float("-inf")} \ for _ in xrange(bucket_size)] # Find the bucket where the n should be put. - for n in unique_nums: + for n in nums: # min_val / max_val is in the first / last bucket. if n in (max_val, min_val): continue @@ -55,6 +56,7 @@ def maximumGap(self, nums): return max_gap + # Time: O(nlogn) # Space: O(n) class Solution2: From 8bb92083942bc796f6959820174120de4a6ed96b Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 1 Jun 2015 13:47:54 +0800 Subject: [PATCH 332/345] Create contains-duplicate-iii.cpp --- C++/contains-duplicate-iii.cpp | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 C++/contains-duplicate-iii.cpp diff --git a/C++/contains-duplicate-iii.cpp b/C++/contains-duplicate-iii.cpp new file mode 100644 index 000000000..cc4cc48be --- /dev/null +++ b/C++/contains-duplicate-iii.cpp @@ -0,0 +1,28 @@ +// Time: O(nlogn) +// Space: O(n) + +class Solution { +public: + bool containsNearbyAlmostDuplicate(vector& nums, int k, int t) { + deque window_deq; + multiset window; + for (int i = 0; i < nums.size(); ++i) { + // Only keep at most k elements. + if (window.size() > k) { + int num = window_deq.front(); + window_deq.pop_front(); + window.erase(window.find(num)); + } + // Every search costs time: O(logn). + const auto it = window.lower_bound(nums[i] - t); + if (it == window.cend() || (*it - nums[i]) > t) { + // Not found. + window_deq.emplace_back(nums[i]); + window.emplace(nums[i]); + } else { + return true; + } + } + return false; + } +}; From 71d7ba6ada5a519b9a316289b5e326dedcf885d3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 1 Jun 2015 13:50:35 +0800 Subject: [PATCH 333/345] Update contains-duplicate-iii.cpp --- C++/contains-duplicate-iii.cpp | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/C++/contains-duplicate-iii.cpp b/C++/contains-duplicate-iii.cpp index cc4cc48be..589b3f2f0 100644 --- a/C++/contains-duplicate-iii.cpp +++ b/C++/contains-duplicate-iii.cpp @@ -4,21 +4,21 @@ class Solution { public: bool containsNearbyAlmostDuplicate(vector& nums, int k, int t) { - deque window_deq; - multiset window; + deque window; + multiset bst; for (int i = 0; i < nums.size(); ++i) { // Only keep at most k elements. - if (window.size() > k) { - int num = window_deq.front(); - window_deq.pop_front(); - window.erase(window.find(num)); + if (bst.size() > k) { + int num = window.front(); + window.pop_front(); + bst.erase(bst.find(num)); } // Every search costs time: O(logn). - const auto it = window.lower_bound(nums[i] - t); - if (it == window.cend() || (*it - nums[i]) > t) { + const auto it = bst.lower_bound(nums[i] - t); + if (it == bst.cend() || (*it - nums[i]) > t) { // Not found. - window_deq.emplace_back(nums[i]); - window.emplace(nums[i]); + window.emplace_back(nums[i]); + bst.emplace(nums[i]); } else { return true; } From c13913dded51e4db320e93003b1a8e4b457c3a0d Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 1 Jun 2015 13:54:01 +0800 Subject: [PATCH 334/345] Update README.md --- README.md | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index b667af53b..6b54425f9 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ LeetCode ======== -Up to date (2015-05-29), there are `203` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2015-06-01), there are `204` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://leetcode.com/). The number of problems is increasing recently. -Here is the classification of all `219` problems. +Here is the classification of all `220` problems. For extra problems and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repo. I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "📖" means you have to buy the book from LeetCode. ) @@ -26,7 +26,8 @@ Algorithms * [Sort](https://github.com/kamyu104/LeetCode#sort) * [Brute Force Search](https://github.com/kamyu104/LeetCode#brute-force-search) * [Divide and Conquer](https://github.com/kamyu104/LeetCode#divide-and-conquer) -* [Binary Search](https://github.com/kamyu104/LeetCode#binary-search) +* [Binary Search Tree](https://github.com/kamyu104/LeetCode#binary-search) +* * [Binary Search](https://github.com/kamyu104/LeetCode#binary-search-tree) * [Breadth-First Search](https://github.com/kamyu104/LeetCode#breadth-first-search) * [Depth-First Search](https://github.com/kamyu104/LeetCode#depth-first-search) * [Dynamic Programming](https://github.com/kamyu104/LeetCode#dynamic-programming) @@ -50,6 +51,7 @@ Shell ##Bit Manipulation # | Problem | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- +219| [Contains Duplicate II](https://leetcode.com/problems/contains-duplicate-ii/) | [C++](./C++/contains-duplicate-ii.cpp) [Python](./Python/contains-duplicate-ii.py) | _O(n)_ | _O(n)_ | Easy || 136 | [Single Number](https://leetcode.com/problems/single-number/) | [Python](./Python/single-number.py) | _O(n)_ | _O(1)_ | Medium || 137 | [Single Number II](https://leetcode.com/problems/single-number-ii/) | [Python](./Python/single-number-ii.py) | _O(n)_ | _O(1)_ | Medium || 190 | [Reverse Bits](https://leetcode.com/problems/reverse-bits/) | [Python](./Python/reverse-bits.py) | _O(n)_ | _O(1)_ | Easy || @@ -282,6 +284,12 @@ Shell 154| [Find Minimum in Rotated Sorted Array II](https://leetcode.com/problems/find-minimum-in-rotated-sorted-array-ii/) | [Python](./Python/find-minimum-in-rotated-sorted-array-ii.py) | _O(logn)_ ~ _O(n)_ | _O(1)_ | Hard || 162| [Find Peak Element](https://leetcode.com/problems/find-peak-element/) | [Python](./Python/find-peak-element.py) | _O(logn)_ | _O(1)_ | Medium || +-- +##Binary Search Tree + # | Problem | Solution | Time | Space | Difficulty | Tag | Note +-----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- +220| [Contains Duplicate III](https://leetcode.com/problems/contains-duplicate-iii/) | [C++](./C++/contains-duplicate-iii.cpp) | _O(nlogn)_ | _O(n)_ | medium || + --- ##Breadth-First Search From dda2c02ff609fe89fe486a7417ba8f1c6e85e079 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 1 Jun 2015 14:16:43 +0800 Subject: [PATCH 335/345] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 6b54425f9..985c9d826 100644 --- a/README.md +++ b/README.md @@ -26,8 +26,8 @@ Algorithms * [Sort](https://github.com/kamyu104/LeetCode#sort) * [Brute Force Search](https://github.com/kamyu104/LeetCode#brute-force-search) * [Divide and Conquer](https://github.com/kamyu104/LeetCode#divide-and-conquer) -* [Binary Search Tree](https://github.com/kamyu104/LeetCode#binary-search) -* * [Binary Search](https://github.com/kamyu104/LeetCode#binary-search-tree) +* [Binary Search](https://github.com/kamyu104/LeetCode#binary-search) +* [Binary Search Tree](https://github.com/kamyu104/LeetCode#binary-search-tree) * [Breadth-First Search](https://github.com/kamyu104/LeetCode#breadth-first-search) * [Depth-First Search](https://github.com/kamyu104/LeetCode#depth-first-search) * [Dynamic Programming](https://github.com/kamyu104/LeetCode#dynamic-programming) From 78054d40fb0af17970ea900d1739b3139d5b24e0 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 1 Jun 2015 14:20:02 +0800 Subject: [PATCH 336/345] Update README.md --- README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/README.md b/README.md index 985c9d826..c810ab6e4 100644 --- a/README.md +++ b/README.md @@ -51,7 +51,6 @@ Shell ##Bit Manipulation # | Problem | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- -219| [Contains Duplicate II](https://leetcode.com/problems/contains-duplicate-ii/) | [C++](./C++/contains-duplicate-ii.cpp) [Python](./Python/contains-duplicate-ii.py) | _O(n)_ | _O(n)_ | Easy || 136 | [Single Number](https://leetcode.com/problems/single-number/) | [Python](./Python/single-number.py) | _O(n)_ | _O(1)_ | Medium || 137 | [Single Number II](https://leetcode.com/problems/single-number-ii/) | [Python](./Python/single-number-ii.py) | _O(n)_ | _O(1)_ | Medium || 190 | [Reverse Bits](https://leetcode.com/problems/reverse-bits/) | [Python](./Python/reverse-bits.py) | _O(n)_ | _O(1)_ | Easy || From 4d0d045bae664662941efd3f2b3f1166b8399a17 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 1 Jun 2015 14:33:20 +0800 Subject: [PATCH 337/345] Update contains-duplicate-iii.cpp --- C++/contains-duplicate-iii.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/C++/contains-duplicate-iii.cpp b/C++/contains-duplicate-iii.cpp index 589b3f2f0..3485796c6 100644 --- a/C++/contains-duplicate-iii.cpp +++ b/C++/contains-duplicate-iii.cpp @@ -4,20 +4,20 @@ class Solution { public: bool containsNearbyAlmostDuplicate(vector& nums, int k, int t) { - deque window; + queue window; multiset bst; for (int i = 0; i < nums.size(); ++i) { // Only keep at most k elements. if (bst.size() > k) { int num = window.front(); - window.pop_front(); + window.pop(); bst.erase(bst.find(num)); } // Every search costs time: O(logn). const auto it = bst.lower_bound(nums[i] - t); if (it == bst.cend() || (*it - nums[i]) > t) { // Not found. - window.emplace_back(nums[i]); + window.emplace(nums[i]); bst.emplace(nums[i]); } else { return true; From fe90c48cae4f8ba2f4edaaafecc0c6da34d6f8fb Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 1 Jun 2015 15:00:39 +0800 Subject: [PATCH 338/345] Update contains-duplicate-iii.cpp --- C++/contains-duplicate-iii.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/contains-duplicate-iii.cpp b/C++/contains-duplicate-iii.cpp index 3485796c6..a5fe92baa 100644 --- a/C++/contains-duplicate-iii.cpp +++ b/C++/contains-duplicate-iii.cpp @@ -1,5 +1,5 @@ -// Time: O(nlogn) -// Space: O(n) +// Time: O(nlogk) +// Space: O(k) class Solution { public: From 90355d55d35486467dbc2ebd67d11e42d7092f37 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 1 Jun 2015 15:01:29 +0800 Subject: [PATCH 339/345] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index c810ab6e4..427c380e2 100644 --- a/README.md +++ b/README.md @@ -287,7 +287,7 @@ Shell ##Binary Search Tree # | Problem | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- -220| [Contains Duplicate III](https://leetcode.com/problems/contains-duplicate-iii/) | [C++](./C++/contains-duplicate-iii.cpp) | _O(nlogn)_ | _O(n)_ | medium || +220| [Contains Duplicate III](https://leetcode.com/problems/contains-duplicate-iii/) | [C++](./C++/contains-duplicate-iii.cpp) | _O(nlogk)_ | _O(k)_ | medium || --- From 066dbd5b716289799c5f55debda2c850e3289564 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 1 Jun 2015 15:25:47 +0800 Subject: [PATCH 340/345] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 427c380e2..db078e68d 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ LeetCode Up to date (2015-06-01), there are `204` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://leetcode.com/). The number of problems is increasing recently. Here is the classification of all `220` problems. -For extra problems and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repo. +For extra problems and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "📖" means you have to buy the book from LeetCode. ) From d3740bce433f46431bcc96f9cb997ad563ad36c0 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 1 Jun 2015 17:59:33 +0800 Subject: [PATCH 341/345] Update the-skyline-problem.cpp --- C++/the-skyline-problem.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/the-skyline-problem.cpp b/C++/the-skyline-problem.cpp index 51530222d..55cb51376 100644 --- a/C++/the-skyline-problem.cpp +++ b/C++/the-skyline-problem.cpp @@ -4,7 +4,7 @@ // BST solution. class Solution { public: - enum {start, end, height} ; + enum {start, end, height}; struct Endpoint { int height; From dd545a5461e3fa65e1b2a0ec1e4fad94af42d7aa Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 1 Jun 2015 23:40:30 +0800 Subject: [PATCH 342/345] Update letter-combinations-of-a-phone-number.py --- Python/letter-combinations-of-a-phone-number.py | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/Python/letter-combinations-of-a-phone-number.py b/Python/letter-combinations-of-a-phone-number.py index c3d5e7779..f25d8bcc8 100644 --- a/Python/letter-combinations-of-a-phone-number.py +++ b/Python/letter-combinations-of-a-phone-number.py @@ -17,25 +17,33 @@ class Solution: # @return a list of strings, [s1, s2] def letterCombinations(self, digits): - lookup, result = ["", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"], [""] + if not digits: + return [] + + lookup, result = ["", "", "abc", "def", "ghi", "jkl", "mno", \ + "pqrs", "tuv", "wxyz"], [""] - for digit in digits: + for digit in reversed(digits): choices = lookup[int(digit)] m, n = len(choices), len(result) result.extend([result[i % n] for i in xrange(n, m * n)]) for i in xrange(m * n): - result[i] += choices[i / n] + result[i] = choices[i / n] + result[i] return result + # Time: O(n * 4^n) # Space: O(n) # Recursive Solution class Solution2: # @return a list of strings, [s1, s2] def letterCombinations(self, digits): - lookup, result = ["", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"], [] + if not digits: + return [] + lookup, result = ["", "", "abc", "def", "ghi", "jkl", "mno", \ + "pqrs", "tuv", "wxyz"], [] self.letterCombinationsRecu(result, digits, lookup, "", 0) return result From 8b4759021206bdbe149127a55b8f5518b8f5d675 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 2 Jun 2015 11:58:38 +0800 Subject: [PATCH 343/345] Create contains-duplicate-iii.py --- Python/contains-duplicate-iii.py | 34 ++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 Python/contains-duplicate-iii.py diff --git a/Python/contains-duplicate-iii.py b/Python/contains-duplicate-iii.py new file mode 100644 index 000000000..42841b948 --- /dev/null +++ b/Python/contains-duplicate-iii.py @@ -0,0 +1,34 @@ +# Time: O(n * t) +# Space: O(max(k, t)) +# +# Given an array of integers, find out whether there +# are two distinct inwindowes i and j in the array such +# that the difference between nums[i] and nums[j] is +# at most t and the difference between i and j is at +# most k. +# + +# This is not the best solution +# since there is no built-in bst structure in Python. +# The better solution could be found in C++ solution. +class Solution: + # @param {integer[]} nums + # @param {integer} k + # @param {integer} t + # @return {boolean} + def containsNearbyAlmostDuplicate(self, nums, k, t): + if k < 0 or t < 0: + return False + window = collections.OrderedDict() + for n in nums: + # Make sure window size + if len(window) > k: + window.popitem(False) + + bucket = n if not t else n // t + # At most 2t items. + for m in (window.get(bucket - 1), window.get(bucket), window.get(bucket + 1)): + if m is not None and abs(n - m) <= t: + return True + window[bucket] = n + return False From 4d15a0139ad10fdf2ef7486de22e7d8883e6f90c Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 2 Jun 2015 12:00:39 +0800 Subject: [PATCH 344/345] Update contains-duplicate-iii.cpp --- C++/contains-duplicate-iii.cpp | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/C++/contains-duplicate-iii.cpp b/C++/contains-duplicate-iii.cpp index a5fe92baa..0231eb157 100644 --- a/C++/contains-duplicate-iii.cpp +++ b/C++/contains-duplicate-iii.cpp @@ -4,6 +4,10 @@ class Solution { public: bool containsNearbyAlmostDuplicate(vector& nums, int k, int t) { + if (k < 0 || t < 0) { + return false; + } + queue window; multiset bst; for (int i = 0; i < nums.size(); ++i) { From d8ff29563a1031242c591f794189d33d881a0ff7 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 2 Jun 2015 12:01:30 +0800 Subject: [PATCH 345/345] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index db078e68d..fc6b4178c 100644 --- a/README.md +++ b/README.md @@ -287,7 +287,7 @@ Shell ##Binary Search Tree # | Problem | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- -220| [Contains Duplicate III](https://leetcode.com/problems/contains-duplicate-iii/) | [C++](./C++/contains-duplicate-iii.cpp) | _O(nlogk)_ | _O(k)_ | medium || +220| [Contains Duplicate III](https://leetcode.com/problems/contains-duplicate-iii/) | [C++](./C++/contains-duplicate-iii.cpp) [Python](./Python/contains-duplicate-iii.py) | _O(nlogk)_ | _O(k)_ | medium || ---