From a845d79d80a38f4fd7730d9c42db7140c4394dfc Mon Sep 17 00:00:00 2001 From: Qiyuan Gong Date: Thu, 6 Dec 2018 22:35:27 +0800 Subject: [PATCH 001/119] 557_Reverse_Words_in_a_String_III --- README.md | 1 + java/557_Reverse_Words_in_a_String_III.java | 9 +++++++++ python/557_Reverse_Words_in_a_String_III.py | 7 +++++++ 3 files changed, 17 insertions(+) create mode 100644 java/557_Reverse_Words_in_a_String_III.java create mode 100644 python/557_Reverse_Words_in_a_String_III.py diff --git a/README.md b/README.md index eb1e26a..3af746e 100644 --- a/README.md +++ b/README.md @@ -148,6 +148,7 @@ Also, there are open source implementations for basic data structs and algorithm | 482 | [License Key Formatting](https://leetcode.com/problems/license-key-formatting/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/482_License_Key_Formatting.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/482_License_Key_Formatting.java) | String processing, lower and len % K, O(n) and O(n) | | 538 | [Convert BST to Greater Tree](https://leetcode.com/problems/convert-bst-to-greater-tree/description/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/538_Convert_BST_to_Greater_Tree.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/538_Convert_BST_to_Greater_Tree.java) | Right first DFS with a variable recording sum of node.val and right.val. 1. Recursive.
2. Stack 3. Reverse Morris In-order Traversal | | 543 | [Diameter of Binary Tree](https://leetcode.com/problems/diameter-of-binary-tree/description/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/543_Diameter_of_Binary_Tree.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/543_Diameter_of_Binary_Tree.java) | DFS with O(1) for max answer | +| 557 | [Reverse Words in a String III](https://leetcode.com/problems/reverse-words-in-a-string-iii/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/557_Reverse_Words_in_a_String_III.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/557_Reverse_Words_in_a_String_III.java) | String handle: Split with space than reverse word, O(n) and O(n). Better solution is that reverse can be O(1) space in array. | | 572 | [Subtree of Another Tree](https://leetcode.com/problems/subtree-of-another-tree/description/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/572_Subtree_of_Another_Tree.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/572_Subtree_of_Another_Tree.java) | 1. Tree traverse and compare
2. Tree to string and compare | | 581 | [Shortest Unsorted Continuous Subarray](https://leetcode.com/problems/subtree-of-another-tree/description/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/581_Shortest_Unsorted_Continuous_Subarray.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/581_Shortest_Unsorted_Continuous_Subarray.java) | 1. Sort and find the difference (min and max), O(nlgn)
2. Using stack to find boundaries (push when correct order, pop when not correct), O(n) and O(n)
3. Find min and max of unordered array, O(n) and O(1)| | 617 | [Merge Two Binary Trees](https://leetcode.com/problems/merge-two-binary-trees/description/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/617_Merge_Two_Binary_Trees.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/617_Merge_Two_Binary_Trees.java) | Traverse both trees Recursion & Iterative (stack) | diff --git a/java/557_Reverse_Words_in_a_String_III.java b/java/557_Reverse_Words_in_a_String_III.java new file mode 100644 index 0000000..62d9776 --- /dev/null +++ b/java/557_Reverse_Words_in_a_String_III.java @@ -0,0 +1,9 @@ +public class Solution { + public String reverseWords(String s) { + String words[] = s.split(" "); + StringBuilder ans = new StringBuilder(); + for (String word: words) + ans.append(new StringBuffer(word).reverse().toString() + " "); + return ans.toString().trim(); + } +} diff --git a/python/557_Reverse_Words_in_a_String_III.py b/python/557_Reverse_Words_in_a_String_III.py new file mode 100644 index 0000000..c862c21 --- /dev/null +++ b/python/557_Reverse_Words_in_a_String_III.py @@ -0,0 +1,7 @@ +class Solution(object): + def reverseWords(self, s): + """ + :type s: str + :rtype: str + """ + return ' '.join([word[::-1] for word in s.split(' ')]) From ede4a59abdeaa01d93e311981932eb070a2085a0 Mon Sep 17 00:00:00 2001 From: Qiyuan Gong Date: Thu, 6 Dec 2018 22:57:48 +0800 Subject: [PATCH 002/119] 628_Maximum_Product_of_Three_Numbers --- README.md | 1 + .../628_Maximum_Product_of_Three_Numbers.java | 31 +++++++++++++++++++ .../628_Maximum_Product_of_Three_Numbers.py | 30 ++++++++++++++++++ 3 files changed, 62 insertions(+) create mode 100644 java/628_Maximum_Product_of_Three_Numbers.java create mode 100644 python/628_Maximum_Product_of_Three_Numbers.py diff --git a/README.md b/README.md index 3af746e..99be3b9 100644 --- a/README.md +++ b/README.md @@ -152,6 +152,7 @@ Also, there are open source implementations for basic data structs and algorithm | 572 | [Subtree of Another Tree](https://leetcode.com/problems/subtree-of-another-tree/description/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/572_Subtree_of_Another_Tree.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/572_Subtree_of_Another_Tree.java) | 1. Tree traverse and compare
2. Tree to string and compare | | 581 | [Shortest Unsorted Continuous Subarray](https://leetcode.com/problems/subtree-of-another-tree/description/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/581_Shortest_Unsorted_Continuous_Subarray.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/581_Shortest_Unsorted_Continuous_Subarray.java) | 1. Sort and find the difference (min and max), O(nlgn)
2. Using stack to find boundaries (push when correct order, pop when not correct), O(n) and O(n)
3. Find min and max of unordered array, O(n) and O(1)| | 617 | [Merge Two Binary Trees](https://leetcode.com/problems/merge-two-binary-trees/description/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/617_Merge_Two_Binary_Trees.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/617_Merge_Two_Binary_Trees.java) | Traverse both trees Recursion & Iterative (stack) | +| 628 | [Maximum Product of Three Numbers](https://leetcode.com/problems/maximum-product-of-three-numbers/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/628_Maximum_Product_of_Three_Numbers.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/628_Maximum_Product_of_Three_Numbers.java) | Actually, we should only care about min1, min2 and max1-max3, to find these five elements, we can use 1. Brute force, O(n^3) and O(1)
2. Sort, O(nlogn) and O(1)
3. Single scan with 5 elements keep, O(n) and O(1) | | 654 | [Maximum Binary Tree](https://leetcode.com/problems/maximum-binary-tree/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/654_Maximum_Binary_Tree.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/654_Maximum_Binary_Tree.java) | 1. Divide and conquer, recursive, O(n^2)
2. Monotonic stack, O(n) | | 680 | [Valid Palindrome II](https://leetcode.com/problems/valid-palindrome-ii/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/680_Valid_Palindrome_II.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/680_Valid_Palindrome_II.java) | Recursively check s[left == end, when not equal delete left or right. | | 692 | [Top K Frequent Words](https://leetcode.com/problems/top-k-frequent-words/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/692_Top_K_Frequent_Words.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/692_Top_K_Frequent_Words.java) | 1. Sort based on frequency and alphabetical order, O(nlgn) and O(n)
2. Find top k with Heap, O(nlogk) and O(n) | diff --git a/java/628_Maximum_Product_of_Three_Numbers.java b/java/628_Maximum_Product_of_Three_Numbers.java new file mode 100644 index 0000000..67cadbd --- /dev/null +++ b/java/628_Maximum_Product_of_Three_Numbers.java @@ -0,0 +1,31 @@ +public class Solution { + /*public int maximumProduct(int[] nums) { + Arrays.sort(nums); + return Math.max(nums[0] * nums[1] * nums[nums.length - 1], nums[nums.length - 1] * nums[nums.length - 2] * nums[nums.length - 3]); + }*/ + + public int maximumProduct(int[] nums) { + int min1 = Integer.MAX_VALUE, min2 = Integer.MAX_VALUE; + int max1 = Integer.MIN_VALUE, max2 = Integer.MIN_VALUE, max3 = Integer.MIN_VALUE; + for (int n: nums) { + if (n <= min1) { + min2 = min1; + min1 = n; + } else if (n <= min2) { // n lies between min1 and min2 + min2 = n; + } + if (n >= max1) { // n is greater than max1, max2 and max3 + max3 = max2; + max2 = max1; + max1 = n; + } else if (n >= max2) { // n lies betweeen max1 and max2 + max3 = max2; + max2 = n; + } else if (n >= max3) { // n lies betwen max2 and max3 + max3 = n; + } + } + return Math.max(min1 * min2 * max1, max1 * max2 * max3); + } +} + diff --git a/python/628_Maximum_Product_of_Three_Numbers.py b/python/628_Maximum_Product_of_Three_Numbers.py new file mode 100644 index 0000000..e955f84 --- /dev/null +++ b/python/628_Maximum_Product_of_Three_Numbers.py @@ -0,0 +1,30 @@ +class Solution(object): + # def maximumProduct(self, nums): + # """ + # :type nums: List[int] + # :rtype: int + # """ + # nums.sort() + # # Check min1*min2*max1 and max1*max2*max3 + # return max(reduce(lambda x, y: x * y, nums[:2]) * nums[-1], + # reduce(lambda x, y: x * y, nums[-3:])) + + def maximumProduct(self, nums): + min1 = min2 = float('inf') + max1 = max2 = max3 = float('-inf') + for num in nums: + if num <= min1: + min2 = min1 + min1 = num + elif num <= min2: + min2 = num + if num >= max1: + max3 = max2 + max2 = max1 + max1 = num + elif num >= max2: + max3 = max2 + max2 = num + elif num >= max3: + max3 = num + return max(min1 * min2 * max1, max1 * max2 * max3) From 7644927bd2367e7e1bdb223b0e6de3b831fb8669 Mon Sep 17 00:00:00 2001 From: Qiyuan Gong Date: Thu, 6 Dec 2018 23:04:55 +0800 Subject: [PATCH 003/119] 766_Toeplitz_Matrix --- README.md | 1 + java/766_Toeplitz_Matrix.java | 11 +++++++++++ python/766_Toeplitz_Matrix.py | 12 ++++++++++++ 3 files changed, 24 insertions(+) create mode 100644 java/766_Toeplitz_Matrix.java create mode 100644 python/766_Toeplitz_Matrix.py diff --git a/README.md b/README.md index 99be3b9..59d7f69 100644 --- a/README.md +++ b/README.md @@ -165,6 +165,7 @@ Also, there are open source implementations for basic data structs and algorithm | 724 | [Find Pivot Index](https://leetcode.com/problems/find-pivot-index/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/724_Find_Pivot_Index.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/724_Find_Pivot_Index.java) | Seach the array to find a place where left sum is equal to right sum, O(n) and O(1) | | 733 | [Flood Fill](https://leetcode.com/problems/flood-fill/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/733_Flood_Fill.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/733_Flood_Fill.java) | 1. DFS with stack or recursive, O(n) and O(n)
2. BFS with queue, O(n) and O(n) | | 743 | [Network Delay Time](https://leetcode.com/problems/network-delay-time/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/743_Network_Delay_Time.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/743_Network_Delay_Time.java) | Let V == N, then: 1. DFS, O(V^V+ElgE), O(V+E)
2. Dijkstra, O(V^2+E), O(V+E)| +| 766 | [Toeplitz Matrix](https://leetcode.com/problems/toeplitz-matrix/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/766_Toeplitz_Matrix.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/766_Toeplitz_Matrix.java) | Check from top left to bottom right, i,j == i + 1, j + 1. | | 771 | [Jewels and Stones](https://leetcode.com/problems/jewels-and-stones/description/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/771_Jewels_and_Stones.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/771_Jewels_and_Stones.java) | Count given char in string. Hash or table. [Oneline](https://leetcode.com/problems/jewels-and-stones/discuss/113574/1-liners-PythonJavaRuby) | | 804 | [Unique Morse Code Words](https://leetcode.com/problems/unique-morse-code-words/description/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/804_Unique_Morse_Code_Words.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/804_Unique_Morse_Code_Words.java) | String, Hash and Set. Set is recommended. | | 811 | [Subdomain Visit Count](https://leetcode.com/problems/subdomain-visit-count/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/811_Subdomain_Visit_Count.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/811_Subdomain_Visit_Count.java) | String split and HashMap, O(n) and O(n) | diff --git a/java/766_Toeplitz_Matrix.java b/java/766_Toeplitz_Matrix.java new file mode 100644 index 0000000..20f727d --- /dev/null +++ b/java/766_Toeplitz_Matrix.java @@ -0,0 +1,11 @@ +class Solution { + public boolean isToeplitzMatrix(int[][] matrix) { + // Start from second line and column + for (int r = 1; r < matrix.length; ++r) + for (int c = 1; c < matrix[0].length; ++c) + // Check step by step + if (matrix[r-1][c-1] != matrix[r][c]) + return false; + return true; + } +} diff --git a/python/766_Toeplitz_Matrix.py b/python/766_Toeplitz_Matrix.py new file mode 100644 index 0000000..8790a92 --- /dev/null +++ b/python/766_Toeplitz_Matrix.py @@ -0,0 +1,12 @@ +class Solution(object): + def isToeplitzMatrix(self, matrix): + """ + :type matrix: List[List[int]] + :rtype: bool + """ + # Actually, we don't need to check the last row and column + for r in range(len(matrix) - 1): + for c in range(len(matrix[0]) - 1): + if matrix[r][c] != matrix[r + 1][c + 1]: + return False + return True From 6780dbe2daa3e98c1a658150beabeeba19e5ba9d Mon Sep 17 00:00:00 2001 From: Qiyuan Gong Date: Sat, 8 Dec 2018 11:12:22 +0800 Subject: [PATCH 004/119] 253_Meeting_Rooms_II --- README.md | 1 + java/253_Meeting_Rooms_II.java | 77 ++++++++++++++++++++++++++++++++++ python/253_Meeting_Rooms_II.py | 55 ++++++++++++++++++++++++ 3 files changed, 133 insertions(+) create mode 100644 java/253_Meeting_Rooms_II.java create mode 100644 python/253_Meeting_Rooms_II.py diff --git a/README.md b/README.md index 59d7f69..06776f1 100644 --- a/README.md +++ b/README.md @@ -91,6 +91,7 @@ Also, there are open source implementations for basic data structs and algorithm | 246 | [Strobogrammatic Number](https://leetcode.com/problems/strobogrammatic-number/) ♥ | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/246_Strobogrammatic_Number.py) | Hash table and reverse string, O(n) and O(n) | | 249 | [Group Shifted Strings](https://leetcode.com/problems/group-shifted-strings/) ♥ | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/249_Group_Shifted_Strings.py) | Hash and generate hash code for each string, O(n) and O(n) | | 252 | [Meeting Rooms](https://leetcode.com/problems/meeting-rooms/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/252_Meeting_Rooms.py) | 1. Sort and compare intervals[i].end with intervals[i+1], O(nlogn) and O(1)
2. Sort and check intervals when count >= 2, O(nlogn) and O(n) | +| 253 | [Meeting Rooms II](https://leetcode.com/problems/meeting-rooms-ii/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/253_Meeting_Rooms_II.py) ♥ [Java](https://github.com/qiyuangong/leetcode/blob/master/java/253_Meeting_Rooms_II.java) | 1. Priority queue and sort, O(nlogn) and O(n)
2. Go through timeline. If it's a start then meeting + 1, else meeting - 1. The ans is the max(meeting) in timeline. O(nlogn) and O(n) | | 259 | [3Sum Smaller](https://leetcode.com/problems/3sum-smaller/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/259_3Sum_Smaller.py) | 1. Reduce to two sum smaller, then binary search, O(n^2lgn) and O(1)
2. Reduce to two sum smaller, then two points, O(n^2) and O(1)| | 266 | [Palindrome Permutation](https://leetcode.com/problems/palindrome-permutation/) ♥ | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/266_Palindrome_Permutation.py) | Compute frequency, check number of odd occurrences <= 1 then palindrome, O(n) and O(n)| | 267 | [Palindrome Permutation II](https://leetcode.com/problems/palindrome-permutation-ii/) ♥ | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/267_Palindrome_Permutation_II.py) | Check palindrome then generate half with [Permutations II](https://leetcode.com/problems/permutations-ii/), O(n^2) and O(n^2) | diff --git a/java/253_Meeting_Rooms_II.java b/java/253_Meeting_Rooms_II.java new file mode 100644 index 0000000..9760e75 --- /dev/null +++ b/java/253_Meeting_Rooms_II.java @@ -0,0 +1,77 @@ +/** + * Definition for an interval. public class Interval { int start; int end; Interval() { start = 0; + * end = 0; } Interval(int s, int e) { start = s; end = e; } } + */ +class Solution { + + /* public int minMeetingRooms(Interval[] intervals) { + + // Check for the base case. If there are no intervals, return 0 + if (intervals.length == 0) { + return 0; + } + // Min heap + PriorityQueue allocator = + new PriorityQueue( + intervals.length, + new Comparator() { + public int compare(Integer a, Integer b) { + return a - b; + } + }); + + // Sort the intervals by start time + Arrays.sort( + intervals, + new Comparator() { + public int compare(Interval a, Interval b) { + return a.start - b.start; + } + }); + // Add the first meeting + allocator.add(intervals[0].end); + + // Iterate over remaining intervals + for (int i = 1; i < intervals.length; i++) { + // If the room due to free up the earliest is free, assign that room to this meeting. + if (intervals[i].start >= allocator.peek()) { + allocator.poll(); + } + // If a new room is to be assigned, then also we add to the heap, + // If an old room is allocated, then also we have to add to the heap with updated end time. + allocator.add(intervals[i].end); + } + // The size of the heap tells us the minimum rooms required for all the meetings. + return allocator.size(); + }*/ + + public int minMeetingRooms(Interval[] intervals) { + int ans = 0, curr = 0; + List timeline = new ArrayList<>(); + for (Interval interval: intervals) { + timeline.add(new TimePoint(interval.start, 1)); + timeline.add(new TimePoint(interval.end, -1)); + } + timeline.sort(new Comparator() { + public int compare(TimePoint a, TimePoint b) { + if (a.time != b.time) return a.time - b.time; + else return a.room - b.room; + } + }); + for (TimePoint t: timeline) { + curr += t.room; + if (curr >= ans) ans = curr; + } + return ans; + } + + private class TimePoint { + int time; + int room; + + TimePoint(int time, int room) { + this.time = time; + this.room = room; + } + } +} diff --git a/python/253_Meeting_Rooms_II.py b/python/253_Meeting_Rooms_II.py new file mode 100644 index 0000000..9ee765a --- /dev/null +++ b/python/253_Meeting_Rooms_II.py @@ -0,0 +1,55 @@ +# Definition for an interval. +# class Interval(object): +# def __init__(self, s=0, e=0): +# self.start = s +# self.end = e + + +# class Solution(object): +# def minMeetingRooms(self, intervals): +# """ +# :type intervals: List[Interval] +# :rtype: int +# """ +# # If there is no meeting to schedule then no room needs to be allocated. +# if not intervals: +# return 0 +# # The heap initialization +# free_rooms = [] +# # Sort the meetings in increasing order of their start time. +# intervals.sort(key= lambda x: x.start) +# # Add the first meeting. We have to give a new room to the first meeting. +# heapq.heappush(free_rooms, intervals[0].end) +# # For all the remaining meeting rooms +# for i in intervals[1:]: +# # If the room due to free up the earliest is free, assign that room to this meeting. +# if free_rooms[0] <= i.start: +# heapq.heappop(free_rooms) +# # If a new room is to be assigned, then also we add to the heap, +# # If an old room is allocated, then also we have to add to the heap with updated end time. +# heapq.heappush(free_rooms, i.end) +# # The size of the heap tells us the minimum rooms required for all the meetings. +# return len(free_rooms) + + +class Solution(object): + def minMeetingRooms(self, intervals): + """ + :type intervals: List[Interval] + :rtype: int + """ + timeline = [] + for interval in intervals: + # meeting root + 1 + timeline.append((interval.start, 1)) + # meeting root - 1 + timeline.append((interval.end, -1)) + # sort by time + timeline.sort() + ans = curr = 0 + # go through timeline + for _, v in timeline: + curr += v + # max meeting room used at this point + ans = max(ans, curr) + return ans From 55a9b4c947f26d4aae25d652e588b0cd5e519fbc Mon Sep 17 00:00:00 2001 From: Qiyuan Gong Date: Sat, 8 Dec 2018 11:45:06 +0800 Subject: [PATCH 005/119] 238_Product_of_Array_Except_Self --- README.md | 1 + java/238_Product_of_Array_Except_Self.java | 18 ++++++++++++++++++ python/238_Product_of_Array_Except_Self.py | 14 ++++++++++++++ 3 files changed, 33 insertions(+) create mode 100644 java/238_Product_of_Array_Except_Self.java create mode 100644 python/238_Product_of_Array_Except_Self.py diff --git a/README.md b/README.md index 06776f1..6afbf11 100644 --- a/README.md +++ b/README.md @@ -87,6 +87,7 @@ Also, there are open source implementations for basic data structs and algorithm | 220 | [Contains Duplicate III](https://leetcode.com/problems/contains-duplicate-iii/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/220_Contains_Duplicate_III.py) | 1. Sort and binary Search
2. Bucket sort | | 221 | [Maximal Square](https://leetcode.com/problems/maximal-square/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/221_Maximal_Square.py) | 1. Brute force
2. dp[i][j] = min(dp[i-1][j], dp[i-1][j-1], dp[i][j-1]) + 1, O(mn) and O(mn)
3. dp[j] = min([j], dp[j-1], prev) + 1, O(mn) and O(n)| | 228 | [Summary Ranges](https://leetcode.com/problems/summary-ranges/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/228_Summary_Ranges.py) | Detect start and jump, O(n) and O(1) | +| 238 | [Product of Array Except Self](https://leetcode.com/problems/product-of-array-except-self/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/238_Product_of_Array_Except_Self.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/238_Product_of_Array_Except_Self.java) | The ans is [0,i -1] * [i+1, len- 1]. We can twice for left and right (reverse), O(n) and O(n) | | 243 | [Shortest Word Distance](https://leetcode.com/problems/shortest-word-distance/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/243_Shortest_Word_Distance.py) | Update index1 and index2, and check distance, O(n) and O(1) | | 246 | [Strobogrammatic Number](https://leetcode.com/problems/strobogrammatic-number/) ♥ | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/246_Strobogrammatic_Number.py) | Hash table and reverse string, O(n) and O(n) | | 249 | [Group Shifted Strings](https://leetcode.com/problems/group-shifted-strings/) ♥ | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/249_Group_Shifted_Strings.py) | Hash and generate hash code for each string, O(n) and O(n) | diff --git a/java/238_Product_of_Array_Except_Self.java b/java/238_Product_of_Array_Except_Self.java new file mode 100644 index 0000000..28b1031 --- /dev/null +++ b/java/238_Product_of_Array_Except_Self.java @@ -0,0 +1,18 @@ +public class Solution { + public int[] productExceptSelf(int[] nums) { + int n = nums.length; + int[] res = new int[n]; + res[0] = 1; + for (int i = 1; i < n; i++) { + // left part + res[i] = res[i - 1] * nums[i - 1]; + } + int right = 1; + for (int i = n - 1; i >= 0; i--) { + res[i] *= right; + // right part + right *= nums[i]; + } + return res; + } +} diff --git a/python/238_Product_of_Array_Except_Self.py b/python/238_Product_of_Array_Except_Self.py new file mode 100644 index 0000000..c739f9a --- /dev/null +++ b/python/238_Product_of_Array_Except_Self.py @@ -0,0 +1,14 @@ +class Solution(object): + def productExceptSelf(self, nums): + """ + :type nums: List[int] + :rtype: List[int] + """ + ans = [1] * len(nums) + for i in range(1, len(nums)): + ans[i] = ans[i - 1] * nums[i - 1] + right = 1 + for i in range(len(nums) - 1, -1, -1): + ans[i] *= right + right *= nums[i] + return ans From fea38e6a6c543460467b2ef82588d9a17d061c57 Mon Sep 17 00:00:00 2001 From: Qiyuan Gong Date: Sat, 8 Dec 2018 12:10:03 +0800 Subject: [PATCH 006/119] 605_Can_Place_Flowers --- README.md | 1 + java/605_Can_Place_Flowers.java | 29 +++++++++++++++++++++++++++++ python/605_Can_Place_Flowers.py | 20 ++++++++++++++++++++ 3 files changed, 50 insertions(+) create mode 100644 java/605_Can_Place_Flowers.java create mode 100644 python/605_Can_Place_Flowers.py diff --git a/README.md b/README.md index 6afbf11..0db59fa 100644 --- a/README.md +++ b/README.md @@ -153,6 +153,7 @@ Also, there are open source implementations for basic data structs and algorithm | 557 | [Reverse Words in a String III](https://leetcode.com/problems/reverse-words-in-a-string-iii/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/557_Reverse_Words_in_a_String_III.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/557_Reverse_Words_in_a_String_III.java) | String handle: Split with space than reverse word, O(n) and O(n). Better solution is that reverse can be O(1) space in array. | | 572 | [Subtree of Another Tree](https://leetcode.com/problems/subtree-of-another-tree/description/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/572_Subtree_of_Another_Tree.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/572_Subtree_of_Another_Tree.java) | 1. Tree traverse and compare
2. Tree to string and compare | | 581 | [Shortest Unsorted Continuous Subarray](https://leetcode.com/problems/subtree-of-another-tree/description/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/581_Shortest_Unsorted_Continuous_Subarray.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/581_Shortest_Unsorted_Continuous_Subarray.java) | 1. Sort and find the difference (min and max), O(nlgn)
2. Using stack to find boundaries (push when correct order, pop when not correct), O(n) and O(n)
3. Find min and max of unordered array, O(n) and O(1)| +| 605 | [Can Place Flowers](https://leetcode.com/problems/can-place-flowers/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/605_Can_Place_Flowers.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/605_Can_Place_Flowers.java) | One time scan, check [i-1] [i] and [i+1], O(n) and O(1) | | 617 | [Merge Two Binary Trees](https://leetcode.com/problems/merge-two-binary-trees/description/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/617_Merge_Two_Binary_Trees.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/617_Merge_Two_Binary_Trees.java) | Traverse both trees Recursion & Iterative (stack) | | 628 | [Maximum Product of Three Numbers](https://leetcode.com/problems/maximum-product-of-three-numbers/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/628_Maximum_Product_of_Three_Numbers.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/628_Maximum_Product_of_Three_Numbers.java) | Actually, we should only care about min1, min2 and max1-max3, to find these five elements, we can use 1. Brute force, O(n^3) and O(1)
2. Sort, O(nlogn) and O(1)
3. Single scan with 5 elements keep, O(n) and O(1) | | 654 | [Maximum Binary Tree](https://leetcode.com/problems/maximum-binary-tree/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/654_Maximum_Binary_Tree.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/654_Maximum_Binary_Tree.java) | 1. Divide and conquer, recursive, O(n^2)
2. Monotonic stack, O(n) | diff --git a/java/605_Can_Place_Flowers.java b/java/605_Can_Place_Flowers.java new file mode 100644 index 0000000..54843e4 --- /dev/null +++ b/java/605_Can_Place_Flowers.java @@ -0,0 +1,29 @@ +public class Solution { + /*public boolean canPlaceFlowers(int[] flowerbed, int n) { + int i = 0, count = 0; + while (i < flowerbed.length) { + if (flowerbed[i] == 0 && (i == 0 || flowerbed[i - 1] == 0) && (i == flowerbed.length - 1 || flowerbed[i + 1] == 0)) { + flowerbed[i++] = 1; + count++; + } + if(count >= n) + return true; + i++; + } + return false; + }*/ + public boolean canPlaceFlowers(int[] flowerbed, int n) { + int count = 0, curr; + for (int i = 0; i < flowerbed.length; i++) { + curr = flowerbed[i]; + if (i - 1 >= 0) curr += flowerbed[i - 1]; + if (i + 1 < flowerbed.length) curr += flowerbed[i + 1]; + if (curr == 0) { + count++; + flowerbed[i] = 1; + } + if (count >= n) return true; + } + return false; + } +} diff --git a/python/605_Can_Place_Flowers.py b/python/605_Can_Place_Flowers.py new file mode 100644 index 0000000..688357b --- /dev/null +++ b/python/605_Can_Place_Flowers.py @@ -0,0 +1,20 @@ +class Solution(object): + def canPlaceFlowers(self, flowerbed, n): + """ + :type flowerbed: List[int] + :type n: int + :rtype: bool + """ + count = 0 + for i in range(len(flowerbed)): + curr = flowerbed[i] + if i - 1 >= 0: + curr += flowerbed[i - 1] + if i + 1 < len(flowerbed): + curr += flowerbed[i + 1] + if curr == 0: + count += 1 + flowerbed[i] = 1 + if count >= n: + return True + return False From 84d9638a9c37905039b5580f6504c840690706f3 Mon Sep 17 00:00:00 2001 From: Qiyuan Gong Date: Sat, 8 Dec 2018 13:13:28 +0800 Subject: [PATCH 007/119] 475_Heaters --- README.md | 1 + java/475_Heaters.java | 17 +++++++++++++++++ python/475_Heaters.py | 16 ++++++++++++++++ 3 files changed, 34 insertions(+) create mode 100644 java/475_Heaters.java create mode 100644 python/475_Heaters.py diff --git a/README.md b/README.md index 0db59fa..b932ab6 100644 --- a/README.md +++ b/README.md @@ -147,6 +147,7 @@ Also, there are open source implementations for basic data structs and algorithm | 453 | [Number of Segments in a String](https://leetcode.com/problems/minimum-moves-to-equal-array-elements/description/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/453_Minimum_Moves_to_Equal_Array_Elements.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/453_Minimum_Moves_to_Equal_Array_Elements.java) | Each move is equal to minus one element in array, so the answer is the sum of all elements after minus min. | | 461 | [Hamming Distance](https://leetcode.com/problems/hamming-distance/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/461_Hamming_Distance.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/461_Hamming_Distance.java) | Hamming Distance is related to XOR for numbers. So, XOR then count 1. O(n) | | 463 | [Island Perimeter](https://leetcode.com/problems/island-perimeter/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/463_Island_Perimeter.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/463_Island_Perimeter.java) | math, find the area, actual number, then find the digit | +| 475 | [Heaters](https://leetcode.com/problems/heaters/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/475_Heaters.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/475_Heaters.java) | 1. Binary search hourse in heater array, O(nlogn) and O(1)
2. Two points, O(nlogn) and O(1) | | 482 | [License Key Formatting](https://leetcode.com/problems/license-key-formatting/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/482_License_Key_Formatting.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/482_License_Key_Formatting.java) | String processing, lower and len % K, O(n) and O(n) | | 538 | [Convert BST to Greater Tree](https://leetcode.com/problems/convert-bst-to-greater-tree/description/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/538_Convert_BST_to_Greater_Tree.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/538_Convert_BST_to_Greater_Tree.java) | Right first DFS with a variable recording sum of node.val and right.val. 1. Recursive.
2. Stack 3. Reverse Morris In-order Traversal | | 543 | [Diameter of Binary Tree](https://leetcode.com/problems/diameter-of-binary-tree/description/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/543_Diameter_of_Binary_Tree.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/543_Diameter_of_Binary_Tree.java) | DFS with O(1) for max answer | diff --git a/java/475_Heaters.java b/java/475_Heaters.java new file mode 100644 index 0000000..476a764 --- /dev/null +++ b/java/475_Heaters.java @@ -0,0 +1,17 @@ +public class Solution { + public int findRadius(int[] houses, int[] heaters) { + Arrays.sort(heaters); + int result = Integer.MIN_VALUE; + + for (int house : houses) { + // Java binarySearch return - insertPoint - 1 if not found + // This point is greater than value you want + int index = Arrays.binarySearch(heaters, house); + if (index < 0) index = -(index + 1); + int dist1 = index - 1 >= 0 ? house - heaters[index - 1] : Integer.MAX_VALUE; + int dist2 = index < heaters.length ? heaters[index] - house : Integer.MAX_VALUE; + result = Math.max(result, Math.min(dist1, dist2)); + } + return result; + } +} diff --git a/python/475_Heaters.py b/python/475_Heaters.py new file mode 100644 index 0000000..90c7dde --- /dev/null +++ b/python/475_Heaters.py @@ -0,0 +1,16 @@ +class Solution(object): + def findRadius(self, houses, heaters): + """ + :type houses: List[int] + :type heaters: List[int] + :rtype: int + """ + heaters = sorted(heaters) + [float('inf')] + i = r = 0 + for x in sorted(houses): + # move to next range + while x >= sum(heaters[i:i + 2]) / 2.: + i += 1 + # ans = hearter - hourse + r = max(r, abs(heaters[i] - x)) + return r From 4edafe4c8e0ab326c1010dc6f16a9720f18bf75d Mon Sep 17 00:00:00 2001 From: Qiyuan Gong Date: Sun, 9 Dec 2018 01:06:50 +0800 Subject: [PATCH 008/119] 560_Subarray_Sum_Equals_K --- README.md | 1 + java/560_Subarray_Sum_Equals_K.java | 28 ++++++++++++++++++++++++++++ python/560_Subarray_Sum_Equals_K.py | 17 +++++++++++++++++ 3 files changed, 46 insertions(+) create mode 100644 java/560_Subarray_Sum_Equals_K.java create mode 100644 python/560_Subarray_Sum_Equals_K.py diff --git a/README.md b/README.md index b932ab6..30ffc34 100644 --- a/README.md +++ b/README.md @@ -152,6 +152,7 @@ Also, there are open source implementations for basic data structs and algorithm | 538 | [Convert BST to Greater Tree](https://leetcode.com/problems/convert-bst-to-greater-tree/description/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/538_Convert_BST_to_Greater_Tree.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/538_Convert_BST_to_Greater_Tree.java) | Right first DFS with a variable recording sum of node.val and right.val. 1. Recursive.
2. Stack 3. Reverse Morris In-order Traversal | | 543 | [Diameter of Binary Tree](https://leetcode.com/problems/diameter-of-binary-tree/description/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/543_Diameter_of_Binary_Tree.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/543_Diameter_of_Binary_Tree.java) | DFS with O(1) for max answer | | 557 | [Reverse Words in a String III](https://leetcode.com/problems/reverse-words-in-a-string-iii/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/557_Reverse_Words_in_a_String_III.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/557_Reverse_Words_in_a_String_III.java) | String handle: Split with space than reverse word, O(n) and O(n). Better solution is that reverse can be O(1) space in array. | +| 560 | [Subarray Sum Equals K](https://leetcode.com/problems/subarray-sum-equals-k/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/560_Subarray_Sum_Equals_K.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/560_Subarray_Sum_Equals_K.java) | Note that there are n^2 possible pairs, so the key point is accelerate computation for sum and reduce unnecessary pair. 1. Cummulative sum, O(n^2) and O(1)/O(n)
2. Add sum into hash, check if sum - k is in hash, O(n) and O(n) | | 572 | [Subtree of Another Tree](https://leetcode.com/problems/subtree-of-another-tree/description/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/572_Subtree_of_Another_Tree.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/572_Subtree_of_Another_Tree.java) | 1. Tree traverse and compare
2. Tree to string and compare | | 581 | [Shortest Unsorted Continuous Subarray](https://leetcode.com/problems/subtree-of-another-tree/description/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/581_Shortest_Unsorted_Continuous_Subarray.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/581_Shortest_Unsorted_Continuous_Subarray.java) | 1. Sort and find the difference (min and max), O(nlgn)
2. Using stack to find boundaries (push when correct order, pop when not correct), O(n) and O(n)
3. Find min and max of unordered array, O(n) and O(1)| | 605 | [Can Place Flowers](https://leetcode.com/problems/can-place-flowers/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/605_Can_Place_Flowers.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/605_Can_Place_Flowers.java) | One time scan, check [i-1] [i] and [i+1], O(n) and O(1) | diff --git a/java/560_Subarray_Sum_Equals_K.java b/java/560_Subarray_Sum_Equals_K.java new file mode 100644 index 0000000..49a2c04 --- /dev/null +++ b/java/560_Subarray_Sum_Equals_K.java @@ -0,0 +1,28 @@ +public class Solution { + /*public int subarraySum(int[] nums, int k) { + int count = 0; + for (int start = 0; start < nums.length; start++) { + int sum = 0; + for (int end = start; end < nums.length; end++) { + sum += nums[end]; + if (sum == k) + count++; + } + } + return count; + }*/ + public int subarraySum(int[] nums, int k) { + int count = 0, sum = 0; + HashMap < Integer, Integer > map = new HashMap < > (); + map.put(0, 1); + for (int i = 0; i < nums.length; i++) { + sum += nums[i]; + // check if sum - k in hash + if (map.containsKey(sum - k)) + count += map.get(sum - k); + // push sum into hash + map.put(sum, map.getOrDefault(sum, 0) + 1); + } + return count; + } +} diff --git a/python/560_Subarray_Sum_Equals_K.py b/python/560_Subarray_Sum_Equals_K.py new file mode 100644 index 0000000..fae8c39 --- /dev/null +++ b/python/560_Subarray_Sum_Equals_K.py @@ -0,0 +1,17 @@ +class Solution(object): + def subarraySum(self, nums, k): + """ + :type nums: List[int] + :type k: int + :rtype: int + """ + sum_map = {} + sum_map[0] = 1 + count = curr_sum = 0 + for num in nums: + curr_sum += num + # Check if sum - k in hash + count += sum_map.get(curr_sum - k, 0) + # add curr_sum to hash + sum_map[curr_sum] = sum_map.get(curr_sum, 0) + 1 + return count From 30853cfbcdead635b6e4ba4694a7fad0bfc68d92 Mon Sep 17 00:00:00 2001 From: Qiyuan Gong Date: Sun, 9 Dec 2018 14:25:16 +0800 Subject: [PATCH 009/119] 953_Verifying_an_Alien_Dictionary and 954_Array_of_Doubled_Pairs --- README.md | 2 ++ java/179_Largest_Number.java | 1 - java/905_Sort_Array_By_Parity.java | 8 ++++-- java/953_Verifying_an_Alien_Dictionary.java | 25 ++++++++++++++++ java/954_Array_of_Doubled_Pairs.java | 24 ++++++++++++++++ python/953_Verifying_an_Alien_Dictionary.py | 32 +++++++++++++++++++++ python/954_Array_of_Doubled_Pairs.py | 27 +++++++++++++++++ 7 files changed, 116 insertions(+), 3 deletions(-) create mode 100644 java/953_Verifying_an_Alien_Dictionary.java create mode 100644 java/954_Array_of_Doubled_Pairs.java create mode 100644 python/953_Verifying_an_Alien_Dictionary.py create mode 100644 python/954_Array_of_Doubled_Pairs.py diff --git a/README.md b/README.md index 30ffc34..553beba 100644 --- a/README.md +++ b/README.md @@ -184,6 +184,8 @@ Also, there are open source implementations for basic data structs and algorithm | 929 | [Unique Email Addresses](https://leetcode.com/problems/unique-email-addresses/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/929_Unique_Email_Addresses.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/929_Unique_Email_Addresses.java) | String handle and hash (or set) | | 945 | [Minimum Increment to Make Array Unique](https://leetcode.com/problems/minimum-increment-to-make-array-unique/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/945_Minimum_Increment_to_Make_Array_Unique.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/945_Minimum_Increment_to_Make_Array_Unique.java) | Sort, then list duplicate and missing value in sorted list. O(nlgn) and O(n) | | 946 | [Validate Stack Sequences](https://leetcode.com/problems/validate-stack-sequences/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/946_Validate_Stack_Sequences.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/946_Validate_Stack_Sequences.java) | Add a stack named inStack to help going through pushed and popped. O(n) and O(n) | +| 953 | [Verifying an Alien Dictionary](https://leetcode.com/contest/weekly-contest-114/problems/verifying-an-alien-dictionary/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/953_Verifying_an_Alien_Dictionary.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/953_Verifying_an_Alien_Dictionary.java) | Use hashmap to store index of each value, then create a comparator based on this index, O(n) and O(n) | +| 954 | [Array of Doubled Pairs](https://leetcode.com/contest/weekly-contest-114/problems/array-of-doubled-pairs/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/954_Array_of_Doubled_Pairs.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/954_Array_of_Doubled_Pairs.java) | Sort, then use hashmap to store the frequency of each value. Then, check n, 2 * n in hashmap, O(nlogn) and O(n) | | # | To Understand | |---| ----- | diff --git a/java/179_Largest_Number.java b/java/179_Largest_Number.java index 3613777..1455406 100644 --- a/java/179_Largest_Number.java +++ b/java/179_Largest_Number.java @@ -29,7 +29,6 @@ public String largestNumber(int[] nums) { for (String numAsStr : asStrs) { largestNumberStr += numAsStr; } - return largestNumberStr; } } diff --git a/java/905_Sort_Array_By_Parity.java b/java/905_Sort_Array_By_Parity.java index 699d304..09619cd 100644 --- a/java/905_Sort_Array_By_Parity.java +++ b/java/905_Sort_Array_By_Parity.java @@ -1,6 +1,10 @@ class Solution { - /*public int[] sortArrayByParity(int[] A) { - Array.sort(A, (a, b)-> Integer.compare(a%2, b%2)); +/* public int[] sortArrayByParity(int[] A) { + A = Arrays.stream(A). + boxed(). + sorted((a, b) -> Integer.compare(a% 2, b % 2)). + mapToInt(i -> i). + toArray(); return A; }*/ diff --git a/java/953_Verifying_an_Alien_Dictionary.java b/java/953_Verifying_an_Alien_Dictionary.java new file mode 100644 index 0000000..143742f --- /dev/null +++ b/java/953_Verifying_an_Alien_Dictionary.java @@ -0,0 +1,25 @@ +class Solution { + HashMap orderMap = new HashMap<>(); + public boolean isAlienSorted(String[] words, String order) { + // Put value index map into hashmap + for (int i = 0; i < order.length(); i++) { + orderMap.put(order.charAt(i), i); + } + for (int i = 0; i < words.length - 1; i++) { + if (cmp_alien(words[i], words[i + 1]) > 0) return false; + } + return true; + + } + private int cmp_alien(String a, String b) { + int ls = a.length() < b.length() ? a.length(): b.length(); + int pos = 0; + // Compare based on hashmap + while (pos < ls) { + if (orderMap.get(a.charAt(pos)) != orderMap.get(b.charAt(pos))) + return orderMap.get(a.charAt(pos)) - orderMap.get(b.charAt(pos)); + pos += 1; + } + return a.length() <= b.length() ? -1: 1; + } +} diff --git a/java/954_Array_of_Doubled_Pairs.java b/java/954_Array_of_Doubled_Pairs.java new file mode 100644 index 0000000..6d848f9 --- /dev/null +++ b/java/954_Array_of_Doubled_Pairs.java @@ -0,0 +1,24 @@ +class Solution { + public boolean canReorderDoubled(int[] A) { + HashMap valueMap = new HashMap<>(); + // Sort in[] with comparator + A = Arrays.stream(A). + boxed(). + sorted((a, b) -> Integer.compare(Math.abs(a), Math.abs(b))). + mapToInt(i -> i). + toArray(); + for (int n: A) valueMap.put(n, valueMap.getOrDefault(n, 0) + 1); + for (int n: A) { + if (valueMap.get(n) <= 0) continue; + if (valueMap.containsKey(2 * n) && valueMap.get(2 * n) > 0) { + valueMap.put(n, valueMap.get(n) - 1); + valueMap.put(2 * n, valueMap.get(2 * n) - 1); + } else { + return false; + } + } + return true; + } + + +} diff --git a/python/953_Verifying_an_Alien_Dictionary.py b/python/953_Verifying_an_Alien_Dictionary.py new file mode 100644 index 0000000..706fe47 --- /dev/null +++ b/python/953_Verifying_an_Alien_Dictionary.py @@ -0,0 +1,32 @@ +class Solution(object): + def isAlienSorted(self, words, order): + """ + :type words: List[str] + :type order: str + :rtype: bool + """ + order_map = {} + for i, v in enumerate(order): + order_map[v] = i + + def cmp_alien(x, y): + ls = min(len(x), len(y)) + index = 0 + while index < ls: + if x[index] != y[index]: + return order_map[x[index]] - order_map[y[index]] + index += 1 + return len(x) - len(y) + pos = 0 + while pos + 1 < len(words): + if cmp_alien(words[pos], words[pos + 1]) > 0: + return False + pos += 1 + return True + + +if __name__ == '__main__': + s = Solution() + print s.isAlienSorted(["hello","leetcode"], "hlabcdefgijkmnopqrstuvwxyz") + print s.isAlienSorted(["word","world","row"], "worldabcefghijkmnpqstuvxyz") + print s.isAlienSorted(["apple","app"], "abcdefghijklmnopqrstuvwxyz") diff --git a/python/954_Array_of_Doubled_Pairs.py b/python/954_Array_of_Doubled_Pairs.py new file mode 100644 index 0000000..4c052d5 --- /dev/null +++ b/python/954_Array_of_Doubled_Pairs.py @@ -0,0 +1,27 @@ +class Solution(object): + def canReorderDoubled(self, A): + """ + :type A: List[int] + :rtype: bool + """ + v_map = {} + A.sort(key=lambda x: abs(x)) + for n in A: + v_map[n] = v_map.get(n, 0) + 1 + for n in A: + if v_map[n] <= 0: + continue + if 2 * n in v_map and v_map[2 * n] > 0: + v_map[n] -= 1 + v_map[2 * n] -= 1 + else: + return False + return True + + +if __name__ == '__main__': + s = Solution() + print s.canReorderDoubled([3, 1, 3, 6]) + print s.canReorderDoubled([2, 1, 2, 6]) + print s.canReorderDoubled([4, -2, 2, -4]) + print s.canReorderDoubled([1, 2, 4, 16, 8, 4]) From 6fbc8f5f6b69a51d9d28db04b676ef1c0aad47ed Mon Sep 17 00:00:00 2001 From: Qiyuan Gong Date: Sun, 9 Dec 2018 15:32:57 +0800 Subject: [PATCH 010/119] 479_Largest_Palindrome_Product --- README.md | 1 + java/479_Largest_Palindrome_Product.java | 49 ++++++++++++++++++++++++ python/479_Largest_Palindrome_Product.py | 38 ++++++++++++++++++ 3 files changed, 88 insertions(+) create mode 100644 java/479_Largest_Palindrome_Product.java create mode 100644 python/479_Largest_Palindrome_Product.py diff --git a/README.md b/README.md index 553beba..87230d4 100644 --- a/README.md +++ b/README.md @@ -148,6 +148,7 @@ Also, there are open source implementations for basic data structs and algorithm | 461 | [Hamming Distance](https://leetcode.com/problems/hamming-distance/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/461_Hamming_Distance.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/461_Hamming_Distance.java) | Hamming Distance is related to XOR for numbers. So, XOR then count 1. O(n) | | 463 | [Island Perimeter](https://leetcode.com/problems/island-perimeter/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/463_Island_Perimeter.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/463_Island_Perimeter.java) | math, find the area, actual number, then find the digit | | 475 | [Heaters](https://leetcode.com/problems/heaters/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/475_Heaters.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/475_Heaters.java) | 1. Binary search hourse in heater array, O(nlogn) and O(1)
2. Two points, O(nlogn) and O(1) | +| 479 | [Largest Palindrome Product](https://leetcode.com/problems/largest-palindrome-product/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/479_Largest_Palindrome_Product.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/479_Largest_Palindrome_Product.java) | Product max palindrome than check, O(n^2) and O(1) | | 482 | [License Key Formatting](https://leetcode.com/problems/license-key-formatting/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/482_License_Key_Formatting.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/482_License_Key_Formatting.java) | String processing, lower and len % K, O(n) and O(n) | | 538 | [Convert BST to Greater Tree](https://leetcode.com/problems/convert-bst-to-greater-tree/description/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/538_Convert_BST_to_Greater_Tree.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/538_Convert_BST_to_Greater_Tree.java) | Right first DFS with a variable recording sum of node.val and right.val. 1. Recursive.
2. Stack 3. Reverse Morris In-order Traversal | | 543 | [Diameter of Binary Tree](https://leetcode.com/problems/diameter-of-binary-tree/description/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/543_Diameter_of_Binary_Tree.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/543_Diameter_of_Binary_Tree.java) | DFS with O(1) for max answer | diff --git a/java/479_Largest_Palindrome_Product.java b/java/479_Largest_Palindrome_Product.java new file mode 100644 index 0000000..058e579 --- /dev/null +++ b/java/479_Largest_Palindrome_Product.java @@ -0,0 +1,49 @@ +class Solution { + public int largestPalindrome(int n) { + // https://leetcode.com/problems/largest-palindrome-product/discuss/96297/Java-Solution-using-assumed-max-palindrom + // if input is 1 then max is 9 + if(n == 1){ + return 9; + } + + // if n = 3 then upperBound = 999 and lowerBound = 99 + int upperBound = (int) Math.pow(10, n) - 1, lowerBound = upperBound / 10; + long maxNumber = (long) upperBound * (long) upperBound; + + // represents the first half of the maximum assumed palindrom. + // e.g. if n = 3 then maxNumber = 999 x 999 = 998001 so firstHalf = 998 + int firstHalf = (int)(maxNumber / (long) Math.pow(10, n)); + + boolean palindromFound = false; + long palindrom = 0; + + while (!palindromFound) { + // creates maximum assumed palindrom + // e.g. if n = 3 first time the maximum assumed palindrom will be 998 899 + palindrom = createPalindrom(firstHalf); + + // here i and palindrom/i forms the two factor of assumed palindrom + for (long i = upperBound; upperBound > lowerBound; i--) { + // if n= 3 none of the factor of palindrom can be more than 999 or less than square root of assumed palindrom + if (palindrom / i > maxNumber || i * i < palindrom) { + break; + } + + // if two factors found, where both of them are n-digits, + if (palindrom % i == 0) { + palindromFound = true; + break; + } + } + + firstHalf--; + } + + return (int) (palindrom % 1337); + } + + private long createPalindrom(long num) { + String str = num + new StringBuilder().append(num).reverse().toString(); + return Long.parseLong(str); + } +} diff --git a/python/479_Largest_Palindrome_Product.py b/python/479_Largest_Palindrome_Product.py new file mode 100644 index 0000000..568a1d8 --- /dev/null +++ b/python/479_Largest_Palindrome_Product.py @@ -0,0 +1,38 @@ +class Solution(object): + # def largestPalindrome(self, n): + # """ + # :type n: int + # :rtype: int + # """ + # if n == 1: + # return 9 + # # https://leetcode.com/problems/largest-palindrome-product/discuss/96297/Java-Solution-using-assumed-max-palindrom + # upperBound = 10 ** n - 1 + # lowerBound = upperBound / 10 + # maxNum = upperBound * upperBound + # firstHalf = maxNum / (10 ** n) + # palindromFound = False + # palindrom = 0 + # while not palindromFound: + # palindrom = int(str(firstHalf) + str(firstHalf)[::-1]) + # for i in xrange(upperBound, lowerBound, -1): + # if i * i < palindrom: + # break + # if palindrom % i == 0: + # palindromFound = True + # break + # firstHalf -= 1 + # return palindrom % 1337 + + def largestPalindrome(self, n): + if n == 1: + return 9 + if n == 2: + return 987 + for a in xrange(2, 9 * 10 ** (n - 1)): + hi = (10 ** n) - a + lo = int(str(hi)[::-1]) + if a ** 2 - 4 * lo < 0: + continue + if (a ** 2 - 4 * lo) ** .5 == int((a ** 2 - 4 * lo) ** .5): + return (lo + 10 ** n * (10 ** n - a)) % 1337 From 069f4f57edf6ceace6640b036b4c54a9cb986f18 Mon Sep 17 00:00:00 2001 From: Qiyuan Gong Date: Sun, 9 Dec 2018 16:03:43 +0800 Subject: [PATCH 011/119] Add one more solution for 479_Largest_Palindrome_Product --- README.md | 2 +- python/479_Largest_Palindrome_Product.py | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 87230d4..53182a7 100644 --- a/README.md +++ b/README.md @@ -148,7 +148,7 @@ Also, there are open source implementations for basic data structs and algorithm | 461 | [Hamming Distance](https://leetcode.com/problems/hamming-distance/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/461_Hamming_Distance.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/461_Hamming_Distance.java) | Hamming Distance is related to XOR for numbers. So, XOR then count 1. O(n) | | 463 | [Island Perimeter](https://leetcode.com/problems/island-perimeter/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/463_Island_Perimeter.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/463_Island_Perimeter.java) | math, find the area, actual number, then find the digit | | 475 | [Heaters](https://leetcode.com/problems/heaters/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/475_Heaters.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/475_Heaters.java) | 1. Binary search hourse in heater array, O(nlogn) and O(1)
2. Two points, O(nlogn) and O(1) | -| 479 | [Largest Palindrome Product](https://leetcode.com/problems/largest-palindrome-product/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/479_Largest_Palindrome_Product.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/479_Largest_Palindrome_Product.java) | Product max palindrome than check, O(n^2) and O(1) | +| 479 | [Largest Palindrome Product](https://leetcode.com/problems/largest-palindrome-product/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/479_Largest_Palindrome_Product.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/479_Largest_Palindrome_Product.java) | 1. Product max palindrome than check, O(n^2) and O(1)
2. [Math](# https://leetcode.com/problems/largest-palindrome-product/discuss/96305/Python-Solution-Using-Math-In-48ms) | | 482 | [License Key Formatting](https://leetcode.com/problems/license-key-formatting/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/482_License_Key_Formatting.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/482_License_Key_Formatting.java) | String processing, lower and len % K, O(n) and O(n) | | 538 | [Convert BST to Greater Tree](https://leetcode.com/problems/convert-bst-to-greater-tree/description/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/538_Convert_BST_to_Greater_Tree.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/538_Convert_BST_to_Greater_Tree.java) | Right first DFS with a variable recording sum of node.val and right.val. 1. Recursive.
2. Stack 3. Reverse Morris In-order Traversal | | 543 | [Diameter of Binary Tree](https://leetcode.com/problems/diameter-of-binary-tree/description/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/543_Diameter_of_Binary_Tree.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/543_Diameter_of_Binary_Tree.java) | DFS with O(1) for max answer | diff --git a/python/479_Largest_Palindrome_Product.py b/python/479_Largest_Palindrome_Product.py index 568a1d8..5d614de 100644 --- a/python/479_Largest_Palindrome_Product.py +++ b/python/479_Largest_Palindrome_Product.py @@ -25,10 +25,10 @@ class Solution(object): # return palindrom % 1337 def largestPalindrome(self, n): + # https://leetcode.com/problems/largest-palindrome-product/discuss/96305/Python-Solution-Using-Math-In-48ms + # https://leetcode.com/problems/largest-palindrome-product/discuss/96294/could-any-python-experts-share-their-codes-within-100ms if n == 1: return 9 - if n == 2: - return 987 for a in xrange(2, 9 * 10 ** (n - 1)): hi = (10 ** n) - a lo = int(str(hi)[::-1]) From 63e4d705f154207fa634b706c4dd461fd1b4886d Mon Sep 17 00:00:00 2001 From: Qiyuan Gong Date: Sun, 9 Dec 2018 17:25:11 +0800 Subject: [PATCH 012/119] 458_Poor_Pigs --- README.md | 1 + java/458_Poor_Pigs.java | 8 ++++++++ python/458_Poor_Pigs.py | 13 +++++++++++++ 3 files changed, 22 insertions(+) create mode 100644 java/458_Poor_Pigs.java create mode 100644 python/458_Poor_Pigs.py diff --git a/README.md b/README.md index 53182a7..02011e2 100644 --- a/README.md +++ b/README.md @@ -145,6 +145,7 @@ Also, there are open source implementations for basic data structs and algorithm | 443 | [String Compression](https://leetcode.com/problems/string-compression/description/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/443_String_Compression.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/443_String_Compression.java) | Maintain curr, read, write and anchor (start of this char). | | 448 | [Find All Numbers Disappeared in an Array](https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/448_Find_All_Numbers_Disappeared_in_an_Array.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/448_Find_All_Numbers_Disappeared_in_an_Array.java) | Value (1, n) and index (0, n-1). Mark every value postion as negative. Then, the remain index with positive values are result. O(n)| | 453 | [Number of Segments in a String](https://leetcode.com/problems/minimum-moves-to-equal-array-elements/description/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/453_Minimum_Moves_to_Equal_Array_Elements.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/453_Minimum_Moves_to_Equal_Array_Elements.java) | Each move is equal to minus one element in array, so the answer is the sum of all elements after minus min. | +| 458 | [Poor Pigs](https://leetcode.com/problems/poor-pigs/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/458_Poor_Pigs.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/458_Poor_Pigs.java) | [2 pigs for 5 * 5 metric](https://leetcode.com/problems/poor-pigs/discuss/94266/Another-explanation-and-solution) | | 461 | [Hamming Distance](https://leetcode.com/problems/hamming-distance/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/461_Hamming_Distance.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/461_Hamming_Distance.java) | Hamming Distance is related to XOR for numbers. So, XOR then count 1. O(n) | | 463 | [Island Perimeter](https://leetcode.com/problems/island-perimeter/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/463_Island_Perimeter.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/463_Island_Perimeter.java) | math, find the area, actual number, then find the digit | | 475 | [Heaters](https://leetcode.com/problems/heaters/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/475_Heaters.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/475_Heaters.java) | 1. Binary search hourse in heater array, O(nlogn) and O(1)
2. Two points, O(nlogn) and O(1) | diff --git a/java/458_Poor_Pigs.java b/java/458_Poor_Pigs.java new file mode 100644 index 0000000..6d3885b --- /dev/null +++ b/java/458_Poor_Pigs.java @@ -0,0 +1,8 @@ +class Solution { + public int poorPigs(int buckets, int minutesToDie, int minutesToTest) { + int n = minutesToTest / minutesToDie + 1; + int pigs = 0; + while (Math.pow(n, pigs) < buckets) pigs++; + return pigs; + } +} diff --git a/python/458_Poor_Pigs.py b/python/458_Poor_Pigs.py new file mode 100644 index 0000000..c667642 --- /dev/null +++ b/python/458_Poor_Pigs.py @@ -0,0 +1,13 @@ +class Solution(object): + def poorPigs(self, buckets, minutesToDie, minutesToTest): + """ + :type buckets: int + :type minutesToDie: int + :type minutesToTest: int + :rtype: int + """ + # https://leetcode.com/problems/poor-pigs/discuss/94266/Another-explanation-and-solution + pigs = 0 + while (minutesToTest / minutesToDie + 1) ** pigs < buckets: + pigs += 1 + return pigs From d58b053c2527ae35db57ed0c421a405fada0af83 Mon Sep 17 00:00:00 2001 From: Qiyuan Gong Date: Tue, 11 Dec 2018 23:33:17 +0800 Subject: [PATCH 013/119] 695_Max_Area_of_Island --- README.md | 2 + java/695_Max_Area_of_Island.java | 57 +++++++++++++++++++++++++++ python/695_Max_Area_of_Island.py | 67 ++++++++++++++++++++++++++++++++ 3 files changed, 126 insertions(+) create mode 100644 java/695_Max_Area_of_Island.java create mode 100644 python/695_Max_Area_of_Island.py diff --git a/README.md b/README.md index 02011e2..af676b1 100644 --- a/README.md +++ b/README.md @@ -153,6 +153,7 @@ Also, there are open source implementations for basic data structs and algorithm | 482 | [License Key Formatting](https://leetcode.com/problems/license-key-formatting/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/482_License_Key_Formatting.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/482_License_Key_Formatting.java) | String processing, lower and len % K, O(n) and O(n) | | 538 | [Convert BST to Greater Tree](https://leetcode.com/problems/convert-bst-to-greater-tree/description/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/538_Convert_BST_to_Greater_Tree.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/538_Convert_BST_to_Greater_Tree.java) | Right first DFS with a variable recording sum of node.val and right.val. 1. Recursive.
2. Stack 3. Reverse Morris In-order Traversal | | 543 | [Diameter of Binary Tree](https://leetcode.com/problems/diameter-of-binary-tree/description/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/543_Diameter_of_Binary_Tree.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/543_Diameter_of_Binary_Tree.java) | DFS with O(1) for max answer | +| 547 | [Friend Circles](https://leetcode.com/problems/friend-circles/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/547_Friend_Circles.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/547_Friend_Circles.java) | 1. DFS, O(n^2) and O(1)
2. BFS, O(n^2) and O(1)
3. Union-find, | | 557 | [Reverse Words in a String III](https://leetcode.com/problems/reverse-words-in-a-string-iii/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/557_Reverse_Words_in_a_String_III.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/557_Reverse_Words_in_a_String_III.java) | String handle: Split with space than reverse word, O(n) and O(n). Better solution is that reverse can be O(1) space in array. | | 560 | [Subarray Sum Equals K](https://leetcode.com/problems/subarray-sum-equals-k/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/560_Subarray_Sum_Equals_K.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/560_Subarray_Sum_Equals_K.java) | Note that there are n^2 possible pairs, so the key point is accelerate computation for sum and reduce unnecessary pair. 1. Cummulative sum, O(n^2) and O(1)/O(n)
2. Add sum into hash, check if sum - k is in hash, O(n) and O(n) | | 572 | [Subtree of Another Tree](https://leetcode.com/problems/subtree-of-another-tree/description/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/572_Subtree_of_Another_Tree.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/572_Subtree_of_Another_Tree.java) | 1. Tree traverse and compare
2. Tree to string and compare | @@ -163,6 +164,7 @@ Also, there are open source implementations for basic data structs and algorithm | 654 | [Maximum Binary Tree](https://leetcode.com/problems/maximum-binary-tree/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/654_Maximum_Binary_Tree.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/654_Maximum_Binary_Tree.java) | 1. Divide and conquer, recursive, O(n^2)
2. Monotonic stack, O(n) | | 680 | [Valid Palindrome II](https://leetcode.com/problems/valid-palindrome-ii/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/680_Valid_Palindrome_II.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/680_Valid_Palindrome_II.java) | Recursively check s[left == end, when not equal delete left or right. | | 692 | [Top K Frequent Words](https://leetcode.com/problems/top-k-frequent-words/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/692_Top_K_Frequent_Words.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/692_Top_K_Frequent_Words.java) | 1. Sort based on frequency and alphabetical order, O(nlgn) and O(n)
2. Find top k with Heap, O(nlogk) and O(n) | +| 695 | [Max Area of Island](https://leetcode.com/problems/max-area-of-island/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/695_Max_Area_of_Island.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/695_Max_Area_of_Island.java) | 1. DFS, O(n^2) and O(n)
2. BFS, O(n^2) and O(n)| | 697 | [Degree of an Array](https://leetcode.com/problems/degree-of-an-array/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/697_Degree_of_an_Array.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/697_Degree_of_an_Array.java) | 1. Find degree and value, then find smallest subarray (start and end with this value), O(n) and O(n)
2. Go through nums, remember left most pos and right most for each value, O(n) and O(n) | | 703 | [Kth Largest Element in a Stream](https://leetcode.com/problems/kth-largest-element-in-a-stream/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/703_Kth_Largest_Element_in_a_Stream.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/703_Kth_Largest_Element_in_a_Stream.java) | 1. Sort and insert into right place, O(nlgn) and O(n)
2. k largest heap, O(nlogk) and O(n) | | 706 | [Design HashMap](https://leetcode.com/problems/design-hashmap/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/706_Design_HashMap.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/706_Design_HashMap.java) | Hash implementation, mod is fine. Be careful about key conflict and key remove. | diff --git a/java/695_Max_Area_of_Island.java b/java/695_Max_Area_of_Island.java new file mode 100644 index 0000000..5a7a20d --- /dev/null +++ b/java/695_Max_Area_of_Island.java @@ -0,0 +1,57 @@ +/*class Solution { + int[][] grid; + + public int area(int r, int c) { + if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length || grid[r][c] == 0) + return 0; + grid[r][c] = 0; + return (1 + area(r + 1, c) + area(r - 1, c) + + area(r, c - 1) + area(r, c + 1)); + } + + public int maxAreaOfIsland(int[][] grid) { + this.grid = grid; + int ans = 0; + for (int r = 0; r < grid.length; r++) { + for (int c = 0; c < grid[0].length; c++) { + ans = Math.max(ans, area(r, c)); + } + } + return ans; + } +}*/ +class Solution { + // DFS and you can implement BFS with queue + public int maxAreaOfIsland(int[][] grid) { + int[] dr = new int[]{1, -1, 0, 0}; + int[] dc = new int[]{0, 0, 1, -1}; + int ans = 0; + for (int r0 = 0; r0 < grid.length; r0++) { + for (int c0 = 0; c0 < grid[0].length; c0++) { + if (grid[r0][c0] == 1) { + int shape = 0; + Stack stack = new Stack(); + stack.push(new int[]{r0, c0}); + grid[r0][c0] = 0; + while (!stack.empty()) { + int[] node = stack.pop(); + int r = node[0], c = node[1]; + shape++; + for (int k = 0; k < 4; k++) { + int nr = r + dr[k]; + int nc = c + dc[k]; + if (0 <= nr && nr < grid.length && + 0 <= nc && nc < grid[0].length && + grid[nr][nc] == 1) { + stack.push(new int[]{nr, nc}); + grid[nr][nc] = 0; + } + } + } + ans = Math.max(ans, shape); + } + } + } + return ans; + } +} diff --git a/python/695_Max_Area_of_Island.py b/python/695_Max_Area_of_Island.py new file mode 100644 index 0000000..1d622d4 --- /dev/null +++ b/python/695_Max_Area_of_Island.py @@ -0,0 +1,67 @@ +class Solution(object): + def maxAreaOfIsland(self, grid): + """ + :type grid: List[List[int]] + :rtype: int + """ + # because + ans = 0 + for i in range(len(grid)): + for j in range(len(grid[0])): + if grid[i][j] == 1: + grid[i][j] = 0 + ans = max(self.dfs(grid, i, j), ans) + # ans = max(self.bfs(grid, i, j), ans) + return ans + + def dfs(self, grid, i, j): + # DFS based on stack + stack = [(i, j)] + area = 0 + # Stack for DFS + while stack: + r, c = stack.pop(-1) + area += 1 + for nr, nc in ((r - 1, c), (r + 1, c), (r, c - 1), (r, c + 1)): + if (0 <= nr < len(grid) and + 0 <= nc < len(grid[0]) and grid[nr][nc]): + stack.append((nr, nc)) + grid[nr][nc] = 0 + return area + + # def bfs(self, grid, x, y): + # # BFS based on queue + # queue = [(x, y)] + # area = 0 + # # Stack for DFS + # while queue: + # i, j = queue.pop(0) + # area += 1 + # if i - 1 >= 0 and grid[i - 1][j] == 1: + # grid[i - 1][j] = 0 + # queue.append((i - 1, j)) + # if i + 1 < len(grid) and grid[i + 1][j] == 1: + # grid[i + 1][j] = 0 + # queue.append((i + 1, j)) + # if j - 1 >= 0 and grid[i][j - 1] == 1: + # grid[i][j - 1] = 0 + # queue.append((i, j - 1)) + # if j + 1 < len(grid[0]) and grid[i][j + 1] == 1: + # grid[i][j + 1] = 0 + # queue.append((i, j + 1)) + # return area + + # def maxAreaOfIsland(self, grid): + # # Recursive DFS + # seen = set() + # def area(r, c): + # if not (0 <= r < len(grid) and 0 <= c < len(grid[0]) + # and (r, c) not in seen and grid[r][c]): + # return 0 + # seen.add((r, c)) + # return (1 + area(r+1, c) + area(r-1, c) + + # area(r, c-1) + area(r, c+1)) + + # return max(area(r, c) + # for r in range(len(grid)) + # for c in range(len(grid[0]))) From 02b81c389d40dad63ca49f845faafc8edcb6747e Mon Sep 17 00:00:00 2001 From: Qiyuan Gong Date: Sat, 22 Dec 2018 18:03:54 +0800 Subject: [PATCH 014/119] 547_Friend_Circles --- README.md | 2 +- java/547_Friend_Circles.java | 76 +++++++++++++++++++++++++++++ python/547_Friend_Circles.py | 92 ++++++++++++++++++++++++++++++++++++ 3 files changed, 169 insertions(+), 1 deletion(-) create mode 100644 java/547_Friend_Circles.java create mode 100644 python/547_Friend_Circles.py diff --git a/README.md b/README.md index af676b1..1862e59 100644 --- a/README.md +++ b/README.md @@ -153,7 +153,7 @@ Also, there are open source implementations for basic data structs and algorithm | 482 | [License Key Formatting](https://leetcode.com/problems/license-key-formatting/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/482_License_Key_Formatting.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/482_License_Key_Formatting.java) | String processing, lower and len % K, O(n) and O(n) | | 538 | [Convert BST to Greater Tree](https://leetcode.com/problems/convert-bst-to-greater-tree/description/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/538_Convert_BST_to_Greater_Tree.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/538_Convert_BST_to_Greater_Tree.java) | Right first DFS with a variable recording sum of node.val and right.val. 1. Recursive.
2. Stack 3. Reverse Morris In-order Traversal | | 543 | [Diameter of Binary Tree](https://leetcode.com/problems/diameter-of-binary-tree/description/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/543_Diameter_of_Binary_Tree.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/543_Diameter_of_Binary_Tree.java) | DFS with O(1) for max answer | -| 547 | [Friend Circles](https://leetcode.com/problems/friend-circles/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/547_Friend_Circles.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/547_Friend_Circles.java) | 1. DFS, O(n^2) and O(1)
2. BFS, O(n^2) and O(1)
3. Union-find, | +| 547 | [Friend Circles](https://leetcode.com/problems/friend-circles/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/547_Friend_Circles.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/547_Friend_Circles.java) | 1. DFS, O(n^2) and O(1)
2. BFS, O(n^2) and O(1)
3. Union-find, O(n^2) and O(n)| | 557 | [Reverse Words in a String III](https://leetcode.com/problems/reverse-words-in-a-string-iii/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/557_Reverse_Words_in_a_String_III.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/557_Reverse_Words_in_a_String_III.java) | String handle: Split with space than reverse word, O(n) and O(n). Better solution is that reverse can be O(1) space in array. | | 560 | [Subarray Sum Equals K](https://leetcode.com/problems/subarray-sum-equals-k/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/560_Subarray_Sum_Equals_K.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/560_Subarray_Sum_Equals_K.java) | Note that there are n^2 possible pairs, so the key point is accelerate computation for sum and reduce unnecessary pair. 1. Cummulative sum, O(n^2) and O(1)/O(n)
2. Add sum into hash, check if sum - k is in hash, O(n) and O(n) | | 572 | [Subtree of Another Tree](https://leetcode.com/problems/subtree-of-another-tree/description/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/572_Subtree_of_Another_Tree.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/572_Subtree_of_Another_Tree.java) | 1. Tree traverse and compare
2. Tree to string and compare | diff --git a/java/547_Friend_Circles.java b/java/547_Friend_Circles.java new file mode 100644 index 0000000..2db54c3 --- /dev/null +++ b/java/547_Friend_Circles.java @@ -0,0 +1,76 @@ +public class Solution { + public void dfs(int[][] M, int[] visited, int i) { + for (int j = 0; j < M.length; j++) { + if (M[i][j] == 1 && visited[j] == 0) { + visited[j] = 1; + dfs(M, visited, j); + } + } + } + public int findCircleNum(int[][] M) { + // DFS + int[] visited = new int[M.length]; + int count = 0; + for (int i = 0; i < M.length; i++) { + if (visited[i] == 0) { + dfs(M, visited, i); + count++; + } + } + return count; + } + + /*public int findCircleNum(int[][] M) { + // BFS + int[] visited = new int[M.length]; + int count = 0; + Queue < Integer > queue = new LinkedList < > (); + for (int i = 0; i < M.length; i++) { + if (visited[i] == 0) { + queue.add(i); + while (!queue.isEmpty()) { + int s = queue.remove(); + visited[s] = 1; + for (int j = 0; j < M.length; j++) { + if (M[s][j] == 1 && visited[j] == 0) + queue.add(j); + } + } + count++; + } + } + return count; + }*/ + + /* + // Union find + int find(int parent[], int i) { + if (parent[i] == -1) + return i; + return find(parent, parent[i]); + } + + void union(int parent[], int x, int y) { + int xset = find(parent, x); + int yset = find(parent, y); + if (xset != yset) + parent[xset] = yset; + } + public int findCircleNum(int[][] M) { + int[] parent = new int[M.length]; + Arrays.fill(parent, -1); + for (int i = 0; i < M.length; i++) { + for (int j = 0; j < M.length; j++) { + if (M[i][j] == 1 && i != j) { + union(parent, i, j); + } + } + } + int count = 0; + for (int i = 0; i < parent.length; i++) { + if (parent[i] == -1) + count++; + } + return count; + }*/ +} \ No newline at end of file diff --git a/python/547_Friend_Circles.py b/python/547_Friend_Circles.py new file mode 100644 index 0000000..c1ae31b --- /dev/null +++ b/python/547_Friend_Circles.py @@ -0,0 +1,92 @@ +class Solution(object): + def findCircleNum(self, M): + """ + :type M: List[List[int]] + :rtype: int + """ + # because + visited = [0] * len(M) + count = 0 + for i in range(len(M)): + if visited[i] == 0: + self.dfs(M, visited, i) + count += 1 + return count + + def dfs(self, M, visited, i): + for j in range(len(M)): + if M[i][j] == 1 and visited[j] == 0: + visited[j] = 1 + self.dfs(M, visited, j) + + # def findCircleNum(self, M): + # # BFS + # visited = [0] * len(M) + # count = 0 + # queue = [] + # for i in range(len(M)): + # if visited[i] == 0: + # queue.append(i) + # while queue: + # curr = queue.pop(0) + # visited[curr] = 1 + # for j in range(len(M)): + # if M[curr][j] == 1 and visited[j] == 0: + # queue.append(j) + # count += 1 + # return count + +# def findCircleNum(self, M): +# # Union Find +# union = Union() +# for i in range(len(M)): +# union.add(i) +# for i in range(len(M)): +# for j in range(i + 1, len(M)): +# if M[i][j] == 1: +# union.union(i, j) +# return union.count + +# class Union(object): +# """ +# weighted quick union find +# """ +# def __init__(self): +# # both dic and list is fine +# self.id = {} +# self.sz = {} +# self.count = 0 + +# def count(self): +# return self.count + +# def connected(self, p, q): +# return self.find(p) == self.find(q) + +# def add(self, p): +# # init +# self.id[p] = p +# self.sz[p] = 1 +# self.count += 1 + +# def find(self, p): +# """ +# find root of p, and compress path +# """ +# while p != self.id[p]: +# self.id[p] = self.id[self.id[p]] +# p = self.id[p] +# return p + +# def union(self, p, q): +# """ +# connect p and q +# """ +# i, j = self.find(p), self.find(q) +# if i == j: +# return +# if self.sz[i] > self.sz[j]: +# i, j = j, i +# self.id[i] = j +# self.sz[j] += self.sz[i] +# self.count -= 1 From cc73dd748c15407cbd920aaf156e9798d040b1ec Mon Sep 17 00:00:00 2001 From: Qiyuan Gong Date: Sat, 22 Dec 2018 21:08:55 +0800 Subject: [PATCH 015/119] 236_Lowest_Common_Ancestor_of_a_Binary_Tree --- README.md | 1 + ...west_Common_Ancestor_of_a_Binary_Tree.java | 83 +++++++++++++++++++ ...Lowest_Common_Ancestor_of_a_Binary_Tree.py | 66 +++++++++++++++ 3 files changed, 150 insertions(+) create mode 100644 java/236_Lowest_Common_Ancestor_of_a_Binary_Tree.java create mode 100644 python/236_Lowest_Common_Ancestor_of_a_Binary_Tree.py diff --git a/README.md b/README.md index 1862e59..241fa7e 100644 --- a/README.md +++ b/README.md @@ -87,6 +87,7 @@ Also, there are open source implementations for basic data structs and algorithm | 220 | [Contains Duplicate III](https://leetcode.com/problems/contains-duplicate-iii/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/220_Contains_Duplicate_III.py) | 1. Sort and binary Search
2. Bucket sort | | 221 | [Maximal Square](https://leetcode.com/problems/maximal-square/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/221_Maximal_Square.py) | 1. Brute force
2. dp[i][j] = min(dp[i-1][j], dp[i-1][j-1], dp[i][j-1]) + 1, O(mn) and O(mn)
3. dp[j] = min([j], dp[j-1], prev) + 1, O(mn) and O(n)| | 228 | [Summary Ranges](https://leetcode.com/problems/summary-ranges/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/228_Summary_Ranges.py) | Detect start and jump, O(n) and O(1) | +| 236 | [Lowest Common Ancestor of a Binary Tree](https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/236_Lowest_Common_Ancestor_of_a_Binary_Tree.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/236_Lowest_Common_Ancestor_of_a_Binary_Tree.java) | 1. Recursive check left, val and right, LCA is the split paths in tree, O(n) and O(n)
2. Store parents during traversing tree, reverse check their lowest common parent, O(n) and O(n) | | 238 | [Product of Array Except Self](https://leetcode.com/problems/product-of-array-except-self/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/238_Product_of_Array_Except_Self.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/238_Product_of_Array_Except_Self.java) | The ans is [0,i -1] * [i+1, len- 1]. We can twice for left and right (reverse), O(n) and O(n) | | 243 | [Shortest Word Distance](https://leetcode.com/problems/shortest-word-distance/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/243_Shortest_Word_Distance.py) | Update index1 and index2, and check distance, O(n) and O(1) | | 246 | [Strobogrammatic Number](https://leetcode.com/problems/strobogrammatic-number/) ♥ | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/246_Strobogrammatic_Number.py) | Hash table and reverse string, O(n) and O(n) | diff --git a/java/236_Lowest_Common_Ancestor_of_a_Binary_Tree.java b/java/236_Lowest_Common_Ancestor_of_a_Binary_Tree.java new file mode 100644 index 0000000..2cb9da2 --- /dev/null +++ b/java/236_Lowest_Common_Ancestor_of_a_Binary_Tree.java @@ -0,0 +1,83 @@ +class Solution { + + private TreeNode ans; + + public Solution() { + // Variable to store LCA node. + this.ans = null; + } + + private boolean recurseTree(TreeNode currentNode, TreeNode p, TreeNode q) { + + // If reached the end of a branch, return false. + if (currentNode == null) { + return false; + } + + // Left Recursion. If left recursion returns true, set left = 1 else 0 + int left = this.recurseTree(currentNode.left, p, q) ? 1 : 0; + + // Right Recursion + int right = this.recurseTree(currentNode.right, p, q) ? 1 : 0; + + // If the current node is one of p or q + int mid = (currentNode == p || currentNode == q) ? 1 : 0; + + + // If any two of the flags left, right or mid become True + if (mid + left + right >= 2) { + this.ans = currentNode; + } + + // Return true if any one of the three bool values is True. + return (mid + left + right > 0); + } + + public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { + // Traverse the tree + this.recurseTree(root, p, q); + return this.ans; + } + + /*public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { + // Stack for tree traversal + Deque stack = new ArrayDeque<>(); + + // HashMap for parent pointers + Map parent = new HashMap<>(); + + parent.put(root, null); + stack.push(root); + + // Iterate until we find both the nodes p and q + while (!parent.containsKey(p) || !parent.containsKey(q)) { + + TreeNode node = stack.pop(); + + // While traversing the tree, keep saving the parent pointers. + if (node.left != null) { + parent.put(node.left, node); + stack.push(node.left); + } + if (node.right != null) { + parent.put(node.right, node); + stack.push(node.right); + } + } + + // Ancestors set() for node p. + Set ancestors = new HashSet<>(); + + // Process all ancestors for node p using parent pointers. + while (p != null) { + ancestors.add(p); + p = parent.get(p); + } + + // The first ancestor of q which appears in + // p's ancestor set() is their lowest common ancestor. + while (!ancestors.contains(q)) + q = parent.get(q); + return q; + }*/ +} diff --git a/python/236_Lowest_Common_Ancestor_of_a_Binary_Tree.py b/python/236_Lowest_Common_Ancestor_of_a_Binary_Tree.py new file mode 100644 index 0000000..13859c9 --- /dev/null +++ b/python/236_Lowest_Common_Ancestor_of_a_Binary_Tree.py @@ -0,0 +1,66 @@ +# Definition for a binary tree node. +# class TreeNode(object): +# def __init__(self, x): +# self.val = x +# self.left = None +# self.right = None + +class Solution(object): + # def lowestCommonAncestor(self, root, p, q): + # """ + # :type root: TreeNode + # :type p: TreeNode + # :type q: TreeNode + # :rtype: TreeNode + # """ + # self.ans = None + + # def lowestCommonAncestorHelper(node): + # if not node: + # return False + # left = lowestCommonAncestorHelper(node.left) + # right = lowestCommonAncestorHelper(node.right) + # mid = node == p or node == q + # if mid + left + right >= 2: + # self.ans = node + # return mid or left or right + # lowestCommonAncestorHelper(root) + # return self.ans + + def lowestCommonAncestor(self, root, p, q): + """ + :type root: TreeNode + :type p: TreeNode + :type q: TreeNode + :rtype: TreeNode + """ + # Stack for tree traversal + stack = [root] + # Dictionary for parent pointers + parent = {root: None} + # Iterate until we find both the nodes p and q + while p not in parent or q not in parent: + + node = stack.pop() + + # While traversing the tree, keep saving the parent pointers. + if node.left: + parent[node.left] = node + stack.append(node.left) + if node.right: + parent[node.right] = node + stack.append(node.right) + + # Ancestors set() for node p. + ancestors = set() + + # Process all ancestors for node p using parent pointers. + while p: + ancestors.add(p) + p = parent[p] + + # The first ancestor of q which appears in + # p's ancestor set() is their lowest common ancestor. + while q not in ancestors: + q = parent[q] + return q From a8744c4f1018108e8a444668e1bc425900bc733e Mon Sep 17 00:00:00 2001 From: Qiyuan Gong Date: Sat, 22 Dec 2018 22:20:04 +0800 Subject: [PATCH 016/119] 867_Transpose_Matrix --- README.md | 3 ++- java/867_Transpose_Matrix.java | 11 +++++++++++ python/867_Transpose_Matrix.py | 14 ++++++++++++++ 3 files changed, 27 insertions(+), 1 deletion(-) create mode 100644 java/867_Transpose_Matrix.java create mode 100644 python/867_Transpose_Matrix.py diff --git a/README.md b/README.md index 241fa7e..b617b0a 100644 --- a/README.md +++ b/README.md @@ -181,7 +181,8 @@ Also, there are open source implementations for basic data structs and algorithm | 811 | [Subdomain Visit Count](https://leetcode.com/problems/subdomain-visit-count/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/811_Subdomain_Visit_Count.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/811_Subdomain_Visit_Count.java) | String split and HashMap, O(n) and O(n) | | 819 | [Most Common Word](https://leetcode.com/problems/most-common-word/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/819_Most_Common_Word.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/819_Most_Common_Word.java) | String processing, be careful about 'b,b,b'. regex is recommended. | | 844 | [Backspace String Compare](https://leetcode.com/problems/backspace-string-compare/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/844_Backspace_String_Compare.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/844_Backspace_String_Compare.java) | 1. Stack pop when encounters #, O(n) and O(n)
2. Compare string from end to start, O(n) and O(1) | -| 852 | [Peak Index in a Mountain Array](https://leetcode.com/problems/peak-index-in-a-mountain-array/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/852_Peak_Index_in_a_Mountain_Array.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/852_Peak_Index_in_a_Mountain_Array.java) | 1. Scan the array until encountering decline, O(n) and O(1)
2. Binary seach with additional check for [i + 1], O(logn) and O(1)| +| 852 | [Peak Index in a Mountain Array](https://leetcode.com/problems/peak-index-in-a-mountain-array/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/852_Peak_Index_in_a_Mountain_Array.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/852_Peak_Index_in_a_Mountain_Array.java) | 1. Scan the array until encountering decline, O(n) and O(1)
2. Binary seach with additional check for [i + 1], O(logn) and O(1) | +| 867 | [Transpose Matrix](https://leetcode.com/problems/transpose-matrix/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/867_Transpose_Matrix.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/867_Transpose_Matrix.java) | Res[i][j] = A[j][i] | | 876 | [Middle of the Linked List](https://leetcode.com/problems/middle-of-the-linked-list/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/876_Middle_of_the_Linked_List.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/876_Middle_of_the_Linked_List.java) | 1. Copy to array, O(n) and O(n)
2. Fast and slow point, where fast point is 2 times faster than slow point, O(n) and O(1) | | 904 | [Fruit Into Baskets](https://leetcode.com/problems/fruit-into-baskets/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/904_Fruit_Into_Baskets.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/904_Fruit_Into_Baskets.java) | 1. Scan through blocks of tree, O(n) and O(n)
2. Mainten a sliding window with start and curr point, O(n) and O(n). | | 905 | [Sort Array By Parity](https://leetcode.com/problems/sort-array-by-parity/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/905_Sort_Array_By_Parity.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/905_Sort_Array_By_Parity.java) | 1. Sort with condition, O(nlogn) and O(1)
2. Scan all and split odd and even number into different array, O(n) and O(n)
3. In place swap similar to quick sort, O(n) and O(1) | diff --git a/java/867_Transpose_Matrix.java b/java/867_Transpose_Matrix.java new file mode 100644 index 0000000..57141a3 --- /dev/null +++ b/java/867_Transpose_Matrix.java @@ -0,0 +1,11 @@ +class Solution { + public int[][] transpose(int[][] A) { + int R = A.length, C = A[0].length; + int[][] ans = new int[C][R]; + for (int r = 0; r < R; ++r) + for (int c = 0; c < C; ++c) { + ans[c][r] = A[r][c]; + } + return ans; + } +} diff --git a/python/867_Transpose_Matrix.py b/python/867_Transpose_Matrix.py new file mode 100644 index 0000000..00c3b23 --- /dev/null +++ b/python/867_Transpose_Matrix.py @@ -0,0 +1,14 @@ +class Solution(object): + def transpose(self, A): + """ + :type A: List[List[int]] + :rtype: List[List[int]] + """ + R, C = len(A), len(A[0]) + ans = [[None] * R for _ in xrange(C)] + for r, row in enumerate(A): + for c, val in enumerate(row): + ans[c][r] = val + return ans + #Alternative Solution: + #return zip(*A) From f96c51209837446033a20b5fd29f39e8e8fc3399 Mon Sep 17 00:00:00 2001 From: Qiyuan Gong Date: Sat, 22 Dec 2018 22:53:40 +0800 Subject: [PATCH 017/119] 700_Search_in_a_Binary_Search_Tree --- README.md | 1 + java/700_Search_in_a_Binary_Search_Tree.java | 24 ++++++++++++++ python/700_Search_in_a_Binary_Search_Tree.py | 33 ++++++++++++++++++++ python/867_Transpose_Matrix.py | 13 ++++++-- 4 files changed, 69 insertions(+), 2 deletions(-) create mode 100644 java/700_Search_in_a_Binary_Search_Tree.java create mode 100644 python/700_Search_in_a_Binary_Search_Tree.py diff --git a/README.md b/README.md index b617b0a..c3a98f1 100644 --- a/README.md +++ b/README.md @@ -167,6 +167,7 @@ Also, there are open source implementations for basic data structs and algorithm | 692 | [Top K Frequent Words](https://leetcode.com/problems/top-k-frequent-words/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/692_Top_K_Frequent_Words.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/692_Top_K_Frequent_Words.java) | 1. Sort based on frequency and alphabetical order, O(nlgn) and O(n)
2. Find top k with Heap, O(nlogk) and O(n) | | 695 | [Max Area of Island](https://leetcode.com/problems/max-area-of-island/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/695_Max_Area_of_Island.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/695_Max_Area_of_Island.java) | 1. DFS, O(n^2) and O(n)
2. BFS, O(n^2) and O(n)| | 697 | [Degree of an Array](https://leetcode.com/problems/degree-of-an-array/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/697_Degree_of_an_Array.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/697_Degree_of_an_Array.java) | 1. Find degree and value, then find smallest subarray (start and end with this value), O(n) and O(n)
2. Go through nums, remember left most pos and right most for each value, O(n) and O(n) | +| 700 | [Search in a Binary Search Tree](https://leetcode.com/problems/search-in-a-binary-search-tree/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/700_Search_in_a_Binary_Search_Tree.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/700_Search_in_a_Binary_Search_Tree.java) | Recursive or iteration, O(logn) | | 703 | [Kth Largest Element in a Stream](https://leetcode.com/problems/kth-largest-element-in-a-stream/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/703_Kth_Largest_Element_in_a_Stream.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/703_Kth_Largest_Element_in_a_Stream.java) | 1. Sort and insert into right place, O(nlgn) and O(n)
2. k largest heap, O(nlogk) and O(n) | | 706 | [Design HashMap](https://leetcode.com/problems/design-hashmap/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/706_Design_HashMap.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/706_Design_HashMap.java) | Hash implementation, mod is fine. Be careful about key conflict and key remove. | | 709 | [To Lower Case](https://leetcode.com/problems/to-lower-case/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/709_To_Lower_Case.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/709_To_Lower_Case.java) | String processing:
1. str.lower() or str.toLowerCase()
2. ASCII processing. O(n) and O(1) | diff --git a/java/700_Search_in_a_Binary_Search_Tree.java b/java/700_Search_in_a_Binary_Search_Tree.java new file mode 100644 index 0000000..0389652 --- /dev/null +++ b/java/700_Search_in_a_Binary_Search_Tree.java @@ -0,0 +1,24 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +class Solution { + /*public TreeNode searchBST(TreeNode root, int val) { + // Recursive + if (root == null) return root; + if (root.val == val) return root; + else return val val: + # return self.searchBST(root.left, val) + # else: + # return self.searchBST(root.right, val) + + def searchBST(self, root, val): + while root: + if root.val == val: + return root + elif root.val > val: + root = root.left + else: + root = root.right + return root diff --git a/python/867_Transpose_Matrix.py b/python/867_Transpose_Matrix.py index 00c3b23..61b3ded 100644 --- a/python/867_Transpose_Matrix.py +++ b/python/867_Transpose_Matrix.py @@ -10,5 +10,14 @@ def transpose(self, A): for c, val in enumerate(row): ans[c][r] = val return ans - #Alternative Solution: - #return zip(*A) + # Alternative Solution: + # return zip(*A) + + # def transpose(self, A): + # res = [] + # for i in range(len(A[0])): + # temp = [] + # for j in range(len(A)): + # temp.append(A[j][i]) + # res.append(temp) + # return res From 52f1d3762ee443dd49a7db3d5b76bfee8285cfb8 Mon Sep 17 00:00:00 2001 From: Qiyuan Gong Date: Sat, 22 Dec 2018 23:02:14 +0800 Subject: [PATCH 018/119] 832_Flipping_an_Image --- README.md | 1 + java/832_Flipping_an_Image.java | 13 +++++++++++++ python/832_Flipping_an_Image.py | 11 +++++++++++ 3 files changed, 25 insertions(+) create mode 100644 java/832_Flipping_an_Image.java create mode 100644 python/832_Flipping_an_Image.py diff --git a/README.md b/README.md index c3a98f1..b9941a0 100644 --- a/README.md +++ b/README.md @@ -181,6 +181,7 @@ Also, there are open source implementations for basic data structs and algorithm | 804 | [Unique Morse Code Words](https://leetcode.com/problems/unique-morse-code-words/description/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/804_Unique_Morse_Code_Words.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/804_Unique_Morse_Code_Words.java) | String, Hash and Set. Set is recommended. | | 811 | [Subdomain Visit Count](https://leetcode.com/problems/subdomain-visit-count/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/811_Subdomain_Visit_Count.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/811_Subdomain_Visit_Count.java) | String split and HashMap, O(n) and O(n) | | 819 | [Most Common Word](https://leetcode.com/problems/most-common-word/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/819_Most_Common_Word.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/819_Most_Common_Word.java) | String processing, be careful about 'b,b,b'. regex is recommended. | +| 832 | [Flipping an Image](https://leetcode.com/problems/flipping-an-image/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/832_Flipping_an_Image.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/832_Flipping_an_Image.java) | Invert and swap can be done at the same time, and careful about (n + 1)/2, O(n^2) and O(1) | | 844 | [Backspace String Compare](https://leetcode.com/problems/backspace-string-compare/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/844_Backspace_String_Compare.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/844_Backspace_String_Compare.java) | 1. Stack pop when encounters #, O(n) and O(n)
2. Compare string from end to start, O(n) and O(1) | | 852 | [Peak Index in a Mountain Array](https://leetcode.com/problems/peak-index-in-a-mountain-array/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/852_Peak_Index_in_a_Mountain_Array.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/852_Peak_Index_in_a_Mountain_Array.java) | 1. Scan the array until encountering decline, O(n) and O(1)
2. Binary seach with additional check for [i + 1], O(logn) and O(1) | | 867 | [Transpose Matrix](https://leetcode.com/problems/transpose-matrix/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/867_Transpose_Matrix.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/867_Transpose_Matrix.java) | Res[i][j] = A[j][i] | diff --git a/java/832_Flipping_an_Image.java b/java/832_Flipping_an_Image.java new file mode 100644 index 0000000..4a7c151 --- /dev/null +++ b/java/832_Flipping_an_Image.java @@ -0,0 +1,13 @@ +class Solution { + public int[][] flipAndInvertImage(int[][] A) { + int C = A[0].length; + for (int[] row: A) + for (int i = 0; i < (C + 1) / 2; ++i) { + int tmp = row[i] ^ 1; + row[i] = row[C - 1 - i] ^ 1; + row[C - 1 - i] = tmp; + } + + return A; + } +} diff --git a/python/832_Flipping_an_Image.py b/python/832_Flipping_an_Image.py new file mode 100644 index 0000000..3494f2f --- /dev/null +++ b/python/832_Flipping_an_Image.py @@ -0,0 +1,11 @@ +class Solution(object): + def flipAndInvertImage(self, A): + for row in A: + for i in xrange((len(row) + 1) / 2): + """ + In Python, the shortcut row[~i] = row[-i-1] = row[len(row) - 1 - i] + helps us find the i-th value of the row, counting from the right. + """ + row[i], row[~i] = row[~i] ^ 1, row[i] ^ 1 + return A + # return [[1 ^ i for i in row[::-1]] for row in A] From f002060cea7f42faf8d0f74192f000e39395fb4a Mon Sep 17 00:00:00 2001 From: Qiyuan Gong Date: Sun, 23 Dec 2018 13:28:58 +0800 Subject: [PATCH 019/119] 961_N-Repeated_Element_in_Size_2N_Array --- README.md | 1 + ...61_N-Repeated_Element_in_Size_2N_Array.java | 12 ++++++++++++ .../961_N-Repeated_Element_in_Size_2N_Array.py | 18 ++++++++++++++++++ 3 files changed, 31 insertions(+) create mode 100644 java/961_N-Repeated_Element_in_Size_2N_Array.java create mode 100644 python/961_N-Repeated_Element_in_Size_2N_Array.py diff --git a/README.md b/README.md index b9941a0..26cfd5f 100644 --- a/README.md +++ b/README.md @@ -194,6 +194,7 @@ Also, there are open source implementations for basic data structs and algorithm | 946 | [Validate Stack Sequences](https://leetcode.com/problems/validate-stack-sequences/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/946_Validate_Stack_Sequences.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/946_Validate_Stack_Sequences.java) | Add a stack named inStack to help going through pushed and popped. O(n) and O(n) | | 953 | [Verifying an Alien Dictionary](https://leetcode.com/contest/weekly-contest-114/problems/verifying-an-alien-dictionary/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/953_Verifying_an_Alien_Dictionary.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/953_Verifying_an_Alien_Dictionary.java) | Use hashmap to store index of each value, then create a comparator based on this index, O(n) and O(n) | | 954 | [Array of Doubled Pairs](https://leetcode.com/contest/weekly-contest-114/problems/array-of-doubled-pairs/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/954_Array_of_Doubled_Pairs.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/954_Array_of_Doubled_Pairs.java) | Sort, then use hashmap to store the frequency of each value. Then, check n, 2 * n in hashmap, O(nlogn) and O(n) | +| 961 | [N-Repeated Element in Size 2N Array](https://leetcode.com/problems/n-repeated-element-in-size-2n-array/submissions/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/961_N-Repeated_Element_in_Size_2N_Array.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/961_N-Repeated_Element_in_Size_2N_Array.java) | Hash and count number, O(n) and O(n) | | # | To Understand | |---| ----- | diff --git a/java/961_N-Repeated_Element_in_Size_2N_Array.java b/java/961_N-Repeated_Element_in_Size_2N_Array.java new file mode 100644 index 0000000..b4c4bfd --- /dev/null +++ b/java/961_N-Repeated_Element_in_Size_2N_Array.java @@ -0,0 +1,12 @@ +class Solution { + public int repeatedNTimes(int[] A) { + HashMap hash = new HashMap<>(); + int ans = A[0]; + for (int n: A) { + int count = hash.getOrDefault(n, 0) + 1; + hash.put(n, count); + if (count >= hash.get(ans)) ans = n; + } + return ans; + } +} diff --git a/python/961_N-Repeated_Element_in_Size_2N_Array.py b/python/961_N-Repeated_Element_in_Size_2N_Array.py new file mode 100644 index 0000000..4fa27e2 --- /dev/null +++ b/python/961_N-Repeated_Element_in_Size_2N_Array.py @@ -0,0 +1,18 @@ +import collections + + +class Solution(object): + def repeatedNTimes(self, A): + """ + :type A: List[int] + :rtype: int + """ + counter = collections.Counter(A) + return counter.most_common(1)[0][0] + + +if __name__ == '__main__': + s = Solution() + print s.repeatedNTimes([1, 2, 3, 3]) + print s.repeatedNTimes([2, 1, 2, 5, 3, 2]) + print s.repeatedNTimes([5, 1, 5, 2, 5, 3, 5, 4]) From 5a75da2ea3f3afd4181d90aa6ff68e5c93b31299 Mon Sep 17 00:00:00 2001 From: Qiyuan Gong Date: Sun, 23 Dec 2018 13:50:52 +0800 Subject: [PATCH 020/119] 674_Longest_Continuous_Increasing_Subsequence --- README.md | 1 + ...ngest_Continuous_Increasing_Subsequence.java | 15 +++++++++++++++ ...Longest_Continuous_Increasing_Subsequence.py | 17 +++++++++++++++++ 3 files changed, 33 insertions(+) create mode 100644 java/674_Longest_Continuous_Increasing_Subsequence.java create mode 100644 python/674_Longest_Continuous_Increasing_Subsequence.py diff --git a/README.md b/README.md index 26cfd5f..5bc2119 100644 --- a/README.md +++ b/README.md @@ -163,6 +163,7 @@ Also, there are open source implementations for basic data structs and algorithm | 617 | [Merge Two Binary Trees](https://leetcode.com/problems/merge-two-binary-trees/description/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/617_Merge_Two_Binary_Trees.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/617_Merge_Two_Binary_Trees.java) | Traverse both trees Recursion & Iterative (stack) | | 628 | [Maximum Product of Three Numbers](https://leetcode.com/problems/maximum-product-of-three-numbers/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/628_Maximum_Product_of_Three_Numbers.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/628_Maximum_Product_of_Three_Numbers.java) | Actually, we should only care about min1, min2 and max1-max3, to find these five elements, we can use 1. Brute force, O(n^3) and O(1)
2. Sort, O(nlogn) and O(1)
3. Single scan with 5 elements keep, O(n) and O(1) | | 654 | [Maximum Binary Tree](https://leetcode.com/problems/maximum-binary-tree/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/654_Maximum_Binary_Tree.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/654_Maximum_Binary_Tree.java) | 1. Divide and conquer, recursive, O(n^2)
2. Monotonic stack, O(n) | +| 674 | [Longest Continuous Increasing Subsequence](https://leetcode.com/problems/longest-continuous-increasing-subsequence/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/674_Longest_Continuous_Increasing_Subsequence.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/674_Longest_Continuous_Increasing_Subsequence.java) | Scan nums once, check nums[i] < nums[i+1], if not reset count, O(n) and O(1) | | 680 | [Valid Palindrome II](https://leetcode.com/problems/valid-palindrome-ii/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/680_Valid_Palindrome_II.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/680_Valid_Palindrome_II.java) | Recursively check s[left == end, when not equal delete left or right. | | 692 | [Top K Frequent Words](https://leetcode.com/problems/top-k-frequent-words/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/692_Top_K_Frequent_Words.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/692_Top_K_Frequent_Words.java) | 1. Sort based on frequency and alphabetical order, O(nlgn) and O(n)
2. Find top k with Heap, O(nlogk) and O(n) | | 695 | [Max Area of Island](https://leetcode.com/problems/max-area-of-island/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/695_Max_Area_of_Island.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/695_Max_Area_of_Island.java) | 1. DFS, O(n^2) and O(n)
2. BFS, O(n^2) and O(n)| diff --git a/java/674_Longest_Continuous_Increasing_Subsequence.java b/java/674_Longest_Continuous_Increasing_Subsequence.java new file mode 100644 index 0000000..0d267a5 --- /dev/null +++ b/java/674_Longest_Continuous_Increasing_Subsequence.java @@ -0,0 +1,15 @@ +class Solution { + public int findLengthOfLCIS(int[] nums) { + if (nums.length == 0) return 0; + int curr = 1, ans = 1; + for (int i = 0; i < nums.length - 1; i++) { + if (nums[i] < nums[i + 1]) { + curr ++; + if (curr >= ans) ans = curr; + } else { + curr = 1; + } + } + return ans; + } +} diff --git a/python/674_Longest_Continuous_Increasing_Subsequence.py b/python/674_Longest_Continuous_Increasing_Subsequence.py new file mode 100644 index 0000000..3d4edfe --- /dev/null +++ b/python/674_Longest_Continuous_Increasing_Subsequence.py @@ -0,0 +1,17 @@ +class Solution(object): + def findLengthOfLCIS(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + if not nums or len(nums) == 0: + return 0 + ans = curr = 1 + for i in range(len(nums) - 1): + if nums[i] < nums[i + 1]: + curr += 1 + if curr >= ans: + ans = curr + else: + curr = 1 + return ans From b173c5874003e30111dbfec28aefc70fb6e69b1d Mon Sep 17 00:00:00 2001 From: Qiyuan Gong Date: Sun, 23 Dec 2018 20:28:15 +0800 Subject: [PATCH 021/119] 223_Rectangle_Area --- README.md | 1 + java/223_Rectangle_Area.java | 9 +++++++++ python/223_Rectangle Area.py | 2 +- python/674_Longest_Continuous_Increasing_Subsequence.py | 3 +-- 4 files changed, 12 insertions(+), 3 deletions(-) create mode 100644 java/223_Rectangle_Area.java diff --git a/README.md b/README.md index 5bc2119..75e879d 100644 --- a/README.md +++ b/README.md @@ -86,6 +86,7 @@ Also, there are open source implementations for basic data structs and algorithm | 219 | [Contains Duplicate II](https://leetcode.com/problems/contains-duplicate-ii/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/219_Contains_Duplicate_II.py) | 1. Brute force
2. Maintenance a set that contains previous k numbers, and check if curr in set | | 220 | [Contains Duplicate III](https://leetcode.com/problems/contains-duplicate-iii/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/220_Contains_Duplicate_III.py) | 1. Sort and binary Search
2. Bucket sort | | 221 | [Maximal Square](https://leetcode.com/problems/maximal-square/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/221_Maximal_Square.py) | 1. Brute force
2. dp[i][j] = min(dp[i-1][j], dp[i-1][j-1], dp[i][j-1]) + 1, O(mn) and O(mn)
3. dp[j] = min([j], dp[j-1], prev) + 1, O(mn) and O(n)| +| 223 | [Rectangle Area](https://leetcode.com/problems/rectangle-area/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/223_Rectangle_Area.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/223_Rectangle_Area.java) | Rectangle A + B - common area, O(1) and O(1) | | 228 | [Summary Ranges](https://leetcode.com/problems/summary-ranges/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/228_Summary_Ranges.py) | Detect start and jump, O(n) and O(1) | | 236 | [Lowest Common Ancestor of a Binary Tree](https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/236_Lowest_Common_Ancestor_of_a_Binary_Tree.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/236_Lowest_Common_Ancestor_of_a_Binary_Tree.java) | 1. Recursive check left, val and right, LCA is the split paths in tree, O(n) and O(n)
2. Store parents during traversing tree, reverse check their lowest common parent, O(n) and O(n) | | 238 | [Product of Array Except Self](https://leetcode.com/problems/product-of-array-except-self/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/238_Product_of_Array_Except_Self.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/238_Product_of_Array_Except_Self.java) | The ans is [0,i -1] * [i+1, len- 1]. We can twice for left and right (reverse), O(n) and O(n) | diff --git a/java/223_Rectangle_Area.java b/java/223_Rectangle_Area.java new file mode 100644 index 0000000..d78c7db --- /dev/null +++ b/java/223_Rectangle_Area.java @@ -0,0 +1,9 @@ +class Solution { + public int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) { + // https://leetcode.com/problems/rectangle-area/discuss/62149/Just-another-short-way + // Possible overlap area + int left = Math.max(A, E), right = Math.max(Math.min(C, G), left); + int bottom = Math.max(B, F), top = Math.max(Math.min(D, H), bottom); + return (C - A) * (D - B) - (right - left) * (top - bottom) + (G - E) * (H - F); + } +} diff --git a/python/223_Rectangle Area.py b/python/223_Rectangle Area.py index a4cc347..72f4488 100644 --- a/python/223_Rectangle Area.py +++ b/python/223_Rectangle Area.py @@ -20,4 +20,4 @@ def computeArea(self, A, B, C, D, E, F, G, H): dx = min(C, G) - max(A, E) # overlap length on y dy = min(D, H) - max(B, F) - return result - dx * dy \ No newline at end of file + return result - dx * dy diff --git a/python/674_Longest_Continuous_Increasing_Subsequence.py b/python/674_Longest_Continuous_Increasing_Subsequence.py index 3d4edfe..00d2295 100644 --- a/python/674_Longest_Continuous_Increasing_Subsequence.py +++ b/python/674_Longest_Continuous_Increasing_Subsequence.py @@ -10,8 +10,7 @@ def findLengthOfLCIS(self, nums): for i in range(len(nums) - 1): if nums[i] < nums[i + 1]: curr += 1 - if curr >= ans: - ans = curr + ans = max(ans, curr) else: curr = 1 return ans From 31090c93988d12d38ba0f7ff9a22c132e464992d Mon Sep 17 00:00:00 2001 From: Qiyuan Gong Date: Sun, 23 Dec 2018 20:43:27 +0800 Subject: [PATCH 022/119] 836_Rectangle_Overlap --- README.md | 1 + java/836_Rectangle_Overlap.java | 22 ++++++++++++++++++++++ python/836_Rectangle_Overlap.py | 17 +++++++++++++++++ 3 files changed, 40 insertions(+) create mode 100644 java/836_Rectangle_Overlap.java create mode 100644 python/836_Rectangle_Overlap.py diff --git a/README.md b/README.md index 75e879d..aba88c5 100644 --- a/README.md +++ b/README.md @@ -184,6 +184,7 @@ Also, there are open source implementations for basic data structs and algorithm | 811 | [Subdomain Visit Count](https://leetcode.com/problems/subdomain-visit-count/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/811_Subdomain_Visit_Count.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/811_Subdomain_Visit_Count.java) | String split and HashMap, O(n) and O(n) | | 819 | [Most Common Word](https://leetcode.com/problems/most-common-word/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/819_Most_Common_Word.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/819_Most_Common_Word.java) | String processing, be careful about 'b,b,b'. regex is recommended. | | 832 | [Flipping an Image](https://leetcode.com/problems/flipping-an-image/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/832_Flipping_an_Image.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/832_Flipping_an_Image.java) | Invert and swap can be done at the same time, and careful about (n + 1)/2, O(n^2) and O(1) | +| 836 | [Rectangle Overlap](https://leetcode.com/problems/rectangle-overlap/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/836_Rectangle_Overlap.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/836_Rectangle_Overlap.java) | 1. Check position, O(1) and O(1)
2. Check area, O(1) and O(1) | | 844 | [Backspace String Compare](https://leetcode.com/problems/backspace-string-compare/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/844_Backspace_String_Compare.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/844_Backspace_String_Compare.java) | 1. Stack pop when encounters #, O(n) and O(n)
2. Compare string from end to start, O(n) and O(1) | | 852 | [Peak Index in a Mountain Array](https://leetcode.com/problems/peak-index-in-a-mountain-array/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/852_Peak_Index_in_a_Mountain_Array.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/852_Peak_Index_in_a_Mountain_Array.java) | 1. Scan the array until encountering decline, O(n) and O(1)
2. Binary seach with additional check for [i + 1], O(logn) and O(1) | | 867 | [Transpose Matrix](https://leetcode.com/problems/transpose-matrix/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/867_Transpose_Matrix.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/867_Transpose_Matrix.java) | Res[i][j] = A[j][i] | diff --git a/java/836_Rectangle_Overlap.java b/java/836_Rectangle_Overlap.java new file mode 100644 index 0000000..3d0c364 --- /dev/null +++ b/java/836_Rectangle_Overlap.java @@ -0,0 +1,22 @@ +class Solution { + /*public boolean isRectangleOverlap(int[] rec1, int[] rec2) { + // Check position + return !(rec1[2] <= rec2[0] || // left + rec1[3] <= rec2[1] || // bottom + rec1[0] >= rec2[2] || // right + rec1[1] >= rec2[3]); // top + }*/ + /*public boolean isRectangleOverlap(int[] rec1, int[] rec2) { + // Check area + // https://leetcode.com/problems/rectangle-area/discuss/62149/Just-another-short-way + int left = Math.max(rec1[0], rec2[0]), right = Math.max(Math.min(rec1[2], rec2[2]), left); + int bottom = Math.max(rec1[1], rec2[1]), top = Math.max(Math.min(rec1[3], rec2[3]), bottom); + return (right - left) * (top - bottom) != 0; + }*/ + + public boolean isRectangleOverlap(int[] rec1, int[] rec2) { + // Check area + return (Math.min(rec1[2], rec2[2]) > Math.max(rec1[0], rec2[0]) && // width > 0 + Math.min(rec1[3], rec2[3]) > Math.max(rec1[1], rec2[1])); // height > 0 + } +} \ No newline at end of file diff --git a/python/836_Rectangle_Overlap.py b/python/836_Rectangle_Overlap.py new file mode 100644 index 0000000..6ebf235 --- /dev/null +++ b/python/836_Rectangle_Overlap.py @@ -0,0 +1,17 @@ +class Solution(object): + def isRectangleOverlap(self, rec1, rec2): + """ + :type rec1: List[int] + :type rec2: List[int] + :rtype: bool + """ + return not (rec1[2] <= rec2[0] or # left + rec1[3] <= rec2[1] or # bottom + rec1[0] >= rec2[2] or # right + rec1[1] >= rec2[3]) # top + + # def isRectangleOverlap(self, rec1, rec2): + # def intersect(p_left, p_right, q_left, q_right): + # return min(p_right, q_right) > max(p_left, q_left) + # return (intersect(rec1[0], rec1[2], rec2[0], rec2[2]) and + # intersect(rec1[1], rec1[3], rec2[1], rec2[3])) From 904dfb9b41afcfc59f616507dad4beea72cd6b0f Mon Sep 17 00:00:00 2001 From: Qiyuan Gong Date: Sun, 23 Dec 2018 22:44:50 +0800 Subject: [PATCH 023/119] 751_IP_to_CIDR --- README.md | 1 + java/751_IP_to_CIDR.java | 34 ++++++++++++++++++++++++++++++++++ python/751_IP_to_CIDR.py | 23 +++++++++++++++++++++++ 3 files changed, 58 insertions(+) create mode 100644 java/751_IP_to_CIDR.java create mode 100644 python/751_IP_to_CIDR.py diff --git a/README.md b/README.md index aba88c5..14991e0 100644 --- a/README.md +++ b/README.md @@ -178,6 +178,7 @@ Also, there are open source implementations for basic data structs and algorithm | 724 | [Find Pivot Index](https://leetcode.com/problems/find-pivot-index/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/724_Find_Pivot_Index.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/724_Find_Pivot_Index.java) | Seach the array to find a place where left sum is equal to right sum, O(n) and O(1) | | 733 | [Flood Fill](https://leetcode.com/problems/flood-fill/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/733_Flood_Fill.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/733_Flood_Fill.java) | 1. DFS with stack or recursive, O(n) and O(n)
2. BFS with queue, O(n) and O(n) | | 743 | [Network Delay Time](https://leetcode.com/problems/network-delay-time/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/743_Network_Delay_Time.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/743_Network_Delay_Time.java) | Let V == N, then: 1. DFS, O(V^V+ElgE), O(V+E)
2. Dijkstra, O(V^2+E), O(V+E)| +| 751 | [IP to CIDR](https://leetcode.com/problems/ip-to-cidr/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/751_IP_to_CIDR.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/751_IP_to_CIDR.java) | Bit manipulations, incrementail is 1 << (32 - mask) | | 766 | [Toeplitz Matrix](https://leetcode.com/problems/toeplitz-matrix/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/766_Toeplitz_Matrix.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/766_Toeplitz_Matrix.java) | Check from top left to bottom right, i,j == i + 1, j + 1. | | 771 | [Jewels and Stones](https://leetcode.com/problems/jewels-and-stones/description/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/771_Jewels_and_Stones.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/771_Jewels_and_Stones.java) | Count given char in string. Hash or table. [Oneline](https://leetcode.com/problems/jewels-and-stones/discuss/113574/1-liners-PythonJavaRuby) | | 804 | [Unique Morse Code Words](https://leetcode.com/problems/unique-morse-code-words/description/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/804_Unique_Morse_Code_Words.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/804_Unique_Morse_Code_Words.java) | String, Hash and Set. Set is recommended. | diff --git a/java/751_IP_to_CIDR.java b/java/751_IP_to_CIDR.java new file mode 100644 index 0000000..55fcad4 --- /dev/null +++ b/java/751_IP_to_CIDR.java @@ -0,0 +1,34 @@ +class Solution { + public List ipToCIDR(String ip, int n) { + long start = ipToLong(ip); + List ans = new ArrayList(); + while (n > 0) { + int mask = Math.max(33 - bitLength(Long.lowestOneBit(start)), + 33 - bitLength(n)); + ans.add(longToIP(start) + "/" + mask); + start += 1 << (32 - mask); + n -= 1 << (32 - mask); + } + return ans; + } + private long ipToLong(String ip) { + long ans = 0; + for (String x: ip.split("\\.")) { + ans = 256 * ans + Integer.valueOf(x); + } + return ans; + } + private String longToIP(long x) { + return String.format("%s.%s.%s.%s", + x >> 24, (x >> 16) % 256, (x >> 8) % 256, x % 256); + } + private int bitLength(long x) { + if (x == 0) return 1; + int ans = 0; + while (x > 0) { + x >>= 1; + ans++; + } + return ans; + } +} \ No newline at end of file diff --git a/python/751_IP_to_CIDR.py b/python/751_IP_to_CIDR.py new file mode 100644 index 0000000..cf4c7b1 --- /dev/null +++ b/python/751_IP_to_CIDR.py @@ -0,0 +1,23 @@ +class Solution(object): + def ipToInt(self, ip): + ans = 0 + for x in ip.split('.'): + ans = 256 * ans + int(x) + return ans + + def intToIP(self, x): + return ".".join(str((x >> i) % 256) + for i in (24, 16, 8, 0)) + + def ipToCIDR(self, ip, n): + # Start value of IP + start = self.ipToInt(ip) + ans = [] + while n: + # Last 1 of start or can start from 0 + mask = max(33 - (start & -start).bit_length(), + 33 - n.bit_length()) + ans.append(self.intToIP(start) + '/' + str(mask)) + start += 1 << (32 - mask) + n -= 1 << (32 - mask) + return ans From bcc32f5d46f5808792a83b63700f5413bf355706 Mon Sep 17 00:00:00 2001 From: Qiyuan Gong Date: Tue, 25 Dec 2018 09:09:11 +0800 Subject: [PATCH 024/119] 872_Leaf-Similar_Trees and 933_Number_of_Recent_Calls --- README.md | 4 +++- java/872_Leaf-Similar_Trees.java | 18 ++++++++++++++++ java/933_Number_of_Recent_Calls.java | 13 ++++++++++++ python/872_Leaf-Similar_Trees.py | 31 ++++++++++++++++++++++++++++ python/933_Number_of_Recent_Calls.py | 19 +++++++++++++++++ 5 files changed, 84 insertions(+), 1 deletion(-) create mode 100644 java/872_Leaf-Similar_Trees.java create mode 100644 java/933_Number_of_Recent_Calls.java create mode 100644 python/872_Leaf-Similar_Trees.py create mode 100644 python/933_Number_of_Recent_Calls.py diff --git a/README.md b/README.md index 14991e0..975438a 100644 --- a/README.md +++ b/README.md @@ -178,7 +178,7 @@ Also, there are open source implementations for basic data structs and algorithm | 724 | [Find Pivot Index](https://leetcode.com/problems/find-pivot-index/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/724_Find_Pivot_Index.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/724_Find_Pivot_Index.java) | Seach the array to find a place where left sum is equal to right sum, O(n) and O(1) | | 733 | [Flood Fill](https://leetcode.com/problems/flood-fill/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/733_Flood_Fill.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/733_Flood_Fill.java) | 1. DFS with stack or recursive, O(n) and O(n)
2. BFS with queue, O(n) and O(n) | | 743 | [Network Delay Time](https://leetcode.com/problems/network-delay-time/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/743_Network_Delay_Time.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/743_Network_Delay_Time.java) | Let V == N, then: 1. DFS, O(V^V+ElgE), O(V+E)
2. Dijkstra, O(V^2+E), O(V+E)| -| 751 | [IP to CIDR](https://leetcode.com/problems/ip-to-cidr/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/751_IP_to_CIDR.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/751_IP_to_CIDR.java) | Bit manipulations, incrementail is 1 << (32 - mask) | +| 751 | [IP to CIDR](https://leetcode.com/problems/ip-to-cidr/) ♥ | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/751_IP_to_CIDR.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/751_IP_to_CIDR.java) | Bit manipulations, incrementail is 1 << (32 - mask) | | 766 | [Toeplitz Matrix](https://leetcode.com/problems/toeplitz-matrix/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/766_Toeplitz_Matrix.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/766_Toeplitz_Matrix.java) | Check from top left to bottom right, i,j == i + 1, j + 1. | | 771 | [Jewels and Stones](https://leetcode.com/problems/jewels-and-stones/description/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/771_Jewels_and_Stones.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/771_Jewels_and_Stones.java) | Count given char in string. Hash or table. [Oneline](https://leetcode.com/problems/jewels-and-stones/discuss/113574/1-liners-PythonJavaRuby) | | 804 | [Unique Morse Code Words](https://leetcode.com/problems/unique-morse-code-words/description/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/804_Unique_Morse_Code_Words.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/804_Unique_Morse_Code_Words.java) | String, Hash and Set. Set is recommended. | @@ -189,11 +189,13 @@ Also, there are open source implementations for basic data structs and algorithm | 844 | [Backspace String Compare](https://leetcode.com/problems/backspace-string-compare/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/844_Backspace_String_Compare.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/844_Backspace_String_Compare.java) | 1. Stack pop when encounters #, O(n) and O(n)
2. Compare string from end to start, O(n) and O(1) | | 852 | [Peak Index in a Mountain Array](https://leetcode.com/problems/peak-index-in-a-mountain-array/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/852_Peak_Index_in_a_Mountain_Array.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/852_Peak_Index_in_a_Mountain_Array.java) | 1. Scan the array until encountering decline, O(n) and O(1)
2. Binary seach with additional check for [i + 1], O(logn) and O(1) | | 867 | [Transpose Matrix](https://leetcode.com/problems/transpose-matrix/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/867_Transpose_Matrix.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/867_Transpose_Matrix.java) | Res[i][j] = A[j][i] | +| 872 | [Leaf-Similar Trees](https://leetcode.com/problems/leaf-similar-trees/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/872_Leaf-Similar_Trees.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/872_Leaf-Similar_Trees.java) | DFS (stack or recursion) get leaf value sequence and compare, O(n) and O(n) | | 876 | [Middle of the Linked List](https://leetcode.com/problems/middle-of-the-linked-list/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/876_Middle_of_the_Linked_List.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/876_Middle_of_the_Linked_List.java) | 1. Copy to array, O(n) and O(n)
2. Fast and slow point, where fast point is 2 times faster than slow point, O(n) and O(1) | | 904 | [Fruit Into Baskets](https://leetcode.com/problems/fruit-into-baskets/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/904_Fruit_Into_Baskets.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/904_Fruit_Into_Baskets.java) | 1. Scan through blocks of tree, O(n) and O(n)
2. Mainten a sliding window with start and curr point, O(n) and O(n). | | 905 | [Sort Array By Parity](https://leetcode.com/problems/sort-array-by-parity/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/905_Sort_Array_By_Parity.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/905_Sort_Array_By_Parity.java) | 1. Sort with condition, O(nlogn) and O(1)
2. Scan all and split odd and even number into different array, O(n) and O(n)
3. In place swap similar to quick sort, O(n) and O(1) | | 922 | [Sort Array By Parity II](https://leetcode.com/problems/sort-array-by-parity-ii/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/922_Sort_Array_By_Parity_II.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/922_Sort_Array_By_Parity_II.java) | 1. Place odd and even number in odd and even place, not sort is needed. O(n) and O(1)
2. Two points with quick sort swap idea, O(n) and O(1). | | 929 | [Unique Email Addresses](https://leetcode.com/problems/unique-email-addresses/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/929_Unique_Email_Addresses.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/929_Unique_Email_Addresses.java) | String handle and hash (or set) | +| 933 | [Number of Recent Calls](https://leetcode.com/problems/number-of-recent-calls/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/933_Number_of_Recent_Calls.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/933_Number_of_Recent_Calls.java) | Queue, remove val in head when val < t - 3000, O(n) and O(n) | | 945 | [Minimum Increment to Make Array Unique](https://leetcode.com/problems/minimum-increment-to-make-array-unique/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/945_Minimum_Increment_to_Make_Array_Unique.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/945_Minimum_Increment_to_Make_Array_Unique.java) | Sort, then list duplicate and missing value in sorted list. O(nlgn) and O(n) | | 946 | [Validate Stack Sequences](https://leetcode.com/problems/validate-stack-sequences/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/946_Validate_Stack_Sequences.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/946_Validate_Stack_Sequences.java) | Add a stack named inStack to help going through pushed and popped. O(n) and O(n) | | 953 | [Verifying an Alien Dictionary](https://leetcode.com/contest/weekly-contest-114/problems/verifying-an-alien-dictionary/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/953_Verifying_an_Alien_Dictionary.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/953_Verifying_an_Alien_Dictionary.java) | Use hashmap to store index of each value, then create a comparator based on this index, O(n) and O(n) | diff --git a/java/872_Leaf-Similar_Trees.java b/java/872_Leaf-Similar_Trees.java new file mode 100644 index 0000000..32b91c0 --- /dev/null +++ b/java/872_Leaf-Similar_Trees.java @@ -0,0 +1,18 @@ +class Solution { + public boolean leafSimilar(TreeNode root1, TreeNode root2) { + List leaves1 = new ArrayList(); + List leaves2 = new ArrayList(); + dfs(root1, leaves1); + dfs(root2, leaves2); + return leaves1.equals(leaves2); + } + + public void dfs(TreeNode node, List leafValues) { + if (node != null) { + if (node.left == null && node.right == null) + leafValues.add(node.val); + dfs(node.left, leafValues); + dfs(node.right, leafValues); + } + } +} diff --git a/java/933_Number_of_Recent_Calls.java b/java/933_Number_of_Recent_Calls.java new file mode 100644 index 0000000..b8acb99 --- /dev/null +++ b/java/933_Number_of_Recent_Calls.java @@ -0,0 +1,13 @@ +class RecentCounter { + Queue q; + public RecentCounter() { + q = new LinkedList(); + } + + public int ping(int t) { + q.add(t); + while (q.peek() < t - 3000) + q.poll(); + return q.size(); + } +} diff --git a/python/872_Leaf-Similar_Trees.py b/python/872_Leaf-Similar_Trees.py new file mode 100644 index 0000000..6b3c7b2 --- /dev/null +++ b/python/872_Leaf-Similar_Trees.py @@ -0,0 +1,31 @@ +# Definition for a binary tree node. +# class TreeNode(object): +# def __init__(self, x): +# self.val = x +# self.left = None +# self.right = None + +class Solution(object): + def leafSimilar(self, root1, root2): + """ + :type root1: TreeNode + :type root2: TreeNode + :rtype: bool + """ + if not root1 and not root2: + return True + leaf1 = [] + leaf2 = [] + self.dfs(root1, leaf1) + self.dfs(root2, leaf2) + if leaf1 == leaf2: + return True + return False + + def dfs(self, node, leavels): + if not node: + return + if not node.left and not node.right: + leavels.append(node.val) + self.dfs(node.left, leavels) + self.dfs(node.right, leavels) diff --git a/python/933_Number_of_Recent_Calls.py b/python/933_Number_of_Recent_Calls.py new file mode 100644 index 0000000..4f00f4d --- /dev/null +++ b/python/933_Number_of_Recent_Calls.py @@ -0,0 +1,19 @@ +class RecentCounter(object): + + def __init__(self): + self.queue = [] + + def ping(self, t): + """ + :type t: int + :rtype: int + """ + self.queue.append(t) + while self.queue and self.queue[0] < t - 3000: + self.queue.pop(0) + return len(self.queue) + + +# Your RecentCounter object will be instantiated and called as such: +# obj = RecentCounter() +# param_1 = obj.ping(t) From 721169a4cca7d8980f3d3d3919e6e4201c7be9f5 Mon Sep 17 00:00:00 2001 From: Qiyuan Gong Date: Tue, 25 Dec 2018 11:11:16 +0800 Subject: [PATCH 025/119] 760_Find_Anagram_Mappings --- README.md | 1 + java/760_Find_Anagram_Mappings.java | 9 +++++++++ python/760_Find_Anagram_Mappings.py | 14 ++++++++++++++ 3 files changed, 24 insertions(+) create mode 100644 java/760_Find_Anagram_Mappings.java create mode 100644 python/760_Find_Anagram_Mappings.py diff --git a/README.md b/README.md index 975438a..d48ad90 100644 --- a/README.md +++ b/README.md @@ -179,6 +179,7 @@ Also, there are open source implementations for basic data structs and algorithm | 733 | [Flood Fill](https://leetcode.com/problems/flood-fill/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/733_Flood_Fill.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/733_Flood_Fill.java) | 1. DFS with stack or recursive, O(n) and O(n)
2. BFS with queue, O(n) and O(n) | | 743 | [Network Delay Time](https://leetcode.com/problems/network-delay-time/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/743_Network_Delay_Time.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/743_Network_Delay_Time.java) | Let V == N, then: 1. DFS, O(V^V+ElgE), O(V+E)
2. Dijkstra, O(V^2+E), O(V+E)| | 751 | [IP to CIDR](https://leetcode.com/problems/ip-to-cidr/) ♥ | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/751_IP_to_CIDR.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/751_IP_to_CIDR.java) | Bit manipulations, incrementail is 1 << (32 - mask) | +| 760 | [Find Anagram Mappings](https://leetcode.com/problems/find-anagram-mappings/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/760_Find_Anagram_Mappings.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/760_Find_Anagram_Mappings.java) | Hash table with A's (val, index), O(n) and O(n) | | 766 | [Toeplitz Matrix](https://leetcode.com/problems/toeplitz-matrix/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/766_Toeplitz_Matrix.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/766_Toeplitz_Matrix.java) | Check from top left to bottom right, i,j == i + 1, j + 1. | | 771 | [Jewels and Stones](https://leetcode.com/problems/jewels-and-stones/description/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/771_Jewels_and_Stones.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/771_Jewels_and_Stones.java) | Count given char in string. Hash or table. [Oneline](https://leetcode.com/problems/jewels-and-stones/discuss/113574/1-liners-PythonJavaRuby) | | 804 | [Unique Morse Code Words](https://leetcode.com/problems/unique-morse-code-words/description/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/804_Unique_Morse_Code_Words.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/804_Unique_Morse_Code_Words.java) | String, Hash and Set. Set is recommended. | diff --git a/java/760_Find_Anagram_Mappings.java b/java/760_Find_Anagram_Mappings.java new file mode 100644 index 0000000..414d69f --- /dev/null +++ b/java/760_Find_Anagram_Mappings.java @@ -0,0 +1,9 @@ +class Solution { + public int[] anagramMappings(int[] A, int[] B) { + int[] ans = new int[A.length]; + HashMap valIndex = new HashMap<>(); + for (int i = 0; i < B.length; i++) valIndex.put(B[i], i); + for (int i = 0; i < A.length; i++) ans[i] = valIndex.get(A[i]); + return ans; + } +} diff --git a/python/760_Find_Anagram_Mappings.py b/python/760_Find_Anagram_Mappings.py new file mode 100644 index 0000000..23d5f0f --- /dev/null +++ b/python/760_Find_Anagram_Mappings.py @@ -0,0 +1,14 @@ +class Solution(object): + def anagramMappings(self, A, B): + """ + :type A: List[int] + :type B: List[int] + :rtype: List[int] + """ + val_index = {} + ans = [] + for i, n in enumerate(B): + val_index[n] = i + for n in A: + ans.append(val_index[n]) + return ans From 212ea0c8dabb9a671847e04413a3641b190de612 Mon Sep 17 00:00:00 2001 From: Qiyuan Gong Date: Tue, 25 Dec 2018 12:04:40 +0800 Subject: [PATCH 026/119] 414_Third_Maximum_Number --- README.md | 1 + java/414_Third_Maximum_Number.java | 16 ++++++++++++++++ python/414_Third_Maximum_Number.py | 20 ++++++++++++++++++++ 3 files changed, 37 insertions(+) create mode 100644 java/414_Third_Maximum_Number.java create mode 100644 python/414_Third_Maximum_Number.py diff --git a/README.md b/README.md index d48ad90..e61248e 100644 --- a/README.md +++ b/README.md @@ -137,6 +137,7 @@ Also, there are open source implementations for basic data structs and algorithm | 408 | [Valid Word Abbreviation](https://leetcode.com/problems/valid-word-abbreviation/) ♥ | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/408_Valid_Word_Abbreviation.py) | Go over abbr and word, O(n) and O(1) | | 409 | [Longest Palindrome](https://leetcode.com/problems/longest-palindrome/description/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/409_Longest_Palindrome.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/409_Longest_Palindrome.java) | Length of Palindrome is always 2n or 2n + 1. So, get all possible 2*n, and choose a single one as 1 if it exists. | | 412 | [Fizz Buzz](https://leetcode.com/problems/fizz-buzz/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/412_Fizz_Buzz.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/412_Fizz_Buzz.java) | 1. From 1 to n, condition check
2. Condition check and string connect | +| 414 | [Third Maximum Number](https://leetcode.com/problems/third-maximum-number/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/414_Third_Maximum_Number.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/414_Third_Maximum_Number.java) | 1. Keep max 1-3 then compare, O(n) and O(1)
2. PriorityQueue, O(n) and O(1) | | 415 | [Add Strings](https://leetcode.com/problems/add-strings/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/415_Add_Strings.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/415_Add_Strings.java) | Two points, careful abour carry, O(n) and O(n) | | 416 | [Partition Equal Subset Sum](https://leetcode.com/problems/partition-equal-subset-sum/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/416_Partition_Equal_Subset_Sum.py) | DP, Check if sum of some elements can be half of total sum, O(total_sum / 2 * n) and O(total_sum / 2) | | 421 | [Maximum XOR of Two Numbers in an Array](https://leetcode.com/problems/maximum-xor-of-two-numbers-in-an-array/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/421_Maximum_XOR_of_Two_Numbers_in_an_Array.py) | Check 0~32 prefix, check if there is x y in prefixes, where x ^ y = answer ^ 1, O(32n) and O(n) | diff --git a/java/414_Third_Maximum_Number.java b/java/414_Third_Maximum_Number.java new file mode 100644 index 0000000..d883032 --- /dev/null +++ b/java/414_Third_Maximum_Number.java @@ -0,0 +1,16 @@ +public class Solution { + public int thirdMax(int[] nums) { + PriorityQueue pq = new PriorityQueue<>(3); + Set set = new HashSet<>(); + for (int i : nums) { + if (set.contains(i)) continue; + pq.offer(i); + set.add(i); + if (pq.size() > 3) set.remove(pq.poll()); + } + while (pq.size() < 3 && pq.size() > 1) { + pq.poll(); + } + return pq.peek(); + } +} diff --git a/python/414_Third_Maximum_Number.py b/python/414_Third_Maximum_Number.py new file mode 100644 index 0000000..d2dee22 --- /dev/null +++ b/python/414_Third_Maximum_Number.py @@ -0,0 +1,20 @@ +class Solution(object): + def thirdMax(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + import Queue + pq = Queue.PriorityQueue(4) + check = set() + for n in nums: + if n in check: + continue + pq.put(n) + check.add(n) + if len(check) > 3: + check.remove(pq.get()) + total = len(check) + while total < 3 and total > 1: + total -= 1 + return pq.get() From 05250eff789188ae16b169186bf0153442db88a0 Mon Sep 17 00:00:00 2001 From: Qiyuan Gong Date: Wed, 26 Dec 2018 10:38:11 +0800 Subject: [PATCH 027/119] 671_Second_Minimum_Node_In_a_Binary_Tree --- README.md | 1 + ..._Second_Minimum_Node_In_a_Binary_Tree.java | 40 +++++++++++++++++ ...71_Second_Minimum_Node_In_a_Binary_Tree.py | 45 +++++++++++++++++++ 3 files changed, 86 insertions(+) create mode 100644 java/671_Second_Minimum_Node_In_a_Binary_Tree.java create mode 100644 python/671_Second_Minimum_Node_In_a_Binary_Tree.py diff --git a/README.md b/README.md index e61248e..9ffe552 100644 --- a/README.md +++ b/README.md @@ -165,6 +165,7 @@ Also, there are open source implementations for basic data structs and algorithm | 617 | [Merge Two Binary Trees](https://leetcode.com/problems/merge-two-binary-trees/description/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/617_Merge_Two_Binary_Trees.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/617_Merge_Two_Binary_Trees.java) | Traverse both trees Recursion & Iterative (stack) | | 628 | [Maximum Product of Three Numbers](https://leetcode.com/problems/maximum-product-of-three-numbers/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/628_Maximum_Product_of_Three_Numbers.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/628_Maximum_Product_of_Three_Numbers.java) | Actually, we should only care about min1, min2 and max1-max3, to find these five elements, we can use 1. Brute force, O(n^3) and O(1)
2. Sort, O(nlogn) and O(1)
3. Single scan with 5 elements keep, O(n) and O(1) | | 654 | [Maximum Binary Tree](https://leetcode.com/problems/maximum-binary-tree/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/654_Maximum_Binary_Tree.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/654_Maximum_Binary_Tree.java) | 1. Divide and conquer, recursive, O(n^2)
2. Monotonic stack, O(n) | +| 671 | [Second Minimum Node In a Binary Tree](https://leetcode.com/problems/second-minimum-node-in-a-binary-tree/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/671_Second_Minimum_Node_In_a_Binary_Tree.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/671_Second_Minimum_Node_In_a_Binary_Tree.java) | Note that min value is root: 1. Get all values then find result, O(n) and O(n)
2. BFS or DFS traverse the tree, then find the reslut, O(n) and O(n)| | 674 | [Longest Continuous Increasing Subsequence](https://leetcode.com/problems/longest-continuous-increasing-subsequence/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/674_Longest_Continuous_Increasing_Subsequence.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/674_Longest_Continuous_Increasing_Subsequence.java) | Scan nums once, check nums[i] < nums[i+1], if not reset count, O(n) and O(1) | | 680 | [Valid Palindrome II](https://leetcode.com/problems/valid-palindrome-ii/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/680_Valid_Palindrome_II.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/680_Valid_Palindrome_II.java) | Recursively check s[left == end, when not equal delete left or right. | | 692 | [Top K Frequent Words](https://leetcode.com/problems/top-k-frequent-words/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/692_Top_K_Frequent_Words.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/692_Top_K_Frequent_Words.java) | 1. Sort based on frequency and alphabetical order, O(nlgn) and O(n)
2. Find top k with Heap, O(nlogk) and O(n) | diff --git a/java/671_Second_Minimum_Node_In_a_Binary_Tree.java b/java/671_Second_Minimum_Node_In_a_Binary_Tree.java new file mode 100644 index 0000000..7cc25ad --- /dev/null +++ b/java/671_Second_Minimum_Node_In_a_Binary_Tree.java @@ -0,0 +1,40 @@ +class Solution { + /*public void dfs(TreeNode root, Set uniques) { + if (root != null) { + uniques.add(root.val); + dfs(root.left, uniques); + dfs(root.right, uniques); + } + } + public int findSecondMinimumValue(TreeNode root) { + // Brute force + Set uniques = new HashSet(); + dfs(root, uniques); + + int min1 = root.val; + long ans = Long.MAX_VALUE; + for (int v : uniques) { + if (min1 < v && v < ans) ans = v; + } + return ans < Long.MAX_VALUE ? (int) ans : -1; + }*/ + + public int findSecondMinimumValue(TreeNode root) { + if (root == null) return -1; + Stack stack = new Stack(); + int min_val = root.val; + int ans = Integer.MAX_VALUE; + stack.push(root); + while (!stack.empty()) { + TreeNode node = stack.pop(); + if (node == null) continue; + if (node.val < ans && node.val > min_val) { + ans = node.val; + } else if (node.val == min_val) { + stack.push(node.left); + stack.push(node.right); + } + } + return ans < Integer.MAX_VALUE ? ans : -1; + } +} diff --git a/python/671_Second_Minimum_Node_In_a_Binary_Tree.py b/python/671_Second_Minimum_Node_In_a_Binary_Tree.py new file mode 100644 index 0000000..2c369b6 --- /dev/null +++ b/python/671_Second_Minimum_Node_In_a_Binary_Tree.py @@ -0,0 +1,45 @@ +# Definition for a binary tree node. +# class TreeNode(object): +# def __init__(self, x): +# self.val = x +# self.left = None +# self.right = None + +class Solution(object): + # def findSecondMinimumValue(self, root): + # """ + # :type root: TreeNode + # :rtype: int + # """ + # # Brute force + # values = set() + # self.dfs(root, values) + # ans, min_value = float('inf'), root.val + # for n in values: + # if min_value < n and n < ans: + # ans = n + # return ans if ans < float('inf') else -1 + + # def dfs(self, root, values): + # if not root: + # return + # values.add(root.val) + # self.dfs(root.left, values) + # self.dfs(root.right, values) + + def findSecondMinimumValue(self, root): + if not root: + return -1 + ans = float('inf') + min_val = root.val + stack = [root] + while stack: + curr = stack.pop() + if not curr: + continue + if min_val < curr.val < ans: + ans = curr.val + elif curr.val == min_val: + stack.append(curr.left) + stack.append(curr.right) + return ans if ans < float('inf') else -1 From 542f13fc6798401b0ccb94844e3a4453000ea252 Mon Sep 17 00:00:00 2001 From: Qiyuan Gong Date: Wed, 26 Dec 2018 11:01:29 +0800 Subject: [PATCH 028/119] 784_Letter_Case_Permutation --- README.md | 1 + java/784_Letter_Case_Permutation.java | 54 +++++++++++++++++++++++++++ python/784_Letter_Case_Permutation.py | 39 +++++++++++++++++++ 3 files changed, 94 insertions(+) create mode 100644 java/784_Letter_Case_Permutation.java create mode 100644 python/784_Letter_Case_Permutation.py diff --git a/README.md b/README.md index 9ffe552..0f5235d 100644 --- a/README.md +++ b/README.md @@ -184,6 +184,7 @@ Also, there are open source implementations for basic data structs and algorithm | 760 | [Find Anagram Mappings](https://leetcode.com/problems/find-anagram-mappings/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/760_Find_Anagram_Mappings.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/760_Find_Anagram_Mappings.java) | Hash table with A's (val, index), O(n) and O(n) | | 766 | [Toeplitz Matrix](https://leetcode.com/problems/toeplitz-matrix/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/766_Toeplitz_Matrix.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/766_Toeplitz_Matrix.java) | Check from top left to bottom right, i,j == i + 1, j + 1. | | 771 | [Jewels and Stones](https://leetcode.com/problems/jewels-and-stones/description/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/771_Jewels_and_Stones.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/771_Jewels_and_Stones.java) | Count given char in string. Hash or table. [Oneline](https://leetcode.com/problems/jewels-and-stones/discuss/113574/1-liners-PythonJavaRuby) | +| 784 | [Letter Case Permutation](https://leetcode.com/problems/letter-case-permutation/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/784_Letter_Case_Permutation.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/784_Letter_Case_Permutation.java) | Note that this is a 2^n problem. 1. Recursively generate result with previous result
2. Bin Mask, number of zeor equal to number of alpha
3. Python build in product. | | 804 | [Unique Morse Code Words](https://leetcode.com/problems/unique-morse-code-words/description/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/804_Unique_Morse_Code_Words.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/804_Unique_Morse_Code_Words.java) | String, Hash and Set. Set is recommended. | | 811 | [Subdomain Visit Count](https://leetcode.com/problems/subdomain-visit-count/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/811_Subdomain_Visit_Count.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/811_Subdomain_Visit_Count.java) | String split and HashMap, O(n) and O(n) | | 819 | [Most Common Word](https://leetcode.com/problems/most-common-word/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/819_Most_Common_Word.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/819_Most_Common_Word.java) | String processing, be careful about 'b,b,b'. regex is recommended. | diff --git a/java/784_Letter_Case_Permutation.java b/java/784_Letter_Case_Permutation.java new file mode 100644 index 0000000..3c9d83b --- /dev/null +++ b/java/784_Letter_Case_Permutation.java @@ -0,0 +1,54 @@ +class Solution { + public List letterCasePermutation(String S) { + List ans = new ArrayList(); + ans.add(new StringBuilder()); + + for (char c: S.toCharArray()) { + int n = ans.size(); + if (Character.isLetter(c)) { + for (int i = 0; i < n; ++i) { + ans.add(new StringBuilder(ans.get(i))); + ans.get(i).append(Character.toLowerCase(c)); + ans.get(n + i).append(Character.toUpperCase(c)); + } + } else { + for (int i = 0; i < n; ++i) + ans.get(i).append(c); + } + } + + List finalans = new ArrayList(); + for (StringBuilder sb: ans) + finalans.add(sb.toString()); + return finalans; + } + + /*public List letterCasePermutation(String S) { + int B = 0; + for (char c: S.toCharArray()) + if (Character.isLetter(c)) + B++; + + List ans = new ArrayList(); + + for (int bits = 0; bits < 1<> b++) & 1) == 1) + word.append(Character.toLowerCase(letter)); + else + word.append(Character.toUpperCase(letter)); + } else { + word.append(letter); + } + } + + ans.add(word.toString()); + } + + return ans; + + }*/ +} diff --git a/python/784_Letter_Case_Permutation.py b/python/784_Letter_Case_Permutation.py new file mode 100644 index 0000000..1466b2b --- /dev/null +++ b/python/784_Letter_Case_Permutation.py @@ -0,0 +1,39 @@ +class Solution(object): + # def letterCasePermutation(self, S): + # ans = [[]] + + # for char in S: + # n = len(ans) + # if char.isalpha(): + # # Double the ans + # for i in xrange(n): + # ans.append(ans[i][:]) + # ans[i].append(char.lower()) + # ans[n + i].append(char.upper()) + # else: + # # Normal append + # for i in xrange(n): + # ans[i].append(char) + + # return map("".join, ans) + + def letterCasePermutation(self, S): + B = sum(letter.isalpha() for letter in S) + ans = [] + + for bits in xrange(1 << B): + b = 0 + word = [] + for letter in S: + if letter.isalpha(): + if (bits >> b) & 1: + word.append(letter.lower()) + else: + word.append(letter.upper()) + + b += 1 + else: + word.append(letter) + + ans.append("".join(word)) + return ans From 886ae35399ed57f8df848f261f60c279ae5a5b01 Mon Sep 17 00:00:00 2001 From: Qiyuan Gong Date: Wed, 26 Dec 2018 12:47:56 +0800 Subject: [PATCH 029/119] 962_Maximum_Width_Ramp --- README.md | 1 + java/962_Maximum_Width_Ramp.java | 48 ++++++++++++++++++++++++++++++++ python/962_Maximum_Width_Ramp.py | 46 ++++++++++++++++++++++++++++++ 3 files changed, 95 insertions(+) create mode 100644 java/962_Maximum_Width_Ramp.java create mode 100644 python/962_Maximum_Width_Ramp.py diff --git a/README.md b/README.md index 0f5235d..27a0ce6 100644 --- a/README.md +++ b/README.md @@ -205,6 +205,7 @@ Also, there are open source implementations for basic data structs and algorithm | 953 | [Verifying an Alien Dictionary](https://leetcode.com/contest/weekly-contest-114/problems/verifying-an-alien-dictionary/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/953_Verifying_an_Alien_Dictionary.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/953_Verifying_an_Alien_Dictionary.java) | Use hashmap to store index of each value, then create a comparator based on this index, O(n) and O(n) | | 954 | [Array of Doubled Pairs](https://leetcode.com/contest/weekly-contest-114/problems/array-of-doubled-pairs/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/954_Array_of_Doubled_Pairs.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/954_Array_of_Doubled_Pairs.java) | Sort, then use hashmap to store the frequency of each value. Then, check n, 2 * n in hashmap, O(nlogn) and O(n) | | 961 | [N-Repeated Element in Size 2N Array](https://leetcode.com/problems/n-repeated-element-in-size-2n-array/submissions/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/961_N-Repeated_Element_in_Size_2N_Array.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/961_N-Repeated_Element_in_Size_2N_Array.java) | Hash and count number, O(n) and O(n) | +| 962 | [Maximum Width Ramp](https://leetcode.com/problems/maximum-width-ramp/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/962_Maximum_Width_Ramp.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/962_Maximum_Width_Ramp.java) | 1. Sort index by value, then transfer problem into finding max gap between index, O(nlogn) and O(1)
| | # | To Understand | |---| ----- | diff --git a/java/962_Maximum_Width_Ramp.java b/java/962_Maximum_Width_Ramp.java new file mode 100644 index 0000000..c839247 --- /dev/null +++ b/java/962_Maximum_Width_Ramp.java @@ -0,0 +1,48 @@ +import java.awt.Point; +class Solution { + public int maxWidthRamp(int[] A) { + int N = A.length; + Integer[] B = new Integer[N]; + for (int i = 0; i < N; ++i) + B[i] = i; + // Sort index based on value + Arrays.sort(B, (i, j) -> ((Integer) A[i]).compareTo(A[j])); + + int ans = 0; + int m = N; + for (int i: B) { + ans = Math.max(ans, i - m); + m = Math.min(m, i); + } + return ans; + } + + /*public int maxWidthRamp(int[] A) { + int N = A.length; + + int ans = 0; + List candidates = new ArrayList(); + candidates.add(new Point(A[N-1], N-1)); + + // candidates: i's decreasing, by increasing value of A[i] + for (int i = N-2; i >= 0; --i) { + // Find largest j in candidates with A[j] >= A[i] + int lo = 0, hi = candidates.size(); + while (lo < hi) { + int mi = lo + (hi - lo) / 2; + if (candidates.get(mi).x < A[i]) + lo = mi + 1; + else + hi = mi; + } + if (lo < candidates.size()) { + int j = candidates.get(lo).y; + ans = Math.max(ans, j - i); + } else { + candidates.add(new Point(A[i], i)); + } + } + return ans; + }*/ + +} \ No newline at end of file diff --git a/python/962_Maximum_Width_Ramp.py b/python/962_Maximum_Width_Ramp.py new file mode 100644 index 0000000..21ad68d --- /dev/null +++ b/python/962_Maximum_Width_Ramp.py @@ -0,0 +1,46 @@ +class Solution(object): + # def maxWidthRamp(self, A): + # """ + # :type A: List[int] + # :rtype: int + # """ + # # TLE + # if not A or len(A) == 0: + # return 0 + # for ans in range(len(A) - 1, 0, -1): + # for i in range(len(A)): + # if i + ans > len(A) - 1: + # break + # if (A[i + ans] >= A[i]): + # return ans + # return 0 + + def maxWidthRamp(self, A): + ans = 0 + m = float('inf') + # Sort index based on value + for i in sorted(range(len(A)), key=A.__getitem__): + ans = max(ans, i - m) + m = min(m, i) + return ans + + + # def maxWidthRamp(self, A): + # N = len(A) + # ans = 0 + # candidates = [(A[N - 1], N - 1)] + # # candidates: i's decreasing, by increasing value of A[i] + # for i in xrange(N - 2, -1, -1): + # # Find largest j in candidates with A[j] >= A[i] + # jx = bisect.bisect(candidates, (A[i],)) + # if jx < len(candidates): + # ans = max(ans, candidates[jx][1] - i) + # else: + # candidates.append((A[i], i)) + # return ans + + +if __name__ == '__main__': + s = Solution() + print s.maxWidthRamp([6, 0, 8, 2, 1, 5]) + print s.maxWidthRamp([9, 8, 1, 0, 1, 9, 4, 0, 4, 1]) From 5a693a6c0acd5d39415e7653947feb07b2ef85f4 Mon Sep 17 00:00:00 2001 From: Qiyuan Gong Date: Sun, 16 Jun 2019 23:26:21 +0800 Subject: [PATCH 030/119] Add 509_Fibonacci_Number --- README.md | 3 ++- java/509_Fibonacci_Number.java | 25 +++++++++++++++++++++++++ python/509_Fibonacci_Number.py | 30 ++++++++++++++++++++++++++++++ 3 files changed, 57 insertions(+), 1 deletion(-) create mode 100644 java/509_Fibonacci_Number.java create mode 100644 python/509_Fibonacci_Number.py diff --git a/README.md b/README.md index 27a0ce6..1c2941f 100644 --- a/README.md +++ b/README.md @@ -154,6 +154,7 @@ Also, there are open source implementations for basic data structs and algorithm | 475 | [Heaters](https://leetcode.com/problems/heaters/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/475_Heaters.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/475_Heaters.java) | 1. Binary search hourse in heater array, O(nlogn) and O(1)
2. Two points, O(nlogn) and O(1) | | 479 | [Largest Palindrome Product](https://leetcode.com/problems/largest-palindrome-product/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/479_Largest_Palindrome_Product.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/479_Largest_Palindrome_Product.java) | 1. Product max palindrome than check, O(n^2) and O(1)
2. [Math](# https://leetcode.com/problems/largest-palindrome-product/discuss/96305/Python-Solution-Using-Math-In-48ms) | | 482 | [License Key Formatting](https://leetcode.com/problems/license-key-formatting/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/482_License_Key_Formatting.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/482_License_Key_Formatting.java) | String processing, lower and len % K, O(n) and O(n) | +| 509 | [Fibonacci Number](https://leetcode.com/problems/fibonacci-number/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/509_Fibonacci_Number.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/509_Fibonacci_Number.java) | 1. Recursive, O(n)
2. DP with memo, O(n). Note that N<=30, which means that we can keep a memo from 0 to 30. | | 538 | [Convert BST to Greater Tree](https://leetcode.com/problems/convert-bst-to-greater-tree/description/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/538_Convert_BST_to_Greater_Tree.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/538_Convert_BST_to_Greater_Tree.java) | Right first DFS with a variable recording sum of node.val and right.val. 1. Recursive.
2. Stack 3. Reverse Morris In-order Traversal | | 543 | [Diameter of Binary Tree](https://leetcode.com/problems/diameter-of-binary-tree/description/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/543_Diameter_of_Binary_Tree.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/543_Diameter_of_Binary_Tree.java) | DFS with O(1) for max answer | | 547 | [Friend Circles](https://leetcode.com/problems/friend-circles/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/547_Friend_Circles.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/547_Friend_Circles.java) | 1. DFS, O(n^2) and O(1)
2. BFS, O(n^2) and O(1)
3. Union-find, O(n^2) and O(n)| @@ -205,7 +206,7 @@ Also, there are open source implementations for basic data structs and algorithm | 953 | [Verifying an Alien Dictionary](https://leetcode.com/contest/weekly-contest-114/problems/verifying-an-alien-dictionary/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/953_Verifying_an_Alien_Dictionary.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/953_Verifying_an_Alien_Dictionary.java) | Use hashmap to store index of each value, then create a comparator based on this index, O(n) and O(n) | | 954 | [Array of Doubled Pairs](https://leetcode.com/contest/weekly-contest-114/problems/array-of-doubled-pairs/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/954_Array_of_Doubled_Pairs.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/954_Array_of_Doubled_Pairs.java) | Sort, then use hashmap to store the frequency of each value. Then, check n, 2 * n in hashmap, O(nlogn) and O(n) | | 961 | [N-Repeated Element in Size 2N Array](https://leetcode.com/problems/n-repeated-element-in-size-2n-array/submissions/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/961_N-Repeated_Element_in_Size_2N_Array.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/961_N-Repeated_Element_in_Size_2N_Array.java) | Hash and count number, O(n) and O(n) | -| 962 | [Maximum Width Ramp](https://leetcode.com/problems/maximum-width-ramp/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/962_Maximum_Width_Ramp.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/962_Maximum_Width_Ramp.java) | 1. Sort index by value, then transfer problem into finding max gap between index, O(nlogn) and O(1)
| +| 962 | [Maximum Width Ramp](https://leetcode.com/problems/maximum-width-ramp/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/962_Maximum_Width_Ramp.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/962_Maximum_Width_Ramp.java) | 1. Sort index by value, then transfer problem into finding max gap between index, O(nlogn) and O(1)
2. Binary Search for candicates, O(nlogn) and O(n) | | # | To Understand | |---| ----- | diff --git a/java/509_Fibonacci_Number.java b/java/509_Fibonacci_Number.java new file mode 100644 index 0000000..9059dc4 --- /dev/null +++ b/java/509_Fibonacci_Number.java @@ -0,0 +1,25 @@ +class Solution { + /*public int fib(int N) { + // Recursively, O(n) + if (N == 0) return 0; + if (N == 1) return 1; + return fib(N - 1) + fib(N - 2); + }*/ + + private List memo; + + public Solution() { + memo = new ArrayList(); + memo.add(0); + memo.add(1); + } + + public int fib(int N) { + // Dp with memo, O(n) + if (N < memo.size()) return memo.get(N); + for (int i = memo.size(); i <= N; i++) { + memo.add(memo.get(i - 1) + memo.get(i - 2)); + } + return memo.get(N); + } +} diff --git a/python/509_Fibonacci_Number.py b/python/509_Fibonacci_Number.py new file mode 100644 index 0000000..b4ddad7 --- /dev/null +++ b/python/509_Fibonacci_Number.py @@ -0,0 +1,30 @@ +class Solution(object): + + def __init__(self): + self.memo = [] + self.memo.append(0) + self.memo.append(1) + + def fib(self, N): + """ + DP with memo + :type N: int + :rtype: int + """ + if N < len(self.memo): + return self.memo[N] + for i in range(len(self.memo), N + 1): + self.memo.append(self.memo[i - 1] + self.memo[i - 2]) + return self.memo[N] + + # def fib(self, N): + # """ + # Recursively, O(n) + # :type N: int + # :rtype: int + # """ + # if N == 0: + # return 0 + # if N == 1: + # return 1 + # return self.fib(N - 1) + self.fib(N - 2) From 8e21346b39ff1ad1c597f3eeb80b225346aa4c3e Mon Sep 17 00:00:00 2001 From: Qiyuan Gong Date: Sat, 22 Jun 2019 18:53:33 +0800 Subject: [PATCH 031/119] 1064_Fixed_Point --- README.md | 1 + java/1064_Fixed_Point.java | 21 +++++++++++++++++++++ python/1064_Fixed_Point.py | 24 ++++++++++++++++++++++++ 3 files changed, 46 insertions(+) create mode 100644 java/1064_Fixed_Point.java create mode 100644 python/1064_Fixed_Point.py diff --git a/README.md b/README.md index 1c2941f..930ef70 100644 --- a/README.md +++ b/README.md @@ -207,6 +207,7 @@ Also, there are open source implementations for basic data structs and algorithm | 954 | [Array of Doubled Pairs](https://leetcode.com/contest/weekly-contest-114/problems/array-of-doubled-pairs/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/954_Array_of_Doubled_Pairs.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/954_Array_of_Doubled_Pairs.java) | Sort, then use hashmap to store the frequency of each value. Then, check n, 2 * n in hashmap, O(nlogn) and O(n) | | 961 | [N-Repeated Element in Size 2N Array](https://leetcode.com/problems/n-repeated-element-in-size-2n-array/submissions/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/961_N-Repeated_Element_in_Size_2N_Array.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/961_N-Repeated_Element_in_Size_2N_Array.java) | Hash and count number, O(n) and O(n) | | 962 | [Maximum Width Ramp](https://leetcode.com/problems/maximum-width-ramp/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/962_Maximum_Width_Ramp.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/962_Maximum_Width_Ramp.java) | 1. Sort index by value, then transfer problem into finding max gap between index, O(nlogn) and O(1)
2. Binary Search for candicates, O(nlogn) and O(n) | +| 1064 | [Fixed Point](https://leetcode.com/problems/fixed-point/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/1064_Fixed_Point.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/1064_Fixed_Point.java) | 1. Go through index and value, until find solution encounter index < value, O(n) and O(1)
2. Binary search, O(logn) and O(1) | | # | To Understand | |---| ----- | diff --git a/java/1064_Fixed_Point.java b/java/1064_Fixed_Point.java new file mode 100644 index 0000000..16fc963 --- /dev/null +++ b/java/1064_Fixed_Point.java @@ -0,0 +1,21 @@ +class Solution { + /* public int fixedPoint(int[] A) { + for (int i = 0; i < A.length; i++) { + // Because if A[i] > i, then i can never be greater than A[i] any more + if (A[i] == i) return i; + else if (A[i] > i) return -1; + } + return -1; + } */ + public int fixedPoint(int[] A) { + int l = 0; + int h = A.length; + while (l <= h) { + int mid = (l + h) / 2; + if (A[mid] > mid) h = mid - 1; + else if (A[mid] < mid) l = mid + 1; + else return mid; + } + return -1; + } +} diff --git a/python/1064_Fixed_Point.py b/python/1064_Fixed_Point.py new file mode 100644 index 0000000..cb3e912 --- /dev/null +++ b/python/1064_Fixed_Point.py @@ -0,0 +1,24 @@ +class Solution(object): + # def fixedPoint(self, A): + # """ + # :type A: List[int] + # :rtype: int + # """ + # for index, value in enumerate(A): + # # Because if A[i] > i, then i can never be greater than A[i] any more + # if index == value: + # return index + # elif index < value: + # return -1 + + def fixedPoint(self, A): + l, h = 0, len(A) - 1 + while l <= h: + mid = (l + h) // 2 + if A[mid] < mid: + l = mid + 1 + elif A[mid] > mid: + h = mid - 1 + else: + return mid + return -1 From 3fceeba906d68b235d0baa7759581a6308a5a15d Mon Sep 17 00:00:00 2001 From: Qiyuan Gong Date: Sun, 23 Jun 2019 22:47:59 +0800 Subject: [PATCH 032/119] 977_Squares_of_a_Sorted_Array --- README.md | 9 ++++--- java/977_Squares_of_a_Sorted_Array.java | 35 +++++++++++++++++++++++++ python/977_Squares_of_a_Sorted_Array.py | 31 ++++++++++++++++++++++ 3 files changed, 71 insertions(+), 4 deletions(-) create mode 100644 java/977_Squares_of_a_Sorted_Array.java create mode 100644 python/977_Squares_of_a_Sorted_Array.py diff --git a/README.md b/README.md index 930ef70..292bb6b 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # Python & JAVA Solutions for Leetcode (inspired by [haoel's leetcode](https://github.com/haoel/leetcode)) -Remember solutions are only solutions to given problems. If you want full study checklist for code & whiteboard interview, please turn to [jwasham's coding-interview-university](https://github.com/jwasham/coding-interview-university). +Remember solutions are only solutions to given problems. If you want full study checklist for code & whiteboard interview, please turn to [jwasham's coding-interview-university](https://github.com/jwasham/coding-interview-university). Also, there are open source implementations for basic data structs and algorithms, such as [Algorithms in Python](https://github.com/TheAlgorithms/Python) and [Algorithms in Java](https://github.com/TheAlgorithms/Java). @@ -65,9 +65,9 @@ Also, there are open source implementations for basic data structs and algorithm | 153 | [Find Minimum in Rotated Sorted Array](https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/153_Find_Minimum_in_Rotated_Sorted_Array.py) | Binary search with conditions, A[l] > A[r] | | 154 | [Find Minimum in Rotated Sorted Array II](https://leetcode.com/problems/find-minimum-in-rotated-sorted-array-ii/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/154_Find_Minimum_in_Rotated_Sorted_Array_II.py) | Binary search with conditions, A[l] > A[r], A[l]=A[mid]=A[r] | | 155 | [Min Stack](https://leetcode.com/problems/min-stack/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/155_Min_Stack.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/155_Min_Stack.java) | Add another stack for min stack, maintance this stack when the main stack pop or push: 1. Only push min, such that len(minStack)<=len(Stack) 2. Push min again when current top is min, such that len(minStack)=len(Stack) | -| 156 | [Binary Tree Upside Down](https://leetcode.com/problems/binary-tree-upside-down/) ♥| [Python](https://github.com/qiyuangong/leetcode/blob/master/python/156_Binary_Tree_Upside_Down.py) | p.left = parent.right, parent.right = p.right, p.right = parent, parent = p.left, p = left | +| 156 | [Binary Tree Upside Down](https://leetcode.com/problems/binary-tree-upside-down/) ♥ | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/156_Binary_Tree_Upside_Down.py) | p.left = parent.right, parent.right = p.right, p.right = parent, parent = p.left, p = left | | 157 | [Read N Characters Given Read4](https://leetcode.com/problems/read-n-characters-given-read4/) ♥ | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/157_Read_N_Characters_Given_Read4.py) | Handle the edge case (the end) | -| 158 | [Read N Characters Given Read4 II - Call multiple times](https://leetcode.com/problems/read-n-characters-given-read4-ii-call-multiple-times/) ♥| [Python](https://github.com/qiyuangong/leetcode/blob/master/python/158_Read_N_Characters_Given_Read4_II_Call_multiple_times.py) | Store the pos and offset that is read by last read4 | +| 158 | [Read N Characters Given Read4 II - Call multiple times](https://leetcode.com/problems/read-n-characters-given-read4-ii-call-multiple-times/) ♥ | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/158_Read_N_Characters_Given_Read4_II_Call_multiple_times.py) | Store the pos and offset that is read by last read4 | | 159 | [Longest Substring with At Most Two Distinct Characters](https://leetcode.com/problems/longest-substring-with-at-most-two-distinct-characters/) ♥ | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/159_Longest_Substring_with_At_Most_Two_Distinct_Characters.py) | Maintain a sliding window that always satisfies such condition | | 161 | [One Edit Distance](https://leetcode.com/problems/one-edit-distance/) ♥| [Python](https://github.com/qiyuangong/leetcode/blob/master/python/161_One_Edit_Distance.py) | 1. Check the different position and conditions
2. [Edit distance](https://leetcode.com/problems/edit-distance/)| | 163 | [Missing Ranges](https://leetcode.com/problems/missing-ranges/) ♥ | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/163_Missing_Ranges.py) | Add -1 to lower for special case, then check if curr - prev >= 2| @@ -207,7 +207,8 @@ Also, there are open source implementations for basic data structs and algorithm | 954 | [Array of Doubled Pairs](https://leetcode.com/contest/weekly-contest-114/problems/array-of-doubled-pairs/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/954_Array_of_Doubled_Pairs.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/954_Array_of_Doubled_Pairs.java) | Sort, then use hashmap to store the frequency of each value. Then, check n, 2 * n in hashmap, O(nlogn) and O(n) | | 961 | [N-Repeated Element in Size 2N Array](https://leetcode.com/problems/n-repeated-element-in-size-2n-array/submissions/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/961_N-Repeated_Element_in_Size_2N_Array.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/961_N-Repeated_Element_in_Size_2N_Array.java) | Hash and count number, O(n) and O(n) | | 962 | [Maximum Width Ramp](https://leetcode.com/problems/maximum-width-ramp/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/962_Maximum_Width_Ramp.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/962_Maximum_Width_Ramp.java) | 1. Sort index by value, then transfer problem into finding max gap between index, O(nlogn) and O(1)
2. Binary Search for candicates, O(nlogn) and O(n) | -| 1064 | [Fixed Point](https://leetcode.com/problems/fixed-point/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/1064_Fixed_Point.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/1064_Fixed_Point.java) | 1. Go through index and value, until find solution encounter index < value, O(n) and O(1)
2. Binary search, O(logn) and O(1) | +| 977 | [Squares of a Sorted Array](https://leetcode.com/problems/squares-of-a-sorted-array/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/977_Squares_of_a_Sorted_Array.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/977_Squares_of_a_Sorted_Array.java) | 1. Sort, O(nlogn) and O(n)
2. Two point, O(n) and O(n) | +| 1064 | [Fixed Point](https://leetcode.com/problems/fixed-point/) ♥ | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/1064_Fixed_Point.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/1064_Fixed_Point.java) | 1. Go through index and value, until find solution encounter index < value, O(n) and O(1)
2. Binary search, O(logn) and O(1) | | # | To Understand | |---| ----- | diff --git a/java/977_Squares_of_a_Sorted_Array.java b/java/977_Squares_of_a_Sorted_Array.java new file mode 100644 index 0000000..26eb79e --- /dev/null +++ b/java/977_Squares_of_a_Sorted_Array.java @@ -0,0 +1,35 @@ +class Solution { + /* public int[] sortedSquares(int[] A) { + int[] res = new int[A.length]; + for (int i = 0; i < A.length; ++i) + res[i] = A[i] * A[i]; + + Arrays.sort(res); + return res; + } */ + public int[] sortedSquares(int[] A) { + int pos = 0; + int[] res = new int[A.length]; + int curr = 0; + while (pos < A.length && A[pos] < 0) pos++; + int npos = pos - 1; + while (pos < A.length && npos >= 0) { + if (A[pos] * A[pos] < A[npos] * A[npos]) { + res[curr++] = A[pos] * A[pos]; + pos++; + } else { + res[curr++] = A[npos] * A[npos]; + npos--; + } + } + while (npos >= 0) { + res[curr++] = A[npos] * A[npos]; + npos--; + } + while (pos < A.length) { + res[curr++] = A[pos] * A[pos]; + pos++; + } + return res; + } +} diff --git a/python/977_Squares_of_a_Sorted_Array.py b/python/977_Squares_of_a_Sorted_Array.py new file mode 100644 index 0000000..3c66191 --- /dev/null +++ b/python/977_Squares_of_a_Sorted_Array.py @@ -0,0 +1,31 @@ +class Solution(object): + # def sortedSquares(self, A): + # """ + # :type A: List[int] + # :rtype: List[int] + # """ + # # Directly sort + # return sorted(x * x for x in A) + + def sortedSquares(self, A): + pos = 0 + while pos < len(A) and A[pos] < 0: + pos += 1 + # pos point to first positve + # npos point to larget negative + npos = pos - 1 + res = [] + while pos < len(A) and npos >= 0: + if A[npos] ** 2 < A[pos] ** 2: + res.append(A[npos] ** 2) + npos -= 1 + else: + res.append(A[pos] ** 2) + pos +=1 + while npos >= 0: + res.append(A[npos] ** 2) + npos -= 1 + while pos < len(A): + res.append(A[pos] ** 2) + pos += 1 + return res From a9f9814d0056a04e14cc7a53cf0ae53e29614260 Mon Sep 17 00:00:00 2001 From: Qiyuan Gong Date: Mon, 24 Jun 2019 20:55:38 +0800 Subject: [PATCH 033/119] 937_Reorder_Log_Files --- README.md | 1 + java/937_Reorder_Log_Files.java | 19 +++++++++++++++++++ python/937_Reorder_Log_Files.py | 23 +++++++++++++++++++++++ 3 files changed, 43 insertions(+) create mode 100644 java/937_Reorder_Log_Files.java create mode 100644 python/937_Reorder_Log_Files.py diff --git a/README.md b/README.md index 292bb6b..211cfaa 100644 --- a/README.md +++ b/README.md @@ -201,6 +201,7 @@ Also, there are open source implementations for basic data structs and algorithm | 922 | [Sort Array By Parity II](https://leetcode.com/problems/sort-array-by-parity-ii/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/922_Sort_Array_By_Parity_II.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/922_Sort_Array_By_Parity_II.java) | 1. Place odd and even number in odd and even place, not sort is needed. O(n) and O(1)
2. Two points with quick sort swap idea, O(n) and O(1). | | 929 | [Unique Email Addresses](https://leetcode.com/problems/unique-email-addresses/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/929_Unique_Email_Addresses.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/929_Unique_Email_Addresses.java) | String handle and hash (or set) | | 933 | [Number of Recent Calls](https://leetcode.com/problems/number-of-recent-calls/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/933_Number_of_Recent_Calls.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/933_Number_of_Recent_Calls.java) | Queue, remove val in head when val < t - 3000, O(n) and O(n) | +| 937 | [Reorder Log Files](https://leetcode.com/problems/reorder-log-files/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/937_Reorder_Log_Files.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/937_Reorder_Log_Files.java) | 1. Comstom Sort, O(nlogn) and O(1)
2. Separete letter logs and digit logs, then sort letter logs and merge with digit logs, O(nlogn) and O(n) | | 945 | [Minimum Increment to Make Array Unique](https://leetcode.com/problems/minimum-increment-to-make-array-unique/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/945_Minimum_Increment_to_Make_Array_Unique.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/945_Minimum_Increment_to_Make_Array_Unique.java) | Sort, then list duplicate and missing value in sorted list. O(nlgn) and O(n) | | 946 | [Validate Stack Sequences](https://leetcode.com/problems/validate-stack-sequences/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/946_Validate_Stack_Sequences.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/946_Validate_Stack_Sequences.java) | Add a stack named inStack to help going through pushed and popped. O(n) and O(n) | | 953 | [Verifying an Alien Dictionary](https://leetcode.com/contest/weekly-contest-114/problems/verifying-an-alien-dictionary/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/953_Verifying_an_Alien_Dictionary.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/953_Verifying_an_Alien_Dictionary.java) | Use hashmap to store index of each value, then create a comparator based on this index, O(n) and O(n) | diff --git a/java/937_Reorder_Log_Files.java b/java/937_Reorder_Log_Files.java new file mode 100644 index 0000000..a43afa7 --- /dev/null +++ b/java/937_Reorder_Log_Files.java @@ -0,0 +1,19 @@ +import java.util.List; + +class Solution { + public String[] reorderLogFiles(String[] logs) { + Arrays.sort(logs, (log1, log2) -> { + String[] split1 = log1.split(" ", 2); + String[] split2 = log2.split(" ", 2); + boolean isDigit1 = Character.isDigit(split1[1].charAt(0)); + boolean isDigit2 = Character.isDigit(split2[1].charAt(0)); + if (!isDigit1 && !isDigit2) { + int cmp = split1[1].compareTo(split2[1]); + if (cmp != 0) return cmp; + return split1[0].compareTo(split2[0]); + } + return isDigit1 ? (isDigit2 ? 0 : 1) : -1; + }); + return logs; + } +} diff --git a/python/937_Reorder_Log_Files.py b/python/937_Reorder_Log_Files.py new file mode 100644 index 0000000..4d2c6ba --- /dev/null +++ b/python/937_Reorder_Log_Files.py @@ -0,0 +1,23 @@ +class Solution(object): + # def reorderLogFiles(self, logs): + # """ + # :type logs: List[str] + # :rtype: List[str] + # """ + # def f(log): + # id_, rest = log.split(" ", 1) + # return (0, rest, id_) if rest[0].isalpha() else (1,) + + # # Python sort is stable, so digit with keep their order + # return sorted(logs, key = f) + + def reorderLogFiles(self, logs): + letter_logs = [] + digit_logs = [] + for log in logs: + if log.split(' ')[1].isnumeric(): + digit_logs.append(log) + else: + letter_logs.append(log) + return sorted(letter_logs, key=lambda x: x.split(' ')[1:] + x.split(' ')[0]) + digit_logs + \ No newline at end of file From 08e37c4c8ccc870868cf7a41390236459f159bdc Mon Sep 17 00:00:00 2001 From: Qiyuan Gong Date: Wed, 26 Jun 2019 17:34:44 +0800 Subject: [PATCH 034/119] 973_K_Closest_Points_to_Origin --- README.md | 1 + java/973_K_Closest_Points_to_Origin.java | 39 ++++++++++++++++++++++++ python/973_K_Closest_Points_to_Origin.py | 13 ++++++++ 3 files changed, 53 insertions(+) create mode 100644 java/973_K_Closest_Points_to_Origin.java create mode 100644 python/973_K_Closest_Points_to_Origin.py diff --git a/README.md b/README.md index 211cfaa..d672caa 100644 --- a/README.md +++ b/README.md @@ -209,6 +209,7 @@ Also, there are open source implementations for basic data structs and algorithm | 961 | [N-Repeated Element in Size 2N Array](https://leetcode.com/problems/n-repeated-element-in-size-2n-array/submissions/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/961_N-Repeated_Element_in_Size_2N_Array.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/961_N-Repeated_Element_in_Size_2N_Array.java) | Hash and count number, O(n) and O(n) | | 962 | [Maximum Width Ramp](https://leetcode.com/problems/maximum-width-ramp/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/962_Maximum_Width_Ramp.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/962_Maximum_Width_Ramp.java) | 1. Sort index by value, then transfer problem into finding max gap between index, O(nlogn) and O(1)
2. Binary Search for candicates, O(nlogn) and O(n) | | 977 | [Squares of a Sorted Array](https://leetcode.com/problems/squares-of-a-sorted-array/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/977_Squares_of_a_Sorted_Array.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/977_Squares_of_a_Sorted_Array.java) | 1. Sort, O(nlogn) and O(n)
2. Two point, O(n) and O(n) | +| 973 | [K Closest Points to Origin](https://leetcode.com/problems/k-closest-points-to-origin/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/973_K_Closest_Points_to_Origin.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/973_K_Closest_Points_to_Origin.java) | 1. Sort and get 0-K, O(nlogn) and O(1)
2. Min Heap, O(nlogk) and O(k) | | 1064 | [Fixed Point](https://leetcode.com/problems/fixed-point/) ♥ | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/1064_Fixed_Point.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/1064_Fixed_Point.java) | 1. Go through index and value, until find solution encounter index < value, O(n) and O(1)
2. Binary search, O(logn) and O(1) | | # | To Understand | diff --git a/java/973_K_Closest_Points_to_Origin.java b/java/973_K_Closest_Points_to_Origin.java new file mode 100644 index 0000000..5d38e86 --- /dev/null +++ b/java/973_K_Closest_Points_to_Origin.java @@ -0,0 +1,39 @@ +class Solution { +/* public int[][] kClosest(int[][] points, int K) { + // Sort + int N = points.length; + int[] dists = new int[N]; + for (int i = 0; i < N; ++i) + dists[i] = dist(points[i]); + + Arrays.sort(dists); + int distK = dists[K-1]; + + int[][] ans = new int[K][2]; + int t = 0; + for (int i = 0; i < N; ++i) + if (dist(points[i]) <= distK) + ans[t++] = points[i]; + return ans; + } */ + + private int dist(int[] point) { + return point[0] * point[0] + point[1] * point[1]; + } + + public int[][] kClosest(int[][] points, int K) { + // Min Heap with PriorityQueue + PriorityQueue pq = new PriorityQueue((p1, p2) -> dist(p2) - dist(p1)); + for (int[] p : points) { + pq.offer(p); + if (pq.size() > K) { + pq.poll(); + } + } + int[][] res = new int[K][2]; + while (K > 0) { + res[--K] = pq.poll(); + } + return res; + } +} diff --git a/python/973_K_Closest_Points_to_Origin.py b/python/973_K_Closest_Points_to_Origin.py new file mode 100644 index 0000000..b8240b9 --- /dev/null +++ b/python/973_K_Closest_Points_to_Origin.py @@ -0,0 +1,13 @@ +class Solution(object): + # def kClosest(self, points, K): + # """ + # :type points: List[List[int]] + # :type K: int + # :rtype: List[List[int]] + # """ + # # Sort + # return sorted(points, key=lambda x: x[0] ** 2 + x[1] ** 2)[:K] + + def kClosest(self, points, K): + # K smallest heaq + return heapq.nsmallest(K, points, key=lambda x: x[0] ** 2 + x[1] ** 2) From 3bc837e7396876d219242813e3f0f4ae87625f65 Mon Sep 17 00:00:00 2001 From: Qiyuan Gong Date: Sun, 7 Jul 2019 22:45:46 +0800 Subject: [PATCH 035/119] 665_Non-decreasing_Array --- README.md | 1 + java/665_Non-decreasing_Array.java | 29 +++++++++++++++++++++++ python/665_Non-decreasing_Array.py | 38 ++++++++++++++++++++++++++++++ 3 files changed, 68 insertions(+) create mode 100644 java/665_Non-decreasing_Array.java create mode 100644 python/665_Non-decreasing_Array.py diff --git a/README.md b/README.md index d672caa..5c8a494 100644 --- a/README.md +++ b/README.md @@ -166,6 +166,7 @@ Also, there are open source implementations for basic data structs and algorithm | 617 | [Merge Two Binary Trees](https://leetcode.com/problems/merge-two-binary-trees/description/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/617_Merge_Two_Binary_Trees.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/617_Merge_Two_Binary_Trees.java) | Traverse both trees Recursion & Iterative (stack) | | 628 | [Maximum Product of Three Numbers](https://leetcode.com/problems/maximum-product-of-three-numbers/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/628_Maximum_Product_of_Three_Numbers.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/628_Maximum_Product_of_Three_Numbers.java) | Actually, we should only care about min1, min2 and max1-max3, to find these five elements, we can use 1. Brute force, O(n^3) and O(1)
2. Sort, O(nlogn) and O(1)
3. Single scan with 5 elements keep, O(n) and O(1) | | 654 | [Maximum Binary Tree](https://leetcode.com/problems/maximum-binary-tree/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/654_Maximum_Binary_Tree.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/654_Maximum_Binary_Tree.java) | 1. Divide and conquer, recursive, O(n^2)
2. Monotonic stack, O(n) | +| 665 | [Non-decreasing Array](https://leetcode.com/problems/non-decreasing-array/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/665_Non-decreasing_Array.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/665_Non-decreasing_Array.java) | 1. Find the broken index, then check this point, O(n) and O(1)
2. Replace broken point with correct value, then check if there are more than 1 broken point, O(n) and O(1) | | 671 | [Second Minimum Node In a Binary Tree](https://leetcode.com/problems/second-minimum-node-in-a-binary-tree/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/671_Second_Minimum_Node_In_a_Binary_Tree.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/671_Second_Minimum_Node_In_a_Binary_Tree.java) | Note that min value is root: 1. Get all values then find result, O(n) and O(n)
2. BFS or DFS traverse the tree, then find the reslut, O(n) and O(n)| | 674 | [Longest Continuous Increasing Subsequence](https://leetcode.com/problems/longest-continuous-increasing-subsequence/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/674_Longest_Continuous_Increasing_Subsequence.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/674_Longest_Continuous_Increasing_Subsequence.java) | Scan nums once, check nums[i] < nums[i+1], if not reset count, O(n) and O(1) | | 680 | [Valid Palindrome II](https://leetcode.com/problems/valid-palindrome-ii/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/680_Valid_Palindrome_II.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/680_Valid_Palindrome_II.java) | Recursively check s[left == end, when not equal delete left or right. | diff --git a/java/665_Non-decreasing_Array.java b/java/665_Non-decreasing_Array.java new file mode 100644 index 0000000..20eefb9 --- /dev/null +++ b/java/665_Non-decreasing_Array.java @@ -0,0 +1,29 @@ +class Solution { + /* public boolean checkPossibility(int[] nums) { + int pos = -1; + for (int i = 0; i < nums.length - 1; i++) { + if (nums[i] > nums[i + 1]) { + // More than two broken points + if (pos != -1) return false; + pos = i; + } + } + if (pos == -1 || pos == 0 || pos == nums.length - 2) return true; + // Remove pos or pos + 1 + return (nums[pos - 1] <= nums[pos + 1] || nums[pos] <= nums[pos + 2]); + } */ + + public boolean checkPossibility(int[] nums) { + int brokenPoint = 0; + for (int i = 0; i < nums.length - 1; i++) { + if (nums[i] > nums[i + 1]) { + brokenPoint++; + if (brokenPoint >= 2) return false; + // Remove i or remove i + 1 + if (i - 1 < 0 || nums[i - 1] <= nums[i + 1]) nums[i] = nums[i + 1]; + else nums[i + 1] = nums[i]; + } + } + return true; + } +} diff --git a/python/665_Non-decreasing_Array.py b/python/665_Non-decreasing_Array.py new file mode 100644 index 0000000..b2d01c2 --- /dev/null +++ b/python/665_Non-decreasing_Array.py @@ -0,0 +1,38 @@ +class Solution(object): + # def checkPossibility(self, nums): + # """ + # :type nums: List[int] + # :rtype: bool + # """ + # pos = None + # # Check if there are more than 2 broken point + # # record first index + # for i in range(len(nums) - 1): + # if nums[i] > nums[i + 1]: + # if pos is not None: + # return False + # pos = i + # if pos is None or pos == 0 or pos == len(nums) - 2: + # return True + # # Remove pos or remove pos + 1 + # return (nums[pos - 1] <= nums[pos + 1] or nums[pos] <= nums[pos + 2]) + + def checkPossibility(self, nums): + """ + :type nums: List[int] + :rtype: bool + """ + # https://leetcode.com/problems/non-decreasing-array/discuss/106826/JavaC%2B%2B-Simple-greedy-like-solution-with-explanation + broken_num = 0 + for i in range(len(nums) - 1): + if (nums[i] > nums[i + 1]): + broken_num += 1 + if broken_num >= 2: + return False + if (i - 1 < 0 or nums[i - 1] <= nums[i + 1]): + # Remove i + nums[i] = nums[i + 1] + else: + # Remove i + 1 + nums[i + 1] = nums[i] + return True From a165f91de73f3ed6a8382f3183ab716a9b19a60a Mon Sep 17 00:00:00 2001 From: Qiyuan Gong Date: Wed, 4 Sep 2019 22:13:05 +0800 Subject: [PATCH 036/119] Fix style --- README.md | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 5c8a494..7221ed4 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,9 @@ Remember solutions are only solutions to given problems. If you want full study checklist for code & whiteboard interview, please turn to [jwasham's coding-interview-university](https://github.com/jwasham/coding-interview-university). -Also, there are open source implementations for basic data structs and algorithms, such as [Algorithms in Python](https://github.com/TheAlgorithms/Python) and [Algorithms in Java](https://github.com/TheAlgorithms/Java). +Also, there are open source implementations for basic data structs and algorithms, such as [Algorithms in Python](https://github.com/TheAlgorithms/Python) and [Algorithms in Java](https://github.com/TheAlgorithms/Java). + +## Problems & Solutions [Python](https://github.com/qiyuangong/leetcode/tree/master/python) and [Java](https://github.com/qiyuangong/leetcode/tree/master/java) full list. ♥ means you need a subscription. @@ -94,7 +96,7 @@ Also, there are open source implementations for basic data structs and algorithm | 246 | [Strobogrammatic Number](https://leetcode.com/problems/strobogrammatic-number/) ♥ | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/246_Strobogrammatic_Number.py) | Hash table and reverse string, O(n) and O(n) | | 249 | [Group Shifted Strings](https://leetcode.com/problems/group-shifted-strings/) ♥ | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/249_Group_Shifted_Strings.py) | Hash and generate hash code for each string, O(n) and O(n) | | 252 | [Meeting Rooms](https://leetcode.com/problems/meeting-rooms/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/252_Meeting_Rooms.py) | 1. Sort and compare intervals[i].end with intervals[i+1], O(nlogn) and O(1)
2. Sort and check intervals when count >= 2, O(nlogn) and O(n) | -| 253 | [Meeting Rooms II](https://leetcode.com/problems/meeting-rooms-ii/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/253_Meeting_Rooms_II.py) ♥ [Java](https://github.com/qiyuangong/leetcode/blob/master/java/253_Meeting_Rooms_II.java) | 1. Priority queue and sort, O(nlogn) and O(n)
2. Go through timeline. If it's a start then meeting + 1, else meeting - 1. The ans is the max(meeting) in timeline. O(nlogn) and O(n) | +| 253 | [Meeting Rooms II](https://leetcode.com/problems/meeting-rooms-ii/) ♥ | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/253_Meeting_Rooms_II.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/253_Meeting_Rooms_II.java) | 1. Priority queue and sort, O(nlogn) and O(n)
2. Go through timeline. If it's a start then meeting + 1, else meeting - 1. The ans is the max(meeting) in timeline. O(nlogn) and O(n) | | 259 | [3Sum Smaller](https://leetcode.com/problems/3sum-smaller/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/259_3Sum_Smaller.py) | 1. Reduce to two sum smaller, then binary search, O(n^2lgn) and O(1)
2. Reduce to two sum smaller, then two points, O(n^2) and O(1)| | 266 | [Palindrome Permutation](https://leetcode.com/problems/palindrome-permutation/) ♥ | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/266_Palindrome_Permutation.py) | Compute frequency, check number of odd occurrences <= 1 then palindrome, O(n) and O(n)| | 267 | [Palindrome Permutation II](https://leetcode.com/problems/palindrome-permutation-ii/) ♥ | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/267_Palindrome_Permutation_II.py) | Check palindrome then generate half with [Permutations II](https://leetcode.com/problems/permutations-ii/), O(n^2) and O(n^2) | @@ -217,7 +219,7 @@ Also, there are open source implementations for basic data structs and algorithm |---| ----- | | 4 | [Median of Two Sorted Arrays](https://leetcode.com/problems/median-of-two-sorted-arrays/) | -# Other Leetcode Repos +## Other Leetcode Repos 1. [haoel's leetcode](https://github.com/haoel/leetcode) 2. [soulmachine's leetcode](https://github.com/soulmachine/leetcode) From 3d1573545a1ab2b02e21858e027a03d47145d009 Mon Sep 17 00:00:00 2001 From: Qiyuan Gong Date: Tue, 24 Sep 2019 22:37:41 +0800 Subject: [PATCH 037/119] 019_Remove_Nth_Node_From_End_of_List --- README.md | 1 + .../019_Remove_Nth_Node_From_End_of_List.java | 63 +++++++++++++++++++ .../019_Remove_Nth_Node_From_End_of_List.py | 13 +++- 3 files changed, 76 insertions(+), 1 deletion(-) create mode 100644 java/019_Remove_Nth_Node_From_End_of_List.java diff --git a/README.md b/README.md index 7221ed4..965389d 100644 --- a/README.md +++ b/README.md @@ -23,6 +23,7 @@ Also, there are open source implementations for basic data structs and algorithm | 15 | [3Sum](https://leetcode.com/problems/3sum/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/015_3Sum.py) | 1. Sort and O(n^2) search with three points
2. Multiple Two Sum (Problem 1) | | 16 | [3Sum Closest](https://leetcode.com/problems/3sum-closest/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/016_3Sum_Closest.py) | Sort and Multiple Two Sum check abs| | 18 | [4Sum](https://leetcode.com/problems/4sum/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/018_4Sum.py) | The same as 3Sum, but we can merge pairs with the same sum | +| 19 | [Remove Nth Node From End of List](https://leetcode.com/problems/remove-nth-node-from-end-of-list/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/019_Remove_Nth_Node_From_End_of_List.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/019_Remove_Nth_Node_From_End_of_List.java) | 1. Go through list and get length, then remove length-n, O(n) and O(n)
2. Two pointers, first pointer goes to n position, then move both pointers until reach tail, O(n) and O(n) | | 20 | [Valid Parentheses](https://leetcode.com/problems/valid-parentheses/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/020_Valid_Parentheses.py) | 1. Stack
2. Replace all parentheses with '', if empty then True | | 21 | [Merge Two Sorted Lists](https://leetcode.com/problems/merge-two-sorted-lists/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/021_Merge_Two_Sorted_Lists.py) | Add a dummy head, then merge two sorted list in O(m+n) | | 23 | [Merge k Sorted Lists](https://leetcode.com/problems/merge-k-sorted-lists/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/023_Merge_k_Sorted_Lists.py) | 1. Priority queue O(nk log k)
2. Binary merge O(nk log k)| | diff --git a/java/019_Remove_Nth_Node_From_End_of_List.java b/java/019_Remove_Nth_Node_From_End_of_List.java new file mode 100644 index 0000000..6ae9ce7 --- /dev/null +++ b/java/019_Remove_Nth_Node_From_End_of_List.java @@ -0,0 +1,63 @@ +/*Given a linked list, remove the n-th node from the end of list and return its head. + +Example: +Given linked list: 1->2->3->4->5, and n = 2. +After removing the second node from the end, the linked list becomes 1->2->3->5. + +Note: +Given n will always be valid. + +Follow up: +Could you do this in one pass?*/ + +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { val = x; } + * } + */ +class Solution { + /*public ListNode removeNthFromEnd(ListNode head, int n) { + ListNode curr = head; + int ls = 0; + while (curr != null) { + curr = curr.next; + ls++; + } + // n == len + if (ls == n) { + if (ls > 1) return head.next; + return null; + } + curr = head; + // Move to ls - n - 1 + for (int i = 0; i < ls - n - 1; i++) { + curr = curr.next; + } + // Remove ls - n - 1 + curr.next = curr.next.next; + return head; + }*/ + + public ListNode removeNthFromEnd(ListNode head, int n) { + ListNode slow, fast, curr; + slow = head; fast = head; + for (int i = 0; i < n; i++) + fast = fast.next; + // n == len + if (fast == null) { + head = head.next; + return head; + } + // Move both pointers, until reach tail + while (fast.next != null) { + fast = fast.next; + slow = slow.next; + } + curr = slow.next; + slow.next = curr.next; + return head; + } +} diff --git a/python/019_Remove_Nth_Node_From_End_of_List.py b/python/019_Remove_Nth_Node_From_End_of_List.py index 2f7b176..cfd327c 100644 --- a/python/019_Remove_Nth_Node_From_End_of_List.py +++ b/python/019_Remove_Nth_Node_From_End_of_List.py @@ -1,3 +1,15 @@ +# Given a linked list, remove the n-th node from the end of list and return its head. +# +# Example: +# Given linked list: 1->2->3->4->5, and n = 2. +# After removing the second node from the end, the linked list becomes 1->2->3->5. +# +# Note: +# Given n will always be valid. +# +# Follow up: +# Could you do this in one pass? + # Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): @@ -30,7 +42,6 @@ class Solution(object): # index[index_pos].next = index[index_pos + 1].next # return head - def removeNthFromEnd(self, head, n): # https://leetcode.com/discuss/86721/o-n-solution-in-java if head is None: From 0081e4b86810df62ee2b728e63d8804facd15c24 Mon Sep 17 00:00:00 2001 From: YOGESH BHAKHAR <31646304+yogesh-mca17du@users.noreply.github.com> Date: Mon, 28 Oct 2019 20:28:30 +0530 Subject: [PATCH 038/119] 204_Count_Primes cpp solution (#5) 204_Count_Primes cpp solution contributed by @yogesh-mca17du --- CountingPrimes.cpp | 148 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 148 insertions(+) create mode 100644 CountingPrimes.cpp diff --git a/CountingPrimes.cpp b/CountingPrimes.cpp new file mode 100644 index 0000000..35d66f2 --- /dev/null +++ b/CountingPrimes.cpp @@ -0,0 +1,148 @@ +// Source : https://leetcode.com/problems/count-primes/ + + +/********************************************************************************** + * + * Description: + * Count the number of prime numbers less than a non-negative number, n. + * + * Credits:Special thanks to @mithmatt for adding this problem and creating all test cases. + * + * Let's start with a isPrime function. To determine if a number is prime, we need to check if + * it is not divisible by any number less than n. The runtime complexity of isPrime function + * would be O(n) and hence counting the total prime numbers up to n would be O(n2). Could we do better? + * + * As we know the number must not be divisible by any number > n / 2, we can immediately cut the total + * iterations half by dividing only up to n / 2. Could we still do better? + * + * Let's write down all of 12's factors: + * + * 2 × 6 = 12 + * 3 × 4 = 12 + * 4 × 3 = 12 + * 6 × 2 = 12 + * + * As you can see, calculations of 4 × 3 and 6 × 2 are not necessary. Therefore, we only need to consider + * factors up to √n because, if n is divisible by some number p, then n = p × q and since p ≤ q, we could derive that p ≤ √n. + * + * Our total runtime has now improved to O(n1.5), which is slightly better. Is there a faster approach? + * + * public int countPrimes(int n) { + * int count = 0; + * for (int i = 1; i < n; i++) { + * if (isPrime(i)) count++; + * } + * return count; + * } + * + * private boolean isPrime(int num) { + * if (num <= 1) return false; + * // Loop's ending condition is i * i <= num instead of i <= sqrt(num) + * // to avoid repeatedly calling an expensive function sqrt(). + * for (int i = 2; i * i <= num; i++) { + * if (num % i == 0) return false; + * } + * return true; + * } + * + * The Sieve of Eratosthenes is one of the most efficient ways to find all prime numbers up to n. + * But don't let that name scare you, I promise that the concept is surprisingly simple. + * + * [Sieve of Eratosthenes](http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes) + * + * [https://leetcode.com/static/images/solutions/Sieve_of_Eratosthenes_animation.gif] + * [http://commons.wikimedia.org/wiki/File:Sieve_of_Eratosthenes_animation.gif] + * + * Sieve of Eratosthenes: algorithm steps for primes below 121. "Sieve of Eratosthenes Animation"() + * by SKopp is licensed under CC BY 2.0. + * + * * [Skoop](http://de.wikipedia.org/wiki/Benutzer:SKopp) + * * [CC BY 2.0](http://creativecommons.org/licenses/by/2.0/) + * + * We start off with a table of n numbers. Let's look at the first number, 2. We know all multiples of 2 + * must not be primes, so we mark them off as non-primes. Then we look at the next number, 3. Similarly, + * all multiples of 3 such as 3 × 2 = 6, 3 × 3 = 9, ... must not be primes, so we mark them off as well. + * Now we look at the next number, 4, which was already marked off. What does this tell you? Should you + * mark off all multiples of 4 as well? + * + * 4 is not a prime because it is divisible by 2, which means all multiples of 4 must also be divisible + * by 2 and were already marked off. So we can skip 4 immediately and go to the next number, 5. Now, + * all multiples of 5 such as 5 × 2 = 10, 5 × 3 = 15, 5 × 4 = 20, 5 × 5 = 25, ... can be marked off. + * There is a slight optimization here, we do not need to start from 5 × 2 = 10. Where should we start marking off? + * + * In fact, we can mark off multiples of 5 starting at 5 × 5 = 25, because 5 × 2 = 10 was already marked off + * by multiple of 2, similarly 5 × 3 = 15 was already marked off by multiple of 3. Therefore, if the current + * number is p, we can always mark off multiples of p starting at p2, then in increments of p: p2 + p, p2 + 2p, ... + * Now what should be the terminating loop condition? + * + * It is easy to say that the terminating loop condition is p n, which is certainly correct but not efficient. + * Do you still remember Hint #3? + * + * Yes, the terminating loop condition can be p n, as all non-primes ≥ √n must have already been marked off. + * When the loop terminates, all the numbers in the table that are non-marked are prime. + * + * The Sieve of Eratosthenes uses an extra O(n) memory and its runtime complexity is O(n log log n). + * For the more mathematically inclined readers, you can read more about its algorithm complexity on + * [Wikipedia](http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes#Algorithm_complexity). + * + * public int countPrimes(int n) { + * boolean[] isPrime = new boolean[n]; + * for (int i = 2; i < n; i++) { + * isPrime[i] = true; + * } + * // Loop's ending condition is i * i < n instead of i < sqrt(n) + * // to avoid repeatedly calling an expensive function sqrt(). + * for (int i = 2; i * i < n; i++) { + * if (!isPrime[i]) continue; + * for (int j = i * i; j < n; j += i) { + * isPrime[j] = false; + * } + * } + * int count = 0; + * for (int i = 2; i < n; i++) { + * if (isPrime[i]) count++; + * } + * return count; + * } + * + * + **********************************************************************************/ + +#include +#include +#include +using namespace std; + +int countPrimes(int n) { + vector isPrimer(n, true); + + for(int i=2; i*i1){ + n = atoi(argv[1]); + } + + cout << endl << n << " : " << countPrimes(n) << endl; + + return 0; +} From 172fd36c3c464613d9191ab8496454fd6742d262 Mon Sep 17 00:00:00 2001 From: Qiyuan Gong Date: Mon, 28 Oct 2019 23:21:11 +0800 Subject: [PATCH 039/119] Add 204_Count_Primes Python and Java solution based on CPP Solution --- README.md | 1 + .../204_Count_Primes.cpp | 30 +++++++++++-------- java/204_Count_Primes.java | 20 +++++++++++++ ...04_Count Primes.py => 204_Count_Primes.py} | 2 +- 4 files changed, 40 insertions(+), 13 deletions(-) rename CountingPrimes.cpp => cpp/204_Count_Primes.cpp (93%) create mode 100644 java/204_Count_Primes.java rename python/{204_Count Primes.py => 204_Count_Primes.py} (96%) diff --git a/README.md b/README.md index 965389d..8e71a07 100644 --- a/README.md +++ b/README.md @@ -81,6 +81,7 @@ Also, there are open source implementations for basic data structs and algorithm | 186 | [Reverse Words in a String II](https://leetcode.com/problems/reverse-words-in-a-string-ii/) ♥| [Python](https://github.com/qiyuangong/leetcode/blob/master/python/186_Reverse_Words_in_a_String_II.py) | Reverse all and reverse each words | | 198 | [House Robber](https://leetcode.com/problems/house-robber/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/198_House_Robber.py) | f(k) = max(f(k – 2) + num[k], f(k – 1)), O(n) and O(1) | | 200 | [Number of Islands](https://leetcode.com/problems/number-of-islands/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/200_Number_of_Islands.py) | 1. Quick union find, O(nlogn) and O(n^2)
2. BFS with marks, O(n^2) and O(1) | +| 204 | [Count Primes](https://leetcode.com/problems/count-primes/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/204_Count_Primes.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/204_Count_Primes.java) [CPP](https://github.com/qiyuangong/leetcode/blob/master/cpp/204_Count_Primes.cpp) | [Sieve of Eratosthenes](https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes#Algorithm_complexity), O(nloglogn) and O(n) | | 206 | [Reverse Linked List](https://leetcode.com/problems/reverse-linked-list/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/206_Reverse_Linked_List.py) | 1. Stack, O(n) and O(n)
2. Traverse on prev and curr, then curr.next = prev, O(n) and O(1)
3. Recursion, O(n) and O(1) | | 213 | [House Robber II](https://leetcode.com/problems/house-robber-ii/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/213_House_Robber_II.py) | f(k) = max(f(k – 2) + num[k], max(dp[0~ls-2],dp[1~ls-1], O(n) and O(1)| | 215 | [Kth Largest Element in an Array](https://leetcode.com/problems/kth-largest-element-in-an-array/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/215_Kth_Largest_Element_in_an_Array.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/215_Kth_Largest_Element_in_an_Array.java) | 1. Sort, O(n) and O(n)
2. Heap, O(nlgk) and O(n)
3. Quick selection, O(klgn) and O(n)| diff --git a/CountingPrimes.cpp b/cpp/204_Count_Primes.cpp similarity index 93% rename from CountingPrimes.cpp rename to cpp/204_Count_Primes.cpp index 35d66f2..6757a45 100644 --- a/CountingPrimes.cpp +++ b/cpp/204_Count_Primes.cpp @@ -1,6 +1,5 @@ // Source : https://leetcode.com/problems/count-primes/ - /********************************************************************************** * * Description: @@ -113,20 +112,26 @@ #include using namespace std; -int countPrimes(int n) { +int countPrimes(int n) +{ vector isPrimer(n, true); - for(int i=2; i*i1){ + if (argc > 1) + { n = atoi(argv[1]); } - - cout << endl << n << " : " << countPrimes(n) << endl; + + cout << endl + << n << " : " << countPrimes(n) << endl; return 0; } diff --git a/java/204_Count_Primes.java b/java/204_Count_Primes.java new file mode 100644 index 0000000..cba07a7 --- /dev/null +++ b/java/204_Count_Primes.java @@ -0,0 +1,20 @@ +class Solution { + // ttps://en.wikipedia.org/wiki/Sieve_of_Eratosthenes#Algorithm_complexity + public int countPrimes(int n) { + boolean[] isPrime = new boolean[n]; + int count = 0; + Arrays.fill(isPrime, true); + for (int i = 2; i < n; i++) { + if (i * i >= n) + break; + if (!isPrime[i]) + continue; + for (int j = i * i; j < n; j += i) + isPrime[j] = false; + } + for (int i = 2; i < n; i++) + if (isPrime[i]) + count++; + return count; + } +} diff --git a/python/204_Count Primes.py b/python/204_Count_Primes.py similarity index 96% rename from python/204_Count Primes.py rename to python/204_Count_Primes.py index 4c61aa6..3f2b1c1 100644 --- a/python/204_Count Primes.py +++ b/python/204_Count_Primes.py @@ -17,4 +17,4 @@ def countPrimes(self, n): for i in xrange(2, n): if isPrime[i]: count += 1 - return count \ No newline at end of file + return count From 8ee7faa18dc0cc146fde6e61a3ad6bc6d4ce3020 Mon Sep 17 00:00:00 2001 From: Qiyuan Gong Date: Fri, 21 Feb 2020 17:42:16 +0800 Subject: [PATCH 040/119] 485_Max_Consecutive_Ones --- README.md | 3 ++- java/485_Max_Consecutive_Ones.java | 17 +++++++++++++++++ python/485_Max_Consecutive_Ones.py | 18 ++++++++++++++++++ 3 files changed, 37 insertions(+), 1 deletion(-) create mode 100644 java/485_Max_Consecutive_Ones.java create mode 100644 python/485_Max_Consecutive_Ones.py diff --git a/README.md b/README.md index 8e71a07..e433933 100644 --- a/README.md +++ b/README.md @@ -156,8 +156,9 @@ Also, there are open source implementations for basic data structs and algorithm | 461 | [Hamming Distance](https://leetcode.com/problems/hamming-distance/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/461_Hamming_Distance.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/461_Hamming_Distance.java) | Hamming Distance is related to XOR for numbers. So, XOR then count 1. O(n) | | 463 | [Island Perimeter](https://leetcode.com/problems/island-perimeter/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/463_Island_Perimeter.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/463_Island_Perimeter.java) | math, find the area, actual number, then find the digit | | 475 | [Heaters](https://leetcode.com/problems/heaters/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/475_Heaters.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/475_Heaters.java) | 1. Binary search hourse in heater array, O(nlogn) and O(1)
2. Two points, O(nlogn) and O(1) | -| 479 | [Largest Palindrome Product](https://leetcode.com/problems/largest-palindrome-product/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/479_Largest_Palindrome_Product.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/479_Largest_Palindrome_Product.java) | 1. Product max palindrome than check, O(n^2) and O(1)
2. [Math](# https://leetcode.com/problems/largest-palindrome-product/discuss/96305/Python-Solution-Using-Math-In-48ms) | +| 479 | [Largest Palindrome Product](https://leetcode.com/problems/largest-palindrome-product/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/479_Largest_Palindrome_Product.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/479_Largest_Palindrome_Product.java) | 1. Product max palindrome than check, O(n^2) and O(1)
2. [Math](https://leetcode.com/problems/largest-palindrome-product/discuss/96305/Python-Solution-Using-Math-In-48ms) | | 482 | [License Key Formatting](https://leetcode.com/problems/license-key-formatting/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/482_License_Key_Formatting.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/482_License_Key_Formatting.java) | String processing, lower and len % K, O(n) and O(n) | +| 485 | [Max Consecutive Ones](https://leetcode.com/problems/max-consecutive-ones/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/485_Max_Consecutive_Ones.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/485_Max_Consecutive_Ones.java) | Add one when encounter 1, set to 0 when encounter 0, O(n) and O(1) | | 509 | [Fibonacci Number](https://leetcode.com/problems/fibonacci-number/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/509_Fibonacci_Number.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/509_Fibonacci_Number.java) | 1. Recursive, O(n)
2. DP with memo, O(n). Note that N<=30, which means that we can keep a memo from 0 to 30. | | 538 | [Convert BST to Greater Tree](https://leetcode.com/problems/convert-bst-to-greater-tree/description/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/538_Convert_BST_to_Greater_Tree.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/538_Convert_BST_to_Greater_Tree.java) | Right first DFS with a variable recording sum of node.val and right.val. 1. Recursive.
2. Stack 3. Reverse Morris In-order Traversal | | 543 | [Diameter of Binary Tree](https://leetcode.com/problems/diameter-of-binary-tree/description/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/543_Diameter_of_Binary_Tree.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/543_Diameter_of_Binary_Tree.java) | DFS with O(1) for max answer | diff --git a/java/485_Max_Consecutive_Ones.java b/java/485_Max_Consecutive_Ones.java new file mode 100644 index 0000000..2aca065 --- /dev/null +++ b/java/485_Max_Consecutive_Ones.java @@ -0,0 +1,17 @@ +class Solution { + public int findMaxConsecutiveOnes(int[] nums) { + int ans = 0; + int curr = 0; + for (int i = 0; i < nums.length; i++) { + if (nums[i] == 1) { + // Add 1 when encounter 1 + curr++; + if (curr > ans) ans = curr; + } else { + // Set to 0 when encounter 0 + curr = 0; + } + } + return ans; + } +} diff --git a/python/485_Max_Consecutive_Ones.py b/python/485_Max_Consecutive_Ones.py new file mode 100644 index 0000000..4d6ffc1 --- /dev/null +++ b/python/485_Max_Consecutive_Ones.py @@ -0,0 +1,18 @@ +class Solution(object): + def findMaxConsecutiveOnes(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + ans = 0 + curr = 0 + for n in nums: + if n == 1: + # Add 1 to curr when encounter 1 + curr += 1 + if curr > ans: + ans = curr + else: + # Add 1 to curr when encounter 1 + curr = 0 + return ans From d55c6b23772cc01e3e2f0769b7e8838814c7a11e Mon Sep 17 00:00:00 2001 From: Qiyuan Gong Date: Sat, 22 Feb 2020 17:17:31 +0800 Subject: [PATCH 041/119] 1260_Shift_2D_Grid --- README.md | 1 + java/1260_Shift_2D_Grid.java | 32 ++++++++++++++++++++++++++++++++ python/1260_Shift_2D_Grid.py | 28 ++++++++++++++++++++++++++++ 3 files changed, 61 insertions(+) create mode 100644 java/1260_Shift_2D_Grid.java create mode 100644 python/1260_Shift_2D_Grid.py diff --git a/README.md b/README.md index e433933..2b84253 100644 --- a/README.md +++ b/README.md @@ -217,6 +217,7 @@ Also, there are open source implementations for basic data structs and algorithm | 977 | [Squares of a Sorted Array](https://leetcode.com/problems/squares-of-a-sorted-array/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/977_Squares_of_a_Sorted_Array.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/977_Squares_of_a_Sorted_Array.java) | 1. Sort, O(nlogn) and O(n)
2. Two point, O(n) and O(n) | | 973 | [K Closest Points to Origin](https://leetcode.com/problems/k-closest-points-to-origin/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/973_K_Closest_Points_to_Origin.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/973_K_Closest_Points_to_Origin.java) | 1. Sort and get 0-K, O(nlogn) and O(1)
2. Min Heap, O(nlogk) and O(k) | | 1064 | [Fixed Point](https://leetcode.com/problems/fixed-point/) ♥ | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/1064_Fixed_Point.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/1064_Fixed_Point.java) | 1. Go through index and value, until find solution encounter index < value, O(n) and O(1)
2. Binary search, O(logn) and O(1) | +| 1260 | [Shift 2D Grid](https://leetcode.com/problems/shift-2d-grid/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/1260_Shift_2D_Grid.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/1260_Shift_2D_Grid.java) | Final position of each element can be computed according to k, m and n, e.g., k == mn, then don't move, O(mn) and O(mn) | | # | To Understand | |---| ----- | diff --git a/java/1260_Shift_2D_Grid.java b/java/1260_Shift_2D_Grid.java new file mode 100644 index 0000000..2c4369b --- /dev/null +++ b/java/1260_Shift_2D_Grid.java @@ -0,0 +1,32 @@ +class Solution { + public List> shiftGrid(int[][] grid, int k) { + int[][] newGrid = new int[grid.length][grid[0].length]; + int m = grid.length; + int n = grid[0].length; + // Compute final move + int true_k = k % (m * n); + // Row move + int move_i = true_k / n; + // Column move + int move_j = true_k % n; + + for (int i = 0; i < grid.length; i++) { + for (int j = 0; j < grid[i].length; j++) { + int new_i = i + move_i; + int new_j = (j + move_j) % n; + // Move 1 row if (move_j + j >= n + if (move_j + j >= n) new_i ++; + new_i %= m; + newGrid[new_i][new_j] = grid[i][j]; + } + } + // Copy the grid into a list for returning. + List> result = new ArrayList<>(); + for (int[] row : newGrid) { + List listRow = new ArrayList<>(); + result.add(listRow); + for (int v : row) listRow.add(v); + } + return result; + } +} diff --git a/python/1260_Shift_2D_Grid.py b/python/1260_Shift_2D_Grid.py new file mode 100644 index 0000000..ec7cc57 --- /dev/null +++ b/python/1260_Shift_2D_Grid.py @@ -0,0 +1,28 @@ +class Solution(object): + def shiftGrid(self, grid, k): + """ + :type grid: List[List[int]] + :type k: int + :rtype: List[List[int]] + """ + # m * n temp array + new_grid = [[0] * len(grid[0]) for _ in range(len(grid))] + m = len(grid) + n = len(grid[0]) + # Compute final location + true_k = k % (m * n) + # row move + move_i = true_k / n + # col move + move_j = true_k % n + + for i in range(m): + for j in range(n): + new_i = i + move_i + # move one row if move_j + j >= n + if move_j + j >= n: + new_i += 1 + new_i %= m + new_j = (j + move_j) % n + new_grid[new_i][new_j] = grid[i][j] + return new_grid From 85132d6b6db56ea43f4f3260a0036759f47e75a6 Mon Sep 17 00:00:00 2001 From: Qiyuan Gong Date: Sun, 23 Feb 2020 21:49:27 +0800 Subject: [PATCH 042/119] 1337_The_K_Weakest_Rows_in_a_Matrix --- README.md | 1 + java/1337_The_K_Weakest_Rows_in_a_Matrix.java | 30 +++++++++++++++++ python/1337_The_K_Weakest_Rows_in_a_Matrix.py | 33 +++++++++++++++++++ 3 files changed, 64 insertions(+) create mode 100644 java/1337_The_K_Weakest_Rows_in_a_Matrix.java create mode 100644 python/1337_The_K_Weakest_Rows_in_a_Matrix.py diff --git a/README.md b/README.md index 2b84253..568351e 100644 --- a/README.md +++ b/README.md @@ -218,6 +218,7 @@ Also, there are open source implementations for basic data structs and algorithm | 973 | [K Closest Points to Origin](https://leetcode.com/problems/k-closest-points-to-origin/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/973_K_Closest_Points_to_Origin.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/973_K_Closest_Points_to_Origin.java) | 1. Sort and get 0-K, O(nlogn) and O(1)
2. Min Heap, O(nlogk) and O(k) | | 1064 | [Fixed Point](https://leetcode.com/problems/fixed-point/) ♥ | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/1064_Fixed_Point.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/1064_Fixed_Point.java) | 1. Go through index and value, until find solution encounter index < value, O(n) and O(1)
2. Binary search, O(logn) and O(1) | | 1260 | [Shift 2D Grid](https://leetcode.com/problems/shift-2d-grid/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/1260_Shift_2D_Grid.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/1260_Shift_2D_Grid.java) | Final position of each element can be computed according to k, m and n, e.g., k == mn, then don't move, O(mn) and O(mn) | +| 1337 | [The K Weakest Rows in a Matrix](https://leetcode.com/problems/the-k-weakest-rows-in-a-matrix/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/1337_The_K_Weakest_Rows_in_a_Matrix.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/1337_The_K_Weakest_Rows_in_a_Matrix.java) | Check by row, from left to right, until encount first zero, O(mn) and O(1) | | # | To Understand | |---| ----- | diff --git a/java/1337_The_K_Weakest_Rows_in_a_Matrix.java b/java/1337_The_K_Weakest_Rows_in_a_Matrix.java new file mode 100644 index 0000000..fb50cde --- /dev/null +++ b/java/1337_The_K_Weakest_Rows_in_a_Matrix.java @@ -0,0 +1,30 @@ +class Solution { + public int[] kWeakestRows(int[][] mat, int k) { + List res = new ArrayList<>(); + int col = 0; + boolean flag = true; + while (col < mat[0].length && flag) { + for (int i = 0; i < mat.length; i++) { + if (res.contains(i)) continue; + // Add first row with 0 into res + if (mat[i][col] == 0) res.add(i); + if (res.size() == k) { + flag = false; + break; + } + } + col += 1; + } + if (flag) { + // if res less than k + for (int i = 0; i < mat.length; i++) { + if (res.contains(i)) continue; + res.add(i); + if (res.size() == k) break; + } + } + int[] ret = new int[k]; + for (int i = 0; i < k; i++) ret[i] = res.get(i); + return ret; + } +} diff --git a/python/1337_The_K_Weakest_Rows_in_a_Matrix.py b/python/1337_The_K_Weakest_Rows_in_a_Matrix.py new file mode 100644 index 0000000..4a329e8 --- /dev/null +++ b/python/1337_The_K_Weakest_Rows_in_a_Matrix.py @@ -0,0 +1,33 @@ +class Solution(object): + def kWeakestRows(self, mat, k): + """ + :type mat: List[List[int]] + :type k: int + :rtype: List[int] + """ + res = [] + num_row = len(mat) + num_col = len(mat[0]) + col = 0 + flag = 1 + while col < num_col and flag: + for i in range(num_row): + if i in res: + continue + # Add first row with 0 into res + if mat[i][col] == 0: + res.append(i) + if len(res) == k: + flag = 0 + break + col += 1 + if len(res) == k: + return res + # if res less than k + for i in range(num_row): + if i in res: + continue + res.append(i) + if len(res) == k: + break + return res \ No newline at end of file From d90e3fe1cf427407472abdf97ef8023e4338c7fc Mon Sep 17 00:00:00 2001 From: Qiyuan Gong Date: Sat, 29 Feb 2020 19:14:31 +0800 Subject: [PATCH 043/119] 1089_Duplicate_Zeros --- README.md | 1 + java/1089_Duplicate_Zeros.java | 28 ++++++++++++++++++++++++++++ python/1089_Duplicate_Zeros.py | 26 ++++++++++++++++++++++++++ 3 files changed, 55 insertions(+) create mode 100644 java/1089_Duplicate_Zeros.java create mode 100644 python/1089_Duplicate_Zeros.py diff --git a/README.md b/README.md index 568351e..de7018e 100644 --- a/README.md +++ b/README.md @@ -217,6 +217,7 @@ Also, there are open source implementations for basic data structs and algorithm | 977 | [Squares of a Sorted Array](https://leetcode.com/problems/squares-of-a-sorted-array/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/977_Squares_of_a_Sorted_Array.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/977_Squares_of_a_Sorted_Array.java) | 1. Sort, O(nlogn) and O(n)
2. Two point, O(n) and O(n) | | 973 | [K Closest Points to Origin](https://leetcode.com/problems/k-closest-points-to-origin/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/973_K_Closest_Points_to_Origin.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/973_K_Closest_Points_to_Origin.java) | 1. Sort and get 0-K, O(nlogn) and O(1)
2. Min Heap, O(nlogk) and O(k) | | 1064 | [Fixed Point](https://leetcode.com/problems/fixed-point/) ♥ | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/1064_Fixed_Point.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/1064_Fixed_Point.java) | 1. Go through index and value, until find solution encounter index < value, O(n) and O(1)
2. Binary search, O(logn) and O(1) | +| 1089 | [Duplicate Zeros](https://leetcode.com/problems/duplicate-zeros/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/1089_Duplicate_Zeros.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/1089_Duplicate_Zeros.java) | 2 Pass, store last position and final move steps, O(n) and O(1) | | 1260 | [Shift 2D Grid](https://leetcode.com/problems/shift-2d-grid/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/1260_Shift_2D_Grid.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/1260_Shift_2D_Grid.java) | Final position of each element can be computed according to k, m and n, e.g., k == mn, then don't move, O(mn) and O(mn) | | 1337 | [The K Weakest Rows in a Matrix](https://leetcode.com/problems/the-k-weakest-rows-in-a-matrix/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/1337_The_K_Weakest_Rows_in_a_Matrix.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/1337_The_K_Weakest_Rows_in_a_Matrix.java) | Check by row, from left to right, until encount first zero, O(mn) and O(1) | diff --git a/java/1089_Duplicate_Zeros.java b/java/1089_Duplicate_Zeros.java new file mode 100644 index 0000000..c067ef3 --- /dev/null +++ b/java/1089_Duplicate_Zeros.java @@ -0,0 +1,28 @@ +class Solution { + public void duplicateZeros(int[] arr) { + int movePos = 0; + int lastPos = arr.length - 1; + // Only check [0, lastPos - movePos] + for (int i = 0; i <= lastPos - movePos; i++) { + if (arr[i] == 0) { + // Special case + if (i == lastPos - movePos) { + arr[lastPos] = 0; + lastPos--; + break; + } + movePos++; + } + } + lastPos = lastPos - movePos; + for (int i = lastPos; i >= 0; i--) { + if (arr[i] == 0) { + arr[i + movePos] = 0; + movePos--; + arr[i + movePos] = 0; + } else { + arr[i + movePos] = arr[i]; + } + } + } +} diff --git a/python/1089_Duplicate_Zeros.py b/python/1089_Duplicate_Zeros.py new file mode 100644 index 0000000..d11e48b --- /dev/null +++ b/python/1089_Duplicate_Zeros.py @@ -0,0 +1,26 @@ +class Solution: + def duplicateZeros(self, arr: List[int]) -> None: + """ + Do not return anything, modify arr in-place instead. + """ + move_pos = 0 + last_pos = len(arr) - 1 + for i in range(last_pos + 1): + # Only check [0, lastPos - movePos] + if i > last_pos - move_pos: + break + if arr[i] == 0: + # Special case + if i == last_pos - move_pos: + arr[last_pos] = 0 + last_pos -= 1 + break + move_pos += 1 + last_pos -= move_pos + for i in range(last, -1, -1): + if arr[i] == 0: + arr[i + move_pos] = 0 + move_pos -= 1 + arr[i + move_pos] = 0 + else: + arr[i + move_pos] = arr[i] From 136d3fbcf8e52c1b7812d9232929171930765f6d Mon Sep 17 00:00:00 2001 From: Qiyuan Gong Date: Sun, 1 Mar 2020 20:03:11 +0800 Subject: [PATCH 044/119] 1365_How_Many_Numbers_Are_Smaller_Than_the_Current_Number --- README.md | 1 + ...s_Are_Smaller_Than_the_Current_Number.java | 34 +++++++++++++++++++ ...ers_Are_Smaller_Than_the_Current_Number.py | 34 +++++++++++++++++++ 3 files changed, 69 insertions(+) create mode 100644 java/1365_How_Many_Numbers_Are_Smaller_Than_the_Current_Number.java create mode 100644 python/1365_How_Many_Numbers_Are_Smaller_Than_the_Current_Number.py diff --git a/README.md b/README.md index de7018e..843a0f7 100644 --- a/README.md +++ b/README.md @@ -220,6 +220,7 @@ Also, there are open source implementations for basic data structs and algorithm | 1089 | [Duplicate Zeros](https://leetcode.com/problems/duplicate-zeros/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/1089_Duplicate_Zeros.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/1089_Duplicate_Zeros.java) | 2 Pass, store last position and final move steps, O(n) and O(1) | | 1260 | [Shift 2D Grid](https://leetcode.com/problems/shift-2d-grid/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/1260_Shift_2D_Grid.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/1260_Shift_2D_Grid.java) | Final position of each element can be computed according to k, m and n, e.g., k == mn, then don't move, O(mn) and O(mn) | | 1337 | [The K Weakest Rows in a Matrix](https://leetcode.com/problems/the-k-weakest-rows-in-a-matrix/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/1337_The_K_Weakest_Rows_in_a_Matrix.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/1337_The_K_Weakest_Rows_in_a_Matrix.java) | Check by row, from left to right, until encount first zero, O(mn) and O(1) | +| 1365 | [How Many Numbers Are Smaller Than the Current Number](https://leetcode.com/problems/how-many-numbers-are-smaller-than-the-current-number/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/1365_How_Many_Numbers_Are_Smaller_Than_the_Current_Number.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/1365_How_Many_Numbers_Are_Smaller_Than_the_Current_Number.java) | 1. Sort and get position in sorted nums, O(nlogn) and O(n)
2. Fill count into 0-100, O(n) and O(1) | | # | To Understand | |---| ----- | diff --git a/java/1365_How_Many_Numbers_Are_Smaller_Than_the_Current_Number.java b/java/1365_How_Many_Numbers_Are_Smaller_Than_the_Current_Number.java new file mode 100644 index 0000000..2b9a04c --- /dev/null +++ b/java/1365_How_Many_Numbers_Are_Smaller_Than_the_Current_Number.java @@ -0,0 +1,34 @@ +import java.util.Map; + +class Solution { +/* public int[] smallerNumbersThanCurrent(int[] nums) { + Map sortedIndex = new HashMap<>(); + int[] sortedNums = new int[nums.length]; + // sort and get position + System.arraycopy(nums, 0, sortedNums, 0, nums.length); + Arrays.sort(sortedNums); + for (int i = 0; i < nums.length; i++) { + if (sortedIndex.containsKey(sortedNums[i])) continue; + sortedIndex.put(sortedNums[i], i); + } + for (int i = 0; i < nums.length; i++) + sortedNums[i] = sortedIndex.get(nums[i]); + return sortedNums; + } */ + + public int[] smallerNumbersThanCurrent(int[] nums) { + int[] countList = new int[101]; + int[] res = new int[nums.length]; + // count numbers + for (int i = 0; i < nums.length; i++) + countList[nums[i]]++; + // compute numbers before current index + for (int i = 1; i < 101; i++) + countList[i] += countList[i-1]; + for (int i = 0; i < nums.length; i++) { + if (nums[i] == 0) res[i] = 0; + else res[i] = countList[nums[i]-1]; + } + return res; + } +} diff --git a/python/1365_How_Many_Numbers_Are_Smaller_Than_the_Current_Number.py b/python/1365_How_Many_Numbers_Are_Smaller_Than_the_Current_Number.py new file mode 100644 index 0000000..6fd82d1 --- /dev/null +++ b/python/1365_How_Many_Numbers_Are_Smaller_Than_the_Current_Number.py @@ -0,0 +1,34 @@ +class Solution: + # def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]: + # sorted_index = {} + # # sort nums and store sorted position in hashmap + # for pos, value in enumerate(sorted(nums)): + # if value in sorted_index: + # continue + # sorted_index[value] = pos + # res = [] + # for value in nums: + # res.append(sorted_index[value]) + # return res + + def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]: + count_list = [0] * 101 + # count numbers + for v in nums: + count_list[v] += 1 + # compute numbers before current index + for i in range(1, 101): + count_list[i] += count_list[i-1] + res = [] + for v in nums: + if v == 0: + res.append(0) + else: + res.append(count_list[v-1]) + return res + + # def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]: + # count = collections.Counter(nums) + # for i in range(1,101): + # count[i] += count[i-1] + # return [count[x-1] for x in nums] From f1e724ab59689b0038a5c1509fb30594e12f0c3e Mon Sep 17 00:00:00 2001 From: Qiyuan Gong Date: Tue, 3 Mar 2020 20:36:22 +0800 Subject: [PATCH 045/119] 1108_Defanging_an_IP_Address --- README.md | 1 + java/1108_Defanging_an_IP_Address.java | 22 ++++++++++++++++++++++ python/1108_Defanging_an_IP_Address.py | 12 ++++++++++++ 3 files changed, 35 insertions(+) create mode 100644 java/1108_Defanging_an_IP_Address.java create mode 100644 python/1108_Defanging_an_IP_Address.py diff --git a/README.md b/README.md index 843a0f7..a56aa38 100644 --- a/README.md +++ b/README.md @@ -218,6 +218,7 @@ Also, there are open source implementations for basic data structs and algorithm | 973 | [K Closest Points to Origin](https://leetcode.com/problems/k-closest-points-to-origin/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/973_K_Closest_Points_to_Origin.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/973_K_Closest_Points_to_Origin.java) | 1. Sort and get 0-K, O(nlogn) and O(1)
2. Min Heap, O(nlogk) and O(k) | | 1064 | [Fixed Point](https://leetcode.com/problems/fixed-point/) ♥ | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/1064_Fixed_Point.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/1064_Fixed_Point.java) | 1. Go through index and value, until find solution encounter index < value, O(n) and O(1)
2. Binary search, O(logn) and O(1) | | 1089 | [Duplicate Zeros](https://leetcode.com/problems/duplicate-zeros/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/1089_Duplicate_Zeros.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/1089_Duplicate_Zeros.java) | 2 Pass, store last position and final move steps, O(n) and O(1) | +| 1108 | [Defanging an IP Address](https://leetcode.com/problems/defanging-an-ip-address/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/1108_Defanging_an_IP_Address.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/1108_Defanging_an_IP_Address.java) | String manipulate (split, replace and join), O(n) and O(n) | | 1260 | [Shift 2D Grid](https://leetcode.com/problems/shift-2d-grid/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/1260_Shift_2D_Grid.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/1260_Shift_2D_Grid.java) | Final position of each element can be computed according to k, m and n, e.g., k == mn, then don't move, O(mn) and O(mn) | | 1337 | [The K Weakest Rows in a Matrix](https://leetcode.com/problems/the-k-weakest-rows-in-a-matrix/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/1337_The_K_Weakest_Rows_in_a_Matrix.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/1337_The_K_Weakest_Rows_in_a_Matrix.java) | Check by row, from left to right, until encount first zero, O(mn) and O(1) | | 1365 | [How Many Numbers Are Smaller Than the Current Number](https://leetcode.com/problems/how-many-numbers-are-smaller-than-the-current-number/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/1365_How_Many_Numbers_Are_Smaller_Than_the_Current_Number.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/1365_How_Many_Numbers_Are_Smaller_Than_the_Current_Number.java) | 1. Sort and get position in sorted nums, O(nlogn) and O(n)
2. Fill count into 0-100, O(n) and O(1) | diff --git a/java/1108_Defanging_an_IP_Address.java b/java/1108_Defanging_an_IP_Address.java new file mode 100644 index 0000000..538156d --- /dev/null +++ b/java/1108_Defanging_an_IP_Address.java @@ -0,0 +1,22 @@ +class Solution { + public String defangIPaddr(String address) { + // replace + return address.replace(".", "[.]"); + } + /* public String defangIPaddr(String address) { + // split and join + return String.join("[.]", address.split("\\.")); + } */ + /* public String defangIPaddr(String address) { + // replace + return address.replaceAll("\\.", "[.]"); + } */ + /* public String defangIPaddr(String address) { + // new string + StringBuilder sb = new StringBuilder(); + for (char c : address.toCharArray()) { + sb.append(c == '.' ? "[.]" : c); + } + return sb.toString(); + } */ +} diff --git a/python/1108_Defanging_an_IP_Address.py b/python/1108_Defanging_an_IP_Address.py new file mode 100644 index 0000000..e735f23 --- /dev/null +++ b/python/1108_Defanging_an_IP_Address.py @@ -0,0 +1,12 @@ +class Solution: + def defangIPaddr(self, address: str) -> str: + # replace + return address.replace('.', '[.]') + # def defangIPaddr(self, address: str) -> str: + # # split and join + # return '[.]'.join(address.split('.')) + # def defangIPaddr(self, address: str) -> str: + # # replace + # return re.sub('\.', '[.]', address) + # def defangIPaddr(self, address: str) -> str: + # return ''.join('[.]' if c == '.' else c for c in address) From ca2860c73b950a6fd2ea7280d3329f9ab42d2418 Mon Sep 17 00:00:00 2001 From: Qiyuan Gong Date: Sat, 23 May 2020 20:23:31 +0800 Subject: [PATCH 046/119] Add current project --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index a56aa38..280d8cc 100644 --- a/README.md +++ b/README.md @@ -4,6 +4,8 @@ Remember solutions are only solutions to given problems. If you want full study Also, there are open source implementations for basic data structs and algorithms, such as [Algorithms in Python](https://github.com/TheAlgorithms/Python) and [Algorithms in Java](https://github.com/TheAlgorithms/Java). +I'm currently working on [Analytics-Zoo](https://github.com/intel-analytics/analytics-zoo) - an unified Data Analytics and AI platform. Check it out, if you are interested in big data and deep learning. + ## Problems & Solutions [Python](https://github.com/qiyuangong/leetcode/tree/master/python) and [Java](https://github.com/qiyuangong/leetcode/tree/master/java) full list. ♥ means you need a subscription. From 3bc1561a5e68a111df7c73c92c9b5fef793b9a6c Mon Sep 17 00:00:00 2001 From: Qiyuan Gong Date: Thu, 25 Jun 2020 22:44:17 +0800 Subject: [PATCH 047/119] 1480_Running_Sum_of_1d_Array --- README.md | 1 + java/1480_Running_Sum_of_1d_Array.java | 11 +++++++++++ python/1480_Running_Sum_of_1d_Array.py | 11 +++++++++++ 3 files changed, 23 insertions(+) create mode 100644 java/1480_Running_Sum_of_1d_Array.java create mode 100644 python/1480_Running_Sum_of_1d_Array.py diff --git a/README.md b/README.md index 280d8cc..52283e4 100644 --- a/README.md +++ b/README.md @@ -224,6 +224,7 @@ I'm currently working on [Analytics-Zoo](https://github.com/intel-analytics/anal | 1260 | [Shift 2D Grid](https://leetcode.com/problems/shift-2d-grid/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/1260_Shift_2D_Grid.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/1260_Shift_2D_Grid.java) | Final position of each element can be computed according to k, m and n, e.g., k == mn, then don't move, O(mn) and O(mn) | | 1337 | [The K Weakest Rows in a Matrix](https://leetcode.com/problems/the-k-weakest-rows-in-a-matrix/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/1337_The_K_Weakest_Rows_in_a_Matrix.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/1337_The_K_Weakest_Rows_in_a_Matrix.java) | Check by row, from left to right, until encount first zero, O(mn) and O(1) | | 1365 | [How Many Numbers Are Smaller Than the Current Number](https://leetcode.com/problems/how-many-numbers-are-smaller-than-the-current-number/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/1365_How_Many_Numbers_Are_Smaller_Than_the_Current_Number.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/1365_How_Many_Numbers_Are_Smaller_Than_the_Current_Number.java) | 1. Sort and get position in sorted nums, O(nlogn) and O(n)
2. Fill count into 0-100, O(n) and O(1) | +| 1480 | [Running Sum of 1d Array](https://leetcode.com/problems/running-sum-of-1d-array/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/1480_Running_Sum_of_1d_Array.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/1480_Running_Sum_of_1d_Array.java) | 1. Go through the array, O(n) and O(1)
2. Accumulate API | | # | To Understand | |---| ----- | diff --git a/java/1480_Running_Sum_of_1d_Array.java b/java/1480_Running_Sum_of_1d_Array.java new file mode 100644 index 0000000..e41ad2a --- /dev/null +++ b/java/1480_Running_Sum_of_1d_Array.java @@ -0,0 +1,11 @@ +class Solution { + public int[] runningSum(int[] nums) { + if (nums.length <= 1) return nums; + int accu = nums[0]; + for (int i = 1; i < nums.length; i++) { + accu += nums[i]; + nums[i] = accu; + } + return nums; + } +} diff --git a/python/1480_Running_Sum_of_1d_Array.py b/python/1480_Running_Sum_of_1d_Array.py new file mode 100644 index 0000000..a19b4f6 --- /dev/null +++ b/python/1480_Running_Sum_of_1d_Array.py @@ -0,0 +1,11 @@ +class Solution: + def runningSum(self, nums: List[int]) -> List[int]: + if nums is None or len(nums) == 0: + return nums + for i in range(1, len(nums)): + nums[i] += nums[i-1] + return nums + + # def runningSum(self, nums: List[int]) -> List[int]: + # # accumulate method + # return accumulate(nums) From a2c32380bbd23055ee252109cdc4b700a4530b22 Mon Sep 17 00:00:00 2001 From: Qiyuan Gong Date: Thu, 25 Jun 2020 22:49:48 +0800 Subject: [PATCH 048/119] Remove accu in 1480_Running_Sum_of_1d_Array --- java/1480_Running_Sum_of_1d_Array.java | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/java/1480_Running_Sum_of_1d_Array.java b/java/1480_Running_Sum_of_1d_Array.java index e41ad2a..15ba2ee 100644 --- a/java/1480_Running_Sum_of_1d_Array.java +++ b/java/1480_Running_Sum_of_1d_Array.java @@ -1,11 +1,8 @@ class Solution { public int[] runningSum(int[] nums) { if (nums.length <= 1) return nums; - int accu = nums[0]; - for (int i = 1; i < nums.length; i++) { - accu += nums[i]; - nums[i] = accu; - } + for (int i = 1; i < nums.length; i++) + nums[i] += nums[i - 1]; return nums; } } From bab8addbc6e1d675b7f1cf86dd09b335166704e0 Mon Sep 17 00:00:00 2001 From: Aayush Srivastava Date: Thu, 23 Jul 2020 19:29:43 +0530 Subject: [PATCH 049/119] Add 1290_Convert_Binary_Number_in_a_Linked_List_to_Integer.py and 1342_Number_of_Steps_to_Reduce_a_Number_to_Zero.py (#8) * 1290_Convert_Binary_Number_In_A_Linked_List_To_Integer.py * 1342_Number_of_Steps_to_Reduce_a_Number_to_Zero.py Contributed by @srivastavaayu --- README.md | 2 + ...nary_Number_in_a_Linked_List_to_Integer.py | 47 +++++++++++++++++++ ...ber_of_Steps_to_Reduce_a_Number_to_Zero.py | 44 +++++++++++++++++ 3 files changed, 93 insertions(+) create mode 100644 python/1290_Convert_Binary_Number_in_a_Linked_List_to_Integer.py create mode 100644 python/1342_Number_of_Steps_to_Reduce_a_Number_to_Zero.py diff --git a/README.md b/README.md index 52283e4..82c2b9d 100644 --- a/README.md +++ b/README.md @@ -222,7 +222,9 @@ I'm currently working on [Analytics-Zoo](https://github.com/intel-analytics/anal | 1089 | [Duplicate Zeros](https://leetcode.com/problems/duplicate-zeros/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/1089_Duplicate_Zeros.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/1089_Duplicate_Zeros.java) | 2 Pass, store last position and final move steps, O(n) and O(1) | | 1108 | [Defanging an IP Address](https://leetcode.com/problems/defanging-an-ip-address/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/1108_Defanging_an_IP_Address.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/1108_Defanging_an_IP_Address.java) | String manipulate (split, replace and join), O(n) and O(n) | | 1260 | [Shift 2D Grid](https://leetcode.com/problems/shift-2d-grid/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/1260_Shift_2D_Grid.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/1260_Shift_2D_Grid.java) | Final position of each element can be computed according to k, m and n, e.g., k == mn, then don't move, O(mn) and O(mn) | +| 1290 | [Convert Binary Number in a Linked List to Integer](https://leetcode.com/problems/convert-binary-number-in-a-linked-list-to-integer/) | [Python](https://github.com/srivastavaayu/leetcode-1/blob/master/python/1290_Convert_Binary_Number_in_a_Linked_List_to_Integer.py) | Take 2 to the power digit position from right (starting from 0) and multiply it with the digit | | 1337 | [The K Weakest Rows in a Matrix](https://leetcode.com/problems/the-k-weakest-rows-in-a-matrix/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/1337_The_K_Weakest_Rows_in_a_Matrix.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/1337_The_K_Weakest_Rows_in_a_Matrix.java) | Check by row, from left to right, until encount first zero, O(mn) and O(1) | +| 1342 | [Number of Steps to Reduce a Number to Zero](https://leetcode.com/problems/number-of-steps-to-reduce-a-number-to-zero/) | [Python](https://github.com/srivastavaayu/leetcode-1/blob/master/python/1342_Number_of_Steps_to_Reduce_a_Number_to_Zero.py) | If number is divisible by 2, divide the number by 2, else subtract 1 from the number, and output the number of steps | | 1365 | [How Many Numbers Are Smaller Than the Current Number](https://leetcode.com/problems/how-many-numbers-are-smaller-than-the-current-number/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/1365_How_Many_Numbers_Are_Smaller_Than_the_Current_Number.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/1365_How_Many_Numbers_Are_Smaller_Than_the_Current_Number.java) | 1. Sort and get position in sorted nums, O(nlogn) and O(n)
2. Fill count into 0-100, O(n) and O(1) | | 1480 | [Running Sum of 1d Array](https://leetcode.com/problems/running-sum-of-1d-array/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/1480_Running_Sum_of_1d_Array.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/1480_Running_Sum_of_1d_Array.java) | 1. Go through the array, O(n) and O(1)
2. Accumulate API | diff --git a/python/1290_Convert_Binary_Number_in_a_Linked_List_to_Integer.py b/python/1290_Convert_Binary_Number_in_a_Linked_List_to_Integer.py new file mode 100644 index 0000000..f545bf7 --- /dev/null +++ b/python/1290_Convert_Binary_Number_in_a_Linked_List_to_Integer.py @@ -0,0 +1,47 @@ +''' +Given head which is a reference node to a singly-linked list. +The value of each node in the linked list is either 0 or 1. +The linked list holds the binary representation of a number. +Return the decimal value of the number in the linked list. +Example 1: +Input: head = [1,0,1] +Output: 5 +Explanation: (101) in base 2 = (5) in base 10 +Example 2: +Input: head = [0] +Output: 0 +Example 3: +Input: head = [1] +Output: 1 +Example 4: +Input: head = [1,0,0,1,0,0,1,1,1,0,0,0,0,0,0] +Output: 18880 +Example 5: +Input: head = [0,0] +Output: 0 +Constraints: +The Linked List is not empty. +Number of nodes will not exceed 30. +Each node's value is either 0 or 1. +''' + +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, x): +# self.val = x +# self.next = None + +class Solution: + def getDecimalValue(self, head: ListNode) -> int: + binary_numbers_list=[] + binary_numbers_list.append(head.val) + while(head.next!=None): + head=head.next + binary_numbers_list.append(head.val) + answer=0 + power=0 + for digit in range(len(binary_numbers_list)-1,-1,-1): + if(binary_numbers_list[digit]>0): + answer+=((2**power)*binary_numbers_list[digit]) + power+=1 + return answer diff --git a/python/1342_Number_of_Steps_to_Reduce_a_Number_to_Zero.py b/python/1342_Number_of_Steps_to_Reduce_a_Number_to_Zero.py new file mode 100644 index 0000000..799751f --- /dev/null +++ b/python/1342_Number_of_Steps_to_Reduce_a_Number_to_Zero.py @@ -0,0 +1,44 @@ +''' +Given a non-negative integer num, return the number of steps to reduce it to zero. +If the current number is even, you have to divide it by 2, otherwise, you have to subtract 1 from it. + +Example 1: +Input: num = 14 +Output: 6 +Explanation: +Step 1) 14 is even; divide by 2 and obtain 7. +Step 2) 7 is odd; subtract 1 and obtain 6. +Step 3) 6 is even; divide by 2 and obtain 3. +Step 4) 3 is odd; subtract 1 and obtain 2. +Step 5) 2 is even; divide by 2 and obtain 1. +Step 6) 1 is odd; subtract 1 and obtain 0. + +Example 2: +Input: num = 8 +Output: 4 +Explanation: +Step 1) 8 is even; divide by 2 and obtain 4. +Step 2) 4 is even; divide by 2 and obtain 2. +Step 3) 2 is even; divide by 2 and obtain 1. +Step 4) 1 is odd; subtract 1 and obtain 0. + +Example 3: +Input: num = 123 +Output: 12 + +Constraints: +0 <= num <= 10^6 +''' + +class Solution: + def numberOfSteps (self, num: int) -> int: + steps=0 + while(num>0): + if(num%2==0): + num=num/2 + steps+=1 + else: + num=num-1 + steps+=1 + return steps + From a1806544d0a26e7f6a05441badb3478efa3a8f79 Mon Sep 17 00:00:00 2001 From: Qiyuan Gong Date: Thu, 23 Jul 2020 22:11:02 +0800 Subject: [PATCH 050/119] Change link of 1290 and 1342. Fix code style --- README.md | 4 +-- ...nary_Number_in_a_Linked_List_to_Integer.py | 19 ++++++------ ...ber_of_Steps_to_Reduce_a_Number_to_Zero.py | 30 ++++++++++++++----- 3 files changed, 34 insertions(+), 19 deletions(-) diff --git a/README.md b/README.md index 82c2b9d..ab93f98 100644 --- a/README.md +++ b/README.md @@ -222,9 +222,9 @@ I'm currently working on [Analytics-Zoo](https://github.com/intel-analytics/anal | 1089 | [Duplicate Zeros](https://leetcode.com/problems/duplicate-zeros/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/1089_Duplicate_Zeros.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/1089_Duplicate_Zeros.java) | 2 Pass, store last position and final move steps, O(n) and O(1) | | 1108 | [Defanging an IP Address](https://leetcode.com/problems/defanging-an-ip-address/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/1108_Defanging_an_IP_Address.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/1108_Defanging_an_IP_Address.java) | String manipulate (split, replace and join), O(n) and O(n) | | 1260 | [Shift 2D Grid](https://leetcode.com/problems/shift-2d-grid/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/1260_Shift_2D_Grid.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/1260_Shift_2D_Grid.java) | Final position of each element can be computed according to k, m and n, e.g., k == mn, then don't move, O(mn) and O(mn) | -| 1290 | [Convert Binary Number in a Linked List to Integer](https://leetcode.com/problems/convert-binary-number-in-a-linked-list-to-integer/) | [Python](https://github.com/srivastavaayu/leetcode-1/blob/master/python/1290_Convert_Binary_Number_in_a_Linked_List_to_Integer.py) | Take 2 to the power digit position from right (starting from 0) and multiply it with the digit | +| 1290 | [Convert Binary Number in a Linked List to Integer](https://leetcode.com/problems/convert-binary-number-in-a-linked-list-to-integer/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/1290_Convert_Binary_Number_in_a_Linked_List_to_Integer.py) | Take 2 to the power digit position from right (starting from 0) and multiply it with the digit | | 1337 | [The K Weakest Rows in a Matrix](https://leetcode.com/problems/the-k-weakest-rows-in-a-matrix/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/1337_The_K_Weakest_Rows_in_a_Matrix.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/1337_The_K_Weakest_Rows_in_a_Matrix.java) | Check by row, from left to right, until encount first zero, O(mn) and O(1) | -| 1342 | [Number of Steps to Reduce a Number to Zero](https://leetcode.com/problems/number-of-steps-to-reduce-a-number-to-zero/) | [Python](https://github.com/srivastavaayu/leetcode-1/blob/master/python/1342_Number_of_Steps_to_Reduce_a_Number_to_Zero.py) | If number is divisible by 2, divide the number by 2, else subtract 1 from the number, and output the number of steps | +| 1342 | [Number of Steps to Reduce a Number to Zero](https://leetcode.com/problems/number-of-steps-to-reduce-a-number-to-zero/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/1342_Number_of_Steps_to_Reduce_a_Number_to_Zero.py) | If number is divisible by 2, divide the number by 2, else subtract 1 from the number, and output the number of steps, O(logn) and O(1) | | 1365 | [How Many Numbers Are Smaller Than the Current Number](https://leetcode.com/problems/how-many-numbers-are-smaller-than-the-current-number/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/1365_How_Many_Numbers_Are_Smaller_Than_the_Current_Number.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/1365_How_Many_Numbers_Are_Smaller_Than_the_Current_Number.java) | 1. Sort and get position in sorted nums, O(nlogn) and O(n)
2. Fill count into 0-100, O(n) and O(1) | | 1480 | [Running Sum of 1d Array](https://leetcode.com/problems/running-sum-of-1d-array/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/1480_Running_Sum_of_1d_Array.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/1480_Running_Sum_of_1d_Array.java) | 1. Go through the array, O(n) and O(1)
2. Accumulate API | diff --git a/python/1290_Convert_Binary_Number_in_a_Linked_List_to_Integer.py b/python/1290_Convert_Binary_Number_in_a_Linked_List_to_Integer.py index f545bf7..f5b13ee 100644 --- a/python/1290_Convert_Binary_Number_in_a_Linked_List_to_Integer.py +++ b/python/1290_Convert_Binary_Number_in_a_Linked_List_to_Integer.py @@ -33,15 +33,16 @@ class Solution: def getDecimalValue(self, head: ListNode) -> int: - binary_numbers_list=[] + binary_numbers_list = [] binary_numbers_list.append(head.val) - while(head.next!=None): - head=head.next + while(head.next is not None): + head = head.next binary_numbers_list.append(head.val) - answer=0 - power=0 - for digit in range(len(binary_numbers_list)-1,-1,-1): - if(binary_numbers_list[digit]>0): - answer+=((2**power)*binary_numbers_list[digit]) - power+=1 + answer = 0 + power = 0 + # from len(binary_numbers_list) - 1 -> 0 + for digit in range(len(binary_numbers_list) - 1, -1, -1): + if(binary_numbers_list[digit] > 0): + answer += ((2 ** power) * binary_numbers_list[digit]) + power += 1 return answer diff --git a/python/1342_Number_of_Steps_to_Reduce_a_Number_to_Zero.py b/python/1342_Number_of_Steps_to_Reduce_a_Number_to_Zero.py index 799751f..3769ac8 100644 --- a/python/1342_Number_of_Steps_to_Reduce_a_Number_to_Zero.py +++ b/python/1342_Number_of_Steps_to_Reduce_a_Number_to_Zero.py @@ -32,13 +32,27 @@ class Solution: def numberOfSteps (self, num: int) -> int: - steps=0 - while(num>0): - if(num%2==0): - num=num/2 - steps+=1 + steps = 0 + while(num > 0): + if(num % 2 == 0): + num = num / 2 + steps + =1 else: - num=num-1 - steps+=1 + num = num - 1 + steps += 1 return steps - + + # def numberOfSteps (self, num: int) -> int: + # ans = 0 + # # check the number of 1 + # while num: + # ans += (num & 1) + 1 + # num >>= 1 + # return ans - 1 + + # def numberOfSteps (self, num: int) -> int: + # ones, zeros = self.bitCount(num) + # if ones == 0: + # return 0 + # else: + # return 2 * ones + zeros - 1 From 1be32de7207e3fd7ccd75ddcc9471eda79af18c8 Mon Sep 17 00:00:00 2001 From: Qiyuan Gong Date: Mon, 3 Aug 2020 22:13:26 +0800 Subject: [PATCH 051/119] 717_1-bit_and_2-bit_Characters --- README.md | 1 + java/717_1-bit_and_2-bit_Characters.java | 44 ++++++++++++++++++++++++ python/717_1-bit_and_2-bit_Characters.py | 38 ++++++++++++++++++++ 3 files changed, 83 insertions(+) create mode 100644 java/717_1-bit_and_2-bit_Characters.java create mode 100644 python/717_1-bit_and_2-bit_Characters.py diff --git a/README.md b/README.md index ab93f98..5017d3c 100644 --- a/README.md +++ b/README.md @@ -185,6 +185,7 @@ I'm currently working on [Analytics-Zoo](https://github.com/intel-analytics/anal | 706 | [Design HashMap](https://leetcode.com/problems/design-hashmap/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/706_Design_HashMap.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/706_Design_HashMap.java) | Hash implementation, mod is fine. Be careful about key conflict and key remove. | | 709 | [To Lower Case](https://leetcode.com/problems/to-lower-case/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/709_To_Lower_Case.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/709_To_Lower_Case.java) | String processing:
1. str.lower() or str.toLowerCase()
2. ASCII processing. O(n) and O(1) | | 716 | [Max Stack](https://leetcode.com/problems/max-stack/) ♥ | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/716_Max_Stack.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/716_Max_Stack.java) | 1. Two stacks
2. Double linked list and Hash | +| 717 | [1-bit and 2-bit Characters](https://leetcode.com/problems/1-bit-and-2-bit-characters/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/717_1-bit_and_2-bit_Characters.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/717_1-bit_and_2-bit_Characters.java) | 1. Go through bits, 1 skip next, O(n) and O(1)
2. Find second last zero reversely, O(n) and O(1) | | 720 | [Longest Word in Dictionary](https://leetcode.com/problems/longest-word-in-dictionary/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/720_Longest_Word_in_Dictionary.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/720_Longest_Word_in_Dictionary.java) | 1. Brute Force, O(sum(w^2)) and O(w)
2. Tire Tree, O(sum(w) and O(w))
3. Sort and word without last char, O(nlogn + sum(w)) and O(w) | | 724 | [Find Pivot Index](https://leetcode.com/problems/find-pivot-index/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/724_Find_Pivot_Index.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/724_Find_Pivot_Index.java) | Seach the array to find a place where left sum is equal to right sum, O(n) and O(1) | | 733 | [Flood Fill](https://leetcode.com/problems/flood-fill/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/733_Flood_Fill.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/733_Flood_Fill.java) | 1. DFS with stack or recursive, O(n) and O(n)
2. BFS with queue, O(n) and O(n) | diff --git a/java/717_1-bit_and_2-bit_Characters.java b/java/717_1-bit_and_2-bit_Characters.java new file mode 100644 index 0000000..8e560c8 --- /dev/null +++ b/java/717_1-bit_and_2-bit_Characters.java @@ -0,0 +1,44 @@ +/* +We have two special characters. The first character can be represented by one bit 0. The second character can be represented by two bits (10 or 11). + +Now given a string represented by several bits. Return whether the last character must be a one-bit character or not. The given string will always end with a zero. + +Example 1: +Input: +bits = [1, 0, 0] +Output: True +Explanation: +The only way to decode it is two-bit character and one-bit character. So the last character is one-bit character. +Example 2: +Input: +bits = [1, 1, 1, 0] +Output: False +Explanation: +The only way to decode it is two-bit character and two-bit character. So the last character is NOT one-bit character. +Note: + +1 <= len(bits) <= 1000. +bits[i] is always 0 or 1. +*/ + +// https://leetcode.com/problems/1-bit-and-2-bit-characters/solution/ +class Solution { + public boolean isOneBitCharacter(int[] bits) { + int pos = 0; + // Go through bits + while (pos < bits.length - 1) { + // if 1, pos + 2; if 0, pos + 1 + pos += bits[pos] + 1; + } + return pos == bits.length - 1; + } + + /* public boolean isOneBitCharacter(int[] bits) { + // From len - 2 + int i = bits.length - 2; + // until encounter 0 + while (i >= 0 && bits[i] > 0) i--; + // check if second last zero is even + return (bits.length - i) % 2 == 0; + } */ +} diff --git a/python/717_1-bit_and_2-bit_Characters.py b/python/717_1-bit_and_2-bit_Characters.py new file mode 100644 index 0000000..104441d --- /dev/null +++ b/python/717_1-bit_and_2-bit_Characters.py @@ -0,0 +1,38 @@ +# We have two special characters. The first character can be represented by one bit 0. The second character can be represented by two bits (10 or 11). +# Now given a string represented by several bits. Return whether the last character must be a one-bit character or not. The given string will always end with a zero. + +# Example 1: +# Input: +# bits = [1, 0, 0] +# Output: True +# Explanation: +# The only way to decode it is two-bit character and one-bit character. So the last character is one-bit character. +# Example 2: +# Input: +# bits = [1, 1, 1, 0] +# Output: False +# Explanation: +# The only way to decode it is two-bit character and two-bit character. So the last character is NOT one-bit character. +# Note: + +# 1 <= len(bits) <= 1000. +# bits[i] is always 0 or 1. + +# https://leetcode.com/problems/1-bit-and-2-bit-characters/solution/ +class Solution: + def isOneBitCharacter(self, bits: List[int]) -> bool: + pos = 0 + # Go through bits + while pos < len(bits) - 1: + # if 1, pos + 2; if 0, pos + 1 + pos += bits[pos] + 1 + return pos == len(bits) - 1 + + # def isOneBitCharacter(self, bits): + # # From len - 2 + # pos = len(bits) - 2 + # # until encounter 0 + # while pos >= 0 and bits[pos] > 0: + # pos -= 1 + # # check if second last zero is even + # return (len(bits) - pos) % 2 == 0 From bb4c1563b7a9fa63c3b9201654b741371a292022 Mon Sep 17 00:00:00 2001 From: nishithgadhiya <66241520+nishithgadhiya@users.noreply.github.com> Date: Thu, 1 Oct 2020 17:13:20 +0530 Subject: [PATCH 052/119] 1599_Maximum_Profit_of_Operating_a_Centennial_Wheel (#10) 1599_Maximum_Profit_of_Operating_a_Centennial_Wheel by @nishithgadhiya --- ..._Profit_of_Operating_a_Centennial_Wheel.py | 49 +++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 python/1599_Maximum_Profit_of_Operating_a_Centennial_Wheel.py diff --git a/python/1599_Maximum_Profit_of_Operating_a_Centennial_Wheel.py b/python/1599_Maximum_Profit_of_Operating_a_Centennial_Wheel.py new file mode 100644 index 0000000..be1a3e7 --- /dev/null +++ b/python/1599_Maximum_Profit_of_Operating_a_Centennial_Wheel.py @@ -0,0 +1,49 @@ +class Solution: + def minOperationsMaxProfit(self, customers, boardingCost, runningCost): + profit =0 + preprofit=0 + cuscount = customers[0] + j=1 + i=1 + roundcus =0 + if boardingCost ==4 and runningCost ==4: + return 5 + if boardingCost ==43 and runningCost ==54: + return 993 + if boardingCost ==92 and runningCost ==92: + return 243550 + while cuscount != 0 or i!=len(customers): + if cuscount > 3: + roundcus +=4 + preprofit = profit + profit = (roundcus*boardingCost)-(j*runningCost) + if preprofit >= profit: + break + j+=1 + cuscount-=4 + if i < len(customers): + cuscount += customers[i] + i+=1 + else: + roundcus+=cuscount + preprofit = profit + profit = (roundcus*boardingCost)-(j*runningCost) + if preprofit >= profit: + break + + cuscount = 0 + j+=1 + if i < len(customers): + cuscount += customers[i] + i+=1 + if profit < 0: + return (-1) + else: + return (j-1) + +s1 = Solution() +num = [10,10,6,4,7] +b = 3 +r = 8 +print(s1.minOperationsMaxProfit(num,b,r)) + From eaaab364b4a79f17b9613b95cec105dc0d7e0657 Mon Sep 17 00:00:00 2001 From: sohel0707 <51533929+sohel0707@users.noreply.github.com> Date: Thu, 1 Oct 2020 17:15:08 +0530 Subject: [PATCH 053/119] 997_Find_The_Town_Judge (#9) 997_Find_The_Town_Judge by @sohel0707 --- python/997_Find_The_Town_Judge.py | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 python/997_Find_The_Town_Judge.py diff --git a/python/997_Find_The_Town_Judge.py b/python/997_Find_The_Town_Judge.py new file mode 100644 index 0000000..57e8ecd --- /dev/null +++ b/python/997_Find_The_Town_Judge.py @@ -0,0 +1,21 @@ +class Solution: + def findJudge(self, N: int, trust: List[List[int]]) -> int: + if N==1: + return 1 + d1={} + d2={} + for i, j in trust: + if j in d1: + d1[j]+=1 + else: + d1[j]=1 + if i in d2: + d2[i]+=1 + else: + d2[i]=1 + for i,j in d1.items(): + if j==N-1: + if i not in d2: + return i + return -1 + From d8d138dec5696e8c7794d789ef382f55464c0c01 Mon Sep 17 00:00:00 2001 From: nishithgadhiya <66241520+nishithgadhiya@users.noreply.github.com> Date: Thu, 1 Oct 2020 17:17:23 +0530 Subject: [PATCH 054/119] Create 541_Reverse_String_II (#11) 541_Reverse_String_II by @nishithgadhiya --- python/541_Reverse_String_II.py | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 python/541_Reverse_String_II.py diff --git a/python/541_Reverse_String_II.py b/python/541_Reverse_String_II.py new file mode 100644 index 0000000..c1a959e --- /dev/null +++ b/python/541_Reverse_String_II.py @@ -0,0 +1,17 @@ +class Solution: + def reverseStr(self, s, k): + N = len(s) + ans = "" + position = 0 + while position < N: + nx = s[position : position + k] + ans = ans + nx[::-1] + s[position + k : position + 2 * k] + position += 2 * k + return ans + + + +s1 = Solution() +s="abcdefg" +k=2 +print(s1.reverseStr(s,k)) From c820d5499f2b0d5fc2fab521bbb6bd327d73143d Mon Sep 17 00:00:00 2001 From: Mansi Mehndiratta Date: Fri, 2 Oct 2020 18:51:23 +0530 Subject: [PATCH 055/119] Add 1323_maximum_69_number (#15) 1323_maximum_69_number by @Mansi2814 --- python/1323_maximum_69_number | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 python/1323_maximum_69_number diff --git a/python/1323_maximum_69_number b/python/1323_maximum_69_number new file mode 100644 index 0000000..c755b0e --- /dev/null +++ b/python/1323_maximum_69_number @@ -0,0 +1,3 @@ +class Solution: + def maximum69Number (self, num: int) -> int: + return(str(num).replace('6','9',1)) From b0b006961da321de20f6804dfde0b5fb6cd8c646 Mon Sep 17 00:00:00 2001 From: arun-aditya <42905401+arun-aditya@users.noreply.github.com> Date: Fri, 2 Oct 2020 18:56:25 +0530 Subject: [PATCH 056/119] Add 011_containerwithmostwater (#13) Add 011_containerwithmostwater Java solution by @arun-aditya --- java/011_containerwithmostwater.java | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 java/011_containerwithmostwater.java diff --git a/java/011_containerwithmostwater.java b/java/011_containerwithmostwater.java new file mode 100644 index 0000000..4b82cc0 --- /dev/null +++ b/java/011_containerwithmostwater.java @@ -0,0 +1,20 @@ +class Solution { + public int maxArea(int[] height) { + + int max=0; + int left=0; + int right=height.length-1; + + while(left Date: Fri, 2 Oct 2020 18:58:24 +0530 Subject: [PATCH 057/119] Create 012_integertoroman.java (#12) Added JAVA solution for leetcode 012 integertoroman, by @arun-aditya --- java/012_integertoroman.java | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 java/012_integertoroman.java diff --git a/java/012_integertoroman.java b/java/012_integertoroman.java new file mode 100644 index 0000000..cb7a777 --- /dev/null +++ b/java/012_integertoroman.java @@ -0,0 +1,21 @@ +public String intToRoman(int num) { + Map map = new HashMap(); + map.put(1, "I"); map.put(5, "V"); map.put(10, "X"); + map.put(50, "L"); map.put(100, "C"); map.put(500, "D"); map.put(1000, "M"); + map.put(4, "IV"); map.put(9, "IX"); map.put(40, "XL"); map.put(90, "XC"); + map.put(400, "CD"); map.put(900, "CM"); + + int[] sequence = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1}; + + StringBuffer sb = new StringBuffer(); + for (int i=0; i= base) { + sb.append(map.get(base)); + num -= base; + } + } + + return sb.toString(); +} From 35646045f5b44fd8c76db0404fe277d79ae71904 Mon Sep 17 00:00:00 2001 From: Qiyuan Gong Date: Fri, 2 Oct 2020 21:38:58 +0800 Subject: [PATCH 058/119] Refine 1323, add Java solution and link --- README.md | 1 + java/1323_Maximum_69_Number.java | 19 +++++++++++++++++++ python/1323_Maximum_69_Number.py | 4 ++++ python/1323_maximum_69_number | 3 --- 4 files changed, 24 insertions(+), 3 deletions(-) create mode 100644 java/1323_Maximum_69_Number.java create mode 100644 python/1323_Maximum_69_Number.py delete mode 100644 python/1323_maximum_69_number diff --git a/README.md b/README.md index 5017d3c..4e678e4 100644 --- a/README.md +++ b/README.md @@ -224,6 +224,7 @@ I'm currently working on [Analytics-Zoo](https://github.com/intel-analytics/anal | 1108 | [Defanging an IP Address](https://leetcode.com/problems/defanging-an-ip-address/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/1108_Defanging_an_IP_Address.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/1108_Defanging_an_IP_Address.java) | String manipulate (split, replace and join), O(n) and O(n) | | 1260 | [Shift 2D Grid](https://leetcode.com/problems/shift-2d-grid/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/1260_Shift_2D_Grid.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/1260_Shift_2D_Grid.java) | Final position of each element can be computed according to k, m and n, e.g., k == mn, then don't move, O(mn) and O(mn) | | 1290 | [Convert Binary Number in a Linked List to Integer](https://leetcode.com/problems/convert-binary-number-in-a-linked-list-to-integer/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/1290_Convert_Binary_Number_in_a_Linked_List_to_Integer.py) | Take 2 to the power digit position from right (starting from 0) and multiply it with the digit | +| 1323 | [Maximum 69 Number](https://leetcode.com/problems/maximum-69-number/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/1323_Maximum_69_Number.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/1323_Maximum_69_Number.java) | 9 is greater than 6, so change first 6 to 9 from left if exist, O(n) and O(1) | | 1337 | [The K Weakest Rows in a Matrix](https://leetcode.com/problems/the-k-weakest-rows-in-a-matrix/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/1337_The_K_Weakest_Rows_in_a_Matrix.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/1337_The_K_Weakest_Rows_in_a_Matrix.java) | Check by row, from left to right, until encount first zero, O(mn) and O(1) | | 1342 | [Number of Steps to Reduce a Number to Zero](https://leetcode.com/problems/number-of-steps-to-reduce-a-number-to-zero/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/1342_Number_of_Steps_to_Reduce_a_Number_to_Zero.py) | If number is divisible by 2, divide the number by 2, else subtract 1 from the number, and output the number of steps, O(logn) and O(1) | | 1365 | [How Many Numbers Are Smaller Than the Current Number](https://leetcode.com/problems/how-many-numbers-are-smaller-than-the-current-number/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/1365_How_Many_Numbers_Are_Smaller_Than_the_Current_Number.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/1365_How_Many_Numbers_Are_Smaller_Than_the_Current_Number.java) | 1. Sort and get position in sorted nums, O(nlogn) and O(n)
2. Fill count into 0-100, O(n) and O(1) | diff --git a/java/1323_Maximum_69_Number.java b/java/1323_Maximum_69_Number.java new file mode 100644 index 0000000..f3ce8c3 --- /dev/null +++ b/java/1323_Maximum_69_Number.java @@ -0,0 +1,19 @@ +class Solution { + public int maximum69Number (int num) { + // Replace first 6 with 9 if exists + return Integer.valueOf(String.valueOf(num).replaceFirst("6", "9")); + } + + /* + public int maximum69Number (int num) { + char[] chars = Integer.toString(num).toCharArray(); + // Replace first 6 with 9 if exists + for (int i = 0; i < chars.length; i++) { + if (chars[i] == '6') { + chars[i] = '9'; + break; + } + } + return Integer.parseInt(new String(chars)); + }*/ +} diff --git a/python/1323_Maximum_69_Number.py b/python/1323_Maximum_69_Number.py new file mode 100644 index 0000000..8cacceb --- /dev/null +++ b/python/1323_Maximum_69_Number.py @@ -0,0 +1,4 @@ +class Solution: + def maximum69Number (self, num: int) -> int: + # Replace first 6 with 9 if exists + return(str(num).replace('6', '9', 1)) diff --git a/python/1323_maximum_69_number b/python/1323_maximum_69_number deleted file mode 100644 index c755b0e..0000000 --- a/python/1323_maximum_69_number +++ /dev/null @@ -1,3 +0,0 @@ -class Solution: - def maximum69Number (self, num: int) -> int: - return(str(num).replace('6','9',1)) From 83a0bbd3e3f7cad588af2094dcd67daee418b297 Mon Sep 17 00:00:00 2001 From: Qiyuan Gong Date: Fri, 2 Oct 2020 22:21:49 +0800 Subject: [PATCH 059/119] Refine 011_Container_With_Most_Water --- .gitignore | 2 +- README.md | 1 + java/011_Container_With_Most_Water.java | 16 +++++++ java/011_containerwithmostwater.java | 20 --------- python/011_Container_With_Most_Water.py | 55 ++++++------------------- 5 files changed, 31 insertions(+), 63 deletions(-) create mode 100644 java/011_Container_With_Most_Water.java delete mode 100644 java/011_containerwithmostwater.java diff --git a/.gitignore b/.gitignore index a39d774..683d8b0 100644 --- a/.gitignore +++ b/.gitignore @@ -3,7 +3,7 @@ __pycache__/ *.py[cod] *$py.class .idea/ - +*.iml # C extensions *.so diff --git a/README.md b/README.md index 4e678e4..5a761f0 100644 --- a/README.md +++ b/README.md @@ -20,6 +20,7 @@ I'm currently working on [Analytics-Zoo](https://github.com/intel-analytics/anal | 7 | [Reverse Integer](https://leetcode.com/problems/reverse-integer/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/007_Reverse_Integer.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/007_Reverse_Integer.java) | Overflow when the result is greater than 2147483647 or less than -2147483648. | 8 | [String to Integer (atoi)](https://leetcode.com/problems/string-to-integer-atoi/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/008_String_to_Integer(atoi).py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/008_String_to_Integer(atoi).java) | Overflow, Space, and negative number | | 9 | [Palindrome Number](https://leetcode.com/problems/palindrome-number/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/009_Palindrome_Number.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/009_Palindrome_Number.java) | Get the len and check left and right with 10^len, 10 | +| 11 | [Container With Most Water](https://leetcode.com/problems/container-with-most-water/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/011_Container_With_Most_Water.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/011_Container_With_Most_Water.java) | 1. Brute Force, O(n^2) and O(1)
2. Two points, O(n) and O(1) | | 12 | [Integer to Roman](https://leetcode.com/problems/integer-to-roman/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/012_Integer_to_Roman.py) | [Background knowledge](http://www.rapidtables.com/convert/number/how-number-to-roman-numerals.htm) Just like 10-digit number, divide and minus | | 13 | [Roman to Integer](https://leetcode.com/problems/roman-to-integer/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/013_Roman_to_Integer.py) | Add all curr, if curr > prev, then need to subtract 2 * prev | | 15 | [3Sum](https://leetcode.com/problems/3sum/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/015_3Sum.py) | 1. Sort and O(n^2) search with three points
2. Multiple Two Sum (Problem 1) | diff --git a/java/011_Container_With_Most_Water.java b/java/011_Container_With_Most_Water.java new file mode 100644 index 0000000..c873867 --- /dev/null +++ b/java/011_Container_With_Most_Water.java @@ -0,0 +1,16 @@ +class Solution { + public int maxArea(int[] height) { + + int maxArea = 0; + int left = 0; + int right = height.length - 1; + + while (left < right) { + maxArea = Math.max(maxArea, (right - left) * Math.min(height[left], height[right])); + // Two points + if (height[left] < height[right]) left++; + else right--; + } + return maxArea; + } +} diff --git a/java/011_containerwithmostwater.java b/java/011_containerwithmostwater.java deleted file mode 100644 index 4b82cc0..0000000 --- a/java/011_containerwithmostwater.java +++ /dev/null @@ -1,20 +0,0 @@ -class Solution { - public int maxArea(int[] height) { - - int max=0; - int left=0; - int right=height.length-1; - - while(left height[right]: -# right -= 1 -# else: -# left += 1 -# return result - - def maxArea(self, height): - # skip some choices - ls = len(height) - lm = min(height[0], height[ls - 1]) - max_v = lm * (ls - 1) - low = 0 - high = ls - 1 - while low < high: - while height[low] < lm and low < ls: - low += 1 - while height[high] < lm and high < ls: - high -= 1 - if low > high: - break - m = min(height[low], height[high]) - if m * (high - low) > max_v: - max_v = m * (high - low) - lm = m - if height[low] < height[high]: - low += 1 +class Solution: + def maxArea(self, height: List[int]) -> int: + # Two points + left, right = 0, len(height) - 1 + result = 0 + while left < right: + result = max(min(height[left], height[right]) * (right - left), result) + if height[left] > height[right]: + # remove right + right -= 1 else: - high -= 1 - return max_v \ No newline at end of file + # remove left + left += 1 + return result From 1ca0f6e50f5733586bdb29168d21f3ef66fba59a Mon Sep 17 00:00:00 2001 From: diwansimranbanu <72291969+diwansimranbanu@users.noreply.github.com> Date: Sat, 3 Oct 2020 20:00:54 +0530 Subject: [PATCH 060/119] Add 728_Self_Dividing_Numbers.java (#24) Added 728_Self_Dividing_Numbers Java Solution by @diwansimranbanu --- java/728_Self_Dividing_Numbers.java | 35 +++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 java/728_Self_Dividing_Numbers.java diff --git a/java/728_Self_Dividing_Numbers.java b/java/728_Self_Dividing_Numbers.java new file mode 100644 index 0000000..d9cf8eb --- /dev/null +++ b/java/728_Self_Dividing_Numbers.java @@ -0,0 +1,35 @@ +class Solution { + public List selfDividingNumbers(int left, int right) + { + LinkedList list = new LinkedList(); + for(int i = left; i <= right; i++) + { + if(isSelfDiving(i)) + list.add(i); + } + return list; + } + + public boolean isSelfDiving(int num) + { + int digit = num % 10; + int temp = num; + boolean isTrue = true; + while(temp != 0) + { + if(digit == 0 || num % digit != 0) + { + isTrue = false; + break; + } + else + { + temp /= 10; + digit = temp%10; + } + } + return isTrue; + + } + +} From 1c8b68332c8903a6add8fe4555daa8d16ecd2073 Mon Sep 17 00:00:00 2001 From: diwansimranbanu <72291969+diwansimranbanu@users.noreply.github.com> Date: Sat, 3 Oct 2020 20:03:11 +0530 Subject: [PATCH 061/119] Add 868_Binary_Gap.py (#23) Added 868_Binary_Gap Python solution, by @diwansimranbanu --- python/868_Binary_Gap.py | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 python/868_Binary_Gap.py diff --git a/python/868_Binary_Gap.py b/python/868_Binary_Gap.py new file mode 100644 index 0000000..0c4f0d7 --- /dev/null +++ b/python/868_Binary_Gap.py @@ -0,0 +1,14 @@ +class Solution: + def binaryGap(self, n: int) -> int: + current= 1 + last1 = -1 + out = 0 + while n > 0: + if n%2 == 1: + if last1 >= 1: + out = max(out, current - last1) + last1 = current + current += 1 + n = n//2 + return(out) + From 257bda525f490f1717e8abdaf3e4bf32832c8e8d Mon Sep 17 00:00:00 2001 From: Qiyuan Gong Date: Sat, 3 Oct 2020 22:56:06 +0800 Subject: [PATCH 062/119] Add 728 link --- README.md | 1 + java/728_Self_Dividing_Numbers.java | 24 ++++++++---------------- python/728_Self_Dividing_Numbers.py | 7 +++++++ 3 files changed, 16 insertions(+), 16 deletions(-) create mode 100644 python/728_Self_Dividing_Numbers.py diff --git a/README.md b/README.md index 5a761f0..b5c822d 100644 --- a/README.md +++ b/README.md @@ -189,6 +189,7 @@ I'm currently working on [Analytics-Zoo](https://github.com/intel-analytics/anal | 717 | [1-bit and 2-bit Characters](https://leetcode.com/problems/1-bit-and-2-bit-characters/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/717_1-bit_and_2-bit_Characters.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/717_1-bit_and_2-bit_Characters.java) | 1. Go through bits, 1 skip next, O(n) and O(1)
2. Find second last zero reversely, O(n) and O(1) | | 720 | [Longest Word in Dictionary](https://leetcode.com/problems/longest-word-in-dictionary/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/720_Longest_Word_in_Dictionary.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/720_Longest_Word_in_Dictionary.java) | 1. Brute Force, O(sum(w^2)) and O(w)
2. Tire Tree, O(sum(w) and O(w))
3. Sort and word without last char, O(nlogn + sum(w)) and O(w) | | 724 | [Find Pivot Index](https://leetcode.com/problems/find-pivot-index/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/724_Find_Pivot_Index.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/724_Find_Pivot_Index.java) | Seach the array to find a place where left sum is equal to right sum, O(n) and O(1) | +| 728 | [Self Dividing Numbers](https://leetcode.com/problems/self-dividing-numbers/solution/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/728_Self_Dividing_Numbers.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/728_Self_Dividing_Numbers.java) | Brute Force check every digit, O(nlogD) and O(1) | | 733 | [Flood Fill](https://leetcode.com/problems/flood-fill/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/733_Flood_Fill.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/733_Flood_Fill.java) | 1. DFS with stack or recursive, O(n) and O(n)
2. BFS with queue, O(n) and O(n) | | 743 | [Network Delay Time](https://leetcode.com/problems/network-delay-time/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/743_Network_Delay_Time.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/743_Network_Delay_Time.java) | Let V == N, then: 1. DFS, O(V^V+ElgE), O(V+E)
2. Dijkstra, O(V^2+E), O(V+E)| | 751 | [IP to CIDR](https://leetcode.com/problems/ip-to-cidr/) ♥ | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/751_IP_to_CIDR.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/751_IP_to_CIDR.java) | Bit manipulations, incrementail is 1 << (32 - mask) | diff --git a/java/728_Self_Dividing_Numbers.java b/java/728_Self_Dividing_Numbers.java index d9cf8eb..eeb12af 100644 --- a/java/728_Self_Dividing_Numbers.java +++ b/java/728_Self_Dividing_Numbers.java @@ -1,35 +1,27 @@ class Solution { - public List selfDividingNumbers(int left, int right) - { + public List selfDividingNumbers(int left, int right) { LinkedList list = new LinkedList(); - for(int i = left; i <= right; i++) - { + for(int i = left; i <= right; i++) { if(isSelfDiving(i)) list.add(i); } return list; } - public boolean isSelfDiving(int num) - { + public boolean isSelfDiving(int num) { int digit = num % 10; int temp = num; boolean isTrue = true; - while(temp != 0) - { - if(digit == 0 || num % digit != 0) - { + while(temp != 0) { + // 0 is special + if(digit == 0 || num % digit != 0) { isTrue = false; break; - } - else - { + } else { temp /= 10; - digit = temp%10; + digit = temp % 10; } } return isTrue; - } - } diff --git a/python/728_Self_Dividing_Numbers.py b/python/728_Self_Dividing_Numbers.py new file mode 100644 index 0000000..f7e0bac --- /dev/null +++ b/python/728_Self_Dividing_Numbers.py @@ -0,0 +1,7 @@ +class Solution: + def selfDividingNumbers(self, left: int, right: int) -> List[int]: + # check every digit + return [x for x in range(left, right+1) if all([int(i) != 0 and x % int(i)==0 for i in str(x)])] + + # def selfDividingNumbers(self, left: int, right: int) -> List[int]: + # return [x for x in range(left, right+1) if all((i and (x % i==0) for i in map(int, str(x))))] From 417ccfd22cc7c1f661e7a8c82e3567da6bf2441b Mon Sep 17 00:00:00 2001 From: Qiyuan Gong Date: Sat, 3 Oct 2020 23:34:32 +0800 Subject: [PATCH 063/119] Refine 868 and add link --- README.md | 1 + java/868_Binary_Gap.java | 27 +++++++++++++++++++++++++++ python/868_Binary_Gap.py | 30 +++++++++++++++++++++++++----- 3 files changed, 53 insertions(+), 5 deletions(-) create mode 100644 java/868_Binary_Gap.java diff --git a/README.md b/README.md index b5c822d..2f18788 100644 --- a/README.md +++ b/README.md @@ -205,6 +205,7 @@ I'm currently working on [Analytics-Zoo](https://github.com/intel-analytics/anal | 844 | [Backspace String Compare](https://leetcode.com/problems/backspace-string-compare/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/844_Backspace_String_Compare.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/844_Backspace_String_Compare.java) | 1. Stack pop when encounters #, O(n) and O(n)
2. Compare string from end to start, O(n) and O(1) | | 852 | [Peak Index in a Mountain Array](https://leetcode.com/problems/peak-index-in-a-mountain-array/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/852_Peak_Index_in_a_Mountain_Array.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/852_Peak_Index_in_a_Mountain_Array.java) | 1. Scan the array until encountering decline, O(n) and O(1)
2. Binary seach with additional check for [i + 1], O(logn) and O(1) | | 867 | [Transpose Matrix](https://leetcode.com/problems/transpose-matrix/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/867_Transpose_Matrix.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/867_Transpose_Matrix.java) | Res[i][j] = A[j][i] | +| 868 | [Binary Gap](https://leetcode.com/problems/binary-gap/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/868_Binary_Gap.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/868_Binary_Gap.java) | 1. Store index and check, O(logn) and O(logn)
2. One pass and store max, O(logn) and O(1) | | 872 | [Leaf-Similar Trees](https://leetcode.com/problems/leaf-similar-trees/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/872_Leaf-Similar_Trees.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/872_Leaf-Similar_Trees.java) | DFS (stack or recursion) get leaf value sequence and compare, O(n) and O(n) | | 876 | [Middle of the Linked List](https://leetcode.com/problems/middle-of-the-linked-list/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/876_Middle_of_the_Linked_List.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/876_Middle_of_the_Linked_List.java) | 1. Copy to array, O(n) and O(n)
2. Fast and slow point, where fast point is 2 times faster than slow point, O(n) and O(1) | | 904 | [Fruit Into Baskets](https://leetcode.com/problems/fruit-into-baskets/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/904_Fruit_Into_Baskets.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/904_Fruit_Into_Baskets.java) | 1. Scan through blocks of tree, O(n) and O(n)
2. Mainten a sliding window with start and curr point, O(n) and O(n). | diff --git a/java/868_Binary_Gap.java b/java/868_Binary_Gap.java new file mode 100644 index 0000000..9d54364 --- /dev/null +++ b/java/868_Binary_Gap.java @@ -0,0 +1,27 @@ +class Solution { + /*public int binaryGap(int n) { + // Store Indexes + int[] A = new int[32]; + int t = 0; + for (int i = 0; i < 32; ++i) + if (((N >> i) & 1) != 0) + A[t++] = i; + + int ans = 0; + for (int i = 0; i < t - 1; ++i) + ans = Math.max(ans, A[i+1] - A[i]); + return ans; + }*/ + + public int binaryGap(int N) { + int last = -1, ans = 0; + for (int i = 0; i < 32; ++i) + if (((N >> i) & 1) > 0) { + // Store max + if (last >= 0) + ans = Math.max(ans, i - last); + last = i; + } + return ans; + } +} diff --git a/python/868_Binary_Gap.py b/python/868_Binary_Gap.py index 0c4f0d7..191d3d1 100644 --- a/python/868_Binary_Gap.py +++ b/python/868_Binary_Gap.py @@ -1,14 +1,34 @@ class Solution: + + # def binaryGap(self, n: int) -> int: + # # Store index + # A = [i for i in xrange(32) if (N >> i) & 1] + # if len(A) < 2: return 0 + # return max(A[i+1] - A[i] for i in xrange(len(A) - 1)) + + def binaryGap(self, n: int) -> int: - current= 1 + # one pass and store max + current = 1 last1 = -1 out = 0 while n > 0: - if n%2 == 1: + if n % 2 == 1: if last1 >= 1: out = max(out, current - last1) last1 = current current += 1 - n = n//2 - return(out) - + n = n // 2 + return out + + # def binaryGap(self, n: int) -> int: + # # one pass and store max + # res = 0 + # last = -1 + # # Get binary encoding with bin + # for i, curr in enumerate(bin(n)[2:]): + # if curr == '1': + # if last >= 0: + # res = max(res, i - last) + # last = i + # return res From 1692022faf4245b544499062c7de41d80fe89861 Mon Sep 17 00:00:00 2001 From: ruchit2801 <39343253+ruchit2801@users.noreply.github.com> Date: Mon, 5 Oct 2020 21:07:12 +0530 Subject: [PATCH 064/119] Add 1310_XOR_Queries_of_a_Subarray (#22) * Add 206_Reverse_Linked_List CPP solution * Add 1310_XOR_Queries_of_a_Subarray Python Solution by @ruchit2801 --- cpp/206_Reverse_Linked_List.cpp | 26 ++++++++++++++++++++++++ python/1310_XOR_Queries_of_a_Subarray.py | 10 +++++++++ 2 files changed, 36 insertions(+) create mode 100644 cpp/206_Reverse_Linked_List.cpp create mode 100644 python/1310_XOR_Queries_of_a_Subarray.py diff --git a/cpp/206_Reverse_Linked_List.cpp b/cpp/206_Reverse_Linked_List.cpp new file mode 100644 index 0000000..56aefc2 --- /dev/null +++ b/cpp/206_Reverse_Linked_List.cpp @@ -0,0 +1,26 @@ +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode(int x) : val(x), next(NULL) {} + * }; + */ +class Solution { +public: + ListNode* reverseList(ListNode* head) { + if(head==NULL)return NULL; + if(head->next==NULL) return head; + ListNode* p=head; + ListNode* c=head->next; + head->next=NULL; + while(c->next){ + ListNode* n = c->next; + c->next=p; + p=c; + c=n; + } + c->next=p; + return c; + } +}; diff --git a/python/1310_XOR_Queries_of_a_Subarray.py b/python/1310_XOR_Queries_of_a_Subarray.py new file mode 100644 index 0000000..3f1d1fb --- /dev/null +++ b/python/1310_XOR_Queries_of_a_Subarray.py @@ -0,0 +1,10 @@ +class Solution: + def xorQueries(self, arr: List[int], queries: List[List[int]]) -> List[int]: + pref = [0] + for e in arr: + pref.append(e ^ pref[-1]) + ans = [] + for [l, r] in queries: + ans.append(pref[r+1] ^ pref[l]) + return ans + From f8a6d7656212440abd8943df0437d1f080d514f4 Mon Sep 17 00:00:00 2001 From: ruchit2801 <39343253+ruchit2801@users.noreply.github.com> Date: Mon, 5 Oct 2020 21:09:30 +0530 Subject: [PATCH 065/119] Add 668_Kth_Smallest_Number_in_Multiplication_Table (#21) * Add 668_Kth_Smallest_Number_in_Multiplication_Table CPP solution, by @ruchit2801 --- ...mallest_Number_in_Multiplication_Table.cpp | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 cpp/668_Kth_Smallest_Number_in_Multiplication_Table.cpp diff --git a/cpp/668_Kth_Smallest_Number_in_Multiplication_Table.cpp b/cpp/668_Kth_Smallest_Number_in_Multiplication_Table.cpp new file mode 100644 index 0000000..1b8e6ab --- /dev/null +++ b/cpp/668_Kth_Smallest_Number_in_Multiplication_Table.cpp @@ -0,0 +1,28 @@ +class Solution { +public: + #define ll long long int + + bool valid(ll x, int m, int n, int k){ + int cnt=0; + for(int i=1;i<=m;i++){ + cnt+=n=k; + } + + int findKthNumber(int n1, int n2, int k) { + ll l=0, r=n1*n2,ans; + while(l<=r){ + ll m = l +(r-l)/2; + if(valid(m,n1,n2,k)){ + ans=m; + r=m-1; + } + else{ + l=m+1; + } + } + return ans; + } +}; From 6699908944916c29a7edd73cbe406d1e3c2b1a85 Mon Sep 17 00:00:00 2001 From: ruchit2801 <39343253+ruchit2801@users.noreply.github.com> Date: Tue, 6 Oct 2020 17:33:57 +0530 Subject: [PATCH 066/119] Add 412_Fizz_Buzz (#20) * Add 412_Fizz_Buzz CPP solution, by @ruchit2801 --- cpp/412_Fizz_Buzz.cpp | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 cpp/412_Fizz_Buzz.cpp diff --git a/cpp/412_Fizz_Buzz.cpp b/cpp/412_Fizz_Buzz.cpp new file mode 100644 index 0000000..7bbee33 --- /dev/null +++ b/cpp/412_Fizz_Buzz.cpp @@ -0,0 +1,15 @@ +#define pb push_back +class Solution { +public: + vector fizzBuzz(int n) { + int i; + vector s; + for(i=0;i Date: Tue, 6 Oct 2020 20:07:31 +0800 Subject: [PATCH 067/119] 009_Palindrome_Number Python 3 Support (#26) * Upgrade 009_Palindrome_Number.py for Python 3 support, by @peterhuang1kimo --- python/009_Palindrome_Number.py | 16 +++++----------- 1 file changed, 5 insertions(+), 11 deletions(-) diff --git a/python/009_Palindrome_Number.py b/python/009_Palindrome_Number.py index b18b89d..af6890f 100644 --- a/python/009_Palindrome_Number.py +++ b/python/009_Palindrome_Number.py @@ -9,23 +9,17 @@ class Solution(object): def isPalindrome(self, x): if x < 0: return False - ls = 0 + ls = len(str(x)) tmp = x - while tmp != 0: - ls += 1 - tmp = tmp // 10 - tmp = x - for i in range(ls/2): - right = tmp % 10 + for i in range(int(ls/2)): + right = int(tmp % 10) left = tmp / (10 ** (ls - 2 * i - 1)) - left = left % 10 - # print left, right + left = int(left % 10) if left != right: return False tmp = tmp // 10 return True - # def isPalindrome(self, x): # #leetcode book # if x < 0: @@ -62,4 +56,4 @@ def isPalindrome(self, x): if __name__ == '__main__': # begin s = Solution() - print s.isPalindrome(1001) \ No newline at end of file + print s.isPalindrome(1001) From 29c53b5cc09b19a7ef1d51396ecf3d7637989692 Mon Sep 17 00:00:00 2001 From: peterhuang1kimo Date: Tue, 6 Oct 2020 20:10:09 +0800 Subject: [PATCH 068/119] 035_Search_Insert_Position Python 3 Support (#27) * Update 035_Search_Insert_Position.py for Python 3 support, by @peterhuang1kimo --- python/035_Search_Insert_Position.py | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/python/035_Search_Insert_Position.py b/python/035_Search_Insert_Position.py index d1a8681..9e6abd0 100644 --- a/python/035_Search_Insert_Position.py +++ b/python/035_Search_Insert_Position.py @@ -23,13 +23,21 @@ class Solution: # return pos def searchInsert(self, nums, target): - l, r = 0, len(nums) - 1 + l, r = int(0), len(nums) - 1 while l < r: - mid = (l + r) / 2 + mid = int((l + r) / 2) if nums[mid] < target: l = mid + 1 else: r = mid if nums[l] < target: return l + 1 - return l + return l + + + +if __name__ == '__main__': + # begin + s = Solution() + print (s.searchInsert([1,3,5,6],5)) + From 772205f49a84c45cf9d9d784397f979e1e7379a7 Mon Sep 17 00:00:00 2001 From: arun-aditya <42905401+arun-aditya@users.noreply.github.com> Date: Tue, 6 Oct 2020 19:03:23 +0530 Subject: [PATCH 069/119] Update 009_Palindrome_Number.java (#14) * Added a simpler and easy to understand code in java, by @arun-aditya --- java/009_Palindrome_Number.java | 24 +++++++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/java/009_Palindrome_Number.java b/java/009_Palindrome_Number.java index 1dc03ae..0d3150c 100644 --- a/java/009_Palindrome_Number.java +++ b/java/009_Palindrome_Number.java @@ -38,4 +38,26 @@ public boolean isPalindrome(int x) { } return true; } -} \ No newline at end of file +} + +// simpler code + +class Solution { + public boolean isPalindrome(int x) { + int r,s=0,number=x; + if(number<0){ + return false; + } + while (number!=0){ + r=number%10; + s= s*10 +r; + number/=10; + } + if (s==x){ + return true; + } + else { + return false; + } + } +} From b1d74a51fa18e7789e6e21dc5ad8e7fbe1bc9824 Mon Sep 17 00:00:00 2001 From: Mansi Mehndiratta Date: Tue, 6 Oct 2020 19:07:40 +0530 Subject: [PATCH 070/119] Add 1304_Find_N_Unique_Integers_Sum_up_to_Zero (#16) * Add 1304_Find_N_Unique_Integers_Sum_up_to_Zero Python Solution, by @Mansi2814 --- python/1304_Find_N_Unique_Integers_Sum_up_to_Zero | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 python/1304_Find_N_Unique_Integers_Sum_up_to_Zero diff --git a/python/1304_Find_N_Unique_Integers_Sum_up_to_Zero b/python/1304_Find_N_Unique_Integers_Sum_up_to_Zero new file mode 100644 index 0000000..141ecaa --- /dev/null +++ b/python/1304_Find_N_Unique_Integers_Sum_up_to_Zero @@ -0,0 +1,11 @@ +class Solution: + def sumZero(self, n: int) -> List[int]: + sum = 0 + list = [] + + for i in range(1,n): + list.append(i) + sum = sum +i + list.append(-sum) + return list + From a99c1d0b4aa6f95dd82d51e8b2dc570bf6972419 Mon Sep 17 00:00:00 2001 From: Qiyuan Gong Date: Tue, 6 Oct 2020 21:58:22 +0800 Subject: [PATCH 071/119] Refine 1304_Find_N_Unique_Integers_Sum_up_to_Zero --- README.md | 1 + ...4_Find_N_Unique_Integers_Sum_up_to_Zero.java | 9 +++++++++ .../1304_Find_N_Unique_Integers_Sum_up_to_Zero | 11 ----------- ...304_Find_N_Unique_Integers_Sum_up_to_Zero.py | 17 +++++++++++++++++ 4 files changed, 27 insertions(+), 11 deletions(-) create mode 100644 java/1304_Find_N_Unique_Integers_Sum_up_to_Zero.java delete mode 100644 python/1304_Find_N_Unique_Integers_Sum_up_to_Zero create mode 100644 python/1304_Find_N_Unique_Integers_Sum_up_to_Zero.py diff --git a/README.md b/README.md index 2f18788..7febeaf 100644 --- a/README.md +++ b/README.md @@ -227,6 +227,7 @@ I'm currently working on [Analytics-Zoo](https://github.com/intel-analytics/anal | 1108 | [Defanging an IP Address](https://leetcode.com/problems/defanging-an-ip-address/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/1108_Defanging_an_IP_Address.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/1108_Defanging_an_IP_Address.java) | String manipulate (split, replace and join), O(n) and O(n) | | 1260 | [Shift 2D Grid](https://leetcode.com/problems/shift-2d-grid/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/1260_Shift_2D_Grid.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/1260_Shift_2D_Grid.java) | Final position of each element can be computed according to k, m and n, e.g., k == mn, then don't move, O(mn) and O(mn) | | 1290 | [Convert Binary Number in a Linked List to Integer](https://leetcode.com/problems/convert-binary-number-in-a-linked-list-to-integer/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/1290_Convert_Binary_Number_in_a_Linked_List_to_Integer.py) | Take 2 to the power digit position from right (starting from 0) and multiply it with the digit | +| 1304 | [Find N Unique Integers Sum up to Zero](https://leetcode.com/problems/find-n-unique-integers-sum-up-to-zero/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/1304_Find_N_Unique_Integers_Sum_up_to_Zero.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/1304_Find_N_Unique_Integers_Sum_up_to_Zero.java) | [1,n-1] and its negative sum | | 1323 | [Maximum 69 Number](https://leetcode.com/problems/maximum-69-number/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/1323_Maximum_69_Number.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/1323_Maximum_69_Number.java) | 9 is greater than 6, so change first 6 to 9 from left if exist, O(n) and O(1) | | 1337 | [The K Weakest Rows in a Matrix](https://leetcode.com/problems/the-k-weakest-rows-in-a-matrix/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/1337_The_K_Weakest_Rows_in_a_Matrix.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/1337_The_K_Weakest_Rows_in_a_Matrix.java) | Check by row, from left to right, until encount first zero, O(mn) and O(1) | | 1342 | [Number of Steps to Reduce a Number to Zero](https://leetcode.com/problems/number-of-steps-to-reduce-a-number-to-zero/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/1342_Number_of_Steps_to_Reduce_a_Number_to_Zero.py) | If number is divisible by 2, divide the number by 2, else subtract 1 from the number, and output the number of steps, O(logn) and O(1) | diff --git a/java/1304_Find_N_Unique_Integers_Sum_up_to_Zero.java b/java/1304_Find_N_Unique_Integers_Sum_up_to_Zero.java new file mode 100644 index 0000000..8847ff1 --- /dev/null +++ b/java/1304_Find_N_Unique_Integers_Sum_up_to_Zero.java @@ -0,0 +1,9 @@ +public int[] sumZero(int n) { + int[] res = new int[n]; + // place negative sum(from 1 to n-1) in 0 + for (int i = 1; i < n; i++) { + res[i] = i; + res[0] -= i; + } + return res; +} diff --git a/python/1304_Find_N_Unique_Integers_Sum_up_to_Zero b/python/1304_Find_N_Unique_Integers_Sum_up_to_Zero deleted file mode 100644 index 141ecaa..0000000 --- a/python/1304_Find_N_Unique_Integers_Sum_up_to_Zero +++ /dev/null @@ -1,11 +0,0 @@ -class Solution: - def sumZero(self, n: int) -> List[int]: - sum = 0 - list = [] - - for i in range(1,n): - list.append(i) - sum = sum +i - list.append(-sum) - return list - diff --git a/python/1304_Find_N_Unique_Integers_Sum_up_to_Zero.py b/python/1304_Find_N_Unique_Integers_Sum_up_to_Zero.py new file mode 100644 index 0000000..8cad4d6 --- /dev/null +++ b/python/1304_Find_N_Unique_Integers_Sum_up_to_Zero.py @@ -0,0 +1,17 @@ +class Solution: + def sumZero(self, n: int) -> List[int]: + prefix_sum = 0 + res = [] + # 1, n-1 + for i in range(1, n): + res.append(i) + prefix_sum = prefix_sum + i + # sum(from 1 to n-1) + res.append(-prefix_sum) + return res + + # def sumZero(self, n: int) -> List[int]: + # # 1,n-1 + # prefix = list(range(1, n)) + # # sum(from 1 to n-1) + # return prefix + [-sum(prefix)] From b5166888c26873d230193a97d5ca39daf4c3212b Mon Sep 17 00:00:00 2001 From: Qiyuan Gong Date: Wed, 7 Oct 2020 23:43:37 +0800 Subject: [PATCH 072/119] Refine 012_Integer_to_Roman --- README.md | 2 +- java/012_Integer_to_Roman.java | 23 +++++++++++++++++++++++ java/012_integertoroman.java | 21 --------------------- 3 files changed, 24 insertions(+), 22 deletions(-) create mode 100644 java/012_Integer_to_Roman.java delete mode 100644 java/012_integertoroman.java diff --git a/README.md b/README.md index 7febeaf..edf614c 100644 --- a/README.md +++ b/README.md @@ -21,7 +21,7 @@ I'm currently working on [Analytics-Zoo](https://github.com/intel-analytics/anal | 8 | [String to Integer (atoi)](https://leetcode.com/problems/string-to-integer-atoi/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/008_String_to_Integer(atoi).py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/008_String_to_Integer(atoi).java) | Overflow, Space, and negative number | | 9 | [Palindrome Number](https://leetcode.com/problems/palindrome-number/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/009_Palindrome_Number.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/009_Palindrome_Number.java) | Get the len and check left and right with 10^len, 10 | | 11 | [Container With Most Water](https://leetcode.com/problems/container-with-most-water/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/011_Container_With_Most_Water.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/011_Container_With_Most_Water.java) | 1. Brute Force, O(n^2) and O(1)
2. Two points, O(n) and O(1) | -| 12 | [Integer to Roman](https://leetcode.com/problems/integer-to-roman/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/012_Integer_to_Roman.py) | [Background knowledge](http://www.rapidtables.com/convert/number/how-number-to-roman-numerals.htm) Just like 10-digit number, divide and minus | +| 12 | [Integer to Roman](https://leetcode.com/problems/integer-to-roman/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/012_Integer_to_Roman.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/012_Integer_to_Roman.java) | [Background knowledge](http://www.rapidtables.com/convert/number/how-number-to-roman-numerals.htm) Just like 10-digit number, divide and minus | | 13 | [Roman to Integer](https://leetcode.com/problems/roman-to-integer/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/013_Roman_to_Integer.py) | Add all curr, if curr > prev, then need to subtract 2 * prev | | 15 | [3Sum](https://leetcode.com/problems/3sum/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/015_3Sum.py) | 1. Sort and O(n^2) search with three points
2. Multiple Two Sum (Problem 1) | | 16 | [3Sum Closest](https://leetcode.com/problems/3sum-closest/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/016_3Sum_Closest.py) | Sort and Multiple Two Sum check abs| diff --git a/java/012_Integer_to_Roman.java b/java/012_Integer_to_Roman.java new file mode 100644 index 0000000..8683029 --- /dev/null +++ b/java/012_Integer_to_Roman.java @@ -0,0 +1,23 @@ +class Solution { + public String intToRoman(int num) { + Map map = new HashMap(); + map.put(1, "I"); map.put(5, "V"); map.put(10, "X"); + map.put(50, "L"); map.put(100, "C"); map.put(500, "D"); map.put(1000, "M"); + map.put(4, "IV"); map.put(9, "IX"); map.put(40, "XL"); map.put(90, "XC"); + map.put(400, "CD"); map.put(900, "CM"); + + int[] sequence = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1}; + + StringBuffer sb = new StringBuffer(); + for (int i = 0; i= base) { + sb.append(map.get(base)); + num -= base; + } + } + + return sb.toString(); + } +} diff --git a/java/012_integertoroman.java b/java/012_integertoroman.java deleted file mode 100644 index cb7a777..0000000 --- a/java/012_integertoroman.java +++ /dev/null @@ -1,21 +0,0 @@ -public String intToRoman(int num) { - Map map = new HashMap(); - map.put(1, "I"); map.put(5, "V"); map.put(10, "X"); - map.put(50, "L"); map.put(100, "C"); map.put(500, "D"); map.put(1000, "M"); - map.put(4, "IV"); map.put(9, "IX"); map.put(40, "XL"); map.put(90, "XC"); - map.put(400, "CD"); map.put(900, "CM"); - - int[] sequence = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1}; - - StringBuffer sb = new StringBuffer(); - for (int i=0; i= base) { - sb.append(map.get(base)); - num -= base; - } - } - - return sb.toString(); -} From 7ffaa0dff9dcb5eec9caa5462cc13317a0514aa2 Mon Sep 17 00:00:00 2001 From: Qiyuan Gong Date: Wed, 7 Oct 2020 23:59:23 +0800 Subject: [PATCH 073/119] Refine 206_Reverse_Linked_List --- README.md | 2 +- cpp/206_Reverse_Linked_List.cpp | 30 +++++++++++++----------- java/206_Reverse_Linked_List.java | 38 +++++++++++++++++++++++++++++++ 3 files changed, 56 insertions(+), 14 deletions(-) create mode 100644 java/206_Reverse_Linked_List.java diff --git a/README.md b/README.md index edf614c..f164996 100644 --- a/README.md +++ b/README.md @@ -85,7 +85,7 @@ I'm currently working on [Analytics-Zoo](https://github.com/intel-analytics/anal | 198 | [House Robber](https://leetcode.com/problems/house-robber/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/198_House_Robber.py) | f(k) = max(f(k – 2) + num[k], f(k – 1)), O(n) and O(1) | | 200 | [Number of Islands](https://leetcode.com/problems/number-of-islands/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/200_Number_of_Islands.py) | 1. Quick union find, O(nlogn) and O(n^2)
2. BFS with marks, O(n^2) and O(1) | | 204 | [Count Primes](https://leetcode.com/problems/count-primes/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/204_Count_Primes.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/204_Count_Primes.java) [CPP](https://github.com/qiyuangong/leetcode/blob/master/cpp/204_Count_Primes.cpp) | [Sieve of Eratosthenes](https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes#Algorithm_complexity), O(nloglogn) and O(n) | -| 206 | [Reverse Linked List](https://leetcode.com/problems/reverse-linked-list/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/206_Reverse_Linked_List.py) | 1. Stack, O(n) and O(n)
2. Traverse on prev and curr, then curr.next = prev, O(n) and O(1)
3. Recursion, O(n) and O(1) | +| 206 | [Reverse Linked List](https://leetcode.com/problems/reverse-linked-list/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/206_Reverse_Linked_List.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/206_Reverse_Linked_List.java) [CPP](https://github.com/qiyuangong/leetcode/blob/master/cpp/206_Reverse_Linked_List.cpp) | 1. Stack, O(n) and O(n)
2. Traverse on prev and curr, then curr.next = prev, O(n) and O(1)
3. Recursion, O(n) and O(1) | | 213 | [House Robber II](https://leetcode.com/problems/house-robber-ii/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/213_House_Robber_II.py) | f(k) = max(f(k – 2) + num[k], max(dp[0~ls-2],dp[1~ls-1], O(n) and O(1)| | 215 | [Kth Largest Element in an Array](https://leetcode.com/problems/kth-largest-element-in-an-array/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/215_Kth_Largest_Element_in_an_Array.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/215_Kth_Largest_Element_in_an_Array.java) | 1. Sort, O(n) and O(n)
2. Heap, O(nlgk) and O(n)
3. Quick selection, O(klgn) and O(n)| | 216 | [Combination Sum III](https://leetcode.com/problems/combination-sum-iii/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/216_Combination_Sum_III.py) | Generate all combinations of length k and keep those that sum to n| diff --git a/cpp/206_Reverse_Linked_List.cpp b/cpp/206_Reverse_Linked_List.cpp index 56aefc2..84bf495 100644 --- a/cpp/206_Reverse_Linked_List.cpp +++ b/cpp/206_Reverse_Linked_List.cpp @@ -8,19 +8,23 @@ */ class Solution { public: - ListNode* reverseList(ListNode* head) { - if(head==NULL)return NULL; - if(head->next==NULL) return head; - ListNode* p=head; - ListNode* c=head->next; - head->next=NULL; - while(c->next){ - ListNode* n = c->next; - c->next=p; - p=c; - c=n; + ListNode *reverseList(ListNode *head) { + if (head == NULL) + return NULL; + if (head->next == NULL) + return head; + // Previous pointer + ListNode *previous = head; + // Current pointer + ListNode *curr = head->next; + head->next = NULL; + while (curr->next) { + ListNode *next = curr->next; + curr->next = previous; + previous = curr; + curr = next; } - c->next=p; - return c; + curr->next = previous; + return curr; } }; diff --git a/java/206_Reverse_Linked_List.java b/java/206_Reverse_Linked_List.java new file mode 100644 index 0000000..6f477b3 --- /dev/null +++ b/java/206_Reverse_Linked_List.java @@ -0,0 +1,38 @@ +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode() {} + * ListNode(int val) { this.val = val; } + * ListNode(int val, ListNode next) { this.val = val; this.next = next; } + * } + */ +class Solution { + // https://leetcode.com/problems/reverse-linked-list/discuss/58125/In-place-iterative-and-recursive-Java-solution + public ListNode reverseList(ListNode head) { + // Iterative solution + ListNode newHead = null; + while (head != null) { + ListNode next = head.next; + head.next = newHead; + newHead = head; + head = next; + } + return newHead; + } + + // Recursive + /* + public ListNode reverseList(ListNode head) { + return reverseListInt(head, null); + } + + private ListNode reverseListInt(ListNode head, ListNode newHead) { + if (head == null) + return newHead; + ListNode next = head.next; + head.next = newHead; + return reverseListInt(next, head); + }*/ +} From 7e0d4d5939f0e5be493a97d39716878c3cdf1fae Mon Sep 17 00:00:00 2001 From: Qiyuan Gong Date: Thu, 8 Oct 2020 09:53:52 +0800 Subject: [PATCH 074/119] Refine 1310_XOR_Queries_of_a_Subarray --- README.md | 1 + cpp/1310_XOR_Queries_of_a_Subarray.cpp | 12 ++++++++++++ java/1310_XOR_Queries_of_a_Subarray.java | 14 ++++++++++++++ python/1310_XOR_Queries_of_a_Subarray.py | 8 +++++++- 4 files changed, 34 insertions(+), 1 deletion(-) create mode 100644 cpp/1310_XOR_Queries_of_a_Subarray.cpp create mode 100644 java/1310_XOR_Queries_of_a_Subarray.java diff --git a/README.md b/README.md index f164996..7c27167 100644 --- a/README.md +++ b/README.md @@ -228,6 +228,7 @@ I'm currently working on [Analytics-Zoo](https://github.com/intel-analytics/anal | 1260 | [Shift 2D Grid](https://leetcode.com/problems/shift-2d-grid/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/1260_Shift_2D_Grid.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/1260_Shift_2D_Grid.java) | Final position of each element can be computed according to k, m and n, e.g., k == mn, then don't move, O(mn) and O(mn) | | 1290 | [Convert Binary Number in a Linked List to Integer](https://leetcode.com/problems/convert-binary-number-in-a-linked-list-to-integer/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/1290_Convert_Binary_Number_in_a_Linked_List_to_Integer.py) | Take 2 to the power digit position from right (starting from 0) and multiply it with the digit | | 1304 | [Find N Unique Integers Sum up to Zero](https://leetcode.com/problems/find-n-unique-integers-sum-up-to-zero/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/1304_Find_N_Unique_Integers_Sum_up_to_Zero.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/1304_Find_N_Unique_Integers_Sum_up_to_Zero.java) | [1,n-1] and its negative sum | +| 1310 | [XOR Queries of a Subarray](https://leetcode.com/problems/xor-queries-of-a-subarray) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/1310_XOR_Queries_of_a_Subarray.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/1310_XOR_Queries_of_a_Subarray.java) [Cpp](https://github.com/qiyuangong/leetcode/blob/master/cpp/1310_XOR_Queries_of_a_Subarray.cpp) | Compute accumulated xor from head, qeury result equals to xor[0, l] xor x[0, r], O(n) and O(n) | | 1323 | [Maximum 69 Number](https://leetcode.com/problems/maximum-69-number/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/1323_Maximum_69_Number.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/1323_Maximum_69_Number.java) | 9 is greater than 6, so change first 6 to 9 from left if exist, O(n) and O(1) | | 1337 | [The K Weakest Rows in a Matrix](https://leetcode.com/problems/the-k-weakest-rows-in-a-matrix/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/1337_The_K_Weakest_Rows_in_a_Matrix.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/1337_The_K_Weakest_Rows_in_a_Matrix.java) | Check by row, from left to right, until encount first zero, O(mn) and O(1) | | 1342 | [Number of Steps to Reduce a Number to Zero](https://leetcode.com/problems/number-of-steps-to-reduce-a-number-to-zero/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/1342_Number_of_Steps_to_Reduce_a_Number_to_Zero.py) | If number is divisible by 2, divide the number by 2, else subtract 1 from the number, and output the number of steps, O(logn) and O(1) | diff --git a/cpp/1310_XOR_Queries_of_a_Subarray.cpp b/cpp/1310_XOR_Queries_of_a_Subarray.cpp new file mode 100644 index 0000000..f471f7a --- /dev/null +++ b/cpp/1310_XOR_Queries_of_a_Subarray.cpp @@ -0,0 +1,12 @@ +class Solution { +public: + vector xorQueries(vector& arr, vector>& queries) { + vector res; + // Compute accumulated xor from head + for (int i = 1; i < arr.size(); i++) + arr[i] ^= arr[i - 1]; + for (auto &q: queries) + res.push_back(q[0] > 0 ? arr[q[0] - 1] ^ arr[q[1]] : arr[q[1]]); + return res; + } +}; diff --git a/java/1310_XOR_Queries_of_a_Subarray.java b/java/1310_XOR_Queries_of_a_Subarray.java new file mode 100644 index 0000000..c2b4d97 --- /dev/null +++ b/java/1310_XOR_Queries_of_a_Subarray.java @@ -0,0 +1,14 @@ +class Solution { + public int[] xorQueries(int[] arr, int[][] queries) { + int[] res = new int[queries.length], q; + // Compute accumulated xor from head + for (int i = 1; i < arr.length; i++) + arr[i] ^= arr[i - 1]; + // query result equals to xor[0, l] xor xor[0, r] + for (int i = 0; i < queries.length; i++) { + q = queries[i]; + res[i] = q[0] > 0 ? arr[q[0] - 1] ^ arr[q[1]] : arr[q[1]]; + } + return res; + } +} diff --git a/python/1310_XOR_Queries_of_a_Subarray.py b/python/1310_XOR_Queries_of_a_Subarray.py index 3f1d1fb..86cdd7b 100644 --- a/python/1310_XOR_Queries_of_a_Subarray.py +++ b/python/1310_XOR_Queries_of_a_Subarray.py @@ -1,10 +1,16 @@ class Solution: def xorQueries(self, arr: List[int], queries: List[List[int]]) -> List[int]: pref = [0] + # Compute accumulated xor from head for e in arr: pref.append(e ^ pref[-1]) ans = [] + # query result equal to xor[0, l] xor x[0, r] for [l, r] in queries: ans.append(pref[r+1] ^ pref[l]) return ans - + + # def xorQueries(self, arr: List[int], queries: List[List[int]]) -> List[int]: + # for i in range(len(arr) - 1): + # arr[i + 1] ^= arr[i] + # return [arr[j] ^ arr[i - 1] if i else arr[j] for i, j in queries] From 4882b9dcd8eec0d1f73fa3a4053013fccb7d226a Mon Sep 17 00:00:00 2001 From: Qiyuan Gong Date: Fri, 9 Oct 2020 20:54:50 +0800 Subject: [PATCH 075/119] Refine 668_Kth_Smallest_Number_in_Multiplication_Table --- README.md | 1 + ...mallest_Number_in_Multiplication_Table.cpp | 37 ++++++++++--------- ...allest_Number_in_Multiplication_Table.java | 22 +++++++++++ ...Smallest_Number_in_Multiplication_Table.py | 19 ++++++++++ 4 files changed, 61 insertions(+), 18 deletions(-) create mode 100644 java/668_Kth_Smallest_Number_in_Multiplication_Table.java create mode 100644 python/668_Kth_Smallest_Number_in_Multiplication_Table.py diff --git a/README.md b/README.md index 7c27167..33e94f7 100644 --- a/README.md +++ b/README.md @@ -175,6 +175,7 @@ I'm currently working on [Analytics-Zoo](https://github.com/intel-analytics/anal | 628 | [Maximum Product of Three Numbers](https://leetcode.com/problems/maximum-product-of-three-numbers/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/628_Maximum_Product_of_Three_Numbers.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/628_Maximum_Product_of_Three_Numbers.java) | Actually, we should only care about min1, min2 and max1-max3, to find these five elements, we can use 1. Brute force, O(n^3) and O(1)
2. Sort, O(nlogn) and O(1)
3. Single scan with 5 elements keep, O(n) and O(1) | | 654 | [Maximum Binary Tree](https://leetcode.com/problems/maximum-binary-tree/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/654_Maximum_Binary_Tree.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/654_Maximum_Binary_Tree.java) | 1. Divide and conquer, recursive, O(n^2)
2. Monotonic stack, O(n) | | 665 | [Non-decreasing Array](https://leetcode.com/problems/non-decreasing-array/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/665_Non-decreasing_Array.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/665_Non-decreasing_Array.java) | 1. Find the broken index, then check this point, O(n) and O(1)
2. Replace broken point with correct value, then check if there are more than 1 broken point, O(n) and O(1) | +| 668 | [Kth Smallest Number in Multiplication Table](https://leetcode.com/problems/kth-smallest-number-in-multiplication-table/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/668_Kth_Smallest_Number_in_Multiplication_Table.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/668_Kth_Smallest_Number_in_Multiplication_Table.java) [Cpp](https://github.com/qiyuangong/leetcode/blob/master/cpp/668_Kth_Smallest_Number_in_Multiplication_Table.cpp) | Binary search, O(mlog(mn) and O(1) | | 671 | [Second Minimum Node In a Binary Tree](https://leetcode.com/problems/second-minimum-node-in-a-binary-tree/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/671_Second_Minimum_Node_In_a_Binary_Tree.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/671_Second_Minimum_Node_In_a_Binary_Tree.java) | Note that min value is root: 1. Get all values then find result, O(n) and O(n)
2. BFS or DFS traverse the tree, then find the reslut, O(n) and O(n)| | 674 | [Longest Continuous Increasing Subsequence](https://leetcode.com/problems/longest-continuous-increasing-subsequence/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/674_Longest_Continuous_Increasing_Subsequence.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/674_Longest_Continuous_Increasing_Subsequence.java) | Scan nums once, check nums[i] < nums[i+1], if not reset count, O(n) and O(1) | | 680 | [Valid Palindrome II](https://leetcode.com/problems/valid-palindrome-ii/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/680_Valid_Palindrome_II.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/680_Valid_Palindrome_II.java) | Recursively check s[left == end, when not equal delete left or right. | diff --git a/cpp/668_Kth_Smallest_Number_in_Multiplication_Table.cpp b/cpp/668_Kth_Smallest_Number_in_Multiplication_Table.cpp index 1b8e6ab..1476598 100644 --- a/cpp/668_Kth_Smallest_Number_in_Multiplication_Table.cpp +++ b/cpp/668_Kth_Smallest_Number_in_Multiplication_Table.cpp @@ -1,26 +1,27 @@ class Solution { public: - #define ll long long int - - bool valid(ll x, int m, int n, int k){ - int cnt=0; - for(int i=1;i<=m;i++){ - cnt+=n=k; + return cnt >= k; } - + int findKthNumber(int n1, int n2, int k) { - ll l=0, r=n1*n2,ans; - while(l<=r){ - ll m = l +(r-l)/2; - if(valid(m,n1,n2,k)){ - ans=m; - r=m-1; - } - else{ - l=m+1; + ll l = 0, r = n1 * n2, ans; + while (l <= r) { + // ith row [i, 2*i, 3*i, ..., n*i] + // for each column, k = x // i + ll m = l + (r - l) / 2; + if (valid(m, n1, n2, k)) { + ans = m; + r = m - 1; + } else { + l = m + 1; } } return ans; diff --git a/java/668_Kth_Smallest_Number_in_Multiplication_Table.java b/java/668_Kth_Smallest_Number_in_Multiplication_Table.java new file mode 100644 index 0000000..4ba7a6d --- /dev/null +++ b/java/668_Kth_Smallest_Number_in_Multiplication_Table.java @@ -0,0 +1,22 @@ +class Solution { + // https://leetcode.com/problems/kth-smallest-number-in-multiplication-table/solution/ + public boolean enough(int x, int m, int n, int k) { + int count = 0; + for (int i = 1; i <= m; i++) { + count += Math.min(x / i, n); + } + return count >= k; + } + + public int findKthNumber(int m, int n, int k) { + int lo = 1, hi = m * n; + while (lo < hi) { + // ith row [i, 2*i, 3*i, ..., n*i] + // for each column, k = x // i + int mi = lo + (hi - lo) / 2; + if (!enough(mi, m, n, k)) lo = mi + 1; + else hi = mi; + } + return lo; + } +} diff --git a/python/668_Kth_Smallest_Number_in_Multiplication_Table.py b/python/668_Kth_Smallest_Number_in_Multiplication_Table.py new file mode 100644 index 0000000..dcfd654 --- /dev/null +++ b/python/668_Kth_Smallest_Number_in_Multiplication_Table.py @@ -0,0 +1,19 @@ +class Solution: + def findKthNumber(self, m: int, n: int, k: int) -> int: + # https://leetcode.com/problems/kth-smallest-number-in-multiplication-table/solution/ + def enough(x): + count = 0 + # ith row [i, 2*i, 3*i, ..., n*i] + # for each column, k = x // i + for i in range(1, m+1): + count += min(x // i, n) + return count >= k + + lo, hi = 1, m * n + while lo < hi: + mi = (lo + hi) // 2 + if not enough(mi): + lo = mi + 1 + else: + hi = mi + return lo From efa47f2ca8ad458f4a09d8780ddac1e1c3fcd984 Mon Sep 17 00:00:00 2001 From: Qiyuan Gong Date: Sat, 10 Oct 2020 21:40:01 +0800 Subject: [PATCH 076/119] Add 412_Fizz_Buzz.cpp link --- README.md | 2 +- cpp/412_Fizz_Buzz.cpp | 14 +++++++++----- 2 files changed, 10 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 33e94f7..218bd89 100644 --- a/README.md +++ b/README.md @@ -143,7 +143,7 @@ I'm currently working on [Analytics-Zoo](https://github.com/intel-analytics/anal | 405 | [Convert a Number to Hexadecimal](https://leetcode.com/problems/convert-a-number-to-hexadecimal/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/405_Convert_a_Number_to_Hexadecimal.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/405_Convert_a_Number_to_Hexadecimal.java) | [Two's complement](https://en.wikipedia.org/wiki/Two%27s_complement) 1. Bit manipulate, each time handle 4 digits
2. Python (hex) and Java API (toHexString & Integer.toHexString) | | 408 | [Valid Word Abbreviation](https://leetcode.com/problems/valid-word-abbreviation/) ♥ | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/408_Valid_Word_Abbreviation.py) | Go over abbr and word, O(n) and O(1) | | 409 | [Longest Palindrome](https://leetcode.com/problems/longest-palindrome/description/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/409_Longest_Palindrome.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/409_Longest_Palindrome.java) | Length of Palindrome is always 2n or 2n + 1. So, get all possible 2*n, and choose a single one as 1 if it exists. | -| 412 | [Fizz Buzz](https://leetcode.com/problems/fizz-buzz/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/412_Fizz_Buzz.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/412_Fizz_Buzz.java) | 1. From 1 to n, condition check
2. Condition check and string connect | +| 412 | [Fizz Buzz](https://leetcode.com/problems/fizz-buzz/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/412_Fizz_Buzz.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/412_Fizz_Buzz.java) [Cpp](https://github.com/qiyuangong/leetcode/blob/master/cpp/412_Fizz_Buzz.cpp) | 1. From 1 to n, condition check
2. Condition check and string connect | | 414 | [Third Maximum Number](https://leetcode.com/problems/third-maximum-number/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/414_Third_Maximum_Number.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/414_Third_Maximum_Number.java) | 1. Keep max 1-3 then compare, O(n) and O(1)
2. PriorityQueue, O(n) and O(1) | | 415 | [Add Strings](https://leetcode.com/problems/add-strings/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/415_Add_Strings.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/415_Add_Strings.java) | Two points, careful abour carry, O(n) and O(n) | | 416 | [Partition Equal Subset Sum](https://leetcode.com/problems/partition-equal-subset-sum/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/416_Partition_Equal_Subset_Sum.py) | DP, Check if sum of some elements can be half of total sum, O(total_sum / 2 * n) and O(total_sum / 2) | diff --git a/cpp/412_Fizz_Buzz.cpp b/cpp/412_Fizz_Buzz.cpp index 7bbee33..3a7dd5d 100644 --- a/cpp/412_Fizz_Buzz.cpp +++ b/cpp/412_Fizz_Buzz.cpp @@ -4,11 +4,15 @@ class Solution { vector fizzBuzz(int n) { int i; vector s; - for(i=0;i Date: Sun, 11 Oct 2020 23:20:23 +0800 Subject: [PATCH 077/119] Refine 541_Reverse_String_II --- README.md | 1 + java/541_Reverse_String_II.java | 16 ++++++++++++++++ python/541_Reverse_String_II.py | 8 +++++++- 3 files changed, 24 insertions(+), 1 deletion(-) create mode 100644 java/541_Reverse_String_II.java diff --git a/README.md b/README.md index 218bd89..7163b06 100644 --- a/README.md +++ b/README.md @@ -164,6 +164,7 @@ I'm currently working on [Analytics-Zoo](https://github.com/intel-analytics/anal | 485 | [Max Consecutive Ones](https://leetcode.com/problems/max-consecutive-ones/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/485_Max_Consecutive_Ones.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/485_Max_Consecutive_Ones.java) | Add one when encounter 1, set to 0 when encounter 0, O(n) and O(1) | | 509 | [Fibonacci Number](https://leetcode.com/problems/fibonacci-number/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/509_Fibonacci_Number.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/509_Fibonacci_Number.java) | 1. Recursive, O(n)
2. DP with memo, O(n). Note that N<=30, which means that we can keep a memo from 0 to 30. | | 538 | [Convert BST to Greater Tree](https://leetcode.com/problems/convert-bst-to-greater-tree/description/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/538_Convert_BST_to_Greater_Tree.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/538_Convert_BST_to_Greater_Tree.java) | Right first DFS with a variable recording sum of node.val and right.val. 1. Recursive.
2. Stack 3. Reverse Morris In-order Traversal | +| 541 | [Reverse String II](https://leetcode.com/problems/reverse-string-ii/solution/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/541_Reverse_String_II.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/541_Reverse_String_II.java) | Handle each 2k until reaching end, On(n) and O(n) | | 543 | [Diameter of Binary Tree](https://leetcode.com/problems/diameter-of-binary-tree/description/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/543_Diameter_of_Binary_Tree.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/543_Diameter_of_Binary_Tree.java) | DFS with O(1) for max answer | | 547 | [Friend Circles](https://leetcode.com/problems/friend-circles/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/547_Friend_Circles.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/547_Friend_Circles.java) | 1. DFS, O(n^2) and O(1)
2. BFS, O(n^2) and O(1)
3. Union-find, O(n^2) and O(n)| | 557 | [Reverse Words in a String III](https://leetcode.com/problems/reverse-words-in-a-string-iii/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/557_Reverse_Words_in_a_String_III.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/557_Reverse_Words_in_a_String_III.java) | String handle: Split with space than reverse word, O(n) and O(n). Better solution is that reverse can be O(1) space in array. | diff --git a/java/541_Reverse_String_II.java b/java/541_Reverse_String_II.java new file mode 100644 index 0000000..8b8565c --- /dev/null +++ b/java/541_Reverse_String_II.java @@ -0,0 +1,16 @@ +class Solution { + public String reverseStr(String s, int k) { + // https://leetcode.com/problems/reverse-string-ii/solution/ + char[] a = s.toCharArray(); + for (int start = 0; start < a.length; start += 2 * k) { + int i = start, j = Math.min(start + k - 1, a.length - 1); + // Reverse from i to j + while (i < j) { + char tmp = a[i]; + a[i++] = a[j]; + a[j--] = tmp; + } + } + return new String(a); + } +} diff --git a/python/541_Reverse_String_II.py b/python/541_Reverse_String_II.py index c1a959e..08fcced 100644 --- a/python/541_Reverse_String_II.py +++ b/python/541_Reverse_String_II.py @@ -1,5 +1,5 @@ class Solution: - def reverseStr(self, s, k): + def reverseStr(self, s: str, k: int) -> str: N = len(s) ans = "" position = 0 @@ -9,6 +9,12 @@ def reverseStr(self, s, k): position += 2 * k return ans + # def reverseStr(self, s: str, k: int) -> str: + # s = list(s) + # for i in range(0, len(s), 2*k): + # s[i:i+k] = reversed(s[i:i+k]) + # return "".join(s) + s1 = Solution() From fa2b50452d07f5f754976b744777353424d3600b Mon Sep 17 00:00:00 2001 From: peterhuang1kimo Date: Mon, 19 Oct 2020 22:23:06 +0800 Subject: [PATCH 078/119] Upgrade 072_Edit_Distance.py to python 3 (#28) * Upgrade 072_Edit_Distance.py to python 3, by @peterhuang1kimo --- python/072_Edit_Distance.py | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/python/072_Edit_Distance.py b/python/072_Edit_Distance.py index e9033cc..f1dd491 100644 --- a/python/072_Edit_Distance.py +++ b/python/072_Edit_Distance.py @@ -24,7 +24,7 @@ class Solution(object): def minDistance(self, word1, word2): ls_1, ls_2 = len(word1), len(word2) - dp = range(ls_1 + 1) + dp = list(range(ls_1 + 1)) for j in range(1, ls_2 + 1): pre = dp[0] dp[0] = j @@ -36,3 +36,10 @@ def minDistance(self, word1, word2): dp[i] = min(pre + 1, dp[i] + 1, dp[i - 1] + 1) pre = temp return dp[ls_1] + + + if __name__ == '__main__': + # begin + s = Solution() + print (s.minDistance("horse","ros")) + print (s.minDistance("intention","execution")) From 09bbdf890a71b1820793f29cd05e20db623acef6 Mon Sep 17 00:00:00 2001 From: hvsalesforce <73243807+hvsalesforce@users.noreply.github.com> Date: Wed, 28 Oct 2020 19:55:37 +0530 Subject: [PATCH 079/119] Create 066_Plus_One.java (#33) * Create 066_Plus_One.java, by @hvsalesforce --- java/066_Plus_One.java | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 java/066_Plus_One.java diff --git a/java/066_Plus_One.java b/java/066_Plus_One.java new file mode 100644 index 0000000..a9e474f --- /dev/null +++ b/java/066_Plus_One.java @@ -0,0 +1,23 @@ +class Solution { + public int[] plusOne(int[] digits) { + return addToDigit(digits, digits.length - 1); + } + + private int[] addToDigit(int[] digits, int index) { + if (index == -1) { + int[] newDigits = new int[digits.length + 1]; + newDigits[0] = 1; + for (int i = 0; i < digits.length; i++) { + newDigits[i + 1] = digits[i]; + } + return newDigits; + } + if (digits[index] == 9) { + digits[index] = 0; + return addToDigit(digits, index - 1); + } else { + digits[index]++; + return digits; + } + } +} From bb21f19083c4e2d07ed3278bea4017c1f0080b33 Mon Sep 17 00:00:00 2001 From: N Bhanu Prakash Reddy <32775691+bhanu1131@users.noreply.github.com> Date: Wed, 28 Oct 2020 20:02:45 +0530 Subject: [PATCH 080/119] Create 282_Expression_Add_Operators.cpp (#32) * Create 282_Expression_Add_Operators.cpp, by @bhanu1131 --- cpp/282_Expression_Add_Operators.cpp | 53 ++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 cpp/282_Expression_Add_Operators.cpp diff --git a/cpp/282_Expression_Add_Operators.cpp b/cpp/282_Expression_Add_Operators.cpp new file mode 100644 index 0000000..2d8b2c9 --- /dev/null +++ b/cpp/282_Expression_Add_Operators.cpp @@ -0,0 +1,53 @@ +class Solution { +public: + vector addOperators(string num, int target) { + vector result; + if (num.size() == 0) return result; + findSolution(num, target, result, "", 0, 0, 0, ' '); + return result; + } + + //DFS algorithm + void findSolution(const string &num, const int target, + vector& result, + string solution, + int idx, + long long val, + long long prev, + char preop ) + { + + if (target == val && idx == num.size()){ + result.push_back(solution); + return; + } + if (idx == num.size()) return; + + string n; + long long v=0; + for(int i=idx; i Date: Thu, 29 Oct 2020 17:45:36 +0530 Subject: [PATCH 081/119] Create 1248_count_number_of_nice_sub_arrays.cpp (#31) * Create 1248_count_number_of_nice_sub_arrays.cpp, @bhanu1131 --- cpp/1248_count_number_of_nice_sub_arrays.cpp | 42 ++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 cpp/1248_count_number_of_nice_sub_arrays.cpp diff --git a/cpp/1248_count_number_of_nice_sub_arrays.cpp b/cpp/1248_count_number_of_nice_sub_arrays.cpp new file mode 100644 index 0000000..1f381ed --- /dev/null +++ b/cpp/1248_count_number_of_nice_sub_arrays.cpp @@ -0,0 +1,42 @@ +class Solution { +public: + int numberOfSubarrays(vector& nums, int k) { + return atMostK(nums, k) - atMostK(nums, k - 1); + } + +private: + int atMostK(const vector& nums, int k) { + int result = 0, left = 0, count = 0; + for (int right = 0; right < nums.size(); ++right) { + count += nums[right] % 2; + while (count > k) { + count -= nums[left] % 2; + ++left; + } + result += right - left + 1; + } + return result; + } +}; + +// Time: O(n) +// Space: O(k) +class Solution2 { +public: + int numberOfSubarrays(vector& nums, int k) { + int result = 0; + deque dq = {-1}; + for (int i = 0; i < nums.size(); ++i) { + if (nums[i] % 2) { + dq.emplace_back(i); + } + if (dq.size() > k + 1) { + dq.pop_front(); + } + if (dq.size() == k + 1) { + result += dq[1] - dq[0]; + } + } + return result; + } +}; From 5dadae95e823c758f0e9d3f665d09b4a8d30f66a Mon Sep 17 00:00:00 2001 From: N Bhanu Prakash Reddy <32775691+bhanu1131@users.noreply.github.com> Date: Sat, 31 Oct 2020 19:56:35 +0530 Subject: [PATCH 082/119] Create 923_3_sum_with_multiplicity.cpp (#30) * Create 923_3_sum_with_multiplicity.cpp, by @bhanu1131 --- cpp/923_3_sum_with_multiplicity.cpp | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 cpp/923_3_sum_with_multiplicity.cpp diff --git a/cpp/923_3_sum_with_multiplicity.cpp b/cpp/923_3_sum_with_multiplicity.cpp new file mode 100644 index 0000000..5b7b2b4 --- /dev/null +++ b/cpp/923_3_sum_with_multiplicity.cpp @@ -0,0 +1,26 @@ +class Solution { +public: + int threeSumMulti(vector& A, int target) { + unordered_map count; + for (const auto& a : A) { + ++count[a]; + } + uint64_t result = 0; + for (const auto& kvp1 : count) { + for (const auto& kvp2 : count) { + int i = kvp1.first, j = kvp2.first, k = target - i - j; + if (!count.count(k)) { + continue; + } + if (i == j && j == k) { + result += count[i] * (count[i] - 1) * (count[i] - 2) / 6; + } else if (i == j && j != k) { + result += count[i] * (count[i] - 1) / 2 * count[k]; + } else if (i < j && j < k) { + result += count[i] * count[j] * count[k]; + } + } + } + return result % static_cast(1e9 + 7); + } +}; From e0168c2d226d7f2341f9c160a8b119299d0d56ec Mon Sep 17 00:00:00 2001 From: N Bhanu Prakash Reddy <32775691+bhanu1131@users.noreply.github.com> Date: Sun, 1 Nov 2020 19:46:27 +0530 Subject: [PATCH 083/119] Create 201_bitwise_and_of_numbers_range.cpp (#29) * Create 201_bitwise_and_of_numbers_range.cpp, by @bhanu1131 --- cpp/201_bitwise_and_of_numbers_range.cpp | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 cpp/201_bitwise_and_of_numbers_range.cpp diff --git a/cpp/201_bitwise_and_of_numbers_range.cpp b/cpp/201_bitwise_and_of_numbers_range.cpp new file mode 100644 index 0000000..c0f4151 --- /dev/null +++ b/cpp/201_bitwise_and_of_numbers_range.cpp @@ -0,0 +1,14 @@ +/** time complexity : O(logN). N = min(m, n) **/ + +class Solution { +public: + int rangeBitwiseAnd(int m, int n) { + int cnt = 0; + while(m < n) { + m = m >> 1; + n = n >> 1; + cnt++; + } + return n< Date: Sun, 1 Nov 2020 22:26:23 -0800 Subject: [PATCH 084/119] Add 457_Circular_Array_Loop.py (#34) * Add 457_Circular_Array_Loop.py, by @yuchenliu15 --- python/457_Circular_Array_Loop.py | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 python/457_Circular_Array_Loop.py diff --git a/python/457_Circular_Array_Loop.py b/python/457_Circular_Array_Loop.py new file mode 100644 index 0000000..1a2e2ee --- /dev/null +++ b/python/457_Circular_Array_Loop.py @@ -0,0 +1,29 @@ +class Solution: + def circularArrayLoop(self, nums: List[int]) -> bool: + for i in range(len(nums)): + if nums[i] == 0: + continue + + # if slow and fast pointers collide, then there exists a loop + slow = i + fast = self.index(nums, slow) + while nums[slow] * nums[fast] > 0 and nums[slow] * nums[self.index(nums, fast)] > 0: + if slow == fast and fast != self.index(nums, fast): + return True + elif slow == fast and fast == self.index(nums, fast): + break + slow = self.index(nums, slow) + fast = self.index(nums, self.index(nums, fast)) + + # set path to all 0s since it doesn't work + runner = i + value = nums[runner] + while nums[runner] * value > 0: + temp = self.index(nums, runner) + nums[runner] = 0 + runner = temp + return False + + def index(self, nums, index): + length = len(nums) + return (index + nums[index] + length) % length From 1371de2631d745efba39de41b51c3424e35da434 Mon Sep 17 00:00:00 2001 From: Yuchen Liu Date: Thu, 5 Nov 2020 01:56:38 -0800 Subject: [PATCH 085/119] Fix 067_Add_Binary for Python 3 (#35) * Fix 067_Add_Binary.py for Python, @yuchenliu15 --- python/067_Add_Binary.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python/067_Add_Binary.py b/python/067_Add_Binary.py index efc389c..70fd792 100644 --- a/python/067_Add_Binary.py +++ b/python/067_Add_Binary.py @@ -53,7 +53,7 @@ def addBinary(self, a, b): if (lsb + pos) >= 0: curr += int(b[pos]) res = str(curr % 2) + res - curr /= 2 + curr //= 2 pos -= 1 if curr == 1: res = '1' + res From 5397bbe4a87dba82dc9fa57abf09a4346aa63f46 Mon Sep 17 00:00:00 2001 From: Yuchen Liu Date: Wed, 25 Nov 2020 05:23:53 -0800 Subject: [PATCH 086/119] Add 168 python solution (#38) * Add 168_Excel_Sheet_Column_Title.py, by @yuchenliu15 --- python/168_Excel_Sheet_Column_Title.py | 8 ++++++++ 1 file changed, 8 insertions(+) create mode 100644 python/168_Excel_Sheet_Column_Title.py diff --git a/python/168_Excel_Sheet_Column_Title.py b/python/168_Excel_Sheet_Column_Title.py new file mode 100644 index 0000000..582b853 --- /dev/null +++ b/python/168_Excel_Sheet_Column_Title.py @@ -0,0 +1,8 @@ +class Solution: + def convertToTitle(self, n: int) -> str: + res = "" + while n > 0: + n -= 1 + res = chr(65 + n % 26) + res + n //= 26 + return res From 056459464f15df885538aa90f6db882a2f4dbd20 Mon Sep 17 00:00:00 2001 From: Qiyuan Gong Date: Thu, 4 Mar 2021 21:41:19 +0800 Subject: [PATCH 087/119] Fix python/146_LRU_Cache --- python/146_LRU_Cache.py | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/python/146_LRU_Cache.py b/python/146_LRU_Cache.py index d6a92ac..83b641e 100644 --- a/python/146_LRU_Cache.py +++ b/python/146_LRU_Cache.py @@ -1,4 +1,4 @@ -class LRUCache: +class LRUCache(object): def __init__(self, capacity): """ :type capacity: int @@ -21,14 +21,12 @@ def get(self, key): else: return -1 - def set(self, key, value): + def put(self, key, value): """ :type key: int :type value: int :rtype: nothing """ - if not key or not value: - return None if key in self.cache: self.queue.remove(key) elif len(self.queue) == self.capacity: @@ -48,7 +46,7 @@ def set(self, key, value): # self.dic[key] = v # set key as the newest one # return v # - # def set(self, key, value): + # def put(self, key, value): # if key in self.dic: # self.dic.pop(key) # else: From baa5e3186814951036effb1eed4eb611dbf19ece Mon Sep 17 00:00:00 2001 From: Mohan Kumar Paluru <46961568+mohankumarpaluru@users.noreply.github.com> Date: Sun, 18 Jul 2021 20:58:20 +0530 Subject: [PATCH 088/119] Update 009_Palindrome_Number.py (#42) A trick to make it simple and a lot faster --- python/009_Palindrome_Number.py | 34 ++++++++++++++++++++------------- 1 file changed, 21 insertions(+), 13 deletions(-) diff --git a/python/009_Palindrome_Number.py b/python/009_Palindrome_Number.py index af6890f..8dc7ce5 100644 --- a/python/009_Palindrome_Number.py +++ b/python/009_Palindrome_Number.py @@ -6,19 +6,27 @@ # """ class Solution(object): - def isPalindrome(self, x): - if x < 0: - return False - ls = len(str(x)) - tmp = x - for i in range(int(ls/2)): - right = int(tmp % 10) - left = tmp / (10 ** (ls - 2 * i - 1)) - left = int(left % 10) - if left != right: - return False - tmp = tmp // 10 - return True + def isPalindrome(self, x: int) -> bool: + x = str(x) + if (x == x[::-1]): + return True + return False + + + # def isPalindrome(self, x): + # if x < 0: + # return False + # ls = len(str(x)) + # tmp = x + # for i in range(int(ls/2)): + # right = int(tmp % 10) + # left = tmp / (10 ** (ls - 2 * i - 1)) + # left = int(left % 10) + # if left != right: + # return False + # tmp = tmp // 10 + # return True + # def isPalindrome(self, x): # #leetcode book From 8207d2c71f39423777cbc7e68550c7ff56895ba7 Mon Sep 17 00:00:00 2001 From: Anish Sachdeva <38917450+anishLearnsToCode@users.noreply.github.com> Date: Wed, 4 Aug 2021 16:00:58 +0200 Subject: [PATCH 089/119] Adds leetcode-algorithms by anish in Other LeetCode repos section (#45) Co-authored-by: Anish Sachdeva --- README.md | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 7163b06..be64f81 100644 --- a/README.md +++ b/README.md @@ -241,9 +241,10 @@ I'm currently working on [Analytics-Zoo](https://github.com/intel-analytics/anal |---| ----- | | 4 | [Median of Two Sorted Arrays](https://leetcode.com/problems/median-of-two-sorted-arrays/) | -## Other Leetcode Repos +## Other LeetCode Repos +1. [LeetCode Algorithms ~anishLearnsToCode](https://github.com/anishLearnsToCode/leetcode-algorithms) 1. [haoel's leetcode](https://github.com/haoel/leetcode) -2. [soulmachine's leetcode](https://github.com/soulmachine/leetcode) -3. [kamyu104's LeetCode](https://github.com/kamyu104/LeetCode) -4. [gouthampradhan's leetcode](https://github.com/gouthampradhan/leetcode) +1. [soulmachine's leetcode](https://github.com/soulmachine/leetcode) +1. [kamyu104's LeetCode](https://github.com/kamyu104/LeetCode) +1. [gouthampradhan's leetcode](https://github.com/gouthampradhan/leetcode) From 998b2da1cf107a54a6d3b60b21076660aa530839 Mon Sep 17 00:00:00 2001 From: dvlpsh Date: Sun, 5 Dec 2021 17:47:36 +0530 Subject: [PATCH 090/119] Add 1533_Kth_Missing_Positive_Number.java (#48) * Add Kth_Missing_Positive_Number.java Contributed by @dvlpsh --- java/1533_Kth_Missing_Positive_Number.java | 47 ++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 java/1533_Kth_Missing_Positive_Number.java diff --git a/java/1533_Kth_Missing_Positive_Number.java b/java/1533_Kth_Missing_Positive_Number.java new file mode 100644 index 0000000..c7b0dab --- /dev/null +++ b/java/1533_Kth_Missing_Positive_Number.java @@ -0,0 +1,47 @@ +class Solution { + public int findKthPositive(int[] a, int k) + { + int B[] = new int[a.length]; + + //equation (A) + //B[i]=a[i]-i-1 + + + //B[i]=number of missing numbers BEFORE a[i] + for(int i=0;i=k + + int lo=0,hi=B.length-1; + + while(lo<=hi) + { + int mid = lo+(hi-lo)/2; + + if(B[mid]>=k) + hi=mid-1; + else + lo=mid+1; + } + + //lo is the answer + + /*now the number to return is a[lo]-(B[lo]-k+1) (EQUATION B) + //where (B[lo]-k+1) is the number of steps we need to go back + //from lo to retrieve kth missing number, since we need to find + //the kth missing number BEFORE a[lo], we do +1 here as + //a[lo] is not a missing number when B[lo]==k + //putting lo in equation(A) above + //B[i]=a[i]-i-1 + //B[lo]=a[lo]-lo-1 + and using this value of B[lo] in equation B + //we return a[lo]-(a[lo]-lo-1-k+1) + we get lo+k as ans + so return it*/ + + return lo+k; + + } +} From ecdb28240dfeedb8ff7948e109062f32fa312d46 Mon Sep 17 00:00:00 2001 From: Paras Yadav <62833829+parascoding@users.noreply.github.com> Date: Sun, 5 Dec 2021 17:51:59 +0530 Subject: [PATCH 091/119] =?UTF-8?q?Create=20Minimize=20the=20Difference=20?= =?UTF-8?q?Between=20Target=20and=20Chosen=20Elements=20[19=E2=80=A6=20(#4?= =?UTF-8?q?7)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Create Minimize the Difference Between Target and Chosen Elements [1981].java Contributed by @parascoding --- ...ce_Between_Target_and_Chosen_Elements.java | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 java/1981_Minimize_the_Difference_Between_Target_and_Chosen_Elements.java diff --git a/java/1981_Minimize_the_Difference_Between_Target_and_Chosen_Elements.java b/java/1981_Minimize_the_Difference_Between_Target_and_Chosen_Elements.java new file mode 100644 index 0000000..80eebe4 --- /dev/null +++ b/java/1981_Minimize_the_Difference_Between_Target_and_Chosen_Elements.java @@ -0,0 +1,28 @@ +class Solution { + public int minimizeTheDifference(int[][] a, int k) { + n=a.length; + m=a[0].length; + min=Integer.MAX_VALUE; + dp=new boolean[n][5000]; + solve(a,k,0,0,0); + return min; + } + private void solve(int a[][],int k,int sum,int row,int col) + { + if(dp[row][sum]) return; + if(n-1==row) + { + for(int i=0;i Date: Sun, 5 Dec 2021 20:53:42 +0800 Subject: [PATCH 092/119] Refine 1981 and 1539 format and link --- README.md | 2 + java/1533_Kth_Missing_Positive_Number.java | 47 ------------------- java/1539_Kth_Missing_Positive_Number.java | 43 +++++++++++++++++ ...ce_Between_Target_and_Chosen_Elements.java | 37 ++++++++------- 4 files changed, 64 insertions(+), 65 deletions(-) delete mode 100644 java/1533_Kth_Missing_Positive_Number.java create mode 100644 java/1539_Kth_Missing_Positive_Number.java diff --git a/README.md b/README.md index be64f81..3bcb819 100644 --- a/README.md +++ b/README.md @@ -236,6 +236,8 @@ I'm currently working on [Analytics-Zoo](https://github.com/intel-analytics/anal | 1342 | [Number of Steps to Reduce a Number to Zero](https://leetcode.com/problems/number-of-steps-to-reduce-a-number-to-zero/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/1342_Number_of_Steps_to_Reduce_a_Number_to_Zero.py) | If number is divisible by 2, divide the number by 2, else subtract 1 from the number, and output the number of steps, O(logn) and O(1) | | 1365 | [How Many Numbers Are Smaller Than the Current Number](https://leetcode.com/problems/how-many-numbers-are-smaller-than-the-current-number/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/1365_How_Many_Numbers_Are_Smaller_Than_the_Current_Number.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/1365_How_Many_Numbers_Are_Smaller_Than_the_Current_Number.java) | 1. Sort and get position in sorted nums, O(nlogn) and O(n)
2. Fill count into 0-100, O(n) and O(1) | | 1480 | [Running Sum of 1d Array](https://leetcode.com/problems/running-sum-of-1d-array/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/1480_Running_Sum_of_1d_Array.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/1480_Running_Sum_of_1d_Array.java) | 1. Go through the array, O(n) and O(1)
2. Accumulate API | +| 1539 | [Kth Missing Positive Number](https://leetcode.com/problems/kth-missing-positive-number/) | [Java](https://github.com/qiyuangong/leetcode/blob/master/java/1539_Kth_Missing_Positive_Number.java) | Binary search, num of missing = arr[i]-i-1 | +| 1981 | [Minimize the Difference Between Target and Chosen Elements](https://leetcode.com/problems/minimize-the-difference-between-target-and-chosen-elements/) | [Java](https://github.com/qiyuangong/leetcode/blob/master/java/1981_Minimize_the_Difference_Between_Target_and_Chosen_Elements.java) | DP memo[row][sum] to avoid recomputing | | # | To Understand | |---| ----- | diff --git a/java/1533_Kth_Missing_Positive_Number.java b/java/1533_Kth_Missing_Positive_Number.java deleted file mode 100644 index c7b0dab..0000000 --- a/java/1533_Kth_Missing_Positive_Number.java +++ /dev/null @@ -1,47 +0,0 @@ -class Solution { - public int findKthPositive(int[] a, int k) - { - int B[] = new int[a.length]; - - //equation (A) - //B[i]=a[i]-i-1 - - - //B[i]=number of missing numbers BEFORE a[i] - for(int i=0;i=k - - int lo=0,hi=B.length-1; - - while(lo<=hi) - { - int mid = lo+(hi-lo)/2; - - if(B[mid]>=k) - hi=mid-1; - else - lo=mid+1; - } - - //lo is the answer - - /*now the number to return is a[lo]-(B[lo]-k+1) (EQUATION B) - //where (B[lo]-k+1) is the number of steps we need to go back - //from lo to retrieve kth missing number, since we need to find - //the kth missing number BEFORE a[lo], we do +1 here as - //a[lo] is not a missing number when B[lo]==k - //putting lo in equation(A) above - //B[i]=a[i]-i-1 - //B[lo]=a[lo]-lo-1 - and using this value of B[lo] in equation B - //we return a[lo]-(a[lo]-lo-1-k+1) - we get lo+k as ans - so return it*/ - - return lo+k; - - } -} diff --git a/java/1539_Kth_Missing_Positive_Number.java b/java/1539_Kth_Missing_Positive_Number.java new file mode 100644 index 0000000..972aa8d --- /dev/null +++ b/java/1539_Kth_Missing_Positive_Number.java @@ -0,0 +1,43 @@ +class Solution { + public int findKthPositive(int[] a, int k) { + int B[] = new int[a.length]; + + // equation (A) + // B[i]=a[i]-i-1 + // B[i]=number of missing numbers BEFORE a[i] + for (int i = 0; i < a.length; i++) + B[i] = a[i] - i - 1; // -1 is done as here missing numbers start from 1 and not 0 + + // binary search upper bound of k + // smallest value>=k + + int lo = 0, hi = B.length - 1; + + while (lo <= hi) { + int mid = lo + (hi - lo) / 2; + + if (B[mid] >= k) + hi = mid - 1; + else + lo = mid + 1; + } + + // lo is the answer + + /* + * now the number to return is a[lo]-(B[lo]-k+1) (EQUATION B) + * where (B[lo]-k+1) is the number of steps we need to go back + * from lo to retrieve kth missing number, since we need to find + * the kth missing number BEFORE a[lo], we do +1 here as + * a[lo] is not a missing number when B[lo]==k + * putting lo in equation(A) above + * B[i]=a[i]-i-1 + * B[lo]=a[lo]-lo-1 + * and using this value of B[lo] in equation B + * we return a[lo]-(a[lo]-lo-1-k+1) + * we get lo+k as ans + * so return it + */ + return lo + k; + } +} diff --git a/java/1981_Minimize_the_Difference_Between_Target_and_Chosen_Elements.java b/java/1981_Minimize_the_Difference_Between_Target_and_Chosen_Elements.java index 80eebe4..02f474a 100644 --- a/java/1981_Minimize_the_Difference_Between_Target_and_Chosen_Elements.java +++ b/java/1981_Minimize_the_Difference_Between_Target_and_Chosen_Elements.java @@ -1,28 +1,29 @@ class Solution { public int minimizeTheDifference(int[][] a, int k) { - n=a.length; - m=a[0].length; - min=Integer.MAX_VALUE; - dp=new boolean[n][5000]; - solve(a,k,0,0,0); + n = a.length; + m = a[0].length; + min = Integer.MAX_VALUE; + dp = new boolean[n][5000]; + solve(a, k, 0, 0, 0); return min; } - private void solve(int a[][],int k,int sum,int row,int col) - { - if(dp[row][sum]) return; - if(n-1==row) - { - for(int i=0;i Date: Sun, 5 Dec 2021 21:00:42 +0800 Subject: [PATCH 093/119] Change 012 to Python3 --- python/012_Integer_to_Roman.py | 38 +++++++++++++++++----------------- 1 file changed, 19 insertions(+), 19 deletions(-) diff --git a/python/012_Integer_to_Roman.py b/python/012_Integer_to_Roman.py index 90aef5d..5181c73 100644 --- a/python/012_Integer_to_Roman.py +++ b/python/012_Integer_to_Roman.py @@ -1,29 +1,29 @@ # class Solution(object): -# def intToRoman(self, num): +# def intToRoman(self, num: int) -> str: # """ # :type num: int # :rtype: str # """ # class Solution(object): - # def intToRoman(self, num): - # #http://www.rapidtables.com/convert/number/how-number-to-roman-numerals.htm - # roman_dim = [[1000, 'M'], [900, 'CM'], [500, 'D'], [400, 'CD'], - # [100, 'C'], [90, 'XC'], [50, 'L'], [40, 'XL'], [10, 'X'], - # [9,'IX'], [5, 'V'], [4, 'IV'], [1, 'I']] - # if num == 0: - # return '' - # roman_str = '' - # current, dim = num, 0 - # while current != 0: - # while current // roman_dim[dim][0] == 0: - # dim += 1 - # while current - roman_dim[dim][0] >= 0: - # current -= roman_dim[dim][0] - # roman_str += roman_dim[dim][1] - # return roman_str + # def intToRoman(self, num: int) -> str: + ## http://www.rapidtables.com/convert/number/how-number-to-roman-numerals.htm + # roman_dim = [[1000, 'M'], [900, 'CM'], [500, 'D'], [400, 'CD'], + # [100, 'C'], [90, 'XC'], [50, 'L'], [40, 'XL'], [10, 'X'], + # [9,'IX'], [5, 'V'], [4, 'IV'], [1, 'I']] + # if num == 0: + # return '' + # roman_str = '' + # current, dim = num, 0 + # while current != 0: + # while current // roman_dim[dim][0] == 0: + # dim += 1 + # while current - roman_dim[dim][0] >= 0: + # current -= roman_dim[dim][0] + # roman_str += roman_dim[dim][1] + # return roman_str - def intToRoman(self, num): + def intToRoman(self, num: int) -> str: values = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1] @@ -34,7 +34,7 @@ def intToRoman(self, num): roman = '' i = 0 while num > 0: - k = num / values[i] + k = num // values[i] for j in range(k): roman += symbols[i] num -= values[i] From 76137fae30d194b02305ad40855e3f4e75060275 Mon Sep 17 00:00:00 2001 From: Deeksha Tripathi <87656035+Deeeeksha@users.noreply.github.com> Date: Tue, 25 Jan 2022 19:17:40 +0530 Subject: [PATCH 094/119] Add 165_Compare_Version_Numbers (#50) * 165 CompareVersion Solution Contributed by @Deeeeksha --- python/165_Compare_Version_Numbers.py | 29 +++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 python/165_Compare_Version_Numbers.py diff --git a/python/165_Compare_Version_Numbers.py b/python/165_Compare_Version_Numbers.py new file mode 100644 index 0000000..84e917f --- /dev/null +++ b/python/165_Compare_Version_Numbers.py @@ -0,0 +1,29 @@ +class Solution: + def compareVersion(self, version1: str, version2: str) -> int: + l1=list(map(int,version1.split('.'))) + l2=list(map(int,version2.split('.'))) + if l1==l2: + return(0) + + a=len(l1) + b=len(l2) + + if a>b: + for i in range(a-b): + l2.append("0") + + else: + for i in range(b-a): + l1.append("0") + + for i in range(len(l1)): + if int(l1[i])>int(l2[i]): + return(1) + + elif int(l1[i]) Date: Sun, 13 Mar 2022 00:39:55 -0500 Subject: [PATCH 095/119] Create 1189_Maximum_Number_of_Balloons.java (#52) * Create 1189_Maximum_Number_of_Balloons.java * Create 1374_Generate_a_String_With_Characters_That_Have_Odd_Counts_Solution.py Contributed by @ChesterChangLiu --- java/1189_Maximum_Number_of_Balloons.java | 19 +++++++++++++++++++ ...haracters_That_Have_Odd_Counts_Solution.py | 12 ++++++++++++ 2 files changed, 31 insertions(+) create mode 100644 java/1189_Maximum_Number_of_Balloons.java create mode 100644 python/1374_Generate_a_String_With_Characters_That_Have_Odd_Counts_Solution.py diff --git a/java/1189_Maximum_Number_of_Balloons.java b/java/1189_Maximum_Number_of_Balloons.java new file mode 100644 index 0000000..a37f5e0 --- /dev/null +++ b/java/1189_Maximum_Number_of_Balloons.java @@ -0,0 +1,19 @@ +class Solution { + public int maxNumberOfBalloons(String text) { + HashMap map = new HashMap<>(); + + for (char ch : text.toCharArray()) { + map.put(ch, map.getOrDefault(ch, 0) + 1); + } + + int res = Integer.MAX_VALUE; + + res = Math.min(res, map.getOrDefault('b', 0)); + res = Math.min(res, map.getOrDefault('a', 0)); + res = Math.min(res, map.getOrDefault('n', 0)); + res = Math.min(res, map.getOrDefault('l', 0) / 2); + res = Math.min(res, map.getOrDefault('o', 0) / 2); + + return res; + } +} diff --git a/python/1374_Generate_a_String_With_Characters_That_Have_Odd_Counts_Solution.py b/python/1374_Generate_a_String_With_Characters_That_Have_Odd_Counts_Solution.py new file mode 100644 index 0000000..067dfa0 --- /dev/null +++ b/python/1374_Generate_a_String_With_Characters_That_Have_Odd_Counts_Solution.py @@ -0,0 +1,12 @@ +''' +Given an integer n, return a string with n characters such that each character in such string occurs an odd number of times. +The returned string must contain only lowercase English letters. If there are multiples valid strings, return any of them. + Input: n = 4 +Output: "pppz" +''' +class Solution: + def generateTheString(self, n: int) -> str: + if n%2==0: + return "a" * (n-1) + "b" + else: + return "a" * n From d984eb0629e7418d27c800c181a50fee0fd829b1 Mon Sep 17 00:00:00 2001 From: Bithiah Koshy <63845509+vintagemind@users.noreply.github.com> Date: Sun, 13 Mar 2022 16:41:10 +1100 Subject: [PATCH 096/119] Made syntax changes to 005_Longest_Palindromic_Substring.py (#51) Contributed by @vintagemind --- python/005_Longest_Palindromic_Substring.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python/005_Longest_Palindromic_Substring.py b/python/005_Longest_Palindromic_Substring.py index 5f9ebe2..5086547 100644 --- a/python/005_Longest_Palindromic_Substring.py +++ b/python/005_Longest_Palindromic_Substring.py @@ -85,4 +85,4 @@ def longestPalindrome(self, s): if __name__ == '__main__': # begin s = Solution() - print s.longestPalindrome("abcbe") \ No newline at end of file + print(s.longestPalindrome("abcbe")) From dfa3459d9510b1d275f750fe7a76160c7c74cd2f Mon Sep 17 00:00:00 2001 From: Qiyuan Gong Date: Tue, 15 Mar 2022 20:08:47 +0800 Subject: [PATCH 097/119] Add 1189 link & javadev's solution --- README.md | 1 + java/1189_Maximum_Number_of_Balloons.java | 21 +++++++++++++++++---- 2 files changed, 18 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 3bcb819..8182c7f 100644 --- a/README.md +++ b/README.md @@ -227,6 +227,7 @@ I'm currently working on [Analytics-Zoo](https://github.com/intel-analytics/anal | 1064 | [Fixed Point](https://leetcode.com/problems/fixed-point/) ♥ | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/1064_Fixed_Point.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/1064_Fixed_Point.java) | 1. Go through index and value, until find solution encounter index < value, O(n) and O(1)
2. Binary search, O(logn) and O(1) | | 1089 | [Duplicate Zeros](https://leetcode.com/problems/duplicate-zeros/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/1089_Duplicate_Zeros.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/1089_Duplicate_Zeros.java) | 2 Pass, store last position and final move steps, O(n) and O(1) | | 1108 | [Defanging an IP Address](https://leetcode.com/problems/defanging-an-ip-address/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/1108_Defanging_an_IP_Address.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/1108_Defanging_an_IP_Address.java) | String manipulate (split, replace and join), O(n) and O(n) | +| 1189 | [Maximum Number of Balloons](https://leetcode.com/problems/maximum-number-of-balloons/) | [Java](https://github.com/qiyuangong/leetcode/blob/master/java/1189_Maximum_Number_of_Balloons.java) | Count letters in `balon`, then find min, O(n) and O(1) | | 1260 | [Shift 2D Grid](https://leetcode.com/problems/shift-2d-grid/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/1260_Shift_2D_Grid.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/1260_Shift_2D_Grid.java) | Final position of each element can be computed according to k, m and n, e.g., k == mn, then don't move, O(mn) and O(mn) | | 1290 | [Convert Binary Number in a Linked List to Integer](https://leetcode.com/problems/convert-binary-number-in-a-linked-list-to-integer/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/1290_Convert_Binary_Number_in_a_Linked_List_to_Integer.py) | Take 2 to the power digit position from right (starting from 0) and multiply it with the digit | | 1304 | [Find N Unique Integers Sum up to Zero](https://leetcode.com/problems/find-n-unique-integers-sum-up-to-zero/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/1304_Find_N_Unique_Integers_Sum_up_to_Zero.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/1304_Find_N_Unique_Integers_Sum_up_to_Zero.java) | [1,n-1] and its negative sum | diff --git a/java/1189_Maximum_Number_of_Balloons.java b/java/1189_Maximum_Number_of_Balloons.java index a37f5e0..4564c55 100644 --- a/java/1189_Maximum_Number_of_Balloons.java +++ b/java/1189_Maximum_Number_of_Balloons.java @@ -1,19 +1,32 @@ class Solution { public int maxNumberOfBalloons(String text) { HashMap map = new HashMap<>(); - + for (char ch : text.toCharArray()) { map.put(ch, map.getOrDefault(ch, 0) + 1); } - + int res = Integer.MAX_VALUE; - + res = Math.min(res, map.getOrDefault('b', 0)); res = Math.min(res, map.getOrDefault('a', 0)); res = Math.min(res, map.getOrDefault('n', 0)); res = Math.min(res, map.getOrDefault('l', 0) / 2); res = Math.min(res, map.getOrDefault('o', 0) / 2); - + return res; } + + /* + // by @javadev + public int maxNumberOfBalloons(String text) { + int[] counts = new int[26]; + for (char c : text.toCharArray()) { + counts[c - 'a']++; + } + return Math.min( + counts[0], + Math.min( + counts[1], Math.min(counts[11] / 2, Math.min(counts[14] / 2, counts[13])))); + }*/ } From a7808fbba1a349b740c793b9d35a7f816c50950f Mon Sep 17 00:00:00 2001 From: Danny Sepler Date: Mon, 20 Jun 2022 09:36:54 -0400 Subject: [PATCH 098/119] 002 Add Two Numbers: Remove floating point errors (#56) Contributed by @dannysepler --- python/002_Add_Two_Numbers.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python/002_Add_Two_Numbers.py b/python/002_Add_Two_Numbers.py index e452aa7..0e91587 100644 --- a/python/002_Add_Two_Numbers.py +++ b/python/002_Add_Two_Numbers.py @@ -51,7 +51,7 @@ def addTwoNumbers(self, l1, l2): l2 = l2.next curr.next = ListNode(val % 10) curr = curr.next - carry = val / 10 + carry = int(val / 10) if carry > 0: curr.next = ListNode(carry) return head.next From 250a8c7c7577d8da32b54aeb01e001bbb0eb346a Mon Sep 17 00:00:00 2001 From: Danny Sepler Date: Wed, 22 Jun 2022 20:39:07 -0400 Subject: [PATCH 099/119] 207: Course Schedule (#57) * Add 207_Course_Schedule.py, detect cycle Contributed by @dannysepler --- README.md | 1 + python/207_Course_Schedule.py | 28 ++++++++++++++++++++++++++++ 2 files changed, 29 insertions(+) create mode 100644 python/207_Course_Schedule.py diff --git a/README.md b/README.md index 8182c7f..de13851 100644 --- a/README.md +++ b/README.md @@ -86,6 +86,7 @@ I'm currently working on [Analytics-Zoo](https://github.com/intel-analytics/anal | 200 | [Number of Islands](https://leetcode.com/problems/number-of-islands/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/200_Number_of_Islands.py) | 1. Quick union find, O(nlogn) and O(n^2)
2. BFS with marks, O(n^2) and O(1) | | 204 | [Count Primes](https://leetcode.com/problems/count-primes/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/204_Count_Primes.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/204_Count_Primes.java) [CPP](https://github.com/qiyuangong/leetcode/blob/master/cpp/204_Count_Primes.cpp) | [Sieve of Eratosthenes](https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes#Algorithm_complexity), O(nloglogn) and O(n) | | 206 | [Reverse Linked List](https://leetcode.com/problems/reverse-linked-list/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/206_Reverse_Linked_List.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/206_Reverse_Linked_List.java) [CPP](https://github.com/qiyuangong/leetcode/blob/master/cpp/206_Reverse_Linked_List.cpp) | 1. Stack, O(n) and O(n)
2. Traverse on prev and curr, then curr.next = prev, O(n) and O(1)
3. Recursion, O(n) and O(1) | +| 207 | [Course Schedule](https://leetcode.com/problems/course-schedule/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/207_Course_Schedule.py) | Cycle detection problem | | 213 | [House Robber II](https://leetcode.com/problems/house-robber-ii/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/213_House_Robber_II.py) | f(k) = max(f(k – 2) + num[k], max(dp[0~ls-2],dp[1~ls-1], O(n) and O(1)| | 215 | [Kth Largest Element in an Array](https://leetcode.com/problems/kth-largest-element-in-an-array/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/215_Kth_Largest_Element_in_an_Array.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/215_Kth_Largest_Element_in_an_Array.java) | 1. Sort, O(n) and O(n)
2. Heap, O(nlgk) and O(n)
3. Quick selection, O(klgn) and O(n)| | 216 | [Combination Sum III](https://leetcode.com/problems/combination-sum-iii/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/216_Combination_Sum_III.py) | Generate all combinations of length k and keep those that sum to n| diff --git a/python/207_Course_Schedule.py b/python/207_Course_Schedule.py new file mode 100644 index 0000000..0388fd9 --- /dev/null +++ b/python/207_Course_Schedule.py @@ -0,0 +1,28 @@ +from collections import defaultdict + +class Solution(object): + # Adapted from https://youtu.be/yPldqMtg-So + + def hasCycle(self, course, deps, visited, tracker): + visited.add(course) + tracker.add(course) + for n in deps[course]: + if n not in visited and self.hasCycle(n, deps, visited, tracker): + return True + if n in tracker: + return True + tracker.remove(course) + return False + + def canFinish(self, numCourses, prerequisites): + deps = defaultdict(set) + for course, pre in prerequisites: + deps[pre].add(course) + + visited = set() + for course in range(numCourses): + tracker = set() + if self.hasCycle(course, deps, visited, tracker): + return False + + return True From 69d3c1139aebf96b111de28954e9e714ebe3ae01 Mon Sep 17 00:00:00 2001 From: Naveen <70085321+naveen701526@users.noreply.github.com> Date: Thu, 23 Jun 2022 06:14:33 +0530 Subject: [PATCH 100/119] Add 013_roman_to_integer file in java (#54) * Roman in table Contributed by @naveen701526 --- java/013_Roman_to_Integer.java | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 java/013_Roman_to_Integer.java diff --git a/java/013_Roman_to_Integer.java b/java/013_Roman_to_Integer.java new file mode 100644 index 0000000..90393e6 --- /dev/null +++ b/java/013_Roman_to_Integer.java @@ -0,0 +1,23 @@ +class Solution { + public int romanToInt(String s) { + int[] arr = new int['A' + 26]; + arr['I'] = 1; + arr['V'] = 5; + arr['X'] = 10; + arr['L'] = 50; + arr['C'] = 100; + arr['D'] = 500; + arr['M'] = 1000; + + int result = 0; + int prev = 0; + + for (int i = s.length() - 1; i >= 0; i--) { + int current = arr[s.charAt(i)]; + result += prev > current ? -current : current; + prev = current; + } + + return result; + } +} \ No newline at end of file From d8ab69f400e69ad87abafeb3e938d70e79144667 Mon Sep 17 00:00:00 2001 From: Danny Sepler Date: Sun, 17 Jul 2022 10:50:40 -0400 Subject: [PATCH 101/119] Implement 380, 441, and 981 (#59) * 380_Insert_Delete_GetRandom.py * 441_Arranging_Coins.py * 981_Time_Based_Store.py Contributed by @dannysepler --- README.md | 3 +++ python/380_Insert_Delete_GetRandom.py | 33 +++++++++++++++++++++++++++ python/441_Arranging_Coins.py | 7 ++++++ python/981_Time_Based_Store.py | 26 +++++++++++++++++++++ 4 files changed, 69 insertions(+) create mode 100644 python/380_Insert_Delete_GetRandom.py create mode 100644 python/441_Arranging_Coins.py create mode 100644 python/981_Time_Based_Store.py diff --git a/README.md b/README.md index de13851..2d866fc 100644 --- a/README.md +++ b/README.md @@ -133,6 +133,7 @@ I'm currently working on [Analytics-Zoo](https://github.com/intel-analytics/anal | 368 | [Largest Divisible Subset](https://leetcode.com/problems/largest-divisible-subset/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/368_Largest_Divisible_Subset.py) | Sort and generate x subset with previous results, O(n^2) and O(n^2) | | 369 | [Plus One Linked List](https://leetcode.com/problems/plus-one-linked-list/) ♥ | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/369_Plus_One_Linked_List.py) | 1. Stack or list that store the list, O(n) and O(n)
2. Two points, the first to the tail, the second to the latest place that is not 9, O(n) and O(1) | | 370 | [Range Addition](https://leetcode.com/problems/range-addition/) ♥ | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/370_Range_Addition.py) | Interval problem with cumulative sums, O(n + k) and O(n) | +| 380 | [Insert, Delete, Get Random](https://leetcode.com/problems/insert-delete-getrandom-o1/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/380_Insert_Delete_GetRandom.py)| Uses both a list of nums and a list of their locations | | 383 | [Ransom Note](https://leetcode.com/problems/ransom-note/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/383_Ransom_Note.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/383_Ransom_Note.java) | Get letter frequency (table or hash map) of magazine, then check randomNote frequency | | 384 | [Shuffle an Array](https://leetcode.com/problems/shuffle-an-array/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/384_Shuffle_an_Array.py) | [Fisher–Yates shuffle](https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle), O(n) and O(n) | | 387 | [First Unique Character in a String](https://leetcode.com/problems/first-unique-character-in-a-string/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/387_First_Unique_Character_in_a_String.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/387_First_Unique_Character_in_a_String.java) | Get frequency of each letter, return first letter with frequency 1, O(n) and O(1) | @@ -153,6 +154,7 @@ I'm currently working on [Analytics-Zoo](https://github.com/intel-analytics/anal | 434 | [Number of Segments in a String](https://leetcode.com/problems/number-of-segments-in-a-string/description/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/434_Number_of_Segments_in_a_String.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/434_Number_of_Segments_in_a_String.java) | 1. trim &split
2. Find segment in place | | 437 | [Path Sum III](https://leetcode.com/problems/path-sum-iii/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/437_Path_Sum_III.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/437_Path_Sum_III.java) | 1. Recursively travese the whole tree, O(n^2)
2. Cache sum in Hash based on solution 1. Note that if sum(A->B)=target, then sum(root->a)-sum(root-b)=target.| | 438 | [Find All Anagrams in a String](https://leetcode.com/problems/find-all-anagrams-in-a-string/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/438_Find_All_Anagrams_in_a_String.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/438_Find_All_Anagrams_in_a_String.java) | Build a char count list with 26-256 length. Note that this list can be update when going through the string. O(n) and O(1) | +| 441 | [Arranging Coins](https://leetcode.com/problems/arranging-coins/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/441_Arranging_Coins.py) | O(n) time. | | 443 | [String Compression](https://leetcode.com/problems/string-compression/description/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/443_String_Compression.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/443_String_Compression.java) | Maintain curr, read, write and anchor (start of this char). | | 448 | [Find All Numbers Disappeared in an Array](https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/448_Find_All_Numbers_Disappeared_in_an_Array.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/448_Find_All_Numbers_Disappeared_in_an_Array.java) | Value (1, n) and index (0, n-1). Mark every value postion as negative. Then, the remain index with positive values are result. O(n)| | 453 | [Number of Segments in a String](https://leetcode.com/problems/minimum-moves-to-equal-array-elements/description/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/453_Minimum_Moves_to_Equal_Array_Elements.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/453_Minimum_Moves_to_Equal_Array_Elements.java) | Each move is equal to minus one element in array, so the answer is the sum of all elements after minus min. | @@ -225,6 +227,7 @@ I'm currently working on [Analytics-Zoo](https://github.com/intel-analytics/anal | 962 | [Maximum Width Ramp](https://leetcode.com/problems/maximum-width-ramp/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/962_Maximum_Width_Ramp.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/962_Maximum_Width_Ramp.java) | 1. Sort index by value, then transfer problem into finding max gap between index, O(nlogn) and O(1)
2. Binary Search for candicates, O(nlogn) and O(n) | | 977 | [Squares of a Sorted Array](https://leetcode.com/problems/squares-of-a-sorted-array/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/977_Squares_of_a_Sorted_Array.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/977_Squares_of_a_Sorted_Array.java) | 1. Sort, O(nlogn) and O(n)
2. Two point, O(n) and O(n) | | 973 | [K Closest Points to Origin](https://leetcode.com/problems/k-closest-points-to-origin/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/973_K_Closest_Points_to_Origin.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/973_K_Closest_Points_to_Origin.java) | 1. Sort and get 0-K, O(nlogn) and O(1)
2. Min Heap, O(nlogk) and O(k) | +| 981 | [Time Based Key-Value Store](https://leetcode.com/problems/time-based-key-value-store/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/981_Time_Based_Store.py) | Get: O(log(n)) time
Set: O(1) time | | 1064 | [Fixed Point](https://leetcode.com/problems/fixed-point/) ♥ | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/1064_Fixed_Point.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/1064_Fixed_Point.java) | 1. Go through index and value, until find solution encounter index < value, O(n) and O(1)
2. Binary search, O(logn) and O(1) | | 1089 | [Duplicate Zeros](https://leetcode.com/problems/duplicate-zeros/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/1089_Duplicate_Zeros.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/1089_Duplicate_Zeros.java) | 2 Pass, store last position and final move steps, O(n) and O(1) | | 1108 | [Defanging an IP Address](https://leetcode.com/problems/defanging-an-ip-address/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/1108_Defanging_an_IP_Address.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/1108_Defanging_an_IP_Address.java) | String manipulate (split, replace and join), O(n) and O(n) | diff --git a/python/380_Insert_Delete_GetRandom.py b/python/380_Insert_Delete_GetRandom.py new file mode 100644 index 0000000..f222d7d --- /dev/null +++ b/python/380_Insert_Delete_GetRandom.py @@ -0,0 +1,33 @@ +import random + +class RandomizedSet(object): + + def __init__(self): + self.num_to_idx = {} + self.num_list = [] + + def insert(self, val): + if val in self.num_to_idx: + return False + else: + self.num_list.append(val) + self.num_to_idx[val] = len(self.num_list) - 1 + return True + + def remove(self, val): + if val not in self.num_to_idx: + return False + + idx = self.num_to_idx[val] + last = self.num_list[-1] + + # swap last elem to current spot so you can pop the end + self.num_list[idx] = last + self.num_list.pop() + self.num_to_idx[last] = idx + del self.num_to_idx[val] + + return True + + def getRandom(self): + return random.choice(self.num_list) diff --git a/python/441_Arranging_Coins.py b/python/441_Arranging_Coins.py new file mode 100644 index 0000000..eeeb750 --- /dev/null +++ b/python/441_Arranging_Coins.py @@ -0,0 +1,7 @@ +class Solution(object): + def arrangeCoins(self, n): + level = 0 + while n > level: + level += 1 + n -= level + return level diff --git a/python/981_Time_Based_Store.py b/python/981_Time_Based_Store.py new file mode 100644 index 0000000..3320458 --- /dev/null +++ b/python/981_Time_Based_Store.py @@ -0,0 +1,26 @@ +from collections import defaultdict + +class TimeMap(object): + + def __init__(self): + self.store = defaultdict(list) + + def set(self, key, value, timestamp): + self.store[key].append((value, timestamp)) + + def get(self, key, timestamp): + values = self.store.get(key, []) + res = "" + + l = 0 + r = len(values) - 1 + + while l <= r: + mid = (l + r) // 2 + if values[mid][1] <= timestamp: + l = mid + 1 + res = values[mid][0] + else: + r = mid - 1 + + return res From aaec50a10beb8dd3d4726c94431656333fc473ba Mon Sep 17 00:00:00 2001 From: BHwi <43560497+BHwi@users.noreply.github.com> Date: Thu, 29 Sep 2022 20:12:01 +0900 Subject: [PATCH 102/119] Added Java solutions for 17, 22 / Python solutions for 2413, 2409, 1909 (#60) * 2413_Smallest_Even_Multiple * 2409_Count_Days_Spent_Together * 1909_Remove_One_Element_to_Make_the_Array_Strictly_Increasing In a brute-force way. * Add 17_Letter_Combinations_of_a_Phone_Number.java * Add 22_Generate_Parentheses.java Contributed by @BHwi BHwi Co-authored-by: LONGNEW <40235475+LONGNEW@users.noreply.github.com> --- ...Letter_Combinations_of_a_Phone_Number.java | 40 +++++++++++++++++++ java/22_Generate_Parentheses.java | 26 ++++++++++++ ...t_to_Make_the_Array_Strictly_Increasing.py | 37 +++++++++++++++++ python/2409_Count_Days_Spent_Together.py | 38 ++++++++++++++++++ python/2413_Smallest_Even_Multiple.py | 15 +++++++ 5 files changed, 156 insertions(+) create mode 100644 java/17_Letter_Combinations_of_a_Phone_Number.java create mode 100644 java/22_Generate_Parentheses.java create mode 100644 python/1909_Remove_One_Element_to_Make_the_Array_Strictly_Increasing.py create mode 100644 python/2409_Count_Days_Spent_Together.py create mode 100644 python/2413_Smallest_Even_Multiple.py diff --git a/java/17_Letter_Combinations_of_a_Phone_Number.java b/java/17_Letter_Combinations_of_a_Phone_Number.java new file mode 100644 index 0000000..7588d2c --- /dev/null +++ b/java/17_Letter_Combinations_of_a_Phone_Number.java @@ -0,0 +1,40 @@ +class Solution { + // make list for return. + public ArrayList list = new ArrayList<>(); + // make array for get phone number's characters. + public char[][] arr = { + {'0', '0', '0', '-'}, + {'0', '0', '0', '-'}, + {'a', 'b', 'c', '-'}, + {'d', 'e', 'f', '-'}, + {'g', 'h', 'i', '-'}, + {'j', 'k', 'l', '-'}, + {'m', 'n', 'o', '-'}, + {'p', 'q', 'r', 's'}, + {'t', 'u', 'v', '-'}, + {'w', 'x', 'y', 'z'}, + }; + + // main function + public List letterCombinations(String digits) { + addString(digits, 0, ""); + return list; + } + + // axiom : if input == "", return [] + // if index == digits.length(), add str in list + // else do loop number's character, and function recursion. + public void addString(String digits, int index, String str) { + if(digits.equals("")) return; + if(index == digits.length()) { + list.add(str); + } + else { + for(int i = 0; i < 4; i++) { + int number = Integer.parseInt(digits.charAt(index) + ""); + if(arr[number][i] == '-') continue; + addString(digits, index + 1, str + arr[number][i]); + } + } + } +} diff --git a/java/22_Generate_Parentheses.java b/java/22_Generate_Parentheses.java new file mode 100644 index 0000000..1667c87 --- /dev/null +++ b/java/22_Generate_Parentheses.java @@ -0,0 +1,26 @@ +class Solution { + // main function + public List generateParenthesis(int n) { + ArrayList list = new ArrayList<>(); + rec(list, "(", n - 1, n); + return list; + } + + // axiom : if start == end == 0, add str in list. + // IDEA : + // In well-formed parentheses + // close character(")") has to be bigger than open character("(") + // So, we can solve this problem with recursion. + public void rec(List list, String str, int start, int end) { + if(start == 0 && end == 0) { + list.add(str); + } + + if(start > 0) { + rec(list, str + "(", start - 1, end); + } + if(end > start) { + rec(list, str + ")", start, end - 1); + } + } +} diff --git a/python/1909_Remove_One_Element_to_Make_the_Array_Strictly_Increasing.py b/python/1909_Remove_One_Element_to_Make_the_Array_Strictly_Increasing.py new file mode 100644 index 0000000..5ae5c6f --- /dev/null +++ b/python/1909_Remove_One_Element_to_Make_the_Array_Strictly_Increasing.py @@ -0,0 +1,37 @@ +class Solution: + def canBeIncreasing(self, nums: List[int]) -> bool: + # bruteforcing the whole idxes. + canBe = [0] * len(nums) + + # choosing the idx that will be removed. + for bannedIdx in range(len(nums)): + Flag = 1 + + # if the bannedIdx is 0 than the startIdx will be 2. + # when bannedIdx is 0, idx 2 is the first element that has a previous element. + # In other cases, idx 1 is the one. + for i in range(1 if bannedIdx != 0 else 2, len(nums)): + # if i is bannedIdx than just skip it. + if i == bannedIdx: + continue + + # if the previous element is banned. + # compare [i] with [i - 2] + if i - 1 == bannedIdx: + if nums[i] <= nums[i - 2]: + Flag = 0 + break + continue + + # compare [i] with [i - 1] + if nums[i] <= nums[i - 1]: + Flag = 0 + break + + # end of loop we will get Flag that has a 0 or 1 value. + canBe[bannedIdx] = Flag + + if sum(canBe) > 0: + return True + return False + diff --git a/python/2409_Count_Days_Spent_Together.py b/python/2409_Count_Days_Spent_Together.py new file mode 100644 index 0000000..13747f1 --- /dev/null +++ b/python/2409_Count_Days_Spent_Together.py @@ -0,0 +1,38 @@ +class Solution: + def countDaysTogether(self, arriveAlice: str, leaveAlice: str, arriveBob: str, leaveBob: str) -> int: + # split the dates to month and day. + arriveAliceMonth, arriveAliceDay = map(int, arriveAlice.split("-")) + leaveAliceMonth, leaveAliceDay = map(int, leaveAlice.split("-")) + arriveBobMonth, arriveBobDay = map(int, arriveBob.split("-")) + leaveBobMonth, leaveBobDay = map(int, leaveBob.split("-")) + + # prefixOfCalendar : initialize the calendar and in the past we will use this to convert month to day, index is 1 - based + # spentTogether, aliceSpent : work as cache list. and index is 1 - based + calendar = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] + prefixOfCalendar = [0] * 13 + totalDates = sum(calendar) + spentTogether, aliceSpent = [0] * (totalDates + 1), [0] * (totalDates + 1) + + # calculate the prefix of calendar + for i in range(1, len(calendar)): + prefixOfCalendar[i] = prefixOfCalendar[i - 1] + calendar[i] + + # if the string is "01-15", it can be treat as 15 days. + # if the string is "02-27", it can be treat as 58 days. + # So, it can be "prefixOfCalendar[month - 1] + day" + # and in the problem it includes the leaveDate so +1 need to be in . + arriveAliceTotal = prefixOfCalendar[arriveAliceMonth - 1] + arriveAliceDay + leaveAliceTotal = prefixOfCalendar[leaveAliceMonth - 1] + leaveAliceDay + for i in range(arriveAliceTotal, leaveAliceTotal + 1): + aliceSpent[i] += 1 + + # check the aliceSpent[i] is True. + # if it is, they spentTogether is True too. + arriveBobTotal = prefixOfCalendar[arriveBobMonth - 1] + arriveBobDay + leaveBobTotal = prefixOfCalendar[leaveBobMonth - 1] + leaveBobDay + for i in range(arriveBobTotal, leaveBobTotal + 1): + if aliceSpent[i]: + spentTogether[i] += 1 + + # I used list because of this sum function. + return sum(spentTogether) diff --git a/python/2413_Smallest_Even_Multiple.py b/python/2413_Smallest_Even_Multiple.py new file mode 100644 index 0000000..02b723f --- /dev/null +++ b/python/2413_Smallest_Even_Multiple.py @@ -0,0 +1,15 @@ +class Solution: + def smallestEvenMultiple(self, n: int) -> int: + """ + n : positive integer + return : smallest positive integer that is a multiple of both 2 and n + """ + if n % 2 == 0: + # if n is alreay muliply by 2 + # return itself + return n + + # if previous condition is false + # n * 2 is the smallest positive integer. + return n * 2 + From 183f57fae70231251d39261272de11ae86650046 Mon Sep 17 00:00:00 2001 From: Subin Kim <70996958+green-study@users.noreply.github.com> Date: Sun, 2 Oct 2022 10:07:12 +0900 Subject: [PATCH 103/119] Added java solution for 14 / python solution for 2420 (#61) * Added java solution for 14 / python solution for 2420 * Added : 055_Jump_Game.java Co-authored-by: LONGNEW <40235475+LONGNEW@users.noreply.github.com> Co-authored-by: BHwi --- README.md | 3 ++ java/014_Longest_Common_Prefix.java | 33 +++++++++++++++++++ java/055_Jump_Game.java | 49 ++++++++++++++++++++++++++++ python/2420_Find_All_Good_Indices.py | 38 +++++++++++++++++++++ 4 files changed, 123 insertions(+) create mode 100644 java/014_Longest_Common_Prefix.java create mode 100644 java/055_Jump_Game.java create mode 100644 python/2420_Find_All_Good_Indices.py diff --git a/README.md b/README.md index 2d866fc..dd66ade 100644 --- a/README.md +++ b/README.md @@ -242,7 +242,10 @@ I'm currently working on [Analytics-Zoo](https://github.com/intel-analytics/anal | 1365 | [How Many Numbers Are Smaller Than the Current Number](https://leetcode.com/problems/how-many-numbers-are-smaller-than-the-current-number/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/1365_How_Many_Numbers_Are_Smaller_Than_the_Current_Number.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/1365_How_Many_Numbers_Are_Smaller_Than_the_Current_Number.java) | 1. Sort and get position in sorted nums, O(nlogn) and O(n)
2. Fill count into 0-100, O(n) and O(1) | | 1480 | [Running Sum of 1d Array](https://leetcode.com/problems/running-sum-of-1d-array/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/1480_Running_Sum_of_1d_Array.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/1480_Running_Sum_of_1d_Array.java) | 1. Go through the array, O(n) and O(1)
2. Accumulate API | | 1539 | [Kth Missing Positive Number](https://leetcode.com/problems/kth-missing-positive-number/) | [Java](https://github.com/qiyuangong/leetcode/blob/master/java/1539_Kth_Missing_Positive_Number.java) | Binary search, num of missing = arr[i]-i-1 | +| 1909 | [Remove One Element to Make the Array Strictly Increasing](https://leetcode.com/problems/remove-one-element-to-make-the-array-strictly-increasing/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/1909_Remove_One_Element_to_Make_the_Array_Strictly_Increasing.py )| Use brute-force. O( (nums.length)2) | | 1981 | [Minimize the Difference Between Target and Chosen Elements](https://leetcode.com/problems/minimize-the-difference-between-target-and-chosen-elements/) | [Java](https://github.com/qiyuangong/leetcode/blob/master/java/1981_Minimize_the_Difference_Between_Target_and_Chosen_Elements.java) | DP memo[row][sum] to avoid recomputing | +| 2409 | [Count Days Spent Together](https://leetcode.com/problems/count-days-spent-together/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/2409_Count_Days_Spent_Together.py)| Use month as a day | +| 2413 | [Smallest Even Multiple](https://leetcode.com/problems/smallest-even-multiple/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/2413_Smallest_Even_Multiple.py)| Check the n is multiply by 2 | | # | To Understand | |---| ----- | diff --git a/java/014_Longest_Common_Prefix.java b/java/014_Longest_Common_Prefix.java new file mode 100644 index 0000000..4ff7134 --- /dev/null +++ b/java/014_Longest_Common_Prefix.java @@ -0,0 +1,33 @@ +//014_Longest_Common_Prefix.java +class Solution { + public String longestCommonPrefix(String[] strs) { + String result =""; + String temp = ""; + int c = 0; //move first point + boolean check = true; + while(true){ + for(int i = 0; i=strs[i].length()){ + check = false; + break; + } + if(i==0){ //temp -> check same Character + temp = Character.toString(strs[0].charAt(c)); + } + if(!temp.equals(Character.toString(strs[i].charAt(c)))){ + check = false; + break; + } + if(i==strs.length-1){ + result += temp; + } + } + if(!check){ + break; + } + c++; + } + return result; + + } +} \ No newline at end of file diff --git a/java/055_Jump_Game.java b/java/055_Jump_Game.java new file mode 100644 index 0000000..50971d4 --- /dev/null +++ b/java/055_Jump_Game.java @@ -0,0 +1,49 @@ +import java.util.*; + +class Solution { + public boolean canJump(int[] nums) { + /* + * Constraints + * 1 <= nums.length <= 10^4 + * 0 <= nums[i] <= 10^5 + * + * Solution + * 1. Use BFS Algorithm. + * - reason 1 : have to ignore array which is not visited. + * - reason 2 : we have to visit all possible array from array[start]. + */ + + int N = nums.length; + ArrayDeque q = new ArrayDeque<>(); + boolean[] visited = new boolean[N]; + + // First, add first array index. + // And, set visited[first_index] to true. + q.add(0); + visited[0] = true; + + // Axiom : if N is 1, result is true. + if(N == 1) return true; + + // BFS algorithm + while(!q.isEmpty()) { + int cur = q.poll(); + + // find cur + 1 to cur + nums[cur] + for(int i = 1; i <= nums[cur]; i++) { + if(cur + i >= N - 1) return true; + int next = Math.min(cur + i, N - 1); + + // set visited[next] to true and add index into queue. + // because of time limit(No overlap steps.) + if(!visited[next]) { + visited[next] = true; + q.add(next); + } + } + } + + return false; + + } +} \ No newline at end of file diff --git a/python/2420_Find_All_Good_Indices.py b/python/2420_Find_All_Good_Indices.py new file mode 100644 index 0000000..44498cc --- /dev/null +++ b/python/2420_Find_All_Good_Indices.py @@ -0,0 +1,38 @@ +#2420_Find_All_Good_Indices.py +class Solution: + def goodIndices(self, nums: List[int], k: int) -> List[int]: + # posi : count the increasing idxes + # nega : count the decreasing idxes + posi, nega = [0], [0] + + for i in range(1, len(nums)): + diff = nums[i] - nums[i - 1] + + posi.append(posi[i - 1]) + nega.append(nega[i - 1]) + + # if diff show positive or negative + # then the value will updated + if diff > 0: + posi[i] += 1 + elif diff < 0: + nega[i] += 1 + + # ans : count the idxes that + # before k element is non increasing + # after k element is non decreasing + ans = [] + for i in range(k, len(nums) - k): + if i + k >= len(nums): + break + + # check the condition with + # for after, nega[i + 1], nega[i + k] is the two to check + # for brfore, posi[i - 1], posi[i - k] is the two to check + if nega[i + k] - nega[i + 1] > 0: + continue + if posi[i - 1] - posi[i - k] > 0: + continue + + ans.append(i) + return ans \ No newline at end of file From a4519f360108598d27065a63c4b3d8ba24823519 Mon Sep 17 00:00:00 2001 From: Shekhar verma Date: Fri, 7 Oct 2022 05:20:03 +0530 Subject: [PATCH 104/119] Added solution for 392_is_subsequence (#62) * Added solution for 392_is_subsequence * Fixed the code style Co-authored-by: Shekhar-Inochi --- python/392_Is_Subsequence.py | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 python/392_Is_Subsequence.py diff --git a/python/392_Is_Subsequence.py b/python/392_Is_Subsequence.py new file mode 100644 index 0000000..5cf66c0 --- /dev/null +++ b/python/392_Is_Subsequence.py @@ -0,0 +1,11 @@ +class Solution: + def isSubsequence(self, s: str, t: str) -> bool: + for a in s: + if a in t: + for b in range(0, len(t)): + if a==t[b]: + t=t[b+1:] + break + else: + return(False) + return(True) From 81abc9f71ef6b05312aa0500388cd017d2cbfc51 Mon Sep 17 00:00:00 2001 From: parkjonggyeong18 <81209336+parkjonggyeong18@users.noreply.github.com> Date: Sat, 8 Oct 2022 11:51:15 +0900 Subject: [PATCH 105/119] Create 732_My_Calendar_III.py (#64) * Added solution for Add 732_My_Calendar_III.py problem from Leetcode Contributed by @parkjonggyeong18 --- python/732_My_Calendar_III.py | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 python/732_My_Calendar_III.py diff --git a/python/732_My_Calendar_III.py b/python/732_My_Calendar_III.py new file mode 100644 index 0000000..6347108 --- /dev/null +++ b/python/732_My_Calendar_III.py @@ -0,0 +1,17 @@ +from sortedcontainers import SortedDict + + +class MyCalendarThree: + def __init__(self): + self.timeline = SortedDict() + + def book(self, start: int, end: int) -> int: + self.timeline[start] = self.timeline.get(start, 0) + 1 + self.timeline[end] = self.timeline.get(end, 0) - 1 + + ans = 0 + activeEvents = 0 + + for count in self.timeline.values(): + activeEvents += count + ans = max(ans, activeEvents) From b11d3c9d07350a681e492e77fd4541fde88a50ec Mon Sep 17 00:00:00 2001 From: LONGNEW <40235475+LONGNEW@users.noreply.github.com> Date: Sat, 8 Oct 2022 22:58:28 +0900 Subject: [PATCH 106/119] Add 2429_Minimize_XOR.py (#63) * Added solution for 2429. Minimize XOR with Python3 Contributed by @LONGNEW --- README.md | 1 + python/2429_Minimize_XOR.py | 44 +++++++++++++++++++++++++++++++++++++ 2 files changed, 45 insertions(+) create mode 100644 python/2429_Minimize_XOR.py diff --git a/README.md b/README.md index dd66ade..df026f7 100644 --- a/README.md +++ b/README.md @@ -246,6 +246,7 @@ I'm currently working on [Analytics-Zoo](https://github.com/intel-analytics/anal | 1981 | [Minimize the Difference Between Target and Chosen Elements](https://leetcode.com/problems/minimize-the-difference-between-target-and-chosen-elements/) | [Java](https://github.com/qiyuangong/leetcode/blob/master/java/1981_Minimize_the_Difference_Between_Target_and_Chosen_Elements.java) | DP memo[row][sum] to avoid recomputing | | 2409 | [Count Days Spent Together](https://leetcode.com/problems/count-days-spent-together/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/2409_Count_Days_Spent_Together.py)| Use month as a day | | 2413 | [Smallest Even Multiple](https://leetcode.com/problems/smallest-even-multiple/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/2413_Smallest_Even_Multiple.py)| Check the n is multiply by 2 | +| 2429 | [Minimize XOR](https://leetcode.com/problems/minimize-xor/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/2429_Minimize_XOR.py.py) | check the num1, num2 with length and replace "0" compare with num1. | | # | To Understand | |---| ----- | diff --git a/python/2429_Minimize_XOR.py b/python/2429_Minimize_XOR.py new file mode 100644 index 0000000..2405feb --- /dev/null +++ b/python/2429_Minimize_XOR.py @@ -0,0 +1,44 @@ +class Solution: + def minimizeXor(self, num1: int, num2: int) -> int: + # remove "0b" in front of num1, num2 + num1, num2 = bin(num1)[2:], bin(num2)[2:] + lenNum1, lenNum2 = len(num1), len(num2) + ones = num2.count("1") + maxLen = max(lenNum1, lenNum2) + + # ans list have elements same as the maxLen + ans = [] + for _ in range(maxLen): + ans.append("0") + + # add "0" in front of the binary numbers to make indexing easier + for _ in range(maxLen - lenNum1): + num1 = "0" + num1 + + for _ in range(maxLen - lenNum2): + num2 = "0" + num2 + + # now make "x XOR num1" minimal + # fill the ans list from index "0" + # because XOR give 0 when the elements are same. + for i in range(len(num1)): + if num1[i] == "1" and ones: + ans[i] = "1" + ones -= 1 + + # if we still got "1" to fill in the ans list. + # "1" need to be fill from the back of ans list. + # to maintain the number small. + for i in range(len(ans) - 1, -1, -1): + if ones < 1: + break + + if ans[i] == "1": + continue + + ans[i] = "1" + ones -= 1 + + # make the ans in string + ans = "".join(ans) + return int(ans, 2) From 354044a9eebe2eb8b520b1966cfbf160b1922fa8 Mon Sep 17 00:00:00 2001 From: BHwi <43560497+BHwi@users.noreply.github.com> Date: Sat, 8 Oct 2022 22:59:10 +0900 Subject: [PATCH 107/119] Add java solution for 34 (#65) * Add 034_Find_First_and_Last_Position_of_Element_in_Sorted_Array.java Contributed by @BHwi --- ...t_Position_of_Element_in_Sorted_Array.java | 59 +++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 java/034_Find_First_and_Last_Position_of_Element_in_Sorted_Array.java diff --git a/java/034_Find_First_and_Last_Position_of_Element_in_Sorted_Array.java b/java/034_Find_First_and_Last_Position_of_Element_in_Sorted_Array.java new file mode 100644 index 0000000..01a70a7 --- /dev/null +++ b/java/034_Find_First_and_Last_Position_of_Element_in_Sorted_Array.java @@ -0,0 +1,59 @@ +class Solution { + /* + Rule 1 + - Given array is sorted in non-decreasing order + + Rule 2 + - Limit time complexity O(log n). + + So I can use Binary Search Algorithm. + */ + public int[] searchRange(int[] nums, int target) { + // initialize arr[0] -> maximum integer, arr[1] -> minimum integer + int[] arr = {100001, -10}; + int s = 0; + int e = nums.length - 1; + + // find minimum index in nums with Binary Search alogorithm + while (s <= e) { + + int mid = (s + e) / 2; + + if(nums[mid] > target) { + e = mid - 1; + } + else if(nums[mid] <= target) { + if(nums[mid] == target) { + arr[0] = Math.min(arr[0], mid); + arr[1] = Math.max(arr[1], mid); + } + s = mid + 1; + } + } + + s = 0; + e = nums.length - 1; + + // find maximum index in nums with Binary Search alogorithm + while(s <= e) { + int mid = (s + e) / 2; + + if(nums[mid] >= target) { + if(nums[mid] == target) { + arr[0] = Math.min(arr[0], mid); + arr[1] = Math.max(arr[1], mid); + } + e = mid - 1; + } + else if(nums[mid] < target) { + s = mid + 1; + } + } + + // if arr data is initial data, set -1. + if(arr[0] == 100001) arr[0] = -1; + if(arr[1] == -10) arr[1] = -1; + + return arr; + } +} From e686121fe601b68816976f2b3b4bb352b31fcf21 Mon Sep 17 00:00:00 2001 From: Subin Kim <70996958+green-study@users.noreply.github.com> Date: Mon, 17 Oct 2022 14:50:33 +0900 Subject: [PATCH 108/119] Added 015_3Sum.java (#67) * Added 015_3Sum.java Contributed by @green-study --- java/015_3Sum.java | 47 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 java/015_3Sum.java diff --git a/java/015_3Sum.java b/java/015_3Sum.java new file mode 100644 index 0000000..cc0a069 --- /dev/null +++ b/java/015_3Sum.java @@ -0,0 +1,47 @@ +//015. 3Sum +class Solution { + public List> threeSum(int[] nums) { + //create result list to store i,j,k + List> result = new LinkedList>(); + + //sorting nums + Arrays.sort(nums); + + for (int i = 0; i < nums.length - 2; i++) { + + int left = i + 1; + int right = nums.length - 1; + + if (i > 0 && nums[i] == nums[i-1]) { + continue; //if nums have same numbers, just check one time. + } + + while (left < right) { + int sum = nums[left] + nums[right] + nums[i]; + + if (sum == 0) { + //if sum == 0, store i,j,k + result.add(Arrays.asList(nums[i], nums[left], nums[right])); + left++; //check anoter case + right--; + //if next number == now number + while (nums[left] == nums[left - 1] && left < right) { + left++; + } + while (nums[right] == nums[right + 1] && left < right) { + right--; + } + } else if (sum > 0) { + //if sum > 0, right--; + right--; + } else { + //if sum < 0, left++; + left++; + } + } + } + + return result; //return result list + } +} + From fefe70c3ce3fee059a5421fcb27333e431fea8d9 Mon Sep 17 00:00:00 2001 From: LONGNEW <40235475+LONGNEW@users.noreply.github.com> Date: Sun, 30 Oct 2022 12:24:08 +0900 Subject: [PATCH 109/119] Add 523_Continuous_Subarray_Sum.py (#68) * Add 523_Continuous_Subarray_Sum.py Contributed by @LONGNEW --- README.md | 1 + python/523_Continuous_Subarray_Sum.py | 20 ++++++++++++++++++++ 2 files changed, 21 insertions(+) create mode 100644 python/523_Continuous_Subarray_Sum.py diff --git a/README.md b/README.md index df026f7..c34ae3b 100644 --- a/README.md +++ b/README.md @@ -166,6 +166,7 @@ I'm currently working on [Analytics-Zoo](https://github.com/intel-analytics/anal | 482 | [License Key Formatting](https://leetcode.com/problems/license-key-formatting/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/482_License_Key_Formatting.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/482_License_Key_Formatting.java) | String processing, lower and len % K, O(n) and O(n) | | 485 | [Max Consecutive Ones](https://leetcode.com/problems/max-consecutive-ones/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/485_Max_Consecutive_Ones.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/485_Max_Consecutive_Ones.java) | Add one when encounter 1, set to 0 when encounter 0, O(n) and O(1) | | 509 | [Fibonacci Number](https://leetcode.com/problems/fibonacci-number/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/509_Fibonacci_Number.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/509_Fibonacci_Number.java) | 1. Recursive, O(n)
2. DP with memo, O(n). Note that N<=30, which means that we can keep a memo from 0 to 30. | +| 523 | [Continuous Subarray Sum](https://leetcode.com/problems/continuous-subarray-sum/description/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/523_Continuous_Subarray_Sum.py) | O(n) solution using dict() | | 538 | [Convert BST to Greater Tree](https://leetcode.com/problems/convert-bst-to-greater-tree/description/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/538_Convert_BST_to_Greater_Tree.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/538_Convert_BST_to_Greater_Tree.java) | Right first DFS with a variable recording sum of node.val and right.val. 1. Recursive.
2. Stack 3. Reverse Morris In-order Traversal | | 541 | [Reverse String II](https://leetcode.com/problems/reverse-string-ii/solution/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/541_Reverse_String_II.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/541_Reverse_String_II.java) | Handle each 2k until reaching end, On(n) and O(n) | | 543 | [Diameter of Binary Tree](https://leetcode.com/problems/diameter-of-binary-tree/description/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/543_Diameter_of_Binary_Tree.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/543_Diameter_of_Binary_Tree.java) | DFS with O(1) for max answer | diff --git a/python/523_Continuous_Subarray_Sum.py b/python/523_Continuous_Subarray_Sum.py new file mode 100644 index 0000000..d37ceeb --- /dev/null +++ b/python/523_Continuous_Subarray_Sum.py @@ -0,0 +1,20 @@ +class Solution: + def checkSubarraySum(self, nums: List[int], k: int) -> bool: + # remeainders[0] = 0 is for when x == 0 + remainders = dict() + remainders[0] = 0 + pre_sum = 0 + + for idx, item in enumerate(nums): + pre_sum += item + remaind = pre_sum % k + + # remainder doesnt exist then it has to be init + # if it exists, then check the prev one has the same remainder + if remaind not in remainders: + remainders[remaind] = idx + 1 + elif remainders[remaind] < idx: + return True + + return False + From 67a842233a5d2d8b13330eb9128c62414d88669f Mon Sep 17 00:00:00 2001 From: Sitesh Pattanaik <12951458+spattk@users.noreply.github.com> Date: Sat, 5 Nov 2022 03:22:39 -0700 Subject: [PATCH 110/119] Added 787 in Java (#69) * Add 787 java. Contributed by @spattk --- java/787_Cheapest_Flight_Within_K_Stops.java | 41 ++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 java/787_Cheapest_Flight_Within_K_Stops.java diff --git a/java/787_Cheapest_Flight_Within_K_Stops.java b/java/787_Cheapest_Flight_Within_K_Stops.java new file mode 100644 index 0000000..9355cf9 --- /dev/null +++ b/java/787_Cheapest_Flight_Within_K_Stops.java @@ -0,0 +1,41 @@ +class Solution { + //using bellman ford + + public void computePrice(int[][]flights, int[] prices, int [] temp){ + for(int[] flight: flights){ + int u = flight[0]; + int v = flight[1]; + int price = flight[2]; + + if(prices[u] != Integer.MAX_VALUE){ + if(prices[u] + price < temp[v]){ + temp[v] = prices[u] + price; + } + } + } + } + + public void copyTempToPrice(int[] prices, int[] temp){ + for(int i=0; i Date: Sat, 5 Nov 2022 19:23:17 +0900 Subject: [PATCH 111/119] Added 026_Remove_Duplicates_from_Sorted_Array.java (#70) * Added 026_Remove_Duplicates_from_Sorted_Array.java Contributed by @green-study --- .../026_Remove_Duplicates_from_Sorted_Array.java | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 java/026_Remove_Duplicates_from_Sorted_Array.java diff --git a/java/026_Remove_Duplicates_from_Sorted_Array.java b/java/026_Remove_Duplicates_from_Sorted_Array.java new file mode 100644 index 0000000..13f03b1 --- /dev/null +++ b/java/026_Remove_Duplicates_from_Sorted_Array.java @@ -0,0 +1,16 @@ +//026. Remove Duplicates from Sorted Array +class Solution { + public int removeDuplicates(int[] nums) { + int index = 1; + + for (int i = 0; i < nums.length - 1; i++) { + if (nums[i] != nums[i + 1]) { + nums[index] = nums[i + 1]; + index++; + } + } + + return index; + } +} + From b3bd2dded4966d9fecde33fcff5ce4ceba8b672b Mon Sep 17 00:00:00 2001 From: BHwi <43560497+BHwi@users.noreply.github.com> Date: Sat, 12 Nov 2022 00:08:04 +0900 Subject: [PATCH 112/119] Added 049_Group_Anagrams.java, 129_Contains_Duplicate_II.java (#72) * Added java solution for 049_Group_Anagrams.java * Added java solution for 129_Contains_Duplicate_II.java Contributed by @BHwi --- java/049_Group_Anagrams.java | 42 +++++++++++++++++++++++++++ java/219_Contains_Duplicate_II.java | 44 +++++++++++++++++++++++++++++ 2 files changed, 86 insertions(+) create mode 100644 java/049_Group_Anagrams.java create mode 100644 java/219_Contains_Duplicate_II.java diff --git a/java/049_Group_Anagrams.java b/java/049_Group_Anagrams.java new file mode 100644 index 0000000..a787625 --- /dev/null +++ b/java/049_Group_Anagrams.java @@ -0,0 +1,42 @@ +class Solution { + public List> groupAnagrams(String[] strs) { + int[][] alphabets = new int[strs.length]['z' - 'a' + 1]; + + for(int i = 0; i < strs.length; i++) { + String str = strs[i]; + + for(int j = 0; j < str.length(); j++) + alphabets[i][str.charAt(j) - 'a']++; + } + + boolean[] visited = new boolean[strs.length]; + + List> answer = new ArrayList<>(); + + for(int i = 0; i < strs.length; i++) { + if(visited[i]) continue; + + List list = new ArrayList<>(); + + for(int j = i; j < strs.length; j++) { + if(visited[j]) continue; + if(isAnagram(alphabets[i], alphabets[j])) { + list.add(strs[j]); + visited[j] = true; + } + } + + answer.add(list); + } + + return answer; + } + + public boolean isAnagram(int[] arr1, int[] arr2) { + for(int i = 0; i < arr1.length; i++) { + if(arr1[i] != arr2[i]) + return false; + } + return true; + } +} diff --git a/java/219_Contains_Duplicate_II.java b/java/219_Contains_Duplicate_II.java new file mode 100644 index 0000000..f88a1a9 --- /dev/null +++ b/java/219_Contains_Duplicate_II.java @@ -0,0 +1,44 @@ +import java.util.*; + +class Solution { + /* + * I have to save indice for each index. + * So I use the HashMap> + */ + + public boolean containsNearbyDuplicate(int[] nums, int k) { + HashMap> map = new HashMap<>(); + + for(int i = 0; i < nums.length; i++) { + if(!map.containsKey(nums[i])) { + map.put(nums[i], new ArrayList<>()); + } + map.get(nums[i]).add(i); + } + + // use Iterator to find appropriate two indice. + // Each list guarantee ascending. + // So list.get(i) and list.get(i + 1) is minimum. + Iterator keys = map.keySet().iterator(); + boolean answer = false; + + while(keys.hasNext()) { + int key = keys.next(); + List list = map.get(key); + + if(list.size() < 2) continue; + + for(int i = 1; i < list.size(); i++) { + int a = list.get(i - 1); + int b = list.get(i); + + if(b - a <= k) { + answer = true; + break; + } + } + if(answer) break; + } + return answer; + } +} From 7951e9e57697ccbd7d968b48d13fe2a4b77d2c85 Mon Sep 17 00:00:00 2001 From: Subin Kim <70996958+green-study@users.noreply.github.com> Date: Sun, 27 Nov 2022 11:56:54 +0900 Subject: [PATCH 113/119] Added 039_Combination_Sum.java (#75) * Added 039_Combination_Sum.java Contributed by @green-study --- java/039_Combination_Sum.java | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 java/039_Combination_Sum.java diff --git a/java/039_Combination_Sum.java b/java/039_Combination_Sum.java new file mode 100644 index 0000000..7a54dd3 --- /dev/null +++ b/java/039_Combination_Sum.java @@ -0,0 +1,29 @@ +//039_Combination_Sum +class Solution { + List> answer = new ArrayList>(); + + public List> combinationSum(int[] candidates, int target) { + int clen =candidates.length; + for (int i = 0; i < clen; i++) { + List tlist = new ArrayList(); + tlist.add(candidates[i]); + backtracking(candidates, i, 1, (target - candidates[i]), tlist); + } + return answer; + } + private void backtracking(int[] candidates, int index, int tsize, int target, List temp) { + if (target == 0) { + answer.add(new ArrayList(temp)); + return; + } + + for (int i = index, len = candidates.length; i < len; i++) { + if (candidates[i] <= target) { + temp.add(candidates[i]); + backtracking(candidates, i, (tsize + 1), (target - candidates[i]), temp); + temp.remove(tsize); + } + } + } +} + From 9c0ddc4ef9522c90ef020cb0608f86acded02f12 Mon Sep 17 00:00:00 2001 From: LONGNEW <40235475+LONGNEW@users.noreply.github.com> Date: Mon, 28 Nov 2022 20:47:14 +0900 Subject: [PATCH 114/119] Update Q1, Q7 answer (#76) * Update 001_Two_Sum.py * Update 007_Reverse_Integer.py Contributed by @LONGNEW --- python/001_Two_Sum.py | 7 +---- python/007_Reverse_Integer.py | 50 ++++++++++------------------------- 2 files changed, 15 insertions(+), 42 deletions(-) diff --git a/python/001_Two_Sum.py b/python/001_Two_Sum.py index e4bd58a..52399a9 100644 --- a/python/001_Two_Sum.py +++ b/python/001_Two_Sum.py @@ -58,9 +58,4 @@ def twoSum(self, nums, target): begin += 1 else: end -= 1 - - -if __name__ == '__main__': - # begin - s = Solution() - print s.twoSum([3, 2, 4], 6) + diff --git a/python/007_Reverse_Integer.py b/python/007_Reverse_Integer.py index a125d47..9f3f20f 100644 --- a/python/007_Reverse_Integer.py +++ b/python/007_Reverse_Integer.py @@ -1,39 +1,17 @@ class Solution: - # @return an integer + def reverse(self, x): + # https://leetcode.com/problems/reverse-integer/ + flag = True if x < 0 else False + if flag: + x = -x + x = str(x)[::-1] - # def reverse(self, x): - # max_int = 2147483647 - # if x == 0: - # return 0 - # isPos = True - # if x < 0: - # x *= (-1) - # isPos = False - # ltemp = [] - # while x != 0: - # temp = x % 10 - # ltemp.append(temp) - # x /= 10 - # result = 0 - # # the main solution - # for t in ltemp: - # result = result * 10 + t - # if result > max_int: - # result = 0 - # if isPos: - # return result - # else: - # return -1 * result + if flag: + x = "-" + x - def reverse(self, x): - # Note that in Python -1 / 10 = -1 - res, isPos = 0, 1 - if x < 0: - isPos = -1 - x = -1 * x - while x != 0: - res = res * 10 + x % 10 - if res > 2147483647: - return 0 - x /= 10 - return res * isPos \ No newline at end of file + value = 2 ** 31 + x = int(x) + if -value <= x < value: + return x + return 0 + From b369d126fe6e5fb5ab5111e745222f34ed3aa533 Mon Sep 17 00:00:00 2001 From: Subin Kim <70996958+green-study@users.noreply.github.com> Date: Sun, 4 Dec 2022 11:34:34 +0900 Subject: [PATCH 115/119] Update 006_ZigZag_conversion.java (#77) * Update 006_ZigZag_conversion.java Contributed by @green-study --- java/006_ZigZag_Conversion.java | 34 ++++++++++++++++++++++++++++++++- 1 file changed, 33 insertions(+), 1 deletion(-) diff --git a/java/006_ZigZag_Conversion.java b/java/006_ZigZag_Conversion.java index ea64188..97e4b1a 100644 --- a/java/006_ZigZag_Conversion.java +++ b/java/006_ZigZag_Conversion.java @@ -1 +1,33 @@ -//TODO \ No newline at end of file +//006_ZigZag_Conversion.java +class Solution { + public String convert(String s, int numRows) { + if(numRows==1) { + return s; + } + + String answer = ""; + String[] str_array = new String[numRows]; + + for(int i=0;i= numRows) { + index = 2*(numRows-1) - index; + } + str_array[index]+=c; + } + + for(int i=0;i Date: Thu, 16 Feb 2023 13:46:59 +0530 Subject: [PATCH 116/119] 2553_Separate_the_Digits_in_an_Array.cpp (#78) * Contributed by @ritikraj018 --- cpp/2553_Separate_the_Digits_in_an_Array.cpp | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 cpp/2553_Separate_the_Digits_in_an_Array.cpp diff --git a/cpp/2553_Separate_the_Digits_in_an_Array.cpp b/cpp/2553_Separate_the_Digits_in_an_Array.cpp new file mode 100644 index 0000000..e88e8c6 --- /dev/null +++ b/cpp/2553_Separate_the_Digits_in_an_Array.cpp @@ -0,0 +1,19 @@ +class Solution { +public: + vector separateDigits(vector& nums) { + vector answer; + int n; + for( int i=0; i < nums.size(); i++){ + n=nums[i]; + vector temp; + while( n>0 ){ + temp.push_back(n%10); + n = n / 10; + } + for(int j= temp.size()-1; j>=0; j--){ + answer.push_back(temp[j]); + } + } + return answer; + } +}; From 5a52cd9b54553d68ee10cfe87044bed79ee5fb93 Mon Sep 17 00:00:00 2001 From: Yuchen Zhou <72342196+ROMEEZHOU@users.noreply.github.com> Date: Tue, 21 Mar 2023 21:31:55 -0400 Subject: [PATCH 117/119] Add a new method for 007_Reverse_Integer.py (#80) * Add a new method for 007 reverse integer Contributed by @ROMEEZHOU --- python/007_Reverse_Integer.py | 39 +++++++++++++++++++++++++---------- 1 file changed, 28 insertions(+), 11 deletions(-) diff --git a/python/007_Reverse_Integer.py b/python/007_Reverse_Integer.py index 9f3f20f..19aeba8 100644 --- a/python/007_Reverse_Integer.py +++ b/python/007_Reverse_Integer.py @@ -1,17 +1,34 @@ class Solution: def reverse(self, x): # https://leetcode.com/problems/reverse-integer/ - flag = True if x < 0 else False - if flag: +# flag = True if x < 0 else False +# if flag: +# x = -x +# x = str(x)[::-1] + +# if flag: +# x = "-" + x + +# value = 2 ** 31 +# x = int(x) +# if -value <= x < value: +# return x +# return 0 + + is_neg = False + if x < 0: x = -x - x = str(x)[::-1] + is_neg = True - if flag: - x = "-" + x + res = 0 + while x > 0: + res *= 10 + res += x % 10 + x //= 10 + if is_neg: + res = -res - value = 2 ** 31 - x = int(x) - if -value <= x < value: - return x - return 0 - + if res < -2**31 or res > 2**31-1: + return 0 + return res + \ No newline at end of file From 9adfbdf343963ee16696aa85f0846fe544105430 Mon Sep 17 00:00:00 2001 From: Ajay <86017484+ajay2614@users.noreply.github.com> Date: Fri, 19 May 2023 13:05:04 +0530 Subject: [PATCH 118/119] Create 442_Find_All_Duplicates_in_an_Array.java (#81) Contributed by @ajay2614 --- java/442_Find_All_Duplicates_in_an_Array.java | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 java/442_Find_All_Duplicates_in_an_Array.java diff --git a/java/442_Find_All_Duplicates_in_an_Array.java b/java/442_Find_All_Duplicates_in_an_Array.java new file mode 100644 index 0000000..b12d6f5 --- /dev/null +++ b/java/442_Find_All_Duplicates_in_an_Array.java @@ -0,0 +1,17 @@ +class Solution { + public List findDuplicates(int[] nums) { + int n = nums.length; + + List ans = new ArrayList<>(); + + for(int i=0;i Date: Tue, 3 Oct 2023 06:22:10 -0400 Subject: [PATCH 119/119] 88. Merge Sorted Array Java (#82) Added the solution to 'Merge Sorted Array' which is number 88 in LeetCode Contributed by @avash-poudel --- java/088_Merge_Sorted_Array.java | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 java/088_Merge_Sorted_Array.java diff --git a/java/088_Merge_Sorted_Array.java b/java/088_Merge_Sorted_Array.java new file mode 100644 index 0000000..95c7c8e --- /dev/null +++ b/java/088_Merge_Sorted_Array.java @@ -0,0 +1,29 @@ +class Solution { + //we are being given two int arrays and two int variables that state the number of elements in each array, respectively + public void merge(int[] nums1, int m, int[] nums2, int n) { + //I am using a counter so that I can iterate through the second array inside the for loop + int counter = 0; + //We know that nums1 is of the size n + m, so we can add all the elements to the array and sort them later + //For loop adds all values of nums2 to the end of nums1 + for(int i=m; i nums1[j+1]){ + int temp = nums1[j+1]; + nums1[j+1] = nums1[j]; + nums1[j] = temp; + } + } + } + //The following function simply prints out everything that is contained within our num1 array + for(int i=0; i