Skip to content
Home ยป X Algorithm – 250 LeetCode Coding Challenge Questions

X Algorithm โ€“ 250 LeetCode Coding Challenge Questions

This is a personal coding challenge collection, the source is from LeetCode. To practice how to solve algorithm problems.

Feel free to contact me if you have any problems related.

#ProblemLeetCode DifficultyStructure / AlgorithmSolving Ideas / Hints
1041Robot Bounded in CircleMediumString, Simulate– From LeetCode Tips, the robot stays in the circle if and only if (looking at the final vector) it changes direction (ie. doesn’t stay pointing north), or it moves 0.
7Reverse integerMediumMathJS Max Integer is larger than 2**31;
13Roman to IntegerEasyHash Map– Roman numbers has a nature of sum calculation, so the tip is to have a hashmap/dict/opject to map Roman number to integer
14Longest Common PrefixEasyString– Read Requirement Carefully, prefix is the starting letters only, (I understands it wrongly in the beginning)
– Brute Force, O(n*m), m is the longest string length
67Add BinaryEasyString, Calculation, Binary– No different to add integers or binary, because the result are the same, the only difference is the format
– Most of languages, there is a limit for integer, here the tricky part is that the binary number is above the maximum integer, so when transfer from the binary to integer, it lost some value, use `BigInt` in JS could solve the problem, but in Python 3, there would not be a problem, because there is no int and long in Python3
20Valid ParenthesisEasyString, Stack– Use Stack
– If an input start with ] } ), it will never close
– in JS Set is supported
21Merge Two Sorted LinkListEasyLinkList– The definition of the ListNode is a bit confused, it is ES5 style of class, so for using it, use
new ListNode(0, null)
27Remove ElementsEasyArray, Two PointersTwo Pointers can be used here
– JS Splice Function could be used too
26Remove Duplication from a Sorted ArrayEasyArray, Two Pointers
28strStrEasyString– This basically required to write a `indexOf` function
– Consider not using high level function, like indexOf
35Search Insert PositionEasyBinary Search– Loop, use low and high and while loop
– Recursion, try pass start and end index
49Group AnagramsMediumString, Sort, Hash Map– This one is not very hard, it is a combination of usages of different algorithm and data structure
– Object.values(), Object.keys(), Obejct.entries()
53Maximum Sub ArrayEasyDynamic Programming, Divide and Conquer
58Length of the Last WordEasy– Split String to Words (do not forget trim the end of the string)
– Find last word and get the length
64Minimum Path SumMediumPath Find, Matrix– This looks like to the 53, maximum sub array, but actually, put it in 2d matrix, make it different
– This is a classical path finding problem
– To avoid, time out, use dict/hashmap as a caching layer, caching will solve the problem, but it costs more storage, more about dynamic programming solution

