diff --git a/README.md b/README.md index 7163b06..c34ae3b 100644 --- a/README.md +++ b/README.md @@ -86,6 +86,7 @@ I'm currently working on [Analytics-Zoo](https://github.com/intel-analytics/anal | 200 | [Number of Islands](https://leetcode.com/problems/number-of-islands/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/200_Number_of_Islands.py) | 1. Quick union find, O(nlogn) and O(n^2)
2. BFS with marks, O(n^2) and O(1) | | 204 | [Count Primes](https://leetcode.com/problems/count-primes/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/204_Count_Primes.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/204_Count_Primes.java) [CPP](https://github.com/qiyuangong/leetcode/blob/master/cpp/204_Count_Primes.cpp) | [Sieve of Eratosthenes](https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes#Algorithm_complexity), O(nloglogn) and O(n) | | 206 | [Reverse Linked List](https://leetcode.com/problems/reverse-linked-list/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/206_Reverse_Linked_List.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/206_Reverse_Linked_List.java) [CPP](https://github.com/qiyuangong/leetcode/blob/master/cpp/206_Reverse_Linked_List.cpp) | 1. Stack, O(n) and O(n)
2. Traverse on prev and curr, then curr.next = prev, O(n) and O(1)
3. Recursion, O(n) and O(1) | +| 207 | [Course Schedule](https://leetcode.com/problems/course-schedule/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/207_Course_Schedule.py) | Cycle detection problem | | 213 | [House Robber II](https://leetcode.com/problems/house-robber-ii/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/213_House_Robber_II.py) | f(k) = max(f(k – 2) + num[k], max(dp[0~ls-2],dp[1~ls-1], O(n) and O(1)| | 215 | [Kth Largest Element in an Array](https://leetcode.com/problems/kth-largest-element-in-an-array/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/215_Kth_Largest_Element_in_an_Array.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/215_Kth_Largest_Element_in_an_Array.java) | 1. Sort, O(n) and O(n)
2. Heap, O(nlgk) and O(n)
3. Quick selection, O(klgn) and O(n)| | 216 | [Combination Sum III](https://leetcode.com/problems/combination-sum-iii/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/216_Combination_Sum_III.py) | Generate all combinations of length k and keep those that sum to n| @@ -132,6 +133,7 @@ I'm currently working on [Analytics-Zoo](https://github.com/intel-analytics/anal | 368 | [Largest Divisible Subset](https://leetcode.com/problems/largest-divisible-subset/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/368_Largest_Divisible_Subset.py) | Sort and generate x subset with previous results, O(n^2) and O(n^2) | | 369 | [Plus One Linked List](https://leetcode.com/problems/plus-one-linked-list/) ♥ | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/369_Plus_One_Linked_List.py) | 1. Stack or list that store the list, O(n) and O(n)
2. Two points, the first to the tail, the second to the latest place that is not 9, O(n) and O(1) | | 370 | [Range Addition](https://leetcode.com/problems/range-addition/) ♥ | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/370_Range_Addition.py) | Interval problem with cumulative sums, O(n + k) and O(n) | +| 380 | [Insert, Delete, Get Random](https://leetcode.com/problems/insert-delete-getrandom-o1/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/380_Insert_Delete_GetRandom.py)| Uses both a list of nums and a list of their locations | | 383 | [Ransom Note](https://leetcode.com/problems/ransom-note/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/383_Ransom_Note.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/383_Ransom_Note.java) | Get letter frequency (table or hash map) of magazine, then check randomNote frequency | | 384 | [Shuffle an Array](https://leetcode.com/problems/shuffle-an-array/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/384_Shuffle_an_Array.py) | [Fisher–Yates shuffle](https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle), O(n) and O(n) | | 387 | [First Unique Character in a String](https://leetcode.com/problems/first-unique-character-in-a-string/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/387_First_Unique_Character_in_a_String.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/387_First_Unique_Character_in_a_String.java) | Get frequency of each letter, return first letter with frequency 1, O(n) and O(1) | @@ -152,6 +154,7 @@ I'm currently working on [Analytics-Zoo](https://github.com/intel-analytics/anal | 434 | [Number of Segments in a String](https://leetcode.com/problems/number-of-segments-in-a-string/description/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/434_Number_of_Segments_in_a_String.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/434_Number_of_Segments_in_a_String.java) | 1. trim &split
2. Find segment in place | | 437 | [Path Sum III](https://leetcode.com/problems/path-sum-iii/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/437_Path_Sum_III.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/437_Path_Sum_III.java) | 1. Recursively travese the whole tree, O(n^2)
2. Cache sum in Hash based on solution 1. Note that if sum(A->B)=target, then sum(root->a)-sum(root-b)=target.| | 438 | [Find All Anagrams in a String](https://leetcode.com/problems/find-all-anagrams-in-a-string/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/438_Find_All_Anagrams_in_a_String.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/438_Find_All_Anagrams_in_a_String.java) | Build a char count list with 26-256 length. Note that this list can be update when going through the string. O(n) and O(1) | +| 441 | [Arranging Coins](https://leetcode.com/problems/arranging-coins/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/441_Arranging_Coins.py) | O(n) time. | | 443 | [String Compression](https://leetcode.com/problems/string-compression/description/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/443_String_Compression.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/443_String_Compression.java) | Maintain curr, read, write and anchor (start of this char). | | 448 | [Find All Numbers Disappeared in an Array](https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/448_Find_All_Numbers_Disappeared_in_an_Array.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/448_Find_All_Numbers_Disappeared_in_an_Array.java) | Value (1, n) and index (0, n-1). Mark every value postion as negative. Then, the remain index with positive values are result. O(n)| | 453 | [Number of Segments in a String](https://leetcode.com/problems/minimum-moves-to-equal-array-elements/description/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/453_Minimum_Moves_to_Equal_Array_Elements.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/453_Minimum_Moves_to_Equal_Array_Elements.java) | Each move is equal to minus one element in array, so the answer is the sum of all elements after minus min. | @@ -163,6 +166,7 @@ I'm currently working on [Analytics-Zoo](https://github.com/intel-analytics/anal | 482 | [License Key Formatting](https://leetcode.com/problems/license-key-formatting/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/482_License_Key_Formatting.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/482_License_Key_Formatting.java) | String processing, lower and len % K, O(n) and O(n) | | 485 | [Max Consecutive Ones](https://leetcode.com/problems/max-consecutive-ones/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/485_Max_Consecutive_Ones.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/485_Max_Consecutive_Ones.java) | Add one when encounter 1, set to 0 when encounter 0, O(n) and O(1) | | 509 | [Fibonacci Number](https://leetcode.com/problems/fibonacci-number/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/509_Fibonacci_Number.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/509_Fibonacci_Number.java) | 1. Recursive, O(n)
2. DP with memo, O(n). Note that N<=30, which means that we can keep a memo from 0 to 30. | +| 523 | [Continuous Subarray Sum](https://leetcode.com/problems/continuous-subarray-sum/description/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/523_Continuous_Subarray_Sum.py) | O(n) solution using dict() | | 538 | [Convert BST to Greater Tree](https://leetcode.com/problems/convert-bst-to-greater-tree/description/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/538_Convert_BST_to_Greater_Tree.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/538_Convert_BST_to_Greater_Tree.java) | Right first DFS with a variable recording sum of node.val and right.val. 1. Recursive.
2. Stack 3. Reverse Morris In-order Traversal | | 541 | [Reverse String II](https://leetcode.com/problems/reverse-string-ii/solution/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/541_Reverse_String_II.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/541_Reverse_String_II.java) | Handle each 2k until reaching end, On(n) and O(n) | | 543 | [Diameter of Binary Tree](https://leetcode.com/problems/diameter-of-binary-tree/description/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/543_Diameter_of_Binary_Tree.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/543_Diameter_of_Binary_Tree.java) | DFS with O(1) for max answer | @@ -224,9 +228,11 @@ I'm currently working on [Analytics-Zoo](https://github.com/intel-analytics/anal | 962 | [Maximum Width Ramp](https://leetcode.com/problems/maximum-width-ramp/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/962_Maximum_Width_Ramp.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/962_Maximum_Width_Ramp.java) | 1. Sort index by value, then transfer problem into finding max gap between index, O(nlogn) and O(1)
2. Binary Search for candicates, O(nlogn) and O(n) | | 977 | [Squares of a Sorted Array](https://leetcode.com/problems/squares-of-a-sorted-array/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/977_Squares_of_a_Sorted_Array.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/977_Squares_of_a_Sorted_Array.java) | 1. Sort, O(nlogn) and O(n)
2. Two point, O(n) and O(n) | | 973 | [K Closest Points to Origin](https://leetcode.com/problems/k-closest-points-to-origin/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/973_K_Closest_Points_to_Origin.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/973_K_Closest_Points_to_Origin.java) | 1. Sort and get 0-K, O(nlogn) and O(1)
2. Min Heap, O(nlogk) and O(k) | +| 981 | [Time Based Key-Value Store](https://leetcode.com/problems/time-based-key-value-store/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/981_Time_Based_Store.py) | Get: O(log(n)) time
Set: O(1) time | | 1064 | [Fixed Point](https://leetcode.com/problems/fixed-point/) ♥ | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/1064_Fixed_Point.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/1064_Fixed_Point.java) | 1. Go through index and value, until find solution encounter index < value, O(n) and O(1)
2. Binary search, O(logn) and O(1) | | 1089 | [Duplicate Zeros](https://leetcode.com/problems/duplicate-zeros/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/1089_Duplicate_Zeros.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/1089_Duplicate_Zeros.java) | 2 Pass, store last position and final move steps, O(n) and O(1) | | 1108 | [Defanging an IP Address](https://leetcode.com/problems/defanging-an-ip-address/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/1108_Defanging_an_IP_Address.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/1108_Defanging_an_IP_Address.java) | String manipulate (split, replace and join), O(n) and O(n) | +| 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 | @@ -236,14 +242,21 @@ I'm currently working on [Analytics-Zoo](https://github.com/intel-analytics/anal | 1342 | [Number of Steps to Reduce a Number to Zero](https://leetcode.com/problems/number-of-steps-to-reduce-a-number-to-zero/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/1342_Number_of_Steps_to_Reduce_a_Number_to_Zero.py) | If number is divisible by 2, divide the number by 2, else subtract 1 from the number, and output the number of steps, O(logn) and O(1) | | 1365 | [How Many Numbers Are Smaller Than the Current Number](https://leetcode.com/problems/how-many-numbers-are-smaller-than-the-current-number/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/1365_How_Many_Numbers_Are_Smaller_Than_the_Current_Number.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/1365_How_Many_Numbers_Are_Smaller_Than_the_Current_Number.java) | 1. Sort and get position in sorted nums, O(nlogn) and O(n)
2. Fill count into 0-100, O(n) and O(1) | | 1480 | [Running Sum of 1d Array](https://leetcode.com/problems/running-sum-of-1d-array/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/1480_Running_Sum_of_1d_Array.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/1480_Running_Sum_of_1d_Array.java) | 1. Go through the array, O(n) and O(1)
2. Accumulate API | +| 1539 | [Kth Missing Positive Number](https://leetcode.com/problems/kth-missing-positive-number/) | [Java](https://github.com/qiyuangong/leetcode/blob/master/java/1539_Kth_Missing_Positive_Number.java) | Binary search, num of missing = arr[i]-i-1 | +| 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/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/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= 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/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/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 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/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/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 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 af6890f..8dc7ce5 100644 --- a/python/009_Palindrome_Number.py +++ b/python/009_Palindrome_Number.py @@ -6,19 +6,27 @@ # """ class Solution(object): - def isPalindrome(self, x): - if x < 0: - return False - ls = len(str(x)) - tmp = x - for i in range(int(ls/2)): - right = int(tmp % 10) - left = tmp / (10 ** (ls - 2 * i - 1)) - left = int(left % 10) - if left != right: - return False - tmp = tmp // 10 - return True + def isPalindrome(self, x: int) -> bool: + x = str(x) + if (x == x[::-1]): + return True + return False + + + # def isPalindrome(self, x): + # if x < 0: + # return False + # ls = len(str(x)) + # tmp = x + # for i in range(int(ls/2)): + # right = int(tmp % 10) + # left = tmp / (10 ** (ls - 2 * i - 1)) + # left = int(left % 10) + # if left != right: + # return False + # tmp = tmp // 10 + # return True + # def isPalindrome(self, x): # #leetcode book 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/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/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]) 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/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/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/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/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