Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Python & JAVA Solutions for Leetcode

License

NotificationsYou must be signed in to change notification settings

coderscode91/leetcode

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

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

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

Python andJava full list. ♥ means you need a subscription.

#TitleSolutionBasic idea (One line)
1Two SumPythonJava1. Hash O(n) and O(n) space.
2. Sort and search with two points O(n) and O(1) space.
2Add Two NumbersPythonJavaTake care of the carry from lower digit.
3Longest Substring Without Repeating CharactersPythonJava1. 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 ArraysPythonJava1. 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 SubstringPythonJavaBackground 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 IntegerPythonJavaOverflow when the result is greater than 2147483647 or less than -2147483648.
8String to Integer (atoi)PythonJavaOverflow, Space, and negative number
9Palindrome NumberPythonJavaGet 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 StackPythonJavaAdd 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 NumberPythonJavaDefine 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 ArrayPythonJava1. 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 AreaPythonJavaRectangle 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 TreePythonJava1. 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 SelfPythonJavaThe 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 withPermutations II, O(n^2) and O(n^2)
268Missing NumberPythonJava1. 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 WordsPythonJavaCareful 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 onSprague-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 PairsPythonJava1. 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 ElementsPythonJava1. 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 SquarePythonJavaInteger 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 NotePythonJavaGet 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 StringPythonJavaGet 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 DifferencePythonJava1. Imaging letter a as 0, then the sum(t)-sum(s) is the result
2. Based on solution 1, bit manipulate
400Nth DigitPythonJavaislands * 4 - overlaps * 2
401Binary WatchPythonJavaNote that 12 * 60 is much less than 2^n or n^2.
404Sum of Left LeavesPythonJava1. Recursively DFS with root.left.left and root.left.right check
2. The same DFS based on stack
405Convert a Number to HexadecimalPythonJavaTwo'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 PalindromePythonJavaLength 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 BuzzPythonJava1. From 1 to n, condition check
2. Condition check and string connect
414Third Maximum NumberPythonJava1. Keep max 1-3 then compare, O(n) and O(1)
2. PriorityQueue, O(n) and O(1)
415Add StringsPythonJavaTwo 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 StringPythonJava1. trim &split
2. Find segment in place
437Path Sum IIIPythonJava1. 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 StringPythonJavaBuild 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 CompressionPythonJavaMaintain curr, read, write and anchor (start of this char).
448Find All Numbers Disappeared in an ArrayPythonJavaValue (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 StringPythonJavaEach move is equal to minus one element in array, so the answer is the sum of all elements after minus min.
458Poor PigsPythonJava2 pigs for 5 * 5 metric
461Hamming DistancePythonJavaHamming Distance is related to XOR for numbers. So, XOR then count 1. O(n)
463Island PerimeterPythonJavamath, find the area, actual number, then find the digit
475HeatersPythonJava1. Binary search hourse in heater array, O(nlogn) and O(1)
2. Two points, O(nlogn) and O(1)
479Largest Palindrome ProductPythonJava1. 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 FormattingPythonJavaString processing, lower and len % K, O(n) and O(n)
538Convert BST to Greater TreePythonJavaRight 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 TreePythonJavaDFS with O(1) for max answer
547Friend CirclesPythonJava1. 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 IIIPythonJavaString 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 KPythonJavaNote 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 TreePythonJava1. Tree traverse and compare
2. Tree to string and compare
581Shortest Unsorted Continuous SubarrayPythonJava1. 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 FlowersPythonJavaOne time scan, check [i-1] [i] and [i+1], O(n) and O(1)
617Merge Two Binary TreesPythonJavaTraverse both trees Recursion & Iterative (stack)
628Maximum Product of Three NumbersPythonJavaActually, 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 TreePythonJava1. Divide and conquer, recursive, O(n^2)
2. Monotonic stack, O(n)
671Second Minimum Node In a Binary TreePythonJavaNote 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 SubsequencePythonJavaScan nums once, check nums[i] < nums[i+1], if not reset count, O(n) and O(1)
680Valid Palindrome IIPythonJavaRecursively check s[left == end, when not equal delete left or right.
692Top K Frequent WordsPythonJava1. 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 IslandPythonJava1. DFS, O(n^2) and O(n)
2. BFS, O(n^2) and O(n)
697Degree of an ArrayPythonJava1. 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 TreePythonJavaRecursive or iteration, O(logn)
703Kth Largest Element in a StreamPythonJava1. Sort and insert into right place, O(nlgn) and O(n)
2. k largest heap, O(nlogk) and O(n)
706Design HashMapPythonJavaHash implementation, mod is fine. Be careful about key conflict and key remove.
709To Lower CasePythonJavaString processing:
1. str.lower() or str.toLowerCase()
2. ASCII processing. O(n) and O(1)
716Max StackPythonJava1. Two stacks
2. Double linked list and Hash
720Longest Word in DictionaryPythonJava1. 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 IndexPythonJavaSeach the array to find a place where left sum is equal to right sum, O(n) and O(1)
733Flood FillPythonJava1. DFS with stack or recursive, O(n) and O(n)
2. BFS with queue, O(n) and O(n)
743Network Delay TimePythonJavaLet V == N, then: 1. DFS, O(V^V+ElgE), O(V+E)
2. Dijkstra, O(V^2+E), O(V+E)
751IP to CIDRPythonJavaBit manipulations, incrementail is 1 << (32 - mask)
760Find Anagram MappingsPythonJavaHash table with A's (val, index), O(n) and O(n)
766Toeplitz MatrixPythonJavaCheck from top left to bottom right, i,j == i + 1, j + 1.
771Jewels and StonesPythonJavaCount given char in string. Hash or table.Oneline
784Letter Case PermutationPythonJavaNote 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 WordsPythonJavaString, Hash and Set. Set is recommended.
811Subdomain Visit CountPythonJavaString split and HashMap, O(n) and O(n)
819Most Common WordPythonJavaString processing, be careful about 'b,b,b'. regex is recommended.
832Flipping an ImagePythonJavaInvert and swap can be done at the same time, and careful about (n + 1)/2, O(n^2) and O(1)
836Rectangle OverlapPythonJava1. Check position, O(1) and O(1)
2. Check area, O(1) and O(1)
844Backspace String ComparePythonJava1. 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 ArrayPythonJava1. 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 MatrixPythonJavaRes[i][j] = A[j][i]
872Leaf-Similar TreesPythonJavaDFS (stack or recursion) get leaf value sequence and compare, O(n) and O(n)
876Middle of the Linked ListPythonJava1. 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 BasketsPythonJava1. 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 ParityPythonJava1. 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 IIPythonJava1. 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 AddressesPythonJavaString handle and hash (or set)
933Number of Recent CallsPythonJavaQueue, remove val in head when val < t - 3000, O(n) and O(n)
945Minimum Increment to Make Array UniquePythonJavaSort, then list duplicate and missing value in sorted list. O(nlgn) and O(n)
946Validate Stack SequencesPythonJavaAdd a stack named inStack to help going through pushed and popped. O(n) and O(n)
953Verifying an Alien DictionaryPythonJavaUse hashmap to store index of each value, then create a comparator based on this index, O(n) and O(n)
954Array of Doubled PairsPythonJavaSort, 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 ArrayPythonJavaHash and count number, O(n) and O(n)
962Maximum Width RampPythonJava1. Sort index by value, then transfer problem into finding max gap between index, O(nlogn) and O(1)
#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

About

Python & JAVA Solutions for Leetcode

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • Python81.5%
  • Java18.5%

[8]ページ先頭

©2009-2025 Movatter.jp