66Plus OneEasyArray– Unshift can be used to append 1 into the beginning of array
– Shift is used to remove the 1st element, different with pop().
– i++/i– return the value before calculation, comparing to ++i/–i
67Add BinaryEasy– BigInt can be used here
69SqrtxEasyMath– Use Binary Search here
70Climbing StairsEasyDynamic Programming– Find the pattern of the result, which it is Fibonacci
605Can Place FlowersEasy– Read requirements carefully
83Remove Duplicates from Sorted ListEasyLinked List, Two Pointer– I wrote a simple JS solution for this, in page 2, faster than 93% js solution
88Merge Sorted ArraysEasyTodo, I did not figure out a proper way to cover all cases in the beginning in time O(m+n)
– There is a O(m+n) solution in page 3, try think reversely
– But merge arrays and resort is the easiest solution, will be nLogN
94Binary Tree Inorder TraversalEasyTree, Binary Tree, Stack, Recursion, Depth First– Recursion is easier for solving this
– pop, push, shift unshift
100Same TreeEasyTree
101Symmetric TreeEasyTree, BFS, DFS– DFS Recursion solution is easy to get
– For interaction, this is a good discussion on LeetCode as a queue base BFS solution
104Maximum Depth of Binary TreeEasyTree, BFS, DFS,– Good Stack Based DFS/ Queue Based BFS iteration examples on LeetCode, actually the DFS iteration solution is a bit hard to understand
– DFS Recursion is easier to understand
108Convert Sorted Array to Binary Search TreeEasyDFS
520Detect CapitalEasyString
110Balanced Binary TreeEasyBalanced Tree– Balanced Binary Tree, left height and right height differs in 1
– Both left, right and all sub trees are balanced
111Minimum Depth of Binary TreeEasyBFS, DFS
112Path SumEasyDFS
113Path Sum 2MediumDFS, Binary Tree
125Valid PalindromeEasyString
136Single NumberEasyList, Bit Manipulation– 5^5 = 0, XOR, Any same two elements XOR operation, it will be 0, this is why Bit Manipulation works in reduce
941Valid Mountain ArrayEasyList
141Linked List CycleEasyLinked List, Slow And Fast, Two Pointersthere are 3 ideas for this,
– 1 use Set/Map, time O(n), Space O(n)
– 2 use Slow Fast Pointers, time O(n), Space O(1)
– 3 modify the nodes in the interaction, time O(n), space O(1)
144Binary Tree PreOrder TraversalEasyDFS, Stack
145Binary Tree PostOrder TraversalEasyDFS, Stack
118Pascal’s TriangleEasyDynamic Programming
160Two Linked List IntersectionEasyLinked List, O(1) Space Solution,
– O(n) Space Solution, using Hash Map
167Two Sum 2EasyBinary, Two Pointers, Hash MapThere are 3 ideas for this, 1 is brute force, O(n^2), 2 is through using Hash Map, like normal Two Sum, 3 is using 2 pointers, one start one end, because the array is sorted
168Excel Sheet ColumnEasyString, Math
169Majority ElementEasyHash Map, Divide and ConquerThe optional requirement here is to make it in O(1) space.
– There is one amazing two line approach for this. nums.sort((a,b) => a - b); return nums[Math.floor(nums.length/2)]; O(nlog(n)) + O(1)
Boyer-Moore Voting Algorithmleetcode submission O(n) + O(1)
– For divide and conquer, it will be a bit more complicated, O(n) + O(1)
171Excel Sheet Column NumberEasyString, Math
1672Richest Customer WealthEasyArray, Matrix
190Reverse BitsEasyBit Manipulation, Divide and Conquer
121Best Time To Buy and Sell StockEasyArray, Dynamic ProgrammingWithout dynamic programming, it will exceed time limit.
191Number of 1 BitsEasyBit Manipulation0b111 & 1 => 1
0b110 & 1 => 0
0b111 >> 1 => 0b011
257Binary Tree PathsEasyDFS, Backtracking, Binary Tree
202Happy NumberEasyHash Set, Two PointersCoding Tips, reduce((a,b)=>a*a+b*b) is not the proper way to get sum of square
Besides using Set, another idea is to use fast/slow two pointer
203Remove Linked List ElementsEasyLinked List
205Isomorphic StringsEasyHash MapThe key for this question is to check mapper value either unique or not. If not false, otherwise true.
206Reversed Linked ListEasyLinked List, Recursion
217Contains DuplicateEasyHash Set
219Contains Duplicate 2EasyHash Map– Store higher index in Hash Map
225Implement Stack using QueuesEasyQueue, Stack1 idea is using a nested queue
Another idea is to use two queue
226Invert Binary TreeEasyTree, DFS, BFS
228Summary RangesEasyArray
231Power of TwoEasyBit ManipulationMy own 1 line solution
return 2**(n.toString(2).length-1) === n
Better one from discussion
n > 0 ? !(n & n-1) : false;
232Implement Queue using StacksEasyQueue, Stack
234Palindrome Linked ListEasyLinked ListOne easy solution is to convert to array and check it. O(n), O(n)
The other solution is to
1. detect middle of array
2. reverse the second part of array
3. check the first part and second part of array
235Lowest Common Ancestor of a Binary Search TreeEasyBSTMy own solution is through Recursion
There is a simple iteration solution. (In Python)
while (root.val - p.val) * (root.val - q.val) > 0:
root = (root.left, root.right)
[p.val > root.val] return root
389Find DifferenceEasyString, Hash MapSolution 1, using a Hash Map to store character frequency, O(n) O(n)
Solution 2, using string replace O(n) O(n)
for (let letter of s) t = t.replace(letter, ''); return t;
Solution 3, using char operation, O(n) O(1)
for (let i = 0; i < t.length; i++) {
if(s[i]) charCode -= s[i].charCodeAt();
charCode += t[i].charCodeAt() };
return String.fromCharCode(charCode);
237Delete Node In A Linked ListEasyLinked List
238Product of Array Except SelfMediumArray– for no divide, use left and right two multiplier , this solution is quite tricky, the actual space complexity is O(n)
242Valid AnagramEasyString, Hash Map
LeetCode 250

Leave a Reply

Pages: 1 2 3 4