Home

Awesome

Python & JAVA Solutions for Leetcode (inspired by haoel's leetcode)

Remember solutions are only solutions to given problems. If you want full study checklist for code & whiteboard interview, please turn to jwasham's coding-interview-university.

Also, there are open source implementations for basic data structs and algorithms, such as Algorithms in Python and Algorithms in Java.

I'm currently working on Analytics-Zoo - an unified Data Analytics and AI platform. Check it out, if you are interested in big data and deep learning.

Problems & Solutions

Python and Java full list. ♥ means you need a subscription.

#TitleSolutionBasic idea (One line)
1Two SumPython Java1. Hash O(n) and O(n) space.<br>2. Sort and search with two points O(n) and O(1) space.
2Add Two NumbersPython JavaTake care of the carry from lower digit.
3Longest Substring Without Repeating CharactersPython Java1. Check every possible substring O(n^2) <br>2. Remember the character index and current check pos, if character index >= current pos, then there is duplicate
4Median of Two Sorted ArraysPython Java1. Merge two sorted lists and compute median, O(m + n) and O(m + n)<br>2. An extension of median of two sorted arrays of equal size problem
5Longest Palindromic SubstringPython JavaBackground knowledge<br>1. DP if s[i]==s[j] and P[i+1, j-1] then P[i,j]<br>2. A palindrome can be expanded from its center<br>3. Manacher algorithm
7Reverse IntegerPython JavaOverflow when the result is greater than 2147483647 or less than -2147483648.
8String to Integer (atoi)Python JavaOverflow, Space, and negative number
9Palindrome NumberPython JavaGet the len and check left and right with 10^len, 10
11Container With Most WaterPython Java1. Brute Force, O(n^2) and O(1)<br>2. Two points, O(n) and O(1)
12Integer to RomanPython JavaBackground knowledge Just like 10-digit number, divide and minus
13Roman to IntegerPythonAdd all curr, if curr > prev, then need to subtract 2 * prev
153SumPython1. Sort and O(n^2) search with three points <br>2. Multiple Two Sum (Problem 1)
163Sum ClosestPythonSort and Multiple Two Sum check abs
184SumPythonThe same as 3Sum, but we can merge pairs with the same sum
19Remove Nth Node From End of ListPython Java1. Go through list and get length, then remove length-n, O(n) and O(n)<br>2. Two pointers, first pointer goes to n position, then move both pointers until reach tail, O(n) and O(n)
20Valid ParenthesesPython1. Stack<br>2. Replace all parentheses with '', if empty then True
21Merge Two Sorted ListsPythonAdd a dummy head, then merge two sorted list in O(m+n)
23Merge k Sorted ListsPython1. Priority queue O(nk log k)<br>2. Binary merge O(nk log k)
24Swap Nodes in PairsPythonAdd a dummy and store the prev
28Implement strStr()Python1. O(nm) comparison <br>2. KMP
35Search Insert PositionPythonBinary Search
46PermutationsPython1. Python itertools.permutations<br>2. DFS with swapping, O(n^2) and O(n^2)<br>3. iteratively generate n-permutations with (n-1)-permutations, O(n^3) and O(n^2)
47Permutations IIPython1. DFS with swapping, check duplicate, O(n^2) and O(n^2)<br>2. iteratively generate n-permutations with (n-1)-permutations, O(n^3) and O(n^2)
53Maximum SubarrayPython1. Recursion, O(nlgn), O(lgn)<br> 2. Bottom-up DP, O(n) and O(n)<br>3. Bottom-up DP, f(x) = max(f(x-1)+A[x], A[x]), f(x) = max(f(x-1)+A[x], A[x]),O(n) and O(1)
54Spiral MatrixPythonO(nm) 1. Turn in the corner and loop<br>2. (0, 1) -> (1, 0) -> (0, -1) -> (-1, 0)
62Unique PathsPython1. Bottom-up DP, dp[i][j] = dmap[i-1][j] + dmap[i][j-1], O(mn) and O(mn)<br>2. Combination (m+n-2, m-1)
63Unique Paths IIPythonBottom-up DP, dp[i][j] = dmap[i-1][j] + dmap[i][j-1] (if block, then 0), O(mn) and O(mn)
65Valid NumberPython1. strip leading and tailing space, then check float using exception, check e using split <br>2. check is number split by . or e, note that number after e may be negative
66Plus OnePythonCheck if current digit == 9.
70Climbing StairsPythonBottom-up DP, dp[i] = dp[i - 2] + dp[i- 1] <br>1. O(n) and O(n)<br>2. Only two variables are needed, O(n) and O(1)
72Edit DistancePythonBackground<br> 1. DP O(n^2) space<br>2. DP O(n) space
78SubsetsPython1. DFS Recursion, O(2^n) and O(2^n)<br>2. Recursion on a binary number, O(2^n) and O(2^n)<br>3. Sort and iteratively generate n subset with n-1 subset, O(n^2) and O(2^n)
90Subsets IIPython1. DFS Recursion with duplicate check, O(2^n) and O(2^n)<br>2. Recursion on a binary number, O(2^n) and O(2^n)<br>3. Sort and iteratively generate n subset with n-1 subset, note that if nums[index] == nums[index - 1] then generate from last end to curr end, O(n^2) and O(2^n)
94Binary Tree Inorder TraversalPython1. Recursion, O(n) and O(1)<br>2. Stack and check isinstance(curr, TreeNode), O(n) and O(n)<br>3. Stack and check left and right, O(n) and O(n)
98Validate Binary Search TreePython1. Stack O(n) and O(n)<br>2. Recursion O(n) and O(n)
104Maximum Depth of Binary TreePythonRecursion max(left, right) + 1
108Convert Sorted Array to Binary Search TreePythonRecursion O(n) and O(nlgn)
109Convert Sorted List to Binary Search TreePython1. Two points fast (next next) and slow (next) O(nlgn) and O(n)<br>2. Bottom-up recursion O(n) and O(lgn)
110Balanced Binary TreePythonRecursion 1. Top-down O(n^2) and O(n), Bottom-up recursion with sentinel -1 O(n) and O(n)
111Minimum Depth of Binary TreePython1. Recursion, note that when size of left (ld) or right (rd) is 0, then min = 1 + ld + rd<br> 2. BFS check by level (right most), which is much faster than recursion
124Binary Tree Maximum Path SumPythonRecursion O(n) and O(n), max (left + node, right + node, left + node + right)
125Valid PalindromePythonExclude non-alphanumeric characters and compare O(n)
128Longest Consecutive SequencePythonSet or hash, pop adjacency, O(n) and O(n)
133Clone GraphPythonHash and DFS or BFS
136Single NumberPython1. Hash or set, O(n) and O(n)<br>2. xor O(n) and O(1)
137Single Number IIPython1. ctypes 32 % 3 and &, O(n) and O(1)<br>2. ones, twos, threes as bitmask (e.g. ones represents ith bit had appeared once), O(n) and O(1)
138Copy List with Random PointerPython1. Hash O(n) and O(n)<br>2. Modify original structure: Original->Copy->Original, then node.next.random = node.random.next, O(n) and O(1)
141Linked List CyclePython1. Hash or set<br> 2. Two points (fast and slow)<br>3. Add a max and check if reach the max
142Linked List Cycle IIPythonTwo points, a+b=nr
143Reorder ListPython1. List as index to rebuild relation, O(n) and O(n)<br>2. Two points, O(n) and O(1)
144Binary Tree Preorder TraversalPython1. Recursion, O(n) and O(n)<br>2. Stack, O(n) and O(n)
145Binary Tree Postorder TraversalPython1. Recursion, O(n) and O(n)<br>2. Stack and queue (insert 0), O(n) and O(n)<br>3. Stack and isinstance(curr, TreeNode), O(n) and O(n)
146LRU CachePython1. Queue and dict<br>2. OrderedDict
150Evaluate Reverse Polish NotationPythonStack
151Reverse Words in a StringPython1. Python split by space <br>2. Reverse all and reverse words
152Maximum Product SubarrayPythonDP, f(k) = max(f(k-1) * A[k], A[k], g(k-1) * A[k]), g(k) = min(g(k-1) * A[k], A[k], f(k-1) * A[k]), O(n) and O(1)
153Find Minimum in Rotated Sorted ArrayPythonBinary search with conditions, A[l] > A[r]
154Find Minimum in Rotated Sorted Array IIPythonBinary search with conditions, A[l] > A[r], A[l]=A[mid]=A[r]
155Min StackPython JavaAdd another stack for min stack, maintance this stack when the main stack pop or push: 1. Only push min, such that len(minStack)<=len(Stack) 2. Push min again when current top is min, such that len(minStack)=len(Stack)
156Binary Tree Upside DownPythonp.left = parent.right, parent.right = p.right, p.right = parent, parent = p.left, p = left
157Read N Characters Given Read4PythonHandle the edge case (the end)
158Read N Characters Given Read4 II - Call multiple timesPythonStore the pos and offset that is read by last read4
159Longest Substring with At Most Two Distinct CharactersPythonMaintain a sliding window that always satisfies such condition
161One Edit DistancePython1. Check the different position and conditions<br>2. Edit distance
163Missing RangesPythonAdd -1 to lower for special case, then check if curr - prev >= 2
166Fraction to Recurring DecimalPython% and Hash to find duplicate
167Two Sum II - Input array is sortedPythonTwo points O(n) and O(1)
170Two Sum III - Data structure designPython1. Hash, O(1) for add, O(n) for find, O(n) space<br>2. sorted list, O(logn) for add, O(n) for find, O(n) space<br> 3. Sort before find, O(1) for add, O(nlogn) for find, O(n) space
179Largest NumberPython JavaDefine a comparator with str(x) + str(y) > str(y) + str(x), O(nlgn) and O(n)
186Reverse Words in a String IIPythonReverse all and reverse each words
198House RobberPythonf(k) = max(f(k – 2) + num[k], f(k – 1)), O(n) and O(1)
200Number of IslandsPython1. Quick union find, O(nlogn) and O(n^2)<br>2. BFS with marks, O(n^2) and O(1)
204Count PrimesPython Java CPPSieve of Eratosthenes, O(nloglogn) and O(n)
206Reverse Linked ListPython Java CPP1. Stack, O(n) and O(n)<br>2. Traverse on prev and curr, then curr.next = prev, O(n) and O(1)<br>3. Recursion, O(n) and O(1)
207Course SchedulePythonCycle detection problem
213House Robber IIPythonf(k) = max(f(k – 2) + num[k], max(dp[0ls-2],dp[1ls-1], O(n) and O(1)
215Kth Largest Element in an ArrayPython Java1. Sort, O(n) and O(n)<br>2. Heap, O(nlgk) and O(n)<br>3. Quick selection, O(klgn) and O(n)
216Combination Sum IIIPythonGenerate all combinations of length k and keep those that sum to n
217Contains DuplicatePython1. Set and compare length<br>2. Sort and check i,i +1
219Contains Duplicate IIPython1. Brute force<br> 2. Maintenance a set that contains previous k numbers, and check if curr in set
220Contains Duplicate IIIPython1. Sort and binary Search <br>2. Bucket sort
221Maximal SquarePython1. Brute force<br> 2. dp[i][j] = min(dp[i-1][j], dp[i-1][j-1], dp[i][j-1]) + 1, O(mn) and O(mn)<br>3. dp[j] = min([j], dp[j-1], prev) + 1, O(mn) and O(n)
223Rectangle AreaPython JavaRectangle A + B - common area, O(1) and O(1)
228Summary RangesPythonDetect start and jump, O(n) and O(1)
236Lowest Common Ancestor of a Binary TreePython Java1. Recursive check left, val and right, LCA is the split paths in tree, O(n) and O(n)<br>2. Store parents during traversing tree, reverse check their lowest common parent, O(n) and O(n)
238Product of Array Except SelfPython JavaThe ans is [0,i -1] * [i+1, len- 1]. We can twice for left and right (reverse), O(n) and O(n)
243Shortest Word DistancePythonUpdate index1 and index2, and check distance, O(n) and O(1)
246Strobogrammatic NumberPythonHash table and reverse string, O(n) and O(n)
249Group Shifted StringsPythonHash and generate hash code for each string, O(n) and O(n)
252Meeting RoomsPython1. Sort and compare intervals[i].end with intervals[i+1], O(nlogn) and O(1)<br>2. Sort and check intervals when count >= 2, O(nlogn) and O(n)
253Meeting Rooms IIPython Java1. Priority queue and sort, O(nlogn) and O(n)<br>2. Go through timeline. If it's a start then meeting + 1, else meeting - 1. The ans is the max(meeting) in timeline. O(nlogn) and O(n)
2593Sum SmallerPython1. Reduce to two sum smaller, then binary search, O(n^2lgn) and O(1)<br>2. Reduce to two sum smaller, then two points, O(n^2) and O(1)
266Palindrome PermutationPythonCompute frequency, check number of odd occurrences <= 1 then palindrome, O(n) and O(n)
267Palindrome Permutation IIPythonCheck palindrome then generate half with Permutations II, O(n^2) and O(n^2)
268Missing NumberPython Java1. Find missing by n * (n - 1)/2 - sum(nums)<br>2. XOR with index<br>3. Sort and binary search
270Closest Binary Search Tree ValuePython1. Recursively brute force, O(n) and O(n)<br>2. Recursively compare root result with current kid's result (left or right), O(logn) and O(logn)<br>3. Iteratively compare root result with current kid's result (left or right), O(logn) and O(logn)
273Integer to English WordsPython JavaCareful about corner cases, such 1-20 and 21-Hundred, O(lgn) and O(1)
274H-IndexPythonBackground<br>1. Sort and check number of papers greater than h, O(nlogn) and O(1)<br>2. Counting sort, O(n) and O(n)
276Paint FencePythonways[i>2] = (ways[i-1] + ways[i-2]) * (k - 1), O(n) and O(1)
280Wiggle SortPython1. Sort and insert (n - 1) / 2 from tail to correct position, O(nlogn) and O(1)<br>2. Sort and swap(i, i + 1) from 1 to n - 1, O(nlogn)<br>3. Iteratively check order and reverse order, if not satisfied, then swap i with i + 1, O(n)
286Walls and GatesPythonBFS with queue, O(mn) and O(mn)
288Unique Word AbbreviationPythonhash
293Flip GamePythonPython string slicing
294Flip Game IIPython1. Backtracking to ensure that next step is False, O(n!!) and O(n!!)<br>2. Backtracking with memo, O(n!!) and O(n!)<br>3. DP based on Sprague-Grundy Function
296Best Meeting PointPythonThink hard about Manhattan Distance in 1D case. Sort and find mean, O(mnlogmn) and O(1)
298Binary Tree Longest Consecutive SequencePythonBottom-up or top-down recursion, O(n) and O(n)
305Number of Islands IIPythonQuick union find with weights, O(nlogn) and O(n)
322Coin ChangePythonBottom-up or top-down DP, dp[n] = min(dp[n], dp[n - v_i]), where v_i is the coin, O(amount * n) and O(amount)
336Palindrome PairsPython Java1. Create a reverse word to index map, then for each word, check prefix and posfix, O(nk^2) and O(n)<br>2. Tire tree, O(nk^2) and O(n)
337House Robber IIIPython1. Recursion with hash map, O(n) and O(n)<br>2. Recursion on two steps, O(n) and O(1)
339Nested List Weight SumPythonDepth-first recursion
340Longest Substring with At Most K Distinct CharactersPythonMaintain a sliding window with at most k distinct characters and a count for this window. Note that the start position need a loop to update.
346Moving Average from Data StreamPythonfix-sized queue or dequeue, O(1) and O(n)
347Top K Frequent ElementsPython Java1. Sort by frequency, O(nlogn) and O(n). <br> 2. we can build a min heaq (based on frequency), then pop min until there are k element, O(klgn) and O(n)
351Android Unlock PatternsPythonBacktracking, O(n!) and O(n)
359Logger Rate LimiterPython1. hash which stores the latest timestamp, O(1) and O(n)<br>2. Using Priority queue to remove older logs, O(n) and O(n)
366Find Leaves of Binary TreePython1. Set or hash to check leaft, O(n^2) and O(n)<br>2. Recursively check level and return them, O(n) and O(n)
367Valid Perfect SquarePython JavaInteger square root<br>1. 1+3+…+(2n-1) = n^2<br>2. Binary search<br>3. Newton's method
368Largest Divisible SubsetPythonSort and generate x subset with previous results, O(n^2) and O(n^2)
369Plus One Linked ListPython1. Stack or list that store the list, O(n) and O(n)<br>2. Two points, the first to the tail, the second to the latest place that is not 9, O(n) and O(1)
370Range AdditionPythonInterval problem with cumulative sums, O(n + k) and O(n)
380Insert, Delete, Get RandomPythonUses both a list of nums and a list of their locations
383Ransom NotePython JavaGet letter frequency (table or hash map) of magazine, then check randomNote frequency
384Shuffle an ArrayPythonFisher–Yates shuffle, O(n) and O(n)
387First Unique Character in a StringPython JavaGet frequency of each letter, return first letter with frequency 1, O(n) and O(1)
388Longest Absolute File PathPythonStore last length and rindex, O(n) and O(n)
389Find the DifferencePython Java1. Imaging letter a as 0, then the sum(t)-sum(s) is the result<br> 2. Based on solution 1, bit manipulate
400Nth DigitPython Javaislands * 4 - overlaps * 2
401Binary WatchPython JavaNote that 12 * 60 is much less than 2^n or n^2.
404Sum of Left LeavesPython Java1. Recursively DFS with root.left.left and root.left.right check<br>2. The same DFS based on stack
405Convert a Number to HexadecimalPython JavaTwo's complement 1. Bit manipulate, each time handle 4 digits<br>2. Python (hex) and Java API (toHexString & Integer.toHexString)
408Valid Word AbbreviationPythonGo over abbr and word, O(n) and O(1)
409Longest PalindromePython JavaLength of Palindrome is always 2n or 2n + 1. So, get all possible 2*n, and choose a single one as 1 if it exists.
412Fizz BuzzPython Java Cpp1. From 1 to n, condition check<br>2. Condition check and string connect
414Third Maximum NumberPython Java1. Keep max 1-3 then compare, O(n) and O(1)<br>2. PriorityQueue, O(n) and O(1)
415Add StringsPython JavaTwo points, careful abour carry, O(n) and O(n)
416Partition Equal Subset SumPythonDP, Check if sum of some elements can be half of total sum, O(total_sum / 2 * n) and O(total_sum / 2)
421Maximum XOR of Two Numbers in an ArrayPythonCheck 0~32 prefix, check if there is x y in prefixes, where x ^ y = answer ^ 1, O(32n) and O(n)
422Valid Word SquarePythonCompare row with column, O(n^2)
434Number of Segments in a StringPython Java1. trim &split<br>2. Find segment in place
437Path Sum IIIPython Java1. Recursively travese the whole tree, O(n^2)<br>2. Cache sum in Hash based on solution 1. Note that if sum(A->B)=target, then sum(root->a)-sum(root-b)=target.
438Find All Anagrams in a StringPython JavaBuild a char count list with 26-256 length. Note that this list can be update when going through the string. O(n) and O(1)
441Arranging CoinsPythonO(n) time.
443String CompressionPython JavaMaintain curr, read, write and anchor (start of this char).
448Find All Numbers Disappeared in an ArrayPython JavaValue (1, n) and index (0, n-1). Mark every value postion as negative. Then, the remain index with positive values are result. O(n)
453Number of Segments in a StringPython JavaEach move is equal to minus one element in array, so the answer is the sum of all elements after minus min.
458Poor PigsPython Java2 pigs for 5 * 5 metric
461Hamming DistancePython JavaHamming Distance is related to XOR for numbers. So, XOR then count 1. O(n)
463Island PerimeterPython Javamath, find the area, actual number, then find the digit
475HeatersPython Java1. Binary search hourse in heater array, O(nlogn) and O(1)<br> 2. Two points, O(nlogn) and O(1)
479Largest Palindrome ProductPython Java1. Product max palindrome than check, O(n^2) and O(1)<br>2. Math
482License Key FormattingPython JavaString processing, lower and len % K, O(n) and O(n)
485Max Consecutive OnesPython JavaAdd one when encounter 1, set to 0 when encounter 0, O(n) and O(1)
509Fibonacci NumberPython Java1. Recursive, O(n) <br>2. DP with memo, O(n). Note that N<=30, which means that we can keep a memo from 0 to 30.
523Continuous Subarray SumPythonO(n) solution using dict()
538Convert BST to Greater TreePython JavaRight first DFS with a variable recording sum of node.val and right.val. 1. Recursive.<br>2. Stack 3. Reverse Morris In-order Traversal
541Reverse String IIPython JavaHandle each 2k until reaching end, On(n) and O(n)
543Diameter of Binary TreePython JavaDFS with O(1) for max answer
547Friend CirclesPython Java1. DFS, O(n^2) and O(1)<br>2. BFS, O(n^2) and O(1)<br>3. Union-find, O(n^2) and O(n)
557Reverse Words in a String IIIPython JavaString handle: Split with space than reverse word, O(n) and O(n). Better solution is that reverse can be O(1) space in array.
560Subarray Sum Equals KPython JavaNote that there are n^2 possible pairs, so the key point is accelerate computation for sum and reduce unnecessary pair. 1. Cummulative sum, O(n^2) and O(1)/O(n)<br>2. Add sum into hash, check if sum - k is in hash, O(n) and O(n)
572Subtree of Another TreePython Java1. Tree traverse and compare<br>2. Tree to string and compare
581Shortest Unsorted Continuous SubarrayPython Java1. Sort and find the difference (min and max), O(nlgn)<br>2. Using stack to find boundaries (push when correct order, pop when not correct), O(n) and O(n)<br>3. Find min and max of unordered array, O(n) and O(1)
605Can Place FlowersPython JavaOne time scan, check [i-1] [i] and [i+1], O(n) and O(1)
617Merge Two Binary TreesPython JavaTraverse both trees Recursion & Iterative (stack)
628Maximum Product of Three NumbersPython JavaActually, we should only care about min1, min2 and max1-max3, to find these five elements, we can use 1. Brute force, O(n^3) and O(1)<br>2. Sort, O(nlogn) and O(1)<br>3. Single scan with 5 elements keep, O(n) and O(1)
654Maximum Binary TreePython Java1. Divide and conquer, recursive, O(n^2)<br>2. Monotonic stack, O(n)
665Non-decreasing ArrayPython Java1. Find the broken index, then check this point, O(n) and O(1)<br>2. Replace broken point with correct value, then check if there are more than 1 broken point, O(n) and O(1)
668Kth Smallest Number in Multiplication TablePython Java CppBinary search, O(mlog(mn) and O(1)
671Second Minimum Node In a Binary TreePython JavaNote that min value is root: 1. Get all values then find result, O(n) and O(n)<br>2. BFS or DFS traverse the tree, then find the reslut, O(n) and O(n)
674Longest Continuous Increasing SubsequencePython JavaScan nums once, check nums[i] < nums[i+1], if not reset count, O(n) and O(1)
680Valid Palindrome IIPython JavaRecursively check s[left == end, when not equal delete left or right.
692Top K Frequent WordsPython Java1. Sort based on frequency and alphabetical order, O(nlgn) and O(n)<br>2. Find top k with Heap, O(nlogk) and O(n)
695Max Area of IslandPython Java1. DFS, O(n^2) and O(n)<br>2. BFS, O(n^2) and O(n)
697Degree of an ArrayPython Java1. Find degree and value, then find smallest subarray (start and end with this value), O(n) and O(n)<br>2. Go through nums, remember left most pos and right most for each value, O(n) and O(n)
700Search in a Binary Search TreePython JavaRecursive or iteration, O(logn)
703Kth Largest Element in a StreamPython Java1. Sort and insert into right place, O(nlgn) and O(n)<br>2. k largest heap, O(nlogk) and O(n)
706Design HashMapPython JavaHash implementation, mod is fine. Be careful about key conflict and key remove.
709To Lower CasePython JavaString processing:<br>1. str.lower() or str.toLowerCase()<br>2. ASCII processing. O(n) and O(1)
716Max StackPython Java1. Two stacks<br> 2. Double linked list and Hash
7171-bit and 2-bit CharactersPython Java1. Go through bits, 1 skip next, O(n) and O(1)<br>2. Find second last zero reversely, O(n) and O(1)
720Longest Word in DictionaryPython Java1. Brute Force, O(sum(w^2)) and O(w)<br>2. Tire Tree, O(sum(w) and O(w))<br>3. Sort and word without last char, O(nlogn + sum(w)) and O(w)
724Find Pivot IndexPython JavaSeach the array to find a place where left sum is equal to right sum, O(n) and O(1)
728Self Dividing NumbersPython JavaBrute Force check every digit, O(nlogD) and O(1)
733Flood FillPython Java1. DFS with stack or recursive, O(n) and O(n)<br>2. BFS with queue, O(n) and O(n)
743Network Delay TimePython JavaLet V == N, then: 1. DFS, O(V^V+ElgE), O(V+E)<br>2. Dijkstra, O(V^2+E), O(V+E)
751IP to CIDRPython JavaBit manipulations, incrementail is 1 << (32 - mask)
760Find Anagram MappingsPython JavaHash table with A's (val, index), O(n) and O(n)
766Toeplitz MatrixPython JavaCheck from top left to bottom right, i,j == i + 1, j + 1.
771Jewels and StonesPython JavaCount given char in string. Hash or table. Oneline
784Letter Case PermutationPython JavaNote that this is a 2^n problem. 1. Recursively generate result with previous result <br> 2. Bin Mask, number of zeor equal to number of alpha<br>3. Python build in product.
804Unique Morse Code WordsPython JavaString, Hash and Set. Set is recommended.
811Subdomain Visit CountPython JavaString split and HashMap, O(n) and O(n)
819Most Common WordPython JavaString processing, be careful about 'b,b,b'. regex is recommended.
832Flipping an ImagePython JavaInvert and swap can be done at the same time, and careful about (n + 1)/2, O(n^2) and O(1)
836Rectangle OverlapPython Java1. Check position, O(1) and O(1)<br>2. Check area, O(1) and O(1)
844Backspace String ComparePython Java1. Stack pop when encounters #, O(n) and O(n)<br>2. Compare string from end to start, O(n) and O(1)
852Peak Index in a Mountain ArrayPython Java1. Scan the array until encountering decline, O(n) and O(1)<br>2. Binary seach with additional check for [i + 1], O(logn) and O(1)
867Transpose MatrixPython JavaRes[i][j] = A[j][i]
868Binary GapPython Java1. Store index and check, O(logn) and O(logn)<br>2. One pass and store max, O(logn) and O(1)
872Leaf-Similar TreesPython JavaDFS (stack or recursion) get leaf value sequence and compare, O(n) and O(n)
876Middle of the Linked ListPython Java1. Copy to array, O(n) and O(n)<br>2. Fast and slow point, where fast point is 2 times faster than slow point, O(n) and O(1)
904Fruit Into BasketsPython Java1. Scan through blocks of tree, O(n) and O(n)<br>2. Mainten a sliding window with start and curr point, O(n) and O(n).
905Sort Array By ParityPython Java1. Sort with condition, O(nlogn) and O(1)<br>2. Scan all and split odd and even number into different array, O(n) and O(n)<br>3. In place swap similar to quick sort, O(n) and O(1)
922Sort Array By Parity IIPython Java1. Place odd and even number in odd and even place, not sort is needed. O(n) and O(1)<br>2. Two points with quick sort swap idea, O(n) and O(1).
929Unique Email AddressesPython JavaString handle and hash (or set)
933Number of Recent CallsPython JavaQueue, remove val in head when val < t - 3000, O(n) and O(n)
937Reorder Log FilesPython Java1. Comstom Sort, O(nlogn) and O(1)<br>2. Separete letter logs and digit logs, then sort letter logs and merge with digit logs, O(nlogn) and O(n)
945Minimum Increment to Make Array UniquePython JavaSort, then list duplicate and missing value in sorted list. O(nlgn) and O(n)
946Validate Stack SequencesPython JavaAdd a stack named inStack to help going through pushed and popped. O(n) and O(n)
953Verifying an Alien DictionaryPython JavaUse hashmap to store index of each value, then create a comparator based on this index, O(n) and O(n)
954Array of Doubled PairsPython JavaSort, then use hashmap to store the frequency of each value. Then, check n, 2 * n in hashmap, O(nlogn) and O(n)
961N-Repeated Element in Size 2N ArrayPython JavaHash and count number, O(n) and O(n)
962Maximum Width RampPython Java1. Sort index by value, then transfer problem into finding max gap between index, O(nlogn) and O(1)<br>2. Binary Search for candicates, O(nlogn) and O(n)
977Squares of a Sorted ArrayPython Java1. Sort, O(nlogn) and O(n)<br>2. Two point, O(n) and O(n)
973K Closest Points to OriginPython Java1. Sort and get 0-K, O(nlogn) and O(1)<br>2. Min Heap, O(nlogk) and O(k)
981Time Based Key-Value StorePythonGet: O(log(n)) time<br>Set: O(1) time
1064Fixed PointPython Java1. Go through index and value, until find solution encounter index < value, O(n) and O(1)<br>2. Binary search, O(logn) and O(1)
1089Duplicate ZerosPython Java2 Pass, store last position and final move steps, O(n) and O(1)
1108Defanging an IP AddressPython JavaString manipulate (split, replace and join), O(n) and O(n)
1189Maximum Number of BalloonsJavaCount letters in balon, then find min, O(n) and O(1)
1260Shift 2D GridPython JavaFinal position of each element can be computed according to k, m and n, e.g., k == mn, then don't move, O(mn) and O(mn)
1290Convert Binary Number in a Linked List to IntegerPythonTake 2 to the power digit position from right (starting from 0) and multiply it with the digit
1304Find N Unique Integers Sum up to ZeroPython Java[1,n-1] and its negative sum
1310XOR Queries of a SubarrayPython Java CppCompute accumulated xor from head, qeury result equals to xor[0, l] xor x[0, r], O(n) and O(n)
1323Maximum 69 NumberPython Java9 is greater than 6, so change first 6 to 9 from left if exist, O(n) and O(1)
1337The K Weakest Rows in a MatrixPython JavaCheck by row, from left to right, until encount first zero, O(mn) and O(1)
1342Number of Steps to Reduce a Number to ZeroPythonIf number is divisible by 2, divide the number by 2, else subtract 1 from the number, and output the number of steps, O(logn) and O(1)
1365How Many Numbers Are Smaller Than the Current NumberPython Java1. Sort and get position in sorted nums, O(nlogn) and O(n)<br>2. Fill count into 0-100, O(n) and O(1)
1480Running Sum of 1d ArrayPython Java1. Go through the array, O(n) and O(1)<br>2. Accumulate API
1539Kth Missing Positive NumberJavaBinary search, num of missing = arr[i]-i-1
1909Remove One Element to Make the Array Strictly IncreasingPythonUse brute-force. O( (nums.length)<sup>2</sup>)
1981Minimize the Difference Between Target and Chosen ElementsJavaDP memo[row][sum] to avoid recomputing
2409Count Days Spent TogetherPythonUse month as a day
2413Smallest Even MultiplePythonCheck the n is multiply by 2
2429Minimize XORPythoncheck the num1, num2 with length and replace "0" compare with num1.
#To Understand
4Median of Two Sorted Arrays

Other LeetCode Repos

  1. LeetCode Algorithms ~anishLearnsToCode
  2. haoel's leetcode
  3. soulmachine's leetcode
  4. kamyu104's LeetCode
  5. gouthampradhan's leetcode