├── python ├── __init__.py ├── 292_Nim_Game.py ├── 1323_Maximum_69_Number.py ├── 344_Reverse_String.py ├── 441_Arranging_Coins.py ├── 461_Hamming_Distance.py ├── 557_Reverse_Words_in_a_String_III.py ├── 168_Excel_Sheet_Column_Title.py ├── 349_Intersection_of_Two_Arrays.py ├── 231_Power_of_Two.py ├── 179_Largest_Number.py ├── 258_Add_Digits.py ├── 216_Combination_Sum_III.py ├── 401_Binary_Watch.py ├── 122_Best_Time_to_Buy_and_Sell_Stock_II.py ├── 453_Minimum_Moves_to_Equal_Array_Elements.py ├── 338_Counting_Bits.py ├── 342_Power_of_Four.py ├── 392_Is_Subsequence.py ├── 347_Top_K_Frequent_Elements.py ├── 058_Length_of_Last_Word.py ├── 929_Unique_Email_Addresses.py ├── 1480_Running_Sum_of_1d_Array.py ├── 202_Happy_Number.py ├── 771_Jewels_and_Stones.py ├── 760_Find_Anagram_Mappings.py ├── 728_Self_Dividing_Numbers.py ├── 055_Jump_Game.py ├── 724_Find_Pivot_Index.py ├── 125_Valid_Palindrome.py ├── 237_Delete_Node_in_a_Linked_List.py ├── 766_Toeplitz_Matrix.py ├── 238_Product_of_Array_Except_Self.py ├── 217_Contains_Duplicate.py ├── 973_K_Closest_Points_to_Origin.py ├── 458_Poor_Pigs.py ├── 732_My_Calendar_III.py ├── 266_Palindrome_Permutation.py ├── 096_Unique_Binary_Search_Trees.py ├── 709_To_Lower_Case.py ├── 674_Longest_Continuous_Increasing_Subsequence.py ├── 389_Find_the_Difference.py ├── 832_Flipping_an_Image.py ├── 933_Number_of_Recent_Calls.py ├── 961_N-Repeated_Element_in_Size_2N_Array.py ├── 011_Container_With_Most_Water.py ├── 2413_Smallest_Even_Multiple.py ├── 104_Maximum_Depth_of_Binary_Tree.py ├── 387_First_Unique_Character_in_a_String.py ├── 434_Number_of_Segments_in_a_String.py ├── 293_Flip_Game.py ├── 1108_Defanging_an_IP_Address.py ├── 1374_Generate_a_String_With_Characters_That_Have_Odd_Counts_Solution.py ├── 475_Heaters.py ├── 278_First_Bad_Version.py ├── 485_Max_Consecutive_Ones.py ├── 118_Pascal's_Triangle.py ├── 119_Pascal's_Triangle_II.py ├── 191_Number_of_1_Bits.py ├── 560_Subarray_Sum_Equals_K.py ├── 1304_Find_N_Unique_Integers_Sum_up_to_Zero.py ├── 400_Nth_Digit.py ├── 167_Two_Sum_II_Input_array_is_sorted.py ├── 045_Jump_Game_II.py ├── 121_Best_Time_to_Buy_and_Sell_Stock.py ├── 370_Range_Addition.py ├── 852_Peak_Index_in_a_Mountain_Array.py ├── 152_Maximum_Product_Subarray.py ├── 326_Power_of_Three.py ├── 414_Third_Maximum_Number.py ├── 482_License_Key_Formatting.py ├── 997_Find_The_Town_Judge.py ├── 819_Most_Common_Word.py ├── 162_Find_Peak_Element.py ├── 071_Simplify_Path.py ├── 204_Count_Primes.py ├── 062_Unique_Paths.py ├── 135_Candy.py ├── 605_Can_Place_Flowers.py ├── 541_Reverse_String_II.py ├── 159_Longest_Substring_with_At_Most_Two_Distinct_Characters.py ├── 186_Reverse_Words_in_a_String_II.py ├── 350_Intersection_of_Two_Arrays_II.py ├── 089_Gray_Code.py ├── 383_Ransom_Note.py ├── 120_Triangle.py ├── 1310_XOR_Queries_of_a_Subarray.py ├── 374_Guess_Number_Higher_or_Lower.py ├── 443_String_Compression.py ├── 448_Find_All_Numbers_Disappeared_in_an_Array.py ├── 981_Time_Based_Store.py ├── 163_Missing_Ranges.py ├── 543_Diameter_of_Binary_Tree.py ├── 668_Kth_Smallest_Number_in_Multiplication_Table.py ├── 246_Strobogrammatic_Number.py ├── 523_Continuous_Subarray_Sum.py ├── 345_Reverse_Vowels_of_a_String.py ├── 115_Distinct_Subsequences.py ├── 223_Rectangle Area.py ├── 038_Count_and_Say.py ├── 421_Maximum_XOR_of_Two_Numbers_in_an_Array.py ├── 867_Transpose_Matrix.py ├── 059_Spiral_Matrix_II.py ├── 150_Evaluate_Reverse_Polish_Notation.py ├── 100_Same_Tree.py ├── 836_Rectangle_Overlap.py ├── 157_Read_N_Characters_Given_Read4.py ├── 371_Sum_of_Two_Integers.py ├── 112_Path_Sum.py ├── 139_Word_Break.py ├── 203_Remove_Linked_List_Elements.py ├── 876_Middle_of_the_Linked_List.py ├── 1064_Fixed_Point.py ├── 340_Longest_Substring_with_At_Most_K_Distinct_Characters.py ├── 134_Gas_Station.py ├── 409_Longest_Palindrome.py ├── 905_Sort_Array_By_Parity.py ├── 372_Super_Pow.py ├── 751_IP_to_CIDR.py ├── 268_Missing_Number.py ├── 303_Range_Sum_Query_Immutable.py ├── 161_One_Edit_Distance.py ├── 091_Decode_Ways.py ├── 276_Paint_Fence.py ├── 080_Remove_Duplicates_from_Sorted_Array_II.py ├── 242_Valid_Anagram.py ├── 373_Find_K_Pairs_with_Smallest_Sums.py ├── 007_Reverse_Integer.py ├── 016_3Sum_Closest.py ├── 388_Longest_Absolute_File_Path.py ├── 509_Fibonacci_Number.py ├── 165_Compare_Version_Numbers.py ├── 140_Word_Break_II.py ├── 804_Unique_Morse_Code_Words.py ├── 937_Reorder_Log_Files.py ├── 160_Intersection_of_Two_Linked_Lists.py ├── 128_Longest_Consecutive_Sequence.py ├── 156_Binary_Tree_Upside_Down.py ├── 954_Array_of_Doubled_Pairs.py ├── 101_Symmetric_Tree.py ├── 041_First_Missing_Positive.py ├── 064_Minimum_Path_Sum.py ├── 263_Ugly_Number.py ├── 290_Word_Pattern.py ├── 142_Linked_List_Cycle_II.py ├── 264_Ugly_Number_II.py ├── 147_Insertion_Sort_List.py ├── 367_Valid_Perfect_Square.py ├── 073_Set_Matrix_Zeroes.py ├── 422_Valid_Word_Square.py ├── 113_Path_Sum_II.py ├── 136_Single_Number.py ├── 703_Kth_Largest_Element_in_a_Stream.py ├── 257_Binary_Tree_Paths.py ├── 922_Sort_Array_By_Parity_II.py ├── 463_Island_Perimeter.py ├── 050_Pow(x, n).py ├── 1260_Shift_2D_Grid.py ├── 872_Leaf-Similar_Trees.py ├── 380_Insert_Delete_GetRandom.py ├── 249_Group_Shifted_Strings.py ├── 368_Largest_Divisible_Subset.py ├── 1089_Duplicate_Zeros.py ├── 207_Course_Schedule.py ├── 129_Sum_Root_to_Leaf_Numbers.py ├── 034_Search_for_a_Range.py ├── 131_Palindrome_Partitioning.py ├── 273_Integer_to_English_Words.py ├── 405_Convert_a_Number_to_Hexadecimal.py ├── 048_Rotate_Image.py ├── 116_Populating_Next_Right_Pointers_in_Each_Node.py ├── 200_Number_of_Islands.py ├── 346_Moving_Average_from_Data_Stream.py ├── 977_Squares_of_a_Sorted_Array.py ├── 026_Remove_Duplicates_from_Sorted_Array.py ├── 017_Letter_Combinations_of_a_Phone_Number.py ├── 700_Search_in_a_Binary_Search_Tree.py ├── 1337_The_K_Weakest_Rows_in_a_Matrix.py ├── 033_Search_in_Rotated_Sorted_Array.py ├── 299_Bulls_and_Cows.py ├── 124_Binary_Tree_Maximum_Path_Sum.py ├── 274_H-Index.py ├── 283_Move Zeroes.py ├── 158_Read_N_Characters_Given_Read4_II_Call_multiple_times.py ├── 066_Plus_One.py └── 070_Climbing_Stairs.py ├── java ├── 461_Hamming_Distance.java ├── 1480_Running_Sum_of_1d_Array.java ├── 1304_Find_N_Unique_Integers_Sum_up_to_Zero.java ├── 458_Poor_Pigs.java ├── 933_Number_of_Recent_Calls.java ├── 383_Ransom_Note.java ├── 867_Transpose_Matrix.java ├── 557_Reverse_Words_in_a_String_III.java ├── 007_Reverse_Integer.java ├── 760_Find_Anagram_Mappings.java ├── 401_Binary_Watch.java ├── 387_First_Unique_Character_in_a_String.java ├── 832_Flipping_an_Image.java ├── 961_N-Repeated_Element_in_Size_2N_Array.java ├── 453_Minimum_Moves_to_Equal_Array_Elements.java ├── 709_To_Lower_Case.java ├── 766_Toeplitz_Matrix.java ├── 026_Remove_Duplicates_from_Sorted_Array.java ├── 011_Container_With_Most_Water.java ├── 724_Find_Pivot_Index.java ├── 400_Nth_Digit.java ├── 409_Longest_Palindrome.java ├── 674_Longest_Continuous_Increasing_Subsequence.java ├── 929_Unique_Email_Addresses.java ├── 412_Fizz_Buzz.java ├── 223_Rectangle_Area.java ├── 482_License_Key_Formatting.java ├── 771_Jewels_and_Stones.java ├── 001_Two_Sum.java ├── 442_Find_All_Duplicates_in_an_Array.java ├── 543_Diameter_of_Binary_Tree.java ├── 852_Peak_Index_in_a_Mountain_Array.java ├── 485_Max_Consecutive_Ones.java ├── 414_Third_Maximum_Number.java ├── 238_Product_of_Array_Except_Self.java ├── 1310_XOR_Queries_of_a_Subarray.java ├── 389_Find_the_Difference.java ├── 541_Reverse_String_II.java ├── 013_Roman_to_Integer.java ├── 405_Convert_a_Number_to_Hexadecimal.java ├── 1323_Maximum_69_Number.java ├── 872_Leaf-Similar_Trees.java ├── 204_Count_Primes.java ├── 1064_Fixed_Point.java ├── 509_Fibonacci_Number.java ├── 415_Add_Strings.java ├── 434_Number_of_Segments_in_a_String.java ├── 443_String_Compression.java ├── 448_Find_All_Numbers_Disappeared_in_an_Array.java ├── 012_Integer_to_Roman.java ├── 680_Valid_Palindrome_II.java ├── 937_Reorder_Log_Files.java ├── 1108_Defanging_an_IP_Address.java ├── 463_Island_Perimeter.java ├── 475_Heaters.java ├── 668_Kth_Smallest_Number_in_Multiplication_Table.java ├── 700_Search_in_a_Binary_Search_Tree.java ├── 008_String_to_Integer(atoi).java ├── 868_Binary_Gap.java ├── 066_Plus_One.java ├── 804_Unique_Morse_Code_Words.java ├── 876_Middle_of_the_Linked_List.java ├── 006_ZigZag_Conversion.java ├── 004_Median_of_Two_Sorted_Arrays.java ├── 697_Degree_of_an_Array.java ├── 22_Generate_Parentheses.java ├── 728_Self_Dividing_Numbers.java ├── 347_Top_K_Frequent_Elements.java ├── 268_Missing_Number.java ├── 922_Sort_Array_By_Parity_II.java ├── 954_Array_of_Doubled_Pairs.java ├── 946_Validate_Stack_Sequences.java ├── 002_Add_Two_Numbers.java ├── 1089_Duplicate_Zeros.java ├── 1981_Minimize_the_Difference_Between_Target_and_Chosen_Elements.java ├── 703_Kth_Largest_Element_in_a_Stream.java ├── 367_Valid_Perfect_Square.java ├── 003_Longest_Substring_Without_Repeating_Characters.java ├── 560_Subarray_Sum_Equals_K.java ├── 811_Subdomain_Visit_Count.java ├── 953_Verifying_an_Alien_Dictionary.java ├── 605_Can_Place_Flowers.java └── 1337_The_K_Weakest_Rows_in_a_Matrix.java ├── cpp ├── 201_bitwise_and_of_numbers_range.cpp ├── 1310_XOR_Queries_of_a_Subarray.cpp ├── 412_Fizz_Buzz.cpp ├── 2553_Separate_the_Digits_in_an_Array.cpp ├── 206_Reverse_Linked_List.cpp ├── 668_Kth_Smallest_Number_in_Multiplication_Table.cpp └── 923_3_sum_with_multiplicity.cpp ├── create_empty_files.py └── .gitignore /python/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /java/461_Hamming_Distance.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int hammingDistance(int x, int y) { 3 | return Integer.bitCount(x ^ y); 4 | } 5 | } -------------------------------------------------------------------------------- /python/292_Nim_Game.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def canWinNim(self, n): 3 | """ 4 | :type n: int 5 | :rtype: bool 6 | """ 7 | return n % 4 != 0 -------------------------------------------------------------------------------- /python/1323_Maximum_69_Number.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maximum69Number (self, num: int) -> int: 3 | # Replace first 6 with 9 if exists 4 | return(str(num).replace('6', '9', 1)) 5 | -------------------------------------------------------------------------------- /python/344_Reverse_String.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def reverseString(self, s): 3 | """ 4 | :type s: str 5 | :rtype: str 6 | """ 7 | # slice 8 | return s[::-1] -------------------------------------------------------------------------------- /python/441_Arranging_Coins.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def arrangeCoins(self, n): 3 | level = 0 4 | while n > level: 5 | level += 1 6 | n -= level 7 | return level 8 | -------------------------------------------------------------------------------- /python/461_Hamming_Distance.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def hammingDistance(self, x, y): 3 | """ 4 | :type x: int 5 | :type y: int 6 | :rtype: int 7 | """ 8 | return bin(x ^ y).count('1') 9 | -------------------------------------------------------------------------------- /python/557_Reverse_Words_in_a_String_III.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def reverseWords(self, s): 3 | """ 4 | :type s: str 5 | :rtype: str 6 | """ 7 | return ' '.join([word[::-1] for word in s.split(' ')]) 8 | -------------------------------------------------------------------------------- /python/168_Excel_Sheet_Column_Title.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def convertToTitle(self, n: int) -> str: 3 | res = "" 4 | while n > 0: 5 | n -= 1 6 | res = chr(65 + n % 26) + res 7 | n //= 26 8 | return res 9 | -------------------------------------------------------------------------------- /java/1480_Running_Sum_of_1d_Array.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[] runningSum(int[] nums) { 3 | if (nums.length <= 1) return nums; 4 | for (int i = 1; i < nums.length; i++) 5 | nums[i] += nums[i - 1]; 6 | return nums; 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /java/1304_Find_N_Unique_Integers_Sum_up_to_Zero.java: -------------------------------------------------------------------------------- 1 | public int[] sumZero(int n) { 2 | int[] res = new int[n]; 3 | // place negative sum(from 1 to n-1) in 0 4 | for (int i = 1; i < n; i++) { 5 | res[i] = i; 6 | res[0] -= i; 7 | } 8 | return res; 9 | } 10 | -------------------------------------------------------------------------------- /java/458_Poor_Pigs.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int poorPigs(int buckets, int minutesToDie, int minutesToTest) { 3 | int n = minutesToTest / minutesToDie + 1; 4 | int pigs = 0; 5 | while (Math.pow(n, pigs) < buckets) pigs++; 6 | return pigs; 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /python/349_Intersection_of_Two_Arrays.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def intersection(self, nums1, nums2): 3 | """ 4 | :type nums1: List[int] 5 | :type nums2: List[int] 6 | :rtype: List[int] 7 | """ 8 | # set 9 | return list(set(nums1) & set(nums2)) -------------------------------------------------------------------------------- /python/231_Power_of_Two.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def isPowerOfTwo(self, n): 3 | """ 4 | :type n: int 5 | :rtype: bool 6 | """ 7 | if n < 0: 8 | return False 9 | bin_str = bin(n) 10 | return sum(map(lambda x: int(x), list(bin_str[2:]))) == 1 -------------------------------------------------------------------------------- /python/179_Largest_Number.py: -------------------------------------------------------------------------------- 1 | class LargerNumKey(str): 2 | def __lt__(x, y): 3 | return x + y > y + x 4 | 5 | 6 | class Solution: 7 | def largestNumber(self, nums): 8 | largest_num = ''.join(sorted(map(str, nums), key=LargerNumKey)) 9 | return '0' if largest_num[0] == '0' else largest_num 10 | -------------------------------------------------------------------------------- /python/258_Add_Digits.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def addDigits(self, num): 3 | """ 4 | :type num: int 5 | :rtype: int 6 | """ 7 | # https: // en.wikipedia.org / wiki / Digital_root 8 | if num < 10: 9 | return num 10 | return num - ((num - 1) / 9) * 9 -------------------------------------------------------------------------------- /java/933_Number_of_Recent_Calls.java: -------------------------------------------------------------------------------- 1 | class RecentCounter { 2 | Queue q; 3 | public RecentCounter() { 4 | q = new LinkedList(); 5 | } 6 | 7 | public int ping(int t) { 8 | q.add(t); 9 | while (q.peek() < t - 3000) 10 | q.poll(); 11 | return q.size(); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /python/216_Combination_Sum_III.py: -------------------------------------------------------------------------------- 1 | import itertools as it 2 | class Solution(object): 3 | def combinationSum3(self, k, n): 4 | """ 5 | :type k: int 6 | :type n: int 7 | :rtype: List[List[int]] 8 | """ 9 | return list(it.ifilter(lambda x: sum(x) == n, list(it.combinations(range(1, 10), k)))) 10 | -------------------------------------------------------------------------------- /python/401_Binary_Watch.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def readBinaryWatch(self, num): 3 | """ 4 | :type num: int 5 | :rtype: List[str] 6 | """ 7 | return ['%d:%02d' % (h, m) 8 | for h in range(12) for m in range(60) 9 | if (bin(h) + bin(m)).count('1') == num] 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /python/122_Best_Time_to_Buy_and_Sell_Stock_II.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def maxProfit(self, prices): 3 | """ 4 | :type prices: List[int] 5 | :rtype: int 6 | """ 7 | # sum of prices[i + 1] - prices[i], if prices[i + 1] > prices[i] 8 | return sum([y - x for x, y in zip(prices[0:-1], prices[1:]) if x < y]) 9 | -------------------------------------------------------------------------------- /python/453_Minimum_Moves_to_Equal_Array_Elements.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def minMoves(self, nums): 3 | """ 4 | :type nums: List[int] 5 | :rtype: int 6 | """ 7 | if nums is None or len(nums) == 0: 8 | return 0 9 | min_num = min(nums) 10 | return sum([i - min_num for i in nums]) 11 | -------------------------------------------------------------------------------- /java/383_Ransom_Note.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean canConstruct(String ransomNote, String magazine) { 3 | int[] table = new int[128]; 4 | for (char c : magazine.toCharArray()) table[c]++; 5 | for (char c : ransomNote.toCharArray()) 6 | if (--table[c] < 0) return false; 7 | return true; 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /cpp/201_bitwise_and_of_numbers_range.cpp: -------------------------------------------------------------------------------- 1 | /** time complexity : O(logN). N = min(m, n) **/ 2 | 3 | class Solution { 4 | public: 5 | int rangeBitwiseAnd(int m, int n) { 6 | int cnt = 0; 7 | while(m < n) { 8 | m = m >> 1; 9 | n = n >> 1; 10 | cnt++; 11 | } 12 | return n<> 1] + (i & 1) 11 | return res 12 | 13 | -------------------------------------------------------------------------------- /java/557_Reverse_Words_in_a_String_III.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public String reverseWords(String s) { 3 | String words[] = s.split(" "); 4 | StringBuilder ans = new StringBuilder(); 5 | for (String word: words) 6 | ans.append(new StringBuffer(word).reverse().toString() + " "); 7 | return ans.toString().trim(); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /python/342_Power_of_Four.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def isPowerOfFour(self, num): 3 | """ 4 | :type num: int 5 | :rtype: bool 6 | """ 7 | # bin(4**0) '0b1' 8 | # bin(4**1) '0b100' 9 | # bin(4**2) '0b10000' 10 | # bin(4**3) '0b1000000' 11 | return num > 0 and num & (num-1) == 0 and len(bin(num)[3:]) % 2 == 0 -------------------------------------------------------------------------------- /python/392_Is_Subsequence.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isSubsequence(self, s: str, t: str) -> bool: 3 | for a in s: 4 | if a in t: 5 | for b in range(0, len(t)): 6 | if a==t[b]: 7 | t=t[b+1:] 8 | break 9 | else: 10 | return(False) 11 | return(True) 12 | -------------------------------------------------------------------------------- /java/007_Reverse_Integer.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int reverse(int x) { 3 | if (x == 0) return 0; 4 | long res = 0; 5 | while (x != 0) { 6 | res = res * 10 + x % 10; 7 | if (res > Integer.MAX_VALUE || res < Integer.MIN_VALUE) 8 | return 0; 9 | x /= 10; 10 | } 11 | return (int) res; 12 | } 13 | } -------------------------------------------------------------------------------- /python/347_Top_K_Frequent_Elements.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def topKFrequent(self, nums, k): 3 | """ 4 | :type nums: List[int] 5 | :type k: int 6 | :rtype: List[int] 7 | """ 8 | counter = collections.Counter(nums) 9 | return [k for k,v in counter.most_common(k)] 10 | # return heapq.nlargest(k, count.keys(), key=count.get) 11 | -------------------------------------------------------------------------------- /java/760_Find_Anagram_Mappings.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[] anagramMappings(int[] A, int[] B) { 3 | int[] ans = new int[A.length]; 4 | HashMap valIndex = new HashMap<>(); 5 | for (int i = 0; i < B.length; i++) valIndex.put(B[i], i); 6 | for (int i = 0; i < A.length; i++) ans[i] = valIndex.get(A[i]); 7 | return ans; 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /java/401_Binary_Watch.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public List readBinaryWatch(int num) { 3 | List times = new ArrayList<>(); 4 | for (int h = 0; h < 12; h++) 5 | for (int m = 0; m < 60; m++) 6 | if (Integer.bitCount(h * 64 + m) == num) 7 | times.add(String.format("%d:%02d", h, m)); 8 | return times; 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /java/387_First_Unique_Character_in_a_String.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int firstUniqChar(String s) { 3 | int freq [] = new int[26]; 4 | for(int i = 0; i < s.length(); i ++) 5 | freq [s.charAt(i) - 'a'] ++; 6 | for(int i = 0; i < s.length(); i ++) 7 | if(freq [s.charAt(i) - 'a'] == 1) 8 | return i; 9 | return -1; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /java/832_Flipping_an_Image.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[][] flipAndInvertImage(int[][] A) { 3 | int C = A[0].length; 4 | for (int[] row: A) 5 | for (int i = 0; i < (C + 1) / 2; ++i) { 6 | int tmp = row[i] ^ 1; 7 | row[i] = row[C - 1 - i] ^ 1; 8 | row[C - 1 - i] = tmp; 9 | } 10 | 11 | return A; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /python/058_Length_of_Last_Word.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def lengthOfLastWord(self, s): 3 | """ 4 | :type s: str 5 | :rtype: int 6 | """ 7 | if len(s) == 0: 8 | return 0 9 | temp = s.split(' ') 10 | temp = [t for t in temp if len(t) > 0] 11 | if len(temp) == 0: 12 | return 0 13 | else: 14 | return len(temp[-1]) -------------------------------------------------------------------------------- /python/929_Unique_Email_Addresses.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def numUniqueEmails(self, emails): 3 | """ 4 | :type emails: List[str] 5 | :rtype: int 6 | """ 7 | email_set = set() 8 | for email in emails: 9 | elements = email.split('@') 10 | email_set.add(elements[0].split('+')[0].replace('.', '') + elements[1]) 11 | return len(email_set) 12 | -------------------------------------------------------------------------------- /java/961_N-Repeated_Element_in_Size_2N_Array.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int repeatedNTimes(int[] A) { 3 | HashMap hash = new HashMap<>(); 4 | int ans = A[0]; 5 | for (int n: A) { 6 | int count = hash.getOrDefault(n, 0) + 1; 7 | hash.put(n, count); 8 | if (count >= hash.get(ans)) ans = n; 9 | } 10 | return ans; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /python/1480_Running_Sum_of_1d_Array.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def runningSum(self, nums: List[int]) -> List[int]: 3 | if nums is None or len(nums) == 0: 4 | return nums 5 | for i in range(1, len(nums)): 6 | nums[i] += nums[i-1] 7 | return nums 8 | 9 | # def runningSum(self, nums: List[int]) -> List[int]: 10 | # # accumulate method 11 | # return accumulate(nums) 12 | -------------------------------------------------------------------------------- /python/202_Happy_Number.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def isHappy(self, n): 3 | """ 4 | :type n: int 5 | :rtype: bool 6 | """ 7 | # https://en.wikipedia.org/wiki/Happy_number 8 | seen_numbers = set() 9 | while n > 1 and n not in seen_numbers: 10 | seen_numbers.add(n) 11 | n = sum(map(lambda x: int(x) * int(x), list(str(n)))) 12 | return n == 1 -------------------------------------------------------------------------------- /python/771_Jewels_and_Stones.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def numJewelsInStones(self, J, S): 3 | """ 4 | :type J: str 5 | :type S: str 6 | :rtype: int 7 | """ 8 | if len(J) == 0 or len(S) == 0: 9 | return 0 10 | j_set = set(J) 11 | ans = 0 12 | for c in S: 13 | if c in j_set: 14 | ans += 1 15 | return ans 16 | -------------------------------------------------------------------------------- /python/760_Find_Anagram_Mappings.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def anagramMappings(self, A, B): 3 | """ 4 | :type A: List[int] 5 | :type B: List[int] 6 | :rtype: List[int] 7 | """ 8 | val_index = {} 9 | ans = [] 10 | for i, n in enumerate(B): 11 | val_index[n] = i 12 | for n in A: 13 | ans.append(val_index[n]) 14 | return ans 15 | -------------------------------------------------------------------------------- /java/453_Minimum_Moves_to_Equal_Array_Elements.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | import java.util.Collections; 3 | 4 | class Solution { 5 | public int minMoves(int[] nums) { 6 | if (nums.length == 0) return 0; 7 | Arrays.sort(nums); 8 | int min_num = nums[0]; 9 | int ans = 0; 10 | for (int num : nums) { 11 | ans += num - min_num; 12 | } 13 | return ans; 14 | } 15 | } -------------------------------------------------------------------------------- /java/709_To_Lower_Case.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public String toLowerCase(String str) { 3 | return str.toLowerCase(); 4 | } 5 | 6 | /*public String toLowerCase(String str) { 7 | char[] a = str.toCharArray(); 8 | for (int i = 0; i < a.length; i++) 9 | if ('A' <= a[i] && a[i] <= 'Z') 10 | a[i] = (char) (a[i] - 'A' + 'a'); 11 | return new String(a); 12 | }*/ 13 | } 14 | -------------------------------------------------------------------------------- /java/766_Toeplitz_Matrix.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean isToeplitzMatrix(int[][] matrix) { 3 | // Start from second line and column 4 | for (int r = 1; r < matrix.length; ++r) 5 | for (int c = 1; c < matrix[0].length; ++c) 6 | // Check step by step 7 | if (matrix[r-1][c-1] != matrix[r][c]) 8 | return false; 9 | return true; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /python/728_Self_Dividing_Numbers.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def selfDividingNumbers(self, left: int, right: int) -> List[int]: 3 | # check every digit 4 | return [x for x in range(left, right+1) if all([int(i) != 0 and x % int(i)==0 for i in str(x)])] 5 | 6 | # def selfDividingNumbers(self, left: int, right: int) -> List[int]: 7 | # return [x for x in range(left, right+1) if all((i and (x % i==0) for i in map(int, str(x))))] 8 | -------------------------------------------------------------------------------- /python/055_Jump_Game.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def canJump(self, nums): 3 | """ 4 | :type nums: List[int] 5 | :rtype: bool 6 | """ 7 | # greedy 8 | # https://leetcode.com/articles/jump-game/ 9 | length = len(nums) 10 | begin = length - 1 11 | for i in reversed(range(length - 1)): 12 | if i + nums[i] >= begin: 13 | begin = i 14 | return not begin -------------------------------------------------------------------------------- /python/724_Find_Pivot_Index.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def pivotIndex(self, nums): 3 | """ 4 | :type nums: List[int] 5 | :rtype: int 6 | """ 7 | totalsum = sum(nums) 8 | leftsum = 0 9 | for i, v in enumerate(nums): 10 | # leftsum == rightsum 11 | if leftsum == totalsum - leftsum - v: 12 | return i 13 | leftsum += v 14 | return -1 15 | -------------------------------------------------------------------------------- /java/026_Remove_Duplicates_from_Sorted_Array.java: -------------------------------------------------------------------------------- 1 | //026. Remove Duplicates from Sorted Array 2 | class Solution { 3 | public int removeDuplicates(int[] nums) { 4 | int index = 1; 5 | 6 | for (int i = 0; i < nums.length - 1; i++) { 7 | if (nums[i] != nums[i + 1]) { 8 | nums[index] = nums[i + 1]; 9 | index++; 10 | } 11 | } 12 | 13 | return index; 14 | } 15 | } 16 | 17 | -------------------------------------------------------------------------------- /cpp/1310_XOR_Queries_of_a_Subarray.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector xorQueries(vector& arr, vector>& queries) { 4 | vector res; 5 | // Compute accumulated xor from head 6 | for (int i = 1; i < arr.size(); i++) 7 | arr[i] ^= arr[i - 1]; 8 | for (auto &q: queries) 9 | res.push_back(q[0] > 0 ? arr[q[0] - 1] ^ arr[q[1]] : arr[q[1]]); 10 | return res; 11 | } 12 | }; 13 | -------------------------------------------------------------------------------- /java/011_Container_With_Most_Water.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int maxArea(int[] height) { 3 | 4 | int maxArea = 0; 5 | int left = 0; 6 | int right = height.length - 1; 7 | 8 | while (left < right) { 9 | maxArea = Math.max(maxArea, (right - left) * Math.min(height[left], height[right])); 10 | // Two points 11 | if (height[left] < height[right]) left++; 12 | else right--; 13 | } 14 | return maxArea; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /create_empty_files.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | if __name__ == '__main__': 4 | file_name = 'test' 5 | try: 6 | file_name = sys.argv[1] 7 | except IndexError: 8 | print("Usage: python create_empty_file [filename]") 9 | print("Creating " + file_name + "in java and python dir...") 10 | with open("python/" + file_name + ".py", 'w'): 11 | pass 12 | with open("java/" + file_name + ".java", 'w'): 13 | pass 14 | print("Done!") 15 | -------------------------------------------------------------------------------- /python/125_Valid_Palindrome.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def isPalindrome(self, s): 3 | """ 4 | :type s: str 5 | :rtype: bool 6 | """ 7 | alnum_s = [t.lower() for t in s if t.isalnum()] 8 | ls = len(alnum_s) 9 | if ls <= 1: 10 | return True 11 | mid = ls / 2 12 | for i in range(mid): 13 | if alnum_s[i] != alnum_s[ls - 1 - i]: 14 | return False 15 | return True -------------------------------------------------------------------------------- /python/237_Delete_Node_in_a_Linked_List.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode(object): 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.next = None 6 | 7 | class Solution(object): 8 | def deleteNode(self, node): 9 | """ 10 | :type node: ListNode 11 | :rtype: void Do not return anything, modify node in-place instead. 12 | """ 13 | node.val = node.next.val 14 | node.next = node.next.next -------------------------------------------------------------------------------- /python/766_Toeplitz_Matrix.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def isToeplitzMatrix(self, matrix): 3 | """ 4 | :type matrix: List[List[int]] 5 | :rtype: bool 6 | """ 7 | # Actually, we don't need to check the last row and column 8 | for r in range(len(matrix) - 1): 9 | for c in range(len(matrix[0]) - 1): 10 | if matrix[r][c] != matrix[r + 1][c + 1]: 11 | return False 12 | return True 13 | -------------------------------------------------------------------------------- /java/724_Find_Pivot_Index.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int pivotIndex(int[] nums) { 3 | int totalsum = 0, leftsum = 0; 4 | // Compute total sum 5 | for (int i = 0; i < nums.length; i++) totalsum += nums[i]; 6 | // Check leftsum == rightsum 7 | for (int i = 0; i < nums.length; i++) { 8 | if (leftsum == totalsum - leftsum - nums[i]) return i; 9 | leftsum += nums[i]; 10 | } 11 | return -1; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /python/238_Product_of_Array_Except_Self.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def productExceptSelf(self, nums): 3 | """ 4 | :type nums: List[int] 5 | :rtype: List[int] 6 | """ 7 | ans = [1] * len(nums) 8 | for i in range(1, len(nums)): 9 | ans[i] = ans[i - 1] * nums[i - 1] 10 | right = 1 11 | for i in range(len(nums) - 1, -1, -1): 12 | ans[i] *= right 13 | right *= nums[i] 14 | return ans 15 | -------------------------------------------------------------------------------- /java/400_Nth_Digit.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int findNthDigit(int n) { 3 | int len = 1; 4 | long count = 9; 5 | int start = 1; 6 | // https://leetcode.com/problems/nth-digit/discuss/88363/Java-solution 7 | while (n > len * count) { 8 | n -= len * count; 9 | len += 1; 10 | count *= 10; 11 | start *= 10; 12 | } 13 | start += (n - 1) / len; 14 | String s = Integer.toString(start); 15 | return Character.getNumericValue(s.charAt((n - 1) % len)); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /java/409_Longest_Palindrome.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | // https://leetcode.com/problems/longest-palindrome/solution/ 3 | public int longestPalindrome(String s) { 4 | int[] count = new int[128]; 5 | for (char c: s.toCharArray()) 6 | count[c]++; 7 | 8 | int ans = 0; 9 | for (int v: count) { 10 | ans += v / 2 * 2; 11 | if (ans % 2 == 0 && v % 2 == 1) 12 | ans++; 13 | } 14 | return ans; 15 | } 16 | } -------------------------------------------------------------------------------- /python/217_Contains_Duplicate.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def containsDuplicate(self, nums): 3 | """ 4 | :type nums: List[int] 5 | :rtype: bool 6 | """ 7 | # use set to check duplicate 8 | return len(nums) != len(set(nums)) 9 | 10 | # def containsDuplicate(self, nums): 11 | # nums.sort() 12 | # for i in range(len(nums) - 1): 13 | # if nums[i] == nums[i + 1]: 14 | # return True 15 | # return False -------------------------------------------------------------------------------- /java/674_Longest_Continuous_Increasing_Subsequence.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int findLengthOfLCIS(int[] nums) { 3 | if (nums.length == 0) return 0; 4 | int curr = 1, ans = 1; 5 | for (int i = 0; i < nums.length - 1; i++) { 6 | if (nums[i] < nums[i + 1]) { 7 | curr ++; 8 | if (curr >= ans) ans = curr; 9 | } else { 10 | curr = 1; 11 | } 12 | } 13 | return ans; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /python/973_K_Closest_Points_to_Origin.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | # def kClosest(self, points, K): 3 | # """ 4 | # :type points: List[List[int]] 5 | # :type K: int 6 | # :rtype: List[List[int]] 7 | # """ 8 | # # Sort 9 | # return sorted(points, key=lambda x: x[0] ** 2 + x[1] ** 2)[:K] 10 | 11 | def kClosest(self, points, K): 12 | # K smallest heaq 13 | return heapq.nsmallest(K, points, key=lambda x: x[0] ** 2 + x[1] ** 2) 14 | -------------------------------------------------------------------------------- /java/929_Unique_Email_Addresses.java: -------------------------------------------------------------------------------- 1 | import java.util.HashSet; 2 | 3 | class Solution { 4 | public int numUniqueEmails(String[] emails) { 5 | HashSet emailSet = new HashSet<>(); 6 | for (String email: emails) { 7 | String firstSplit[] = email.split("@"); 8 | String secondSplit[] = firstSplit[0].replaceAll(".", "").split("[+]"); 9 | emailSet.add(secondSplit[0] + firstSplit[1]); 10 | } 11 | return emailSet.size(); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /python/458_Poor_Pigs.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def poorPigs(self, buckets, minutesToDie, minutesToTest): 3 | """ 4 | :type buckets: int 5 | :type minutesToDie: int 6 | :type minutesToTest: int 7 | :rtype: int 8 | """ 9 | # https://leetcode.com/problems/poor-pigs/discuss/94266/Another-explanation-and-solution 10 | pigs = 0 11 | while (minutesToTest / minutesToDie + 1) ** pigs < buckets: 12 | pigs += 1 13 | return pigs 14 | -------------------------------------------------------------------------------- /python/732_My_Calendar_III.py: -------------------------------------------------------------------------------- 1 | from sortedcontainers import SortedDict 2 | 3 | 4 | class MyCalendarThree: 5 | def __init__(self): 6 | self.timeline = SortedDict() 7 | 8 | def book(self, start: int, end: int) -> int: 9 | self.timeline[start] = self.timeline.get(start, 0) + 1 10 | self.timeline[end] = self.timeline.get(end, 0) - 1 11 | 12 | ans = 0 13 | activeEvents = 0 14 | 15 | for count in self.timeline.values(): 16 | activeEvents += count 17 | ans = max(ans, activeEvents) 18 | -------------------------------------------------------------------------------- /java/412_Fizz_Buzz.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.List; 3 | 4 | class Solution { 5 | public List fizzBuzz(int n) { 6 | List res = new ArrayList<>(); 7 | for (int i = 1; i <= n; i++) { 8 | String tmp = ""; 9 | if (i % 3 == 0) tmp += "Fizz"; 10 | if (i % 5 == 0) tmp += "Buzz"; 11 | if (tmp.length() == 0) tmp += String.valueOf(i); 12 | res.add(tmp); 13 | } 14 | return res; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /python/266_Palindrome_Permutation.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def canPermutePalindrome(self, s): 3 | """ 4 | :type s: str 5 | :rtype: bool 6 | """ 7 | dic = {} 8 | for c in s: 9 | dic[c] = dic.get(c, 0) + 1 10 | odd, even = 0, 0 11 | for c in dic: 12 | if dic[c] % 2 == 0: 13 | even += 1 14 | else: 15 | odd += 1 16 | if odd <= 1: 17 | return True 18 | return False 19 | -------------------------------------------------------------------------------- /java/223_Rectangle_Area.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) { 3 | // https://leetcode.com/problems/rectangle-area/discuss/62149/Just-another-short-way 4 | // Possible overlap area 5 | int left = Math.max(A, E), right = Math.max(Math.min(C, G), left); 6 | int bottom = Math.max(B, F), top = Math.max(Math.min(D, H), bottom); 7 | return (C - A) * (D - B) - (right - left) * (top - bottom) + (G - E) * (H - F); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /java/482_License_Key_Formatting.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public String licenseKeyFormatting(String s, int k) { 3 | // https://leetcode.com/problems/license-key-formatting/discuss/96512/Java-5-lines-clean-solution 4 | StringBuilder sb = new StringBuilder(); 5 | for (int i = s.length() - 1; i >= 0; i--) 6 | if (s.charAt(i) != '-') 7 | sb.append(sb.length() % (k + 1) == k ? '-' : "").append(s.charAt(i)); 8 | return sb.reverse().toString().toUpperCase(); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /java/771_Jewels_and_Stones.java: -------------------------------------------------------------------------------- 1 | import java.util.HashSet; 2 | 3 | class Solution { 4 | public int numJewelsInStones(String J, String S) { 5 | int result = 0; 6 | HashSet jHash = new HashSet<>(); 7 | for (int j = 0; j < J.length(); j++) { 8 | jHash.add(J.charAt(j)); 9 | } 10 | for (int s = 0; s < S.length(); s++) { 11 | if (jHash.contains(S.charAt(s))) { 12 | result++; 13 | } 14 | } 15 | return result; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /python/096_Unique_Binary_Search_Trees.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def numTrees(self, n): 3 | """ 4 | :type n: int 5 | :rtype: int 6 | """ 7 | # https://leetcode.com/discuss/86650/fantastic-clean-java-dp-solution-with-detail-explaination 8 | dp = [0] * (n + 1) 9 | dp[0] = 1 10 | dp[1] = 1 11 | for level in range(2, n + 1): 12 | for root in range(1, level + 1): 13 | dp[level] += dp[level - root] * dp[root - 1] 14 | return dp[n] -------------------------------------------------------------------------------- /python/709_To_Lower_Case.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def toLowerCase(self, str): 3 | """ 4 | :type str: str 5 | :rtype: str 6 | """ 7 | res = [] 8 | gap = ord('a') - ord('A') 9 | for c in str: 10 | if ord(c) >= ord('A') and ord(c) <= ord('Z'): 11 | res.append(chr(ord(c) + gap)) 12 | else: 13 | res.append(c) 14 | return ''.join(res) 15 | 16 | # def toLowerCase(self, str): 17 | # return str.lower() 18 | -------------------------------------------------------------------------------- /python/674_Longest_Continuous_Increasing_Subsequence.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def findLengthOfLCIS(self, nums): 3 | """ 4 | :type nums: List[int] 5 | :rtype: int 6 | """ 7 | if not nums or len(nums) == 0: 8 | return 0 9 | ans = curr = 1 10 | for i in range(len(nums) - 1): 11 | if nums[i] < nums[i + 1]: 12 | curr += 1 13 | ans = max(ans, curr) 14 | else: 15 | curr = 1 16 | return ans 17 | -------------------------------------------------------------------------------- /java/001_Two_Sum.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | // example in leetcode book 3 | public int[] twoSum(int[] nums, int target) { 4 | Map map = new HashMap<>(); 5 | for (int i = 0; i < nums.length; i++) { 6 | int x = nums[i]; 7 | if (map.containsKey(target - x)) { 8 | return new int[]{map.get(target - x), i}; 9 | } 10 | map.put(x, i); 11 | } 12 | throw new IllegalArgumentException("No two sum solution"); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /java/442_Find_All_Duplicates_in_an_Array.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public List findDuplicates(int[] nums) { 3 | int n = nums.length; 4 | 5 | List ans = new ArrayList<>(); 6 | 7 | for(int i=0;i ans) ans = curr; 10 | } else { 11 | // Set to 0 when encounter 0 12 | curr = 0; 13 | } 14 | } 15 | return ans; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /python/011_Container_With_Most_Water.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxArea(self, height: List[int]) -> int: 3 | # Two points 4 | left, right = 0, len(height) - 1 5 | result = 0 6 | while left < right: 7 | result = max(min(height[left], height[right]) * (right - left), result) 8 | if height[left] > height[right]: 9 | # remove right 10 | right -= 1 11 | else: 12 | # remove left 13 | left += 1 14 | return result 15 | -------------------------------------------------------------------------------- /python/2413_Smallest_Even_Multiple.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def smallestEvenMultiple(self, n: int) -> int: 3 | """ 4 | n : positive integer 5 | return : smallest positive integer that is a multiple of both 2 and n 6 | """ 7 | if n % 2 == 0: 8 | # if n is alreay muliply by 2 9 | # return itself 10 | return n 11 | 12 | # if previous condition is false 13 | # n * 2 is the smallest positive integer. 14 | return n * 2 15 | 16 | -------------------------------------------------------------------------------- /python/104_Maximum_Depth_of_Binary_Tree.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node 2 | # class TreeNode: 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.left = None 6 | # self.right = None 7 | 8 | class Solution: 9 | def maxDepth(self, root): 10 | """ 11 | :type root: TreeNode 12 | :rtype: int 13 | """ 14 | if root is None: 15 | return 0 16 | ld = self.maxDepth(root.left) 17 | rd = self.maxDepth(root.right) 18 | return 1 + max(ld, rd) 19 | -------------------------------------------------------------------------------- /cpp/412_Fizz_Buzz.cpp: -------------------------------------------------------------------------------- 1 | #define pb push_back 2 | class Solution { 3 | public: 4 | vector fizzBuzz(int n) { 5 | int i; 6 | vector s; 7 | for (i = 0; i < n; i++) { 8 | if ((i + 1) % 15 == 0) 9 | s.pb("FizzBuzz"); 10 | else if ((i + 1) % 5 == 0) 11 | s.pb("Buzz"); 12 | else if ((i + 1) % 3 == 0) 13 | s.pb("Fizz"); 14 | else 15 | s.pb(to_string(i + 1)); 16 | } 17 | return s; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /python/387_First_Unique_Character_in_a_String.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def firstUniqChar(self, s): 3 | """ 4 | :type s: str 5 | :rtype: int 6 | """ 7 | count_map = {} 8 | for c in s: 9 | count_map[c] = count_map.get(c, 0) + 1 10 | for i, c in enumerate(s): 11 | if count_map[c] == 1: 12 | return i 13 | return -1 14 | 15 | # def firstUniqChar(self, s): 16 | # min([s.find(c) for c in string.ascii_lowercase if s.count(c)==1] or [-1]) 17 | -------------------------------------------------------------------------------- /python/434_Number_of_Segments_in_a_String.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | # https://leetcode.com/problems/number-of-segments-in-a-string/solution/ 3 | # def countSegments(self, s): 4 | # """ 5 | # :type s: str 6 | # :rtype: int 7 | # """ 8 | # return len(s.split()) 9 | 10 | def countSegments(self, s): 11 | segment_count = 0 12 | for i in range(len(s)): 13 | if (i == 0 or s[i-1] == ' ') and s[i] != ' ': 14 | segment_count += 1 15 | 16 | return segment_count -------------------------------------------------------------------------------- /java/414_Third_Maximum_Number.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int thirdMax(int[] nums) { 3 | PriorityQueue pq = new PriorityQueue<>(3); 4 | Set set = new HashSet<>(); 5 | for (int i : nums) { 6 | if (set.contains(i)) continue; 7 | pq.offer(i); 8 | set.add(i); 9 | if (pq.size() > 3) set.remove(pq.poll()); 10 | } 11 | while (pq.size() < 3 && pq.size() > 1) { 12 | pq.poll(); 13 | } 14 | return pq.peek(); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /python/293_Flip_Game.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def generatePossibleNextMoves(self, s): 3 | """ 4 | :type s: str 5 | :rtype: List[str] 6 | """ 7 | # return [s[:i] + "--" + s[i+2:] for i in range(len(s) - 1) if s[i] == s[i + 1] == "+"] 8 | res = [] 9 | if s is None or len(s) == 0: 10 | return res 11 | ls = len(s) 12 | for i in range(ls - 1): 13 | if s[i] == '+' and s[i + 1] == '+': 14 | res.append(s[:i] + '--' + s[i + 2:]) 15 | return res 16 | -------------------------------------------------------------------------------- /python/1108_Defanging_an_IP_Address.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def defangIPaddr(self, address: str) -> str: 3 | # replace 4 | return address.replace('.', '[.]') 5 | # def defangIPaddr(self, address: str) -> str: 6 | # # split and join 7 | # return '[.]'.join(address.split('.')) 8 | # def defangIPaddr(self, address: str) -> str: 9 | # # replace 10 | # return re.sub('\.', '[.]', address) 11 | # def defangIPaddr(self, address: str) -> str: 12 | # return ''.join('[.]' if c == '.' else c for c in address) 13 | -------------------------------------------------------------------------------- /python/1374_Generate_a_String_With_Characters_That_Have_Odd_Counts_Solution.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an integer n, return a string with n characters such that each character in such string occurs an odd number of times. 3 | The returned string must contain only lowercase English letters. If there are multiples valid strings, return any of them. 4 | Input: n = 4 5 | Output: "pppz" 6 | ''' 7 | class Solution: 8 | def generateTheString(self, n: int) -> str: 9 | if n%2==0: 10 | return "a" * (n-1) + "b" 11 | else: 12 | return "a" * n 13 | -------------------------------------------------------------------------------- /python/475_Heaters.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def findRadius(self, houses, heaters): 3 | """ 4 | :type houses: List[int] 5 | :type heaters: List[int] 6 | :rtype: int 7 | """ 8 | heaters = sorted(heaters) + [float('inf')] 9 | i = r = 0 10 | for x in sorted(houses): 11 | # move to next range 12 | while x >= sum(heaters[i:i + 2]) / 2.: 13 | i += 1 14 | # ans = hearter - hourse 15 | r = max(r, abs(heaters[i] - x)) 16 | return r 17 | -------------------------------------------------------------------------------- /python/278_First_Bad_Version.py: -------------------------------------------------------------------------------- 1 | # The isBadVersion API is already defined for you. 2 | # @param version, an integer 3 | # @return a bool 4 | # def isBadVersion(version): 5 | 6 | class Solution(object): 7 | def firstBadVersion(self, n): 8 | """ 9 | :type n: int 10 | :rtype: int 11 | """ 12 | left, right= 1, n 13 | while left < right: 14 | mid = (right + left) / 2 15 | if isBadVersion(mid): 16 | right = mid 17 | else: 18 | left = mid + 1 19 | return left -------------------------------------------------------------------------------- /java/238_Product_of_Array_Except_Self.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int[] productExceptSelf(int[] nums) { 3 | int n = nums.length; 4 | int[] res = new int[n]; 5 | res[0] = 1; 6 | for (int i = 1; i < n; i++) { 7 | // left part 8 | res[i] = res[i - 1] * nums[i - 1]; 9 | } 10 | int right = 1; 11 | for (int i = n - 1; i >= 0; i--) { 12 | res[i] *= right; 13 | // right part 14 | right *= nums[i]; 15 | } 16 | return res; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /python/485_Max_Consecutive_Ones.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def findMaxConsecutiveOnes(self, nums): 3 | """ 4 | :type nums: List[int] 5 | :rtype: int 6 | """ 7 | ans = 0 8 | curr = 0 9 | for n in nums: 10 | if n == 1: 11 | # Add 1 to curr when encounter 1 12 | curr += 1 13 | if curr > ans: 14 | ans = curr 15 | else: 16 | # Add 1 to curr when encounter 1 17 | curr = 0 18 | return ans 19 | -------------------------------------------------------------------------------- /python/118_Pascal's_Triangle.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def generate(self, numRows): 3 | """ 4 | :type numRows: int 5 | :rtype: List[List[int]] 6 | """ 7 | result = [] 8 | for i in range(numRows): 9 | result.append([0] * (i + 1)) 10 | for i in range(numRows): 11 | for j in range(i + 1): 12 | if j == 0 or j == i: 13 | result[i][j] = 1 14 | else: 15 | result[i][j] = result[i - 1][j - 1] + result[i - 1][j] 16 | return result 17 | -------------------------------------------------------------------------------- /python/119_Pascal's_Triangle_II.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def getRow(self, rowIndex): 3 | """ 4 | :type rowIndex: int 5 | :rtype: List[int] 6 | """ 7 | last = [1] 8 | res = [1] 9 | for r in range(1, rowIndex + 1): 10 | res = [1] 11 | for index in range(len(last) - 1): 12 | res.append(last[index] + last[index + 1]) 13 | res.append(1) 14 | last = res 15 | return res 16 | 17 | if __name__ == "__main__": 18 | s = Solution() 19 | print s.getRow(3) -------------------------------------------------------------------------------- /python/191_Number_of_1_Bits.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | # def hammingWeight(self, n): 3 | # """ 4 | # :type n: int 5 | # :rtype: int 6 | # """ 7 | # # using bin 8 | # s_n = bin(n)[2:] 9 | # return s_n.count('1') 10 | 11 | def hammingWeight(self, n): 12 | """ 13 | :type n: int 14 | :rtype: int 15 | """ 16 | # https://leetcode.com/articles/number-1-bits/ 17 | count = 0 18 | while n: 19 | n &= n - 1 20 | count += 1 21 | return count 22 | -------------------------------------------------------------------------------- /java/1310_XOR_Queries_of_a_Subarray.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[] xorQueries(int[] arr, int[][] queries) { 3 | int[] res = new int[queries.length], q; 4 | // Compute accumulated xor from head 5 | for (int i = 1; i < arr.length; i++) 6 | arr[i] ^= arr[i - 1]; 7 | // query result equals to xor[0, l] xor xor[0, r] 8 | for (int i = 0; i < queries.length; i++) { 9 | q = queries[i]; 10 | res[i] = q[0] > 0 ? arr[q[0] - 1] ^ arr[q[1]] : arr[q[1]]; 11 | } 12 | return res; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /python/560_Subarray_Sum_Equals_K.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def subarraySum(self, nums, k): 3 | """ 4 | :type nums: List[int] 5 | :type k: int 6 | :rtype: int 7 | """ 8 | sum_map = {} 9 | sum_map[0] = 1 10 | count = curr_sum = 0 11 | for num in nums: 12 | curr_sum += num 13 | # Check if sum - k in hash 14 | count += sum_map.get(curr_sum - k, 0) 15 | # add curr_sum to hash 16 | sum_map[curr_sum] = sum_map.get(curr_sum, 0) + 1 17 | return count 18 | -------------------------------------------------------------------------------- /cpp/2553_Separate_the_Digits_in_an_Array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector separateDigits(vector& nums) { 4 | vector answer; 5 | int n; 6 | for( int i=0; i < nums.size(); i++){ 7 | n=nums[i]; 8 | vector temp; 9 | while( n>0 ){ 10 | temp.push_back(n%10); 11 | n = n / 10; 12 | } 13 | for(int j= temp.size()-1; j>=0; j--){ 14 | answer.push_back(temp[j]); 15 | } 16 | } 17 | return answer; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /python/1304_Find_N_Unique_Integers_Sum_up_to_Zero.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def sumZero(self, n: int) -> List[int]: 3 | prefix_sum = 0 4 | res = [] 5 | # 1, n-1 6 | for i in range(1, n): 7 | res.append(i) 8 | prefix_sum = prefix_sum + i 9 | # sum(from 1 to n-1) 10 | res.append(-prefix_sum) 11 | return res 12 | 13 | # def sumZero(self, n: int) -> List[int]: 14 | # # 1,n-1 15 | # prefix = list(range(1, n)) 16 | # # sum(from 1 to n-1) 17 | # return prefix + [-sum(prefix)] 18 | -------------------------------------------------------------------------------- /python/400_Nth_Digit.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def findNthDigit(self, n): 3 | """ 4 | :type n: int 5 | :rtype: int 6 | """ 7 | # https://leetcode.com/problems/nth-digit/discuss/88363/Java-solution 8 | count = 9 9 | start = 1 10 | curr_len = 1 11 | while n > curr_len * count: 12 | n -= curr_len * count 13 | curr_len += 1 14 | count *= 10 15 | start *= 10 16 | start += (n - 1) / curr_len 17 | s = str(start) 18 | return int(s[(n - 1) % curr_len] 19 | -------------------------------------------------------------------------------- /python/167_Two_Sum_II_Input_array_is_sorted.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def twoSum(self, numbers, target): 3 | """ 4 | :type numbers: List[int] 5 | :type target: int 6 | :rtype: List[int] 7 | """ 8 | # Two Points 9 | begin, end = 0, len(numbers) - 1 10 | while begin < end: 11 | curr = numbers[begin] + numbers[end] 12 | if curr == target: 13 | return [begin + 1, end + 1] 14 | elif curr < target: 15 | begin += 1 16 | else: 17 | end -= 1 18 | 19 | -------------------------------------------------------------------------------- /java/389_Find_the_Difference.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public char findTheDifference(String s, String t) { 3 | int total = t.charAt(s.length()); 4 | for (int i = 0; i < s.length(); i++) 5 | total += (t.charAt(i) - s.charAt(i)); 6 | return (char) total; 7 | } 8 | 9 | /* public char findTheDifference(String s, String t) { 10 | int total = t.charAt(s.length()); 11 | for (int i = 0; i < s.length(); i++) { 12 | total ^= t.charAt(i); 13 | total ^= s.charAt(i); 14 | } 15 | return (char) total; 16 | } */ 17 | } 18 | -------------------------------------------------------------------------------- /python/045_Jump_Game_II.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def jump(self, nums): 3 | """ 4 | :type nums: List[int] 5 | :rtype: int 6 | """ 7 | if len(nums) <= 1: 8 | return 0 9 | end = 0 + nums[0] 10 | start = 0 11 | step = 1 12 | maxDis = 0 + nums[0] 13 | while end < len(nums) - 1: 14 | for i in range(start + 1, end + 1): 15 | # greedy 16 | maxDis = max(maxDis, nums[i] + i) 17 | start = end 18 | end = maxDis 19 | step += 1 20 | return step 21 | -------------------------------------------------------------------------------- /java/541_Reverse_String_II.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public String reverseStr(String s, int k) { 3 | // https://leetcode.com/problems/reverse-string-ii/solution/ 4 | char[] a = s.toCharArray(); 5 | for (int start = 0; start < a.length; start += 2 * k) { 6 | int i = start, j = Math.min(start + k - 1, a.length - 1); 7 | // Reverse from i to j 8 | while (i < j) { 9 | char tmp = a[i]; 10 | a[i++] = a[j]; 11 | a[j--] = tmp; 12 | } 13 | } 14 | return new String(a); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /python/121_Best_Time_to_Buy_and_Sell_Stock.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def maxProfit(self, prices): 3 | """ 4 | :type prices: List[int] 5 | :rtype: int 6 | """ 7 | length = len(prices) 8 | if length == 0: 9 | return 0 10 | max_profit, low = 0, prices[0] 11 | for i in range(1, length): 12 | if low > prices[i]: 13 | low = prices[i] 14 | else: 15 | temp = prices[i] - low 16 | if temp > max_profit: 17 | max_profit = temp 18 | return max_profit -------------------------------------------------------------------------------- /python/370_Range_Addition.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def getModifiedArray(self, length, updates): 3 | """ 4 | :type length: int 5 | :type updates: List[List[int]] 6 | :rtype: List[int] 7 | """ 8 | res = [0] * length 9 | # interval problem 10 | for t in updates: 11 | start, end, val = t 12 | res[start] += val 13 | if end < length - 1: 14 | res[end + 1] -= val 15 | # Cumulative sums 16 | for i in range(1, length): 17 | res[i] = res[i] + res[i - 1] 18 | return res 19 | -------------------------------------------------------------------------------- /python/852_Peak_Index_in_a_Mountain_Array.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | # def peakIndexInMountainArray(self, A): 3 | # """ 4 | # :type A: List[int] 5 | # :rtype: int 6 | # """ 7 | # i = 0 8 | # while A[i + 1] >= A[i]: 9 | # i += 1 10 | # return i 11 | 12 | def peakIndexInMountainArray(self, A): 13 | lo, hi = 0, len(A) - 1 14 | while lo < hi: 15 | mid = (lo + hi) / 2 16 | if A[mid] < A[mid + 1]: 17 | lo = mid + 1 18 | else: 19 | hi = mid 20 | return lo 21 | -------------------------------------------------------------------------------- /python/152_Maximum_Product_Subarray.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def maxProduct(self, nums): 3 | """ 4 | :type nums: List[int] 5 | :rtype: int 6 | """ 7 | if nums is None or len(nums) == 0: 8 | return 0 9 | max_here = min_here = max_so_far = nums[0] 10 | for i in range(1, len(nums)): 11 | mx, mn = max_here, min_here 12 | max_here = max(max(mx * nums[i], nums[i]), mn * nums[i]) 13 | min_here = min(min(mx * nums[i], nums[i]), mn * nums[i]) 14 | max_so_far = max(max_here, max_so_far) 15 | return max_so_far -------------------------------------------------------------------------------- /python/326_Power_of_Three.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | # def isPowerOfThree(self, n): 3 | # """ 4 | # :type n: int 5 | # :rtype: bool 6 | # """ 7 | # import math 8 | # if n <= 0: 9 | # return False 10 | # # use round to check 11 | # log_res = round(math.log(n, 3), 10) 12 | # if log_res - int(log_res) > 0: 13 | # return False 14 | # return True 15 | 16 | def isPowerOfThree(self, n): 17 | max3pow = 1162261467 18 | if n <= 0 or n > max3pow: 19 | return False 20 | return max3pow % n == 0 -------------------------------------------------------------------------------- /python/414_Third_Maximum_Number.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def thirdMax(self, nums): 3 | """ 4 | :type nums: List[int] 5 | :rtype: int 6 | """ 7 | import Queue 8 | pq = Queue.PriorityQueue(4) 9 | check = set() 10 | for n in nums: 11 | if n in check: 12 | continue 13 | pq.put(n) 14 | check.add(n) 15 | if len(check) > 3: 16 | check.remove(pq.get()) 17 | total = len(check) 18 | while total < 3 and total > 1: 19 | total -= 1 20 | return pq.get() 21 | -------------------------------------------------------------------------------- /python/482_License_Key_Formatting.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def licenseKeyFormatting(self, S, K): 3 | """ 4 | :type S: str 5 | :type K: int 6 | :rtype: str 7 | """ 8 | # https://leetcode.com/problems/license-key-formatting/discuss/96497/Python-solution 9 | S = S.upper().replace('-', '') 10 | ls = len(S) 11 | if ls % K == 0: 12 | pos = K 13 | else: 14 | pos = ls % K 15 | res = S[:pos] 16 | while pos < ls: 17 | res += '-' + S[pos:pos + K] 18 | pos += K 19 | return res 20 | -------------------------------------------------------------------------------- /python/997_Find_The_Town_Judge.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findJudge(self, N: int, trust: List[List[int]]) -> int: 3 | if N==1: 4 | return 1 5 | d1={} 6 | d2={} 7 | for i, j in trust: 8 | if j in d1: 9 | d1[j]+=1 10 | else: 11 | d1[j]=1 12 | if i in d2: 13 | d2[i]+=1 14 | else: 15 | d2[i]=1 16 | for i,j in d1.items(): 17 | if j==N-1: 18 | if i not in d2: 19 | return i 20 | return -1 21 | 22 | -------------------------------------------------------------------------------- /python/819_Most_Common_Word.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def mostCommonWord(self, paragraph, banned): 3 | """ 4 | :type paragraph: str 5 | :type banned: List[str] 6 | :rtype: str 7 | """ 8 | # https://leetcode.com/problems/most-common-word/discuss/193268/python-one-liner 9 | banned = set(banned) 10 | count = collections.Counter(word for word in re.split('[ !?\',;.]', 11 | paragraph.lower()) if word) 12 | return max((item for item in count.items() if item[0] not in banned), 13 | key=operator.itemgetter(1))[0] 14 | -------------------------------------------------------------------------------- /java/013_Roman_to_Integer.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int romanToInt(String s) { 3 | int[] arr = new int['A' + 26]; 4 | arr['I'] = 1; 5 | arr['V'] = 5; 6 | arr['X'] = 10; 7 | arr['L'] = 50; 8 | arr['C'] = 100; 9 | arr['D'] = 500; 10 | arr['M'] = 1000; 11 | 12 | int result = 0; 13 | int prev = 0; 14 | 15 | for (int i = s.length() - 1; i >= 0; i--) { 16 | int current = arr[s.charAt(i)]; 17 | result += prev > current ? -current : current; 18 | prev = current; 19 | } 20 | 21 | return result; 22 | } 23 | } -------------------------------------------------------------------------------- /java/405_Convert_a_Number_to_Hexadecimal.java: -------------------------------------------------------------------------------- 1 | import com.sun.corba.se.spi.orbutil.fsm.Guard.Result; 2 | 3 | class Solution { 4 | public String toHex(int num) { 5 | String hex_map = "0123456789abcdef"; 6 | if (num == 0) return "0"; 7 | String res = ""; 8 | // To avoid infinite loop caused by negative num 9 | while (num != 0 && res.length() < 8) { 10 | res = hex_map.charAt(num & 15) + res; 11 | num = num >> 4; 12 | } 13 | return res; 14 | } 15 | 16 | /* public String toHex(int num) { 17 | String hex = Integer.toHexString(num); 18 | return hex; 19 | } */ 20 | } 21 | -------------------------------------------------------------------------------- /python/162_Find_Peak_Element.py: -------------------------------------------------------------------------------- 1 | # class Solution(object): 2 | # def findPeakElement(self, nums): 3 | # """ 4 | # :type nums: List[int] 5 | # :rtype: int 6 | # """ 7 | 8 | class Solution(object): 9 | def findPeakElement(self, nums): 10 | # https://leetcode.com/discuss/88467/tricky-problem-tricky-solution 11 | # note that num[-1] = num[n] = -∞ 12 | start, end = 0, len(nums) - 1 13 | while start < end: 14 | mid = (start + end) / 2 15 | if nums[mid] < nums[mid+1]: 16 | start= mid + 1 17 | else: 18 | end = mid 19 | return start 20 | -------------------------------------------------------------------------------- /java/1323_Maximum_69_Number.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int maximum69Number (int num) { 3 | // Replace first 6 with 9 if exists 4 | return Integer.valueOf(String.valueOf(num).replaceFirst("6", "9")); 5 | } 6 | 7 | /* 8 | public int maximum69Number (int num) { 9 | char[] chars = Integer.toString(num).toCharArray(); 10 | // Replace first 6 with 9 if exists 11 | for (int i = 0; i < chars.length; i++) { 12 | if (chars[i] == '6') { 13 | chars[i] = '9'; 14 | break; 15 | } 16 | } 17 | return Integer.parseInt(new String(chars)); 18 | }*/ 19 | } 20 | -------------------------------------------------------------------------------- /java/872_Leaf-Similar_Trees.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean leafSimilar(TreeNode root1, TreeNode root2) { 3 | List leaves1 = new ArrayList(); 4 | List leaves2 = new ArrayList(); 5 | dfs(root1, leaves1); 6 | dfs(root2, leaves2); 7 | return leaves1.equals(leaves2); 8 | } 9 | 10 | public void dfs(TreeNode node, List leafValues) { 11 | if (node != null) { 12 | if (node.left == null && node.right == null) 13 | leafValues.add(node.val); 14 | dfs(node.left, leafValues); 15 | dfs(node.right, leafValues); 16 | } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /python/071_Simplify_Path.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def simplifyPath(self, path): 3 | """ 4 | :type path: str 5 | :rtype: str 6 | """ 7 | result = [] 8 | plist = path.split('/') 9 | for pos in plist: 10 | if pos: 11 | if pos == '..': 12 | try: 13 | # up one level 14 | result.pop() 15 | except: 16 | # arrive top level 17 | result = [] 18 | elif pos != '.': 19 | result.append(pos) 20 | return '/'+'/'.join(result) -------------------------------------------------------------------------------- /python/204_Count_Primes.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def countPrimes(self, n): 3 | """ 4 | :type n: int 5 | :rtype: int 6 | """ 7 | # https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes#Algorithm_complexity 8 | isPrime = [True] * n 9 | for i in xrange(2, n): 10 | if i * i >= n: 11 | break 12 | if not isPrime[i]: 13 | continue 14 | for j in xrange(i * i, n, i): 15 | isPrime[j] = False 16 | count = 0 17 | for i in xrange(2, n): 18 | if isPrime[i]: 19 | count += 1 20 | return count 21 | -------------------------------------------------------------------------------- /python/062_Unique_Paths.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def uniquePaths(self, m, n): 3 | """ 4 | :type m: int 5 | :type n: int 6 | :rtype: int 7 | """ 8 | dmap = [[0] * n for _ in range(m)] 9 | for i in range(m): 10 | dmap[i][0] = 1 11 | for j in range(n): 12 | dmap[0][j] = 1 13 | for i in range(1, m): 14 | for j in range(1, n): 15 | l = u = 0 16 | if i-1 >= 0: 17 | u = dmap[i-1][j] 18 | if j-1>= 0: 19 | l = dmap[i][j-1] 20 | dmap[i][j] = l + u 21 | return dmap[m-1][n-1] 22 | -------------------------------------------------------------------------------- /python/135_Candy.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def candy(self, ratings): 3 | """ 4 | :type ratings: List[int] 5 | :rtype: int 6 | """ 7 | # https://discuss.leetcode.com/topic/5243/a-simple-solution 8 | if ratings is None or len(ratings) == 0: 9 | return 0 10 | ls = len(ratings) 11 | num = [1] * ls 12 | for i in range(1, ls): 13 | if ratings[i] > ratings[i - 1]: 14 | num[i] = num[i - 1] + 1 15 | for i in range(ls - 1, 0, -1): 16 | if ratings[i - 1] > ratings[i]: 17 | num[i - 1] = max(num[i] + 1, num[i - 1]) 18 | return sum(num) 19 | 20 | -------------------------------------------------------------------------------- /python/605_Can_Place_Flowers.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def canPlaceFlowers(self, flowerbed, n): 3 | """ 4 | :type flowerbed: List[int] 5 | :type n: int 6 | :rtype: bool 7 | """ 8 | count = 0 9 | for i in range(len(flowerbed)): 10 | curr = flowerbed[i] 11 | if i - 1 >= 0: 12 | curr += flowerbed[i - 1] 13 | if i + 1 < len(flowerbed): 14 | curr += flowerbed[i + 1] 15 | if curr == 0: 16 | count += 1 17 | flowerbed[i] = 1 18 | if count >= n: 19 | return True 20 | return False 21 | -------------------------------------------------------------------------------- /java/204_Count_Primes.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | // ttps://en.wikipedia.org/wiki/Sieve_of_Eratosthenes#Algorithm_complexity 3 | public int countPrimes(int n) { 4 | boolean[] isPrime = new boolean[n]; 5 | int count = 0; 6 | Arrays.fill(isPrime, true); 7 | for (int i = 2; i < n; i++) { 8 | if (i * i >= n) 9 | break; 10 | if (!isPrime[i]) 11 | continue; 12 | for (int j = i * i; j < n; j += i) 13 | isPrime[j] = false; 14 | } 15 | for (int i = 2; i < n; i++) 16 | if (isPrime[i]) 17 | count++; 18 | return count; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /python/541_Reverse_String_II.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def reverseStr(self, s: str, k: int) -> str: 3 | N = len(s) 4 | ans = "" 5 | position = 0 6 | while position < N: 7 | nx = s[position : position + k] 8 | ans = ans + nx[::-1] + s[position + k : position + 2 * k] 9 | position += 2 * k 10 | return ans 11 | 12 | # def reverseStr(self, s: str, k: int) -> str: 13 | # s = list(s) 14 | # for i in range(0, len(s), 2*k): 15 | # s[i:i+k] = reversed(s[i:i+k]) 16 | # return "".join(s) 17 | 18 | 19 | 20 | s1 = Solution() 21 | s="abcdefg" 22 | k=2 23 | print(s1.reverseStr(s,k)) 24 | -------------------------------------------------------------------------------- /python/159_Longest_Substring_with_At_Most_Two_Distinct_Characters.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def lengthOfLongestSubstringTwoDistinct(self, s): 3 | """ 4 | :type s: str 5 | :rtype: int 6 | """ 7 | i, j, maxLen = 0, -1, 0 8 | # i for start, k for end, j for latest pos contains different character from k 9 | for k in range(1, len(s)): 10 | if s[k] == s[k - 1]: 11 | continue 12 | if j >= 0 and s[j] != s[k]: 13 | maxLen = max(k - i, maxLen) 14 | # update i 15 | i = j + 1 16 | # update 17 | j = k - 1 18 | return max(len(s) - i, maxLen) -------------------------------------------------------------------------------- /python/186_Reverse_Words_in_a_String_II.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def reverseWords(self, s): 3 | """ 4 | :type s: a list of 1 length strings (List[str]) 5 | :rtype: nothing 6 | """ 7 | ls, pos = len(s), 0 8 | if s is None or ls == 0: 9 | return 10 | self.reverse(s, 0, ls) 11 | for i in range(ls + 1): 12 | if i == ls or s[i] == ' ': 13 | self.reverse(s, pos, i) 14 | pos = i + 1 15 | 16 | def reverse(self, array_s, begin, end): 17 | for i in range((end - begin) / 2): 18 | array_s[begin + i], array_s[end - i - 1] = array_s[end - i - 1], array_s[begin + i] 19 | -------------------------------------------------------------------------------- /java/1064_Fixed_Point.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | /* public int fixedPoint(int[] A) { 3 | for (int i = 0; i < A.length; i++) { 4 | // Because if A[i] > i, then i can never be greater than A[i] any more 5 | if (A[i] == i) return i; 6 | else if (A[i] > i) return -1; 7 | } 8 | return -1; 9 | } */ 10 | public int fixedPoint(int[] A) { 11 | int l = 0; 12 | int h = A.length; 13 | while (l <= h) { 14 | int mid = (l + h) / 2; 15 | if (A[mid] > mid) h = mid - 1; 16 | else if (A[mid] < mid) l = mid + 1; 17 | else return mid; 18 | } 19 | return -1; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /python/350_Intersection_of_Two_Arrays_II.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def intersect(self, nums1, nums2): 3 | """ 4 | :type nums1: List[int] 5 | :type nums2: List[int] 6 | :rtype: List[int] 7 | """ 8 | nums1.sort() 9 | nums2.sort() 10 | res = [] 11 | pos1 = pos2 = 0 12 | while pos1 < len(nums1) and pos2 < len(nums2): 13 | if nums1[pos1] == nums2[pos2]: 14 | res.append(nums1[pos1]) 15 | pos1 += 1 16 | pos2 += 1 17 | elif nums1[pos1] < nums2[pos2]: 18 | pos1 += 1 19 | else: 20 | pos2 += 1 21 | return res 22 | -------------------------------------------------------------------------------- /java/509_Fibonacci_Number.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | /*public int fib(int N) { 3 | // Recursively, O(n) 4 | if (N == 0) return 0; 5 | if (N == 1) return 1; 6 | return fib(N - 1) + fib(N - 2); 7 | }*/ 8 | 9 | private List memo; 10 | 11 | public Solution() { 12 | memo = new ArrayList(); 13 | memo.add(0); 14 | memo.add(1); 15 | } 16 | 17 | public int fib(int N) { 18 | // Dp with memo, O(n) 19 | if (N < memo.size()) return memo.get(N); 20 | for (int i = memo.size(); i <= N; i++) { 21 | memo.add(memo.get(i - 1) + memo.get(i - 2)); 22 | } 23 | return memo.get(N); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /python/089_Gray_Code.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def grayCode(self, n): 3 | """ 4 | :type n: int 5 | :rtype: List[int] 6 | """ 7 | # https://leetcode.com/discuss/86617/6-line-java-solution-very-concise 8 | res = [0] 9 | for i in range(n): 10 | for j in reversed(range(len(res))): 11 | res.append(res[j] + (1 << i)) 12 | return res 13 | 14 | 15 | # def count_one(self, num): 16 | # count = 0 17 | # while num: 18 | # num &= (num - 1) 19 | # count += 1 20 | # return count 21 | 22 | if __name__ == "__main__": 23 | s = Solution() 24 | print s.grayCode(2) 25 | 26 | -------------------------------------------------------------------------------- /python/383_Ransom_Note.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def canConstruct(self, ransomNote, magazine): 3 | """ 4 | :type ransomNote: str 5 | :type magazine: str 6 | :rtype: bool 7 | """ 8 | letter_map = {} 9 | for letter in magazine: 10 | letter_map[letter] = letter_map.get(letter, 0) + 1 11 | for letter in ransomNote: 12 | letter_map[letter] = letter_map.get(letter, 0) - 1 13 | if letter_map[letter] < 0: 14 | return False 15 | return True 16 | 17 | # def canConstruct(self, ransomNote, magazine): 18 | # return not collections.Counter(ransomNote) - collections.Counter(magazine) 19 | -------------------------------------------------------------------------------- /java/415_Add_Strings.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public String addStrings(String num1, String num2) { 3 | StringBuilder sb = new StringBuilder(); 4 | int carry = 0; 5 | // condition is great 6 | // https://leetcode.com/problems/add-strings/discuss/90436/Straightforward-Java-8-main-lines-25ms 7 | for(int i = num1.length() - 1, j = num2.length() - 1; i >= 0 || j >= 0 || carry == 1; i--, j--){ 8 | int x = i < 0 ? 0 : num1.charAt(i) - '0'; 9 | int y = j < 0 ? 0 : num2.charAt(j) - '0'; 10 | sb.append((x + y + carry) % 10); 11 | carry = (x + y + carry) / 10; 12 | } 13 | return sb.reverse().toString(); 14 | } 15 | } -------------------------------------------------------------------------------- /java/434_Number_of_Segments_in_a_String.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | // https://leetcode.com/problems/number-of-segments-in-a-string/solution/ 3 | // public int countSegments(String s) { 4 | // String trimmed = s.trim(); 5 | // if (trimmed.equals("")) { 6 | // return 0; 7 | // } 8 | // return trimmed.split("\\s+").length; 9 | // } 10 | public int countSegments(String s) { 11 | int segmentCount = 0; 12 | 13 | for (int i = 0; i < s.length(); i++) { 14 | if ((i == 0 || s.charAt(i-1) == ' ') && s.charAt(i) != ' ') { 15 | segmentCount++; 16 | } 17 | } 18 | 19 | return segmentCount; 20 | } 21 | } -------------------------------------------------------------------------------- /python/120_Triangle.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def minimumTotal(self, triangle): 3 | """ 4 | :type triangle: List[List[int]] 5 | :rtype: int 6 | """ 7 | if triangle is None or len(triangle) == 0: 8 | return 0 9 | ls = len(triangle) 10 | dp = [0] * ls 11 | dp[0] = triangle[0][0] 12 | for i in range(1, ls): 13 | # note that dp should be updated in reversed order 14 | dp[i] = dp[i - 1] + triangle[i][i] 15 | for j in reversed(range(1, i)): 16 | dp[j] = min(dp[j - 1] + triangle[i][j], dp[j] + triangle[i][j]) 17 | dp[0] = dp[0] + triangle[i][0] 18 | return min(dp) 19 | -------------------------------------------------------------------------------- /python/1310_XOR_Queries_of_a_Subarray.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def xorQueries(self, arr: List[int], queries: List[List[int]]) -> List[int]: 3 | pref = [0] 4 | # Compute accumulated xor from head 5 | for e in arr: 6 | pref.append(e ^ pref[-1]) 7 | ans = [] 8 | # query result equal to xor[0, l] xor x[0, r] 9 | for [l, r] in queries: 10 | ans.append(pref[r+1] ^ pref[l]) 11 | return ans 12 | 13 | # def xorQueries(self, arr: List[int], queries: List[List[int]]) -> List[int]: 14 | # for i in range(len(arr) - 1): 15 | # arr[i + 1] ^= arr[i] 16 | # return [arr[j] ^ arr[i - 1] if i else arr[j] for i, j in queries] 17 | -------------------------------------------------------------------------------- /python/374_Guess_Number_Higher_or_Lower.py: -------------------------------------------------------------------------------- 1 | # The guess API is already defined for you. 2 | # @param num, your guess 3 | # @return -1 if my number is lower, 1 if my number is higher, otherwise return 0 4 | # def guess(num): 5 | 6 | class Solution(object): 7 | def guessNumber(self, n): 8 | """ 9 | :type n: int 10 | :rtype: int 11 | """ 12 | # binary search 13 | begin, end = 1, n 14 | while begin <= end: 15 | mid = (begin + end) / 2 16 | res = guess(mid) 17 | if res == 0: 18 | return mid 19 | elif res > 0: 20 | begin = mid + 1 21 | else: 22 | end = mid - 1 23 | -------------------------------------------------------------------------------- /python/443_String_Compression.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def compress(self, chars): 3 | """ 4 | :type chars: List[str] 5 | :rtype: int 6 | """ 7 | # https://leetcode.com/problems/string-compression/solution/ 8 | anchor = write = 0 9 | for read, c in enumerate(chars): 10 | if read + 1 == len(chars) or chars[read + 1] != c: 11 | chars[write] = chars[anchor] 12 | write += 1 13 | if read > anchor: 14 | for digit in str(read - anchor + 1): 15 | chars[write] = digit 16 | write += 1 17 | anchor = read + 1 18 | return write -------------------------------------------------------------------------------- /python/448_Find_All_Numbers_Disappeared_in_an_Array.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def findDisappearedNumbers(self, nums): 3 | """ 4 | :type nums: List[int] 5 | :rtype: List[int] 6 | """ 7 | # https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/discuss/92956/Java-accepted-simple-solution 8 | res = [] 9 | if nums: 10 | n = len(nums) 11 | for i in range(n): 12 | val = abs(nums[i]) - 1 13 | if nums[val] > 0: 14 | nums[val] = -nums[val] 15 | for i in range(n): 16 | if nums[i] > 0: 17 | res.append(i + 1) 18 | return res 19 | -------------------------------------------------------------------------------- /java/443_String_Compression.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int compress(char[] chars) { 3 | // https://leetcode.com/problems/string-compression/solution/ 4 | int anchor = 0, write = 0; 5 | for (int read = 0; read < chars.length; read++) { 6 | if (read + 1 == chars.length || chars[read + 1] != chars[read]) { 7 | chars[write++] = chars[anchor]; 8 | if (read > anchor) { 9 | for (char c: ("" + (read - anchor + 1)).toCharArray()) { 10 | chars[write++] = c; 11 | } 12 | } 13 | anchor = read + 1; 14 | } 15 | } 16 | return write; 17 | } 18 | } -------------------------------------------------------------------------------- /python/981_Time_Based_Store.py: -------------------------------------------------------------------------------- 1 | from collections import defaultdict 2 | 3 | class TimeMap(object): 4 | 5 | def __init__(self): 6 | self.store = defaultdict(list) 7 | 8 | def set(self, key, value, timestamp): 9 | self.store[key].append((value, timestamp)) 10 | 11 | def get(self, key, timestamp): 12 | values = self.store.get(key, []) 13 | res = "" 14 | 15 | l = 0 16 | r = len(values) - 1 17 | 18 | while l <= r: 19 | mid = (l + r) // 2 20 | if values[mid][1] <= timestamp: 21 | l = mid + 1 22 | res = values[mid][0] 23 | else: 24 | r = mid - 1 25 | 26 | return res 27 | -------------------------------------------------------------------------------- /python/163_Missing_Ranges.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def findMissingRanges(self, nums, lower, upper): 3 | """ 4 | :type nums: List[int] 5 | :type lower: int 6 | :type upper: int 7 | :rtype: List[str] 8 | """ 9 | ranges = [] 10 | prev = lower - 1 11 | for i in range(len(nums) + 1): 12 | if i == len(nums): 13 | curr = upper + 1 14 | else: 15 | curr = nums[i] 16 | if curr - prev > 2: 17 | ranges.append("%d->%d" % (prev + 1, curr - 1)) 18 | elif curr - prev == 2: 19 | ranges.append("%d" % (prev + 1)) 20 | prev = curr 21 | return ranges -------------------------------------------------------------------------------- /python/543_Diameter_of_Binary_Tree.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode(object): 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.left = None 6 | # self.right = None 7 | 8 | class Solution(object): 9 | # https://leetcode.com/problems/diameter-of-binary-tree/solution/ 10 | def diameterOfBinaryTree(self, root): 11 | self.ans = 1 12 | def depth(node): 13 | if not node: return 0 14 | L = depth(node.left) 15 | R = depth(node.right) 16 | self.ans = max(self.ans, L+R+1) 17 | return max(L, R) + 1 18 | 19 | depth(root) 20 | # number of nodes - 1 = length 21 | return self.ans - 1 22 | -------------------------------------------------------------------------------- /python/668_Kth_Smallest_Number_in_Multiplication_Table.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findKthNumber(self, m: int, n: int, k: int) -> int: 3 | # https://leetcode.com/problems/kth-smallest-number-in-multiplication-table/solution/ 4 | def enough(x): 5 | count = 0 6 | # ith row [i, 2*i, 3*i, ..., n*i] 7 | # for each column, k = x // i 8 | for i in range(1, m+1): 9 | count += min(x // i, n) 10 | return count >= k 11 | 12 | lo, hi = 1, m * n 13 | while lo < hi: 14 | mi = (lo + hi) // 2 15 | if not enough(mi): 16 | lo = mi + 1 17 | else: 18 | hi = mi 19 | return lo 20 | -------------------------------------------------------------------------------- /python/246_Strobogrammatic_Number.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def isStrobogrammatic(self, num): 3 | """ 4 | :type num: str 5 | :rtype: bool 6 | """ 7 | # hash table 8 | dic = {'0':'0', '6':'9', '9': '6', '1' :'1', '8': '8'} 9 | temp_s = '' 10 | for c in num[::-1]: 11 | if c not in dic: 12 | return False 13 | temp_s += dic[c] 14 | if int(temp_s) == int(num): 15 | return True 16 | return False 17 | 18 | # def isStrobogrammatic(self, num): 19 | # # https://discuss.leetcode.com/topic/20840/1-liners-python 20 | # return all(num[i] + num[~i] in '696 00 11 88' for i in range(len(num)/2+1)) 21 | -------------------------------------------------------------------------------- /python/523_Continuous_Subarray_Sum.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def checkSubarraySum(self, nums: List[int], k: int) -> bool: 3 | # remeainders[0] = 0 is for when x == 0 4 | remainders = dict() 5 | remainders[0] = 0 6 | pre_sum = 0 7 | 8 | for idx, item in enumerate(nums): 9 | pre_sum += item 10 | remaind = pre_sum % k 11 | 12 | # remainder doesnt exist then it has to be init 13 | # if it exists, then check the prev one has the same remainder 14 | if remaind not in remainders: 15 | remainders[remaind] = idx + 1 16 | elif remainders[remaind] < idx: 17 | return True 18 | 19 | return False 20 | 21 | -------------------------------------------------------------------------------- /java/448_Find_All_Numbers_Disappeared_in_an_Array.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | // https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/discuss/92956/Java-accepted-simple-solution 3 | public List findDisappearedNumbers(int[] nums) { 4 | List ret = new ArrayList(); 5 | 6 | for(int i = 0; i < nums.length; i++) { 7 | int val = Math.abs(nums[i]) - 1; 8 | if(nums[val] > 0) { 9 | nums[val] = -nums[val]; 10 | } 11 | } 12 | 13 | for(int i = 0; i < nums.length; i++) { 14 | if(nums[i] > 0) { 15 | ret.add(i+1); 16 | } 17 | } 18 | return ret; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /python/345_Reverse_Vowels_of_a_String.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def reverseVowels(self, s): 3 | """ 4 | :type s: str 5 | :rtype: str 6 | """ 7 | str_index = [] 8 | vowel = [] 9 | res = [] 10 | pos = -1 11 | for index, value in enumerate(s): 12 | if value in 'aeiouAEIOU': 13 | str_index.append(-1) 14 | vowel.append(value) 15 | else: 16 | str_index.append(index) 17 | for index in str_index: 18 | if index < 0: 19 | res.append(vowel[pos]) 20 | pos -= 1 21 | else: 22 | res.append(s[index]) 23 | return ''.join(res) 24 | 25 | -------------------------------------------------------------------------------- /python/115_Distinct_Subsequences.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def numDistinct(self, s, t): 3 | """ 4 | :type s: str 5 | :type t: str 6 | :rtype: int 7 | """ 8 | # https://discuss.leetcode.com/topic/51131/space-o-mn-and-o-n-python-solutions 9 | dp = [[0 for j in xrange(0, len(t) + 1)] for i in xrange(0, len(s) + 1)] 10 | for j in xrange(1, len(t) + 1): 11 | dp[0][j] = 0 12 | for i in xrange(1, len(s) + 1): 13 | dp[i][0] = 1 14 | dp[0][0] = 1 15 | for i in xrange(1, len(s) + 1): 16 | for j in xrange(1, len(t) + 1): 17 | dp[i][j] = dp[i - 1][j] + dp[i - 1][j - 1] * (s[i - 1] == t[j - 1]) 18 | 19 | return dp[-1][-1] 20 | -------------------------------------------------------------------------------- /python/223_Rectangle Area.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def computeArea(self, A, B, C, D, E, F, G, H): 3 | """ 4 | :type A: int 5 | :type B: int 6 | :type C: int 7 | :type D: int 8 | :type E: int 9 | :type F: int 10 | :type G: int 11 | :type H: int 12 | :rtype: int 13 | """ 14 | # sum of areas of two rectangles 15 | result = (C - A) * (D - B) + (G - E) * (H - F) 16 | # no overlap 17 | if (C <= E or G <= A or H <= B or D <= F): 18 | return result 19 | # overlap length on x 20 | dx = min(C, G) - max(A, E) 21 | # overlap length on y 22 | dy = min(D, H) - max(B, F) 23 | return result - dx * dy 24 | -------------------------------------------------------------------------------- /python/038_Count_and_Say.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def countAndSay(self, n): 3 | """ 4 | :type n: int 5 | :rtype: str 6 | """ 7 | if n == 1: 8 | return '1' 9 | x = '1' 10 | while n > 1: 11 | # each round, read itself 12 | x = self.count(x) 13 | n -= 1 14 | return x 15 | 16 | def count(self, x): 17 | m = list(x) 18 | res = [] 19 | m.append(None) 20 | i , j = 0 , 0 21 | while i < len(m) - 1: 22 | j += 1 23 | if m[j] != m[i]: 24 | # note j - i is the count of m[i] 25 | res += [j - i, m[i]] 26 | i = j 27 | return ''.join(str(s) for s in res) -------------------------------------------------------------------------------- /python/421_Maximum_XOR_of_Two_Numbers_in_an_Array.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def findMaximumXOR(self, nums): 3 | """ 4 | :type nums: List[int] 5 | :rtype: int 6 | """ 7 | # https://discuss.leetcode.com/topic/63299/python-6-lines-bit-by-bit 8 | answer = 0 9 | for i in range(32)[::-1]: 10 | answer <<= 1 11 | # use a set to remove duplicate 12 | prefixes = {num >> i for num in nums} 13 | # if there is x y in prefixes, where x ^ y = answer ^ 1 14 | answer += any(answer ^ 1 ^ p in prefixes for p in prefixes) 15 | return answer 16 | 17 | 18 | if __name__ == '__main__': 19 | s = Solution() 20 | s.findMaximumXOR([3, 10, 5, 25, 2, 8]) 21 | -------------------------------------------------------------------------------- /python/867_Transpose_Matrix.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def transpose(self, A): 3 | """ 4 | :type A: List[List[int]] 5 | :rtype: List[List[int]] 6 | """ 7 | R, C = len(A), len(A[0]) 8 | ans = [[None] * R for _ in xrange(C)] 9 | for r, row in enumerate(A): 10 | for c, val in enumerate(row): 11 | ans[c][r] = val 12 | return ans 13 | # Alternative Solution: 14 | # return zip(*A) 15 | 16 | # def transpose(self, A): 17 | # res = [] 18 | # for i in range(len(A[0])): 19 | # temp = [] 20 | # for j in range(len(A)): 21 | # temp.append(A[j][i]) 22 | # res.append(temp) 23 | # return res 24 | -------------------------------------------------------------------------------- /java/012_Integer_to_Roman.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public String intToRoman(int num) { 3 | Map map = new HashMap(); 4 | map.put(1, "I"); map.put(5, "V"); map.put(10, "X"); 5 | map.put(50, "L"); map.put(100, "C"); map.put(500, "D"); map.put(1000, "M"); 6 | map.put(4, "IV"); map.put(9, "IX"); map.put(40, "XL"); map.put(90, "XC"); 7 | map.put(400, "CD"); map.put(900, "CM"); 8 | 9 | int[] sequence = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1}; 10 | 11 | StringBuffer sb = new StringBuffer(); 12 | for (int i = 0; i= base) { 16 | sb.append(map.get(base)); 17 | num -= base; 18 | } 19 | } 20 | 21 | return sb.toString(); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /python/059_Spiral_Matrix_II.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def generateMatrix(self, n): 3 | """ 4 | :type n: int 5 | :rtype: List[List[int]] 6 | """ 7 | res = [[0] * n for _ in range(n)] 8 | pos = [0, 0] 9 | move = (0, 1) 10 | for index in range(1, n * n + 1): 11 | res[pos[0]][pos[1]] = index 12 | if res[(pos[0] + move[0]) % n][(pos[1] + move[1]) % n] > 0: 13 | # (0, 1) -> (1, 0) -> (0, -1) -> (-1, 0) 14 | move = (move[1], -1 * move[0]) 15 | pos[0] = pos[0] + move[0] 16 | pos[1] = pos[1] + move[1] 17 | return res 18 | 19 | if __name__ == '__main__': 20 | # begin 21 | s = Solution() 22 | print s.generateMatrix(2) -------------------------------------------------------------------------------- /python/150_Evaluate_Reverse_Polish_Notation.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def evalRPN(self, tokens): 3 | """ 4 | :type tokens: List[str] 5 | :rtype: int 6 | """ 7 | stack = [] 8 | for t in tokens: 9 | try: 10 | temp = int(t) 11 | stack.append(temp) 12 | except: 13 | b = stack.pop() 14 | a = stack.pop() 15 | if t == "+": 16 | a += b 17 | elif t == "-": 18 | a -= b 19 | elif t == "*": 20 | a *= b 21 | else: 22 | a = int(a * 1.0 / b) 23 | stack.append(a) 24 | return stack[-1] -------------------------------------------------------------------------------- /python/100_Same_Tree.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode(object): 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.left = None 6 | # self.right = None 7 | 8 | class Solution(object): 9 | def isSameTree(self, p, q): 10 | """ 11 | :type p: TreeNode 12 | :type q: TreeNode 13 | :rtype: bool 14 | """ 15 | if p == q: 16 | return True 17 | try: 18 | left = right = True 19 | if p.val == q.val: 20 | left = self.isSameTree(p.left, q.left) 21 | right = self.isSameTree(p.right, q.right) 22 | return (left and right) 23 | except: 24 | return False 25 | return False -------------------------------------------------------------------------------- /python/836_Rectangle_Overlap.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def isRectangleOverlap(self, rec1, rec2): 3 | """ 4 | :type rec1: List[int] 5 | :type rec2: List[int] 6 | :rtype: bool 7 | """ 8 | return not (rec1[2] <= rec2[0] or # left 9 | rec1[3] <= rec2[1] or # bottom 10 | rec1[0] >= rec2[2] or # right 11 | rec1[1] >= rec2[3]) # top 12 | 13 | # def isRectangleOverlap(self, rec1, rec2): 14 | # def intersect(p_left, p_right, q_left, q_right): 15 | # return min(p_right, q_right) > max(p_left, q_left) 16 | # return (intersect(rec1[0], rec1[2], rec2[0], rec2[2]) and 17 | # intersect(rec1[1], rec1[3], rec2[1], rec2[3])) 18 | -------------------------------------------------------------------------------- /python/157_Read_N_Characters_Given_Read4.py: -------------------------------------------------------------------------------- 1 | # The read4 API is already defined for you. 2 | # @param buf, a list of characters 3 | # @return an integer 4 | # def read4(buf): 5 | 6 | class Solution(object): 7 | def read(self, buf, n): 8 | """ 9 | :type buf: Destination buffer (List[str]) 10 | :type n: Maximum number of characters to read (int) 11 | :rtype: The number of characters read (int) 12 | """ 13 | pos, eof = 0, False 14 | while not eof and pos < n: 15 | buffer = [''] * 4 16 | sz = read4(buffer) 17 | if sz < 4: 18 | eof = True 19 | for i in range(sz): 20 | buf[pos + i] = buffer[i] 21 | pos += min(n - pos, sz) 22 | return pos -------------------------------------------------------------------------------- /python/371_Sum_of_Two_Integers.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def getSum(self, a, b): 3 | """ 4 | :type a: int 5 | :type b: int 6 | :rtype: int 7 | """ 8 | # https://leetcode.com/discuss/111582/java-simple-easy-understand-solution-with-explanation 9 | # in Python this problem is much different because of the negative number 10 | # https://leetcode.com/discuss/111705/one-positive-one-negative-case-successful-for-python-rules 11 | import ctypes 12 | sum = 0 13 | carry = ctypes.c_int32(b) 14 | while carry.value != 0: 15 | sum = a ^ carry.value 16 | carry = ctypes.c_int32(a & carry.value) 17 | carry.value <<= 1 18 | a = sum 19 | return sum -------------------------------------------------------------------------------- /java/680_Valid_Palindrome_II.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean isPalindromeRange(String s, int i, int j) { 3 | for (int k = i; k <= i + (j - i) / 2; k++) { 4 | if (s.charAt(k) != s.charAt(j - k + i)) return false; 5 | } 6 | return true; 7 | } 8 | public boolean validPalindrome(String s) { 9 | for (int i = 0; i < s.length() / 2; i++) { 10 | if (s.charAt(i) != s.charAt(s.length() - 1 - i)) { 11 | // Not equal 12 | int j = s.length() - 1 - i; 13 | // delete left or right 14 | return (isPalindromeRange(s, i + 1, j) || 15 | isPalindromeRange(s, i, j - 1)); 16 | } 17 | } 18 | return true; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /python/112_Path_Sum.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode(object): 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.left = None 6 | # self.right = None 7 | 8 | class Solution(object): 9 | def hasPathSum(self, root, sum): 10 | """ 11 | :type root: TreeNode 12 | :type sum: int 13 | :rtype: bool 14 | """ 15 | if root is None: 16 | return False 17 | sum = sum - root.val 18 | if sum == 0 and root.left is None and root.right is None: 19 | return True 20 | # check left 21 | left = self.hasPathSum(root.left, sum) 22 | # check right 23 | right = self.hasPathSum(root.right, sum) 24 | return (left or right) 25 | -------------------------------------------------------------------------------- /java/937_Reorder_Log_Files.java: -------------------------------------------------------------------------------- 1 | import java.util.List; 2 | 3 | class Solution { 4 | public String[] reorderLogFiles(String[] logs) { 5 | Arrays.sort(logs, (log1, log2) -> { 6 | String[] split1 = log1.split(" ", 2); 7 | String[] split2 = log2.split(" ", 2); 8 | boolean isDigit1 = Character.isDigit(split1[1].charAt(0)); 9 | boolean isDigit2 = Character.isDigit(split2[1].charAt(0)); 10 | if (!isDigit1 && !isDigit2) { 11 | int cmp = split1[1].compareTo(split2[1]); 12 | if (cmp != 0) return cmp; 13 | return split1[0].compareTo(split2[0]); 14 | } 15 | return isDigit1 ? (isDigit2 ? 0 : 1) : -1; 16 | }); 17 | return logs; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /python/139_Word_Break.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def wordBreak(self, s, wordDict): 3 | """ 4 | :type s: str 5 | :type wordDict: Set[str] 6 | :rtype: bool 7 | """ 8 | queue = [0] 9 | ls = len(s) 10 | lenList = [l for l in set(map(len, wordDict))] 11 | visited = [0 for _ in range(0, ls + 1)] 12 | while queue: 13 | start = queue.pop(0) 14 | for l in lenList: 15 | if s[start:start + l] in wordDict: 16 | if start + l == ls: 17 | return True 18 | if visited[start + l] == 0: 19 | queue.append(start + l) 20 | visited[start + l] = 1 21 | return False 22 | 23 | -------------------------------------------------------------------------------- /python/203_Remove_Linked_List_Elements.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode(object): 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.next = None 6 | 7 | class Solution(object): 8 | def removeElements(self, head, val): 9 | """ 10 | :type head: ListNode 11 | :type val: int 12 | :rtype: ListNode 13 | """ 14 | # add a extra head for removing head 15 | prehead = ListNode(-1) 16 | prehead.next = head 17 | last, pos = prehead, head 18 | while pos is not None: 19 | if pos.val == val: 20 | last.next = pos.next 21 | else: 22 | last = pos 23 | pos = pos.next 24 | return prehead.next 25 | 26 | -------------------------------------------------------------------------------- /java/1108_Defanging_an_IP_Address.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public String defangIPaddr(String address) { 3 | // replace 4 | return address.replace(".", "[.]"); 5 | } 6 | /* public String defangIPaddr(String address) { 7 | // split and join 8 | return String.join("[.]", address.split("\\.")); 9 | } */ 10 | /* public String defangIPaddr(String address) { 11 | // replace 12 | return address.replaceAll("\\.", "[.]"); 13 | } */ 14 | /* public String defangIPaddr(String address) { 15 | // new string 16 | StringBuilder sb = new StringBuilder(); 17 | for (char c : address.toCharArray()) { 18 | sb.append(c == '.' ? "[.]" : c); 19 | } 20 | return sb.toString(); 21 | } */ 22 | } 23 | -------------------------------------------------------------------------------- /java/463_Island_Perimeter.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int islandPerimeter(int[][] grid) { 3 | // https://leetcode.com/problems/island-perimeter/discuss/95001/clear-and-easy-java-solution 4 | int islands = 0, neighbours = 0; 5 | for (int i = 0; i < grid.length; i++) { 6 | for (int j = 0; j < grid[i].length; j++) { 7 | if (grid[i][j] == 1) { 8 | islands++; // count islands 9 | if (i < grid.length - 1 && grid[i + 1][j] == 1) neighbours++; // count down neighbours 10 | if (j < grid[i].length - 1 && grid[i][j + 1] == 1) neighbours++; // count right neighbours 11 | } 12 | } 13 | } 14 | return islands * 4 - neighbours * 2; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /python/876_Middle_of_the_Linked_List.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode(object): 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.next = None 6 | 7 | class Solution(object): 8 | # def middleNode(self, head): 9 | # """ 10 | # :type head: ListNode 11 | # :rtype: ListNode 12 | # """ 13 | # res = [] 14 | # while head: 15 | # res.append(head) 16 | # head = head.next 17 | # return res[len(res) / 2] 18 | 19 | def middleNode(self, head): 20 | # Fast point is 2 times faster than slow point 21 | fast = slow = head 22 | while fast and fast.next: 23 | slow = slow.next 24 | fast = fast.next.next 25 | return slow 26 | -------------------------------------------------------------------------------- /python/1064_Fixed_Point.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | # def fixedPoint(self, A): 3 | # """ 4 | # :type A: List[int] 5 | # :rtype: int 6 | # """ 7 | # for index, value in enumerate(A): 8 | # # Because if A[i] > i, then i can never be greater than A[i] any more 9 | # if index == value: 10 | # return index 11 | # elif index < value: 12 | # return -1 13 | 14 | def fixedPoint(self, A): 15 | l, h = 0, len(A) - 1 16 | while l <= h: 17 | mid = (l + h) // 2 18 | if A[mid] < mid: 19 | l = mid + 1 20 | elif A[mid] > mid: 21 | h = mid - 1 22 | else: 23 | return mid 24 | return -1 25 | -------------------------------------------------------------------------------- /python/340_Longest_Substring_with_At_Most_K_Distinct_Characters.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def lengthOfLongestSubstringKDistinct(self, s, k): 3 | """ 4 | :type s: str 5 | :type k: int 6 | :rtype: int 7 | """ 8 | count = [0] * 256 9 | i, numDistinct, maxLen = 0, 0, 0 10 | for j in range(len(s)): 11 | # udpate j 12 | if count[ord(s[j])] == 0: 13 | numDistinct += 1 14 | count[ord(s[j])] += 1 15 | # udpate i 16 | while numDistinct > k: 17 | count[ord(s[i])] -= 1 18 | if count[ord(s[i])] == 0: 19 | numDistinct -= 1 20 | i += 1 21 | maxLen = max(j - i + 1, maxLen) 22 | return maxLen -------------------------------------------------------------------------------- /java/475_Heaters.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int findRadius(int[] houses, int[] heaters) { 3 | Arrays.sort(heaters); 4 | int result = Integer.MIN_VALUE; 5 | 6 | for (int house : houses) { 7 | // Java binarySearch return - insertPoint - 1 if not found 8 | // This point is greater than value you want 9 | int index = Arrays.binarySearch(heaters, house); 10 | if (index < 0) index = -(index + 1); 11 | int dist1 = index - 1 >= 0 ? house - heaters[index - 1] : Integer.MAX_VALUE; 12 | int dist2 = index < heaters.length ? heaters[index] - house : Integer.MAX_VALUE; 13 | result = Math.max(result, Math.min(dist1, dist2)); 14 | } 15 | return result; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /java/668_Kth_Smallest_Number_in_Multiplication_Table.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | // https://leetcode.com/problems/kth-smallest-number-in-multiplication-table/solution/ 3 | public boolean enough(int x, int m, int n, int k) { 4 | int count = 0; 5 | for (int i = 1; i <= m; i++) { 6 | count += Math.min(x / i, n); 7 | } 8 | return count >= k; 9 | } 10 | 11 | public int findKthNumber(int m, int n, int k) { 12 | int lo = 1, hi = m * n; 13 | while (lo < hi) { 14 | // ith row [i, 2*i, 3*i, ..., n*i] 15 | // for each column, k = x // i 16 | int mi = lo + (hi - lo) / 2; 17 | if (!enough(mi, m, n, k)) lo = mi + 1; 18 | else hi = mi; 19 | } 20 | return lo; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /java/700_Search_in_a_Binary_Search_Tree.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode(int x) { val = x; } 8 | * } 9 | */ 10 | class Solution { 11 | /*public TreeNode searchBST(TreeNode root, int val) { 12 | // Recursive 13 | if (root == null) return root; 14 | if (root.val == val) return root; 15 | else return val= 0: 14 | curr += gas[begin] - cost[begin] 15 | begin += 1 16 | else: 17 | end -= 1 18 | curr += gas[end] - cost[end] 19 | if curr >= 0: 20 | return end 21 | else: 22 | return -1 23 | 24 | -------------------------------------------------------------------------------- /python/409_Longest_Palindrome.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | # https://leetcode.com/problems/longest-palindrome/solution/ 3 | # def longestPalindrome(self, s): 4 | # ans = 0 5 | # for v in collections.Counter(s).itervalues(): 6 | # ans += v / 2 * 2 7 | # if ans % 2 == 0 and v % 2 == 1: 8 | # ans += 1 9 | # return ans 10 | def longestPalindrome(self, s): 11 | ans = 0 12 | char_map = {} 13 | for c in s: 14 | char_map[c] = char_map.get(c, 0) + 1 15 | for c in char_map.keys(): 16 | if char_map[c] % 2 == 0: 17 | ans += char_map.pop(c) 18 | else: 19 | ans += char_map[c] / 2 * 2 20 | if len(char_map) != 0: 21 | ans += 1 22 | return ans -------------------------------------------------------------------------------- /python/905_Sort_Array_By_Parity.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | # def sortArrayByParity(self, A): 3 | # """ 4 | # :type A: List[int] 5 | # :rtype: List[int] 6 | # """ 7 | # # Bad idea, O(nlogn) 8 | # A.sort(key=lambda x: x % 2) 9 | # return A 10 | 11 | # def sortArrayByParity(self, A): 12 | # return ([x for x in A if x % 2 == 0] + 13 | # [x for x in A if x % 2 == 1]) 14 | 15 | def sortArrayByParity(self, A): 16 | # Quit like quick sort or quick selection 17 | lo, hi = 0, len(A) - 1 18 | while lo < hi: 19 | if A[lo] % 2 > A[hi] % 2: 20 | A[lo], A[hi] = A[hi], A[lo] 21 | if A[lo] % 2 == 0: lo += 1 22 | if A[hi] % 2 == 1: hi -= 1 23 | return A 24 | -------------------------------------------------------------------------------- /python/372_Super_Pow.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def __init__(self): 3 | self.base = 1337 4 | 5 | def superPow(self, a, b): 6 | """ 7 | :type a: int 8 | :type b: List[int] 9 | :rtype: int 10 | """ 11 | # One knowledge: ab % k = (a%k)(b%k)%k 12 | # a^1234567 % k = (a^1234560 % k) * (a^7 % k) % k = (a^123456 % k)^10 % k * (a^7 % k) % k 13 | if b is None or len(b) == 0: 14 | return 1 15 | last_digit = b.pop() 16 | return self.powmod(self.superPow(a, b), 10) * \ 17 | self.powmod(a, last_digit) % self.base 18 | 19 | def powmod(self, a, k): 20 | a %= self.base 21 | result = 1 22 | for i in range(k): 23 | result = (result * a) % self.base 24 | return result 25 | -------------------------------------------------------------------------------- /python/751_IP_to_CIDR.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def ipToInt(self, ip): 3 | ans = 0 4 | for x in ip.split('.'): 5 | ans = 256 * ans + int(x) 6 | return ans 7 | 8 | def intToIP(self, x): 9 | return ".".join(str((x >> i) % 256) 10 | for i in (24, 16, 8, 0)) 11 | 12 | def ipToCIDR(self, ip, n): 13 | # Start value of IP 14 | start = self.ipToInt(ip) 15 | ans = [] 16 | while n: 17 | # Last 1 of start or can start from 0 18 | mask = max(33 - (start & -start).bit_length(), 19 | 33 - n.bit_length()) 20 | ans.append(self.intToIP(start) + '/' + str(mask)) 21 | start += 1 << (32 - mask) 22 | n -= 1 << (32 - mask) 23 | return ans 24 | -------------------------------------------------------------------------------- /java/008_String_to_Integer(atoi).java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | // example in leetcode book 3 | private static final int maxDiv10 = Integer.MAX_VALUE / 10; 4 | public int myAtoi(String str) { 5 | int i = 0, n = str.length(); 6 | while (i < n && Character.isWhitespace(str.charAt(i))) 7 | i++; 8 | int sign = 1; 9 | if (i < n && str.charAt(i) == '+') 10 | i++; 11 | else if (i < n && str.charAt(i) == '-') { 12 | sign = -1; 13 | i++; 14 | } 15 | int num = 0; 16 | while (i < n && Character.isDigit(str.charAt(i))) { 17 | int digit = Character.getNumericValue(str.charAt(i)); 18 | if (num > maxDiv10 || num == maxDiv10 && digit >= 8) 19 | return sign == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE; 20 | num = num * 10 + digit; 21 | i++; 22 | } 23 | return sign * num; 24 | } 25 | } -------------------------------------------------------------------------------- /java/868_Binary_Gap.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | /*public int binaryGap(int n) { 3 | // Store Indexes 4 | int[] A = new int[32]; 5 | int t = 0; 6 | for (int i = 0; i < 32; ++i) 7 | if (((N >> i) & 1) != 0) 8 | A[t++] = i; 9 | 10 | int ans = 0; 11 | for (int i = 0; i < t - 1; ++i) 12 | ans = Math.max(ans, A[i+1] - A[i]); 13 | return ans; 14 | }*/ 15 | 16 | public int binaryGap(int N) { 17 | int last = -1, ans = 0; 18 | for (int i = 0; i < 32; ++i) 19 | if (((N >> i) & 1) > 0) { 20 | // Store max 21 | if (last >= 0) 22 | ans = Math.max(ans, i - last); 23 | last = i; 24 | } 25 | return ans; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /python/268_Missing_Number.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | # def missingNumber(self, nums): 3 | # """ 4 | # :type nums: List[int] 5 | # :rtype: int 6 | # """ 7 | # n = len(nums) 8 | # return (n ** 2 + n) / 2 - sum(nums) 9 | 10 | def missingNumber(self, nums): 11 | res = len(nums) 12 | for i, v in enumerate(nums): 13 | res ^= i 14 | res ^= v 15 | return res 16 | 17 | # def missingNumber(self, nums): 18 | # nums.sort() 19 | # left, right = 0, len(nums) - 1 20 | # while left <= right: 21 | # mid = (left + right) / 2 22 | # if nums[mid] <= mid: 23 | # left = mid + 1 24 | # else: 25 | # right = mid - 1 26 | # return left 27 | -------------------------------------------------------------------------------- /python/303_Range_Sum_Query_Immutable.py: -------------------------------------------------------------------------------- 1 | class NumArray(object): 2 | def __init__(self, nums): 3 | """ 4 | initialize your data structure here. 5 | :type nums: List[int] 6 | """ 7 | self.res = [0] * (len(nums) + 1) 8 | self.data = list(nums) 9 | for i in range(len(self.data)): 10 | self.res[i + 1] = self.res[i] + nums[i] 11 | 12 | def sumRange(self, i, j): 13 | """ 14 | sum of elements nums[i..j], inclusive. 15 | :type i: int 16 | :type j: int 17 | :rtype: int 18 | """ 19 | return self.res[j + 1] - self.res[i] 20 | 21 | # Your NumArray object will be instantiated and called as such: 22 | # numArray = NumArray(nums) 23 | # numArray.sumRange(0, 1) 24 | # numArray.sumRange(1, 2) -------------------------------------------------------------------------------- /python/161_One_Edit_Distance.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def isOneEditDistance(self, s, t): 3 | """ 4 | :type s: str 5 | :type t: str 6 | :rtype: bool 7 | """ 8 | ls_s, ls_t = len(s) ,len(t) 9 | # reverse to reduce conditions 10 | if ls_s > ls_t: 11 | return self.isOneEditDistance(t, s) 12 | # edit distance is greater than 1 13 | if ls_t - ls_s > 1: 14 | return False 15 | i, shift = 0, ls_t - ls_s 16 | # find the different position 17 | while i < ls_s and s[i] == t[i]: 18 | i += 1 19 | if i == ls_s: 20 | return shift > 0 21 | if shift == 0: 22 | i += 1 23 | while i < ls_s and s[i] == t[i + shift]: 24 | i += 1 25 | return i == ls_s -------------------------------------------------------------------------------- /java/066_Plus_One.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[] plusOne(int[] digits) { 3 | return addToDigit(digits, digits.length - 1); 4 | } 5 | 6 | private int[] addToDigit(int[] digits, int index) { 7 | if (index == -1) { 8 | int[] newDigits = new int[digits.length + 1]; 9 | newDigits[0] = 1; 10 | for (int i = 0; i < digits.length; i++) { 11 | newDigits[i + 1] = digits[i]; 12 | } 13 | return newDigits; 14 | } 15 | if (digits[index] == 9) { 16 | digits[index] = 0; 17 | return addToDigit(digits, index - 1); 18 | } else { 19 | digits[index]++; 20 | return digits; 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /java/804_Unique_Morse_Code_Words.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | // https://leetcode.com/problems/unique-morse-code-words/solution/ 3 | public int uniqueMorseRepresentations(String[] words) { 4 | String[] MORSE = new String[]{".-","-...","-.-.","-..",".","..-.","--.", 5 | "....","..",".---","-.-",".-..","--","-.", 6 | "---",".--.","--.-",".-.","...","-","..-", 7 | "...-",".--","-..-","-.--","--.."}; 8 | 9 | Set seen = new HashSet(); 10 | for (String word: words) { 11 | StringBuilder code = new StringBuilder(); 12 | for (char c: word.toCharArray()) 13 | code.append(MORSE[c - 'a']); 14 | seen.add(code.toString()); 15 | } 16 | 17 | return seen.size(); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /python/091_Decode_Ways.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def numDecodings(self, s): 3 | """ 4 | :type s: str 5 | :rtype: int 6 | """ 7 | ls = len(s) 8 | if ls == 0: 9 | return 0 10 | dp = [0] * ls 11 | for index in range(ls): 12 | if index >= 1 and int(s[index - 1:index + 1]) < 27 and int(s[index - 1:index + 1]) >= 10: 13 | if index == 1: 14 | dp[index] = 1 15 | else: 16 | # 11-26 17 | dp[index] += dp[index - 2] 18 | if int(s[index]) != 0: 19 | if index == 0: 20 | dp[index] = 1 21 | else: 22 | # 1-9 23 | dp[index] += dp[index - 1] 24 | return dp[ls - 1] 25 | -------------------------------------------------------------------------------- /python/276_Paint_Fence.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | # def numWays(self, n, k): 3 | # """ 4 | # :type n: int 5 | # :type k: int 6 | # :rtype: int 7 | # """ 8 | # w = [0, k, k*k] 9 | # while len(w) <= n: 10 | # w += sum(w[-2:]) * (k-1), 11 | # return w[n] 12 | def numWays(self, n, k): 13 | if n == 0: 14 | return 0 15 | elif n == 1: 16 | return k 17 | # two step dp 18 | # ways[1] = k 19 | # ways[2] = k * k 20 | # ways[i>2] = (ways[i-1] + ways[i-2]) * (k - 1) 21 | dp = [0] * 2 22 | dp[0] = k 23 | dp[1] = k * k 24 | for i in range(2, n): 25 | temp = dp[1] 26 | dp[1] = sum(dp) * (k - 1) 27 | dp[0] = temp 28 | return dp[1] -------------------------------------------------------------------------------- /python/080_Remove_Duplicates_from_Sorted_Array_II.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def removeDuplicates(self, nums): 3 | """ 4 | :type nums: List[int] 5 | :rtype: int 6 | """ 7 | if nums is None: 8 | return 0 9 | length = len(nums) 10 | result = 0 11 | i = j = 0 12 | while i < length: 13 | j = i 14 | while j < length: 15 | if nums[j] != nums[i]: 16 | break 17 | j += 1 18 | if j-i > 2: 19 | length -= j-i-2 20 | for k in range(j-i-2): 21 | del nums[i] 22 | result += 2 23 | j = i+2 24 | else: 25 | result += (j-i) 26 | i = j 27 | return result 28 | 29 | 30 | -------------------------------------------------------------------------------- /python/242_Valid_Anagram.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | # def isAnagram(self, s, t): 3 | # """ 4 | # :type s: str 5 | # :type t: str 6 | # :rtype: bool 7 | # """ 8 | # # sort 9 | # return sorted(s) == sorted(t) 10 | 11 | def isAnagram(self, s, t): 12 | """ 13 | :type s: str 14 | :type t: str 15 | :rtype: bool 16 | """ 17 | # hash 18 | # https://leetcode.com/articles/valid-anagram/ 19 | if len(s) != len(t): 20 | return False 21 | counter = [0] * 26 22 | for i in range(len(s)): 23 | counter[ord(s[i]) - ord('a')] += 1 24 | counter[ord(t[i]) - ord('a')] -= 1 25 | for num in counter: 26 | if num != 0: 27 | return False 28 | return True -------------------------------------------------------------------------------- /python/373_Find_K_Pairs_with_Smallest_Sums.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def kSmallestPairs(self, nums1, nums2, k): 3 | """ 4 | :type nums1: List[int] 5 | :type nums2: List[int] 6 | :type k: int 7 | :rtype: List[List[int]] 8 | """ 9 | # https://discuss.leetcode.com/topic/50450/slow-1-liner-to-fast-solutions 10 | queue = [] 11 | def push(i, j): 12 | if i < len(nums1) and j < len(nums2): 13 | heapq.heappush(queue, [nums1[i] + nums2[j], i, j]) 14 | push(0, 0) 15 | pairs = [] 16 | while queue and len(pairs) < k: 17 | _, i, j = heapq.heappop(queue) 18 | pairs.append([nums1[i], nums2[j]]) 19 | push(i, j + 1) 20 | if j == 0: 21 | push(i + 1, 0) 22 | return pairs -------------------------------------------------------------------------------- /python/007_Reverse_Integer.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def reverse(self, x): 3 | # https://leetcode.com/problems/reverse-integer/ 4 | # flag = True if x < 0 else False 5 | # if flag: 6 | # x = -x 7 | # x = str(x)[::-1] 8 | 9 | # if flag: 10 | # x = "-" + x 11 | 12 | # value = 2 ** 31 13 | # x = int(x) 14 | # if -value <= x < value: 15 | # return x 16 | # return 0 17 | 18 | is_neg = False 19 | if x < 0: 20 | x = -x 21 | is_neg = True 22 | 23 | res = 0 24 | while x > 0: 25 | res *= 10 26 | res += x % 10 27 | x //= 10 28 | if is_neg: 29 | res = -res 30 | 31 | if res < -2**31 or res > 2**31-1: 32 | return 0 33 | return res 34 | -------------------------------------------------------------------------------- /python/016_3Sum_Closest.py: -------------------------------------------------------------------------------- 1 | # class Solution(object): 2 | # def threeSumClosest(self, nums, target): 3 | # """ 4 | # :type nums: List[int] 5 | # :type target: int 6 | # :rtype: int 7 | # """ 8 | class Solution(object): 9 | def threeSumClosest(self, nums, target): 10 | ls = len(nums) 11 | sort_nums = sorted(nums) 12 | res = nums[0] + nums[1] + nums[2] 13 | for i in range(ls - 2): 14 | j, k = i + 1, ls - 1 15 | while j < k: 16 | temp = sort_nums[i] + sort_nums[j] + sort_nums[k] 17 | if abs(target - temp) < abs(target - res): 18 | res = temp 19 | if temp < target: 20 | j += 1 21 | else: 22 | k -= 1 23 | return res 24 | 25 | 26 | -------------------------------------------------------------------------------- /python/388_Longest_Absolute_File_Path.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def lengthLongestPath(self, input): 3 | """ 4 | :type input: str 5 | :rtype: int 6 | """ 7 | if input is None or len(input) == 0: 8 | return 0 9 | lines = input.split('\n') 10 | last_level_len = [0] * (len(lines) + 1); max_len = 0 11 | for line in lines: 12 | try: 13 | level = line.rindex('\t') + 1 14 | except: 15 | level = 0 16 | cur_len = last_level_len[level + 1] = last_level_len[level] + len(line) - level + 1 17 | if '.' in line: 18 | max_len = max(max_len, cur_len - 1) 19 | return max_len 20 | 21 | if __name__ == '__main__': 22 | s = Solution() 23 | print s.lengthLongestPath("dir\n file.txt") 24 | -------------------------------------------------------------------------------- /java/876_Middle_of_the_Linked_List.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * public class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode(int x) { val = x; } 7 | * } 8 | */ 9 | class Solution { 10 | // public ListNode middleNode(ListNode head) { 11 | // List array = new ArrayList(); 12 | // while (head != null) { 13 | // array.add(head); 14 | // head = head.next; 15 | // } 16 | // return array.get(array.size() / 2); 17 | // } 18 | public ListNode middleNode(ListNode head) { 19 | ListNode fast, slow; 20 | fast = slow = head; 21 | while (fast != null && fast.next != null) { 22 | slow = slow.next; 23 | fast = fast.next.next; 24 | } 25 | return slow; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /python/509_Fibonacci_Number.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | 3 | def __init__(self): 4 | self.memo = [] 5 | self.memo.append(0) 6 | self.memo.append(1) 7 | 8 | def fib(self, N): 9 | """ 10 | DP with memo 11 | :type N: int 12 | :rtype: int 13 | """ 14 | if N < len(self.memo): 15 | return self.memo[N] 16 | for i in range(len(self.memo), N + 1): 17 | self.memo.append(self.memo[i - 1] + self.memo[i - 2]) 18 | return self.memo[N] 19 | 20 | # def fib(self, N): 21 | # """ 22 | # Recursively, O(n) 23 | # :type N: int 24 | # :rtype: int 25 | # """ 26 | # if N == 0: 27 | # return 0 28 | # if N == 1: 29 | # return 1 30 | # return self.fib(N - 1) + self.fib(N - 2) 31 | -------------------------------------------------------------------------------- /python/165_Compare_Version_Numbers.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def compareVersion(self, version1: str, version2: str) -> int: 3 | l1=list(map(int,version1.split('.'))) 4 | l2=list(map(int,version2.split('.'))) 5 | if l1==l2: 6 | return(0) 7 | 8 | a=len(l1) 9 | b=len(l2) 10 | 11 | if a>b: 12 | for i in range(a-b): 13 | l2.append("0") 14 | 15 | else: 16 | for i in range(b-a): 17 | l1.append("0") 18 | 19 | for i in range(len(l1)): 20 | if int(l1[i])>int(l2[i]): 21 | return(1) 22 | 23 | elif int(l1[i])= numRows) { 21 | index = 2*(numRows-1) - index; 22 | } 23 | str_array[index]+=c; 24 | } 25 | 26 | for(int i=0;inext == NULL) 15 | return head; 16 | // Previous pointer 17 | ListNode *previous = head; 18 | // Current pointer 19 | ListNode *curr = head->next; 20 | head->next = NULL; 21 | while (curr->next) { 22 | ListNode *next = curr->next; 23 | curr->next = previous; 24 | previous = curr; 25 | curr = next; 26 | } 27 | curr->next = previous; 28 | return curr; 29 | } 30 | }; 31 | -------------------------------------------------------------------------------- /python/140_Word_Break_II.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | # https://discuss.leetcode.com/topic/12997/11ms-c-solution-concise 3 | def __init__(self): 4 | self.solution = {} 5 | 6 | def wordBreak(self, s, wordDict): 7 | """ 8 | :type s: str 9 | :type wordDict: Set[str] 10 | :rtype: List[str] 11 | """ 12 | try: 13 | return self.solution[s] 14 | except KeyError: 15 | pass 16 | result = [] 17 | if s in wordDict: 18 | result.append(s) 19 | for i in range(1, len(s)): 20 | word = s[i:] 21 | if word in wordDict: 22 | rem = s[:i] 23 | prev = self.wordBreak(rem, wordDict) 24 | result.extend([res + ' ' + word for res in prev]) 25 | self.solution[s] = result 26 | return result -------------------------------------------------------------------------------- /python/804_Unique_Morse_Code_Words.py: -------------------------------------------------------------------------------- 1 | Morse_tab = [".-","-...","-.-.", 2 | "-..",".","..-.","--.","....", 3 | "..",".---","-.-",".-..","--", 4 | "-.","---",".--.","--.-",".-.", 5 | "...","-","..-","...-",".--", 6 | "-..-","-.--","--.."] 7 | 8 | class Solution(object): 9 | # https://leetcode.com/problems/unique-morse-code-words/solution/ 10 | def uniqueMorseRepresentations(self, words): 11 | """ 12 | :type words: List[str] 13 | :rtype: int 14 | """ 15 | if len(words) == 0: 16 | return 0 17 | ans_set = set() 18 | for word in words: 19 | morsed = "" 20 | for c in word: 21 | morsed += Morse_tab[ord(c) - ord('a')] 22 | 23 | ans_set.add(morsed) 24 | return len(ans_set) 25 | -------------------------------------------------------------------------------- /python/937_Reorder_Log_Files.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | # def reorderLogFiles(self, logs): 3 | # """ 4 | # :type logs: List[str] 5 | # :rtype: List[str] 6 | # """ 7 | # def f(log): 8 | # id_, rest = log.split(" ", 1) 9 | # return (0, rest, id_) if rest[0].isalpha() else (1,) 10 | 11 | # # Python sort is stable, so digit with keep their order 12 | # return sorted(logs, key = f) 13 | 14 | def reorderLogFiles(self, logs): 15 | letter_logs = [] 16 | digit_logs = [] 17 | for log in logs: 18 | if log.split(' ')[1].isnumeric(): 19 | digit_logs.append(log) 20 | else: 21 | letter_logs.append(log) 22 | return sorted(letter_logs, key=lambda x: x.split(' ')[1:] + x.split(' ')[0]) + digit_logs 23 | -------------------------------------------------------------------------------- /python/160_Intersection_of_Two_Linked_Lists.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode(object): 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.next = None 6 | 7 | class Solution(object): 8 | # https://leetcode.com/articles/intersection-two-linked-lists/ 9 | def getIntersectionNode(self, headA, headB): 10 | """ 11 | :type head1, head1: ListNode 12 | :rtype: ListNode 13 | """ 14 | # two points 15 | if not headA or not headB: 16 | return None 17 | a, b = headA, headB 18 | ans = None 19 | while a or b: 20 | if not a: 21 | a = headB 22 | if not b: 23 | b = headA 24 | if a == b and not ans: 25 | ans = a 26 | a, b = a.next, b.next 27 | return ans 28 | -------------------------------------------------------------------------------- /java/004_Median_of_Two_Sorted_Arrays.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | // example in leetcode book 3 | public double findMedianSortedArrays(int[] nums1, int[] nums2) { 4 | int p1 = 0, p2 = 0, pos = 0; 5 | int ls1 = nums1.length, ls2 = nums2.length; 6 | int[] all_nums = new int[ls1+ls2]; 7 | double median = 0.0; 8 | while (p1 < ls1 && p2 < ls2){ 9 | if (nums1[p1] <= nums2[p2]) 10 | all_nums[pos++] = nums1[p1++]; 11 | else 12 | all_nums[pos++] = nums2[p2++]; 13 | } 14 | while (p1 < ls1) 15 | all_nums[pos++] = nums1[p1++]; 16 | while (p2 < ls2) 17 | all_nums[pos++] = nums2[p2++]; 18 | if ((ls1 + ls2) % 2 == 1) 19 | median = all_nums[(ls1 + ls2) / 2]; 20 | else 21 | median = (all_nums[(ls1 + ls2) / 2] + all_nums[(ls1 + ls2) / 2 - 1]) / 2.0; 22 | return median; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /java/697_Degree_of_an_Array.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int findShortestSubArray(int[] nums) { 3 | Map left = new HashMap(), 4 | right = new HashMap(), count = new HashMap(); 5 | 6 | for (int i = 0; i < nums.length; i++) { 7 | int x = nums[i]; 8 | // left most position 9 | if (left.get(x) == null) left.put(x, i); 10 | // right most position 11 | right.put(x, i); 12 | count.put(x, count.getOrDefault(x, 0) + 1); 13 | } 14 | 15 | int ans = nums.length; 16 | int degree = Collections.max(count.values()); 17 | for (int x: count.keySet()) { 18 | if (count.get(x) == degree) { 19 | ans = Math.min(ans, right.get(x) - left.get(x) + 1); 20 | } 21 | } 22 | return ans; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /cpp/668_Kth_Smallest_Number_in_Multiplication_Table.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | #define ll long long int 4 | bool valid(ll x, int m, int n, int k) { 5 | int cnt = 0; 6 | for (int i = 1; i <= m; i++) { 7 | cnt += n < x / i ? n : x / i; 8 | if (x / i == 0) 9 | break; 10 | } 11 | return cnt >= k; 12 | } 13 | 14 | int findKthNumber(int n1, int n2, int k) { 15 | ll l = 0, r = n1 * n2, ans; 16 | while (l <= r) { 17 | // ith row [i, 2*i, 3*i, ..., n*i] 18 | // for each column, k = x // i 19 | ll m = l + (r - l) / 2; 20 | if (valid(m, n1, n2, k)) { 21 | ans = m; 22 | r = m - 1; 23 | } else { 24 | l = m + 1; 25 | } 26 | } 27 | return ans; 28 | } 29 | }; 30 | -------------------------------------------------------------------------------- /java/22_Generate_Parentheses.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | // main function 3 | public List generateParenthesis(int n) { 4 | ArrayList list = new ArrayList<>(); 5 | rec(list, "(", n - 1, n); 6 | return list; 7 | } 8 | 9 | // axiom : if start == end == 0, add str in list. 10 | // IDEA : 11 | // In well-formed parentheses 12 | // close character(")") has to be bigger than open character("(") 13 | // So, we can solve this problem with recursion. 14 | public void rec(List list, String str, int start, int end) { 15 | if(start == 0 && end == 0) { 16 | list.add(str); 17 | } 18 | 19 | if(start > 0) { 20 | rec(list, str + "(", start - 1, end); 21 | } 22 | if(end > start) { 23 | rec(list, str + ")", start, end - 1); 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /python/128_Longest_Consecutive_Sequence.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def longestConsecutive(self, nums): 3 | """ 4 | :type nums: List[int] 5 | :rtype: int 6 | """ 7 | 8 | def longestConsecutive(self, num): 9 | # Pop adjacency O(n) and O(n) 10 | num = set(num) 11 | maxLen = 0 12 | while num: 13 | n = num.pop() 14 | i = n + 1 15 | l1 = 0 16 | l2 = 0 17 | while i in num: 18 | num.remove(i) 19 | i += 1 20 | l1 += 1 21 | i = n - 1 22 | while i in num: 23 | num.remove(i) 24 | i -= 1 25 | l2 += 1 26 | maxLen = max(maxLen, l1 + l2 + 1) 27 | return maxLen -------------------------------------------------------------------------------- /python/156_Binary_Tree_Upside_Down.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode(object): 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.left = None 6 | # self.right = None 7 | 8 | class Solution(object): 9 | # p.left = parent.right 10 | # parent.right = p.right 11 | # p.right = parent 12 | # parent = p.left 13 | # p = left 14 | def upsideDownBinaryTree(self, root): 15 | """ 16 | :type root: TreeNode 17 | :rtype: TreeNode 18 | """ 19 | # top-down 20 | node, parent, parentRight = root, None, None 21 | while node is not None: 22 | left = node.left 23 | node.left = parentRight 24 | parentRight = node.right 25 | node.right = parent 26 | parent = node 27 | node = left 28 | return parent -------------------------------------------------------------------------------- /python/954_Array_of_Doubled_Pairs.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def canReorderDoubled(self, A): 3 | """ 4 | :type A: List[int] 5 | :rtype: bool 6 | """ 7 | v_map = {} 8 | A.sort(key=lambda x: abs(x)) 9 | for n in A: 10 | v_map[n] = v_map.get(n, 0) + 1 11 | for n in A: 12 | if v_map[n] <= 0: 13 | continue 14 | if 2 * n in v_map and v_map[2 * n] > 0: 15 | v_map[n] -= 1 16 | v_map[2 * n] -= 1 17 | else: 18 | return False 19 | return True 20 | 21 | 22 | if __name__ == '__main__': 23 | s = Solution() 24 | print s.canReorderDoubled([3, 1, 3, 6]) 25 | print s.canReorderDoubled([2, 1, 2, 6]) 26 | print s.canReorderDoubled([4, -2, 2, -4]) 27 | print s.canReorderDoubled([1, 2, 4, 16, 8, 4]) 28 | -------------------------------------------------------------------------------- /java/728_Self_Dividing_Numbers.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public List selfDividingNumbers(int left, int right) { 3 | LinkedList list = new LinkedList(); 4 | for(int i = left; i <= right; i++) { 5 | if(isSelfDiving(i)) 6 | list.add(i); 7 | } 8 | return list; 9 | } 10 | 11 | public boolean isSelfDiving(int num) { 12 | int digit = num % 10; 13 | int temp = num; 14 | boolean isTrue = true; 15 | while(temp != 0) { 16 | // 0 is special 17 | if(digit == 0 || num % digit != 0) { 18 | isTrue = false; 19 | break; 20 | } else { 21 | temp /= 10; 22 | digit = temp % 10; 23 | } 24 | } 25 | return isTrue; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /python/101_Symmetric_Tree.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode(object): 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.left = None 6 | # self.right = None 7 | 8 | class Solution(object): 9 | def isSymmetric(self, root): 10 | """ 11 | :type root: TreeNode 12 | :rtype: bool 13 | """ 14 | if root is None: 15 | return True 16 | return self.mirrorVisit(root.left, root.right) 17 | 18 | def mirrorVisit(self, left, right): 19 | if left is None and right is None: 20 | return True 21 | try: 22 | if left.val == right.val: 23 | if self.mirrorVisit(left.left, right.right) and self.mirrorVisit(left.right, right.left): 24 | return True 25 | return False 26 | except: 27 | return False -------------------------------------------------------------------------------- /python/041_First_Missing_Positive.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def firstMissingPositive(self, nums): 3 | """ 4 | :type nums: List[int] 5 | :rtype: int 6 | """ 7 | # https://leetcode.com/discuss/86025/java-clean-o-n-solution-with-explanation 8 | ls = len(nums) 9 | index = 0 10 | while index < ls: 11 | # nums[nums[index] - 1] == nums[index] means that the num is in right position 12 | if nums[index] <= 0 or nums[index] > ls or nums[nums[index] - 1] == nums[index]: 13 | index += 1 14 | else: 15 | # swap current num to correct position 16 | pos = nums[index] - 1 17 | nums[index], nums[pos] = nums[pos], nums[index] 18 | res = 0 19 | while res < ls and nums[res] == res + 1: 20 | res += 1 21 | return res + 1 22 | -------------------------------------------------------------------------------- /python/064_Minimum_Path_Sum.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def minPathSum(self, grid): 3 | """ 4 | :type grid: List[List[int]] 5 | :rtype: int 6 | """ 7 | height = len(grid) 8 | if height == 0: 9 | return 0 10 | width = len(grid[0]) 11 | pathmap = [] 12 | for i in range(height): 13 | pathmap.append([100000000000] * width) 14 | pathmap[0][0] = grid[0][0] 15 | for i in range(height): 16 | for j in range(width): 17 | compare = [pathmap[i][j]] 18 | if i - 1 >= 0: 19 | compare.append(pathmap[i - 1][j] + grid[i][j]) 20 | if j - 1 >= 0: 21 | compare.append(pathmap[i][j - 1] + grid[i][j]) 22 | # min choice 23 | pathmap[i][j] = min(compare) 24 | return pathmap[-1][-1] -------------------------------------------------------------------------------- /python/263_Ugly_Number.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | # def isUgly(self, num): 3 | # """ 4 | # :type num: int 5 | # :rtype: bool 6 | # """ 7 | # if num <= 0: 8 | # return False 9 | # if num <= 6: 10 | # return True 11 | # while num % 2 == 0: 12 | # num //= 2 13 | # while num % 3 == 0: 14 | # num //= 3 15 | # while num % 5 == 0: 16 | # num //= 5 17 | # if num == 1: 18 | # return True 19 | # return False 20 | def isUgly(self, num): 21 | if num <= 0: 22 | return False 23 | divisors = [2, 3, 5] 24 | for d in divisors: 25 | while num % d == 0: 26 | num /= d 27 | return num == 1 28 | 29 | if __name__ == '__main__': 30 | s = Solution() 31 | print s.isUgly(-2147483648) 32 | -------------------------------------------------------------------------------- /python/290_Word_Pattern.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def wordPattern(self, pattern, str): 3 | """ 4 | :type pattern: str 5 | :type str: str 6 | :rtype: bool 7 | """ 8 | if pattern is None or str is None: 9 | return True 10 | # double map 11 | words_to_pattern = {} 12 | pattern_to_words = {} 13 | word_list = str.split(' ') 14 | if len(word_list) != len(pattern): 15 | return False 16 | for index, word in enumerate(word_list): 17 | curr_p = pattern[index] 18 | if pattern_to_words.get(curr_p, word) != word or words_to_pattern.get(word, curr_p) != curr_p: 19 | return False 20 | pattern_to_words[curr_p] = pattern_to_words.get(curr_p, word) 21 | words_to_pattern[word] = words_to_pattern.get(word, curr_p) 22 | return True -------------------------------------------------------------------------------- /python/142_Linked_List_Cycle_II.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode(object): 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.next = None 6 | 7 | class Solution(object): 8 | def detectCycle(self, head): 9 | """ 10 | :type head: ListNode 11 | :rtype: ListNode 12 | """ 13 | # Two points 14 | # https://discuss.leetcode.com/topic/2975/o-n-solution-by-using-two-pointers-without-change-anything 15 | try: 16 | fast = head.next.next 17 | slow = head.next 18 | 19 | while fast != slow: 20 | fast = fast.next.next 21 | slow = slow.next 22 | except: 23 | return None 24 | slow = head 25 | while fast != slow: 26 | fast = fast.next 27 | slow = slow.next 28 | return fast 29 | 30 | -------------------------------------------------------------------------------- /python/264_Ugly_Number_II.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def nthUglyNumber(self, n): 3 | """ 4 | :type n: int 5 | :rtype: int 6 | """ 7 | if n <= 5: 8 | return n 9 | dp = [0] * (n + 1) 10 | l1 = l2 = l3 = 1 11 | dp[1] = 1 12 | dp[2] = 2 13 | dp[3] = 3 14 | dp[4] = 4 15 | dp[5] = 5 16 | for i in range(6, n + 1): 17 | while dp[l1] * 2 <= dp[i - 1]: 18 | l1 += 1 19 | while dp[l2] * 3 <= dp[i - 1]: 20 | l2 += 1 21 | while dp[l3] * 5 <= dp[i - 1]: 22 | l3 += 1 23 | print l1, l2, l3 24 | dp[i] = min(dp[l1] * 2, dp[l2] * 3, dp[l3] * 5) 25 | # print dp 26 | return dp[n] 27 | 28 | if __name__ == '__main__': 29 | # begin 30 | s = Solution() 31 | print s.nthUglyNumber(10) -------------------------------------------------------------------------------- /java/347_Top_K_Frequent_Elements.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public List topKFrequent(int[] nums, int k) { 3 | // build hash map : character and how often it appears 4 | HashMap count = new HashMap(); 5 | for (int n: nums) { 6 | count.put(n, count.getOrDefault(n, 0) + 1); 7 | } 8 | 9 | // init heap 'the less frequent element first' 10 | PriorityQueue heap = 11 | new PriorityQueue((n1, n2) -> count.get(n1) - count.get(n2)); 12 | 13 | // keep k top frequent elements in the heap 14 | for (int n: count.keySet()) { 15 | heap.add(n); 16 | if (heap.size() > k) 17 | heap.poll(); 18 | } 19 | 20 | // build output list 21 | List top_k = new LinkedList(); 22 | while (!heap.isEmpty()) 23 | top_k.add(heap.poll()); 24 | Collections.reverse(top_k); 25 | return top_k; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /python/147_Insertion_Sort_List.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode(object): 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.next = None 6 | 7 | class Solution(object): 8 | def insertionSortList(self, head): 9 | """ 10 | :type head: ListNode 11 | :rtype: ListNode 12 | """ 13 | # https://discuss.leetcode.com/topic/8570/an-easy-and-clear-way-to-sort-o-1-space 14 | if head is None: 15 | return None 16 | helper = ListNode(-1000) 17 | pre, curr = helper, head 18 | while curr is not None: 19 | next_step = curr.next 20 | while pre.next and pre.next.val < curr.val: 21 | pre = pre.next 22 | curr.next = pre.next 23 | pre.next = curr 24 | pre = helper 25 | curr = next_step 26 | return helper.next 27 | -------------------------------------------------------------------------------- /python/367_Valid_Perfect_Square.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | # def isPerfectSquare(self, num): 3 | # """ 4 | # :type num: int 5 | # :rtype: bool 6 | # """ 7 | # i = 1 8 | # while num > 0: 9 | # num -= i 10 | # i += 2 11 | # return num == 0 12 | 13 | def isPerfectSquare(self, num): 14 | low, high = 1, num 15 | while low <= high: 16 | mid = (low + high) / 2 17 | mid_square = mid * mid 18 | if mid_square == num: 19 | return True 20 | elif mid_square < num: 21 | low = mid + 1 22 | else: 23 | high = mid - 1 24 | return False 25 | 26 | # def isPerfectSquare(self, num): 27 | # x = num 28 | # while x * x > num: 29 | # x = (x + num / x) / 2 30 | # return x * x == num 31 | -------------------------------------------------------------------------------- /python/073_Set_Matrix_Zeroes.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def setZeroes(self, matrix): 3 | """ 4 | :type matrix: List[List[int]] 5 | :rtype: void Do not return anything, modify matrix in-place instead. 6 | """ 7 | if not matrix: 8 | return 9 | m = len(matrix) 10 | if m == 0: 11 | return 12 | r = [] 13 | c = [] 14 | n = len(matrix[0]) 15 | for i in range(m): 16 | for j in range(n): 17 | if matrix[i][j] == 0: 18 | r.append(i) 19 | c.append(j) 20 | # row with zero 21 | r = set(r) 22 | # column with zero 23 | c = set(c) 24 | for i in r: 25 | for j in range(n): 26 | matrix[i][j] = 0 27 | for i in range(m): 28 | for j in c: 29 | matrix[i][j] = 0 30 | -------------------------------------------------------------------------------- /python/422_Valid_Word_Square.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def validWordSquare(self, words): 3 | """ 4 | :type words: List[str] 5 | :rtype: bool 6 | """ 7 | if words is None or len(words) == 0: 8 | return True 9 | ls = len(words) 10 | for i in range(ls): 11 | for j in range(1, len(words[i])): 12 | if j >= ls: 13 | return False 14 | if i >= len(words[j]): 15 | return False 16 | if words[i][j] != words[j][i]: 17 | return False 18 | return True 19 | 20 | # def validWordSquare(self, words): 21 | # # https://discuss.leetcode.com/topic/63423/1-liner-python/2 22 | # # The map(None, ...) transposes the "matrix", filling missing spots with None 23 | # return map(None, *words) == map(None, *map(None, *words)) 24 | -------------------------------------------------------------------------------- /java/268_Missing_Number.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | /* public int missingNumber(int[] nums) { 3 | int n = nums.length; 4 | int total = n * (n + 1) / 2; 5 | for (int i = 0; i < nums.length; i++) { 6 | total -= nums[i]; 7 | } 8 | return total; 9 | } */ 10 | 11 | public int missingNumber(int[] nums) { 12 | int res = nums.length; 13 | for (int i = 0; i < nums.length; i++) { 14 | res ^= i; 15 | res ^= nums[i]; 16 | } 17 | return res; 18 | } 19 | 20 | /* public int missingNumber(int[] nums) { 21 | Arrays.sort(nums); 22 | int left = 0, right = nums.length - 1; 23 | while (left <= right) { 24 | int mid = (left + right) / 2; 25 | if (nums[mid] > mid) right = mid - 1; 26 | else left = mid + 1; 27 | } 28 | return left; 29 | } */ 30 | } 31 | -------------------------------------------------------------------------------- /java/922_Sort_Array_By_Parity_II.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | /*public int[] sortArrayByParityII(int[] A) { 3 | int N = A.length; 4 | int[] ans = new int[N]; 5 | int t = 0; 6 | for (int x: A) if (x % 2 == 0) { 7 | ans[t] = x; 8 | t += 2; 9 | } 10 | t = 1; 11 | for (int x: A) if (x % 2 == 1) { 12 | ans[t] = x; 13 | t += 2; 14 | } 15 | return ans; 16 | }*/ 17 | public int[] sortArrayByParityII(int[] A) { 18 | int j = 1; 19 | for (int i = 0; i < A.length; i += 2) 20 | if (A[i] % 2 == 1) { 21 | while (A[j] % 2 == 1) 22 | j += 2; 23 | 24 | // Swap A[i] and A[j] 25 | int tmp = A[i]; 26 | A[i] = A[j]; 27 | A[j] = tmp; 28 | } 29 | 30 | return A; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /java/954_Array_of_Doubled_Pairs.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean canReorderDoubled(int[] A) { 3 | HashMap valueMap = new HashMap<>(); 4 | // Sort in[] with comparator 5 | A = Arrays.stream(A). 6 | boxed(). 7 | sorted((a, b) -> Integer.compare(Math.abs(a), Math.abs(b))). 8 | mapToInt(i -> i). 9 | toArray(); 10 | for (int n: A) valueMap.put(n, valueMap.getOrDefault(n, 0) + 1); 11 | for (int n: A) { 12 | if (valueMap.get(n) <= 0) continue; 13 | if (valueMap.containsKey(2 * n) && valueMap.get(2 * n) > 0) { 14 | valueMap.put(n, valueMap.get(n) - 1); 15 | valueMap.put(2 * n, valueMap.get(2 * n) - 1); 16 | } else { 17 | return false; 18 | } 19 | } 20 | return true; 21 | } 22 | 23 | 24 | } 25 | -------------------------------------------------------------------------------- /python/113_Path_Sum_II.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode(object): 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.left = None 6 | # self.right = None 7 | 8 | class Solution(object): 9 | def pathSum(self, root, sum): 10 | """ 11 | :type root: TreeNode 12 | :type sum: int 13 | :rtype: List[List[int]] 14 | """ 15 | res = [] 16 | if root is None: 17 | return res 18 | if sum == root.val and root.left is None and root.right is None: 19 | return [[root.val]] 20 | # left side 21 | left_res = self.pathSum(root.left, sum - root.val) 22 | # right side 23 | right_res = self.pathSum(root.right, sum - root.val) 24 | # add current prefix 25 | for t in left_res + right_res: 26 | res.append([root.val] + t) 27 | return res 28 | -------------------------------------------------------------------------------- /python/136_Single_Number.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | # def singleNumber(self, nums): 3 | # """ 4 | # :type nums: List[int] 5 | # :rtype: int 6 | # """ 7 | # # hash 8 | # dic = {} 9 | # for num in nums: 10 | # try: 11 | # dic[num] += 1 12 | # except KeyError: 13 | # dic[num] = 1 14 | # for num in nums: 15 | # if dic[num] == 1: 16 | # return num 17 | 18 | # def singleNumber(self, nums): 19 | # # set 20 | # s = set() 21 | # for num in nums: 22 | # if num in s: 23 | # s.remove(num) 24 | # else: 25 | # s.add(num) 26 | # return s.pop() 27 | 28 | def singleNumber(self, nums): 29 | # xor 30 | res = 0 31 | for num in nums: 32 | res ^= num 33 | return res -------------------------------------------------------------------------------- /java/946_Validate_Stack_Sequences.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean validateStackSequences(int[] pushed, int[] popped) { 3 | Stack inStack = new Stack<>(); 4 | int posPush = 0, posPop = 0; 5 | while (posPush != pushed.length) { 6 | int curr = pushed[posPush]; 7 | while (!inStack.empty() && popped.length > 0 && inStack.peek() == popped[posPop]) { 8 | inStack.pop(); 9 | posPop++; 10 | } 11 | if (popped.length == 0) break; 12 | if (curr == popped[posPop]) posPop++; 13 | else inStack.push(curr); 14 | posPush++; 15 | } 16 | while (!inStack.empty() && popped.length > 0 && inStack.peek() == popped[posPop]) { 17 | inStack.pop(); 18 | posPop++; 19 | } 20 | if (inStack.empty()) return true; 21 | return false; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /python/703_Kth_Largest_Element_in_a_Stream.py: -------------------------------------------------------------------------------- 1 | class KthLargest(object): 2 | 3 | def __init__(self, k, nums): 4 | self.nums = nums 5 | self.k = k 6 | # build min heap 7 | heapq.heapify(self.nums) 8 | # remove n - k smallest number 9 | while len(self.nums) > k: 10 | heapq.heappop(self.nums) 11 | 12 | def add(self, val): 13 | # add to heaq if it's less then k 14 | if len(self.nums) < self.k: 15 | heapq.heappush(self.nums, val) 16 | elif val > self.nums[0]: 17 | # if len(heaq) == k, and val greater than smallest num 18 | # then pop smallest num than add val to heap 19 | heapq.heapreplace(self.nums, val) 20 | # return k largest 21 | return self.nums[0] 22 | 23 | # Your KthLargest object will be instantiated and called as such: 24 | # obj = KthLargest(k, nums) 25 | # param_1 = obj.add(val) 26 | -------------------------------------------------------------------------------- /python/257_Binary_Tree_Paths.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.left = None 6 | # self.right = None 7 | 8 | class Solution: 9 | # @param {TreeNode} root 10 | # @return {string[]} 11 | def binaryTreePaths(self, root): 12 | if root is None: 13 | return [] 14 | paths = [] 15 | self.get_path(paths, [], root) 16 | res = ['->'.join(p) for p in paths ] 17 | return res 18 | 19 | def get_path(self, result, path, node): 20 | if node.left is None and node.right is None: 21 | result.append(path + [str(node.val)]) 22 | return 23 | path = path + [str(node.val)] 24 | if node.left is not None: 25 | self.get_path(result, path, node.left) 26 | if node.right is not None: 27 | self.get_path(result, path, node.right) -------------------------------------------------------------------------------- /python/922_Sort_Array_By_Parity_II.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | # def sortArrayByParityII(self, A): 3 | # N = len(A) 4 | # ans = [None] * N 5 | # t = 0 6 | # for i, x in enumerate(A): 7 | # if x % 2 == 0: 8 | # ans[t] = x 9 | # t += 2 10 | # t = 1 11 | # for i, x in enumerate(A): 12 | # if x % 2 == 1: 13 | # ans[t] = x 14 | # t += 2 15 | # # We could have also used slice assignment: 16 | # # ans[::2] = (x for x in A if x % 2 == 0) 17 | # # ans[1::2] = (x for x in A if x % 2 == 1) 18 | # return ans 19 | 20 | def sortArrayByParityII(self, A): 21 | odd = 1 22 | for i in xrange(0, len(A), 2): 23 | if A[i] % 2: 24 | while A[odd] % 2: 25 | odd += 2 26 | A[i], A[odd] = A[odd], A[i] 27 | return A 28 | -------------------------------------------------------------------------------- /java/002_Add_Two_Numbers.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * public class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode(int x) { val = x; } 7 | * } 8 | */ 9 | public class Solution { 10 | // example in leetcode book 11 | public ListNode addTwoNumbers(ListNode l1, ListNode l2) { 12 | ListNode dummyHead = new ListNode(0); 13 | ListNode p = l1, q= l2, curr = dummyHead; 14 | int carry = 0; 15 | while (p != null || q!= null) { 16 | int x = (p != null) ? p.val : 0; 17 | int y = (q != null) ? q.val : 0; 18 | int digit = carry + x + y; 19 | carry = digit / 10; 20 | curr.next = new ListNode(digit % 10); 21 | curr = curr.next; 22 | if (p != null) p = p.next; 23 | if (q != null) q = q.next; 24 | } 25 | if (carry > 0) { 26 | curr.next = new ListNode(carry); 27 | } 28 | return dummyHead.next; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /java/1089_Duplicate_Zeros.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public void duplicateZeros(int[] arr) { 3 | int movePos = 0; 4 | int lastPos = arr.length - 1; 5 | // Only check [0, lastPos - movePos] 6 | for (int i = 0; i <= lastPos - movePos; i++) { 7 | if (arr[i] == 0) { 8 | // Special case 9 | if (i == lastPos - movePos) { 10 | arr[lastPos] = 0; 11 | lastPos--; 12 | break; 13 | } 14 | movePos++; 15 | } 16 | } 17 | lastPos = lastPos - movePos; 18 | for (int i = lastPos; i >= 0; i--) { 19 | if (arr[i] == 0) { 20 | arr[i + movePos] = 0; 21 | movePos--; 22 | arr[i + movePos] = 0; 23 | } else { 24 | arr[i + movePos] = arr[i]; 25 | } 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /python/463_Island_Perimeter.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def islandPerimeter(self, grid): 3 | """ 4 | :type grid: List[List[int]] 5 | :rtype: int 6 | """ 7 | # https://leetcode.com/problems/island-perimeter/discuss/95001/clear-and-easy-java-solution 8 | row_num = len(grid) 9 | if row_num == 0 || len(grid[0]) == 0: 10 | return 0 11 | islands, overlaps = 0, 0 12 | col_num = len(grid[0]) 13 | for i in range(row_num): 14 | for j in range(col_num): 15 | if (grid[i][j] == 1): 16 | islands += 1 17 | # careful about right and down 18 | if (i < row_num - 1 && grid[i + 1][j] == 1): 19 | overlaps += 1 20 | if (j < col_num - 1 && grid[i][j + 1] == 1): 21 | overlaps += 1 22 | return islands * 4 - overlaps * 2 23 | -------------------------------------------------------------------------------- /java/1981_Minimize_the_Difference_Between_Target_and_Chosen_Elements.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int minimizeTheDifference(int[][] a, int k) { 3 | n = a.length; 4 | m = a[0].length; 5 | min = Integer.MAX_VALUE; 6 | dp = new boolean[n][5000]; 7 | solve(a, k, 0, 0, 0); 8 | return min; 9 | } 10 | 11 | private void solve(int a[][], int k, int sum, int row, int col) { 12 | if (dp[row][sum]) 13 | return; 14 | if (n - 1 == row) { 15 | for (int i = 0; i < m; i++) 16 | min = Math.min(min, Math.abs(k - sum - a[row][i])); 17 | dp[row][sum] = true; 18 | return; 19 | } 20 | 21 | for (int i = 0; i < m; i++) 22 | solve(a, k, sum + a[row][i], row + 1, col); 23 | dp[row][sum] = true; 24 | } 25 | 26 | private int min; 27 | private int dy[], n, m; 28 | private boolean dp[][]; 29 | } 30 | -------------------------------------------------------------------------------- /python/050_Pow(x, n).py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | # def myPow(self, x, n): 3 | # """ 4 | # :type x: float 5 | # :type n: int 6 | # :rtype: float 7 | # """ 8 | # if n == 0: 9 | # return 1 10 | # temp = pow(x, n / 2) 11 | # if n % 2 == 0: 12 | # return temp * temp 13 | # else: 14 | # return temp * temp * x 15 | 16 | def myPow(self, x, n): 17 | # https://leetcode.com/discuss/93413/iterative-log-n-solution-with-clear-explanation 18 | # 9 = 2^3 + 2^0 = 1001 19 | # x^9 = x^(2^3)*x(2^0) 20 | # multiple x^i when i place is 1 21 | if n == 0: 22 | return 1 23 | res ,curr = 1, abs(n) 24 | while curr > 0: 25 | if curr & 1 == 1: 26 | res *= x 27 | curr >>= 1 28 | x *= x 29 | if n < 0: 30 | return 1 / res 31 | return res 32 | -------------------------------------------------------------------------------- /python/1260_Shift_2D_Grid.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def shiftGrid(self, grid, k): 3 | """ 4 | :type grid: List[List[int]] 5 | :type k: int 6 | :rtype: List[List[int]] 7 | """ 8 | # m * n temp array 9 | new_grid = [[0] * len(grid[0]) for _ in range(len(grid))] 10 | m = len(grid) 11 | n = len(grid[0]) 12 | # Compute final location 13 | true_k = k % (m * n) 14 | # row move 15 | move_i = true_k / n 16 | # col move 17 | move_j = true_k % n 18 | 19 | for i in range(m): 20 | for j in range(n): 21 | new_i = i + move_i 22 | # move one row if move_j + j >= n 23 | if move_j + j >= n: 24 | new_i += 1 25 | new_i %= m 26 | new_j = (j + move_j) % n 27 | new_grid[new_i][new_j] = grid[i][j] 28 | return new_grid 29 | -------------------------------------------------------------------------------- /python/872_Leaf-Similar_Trees.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode(object): 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.left = None 6 | # self.right = None 7 | 8 | class Solution(object): 9 | def leafSimilar(self, root1, root2): 10 | """ 11 | :type root1: TreeNode 12 | :type root2: TreeNode 13 | :rtype: bool 14 | """ 15 | if not root1 and not root2: 16 | return True 17 | leaf1 = [] 18 | leaf2 = [] 19 | self.dfs(root1, leaf1) 20 | self.dfs(root2, leaf2) 21 | if leaf1 == leaf2: 22 | return True 23 | return False 24 | 25 | def dfs(self, node, leavels): 26 | if not node: 27 | return 28 | if not node.left and not node.right: 29 | leavels.append(node.val) 30 | self.dfs(node.left, leavels) 31 | self.dfs(node.right, leavels) 32 | -------------------------------------------------------------------------------- /python/380_Insert_Delete_GetRandom.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | class RandomizedSet(object): 4 | 5 | def __init__(self): 6 | self.num_to_idx = {} 7 | self.num_list = [] 8 | 9 | def insert(self, val): 10 | if val in self.num_to_idx: 11 | return False 12 | else: 13 | self.num_list.append(val) 14 | self.num_to_idx[val] = len(self.num_list) - 1 15 | return True 16 | 17 | def remove(self, val): 18 | if val not in self.num_to_idx: 19 | return False 20 | 21 | idx = self.num_to_idx[val] 22 | last = self.num_list[-1] 23 | 24 | # swap last elem to current spot so you can pop the end 25 | self.num_list[idx] = last 26 | self.num_list.pop() 27 | self.num_to_idx[last] = idx 28 | del self.num_to_idx[val] 29 | 30 | return True 31 | 32 | def getRandom(self): 33 | return random.choice(self.num_list) 34 | -------------------------------------------------------------------------------- /java/703_Kth_Largest_Element_in_a_Stream.java: -------------------------------------------------------------------------------- 1 | class KthLargest { 2 | 3 | final PriorityQueue q; 4 | final int k; 5 | 6 | public KthLargest(int k, int[] nums) { 7 | this.k = k; 8 | q = new PriorityQueue<>(k); 9 | // remove n - k smallest number 10 | for (int val : nums) 11 | add(val); 12 | } 13 | 14 | public int add(int val) { 15 | // add to heaq if it's less then k 16 | if (q.size() < k) 17 | q.offer(val); 18 | else if (q.peek() < val) { 19 | // if len(heaq) == k, and val greater than smallest num 20 | // then pop smallest num than add val to heap 21 | q.poll(); 22 | q.offer(val); 23 | } 24 | return q.peek(); 25 | } 26 | } 27 | 28 | /** 29 | * Your KthLargest object will be instantiated and called as such: 30 | * KthLargest obj = new KthLargest(k, nums); 31 | * int param_1 = obj.add(val); 32 | */ -------------------------------------------------------------------------------- /python/249_Group_Shifted_Strings.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def groupStrings(self, strings): 3 | """ 4 | :type strings: List[str] 5 | :rtype: List[List[str]] 6 | """ 7 | dic = {} 8 | for s in strings: 9 | key = self.hashCode(s) 10 | try: 11 | dic[key].append(s) 12 | except KeyError: 13 | dic[key] = [s] 14 | return dic.values() 15 | 16 | def hashCode(self, string): 17 | if string is None or len(string) == 0: 18 | return '' 19 | if len(string) == 1: 20 | return 'a' 21 | step = abs(ord(string[0]) - ord('a')) 22 | if step == 0: 23 | return string 24 | key = 'a' 25 | for ch in string[1:]: 26 | curr = ord(ch) - step 27 | if ord(ch) - step < ord('a'): 28 | curr += 26 29 | key += chr(curr) 30 | return key 31 | -------------------------------------------------------------------------------- /python/368_Largest_Divisible_Subset.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | # def largestDivisibleSubset(self, nums): 3 | # """ 4 | # :type nums: List[int] 5 | # :rtype: List[int] 6 | # """ 7 | # # https://discuss.leetcode.com/topic/49455/4-lines-in-python 8 | # S = {-1: set()} 9 | # for x in sorted(nums): 10 | # # S[x] is the largest subset with x as the largest element 11 | # S[x] = max((S[d] for d in S if x % d == 0), key=len) | {x} 12 | # return list(max(S.values(), key=len)) 13 | 14 | def largestDivisibleSubset(self, nums): 15 | ls = len(nums) 16 | S = {-1: set()} 17 | for num in sorted(nums): 18 | candicate = [] 19 | for key in S: 20 | if num % key == 0: 21 | candicate.append(S[key]) 22 | # max previous with curr 23 | S[num] = max(candicate, key=len) | {num} 24 | return -------------------------------------------------------------------------------- /java/367_Valid_Perfect_Square.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | /* public boolean isPerfectSquare(int num) { 3 | int i = 1; 4 | while (num > 0) { 5 | num -= i; 6 | i += 2; 7 | } 8 | return num == 0; 9 | } */ 10 | 11 | public boolean isPerfectSquare(int num) { 12 | int low = 1; 13 | int high = num; 14 | while (low <= high) { 15 | long mid = (low + high) >>> 1; 16 | if (mid * mid == num) { 17 | return true; 18 | } else if (mid * mid < num) { 19 | low = (int) mid + 1; 20 | } else { 21 | high = (int) mid - 1; 22 | } 23 | } 24 | return false; 25 | } 26 | 27 | /* public boolean isPerfectSquare(int num) { 28 | long x = num; 29 | while (x * x > num) { 30 | x = (x + num / x) >> 1; 31 | } 32 | return x * x == num; 33 | } */ 34 | } 35 | -------------------------------------------------------------------------------- /python/1089_Duplicate_Zeros.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def duplicateZeros(self, arr: List[int]) -> None: 3 | """ 4 | Do not return anything, modify arr in-place instead. 5 | """ 6 | move_pos = 0 7 | last_pos = len(arr) - 1 8 | for i in range(last_pos + 1): 9 | # Only check [0, lastPos - movePos] 10 | if i > last_pos - move_pos: 11 | break 12 | if arr[i] == 0: 13 | # Special case 14 | if i == last_pos - move_pos: 15 | arr[last_pos] = 0 16 | last_pos -= 1 17 | break 18 | move_pos += 1 19 | last_pos -= move_pos 20 | for i in range(last, -1, -1): 21 | if arr[i] == 0: 22 | arr[i + move_pos] = 0 23 | move_pos -= 1 24 | arr[i + move_pos] = 0 25 | else: 26 | arr[i + move_pos] = arr[i] 27 | -------------------------------------------------------------------------------- /python/207_Course_Schedule.py: -------------------------------------------------------------------------------- 1 | from collections import defaultdict 2 | 3 | class Solution(object): 4 | # Adapted from https://youtu.be/yPldqMtg-So 5 | 6 | def hasCycle(self, course, deps, visited, tracker): 7 | visited.add(course) 8 | tracker.add(course) 9 | for n in deps[course]: 10 | if n not in visited and self.hasCycle(n, deps, visited, tracker): 11 | return True 12 | if n in tracker: 13 | return True 14 | tracker.remove(course) 15 | return False 16 | 17 | def canFinish(self, numCourses, prerequisites): 18 | deps = defaultdict(set) 19 | for course, pre in prerequisites: 20 | deps[pre].add(course) 21 | 22 | visited = set() 23 | for course in range(numCourses): 24 | tracker = set() 25 | if self.hasCycle(course, deps, visited, tracker): 26 | return False 27 | 28 | return True 29 | -------------------------------------------------------------------------------- /python/129_Sum_Root_to_Leaf_Numbers.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode(object): 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.left = None 6 | # self.right = None 7 | 8 | class Solution(object): 9 | def sumNumbers(self, root): 10 | """ 11 | :type root: TreeNode 12 | :rtype: int 13 | """ 14 | if root is None: 15 | return 0 16 | res = 0 17 | # bfs with queue 18 | queue = [(root, root.val)] 19 | while len(queue) > 0: 20 | curr, curr_value = queue.pop(0) 21 | if curr.left is None and curr.right is None: 22 | res += curr_value 23 | continue 24 | if curr.left: 25 | queue.append((curr.left, curr_value * 10 + curr.left.val)) 26 | if curr.right: 27 | queue.append((curr.right, curr_value * 10 + curr.right.val)) 28 | return res 29 | -------------------------------------------------------------------------------- /python/034_Search_for_a_Range.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def searchRange(self, nums, target): 3 | """ 4 | :type nums: List[int] 5 | :type target: int 6 | :rtype: List[int] 7 | """ 8 | length = len(nums) 9 | if length == 0: 10 | return [-1, -1] 11 | min = 0 12 | max = length - 1 13 | while min <= max: 14 | pos = (min + max) / 2 15 | if nums[pos] > target: 16 | max = pos - 1 17 | elif nums[pos] < target: 18 | min = pos + 1 19 | else: 20 | # when nums[pos] == target 21 | # find the min and max 22 | for i in range(min, max + 1): 23 | if nums[i] == target: 24 | if min < i and nums[min] != nums[i]: 25 | min = i 26 | max = i 27 | return [min, max] 28 | return [-1, -1] -------------------------------------------------------------------------------- /python/131_Palindrome_Partitioning.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def partition(self, s): 3 | """ 4 | :type s: str 5 | :rtype: List[List[str]] 6 | """ 7 | # https://discuss.leetcode.com/topic/6186/java-backtracking-solution/2 8 | result = [] 9 | curr = [] 10 | self.recurPartition(result, curr, s, 0) 11 | return result 12 | 13 | def recurPartition(self, result, curr, s, start): 14 | if start == len(s): 15 | result.append(list(curr)) 16 | for i in range(start, len(s)): 17 | if self.isPalindrome(s, start, i): 18 | curr.append(s[start:i + 1]) 19 | self.recurPartition(result, curr, s, i + 1) 20 | curr.pop() 21 | 22 | def isPalindrome(self, s, begin, end): 23 | while begin < end: 24 | if s[begin] != s[end]: 25 | return False 26 | begin += 1 27 | end -= 1 28 | return True -------------------------------------------------------------------------------- /python/273_Integer_to_English_Words.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def numberToWords(self, num): 3 | # https://leetcode.com/problems/integer-to-english-words/discuss/70632/Recursive-Python 4 | to19 = 'One Two Three Four Five Six Seven Eight Nine Ten Eleven Twelve ' \ 5 | 'Thirteen Fourteen Fifteen Sixteen Seventeen Eighteen Nineteen'.split() 6 | tens = 'Twenty Thirty Forty Fifty Sixty Seventy Eighty Ninety'.split() 7 | def words(n): 8 | if n < 20: 9 | return to19[n - 1:n] 10 | if n < 100: 11 | return [tens[n / 10 - 2]] + words(n % 10) 12 | if n < 1000: 13 | return [to19[n / 100 - 1]] + ['Hundred'] + words(n % 100) 14 | for p, w in enumerate(('Thousand', 'Million', 'Billion'), 1): 15 | if n < 1000 ** (p + 1): 16 | return words(n / 1000 ** p) + [w] + words(n % 1000 ** p) 17 | return ' '.join(words(num)) or 'Zero' 18 | -------------------------------------------------------------------------------- /python/405_Convert_a_Number_to_Hexadecimal.py: -------------------------------------------------------------------------------- 1 | 2 | class Solution(object): 3 | def toHex(self, num): 4 | """ 5 | :type num: int 6 | :rtype: str 7 | """ 8 | if num == 0: 9 | return '0' 10 | # letter map 11 | mp = '0123456789abcdef' 12 | ans = '' 13 | for _ in range(8): 14 | # get last 4 digits 15 | # num & 1111b 16 | n = num & 15 17 | # hex letter for current 1111 18 | c = mp[n] 19 | ans = c + ans 20 | # num = num / 16 21 | num = num >> 4 22 | #strip leading zeroes 23 | return ans.lstrip('0') 24 | 25 | # def toHex(self, num): 26 | # def tohex(val, nbits): 27 | # return hex((val + (1 << nbits)) % (1 << nbits)) 28 | # return tohex(num, 32)[2:] 29 | 30 | # def toHex(self, num, h=''): 31 | # return (not num or h[7:]) and h or self.toHex(num / 16, '0123456789abcdef'[num % 16] + h) 32 | -------------------------------------------------------------------------------- /java/003_Longest_Substring_Without_Repeating_Characters.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | // example in leetcode book 3 | // public int lengthOfLongestSubstring(String s) { 4 | // boolean[] exist = new boolean[256]; 5 | // int i = 0, maxLen = 0; 6 | // for (int j = 0; j < s.length(); j++) { 7 | // while (exist[s.charAt(j)]){ 8 | // exist[s.charAt(i)] = false; 9 | // i++; 10 | // } 11 | // exist[s.charAt(j)] = true; 12 | // maxLen = Math.max(j - i + 1, maxLen); 13 | // } 14 | // return maxLen; 15 | // } 16 | 17 | public int lengthOfLongestSubstring(String s) { 18 | int[] charMap = new int[256]; 19 | Arrays.fill(charMap, -1); 20 | int i = 0, maxLen = 0; 21 | for (int j = 0; j < s.length(); j++) { 22 | if (charMap[s.charAt(j)] >= i) { 23 | i = charMap[s.charAt(j)] + 1; 24 | } 25 | charMap[s.charAt(j)] = j; 26 | maxLen = Math.max(j - i + 1, maxLen); 27 | } 28 | return maxLen; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /python/048_Rotate_Image.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def rotate(self, matrix): 3 | """ 4 | :type matrix: List[List[int]] 5 | :rtype: void Do not return anything, modify matrix in-place instead. 6 | """ 7 | # rotate from outside to inside 8 | if matrix is None or len(matrix) == 1: 9 | return 10 | ls = len(matrix) 11 | for i in range(ls / 2): 12 | # border 13 | begin, end = i, ls - 1 - i 14 | for k in range(ls - 2 * i - 1): 15 | temp = matrix[end - k][begin] 16 | matrix[end - k][begin] = matrix[end][end - k] 17 | matrix[end][end - k] = matrix[begin + k][end] 18 | matrix[begin + k][end] = matrix[begin][begin + k] 19 | matrix[begin][begin + k] = temp 20 | return 21 | 22 | if __name__ == '__main__': 23 | # begin 24 | s = Solution() 25 | s.rotate([[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]]) 26 | 27 | 28 | 29 | 30 | -------------------------------------------------------------------------------- /python/116_Populating_Next_Right_Pointers_in_Each_Node.py: -------------------------------------------------------------------------------- 1 | # Definition for binary tree with next pointer. 2 | # class TreeLinkNode(object): 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.left = None 6 | # self.right = None 7 | # self.next = None 8 | 9 | class Solution(object): 10 | def connect(self, root): 11 | """ 12 | :type root: TreeLinkNode 13 | :rtype: nothing 14 | """ 15 | if root is None: 16 | return 17 | nodes = [root] 18 | while len(nodes) != 0: 19 | next_step = [] 20 | last = None 21 | for node in nodes: 22 | if last is not None: 23 | last.next = node 24 | if node.left is not None: 25 | next_step.append(node.left) 26 | if node.right is not None: 27 | next_step.append(node.right) 28 | last = node 29 | nodes = next_step 30 | 31 | 32 | -------------------------------------------------------------------------------- /python/200_Number_of_Islands.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def numIslands(self, grid): 3 | """ 4 | :type grid: List[List[str]] 5 | :rtype: int 6 | """ 7 | # BFS with marks 8 | if grid is None or len(grid) == 0: 9 | return 0 10 | islands = 0 11 | for i in range(len(grid)): 12 | for j in range(len(grid[i])): 13 | if grid[i][j] == '1': 14 | self.explore(grid, i, j) 15 | islands += 1 16 | return islands 17 | 18 | def explore(self, grid, i, j): 19 | grid[i][j] = 'X' 20 | if i - 1 >= 0 and grid[i - 1][j] == '1': 21 | self.explore(grid, i - 1, j) 22 | if j - 1 >= 0 and grid[i][j - 1] == '1': 23 | self.explore(grid, i, j - 1) 24 | if i + 1 < len(grid) and grid[i + 1][j] == '1': 25 | self.explore(grid, i + 1, j) 26 | if j + 1 < len(grid[i]) and grid[i][j + 1] == '1': 27 | self.explore(grid, i, j + 1) -------------------------------------------------------------------------------- /python/346_Moving_Average_from_Data_Stream.py: -------------------------------------------------------------------------------- 1 | class MovingAverage(object): 2 | 3 | def __init__(self, size): 4 | """ 5 | Initialize your data structure here. 6 | :type size: int 7 | """ 8 | self.size = size 9 | self.curr_range = [] 10 | 11 | 12 | def next(self, val): 13 | """ 14 | :type val: int 15 | :rtype: float 16 | """ 17 | if len(self.curr_range) == self.size: 18 | self.curr_range.pop(0) 19 | self.curr_range.append(val) 20 | return sum(self.curr_range) * 1.0 / len(self.curr_range) 21 | 22 | 23 | 24 | # Your MovingAverage object will be instantiated and called as such: 25 | # obj = MovingAverage(size) 26 | # param_1 = obj.next(val) 27 | 28 | # def __init__(self, size): 29 | # """ 30 | # Initialize your data structure here. 31 | # :type size: int 32 | # """ 33 | # self.next = lambda v, q=collections.deque((), size): q.append(v) or 1.*sum(q) / len(q) -------------------------------------------------------------------------------- /python/977_Squares_of_a_Sorted_Array.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | # def sortedSquares(self, A): 3 | # """ 4 | # :type A: List[int] 5 | # :rtype: List[int] 6 | # """ 7 | # # Directly sort 8 | # return sorted(x * x for x in A) 9 | 10 | def sortedSquares(self, A): 11 | pos = 0 12 | while pos < len(A) and A[pos] < 0: 13 | pos += 1 14 | # pos point to first positve 15 | # npos point to larget negative 16 | npos = pos - 1 17 | res = [] 18 | while pos < len(A) and npos >= 0: 19 | if A[npos] ** 2 < A[pos] ** 2: 20 | res.append(A[npos] ** 2) 21 | npos -= 1 22 | else: 23 | res.append(A[pos] ** 2) 24 | pos +=1 25 | while npos >= 0: 26 | res.append(A[npos] ** 2) 27 | npos -= 1 28 | while pos < len(A): 29 | res.append(A[pos] ** 2) 30 | pos += 1 31 | return res 32 | -------------------------------------------------------------------------------- /java/560_Subarray_Sum_Equals_K.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | /*public int subarraySum(int[] nums, int k) { 3 | int count = 0; 4 | for (int start = 0; start < nums.length; start++) { 5 | int sum = 0; 6 | for (int end = start; end < nums.length; end++) { 7 | sum += nums[end]; 8 | if (sum == k) 9 | count++; 10 | } 11 | } 12 | return count; 13 | }*/ 14 | public int subarraySum(int[] nums, int k) { 15 | int count = 0, sum = 0; 16 | HashMap < Integer, Integer > map = new HashMap < > (); 17 | map.put(0, 1); 18 | for (int i = 0; i < nums.length; i++) { 19 | sum += nums[i]; 20 | // check if sum - k in hash 21 | if (map.containsKey(sum - k)) 22 | count += map.get(sum - k); 23 | // push sum into hash 24 | map.put(sum, map.getOrDefault(sum, 0) + 1); 25 | } 26 | return count; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /cpp/923_3_sum_with_multiplicity.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int threeSumMulti(vector& A, int target) { 4 | unordered_map count; 5 | for (const auto& a : A) { 6 | ++count[a]; 7 | } 8 | uint64_t result = 0; 9 | for (const auto& kvp1 : count) { 10 | for (const auto& kvp2 : count) { 11 | int i = kvp1.first, j = kvp2.first, k = target - i - j; 12 | if (!count.count(k)) { 13 | continue; 14 | } 15 | if (i == j && j == k) { 16 | result += count[i] * (count[i] - 1) * (count[i] - 2) / 6; 17 | } else if (i == j && j != k) { 18 | result += count[i] * (count[i] - 1) / 2 * count[k]; 19 | } else if (i < j && j < k) { 20 | result += count[i] * count[j] * count[k]; 21 | } 22 | } 23 | } 24 | return result % static_cast(1e9 + 7); 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /java/811_Subdomain_Visit_Count.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public List subdomainVisits(String[] cpdomains) { 3 | // https://leetcode.com/problems/subdomain-visit-count/discuss/121738/C%2B%2BJavaPython-Easy-Understood-Solution 4 | Map map = new HashMap(); 5 | for (String cpdomain : cpdomains) { 6 | int i = cpdomain.indexOf(' '); 7 | int n = Integer.valueOf(cpdomain.substring(0, i)); 8 | String domain = cpdomain.substring(i + 1); 9 | for (i = 0; i < domain.length(); ++i) { 10 | if (domain.charAt(i) == '.') { 11 | String d = domain.substring(i + 1); 12 | map.put(d, map.getOrDefault(d, 0) + n); 13 | } 14 | } 15 | map.put(domain, map.getOrDefault(domain, 0) + n); 16 | } 17 | 18 | List res = new ArrayList(); 19 | for (String domain : map.keySet()) res.add(map.get(domain) + " " + domain); 20 | return res; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /java/953_Verifying_an_Alien_Dictionary.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | HashMap orderMap = new HashMap<>(); 3 | public boolean isAlienSorted(String[] words, String order) { 4 | // Put value index map into hashmap 5 | for (int i = 0; i < order.length(); i++) { 6 | orderMap.put(order.charAt(i), i); 7 | } 8 | for (int i = 0; i < words.length - 1; i++) { 9 | if (cmp_alien(words[i], words[i + 1]) > 0) return false; 10 | } 11 | return true; 12 | 13 | } 14 | private int cmp_alien(String a, String b) { 15 | int ls = a.length() < b.length() ? a.length(): b.length(); 16 | int pos = 0; 17 | // Compare based on hashmap 18 | while (pos < ls) { 19 | if (orderMap.get(a.charAt(pos)) != orderMap.get(b.charAt(pos))) 20 | return orderMap.get(a.charAt(pos)) - orderMap.get(b.charAt(pos)); 21 | pos += 1; 22 | } 23 | return a.length() <= b.length() ? -1: 1; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /python/026_Remove_Duplicates_from_Sorted_Array.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | # def removeDuplicates(self, nums): 3 | # """ 4 | # :type nums: List[int] 5 | # :rtype: int 6 | # """ 7 | # ls = len(nums) 8 | # if ls <= 1: 9 | # return ls 10 | # last = nums[0] 11 | # pos = 1 12 | # for t in nums[1:]: 13 | # if t == last: 14 | # continue 15 | # else: 16 | # nums[pos] = t 17 | # pos += 1 18 | # last = t 19 | # return pos 20 | 21 | # https://leetcode.com/articles/remove-duplicates-sorted-array/ 22 | def removeDuplicates(self, nums): 23 | if len(nums) == 0: 24 | return 0 25 | left = 0 26 | for i in range(1, len(nums)): 27 | if nums[left] == nums[i]: 28 | continue 29 | else: 30 | left += 1 31 | nums[left] = nums[i] 32 | return left + 1 33 | 34 | -------------------------------------------------------------------------------- /python/017_Letter_Combinations_of_a_Phone_Number.py: -------------------------------------------------------------------------------- 1 | # class Solution(object): 2 | # def letterCombinations(self, digits): 3 | # """ 4 | # :type digits: str 5 | # :rtype: List[str] 6 | # """ 7 | dmap = {'2': 'abc', 8 | '3': 'def', 9 | '4': 'ghi', 10 | '5': 'jkl', 11 | '6': 'mno', 12 | '7': 'pqrs', 13 | '8': 'tuv', 14 | '9': 'wxyz', 15 | '0': ' ', 16 | None: None} 17 | 18 | class Solution(object): 19 | def letterCombinations(self, digits): 20 | # DFS 21 | result = [] 22 | ls = len(digits) 23 | if ls == 0: 24 | return result 25 | current = digits[0] 26 | posfix = self.letterCombinations(digits[1:]) 27 | for t in dmap[current]: 28 | if len(posfix) > 0: 29 | for p in posfix: 30 | temp = t + p 31 | result.append(temp) 32 | else: 33 | result.append(t) 34 | return result 35 | 36 | 37 | -------------------------------------------------------------------------------- /python/700_Search_in_a_Binary_Search_Tree.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode(object): 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.left = None 6 | # self.right = None 7 | 8 | class Solution(object): 9 | # def searchBST(self, root, val): 10 | # """ 11 | # :type root: TreeNode 12 | # :type val: int 13 | # :rtype: TreeNode 14 | # """ 15 | # # Recursive 16 | # if not root: 17 | # return None 18 | # if root.val == val: 19 | # return root 20 | # elif root.val > val: 21 | # return self.searchBST(root.left, val) 22 | # else: 23 | # return self.searchBST(root.right, val) 24 | 25 | def searchBST(self, root, val): 26 | while root: 27 | if root.val == val: 28 | return root 29 | elif root.val > val: 30 | root = root.left 31 | else: 32 | root = root.right 33 | return root 34 | -------------------------------------------------------------------------------- /python/1337_The_K_Weakest_Rows_in_a_Matrix.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def kWeakestRows(self, mat, k): 3 | """ 4 | :type mat: List[List[int]] 5 | :type k: int 6 | :rtype: List[int] 7 | """ 8 | res = [] 9 | num_row = len(mat) 10 | num_col = len(mat[0]) 11 | col = 0 12 | flag = 1 13 | while col < num_col and flag: 14 | for i in range(num_row): 15 | if i in res: 16 | continue 17 | # Add first row with 0 into res 18 | if mat[i][col] == 0: 19 | res.append(i) 20 | if len(res) == k: 21 | flag = 0 22 | break 23 | col += 1 24 | if len(res) == k: 25 | return res 26 | # if res less than k 27 | for i in range(num_row): 28 | if i in res: 29 | continue 30 | res.append(i) 31 | if len(res) == k: 32 | break 33 | return res -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | .idea/ 6 | *.iml 7 | # C extensions 8 | *.so 9 | 10 | # Distribution / packaging 11 | .Python 12 | env/ 13 | build/ 14 | develop-eggs/ 15 | dist/ 16 | downloads/ 17 | eggs/ 18 | .eggs/ 19 | lib/ 20 | lib64/ 21 | parts/ 22 | sdist/ 23 | var/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | 28 | # PyInstaller 29 | # Usually these files are written by a python script from a template 30 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 31 | *.manifest 32 | *.spec 33 | 34 | # Installer logs 35 | pip-log.txt 36 | pip-delete-this-directory.txt 37 | 38 | # Unit test / coverage reports 39 | htmlcov/ 40 | .tox/ 41 | .coverage 42 | .coverage.* 43 | .cache 44 | nosetests.xml 45 | coverage.xml 46 | *,cover 47 | .hypothesis/ 48 | 49 | # Translations 50 | *.mo 51 | *.pot 52 | 53 | # Django stuff: 54 | *.log 55 | 56 | # Sphinx documentation 57 | docs/_build/ 58 | 59 | # PyBuilder 60 | target/ 61 | 62 | #Ipython Notebook 63 | .ipynb_checkpoints 64 | -------------------------------------------------------------------------------- /python/033_Search_in_Rotated_Sorted_Array.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def search(self, nums, target): 3 | """ 4 | :type nums: List[int] 5 | :type target: int 6 | :rtype: int 7 | """ 8 | # binary search 9 | # if start < mid, then left part is sorted 10 | # if mid < end, then right part is sorted 11 | def get(start, end): 12 | if start > end: 13 | return -1 14 | mid = (start + end) / 2 15 | if nums[mid] == target: 16 | return mid 17 | elif nums[mid] >= nums[start]: # First half is sorted 18 | if target >= nums[start] and target < nums[mid]: 19 | return get(start, mid - 1) 20 | else: 21 | return get(mid + 1, end) 22 | elif nums[mid] <= nums[end]: # Second half is sorted 23 | if target > nums[mid] and target <= nums[end]: 24 | return get(mid + 1, end) 25 | else: 26 | return get(start, mid - 1) 27 | return get(0, len(nums) - 1) -------------------------------------------------------------------------------- /python/299_Bulls_and_Cows.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def getHint(self, secret, guess): 3 | """ 4 | :type secret: str 5 | :type guess: str 6 | :rtype: str 7 | """ 8 | check = {} 9 | ls = len(secret) 10 | bull, cow = 0, 0 11 | different = [] 12 | for i in range(ls): 13 | if guess[i] == secret[i]: 14 | bull += 1 15 | else: 16 | # store possible index and count for cow 17 | different.append(i) 18 | try: 19 | check[secret[i]] += 1 20 | except KeyError: 21 | check[secret[i]] = 1 22 | for i in different: 23 | try: 24 | if check[guess[i]] > 0: 25 | cow += 1 26 | check[guess[i]] -= 1 27 | except: 28 | pass 29 | return "%dA%dB" % (bull, cow) 30 | 31 | 32 | if __name__ == "__main__": 33 | s = Solution() 34 | print s.getHint("1122", "1222") 35 | -------------------------------------------------------------------------------- /python/124_Binary_Tree_Maximum_Path_Sum.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode(object): 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.left = None 6 | # self.right = None 7 | 8 | 9 | class Solution(object): 10 | def __init__(self): 11 | self.result = -2147483647 12 | 13 | def maxPathSum(self, root): 14 | """ 15 | :type root: TreeNode 16 | :rtype: int 17 | """ 18 | # return (root.val,left+root.val,right+root.val,left+right+root); 19 | self.getNodeMaxValue(root) 20 | return self.result 21 | 22 | def getNodeMaxValue(self, node): 23 | if node is None: 24 | return 0 25 | lresult = self.getNodeMaxValue(node.left) 26 | rresult = self.getNodeMaxValue(node.right) 27 | self.result = max(lresult + rresult + node.val, self.result) 28 | ret = node.val + max(lresult, rresult) 29 | # if max left or right < 0 then return 0 30 | if ret > 0: 31 | return ret 32 | return 0 33 | -------------------------------------------------------------------------------- /python/274_H-Index.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | # def hIndex(self, citations): 3 | # """ 4 | # :type citations: List[int] 5 | # :rtype: int 6 | # """ 7 | # # Sort and check the max h where the number of paper with no less than h citations 8 | # # is no less than h 9 | # citations.sort() 10 | # ls = len(citations) 11 | # h = ls 12 | # while h > 0 and citations[ls - h] < h: 13 | # h -= 1 14 | # return h 15 | 16 | # def hIndex(self, citations): 17 | # citations.sort() 18 | # i = 0 19 | # while i < len(citations) and citations[len(citations) - 1 - i] > i: 20 | # i += 1 21 | # return i 22 | 23 | def hIndex(self, citations): 24 | # counting sort 25 | ls = len(citations) 26 | papers = [0] * (ls + 1) 27 | for c in citations: 28 | papers[min(ls, c)] += 1 29 | k, s = ls, papers[ls] 30 | while k > s: 31 | k -= 1 32 | s += papers[k] 33 | return k -------------------------------------------------------------------------------- /python/283_Move Zeroes.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | # def moveZeroes(self, nums): 3 | # """ 4 | # :type nums: List[int] 5 | # :rtype: void Do not return anything, modify nums in-place instead. 6 | # """ 7 | # # O(n^2) 8 | # ls = len(nums) 9 | # pos = 0 10 | # while pos < ls: 11 | # if nums[pos] == 0: 12 | # curr = pos + 1 13 | # while curr < ls: 14 | # if nums[curr] != 0: 15 | # temp = nums[curr] 16 | # nums[curr] = nums[pos] 17 | # nums[pos] = temp 18 | # break 19 | # curr += 1 20 | # pos += 1 21 | 22 | def moveZeroes(self, nums): 23 | # O(n) 24 | ls = len(nums) 25 | n_pos = 0 26 | for i in range(ls): 27 | if nums[i] != 0: 28 | temp = nums[n_pos] 29 | nums[n_pos] = nums[i] 30 | nums[i] = temp 31 | n_pos += 1 32 | 33 | 34 | -------------------------------------------------------------------------------- /python/158_Read_N_Characters_Given_Read4_II_Call_multiple_times.py: -------------------------------------------------------------------------------- 1 | # The read4 API is already defined for you. 2 | # @param buf, a list of characters 3 | # @return an integer 4 | # def read4(buf): 5 | 6 | class Solution(object): 7 | 8 | def __init__(self): 9 | self.buff = [''] * 4 10 | self.offset = 0 11 | self.bufsize = 0 12 | 13 | def read(self, buf, n): 14 | """ 15 | :type buf: Destination buffer (List[str]) 16 | :type n: Maximum number of characters to read (int) 17 | :rtype: The number of characters read (int) 18 | """ 19 | pos, eof = 0, False 20 | while not eof and pos < n: 21 | if self.bufsize == 0: 22 | self.bufsize = read4(self.buff) 23 | eof = self.bufsize < 4 24 | byte = min(n - pos, self.bufsize) 25 | for i in range(byte): 26 | buf[pos + i] = self.buff[self.offset + i] 27 | self.offset = (self.offset + byte) % 4 28 | self.bufsize -= byte 29 | pos += byte 30 | return pos 31 | -------------------------------------------------------------------------------- /java/605_Can_Place_Flowers.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | /*public boolean canPlaceFlowers(int[] flowerbed, int n) { 3 | int i = 0, count = 0; 4 | while (i < flowerbed.length) { 5 | if (flowerbed[i] == 0 && (i == 0 || flowerbed[i - 1] == 0) && (i == flowerbed.length - 1 || flowerbed[i + 1] == 0)) { 6 | flowerbed[i++] = 1; 7 | count++; 8 | } 9 | if(count >= n) 10 | return true; 11 | i++; 12 | } 13 | return false; 14 | }*/ 15 | public boolean canPlaceFlowers(int[] flowerbed, int n) { 16 | int count = 0, curr; 17 | for (int i = 0; i < flowerbed.length; i++) { 18 | curr = flowerbed[i]; 19 | if (i - 1 >= 0) curr += flowerbed[i - 1]; 20 | if (i + 1 < flowerbed.length) curr += flowerbed[i + 1]; 21 | if (curr == 0) { 22 | count++; 23 | flowerbed[i] = 1; 24 | } 25 | if (count >= n) return true; 26 | } 27 | return false; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /python/066_Plus_One.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | # def plusOne(self, digits): 3 | # """ 4 | # :type digits: List[int] 5 | # :rtype: List[int] 6 | # """ 7 | # ls = len(digits) 8 | # curr, pos = 1, 0 9 | # while pos < ls: 10 | # index = ls - pos - 1 11 | # curr += digits[index] 12 | # digits[index] = curr % 10 13 | # curr /= 10 14 | # if curr == 0: 15 | # # do not need to continue 16 | # break 17 | # pos += 1 18 | # if curr > 0: 19 | # digits.insert(0, curr) 20 | # return digits 21 | 22 | def plusOne(self, digits): 23 | ls = len(digits) 24 | for index in reversed(range(ls)): 25 | if digits[index] < 9: 26 | digits[index] += 1 27 | # do not need to continue 28 | return digits 29 | else: 30 | # 10 31 | digits[index] = 0 32 | digits.insert(0, 1) 33 | return digits 34 | 35 | 36 | -------------------------------------------------------------------------------- /python/070_Climbing_Stairs.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | # def climbStairs(self, n): 3 | # """ 4 | # :type n: int 5 | # :rtype: int 6 | # """ 7 | # dp = [0] * (n + 1) 8 | # dp[0] = 1 9 | # dp[1] = 1 10 | # for i in range(2, n + 1): 11 | # dp[i] = dp[i - 2] + dp[i- 1] 12 | # return dp[n] 13 | 14 | def climbStairs(self, n): 15 | if n <= 1: 16 | return 1 17 | dp = [1] * 2 18 | for i in range(2, n + 1): 19 | dp[1], dp[0] = dp[1] + dp[0], dp[1] 20 | return dp[1] 21 | 22 | 23 | 24 | # C = {1: 1, 2: 2} 25 | # def climbStairs(self, n): 26 | # """ 27 | # :type n: int 28 | # :rtype: int 29 | # """ 30 | # if n in Solution.C: 31 | # return Solution.C[n] 32 | # else: 33 | # result = Solution.C.get(n - 1, self.climbStairs(n - 1)) + \ 34 | # Solution.C.get(n - 2, self.climbStairs(n - 2)) 35 | # Solution.C[n] = result 36 | # return result 37 | 38 | -------------------------------------------------------------------------------- /java/1337_The_K_Weakest_Rows_in_a_Matrix.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[] kWeakestRows(int[][] mat, int k) { 3 | List res = new ArrayList<>(); 4 | int col = 0; 5 | boolean flag = true; 6 | while (col < mat[0].length && flag) { 7 | for (int i = 0; i < mat.length; i++) { 8 | if (res.contains(i)) continue; 9 | // Add first row with 0 into res 10 | if (mat[i][col] == 0) res.add(i); 11 | if (res.size() == k) { 12 | flag = false; 13 | break; 14 | } 15 | } 16 | col += 1; 17 | } 18 | if (flag) { 19 | // if res less than k 20 | for (int i = 0; i < mat.length; i++) { 21 | if (res.contains(i)) continue; 22 | res.add(i); 23 | if (res.size() == k) break; 24 | } 25 | } 26 | int[] ret = new int[k]; 27 | for (int i = 0; i < k; i++) ret[i] = res.get(i); 28 | return ret; 29 | } 30 | } 31 | --------------------------------------------------------------------------------