
Recent Posts
Recent Comments
Archives
Categories
Meta
Tag Archives: algorithms
Binary Search
Whenever I revisit binary search problems, I keep having to work out the edge cases whenever coming up with the algorithm. So I thought I’d make a note of the pseudo code template I always end up with: l=0, r=0 … Continue reading
Leetcode 45: Jump Game II
Only a linear solution will pass the leetcode tests. Use a three counters as we iterate: jumps, current steps left, next steps left. We only use next jump when we run out of current steps left. Continually update next steps … Continue reading
Leetcode 30: Substring with Concatenation of All Words
Put words into hash map, step through each char in s checking for words in the hashmap. If we find a word then step through to the character after that match and attempt to match remaining words with the hash … Continue reading
Leetcode 23: Merge k Sorted Lists
There are a few different ways to solve this. I found the easiest way was to do a merge k1 times. So you merge the first two lists. Then you merge that merged list with list 3. And repeat that … Continue reading
Leetcode 10: Regular Expression Matching
The Kleene stars (the * wildcard character for regular expressions) make this difficult. We can’t just gobble up all the wildcard matching characters, otherwise subsequent matches might not work. One way to solve this is by recursing every possibility, so … Continue reading
Leetcode 4: Median of Two Sorted Arrays
Let’s call our two arrays A and B, where they have sizes a and b. A key insight is that we need to partition both arrays such that the left of both will be the same size as the right … Continue reading
Trie Data Structure (Prefix Tree)
Use a TrieNode class that has a next member which is an array of 26 TrieNode pointers that represents a pointer to TreeNode object for each of 26 letters in the alphabet. We initialise these TrieNode pointers to NULL. We … Continue reading
Leetcode 188: Best Time to Buy and Sell Stock IV
To solve this we can use Dynamic Programming to gradually build upon previous solutions for t1 transactions. The simplest to understand solution uses O(n²k) time and O(nk) space. We can optimise the time to O(nk) and space to O(n). The … Continue reading
Leetcode 185: Department Top Three Salaries
Join Employee and Department tables by DepartmentId. In WHERE clause we need to filter to show only salaries higher than a subquery result. In that subquery we will try to return the third highest distinct salary. Do that subquery by … Continue reading
Leetcode 174: Dungeon Game
My first attempt, where I tried top down DP, didn’t work. My second attempt used bottom up DP where I start from the last cell (bottom right) and work my way through to the first cell (top left). So at … Continue reading