Python & JAVA Solutions for Leetcode

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.

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

#TitleSolutionBasic idea (One line)
1Two SumPython Java1. Hash O(n) and O(n) space.
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)
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)
2. An extension of median of two sorted arrays of equal size problem
5Longest Palindromic SubstringPython JavaBackground knowledge
1. DP if s[i]==s[j] and P[i+1, j-1] then P[i,j]
2. A palindrome can be expanded from its center
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
12Integer to RomanPythonBackground 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
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
20Valid ParenthesesPython1. Stack
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)
2. Binary merge O(nk log k)
24Swap Nodes in PairsPythonAdd a dummy and store the prev
28Implement strStr()Python1. O(nm) comparison
2. KMP
35Search Insert PositionPythonBinary Search
46PermutationsPython1. Python itertools.permutations
2. DFS with swapping, O(n^2) and O(n^2)
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)
2. iteratively generate n-permutations with (n-1)-permutations, O(n^3) and O(n^2)
53Maximum SubarrayPython1. Recursion, O(nlgn), O(lgn)
2. Bottom-up DP, O(n) and O(n)
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
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)
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
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]
1. O(n) and O(n)
2. Only two variables are needed, O(n) and O(1)
72Edit DistancePythonBackground
1. DP O(n^2) space
2. DP O(n) space
78SubsetsPython1. DFS Recursion, O(2^n) and O(2^n)
2. Recursion on a binary number, O(2^n) and O(2^n)
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)
2. Recursion on a binary number, O(2^n) and O(2^n)
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)
2. Stack and check isinstance(curr, TreeNode), O(n) and O(n)
3. Stack and check left and right, O(n) and O(n)
98Validate Binary Search TreePython1. Stack O(n) and O(n)
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)
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
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)
2. xor O(n) and O(1)
137Single Number IIPython1. ctypes 32 % 3 and &, O(n) and O(1)
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)
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
2. Two points (fast and slow)
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)
2. Two points, O(n) and O(1)
144Binary Tree Preorder TraversalPython1. Recursion, O(n) and O(n)
2. Stack, O(n) and O(n)
145Binary Tree Postorder TraversalPython1. Recursion, O(n) and O(n)
2. Stack and queue (insert 0), O(n) and O(n)
3. Stack and isinstance(curr, TreeNode), O(n) and O(n)
146LRU CachePython1. Queue and dict
2. OrderedDict
150Evaluate Reverse Polish NotationPythonStack
151Reverse Words in a StringPython1. Python split by space
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
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
2. sorted list, O(logn) for add, O(n) for find, O(n) space
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)
2. BFS with marks, O(n^2) and O(1)
206Reverse Linked ListPython1. Stack, O(n) and O(n)
2. Traverse on prev and curr, then curr.next = prev, O(n) and O(1)
3. Recursion, O(n) and O(1)
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)
2. Heap, O(nlgk) and O(n)
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
2. Sort and check i,i +1
219Contains Duplicate IIPython1. Brute force
2. Maintenance a set that contains previous k numbers, and check if curr in set
220Contains Duplicate IIIPython1. Sort and binary Search
2. Bucket sort
221Maximal SquarePython1. Brute force
2. dp[i][j] = min(dp[i-1][j], dp[i-1][j-1], dp[i][j-1]) + 1, O(mn) and O(mn)
3. dp[j] = min([j], dp[j-1], prev) + 1, O(mn) and O(n)
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)
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)
2. Sort and check intervals when count >= 2, O(nlogn) and O(n)
253Meeting Rooms IIPythonJava1. Priority queue and sort, O(nlogn) and O(n)
2. Go through timeline. If it’s a start then meeting + 1, else meeting - 1. The ans is the max(meeting) in timeline. O(nlogn) and O(n)
2593Sum SmallerPython1. Reduce to two sum smaller, then binary search, O(n^2lgn) and O(1)
2. Reduce to two sum smaller, then two points, O(n^2) and O(1)
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)
2. XOR with index
3. Sort and binary search
270Closest Binary Search Tree ValuePython1. Recursively brute force, O(n) and O(n)
2. Recursively compare root result with current kid’s result (left or right), O(logn) and O(logn)
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
1. Sort and check number of papers greater than h, O(nlogn) and O(1)
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)
2. Sort and swap(i, i + 1) from 1 to n - 1, O(nlogn)
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!!)
2. Backtracking with memo, O(n!!) and O(n!)
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)
2. Tire tree, O(nk^2) and O(n)
337House Robber IIIPython1. Recursion with hash map, O(n) and O(n)
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).
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)
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)
2. Recursively check level and return them, O(n) and O(n)
367Valid Perfect SquarePython JavaInteger square root
1. 1+3+…+(2n-1) = n^2
2. Binary search
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)
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)
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
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
2. The same DFS based on stack
405Convert a Number to HexadecimalPython JavaTwo’s complement 1. Bit manipulate, each time handle 4 digits
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 Java1. From 1 to n, condition check
2. Condition check and string connect
414Third Maximum NumberPython Java1. Keep max 1-3 then compare, O(n) and O(1)
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
2. Find segment in place
437Path Sum IIIPython Java1. Recursively travese the whole tree, O(n^2)
2. Cache sum in Hash based on solution 1. Note that if sum(A->B)=target, then sum(root->a)-sum(root-b)=target.
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)
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)
2. Two points, O(nlogn) and O(1)
479Largest Palindrome ProductPython Java1. Product max palindrome than check, O(n^2) and O(1)
2. [Math](# https://leetcode.com/problems/largest-palindrome-product/discuss/96305/Python-Solution-Using-Math-In-48ms)
482License Key FormattingPython JavaString processing, lower and len % K, O(n) and O(n)
509Fibonacci NumberPython Java1. Recursive, O(n)
2. DP with memo, O(n). Note that N<=30, which means that we can keep a memo from 0 to 30.
538Convert BST to Greater TreePython JavaRight first DFS with a variable recording sum of node.val and right.val. 1. Recursive.
2. Stack 3. Reverse Morris In-order Traversal
543Diameter of Binary TreePython JavaDFS with O(1) for max answer
547Friend CirclesPython Java1. DFS, O(n^2) and O(1)
2. BFS, O(n^2) and O(1)
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)
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
2. Tree to string and compare
581Shortest Unsorted Continuous SubarrayPython Java1. Sort and find the difference (min and max), O(nlgn)
2. Using stack to find boundaries (push when correct order, pop when not correct), O(n) and O(n)
3. Find min and max of unordered array, O(n) and O(1)
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)
2. Sort, O(nlogn) and O(1)
3. Single scan with 5 elements keep, O(n) and O(1)
654Maximum Binary TreePython Java1. Divide and conquer, recursive, O(n^2)
2. Monotonic stack, O(n)
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)
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)
2. Find top k with Heap, O(nlogk) and O(n)
695Max Area of IslandPython Java1. DFS, O(n^2) and O(n)
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)
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)
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:
1. str.lower() or str.toLowerCase()
2. ASCII processing. O(n) and O(1)
716Max StackPython Java1. Two stacks
2. Double linked list and Hash
720Longest Word in DictionaryPython Java1. Brute Force, O(sum(w^2)) and O(w)
2. Tire Tree, O(sum(w) and O(w))
3. Sort and word without last char, O(nlogn + sum(w)) and O(w)
724Find Pivot IndexPython JavaSeach the array to find a place where left sum is equal to right sum, O(n) and O(1)
733Flood FillPython Java1. DFS with stack or recursive, O(n) and O(n)
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)
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
2. Bin Mask, number of zeor equal to number of alpha
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)
2. Check area, O(1) and O(1)
844Backspace String ComparePython Java1. Stack pop when encounters #, O(n) and O(n)
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)
2. Binary seach with additional check for [i + 1], O(logn) and O(1)
867Transpose MatrixPython JavaRes[i][j] = A[j][i]
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)
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)
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)
2. Scan all and split odd and even number into different array, O(n) and O(n)
3. In place swap similar to quick sort, O(n) and O(1)
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)
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)
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)
2. Binary Search for candicates, O(nlogn) and O(n)
#To Understand
4Median of Two Sorted Arrays

Other Leetcode Repos

  1. haoel’s leetcode
  2. soulmachine’s leetcode
  3. kamyu104’s LeetCode
  4. gouthampradhan’s leetcode
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值