Posts

Showing posts from June, 2023

Saturday Night Dijkstra's Algorithm II

Image
Another problem that requires use of Dijkstra's Algorithm for efficiency's purposes. Basically we have a directed weighted graph, and want to find the min distance between a certain node and any marked node. Approach goes as follows: 1/ Build a quick-access graph using a hashtable. Remember that you can have multiple edges [u,v,w] where u and v are the same. Handle that in the creation method 2/ Make a quick-access look-up table for the marked nodes 3/ Use a ascending priority queue to speed up the BFS algorithm 4/ As you do the BFS, unfortunately there is no easy way to stop it since you may always find a min route. Instead, rely on the pruning to not add to the queue any path larger than the min so far 5/ Handle some edge cases here and there, such as no-path found Code is down below, cheers, ACC Find the Closest Marked Node - LeetCode 2737. Find the Closest Marked Node Medium 10 0 Add to List Share You are given a positive integer  n  which is the number of nodes of a  0-ind

StringBuilder

Image
The beauty of StringBuilder is just the ability of performing character-level operations in-situ without the need to concatenate strings which is expensive and in some cases can lead to TLE. This example, although simple, requires attention to corner-cases (like a string that starts with "a"s) as well as the use of StringBuilder for fast manipulation. Code is down below, cheers, ACC. Lexicographically Smallest String After Substring Operation - LeetCode 2734. Lexicographically Smallest String After Substring Operation Medium 83 106 Add to List Share You are given a string  s  consisting of only lowercase English letters. In one operation, you can do the following: Select any non-empty substring of  s , possibly the entire string, then replace each one of its characters with the previous character of the English alphabet. For example, 'b' is converted to 'a', and 'a' is converted to 'z'. Return  the  lexicographically smallest  string you can ob