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 5c8a494..c34ae3b 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,11 @@ 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). + +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. @@ -16,11 +20,13 @@ Also, there are open source implementations for basic data structs and algorithm | 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 | -| 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 | +| 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) [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| | 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)| | @@ -78,7 +84,9 @@ 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) | -| 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) | +| 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| @@ -94,7 +102,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) | @@ -125,6 +133,7 @@ Also, there are open source implementations for basic data structs and algorithm | 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) | @@ -136,7 +145,7 @@ Also, there are open source implementations for basic data structs and algorithm | 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) | @@ -145,6 +154,7 @@ Also, there are open source implementations for basic data structs and algorithm | 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. | @@ -152,10 +162,13 @@ 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. | +| 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 | | 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. | @@ -167,6 +180,7 @@ Also, there are open source implementations for basic data structs and algorithm | 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. | @@ -178,8 +192,10 @@ Also, there are open source implementations for basic data structs and algorithm | 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) | +| 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) | @@ -195,6 +211,7 @@ 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] | +| 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). | @@ -211,15 +228,35 @@ Also, there are open source implementations for basic data structs and algorithm | 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) | +| 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 | +| 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) | +| 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 | +| 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 | |---| ----- | | 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) 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; + } +}; 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/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< 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 * i < n; i++) + { + if (isPrimer[i]) + { + for (int j = i * i; j < n; j += i) + { + isPrimer[j] = false; + } + } + } + + int cnt = 0; + for (int i = 2; i < n; i++) + { + if (isPrimer[i]) + { + //cout << i << ", "; + cnt++; + } + } + return cnt; +} + +int main(int argc, char **argv) +{ + int n = 100; + if (argc > 1) + { + n = atoi(argv[1]); + } + + cout << endl + << n << " : " << countPrimes(n) << endl; + + return 0; +} diff --git a/cpp/206_Reverse_Linked_List.cpp b/cpp/206_Reverse_Linked_List.cpp new file mode 100644 index 0000000..84bf495 --- /dev/null +++ b/cpp/206_Reverse_Linked_List.cpp @@ -0,0 +1,30 @@ +/** + * 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; + // 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; + } + curr->next = previous; + return curr; + } +}; 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; + } +}; 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 fizzBuzz(int n) { + int i; + vector s; + for (i = 0; i < n; i++) { + if ((i + 1) % 15 == 0) + s.pb("FizzBuzz"); + else if ((i + 1) % 5 == 0) + s.pb("Buzz"); + else if ((i + 1) % 3 == 0) + s.pb("Fizz"); + else + s.pb(to_string(i + 1)); + } + return s; + } +}; 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..1476598 --- /dev/null +++ b/cpp/668_Kth_Smallest_Number_in_Multiplication_Table.cpp @@ -0,0 +1,29 @@ +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 < x / i ? n : x / i; + if (x / i == 0) + break; + } + return cnt >= k; + } + + int findKthNumber(int n1, int n2, int k) { + 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/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); + } +}; 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 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/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 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/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 + } +} + 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/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; + } +} + 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; + } +} 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); + } + } + } +} + 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/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/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; + } + } +} 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= 0; i--) { + if (arr[i] == 0) { + arr[i + movePos] = 0; + movePos--; + arr[i + movePos] = 0; + } else { + arr[i + movePos] = arr[i]; + } + } + } +} 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/java/1189_Maximum_Number_of_Balloons.java b/java/1189_Maximum_Number_of_Balloons.java new file mode 100644 index 0000000..4564c55 --- /dev/null +++ b/java/1189_Maximum_Number_of_Balloons.java @@ -0,0 +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])))); + }*/ +} 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/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/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/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/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/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/java/1480_Running_Sum_of_1d_Array.java b/java/1480_Running_Sum_of_1d_Array.java new file mode 100644 index 0000000..15ba2ee --- /dev/null +++ b/java/1480_Running_Sum_of_1d_Array.java @@ -0,0 +1,8 @@ +class Solution { + public int[] runningSum(int[] nums) { + if (nums.length <= 1) return nums; + for (int i = 1; i < nums.length; i++) + nums[i] += nums[i - 1]; + return nums; + } +} 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/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/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..02f474a --- /dev/null +++ b/java/1981_Minimize_the_Difference_Between_Target_and_Chosen_Elements.java @@ -0,0 +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); + 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 < m; i++) + min = Math.min(min, Math.abs(k - sum - a[row][i])); + dp[row][sum] = true; + return; + } + + for (int i = 0; i < m; i++) + solve(a, k, sum + a[row][i], row + 1, col); + dp[row][sum] = true; + } + + private int min; + private int dy[], n, m; + private boolean dp[][]; +} 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/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); + }*/ +} 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; + } +} 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/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 ans) ans = curr; + } else { + // Set to 0 when encounter 0 + curr = 0; + } + } + return ans; + } +} 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/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/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/java/728_Self_Dividing_Numbers.java b/java/728_Self_Dividing_Numbers.java new file mode 100644 index 0000000..eeb12af --- /dev/null +++ b/java/728_Self_Dividing_Numbers.java @@ -0,0 +1,27 @@ +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) { + // 0 is special + if(digit == 0 || num % digit != 0) { + isTrue = false; + break; + } else { + temp /= 10; + digit = temp % 10; + } + } + return isTrue; + } +} 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> 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/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/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 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")) diff --git a/python/007_Reverse_Integer.py b/python/007_Reverse_Integer.py index a125d47..19aeba8 100644 --- a/python/007_Reverse_Integer.py +++ b/python/007_Reverse_Integer.py @@ -1,39 +1,34 @@ 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 +# value = 2 ** 31 +# x = int(x) +# if -value <= x < value: +# return x +# return 0 + + is_neg = False 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 + x = -x + is_neg = True + + res = 0 + while x > 0: + res *= 10 + res += x % 10 + x //= 10 + if is_neg: + res = -res + + if res < -2**31 or res > 2**31-1: + return 0 + return res + \ No newline at end of file diff --git a/python/009_Palindrome_Number.py b/python/009_Palindrome_Number.py index b18b89d..8dc7ce5 100644 --- a/python/009_Palindrome_Number.py +++ b/python/009_Palindrome_Number.py @@ -6,25 +6,27 @@ # """ class Solution(object): - def isPalindrome(self, x): - if x < 0: - return False - ls = 0 - tmp = x - while tmp != 0: - ls += 1 - tmp = tmp // 10 - tmp = x - for i in range(ls/2): - right = tmp % 10 - left = tmp / (10 ** (ls - 2 * i - 1)) - left = left % 10 - # print left, right - 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 @@ -62,4 +64,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) diff --git a/python/011_Container_With_Most_Water.py b/python/011_Container_With_Most_Water.py index 4f0fa35..e49e40a 100644 --- a/python/011_Container_With_Most_Water.py +++ b/python/011_Container_With_Most_Water.py @@ -1,43 +1,14 @@ -# class Solution(object): -# def maxArea(self, height): -# """ -# :type height: List[int] -# :rtype: int -# """ -class Solution(object): -# def maxArea(self, height): -# # brute force -# ls = len(height) -# left, right = 0, ls - 1 -# result = 0 -# while left < right: -# result = max(min(height[left], height[right]) * (right - left), result) -# if height[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 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] 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: 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)) + 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 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")) 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] 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) 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 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..f5b13ee --- /dev/null +++ b/python/1290_Convert_Binary_Number_in_a_Linked_List_to_Integer.py @@ -0,0 +1,48 @@ +''' +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 is not None): + head = head.next + binary_numbers_list.append(head.val) + 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/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)] 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..86cdd7b --- /dev/null +++ b/python/1310_XOR_Queries_of_a_Subarray.py @@ -0,0 +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] 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/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 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..3769ac8 --- /dev/null +++ b/python/1342_Number_of_Steps_to_Reduce_a_Number_to_Zero.py @@ -0,0 +1,58 @@ +''' +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 + + # 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 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] 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 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: 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) 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)) + 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]) str: + res = "" + while n > 0: + n -= 1 + res = chr(65 + n % 26) + res + n //= 26 + return res 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/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 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 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 + 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 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) 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/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) 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/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 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 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 + diff --git a/python/541_Reverse_String_II.py b/python/541_Reverse_String_II.py new file mode 100644 index 0000000..08fcced --- /dev/null +++ b/python/541_Reverse_String_II.py @@ -0,0 +1,23 @@ +class Solution: + def reverseStr(self, s: str, k: int) -> str: + 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 + + # 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() +s="abcdefg" +k=2 +print(s1.reverseStr(s,k)) 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 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 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))))] 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) diff --git a/python/868_Binary_Gap.py b/python/868_Binary_Gap.py new file mode 100644 index 0000000..191d3d1 --- /dev/null +++ b/python/868_Binary_Gap.py @@ -0,0 +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: + # one pass and store max + 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 + + # 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 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 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 +