Posts

Switching to Python

Image
Hello friends, next few problems will be solved in Python, just to diversify the languages a bit. Starting with basic problems to get a taste of the language:  https://leetcode.com/problems/matrix-diagonal-sum/ 1572. Matrix Diagonal Sum Easy 13 1 Add to List Share Given a square matrix  mat , return the sum of the matrix diagonals. Only include the sum of all the elements on the primary diagonal and all the elements on the secondary diagonal that are not part of the primary diagonal.   Example 1: Input: mat = [[ 1 ,2, 3 ],   [4, 5 ,6],   [ 7 ,8, 9 ]] Output: 25 Explanation: Diagonals sum: 1 + 5 + 9 + 3 + 7 = 25 Notice that element mat[1][1] = 5 is counted only once. Example 2: Input: mat = [[ 1 ,1,1, 1 ],   [1, 1 , 1 ,1],   [1, 1 , 1 ,1],   [ 1 ,1,1, 1 ]] Output: 8 Example 3: Input: mat = [[ 5 ]] Output: 5   Constraints: n == mat.length == mat[i].length 1 <= n...

700

Image
The 700th LC problem that I solved reminds me of the Collatz Conjecture . Here it is  https://leetcode.com/problems/integer-replacement/ 397. Integer Replacement Medium 375 326 Add to List Share Given a positive integer  n  and you can do operations as follow: If  n  is even, replace  n  with  n /2 . If  n  is odd, you can replace  n  with either  n  + 1  or  n  - 1 . What is the minimum number of replacements needed for  n  to become 1? Example 1: Input: 8 Output: 3 Explanation: 8 -> 4 -> 2 -> 1 Example 2: Input: 7 Output: 4 Explanation: 7 -> 8 -> 4 -> 2 -> 1 or 7 -> 6 -> 3 -> 2 -> 1 The idea is to implement the rules mentioned in the problem statement, but with the following observations and optimizations:  1) Use a static hash table to keep track of the results. That's your cache 2) Use long instead of int to avoid overflows 3) Last but n...

Longest Repeating Substring: Sliding Window + Induction

Image
It took me a long time to figure this one out... partially because the hints were a little misleading IMO. Here it is the problem:  https://leetcode.com/problems/longest-repeating-substring/ 1062. Longest Repeating Substring Medium 276 15 Add to List Share Given a string  S , find out the length of the longest repeating substring(s). Return  0  if no repeating substring exists.   Example 1: Input: "abcd" Output: 0 Explanation: There is no repeating substring. Example 2: Input: "abbaba" Output: 2 Explanation: The longest repeating substrings are "ab" and "ba", each of which occurs twice. Example 3: Input: "aabcaabdaab" Output: 3 Explanation: The longest repeating substring is "aab", which occurs 3 times. Example 4: Input: "aaaaa" Output: 4 Explanation: The longest repeating substring is "aaaa", which occurs twice.   Constraints: The string  S  consists of only lowercase English letters from  'a...

Friedman Numbers

Image
 I got the idea from this post from a Fermat's Library tweet: You can find more about Friedman numbers here:  https://en.wikipedia.org/wiki/Friedman_number . The "joke" in the tweet was that I had a proof about the fact that there are infinite such numbers - and the reality is that there are! But I don't really have the proof :) The code though to generate some Friedman numbers is below. I say some because I'm not taking into account parenthesis, so the set below is a subset of the Friedman numbers. It is computational intense since I need to create all the permutations of the number and then check all the possible variations with all the operators. but it finds nice ones, like this: 8^5+7*2+3 = 32785 Code is down below, cheers, ACC. *Notice that I'm using info.lundin.math library, you'll need to Nuget it first public bool IsFriedmanNumber(int number) { return IsFriedmanNumber(number.ToString(), "", new Hashtable()); } private bool IsFried...

Balancing parenthesis: use a counter, no need for a stack

Image
Problems related to balancing parenthesis usually require the use of a stack, except when the problem asks for just the counter (number of movements to balance it) or when the string consists of only one type of parenthesis, say the curly brackets. Here is an example:  https://leetcode.com/problems/minimum-insertions-to-balance-a-parentheses-string/ 1541. Minimum Insertions to Balance a Parentheses String Medium 31 8 Add to List Share Given a parentheses string  s  containing only the characters  '('  and  ')' . A parentheses string is  balanced  if: Any left parenthesis  '('  must have a corresponding two consecutive right parenthesis  '))' . Left parenthesis  '('  must go before the corresponding two consecutive right parenthesis  '))' . For example,  "())" ,  "())(())))"  and  "(())())))"  are balanced,  ")()" ,  "()))"  and  "(()))"  are not balanced...

Finding the Diameter of an N-Ary Tree: the "To-And-Thru" approach

Image
Hello folks, this is a problem that exemplifies a technique that I like to call the To-And-Thru. We want to find the diameter of an N-ary tree (meaning a tree where each node has 0, 1 or more children). Take a look:  https://leetcode.com/problems/diameter-of-n-ary-tree/ What you want is a near-linear solution in the number of nodes. If you assume that the tree has N nodes, and that each node has an average of LogN children, then the To-And-Thru algorithm below will run in O(N * (LogN)^2) time. Not really linear, but something that seems to be closer to NLogN. The idea is the following: Post-Order DFS For each node, compute the following: The longest path TO the node The longest path THRU the node The above computation will take LogN*LogN since there are two nested loops ( I guess there might be a way to reduce this to LogN, meaning one loop ) As you compute 2.1 and 2.2, your diameter will be the Max See figure below. Works well enough. Code is down below, stay safe, stay motivated!...

Classic Dijkstra

Image
Dijkstra invented one of the most classic algorithms to find the min/max path in a graph - we call it today simply  Dijkstra's Algorithm . This problem requires a classic use of Dijkstra's Algorithm:  https://leetcode.com/problems/path-with-maximum-probability/ 1514. Path with Maximum Probability Medium 194 4 Add to List Share You are given an undirected weighted graph of  n  nodes (0-indexed), represented by an edge list where  edges[i] = [a, b]  is an undirected edge connecting the nodes  a  and  b  with a probability of success of traversing that edge  succProb[i] . Given two nodes  start  and  end , find the path with the maximum probability of success to go from  start  to  end  and return its success probability. If there is no path from  start  to  end ,  return 0 . Your answer will be accepted if it differs from the correct answer by at most  1e-5 .  ...