<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Zhen Yang on Medium]]></title>
        <description><![CDATA[Stories by Zhen Yang on Medium]]></description>
        <link>https://medium.com/@zzhenyyang?source=rss-d8396be88a61------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*G56Oo0HtmiVErb76gNGxnA.jpeg</url>
            <title>Stories by Zhen Yang on Medium</title>
            <link>https://medium.com/@zzhenyyang?source=rss-d8396be88a61------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 02:03:21 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@zzhenyyang/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How to perform efficient caching]]></title>
            <link>https://medium.com/@zzhenyyang/how-to-perform-efficient-caching-6a7a7e51bfda?source=rss-d8396be88a61------2</link>
            <guid isPermaLink="false">https://medium.com/p/6a7a7e51bfda</guid>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[caching]]></category>
            <category><![CDATA[lru-cache]]></category>
            <dc:creator><![CDATA[Zhen Yang]]></dc:creator>
            <pubDate>Mon, 16 Jun 2025 10:35:07 GMT</pubDate>
            <atom:updated>2025-06-16T10:35:07.049Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5FiUhpuWis1GnMVD1A65FQ.png" /></figure><p>Caching is a common strategy used to solve many resource bottleneck issues; such as disk I/O, network I/O and CPU speed. To implement a production ready cache, it must satisfy a few criterias.</p><p>It must</p><ol><li>only cache used data</li><li>have a way to manage the growing number of records</li><li>be quick to access</li></ol><p>Many algorithms have come up to fulfill these requirements, each with its own strategy. One of the most prevelant strategies is the Least-Recently-Used (LRU) cache.</p><p>The idea is simple. Given a limited caching capacity, keep only the most recently used data, discarding the least used ones. The most optimal way to do this is with the help of the <strong>doubly linked list </strong>data structure.</p><p>Let’s explore the implementation of an LRU cache using LeetCode question 146.</p><h3>The Problem</h3><p>Design a data structure that follows the constraints of a <a href="https://en.wikipedia.org/wiki/Cache_replacement_policies#LRU"><strong>Least Recently Used (LRU) cache</strong></a>.</p><p>Implement the LRUCache class:</p><ul><li>LRUCache(int capacity) Initialize the LRU cache with <strong>positive</strong> size capacity.</li><li>int get(int key) Return the value of the key if the key exists, otherwise return -1.</li><li>void put(int key, int value) Update the value of the key if the key exists. Otherwise, add the key-value pair to the cache. If the number of keys exceeds the capacity from this operation, <strong>evict</strong> the least recently used key.</li></ul><p>The functions get and put must each run in O(1) average time complexity.</p><p><strong>Example 1:</strong></p><pre>Input<br>[&quot;LRUCache&quot;, &quot;put&quot;, &quot;put&quot;, &quot;get&quot;, &quot;put&quot;, &quot;get&quot;, &quot;put&quot;, &quot;get&quot;, &quot;get&quot;, &quot;get&quot;]<br>[[2], [1, 1], [2, 2], [1], [3, 3], [2], [4, 4], [1], [3], [4]]<br>Output<br>[null, null, null, 1, null, -1, null, -1, 3, 4]</pre><pre>Explanation<br>LRUCache lRUCache = new LRUCache(2);<br>lRUCache.put(1, 1); // cache is {1=1}<br>lRUCache.put(2, 2); // cache is {1=1, 2=2}<br>lRUCache.get(1);    // return 1<br>lRUCache.put(3, 3); // LRU key was 2, evicts key 2, cache is {1=1, 3=3}<br>lRUCache.get(2);    // returns -1 (not found)<br>lRUCache.put(4, 4); // LRU key was 1, evicts key 1, cache is {4=4, 3=3}<br>lRUCache.get(1);    // return -1 (not found)<br>lRUCache.get(3);    // return 3<br>lRUCache.get(4);    // return 4</pre><h3>Approach</h3><p>We will be using a map and a doubly linked list in tandem to perform efficient look ups while satisfying the requirements of a LRU cache.</p><p>We map each key to a node containing its value while constructing a doubly linked list, manipulating it to keep only recently used data.</p><p>The most recently used data will be at the head of the linked list, while the least recently used will be at the tail.</p><h3>Requirement Analysis</h3><h4>Insert new value</h4><p>This new value should be at the head of the linked list as it is the most recently used. But what if the capacity of the cache has been reached? We illustrate it below.</p><p>First the tail has to go.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eF5_-ghol2PBRLgishXclQ.png" /></figure><p>Next, we add the new value at the head of the list.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NG2Hyu-H76NgW8SuuOOrxA.png" /></figure><h4>Update existing key</h4><p>If a key already exists, we want to update its value. But since this is being used, we should make this the most recently used by moving the node to the head.</p><p>Then simply update the value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gQXEw4eRVGwZwC2JYbE9ug.png" /></figure><h4>Get value by key</h4><p>To get a key, simply look up the map, then move that node to the head.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BdzFn7CeD6sLMTCG6uer9g.png" /></figure><h3>Solution design</h3><p>If you’ve noticed, each of these requirements have repeated actions. So let’s create functions for these. The first would be detaching a node.</p><p>To make things easier for us, by default, our doubly linked list will contain at least two nodes, head and tail. Head in green and tail in blue. Let’s look at the head node. We update it’s “next node” by changing which node its pointing to, and this node is the “next node” of the node we want to detach, which happens to be the tail.</p><p>Similarly, we update the “previous node” on the detach node’s “next node”, which happens to be the tail. We update its “previous node” to point to the detach node’s “previous node”, which happens to be the head.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yxp3eyAyqK8BorF6OQzoQA.png" /></figure><p>Next we can remove the previous and next pointers of the node we want to detach.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WVhAcmYg42gs919lLzxjhw.png" /></figure><p>Now for the next function; move next to head. Given a node, set its next node to the next node of the head. And for this next node of the head to set its previous node to the new node.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gZJKPOEDZDEZQbmyuXZaFA.png" /></figure><p>Then we set the head to point to the new node, and the new node can set its previous node to point to the head.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B_Zv1j4jHS-rA18q2npjtA.png" /></figure><p>By putting these together, we can maintain the order of the doubly linked list, and fulfil the LRU requirements.</p><p>You might be wondering, when running a Get on the cache, how do we move the recently used node to the head? We first detach the node from the list, then use the move to head function!</p><h3><strong>Code implementation</strong></h3><pre>package main<br><br>import &quot;fmt&quot;<br><br>type Node struct {<br>    Prev *Node<br>    Next *Node<br>    Val  int<br>    Key  int<br>}<br><br>type LRUCache struct {<br>    head     *Node<br>    tail     *Node<br>    store    map[int]*Node<br>    capacity int<br>}<br><br>func Constructor(capacity int) LRUCache {<br>    head := &amp;Node{Val: -1}<br>    tail := &amp;Node{Val: -1}<br><br>    head.Next = tail<br>    head.Prev = nil<br><br>    tail.Next = nil<br>    tail.Prev = head<br><br>    return LRUCache{<br>        head:     head,<br>        tail:     tail,<br>        capacity: capacity,<br>        store:    make(map[int]*Node, capacity),<br>    }<br>}<br><br>func (this *LRUCache) Get(key int) int {<br>    if node, ok := this.store[key]; ok {<br>        this.detachNode(node)<br>        this.moveNextToHead(node)<br>        return node.Val<br>    }<br>    return -1<br>}<br><br>func (this *LRUCache) Put(key int, value int) {<br>    if node, ok := this.store[key]; ok {<br>        node.Val = value<br>        this.detachNode(node)<br>        this.moveNextToHead(node)<br>        return<br>    }<br>    if len(this.store) == this.capacity {<br>        delete(this.store, this.tail.Prev.Key)<br>        this.detachNode(this.tail.Prev)<br>    }<br>    newNode := &amp;Node{Val: value, Key: key}<br>    this.moveNextToHead(newNode)<br>    this.store[key] = newNode<br>}<br><br>func (this *LRUCache) moveNextToHead(node *Node) {<br>    this.head.Next.Prev = node<br>    node.Prev = this.head<br>    node.Next = this.head.Next<br>    this.head.Next = node<br>}<br><br>func (this *LRUCache) detachNode(node *Node) {<br>    node.Prev.Next = node.Next<br>    node.Next.Prev = node.Prev<br>    node.Prev = nil<br>    node.Next = nil<br>}<br><br>/**<br> * Your LRUCache object will be instantiated and called as such:<br> * obj := Constructor(capacity);<br> * param_1 := obj.Get(key);<br> * obj.Put(key,value);<br> */</pre><p>This solution got me a 79ms runtime which beats 77.92% of submissions.</p><p>Thank you for reading my article 🙏. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6a7a7e51bfda" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to write concurrent code in Go]]></title>
            <link>https://medium.com/@zzhenyyang/concurrency-in-go-653018c06c05?source=rss-d8396be88a61------2</link>
            <guid isPermaLink="false">https://medium.com/p/653018c06c05</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[scalability]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Zhen Yang]]></dc:creator>
            <pubDate>Sat, 26 Apr 2025 13:58:59 GMT</pubDate>
            <atom:updated>2025-05-26T13:08:28.906Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yaTIPlwmuPxfenHL7hS1hQ.png" /></figure><h3>Challenges faced with concurrency</h3><h4>Race conditions</h4><p>Occurs when two or more operations must be executed in the correct order but the program has not been written so that this order is guaranteed.</p><p>A data race is the most common type of race condition that describes a scenario when more than one operation tries to access or write to the same storage at the same time. Typically a mutex is used to ensure only one concurrent process has access to it at any one point.</p><h4>Deadlocks</h4><p>Occurs when two or more concurrent operations hold onto the resources required by the other concurrent operation, causing an infinite wait of releasing resources.</p><p>Below, we start goroutine 1 and 2 at about the same time. However, 1 locks “a” first while 2 locks “b” first. Then, 1 is instructed to lock “b”, while 2 is instructed to lock “a”. Since “a” and “b” are still locked by the other goroutine, this program blocks forever, waiting for a lock to be released.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*TwHLGzXlZ6k1oFgWRk2DQQ.png" /></figure><h4>Livelocks</h4><p>Occurs when two or more concurrent operations are executing, but blocking the progress of each other, causing no work to be done.</p><p>Below shows the same locking problem as above, except the goroutines have been instructed to unlock their resources at the same time and try again.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CBKvXMdIFLnwkIPSQoMUxg.png" /></figure><h3>Starvation</h3><p>Typically refers to a greedy and polite relationship of concurrent operations. The greedy operation hogs onto the shared resource for the entirety of its operation, while a polite operation only holds onto the shared resource when necessary, frequently releasing it for other operations to use.</p><pre>var wg sync.WaitGroup<br>var sharedLock sync.Mutex<br>const runtime = 1 * time.Second<br><br>greedyWorker := func() {<br> defer wg.Done()<br> var count int<br> for begin := time.Now(); time.Since(begin) &lt;= runtime; {<br>  sharedLock.Lock()<br>  time.Sleep(3 * time.Nanosecond)<br>  sharedLock.Unlock()<br>  count++<br> }<br> fmt.Printf(&quot;Greedy worker was able to execute %v work loops\n&quot;, count)<br>}<br><br>politeWorker := func() {<br> defer wg.Done()<br> var count int<br> for begin := time.Now(); time.Since(begin) &lt;= runtime; {<br>  sharedLock.Lock()<br>  time.Sleep(1 * time.Nanosecond)<br>  sharedLock.Unlock()<br>  sharedLock.Lock()<br>  time.Sleep(1 * time.Nanosecond)<br>  sharedLock.Unlock()<br>  sharedLock.Lock()<br>  time.Sleep(1 * time.Nanosecond)<br>  sharedLock.Unlock()<br>  count++<br> }<br> fmt.Printf(&quot;Polite worker was able to execute %v work loops\n&quot;, count)<br>}</pre><h3>The sync package</h3><h4>Waitgroup</h4><p>Can be understood as a counter to keep track of goroutines. Add 1 to the counter right before creating a goroutine, then decrement 1 from the counter right before the goroutine completes its task.</p><h4>Mutex</h4><p>Synchronizes shared memory by blocking access to it when at least one goroutine has requested for exclusive access to it. By default a mutex blockes both read and write access to the locked shared memory.</p><p>For uses where reads are much more frequent than writes, performance can be improved significantly if a RWmutex is used. A RWMutex allows for an undetermined number of read access, but only one access to write access at a time.</p><h4>Cond</h4><p>Cond, short for condition, synchronizes two or more goroutines, where one is sending signals and the other is waiting on said signals. Lets look at an example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OdnZueZnSBsB_PvBlzjF2g.png" /></figure><p>A signal is sent when an object exits the queue, notifying the input goroutine to push in the next object. This maintains the queue size.</p><p>This signal feature can be trivially replicated with the use of channels. Cond shines with its other method called Broadcast, which is just like sending a signal but to multiple goroutines at the same time.</p><h4>Once</h4><p>sync.Once has a method Do that takes in a function and ensures that it will only run once in the entire application. No matter how many times the function is called, even by goroutines, it will only run once. It is typically used for configuration initializations; things that should only be done once in an application.</p><p>Since Go 1.21, there have been more methods similar to Once.</p><p>OnceFunc replaces the Do method by directly taking in a function.</p><p>OnceValue also takes in a function, and stores the result of the function to be returned for any new invocations of the function. Only one value can be stored.</p><p>OnceValues is like OnceValue but can store multiple return values from the passed in function. This solves many problems that come with error handling “Once” triggered functions</p><h4>Pool</h4><p>A pool is a way to create and make available things for use and reuse. This improves performance by reducing the need to repeatedly create and remove expensive things.</p><p>A pool has a Get method, which attempts to get a resource from a pool if it already exists, but would also create a new instance of the resource if it does not exist.</p><p>Pool takes in a New attribute, which is a function that instantiates a resource.</p><p>After calling Get, the caller also has to Put this resource back into the pool. This is commonly done with a defer statement.</p><p>There are two main reasons to use a pool.</p><ol><li>To reduce the amount of compute load and memory needed on the server with the constant creation of expensive resources. This is done by reusing resources as created resources are put into the pool.</li><li>To reduce the time taken for the server to respond to the client/caller. This is done by frontloading the creation of expensive resources and putting them into the pool before the resource is being requested for.</li></ol><h4>Channels</h4><p>It is like a stream to pass data between goroutines.</p><p>To effectively use channels, assign ownership to goroutines with regard to channels.</p><p>If a goroutine owns a channel, it has a type of chan or chan&lt;- which allows it to write to a channel. Owners should be given the following responsibilities:</p><ol><li>Instantiate the channel</li><li>Perform writes or pass ownership to another goroutine</li><li>Close the channel</li><li>Encapsulate the above three, only exposing a read only channel to it</li></ol><p>For a goroutine that consumes a channel, type &lt;-chan , it should:</p><ol><li>Know when a channel is closed</li><li>Handle blocking for any reason</li></ol><h4>Select statement</h4><p>It is used to manage channels.</p><p>If more than one case/channel is ready, only one of them is picked at random to be run.</p><p>Use time.After() for timeouts</p><p>When no channels are ready, a default statement can be provided to stop the select statement from blocking. A quick example below.</p><pre>stopChannel := make(chan any)<br>var counter int<br><br>loop:<br>for {<br>  select {<br>    case &lt;-stopChannel:<br>      loop<br>    default:	<br>  }<br>  // Code below still runs<br>  counter++<br>}</pre><h3>Concurrency patterns in Go</h3><h4>Confinement</h4><p>The idea is to expose only the correct data and concurrency primitives for multiple concurrent processes to use.</p><p>When creating a channel, we should encapsulate the instantiation of the channel, the writer to the channel and the responsiblity of closing the channel together, like in a function for example, and only expose a consumer to that channel. Many goroutines in this article are written to demonstrate this concept.</p><h4>For…select…</h4><p>Basic for-select pattern:</p><pre>for {<br>  select {<br>  case &lt;-channel:<br>    //Do work<br>  }<br>}</pre><p>To terminate a goroutine, conventionally, a “done” channel is used. Let’s confine the owner of the channel into its own function.</p><pre>func newChannel(done &lt;-chan any, channel &lt;-chan any) &lt;-chan any {<br>    terminated := make(chan any)<br>    go func() {<br>        defer close(terminated)<br><br>        for {<br>            select {<br>            case &lt;-channel:<br>                //Do work<br>            case &lt;-done:<br>                return<br>            }<br>        }<br>    }()<br><br>    return terminated<br>}<br><br>// Example usage (assuming &#39;channel&#39; is defined elsewhere)<br>// You would typically define &#39;channel&#39; before calling newChannel<br>// channel := make(chan any)<br><br>done := make(chan any)<br>go func(){<br>    time.Sleep(1*time.Second)<br>    close(done)<br>}()<br>terminated := newChannel(done, channel) // Note: &#39;channel&#39; must be defined before this line<br>&lt;-terminated</pre><p>How about terminating a goroutine that blocks on write</p><pre>func newRandStream(done &lt;-chan any) &lt;-chan int {<br>  randStream := make(chan int)<br>  go func(){<br>    defer close(randStream)<br>    for {<br>      select {<br>        case randStream &lt;- rand.Int():<br>        case &lt;-done:<br>          return<br>      }<br>    }<br>  }()<br><br>  return randStream<br>}<br><br>// Usage<br>done := make(chan any)<br>randStream := newRandStream(done)<br>for range 3 {<br> &lt;-randStream<br>}<br>close(done)</pre><h4>Or-channel</h4><p>An or-channel is a channel that relates to the logical OR operator; because this channel closes when at least one channel under it closes. An or-channel is used to combine one or more channels to a single channel that closes if any of its component channels close.</p><p>A function is used to create an or-channel. It takes in a variadic parameter of channels that you want to be componenets of this or-channel, and of course returns a new channel. For this function to work, it aptly uses recursion.</p><p>In this example we have 4 channels to be components of an or-channel. To begin, we create a “done” channel, which receives from the first two channels. This leaves the next two channels and our new channel.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x9jW_Zzl8eFgfQ0TgbU0Dw.png" /></figure><p>From 4 channels, we are down to 3. From these 3 channels, again, we take the first two channels and create a new channel that receives from those two channels.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fAE2F4Rkv6nWdzCHhJfC6A.png" /></figure><p>Now we are down to 2 channels. The cycle repeats, we create a new channel which receives from the remaining two channels.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Nk4G-YNgKgAmBXztiM6NKQ.png" /></figure><p>This leaves us with just one channel, which we can just return as our complete or-channel. We can see that this channel is connected to all 4 channels, and will close if any one of them decides to close.</p><h4>Error handling</h4><p>Go’s design of explicit error handling should be applied to concurrent programming as well. Errors are passed up from component goroutines, to the parent goroutine that created them, as their parents have more context of the whole application, and therefore how to handle them.</p><pre>type Result struct {<br>  Error error<br>  Response *http.Response<br>}<br><br>func checkStatus(done &lt;-chan interface{}, urls ...string) &lt;-chan Result {<br>  results := make(chan Result)<br><br>  go func() {<br>    defer close(results)<br>    for _, url := range urls {<br>      var result Result<br>      resp, err := http.Get(url)<br>      result = Result{Error: err, Response: resp}<br><br>      select {<br>        case &lt;-done:<br>          return<br>        case results &lt;- result:<br>      }<br>    }<br>  }()<br><br>  return results<br>}<br><br>done := make(chan interface{})<br>defer close(done)<br><br>urls := []string{&quot;https://www.google.com&quot;, &quot;https://badhost&quot;}<br>for result := range checkStatus(done, urls...) {<br>  if result.Error != nil {<br>    fmt.Printf(&quot;error: %v&quot;, result.Error)<br>    continue<br>  }<br><br>  fmt.Printf(&quot;Response: %v\n&quot;, result.Response.Status)<br>}</pre><p>Finally when we are outside of the child goroutine (in checkStatus), the error can be better handled in the main goroutine (parent goroutine). For example, we can choose to terminate the loop for checkStatus after 3 errors have been recorded.</p><h4>Pipelines</h4><p>A function that takes in an object, performs an operation on it, and returns an object of the same type.</p><p>This pattern allows us to chain functions like so:</p><pre>ints := []int{1, 2, 3, 4}<br>for _, v := range add(multiply(ints, 2), 1) {<br>  fmt.Println(v)<br>}</pre><p>The above pipeline takes in and returns a slice of objects. This is known as <strong>batch processing</strong>. The pipeline works on a batch of data. Pipelines that work on one object at a time perform <strong>stream processing</strong> like so…</p><pre>ints := []int{1, 2, 3, 4}<br>for _, i := range ints {<br>  fmt.Println(add(multiply(i, 2), 1)<br>}</pre><p><strong>Batch Processing</strong></p><p>Higher memory footprint, potentially double the size of the input slice at any given time.</p><p><strong>Stream Processing</strong></p><p>Lower memory footprint, down to the size of the pipeline’s input.</p><p><strong>However</strong> there are some problems with this implementation of stream processing</p><ul><li>Limited reuse of how the pipeline is fed, as it’s tied to the for...range loop.</li><li>The pipeline in the example is directly processing elements from the ints slice. If you wanted to apply the same multiply(add(multiply(v, 2), 1), 2) logic to data coming from a different source, such as reading numbers from a file, receiving from a channel, or generating numbers on the fly, you would have to rewrite the for loop structure to accommodate the new data source. The pipeline logic is embedded/coupled within the loop that&#39;s specific to iterating over a slice.</li><li>Limited ability to scale (concurrency is not readily apparent).</li><li>Ineffective instantiation of the pipeline for every iteration of the loop (multiple function calls per item).</li></ul><p>So what is the solution to these problems?</p><p><strong>Use channels</strong></p><pre>generator := func(done &lt;-chan interface{}, integers ...int) &lt;-chan int</pre><p>We can use a generator function to convert discrete values into a channel.</p><p>As all of our pipelines follow this pattern, the channel returned from generator can be passed down to the next operation pipelines.</p><p>The done channel at the front of each pipeline function can be used to terminate the whole pipeline at any point in time.</p><h4>Fan-Out, Fan-In</h4><p>Within a pipeline, there can be some stages that are much more computationally expensive than others, forcing upstream stages to wait for this slower component, resulting in longer execution times.</p><p>To speed things up, it is possible to concurrently run these expensive stages. There are just 2 conditions:</p><ol><li>It does not rely on values that the stage had calculated before</li><li>It takes a long time to run</li></ol><h4>Fan-out example</h4><pre>primeStream := primeFinder(done, randIntStream)<br>numFinders := runtime.NumCPU()<br><br>finders := make([]&lt;-chan int, numFinders)<br><br>for i := 0; i &lt; numFinders; i++ {<br> finders[i] = primeFinder(done, randIntStream)<br>}</pre><p>Now we have a slice of channels, but our next step of the pipeline expects just one channel. We have to <strong>fan-in</strong> the contents from all these channels into one channel. The algorithm below does that.</p><h4>Fan-in function</h4><pre>func fanIn(done &lt;-chan any, channels ...&lt;-chan any) &lt;-chan any {<br> multiplexedStream := make(chan any)<br> var wg sync.WaitGroup{}<br><br> func multiplexer(channel &lt;-chan any) {<br>  defer wg.Done()<br>  for val := range channel {<br>   select {<br>    case &lt;-done:<br>     return<br>    case multiplexedStream &lt;- val:<br>   }<br>  }<br> }<br> <br> wg.Add(len(channels))<br> for _, channel := range channels {<br>  go multiplexer(channel)<br> }<br> <br> go func(){<br>  wg.Wait()<br>  close(multiplexedStream)<br> }()<br> <br> return multiplexedStream<br>}</pre><h3>Or-done-channel</h3><p>Let’s look at an example.</p><pre>for val := range channel {<br>  fmt.Println(val)<br>}</pre><p>val will continue to be printed in the terminal as long as channel remains open.</p><p>Now, channel is from an object outside of your scope. This object is continuously writing to channel and therefore never closes. An example would be a monitoring system.</p><p>However, we do not want to stay stuck in this continuous loop of printing val . We want the loop to terminate when we close a done channel, just like we have been doing.</p><p>What does this code look like?</p><pre>loop:<br>  for {<br>    select {<br>    case &lt;-done:<br>      break loop<br>    case val, ok := &lt;-channel:<br>      if !ok {<br>        break loop<br>      }<br>      fmt.Println(val)<br>    }<br>  }</pre><p>By introducing a done channel, our code for receiving from channel decreased in readability significantly. So instead of constantly repeating this monstrousity, we can abstract this logic away into a function that creates <strong>or-done-channels</strong>.</p><p><strong>Or-done-channels</strong> are channels that you can continuously receive from until they are closed <strong>or have been signaled to be done</strong>.</p><pre>func orDone(done, c &lt;-chan any) &lt;-chan any {<br>  valStream := make(chan any)<br>  go func() {<br>    defer close(valStream)<br>    for {<br>      select {<br>      case &lt;-done:<br>        return<br>      case v, ok := &lt;-c:<br>        if !ok {<br>          return<br>        }<br>        select {<br>        case valStream &lt;- v:<br>        case &lt;-done:<br>          return<br>        }<br>      }<br>    }<br>  }()<br>  return valStream<br>}</pre><p>The nested select clause is used to ensure that valStream &lt;- v can be terminated. If valStream &lt;- v gets blocked because valStream is not ready, closing done can still be received. If we did no have case &lt;-done: , the function will stay blocked even after closing done.</p><h3>The tee-channel</h3><p>Getting its name from the Unix-like operating system command “tee”, the tee-channel takes in an input channel, and creates two output channels, each containing identical contents from the input channel.</p><p>When we receive from a channel, the value is removed from that channel. In order to write the same value to two channels, we need to make a copy of it like so.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/905/1*C_Y6wdnCcvQoYsVYVOPkfQ.png" /></figure><pre>func teeChan(done, in &lt;-chan any) (out1, out2 &lt;-chan any) {<br>    out1 = make(chan any)<br>    out2 = make(chan any)<br><br>    go func(){<br>        defer close(out1)<br>        defer close(out2)<br>        for val := range in {<br>            out1 &lt;- val<br>            out2 &lt;- val<br>        }<br>    }()<br><br>    return out1, out2<br>}</pre><p>What if out1 does not have a ready receiver? It will block us from sending val to out2 as well. Let’s fix this with the use of select.</p><pre>func teeChan(done, in &lt;-chan any) (out1, out2 &lt;-chan any) {<br>  out1 := make(chan any)<br>  out2 := make(chan any)<br>	<br>  go func(){<br>    defer close(out1)<br>    defer close(out2)<br>    for val := range in {<br>      for range 2 {<br>	select {<br>	case out1 &lt;- val:<br>	case out2 &lt;- val:<br>	}<br>      }<br>    }<br>  }()<br>	<br>  return out1, out2<br>}</pre><p>We use a for loop to loop over the select clause that writes to our output channels twice, as a select clause will only pick one case to execute at a time.</p><p>But now we have a problem. The select statement might run case out1 &lt;- val both iterations!</p><p>To solve this, we can make the output channel that got written to, block for the next second iteration. We achieve this by setting the channel to nil.</p><pre>func teeChan(done, in &lt;-chan any) (out1, out2 &lt;-chan any) {<br>  out1 := make(chan any)<br>  out2 := make(chan any)<br> <br>  go func(){<br>    defer close(out1)<br>    defer close(out2)<br>    for val := range in {<br>      var out1, out2 = out1, out2<br>      for range 2 {<br>        select {<br>        case out1 &lt;- val:<br>          out1 = nil<br>        case out2 &lt;- val:<br>          out2 = nil<br>        }<br>      }<br>    }<br>  }()<br> <br>  return out1, out2<br>}</pre><p>The line var out1, out2 = out1, out2 is needed to make a local copy of the pointer to our out channels. After a send is made to one of the out channels, we can set this pointer copy to nil, blocking future writes/sends. This keeps the original channel unaffected.</p><p>But of course let’s not forget about our done channel.</p><pre>func teeChan(done, in &lt;-chan any) (out1, out2 &lt;-chan any) {<br> out1 := make(chan any)<br> out2 := make(chan any)<br> <br> go func(){<br>  defer close(out1)<br>  defer close(out2)<br>  for val := range orDone(done, in) {<br>   var out1, out2 = out1, out2<br>   for range 2 {<br>    select {<br>     case &lt;-done:<br>     case out1 &lt;- val:<br>      out1 = nil<br>     case out2 &lt;- val:<br>      out2 = nil<br>    }<br>   }<br>  }<br> }()<br> <br> return out1, out2<br>}</pre><h3>The bridge-channel</h3><p>If you ever need to receive from a channel of channels, and you do not care about which values came from which channel, it is useful to send these values into a regular channel, to make it easier to receive from.</p><p>The following code does that for you:</p><ol><li>Iterate through the channel of channels chanStream , receiving the nested channel</li><li>Using the orDone function, receive from the nested channel stream</li><li>Write the received value into the new valStream created</li></ol><pre>func bridge(<br>  done &lt;-chan any,<br>  chanStream &lt;-chan &lt;-chan any,<br>) &lt;-chan any {<br>  valStream := make(chan any)<br>  go func() {<br>    defer close(valStream)<br>    for {<br>      var stream &lt;-chan any<br>      select {<br>      case maybeStream, ok := &lt;-chanStream:<br>        if ok == false {<br>          return<br>        }<br>        stream = maybeStream<br>      case &lt;-done:<br>        return<br>      }<br>      for val := range orDone(done, stream) {<br>        select {<br>        case valStream &lt;- val:<br>        case &lt;-done:<br>        }<br>      }<br>    }<br>  }()<br>  return valStream<br>}</pre><h3>Queueing</h3><p>Using a queue for optimization is usually one of the last techniques you need to try. Because it can prematurely hide synchronization issues such as deadlocks.</p><p>A queue often does not reduce the overall time taken for a process to run, but cuts down the amount of time a process/stage is blocking. Queues decouple stages so the runtime of one does not impact the other.</p><p>However there are 2 main cases where queues can improve the overall speed of a system:</p><ol><li>When batch requests save more time; e.g. writing to a file (disk write)</li><li>When the slow processing of a pipeline causes a negative feedback loop</li></ol><blockquote>In some systems, if a process is taking longer than expected, more jobs will get pushed into that process (negative feedback loop) because input is faster than output. This can build up, causing compute resources to be used up, bringing the whole process down.</blockquote><h4>How to determine size of queue</h4><p>Little’s law states that =λW.</p><p>L: average number of units in a system</p><p>λ: average rate of units entering a system</p><p>W: average amount of time a unit remains in a system (processing time)</p><p><em>This law only applies to systems where rate of input is equal to the rate of output.</em></p><p>With sampling, I found that my pipeline has an average amount of time a unit remains in the pipeline to be 2 miliseconds. Say I want to handle 100,000 requests per second, what is the expected number of units in my pipeline at any one point in time?</p><p>L = 100,000 * 2ms = 200 units/s</p><p>Given that my pipeline has 3 stages, each being concurrent, I need a queue size of 200–3 = 197.</p><p>A queue does not make the pipeline faster in this case, but allows users to send their requests to the pipeline early, preventing their requests from being rejected, at the cost of a perceived longer processing time.</p><h3>Context package</h3><p>The context package is intended as a way to provide an API for cancelling branches of goroutines and a datastore for request specific data to be easily passed down to children processes.</p><p>To create a new context, use the context.Background() method</p><p>While in development, and you are developing a process, you might not know what context to use, or the context has not been developed yet. In this case you can use context.TODO() which easily indicates work needing to be done.</p><h4>Cancelling goroutines</h4><p>Just like how we have been passing in a &lt;-done channel as the first parameter of our concurrent functions, we can replace them with a ctx context.Context now. Context makes it even easier to preempt our processes to stop by removing much repeated code.</p><h4>Datastore</h4><p>Context has a WithValue() method. To store values in context:</p><pre>ctx := context.WithValue(context.Background(), &quot;userId&quot;, 1)</pre><p>Where “userId” is the key, and 1 is the value. To get this value, we must use the same context in which the value was stored.</p><pre>ctx.Value(ctx, &quot;userId&quot;) // returns 1</pre><p>There is a problem. What if another function receives this same context, and also sets a value with the same key “userId”? This would cause the original value to be replaced!</p><p>To stop this, we should create a type for our package’s context keys.</p><pre>type ctxKey int<br>const (<br>  ctxUserId ctxKey = iota <br>)<br><br>ctx := context.WithValue(context.Background(), ctxUserId, 1)<br>ctx.Value(ctx, ctxUserId) // returns 1</pre><p>This works because ctxKey is a type unique to our package. Even though ctxUserId has an underlying value of 0, it is treated as a unique key, different from other context keys.</p><p>The line below does not return 1 of type int, but type any.</p><pre>ctx.Value(ctx, ctxUserId) // returns 1</pre><p>So its important to assert its type based on what you expect. Typically helper functions like the following are written.</p><pre>func UserID(c context.Context) int {<br>  return c.Value(ctxUserID).(int)<br>}</pre><h3>Concurrency at scale</h3><h3>Timeouts and cancellation</h3><p>If you have a process with a long queue, data passed into the queue to be processed may already be outdated by the time it actually reaches the process. This is called stale data.</p><p>For instance, you have a login system that requires a One-Time-Password (OTP). You send the user their OTP and they key it into the system. Upon receiving this request, you add the OTP to a queue to be passed into an authentication process. Say this OTP is valid for 10 seconds, but your auth process is congested with a long queue taking 12 seconds to complete processing, this user’s OTP will already be invalid.</p><p>If more users continue to make a login request, you can see how every person is going to fail at authenticating, as the queue never gets shorter.</p><p>Which is why, right at the start of the process, we should verify if the data passed in is still valid.</p><pre>func authenticateUser(ctx context.Context, otpQueue &lt;-chan string) bool {<br>  select {<br>  case enteredOTP := &lt;-otpQueue:<br>    select {<br>    case expectedOTP := &lt;-getExpectedOTP(ctx.Value(&quot;number&quot;)): // long process<br>      if enteredOTP == expectedOTP {<br>        return true<br>      } else {<br>        return false<br>      }<br>    case &lt;-ctx.Done(): // runs if context is cancelled (due to timeout or other reasons)<br>      return false // Authentication failed due to cancellation<br>    }<br>  case &lt;-ctx.Done():<br>    return false<br>  }<br>}</pre><h4>Usage</h4><pre>ctx, cancel := context.WithTimeout(context.Background(), otpValidity)<br>ctx = context.WithValue(ctx, &quot;number&quot;, phoneNumber)<br>defer cancel()<br><br>isAuthenticated := authenticateUser(ctx, otpQueue)</pre><p>Another common use case of timeouts is on everything. To prevent deadlocks in a program, we can use a safegaurd on typically long running processes. An example would be a write to a database. In the golang sql package, it has a QueryContext() method that takes in a context, and the query you want to execute on the database. The context it takes in is typically created with context.WithTimeout() to ensure writes to do not take too long, as it would indicate a potential deadlock. We do not want our users to have to wait forever for a database write.</p><h3>Writing preemptable code</h3><p>Look at this code.</p><pre>reallyLongCalculation := func(<br>  done &lt;-chan any,<br>  value any,<br>) any {<br>  result := make(chan any)<br>  go func() {<br>    defer close(result)<br>    select {<br>    case &lt;-done:<br>      return<br>    case &lt;-longRunningProcess():<br>      result &lt;- 10<br>    }<br>  }()<br><br>  select {<br>  case &lt;-done:<br>    return nil<br>  case res := &lt;-result:<br>    return res<br>  }<br>}</pre><p>We have ensured that this reallyLongCalculation function can be cancelled when the done channel is closed. When done is closed, this function returns and is stopped.</p><p>However, longRunningProcess() continues to run in the background!</p><p>An example of a longRunningProcess() would be a video file uploader. So how should a long running process be implemented?</p><pre>func simulateFileUpload(done &lt;-chan any, filename string) error {<br>  chunks := getFileChunks(filename)<br>  totalChunks := len(chunks)<br>  uploadedChunks := 0<br><br>  for _, chunk := range chunks {<br>    select {<br>    case &lt;-done: // runs when done is closed<br>      return nil<br>    default:<br>      if uploadedChunks &gt;= totalChunks {<br>        return nil<br>      }<br>      uploadChunk(chunk)<br>      uploadedChunks++<br>      fmt.Printf(&quot;Uploaded chunk %d of %s\\n&quot;, uploadedChunks, filename)<br>    }<br>  }<br>  return nil<br>}</pre><p>We have to split this long process into shorter processes so we can periodically check if the done channel has been closed, so that we can still respond to cancellation requests.</p><h3>Heartbeats</h3><p>A heartbeat is used to indicate a live goroutine. Some goroutines remain silent until work is given to them, so heartbeats are a way to tell if they are still alive.</p><p>To periodically send heartbeats, you can do the following.</p><pre>func doWork(<br>  done &lt;-chan interface{},<br>  pulseInterval time.Duration,<br>) (&lt;-chan interface{}, &lt;-chan time.Time) {<br>  heartbeat := make(chan interface{})<br>  results := make(chan time.Time)<br>  go func() {<br>    defer close(heartbeat)<br>    defer close(results)<br>    pulse := time.Tick(pulseInterval)<br>    workGen := time.Tick(2 * pulseInterval)<br><br>    sendPulse := func() {<br>      select {<br>      case heartbeat &lt;- struct{}{}:<br>      default:<br>      }<br>    }<br><br>    sendResult := func(r time.Time) {<br>      for {<br>        select {<br>        case &lt;-done:<br>          return<br>        case &lt;-pulse:<br>          sendPulse()<br>        case results &lt;- r:<br>          return<br>        }<br>      }<br>    }<br><br>    for {<br>      select {<br>      case &lt;-done:<br>        return<br>      case &lt;-pulse:<br>        sendPulse()<br>      case r := &lt;-workGen:<br>        sendResult(r)<br>      }<br>    }<br>  }()<br>  return heartbeat, results<br>}</pre><p>It is necessary to always check the done and pulse channels at each select clause that sends a result to results channel. Specifically, in the sendResult function, we cannot simply perform a send r into results because results channel may be blocking as there is no listener. But we still have to check the done and pulse channels.</p><p>To use a heartbeat, we can use time.After() to stop a process if we do not hear a heartbeat after the pulse interval, like so:</p><pre>const timeout = 2*time.Second<br>heartbeat, results := doWork(done, timeout/2)<br><br>for {<br> select {<br> case _, ok := &lt;-heartbeat:<br>  if !ok {<br>    return<br>  }<br>  fmt.Println(&quot;pulse&quot;)<br> case r, ok := &lt;-results:<br>  if !ok {<br>   return<br>  }<br>  fmt.Printf(&quot;results %v\n&quot;, r.Second())<br> case &lt;-time.After(timeout):<br>  return<br> }<br>}</pre><p>Heartbeats are very useful for testing concurrent code. By sending a heartbeat at the beginning of each unit of work, our tests know when to assert tests without the use of arbitrary timeouts. Let me explain.</p><pre>func TestDoWork_GeneratesAllNumbers(t *testing.T) {<br>  done := make(chan interface{})<br>  defer close(done)<br><br>  intSlice := []int{0, 1, 2, 3, 5}<br>  _, results := DoWork(done, intSlice...)<br>  for i, expected := range intSlice {<br>    select {<br>    case r := &lt;-results:<br>      if r != expected {<br>        t.Errorf(<br>          &quot;index %v: expected %v, but received %v,&quot;,<br>          i,<br>          expected,<br>          r,<br>        )<br>      }<br>    case &lt;-time.After(1 * time.Second):<br>      t.Fatal(&quot;test timed out&quot;)<br>    }<br>  }<br>}</pre><p>Our test above is non-deterministic. How can we gaurantee that DoWork will start sending numbers to results before 1 second is up? We can’t. This is solved with a heartbeat.</p><p>First let’s look inside DoWork.</p><pre>func DoWork(<br>  done &lt;-chan interface{},<br>  nums ...int,<br>) (&lt;-chan interface{}, &lt;-chan int) {<br>  heartbeat := make(chan interface{}, 1)<br>  intStream := make(chan int)<br>  go func() {<br>    defer close(heartbeat)<br>    defer close(intStream)<br>    time.Sleep(2 * time.Second) // simulate work delay<br><br>    for _, n := range nums {<br>      select {<br>      case heartbeat &lt;- struct{}{}:<br>      default:<br>      }<br><br>      select {<br>      case &lt;-done:<br>        return<br>      case intStream &lt;- n:<br>      }<br>    }<br>  }()<br>  return heartbeat, intStream<br>}</pre><p>We have to separate sending of a heartbeat into its own select clause because we do not want to skip n during the iterations in which a heartbeat is sent instead of sending on intStream</p><p>So for each iteration, a heartbeat will be sent.</p><p>Let’s update our test to make it deterministic.</p><pre>func TestDoWork_GeneratesAllNumbers(t *testing.T) {<br>  done := make(chan interface{})<br>  defer close(done)<br>  intSlice := []int{0, 1, 2, 3, 5}<br>  heartbeat, results := DoWork(done, intSlice...)<br><br>  &lt;-heartbeat<br><br>  i := 0<br>  for r := range results {<br>    if expected := intSlice[i]; r != expected {<br>      t.Errorf(&quot;index %v: expected %v, but received %v,&quot;, i, expected, r)<br>    }<br>    i++<br>  }<br>}</pre><p>This time, we only start asserting our test after receiving the first heartbeat. This indicates the goroutine is live and starting to do work. That way we can do away with the arbitrary time.After().</p><p>However the approach above runs the risk that after the first heartbeat, a deadlock may occur. For a more comprehensive test, we can regularly check heartbeat, keeping the time.After() from sending.</p><pre>func TestDoWork_GeneratesAllNumbers(t *testing.T) {<br> done := make(chan interface{})<br> defer close(done)<br> intSlice := []int{0, 1, 2, 3, 5}<br> heartbeat, results := DoWork(done, intSlice...)<br> <br> &lt;-heartbeat<br>  <br> i := 0<br> for {<br>  select {<br>  case r, ok := &lt;-results:<br>   if !ok {<br>    return<br>   }<br>   if expected := intSlice[i]; r != expected {<br>    t.Errorf(&quot;index %v: expected %v, but received %v,&quot;, i, expected, r)<br>   }<br>   i++<br>  case &lt;-heartbeat:<br>  case &lt;-time.After(timeout):<br>   t.Fatal(&quot;test timed out&quot;)<br>  }<br> }<br>}</pre><h3>Replicated Requests</h3><p>If you have a goroutine whose top priority is response speed, e.g. financial trading systems, you can write your code such that one such request would trigger multiple goroutines that try to achieve the same task. And when the first one completes this task, the rest are killed.</p><p>Let’s look at a simple example:</p><pre>done := make(chan interface{})<br>result := make(chan int)<br><br>var wg sync.WaitGroup<br>wg.Add(10)<br>for i:=0; i &lt; 10; i++ {<br>  go doWork(done, i, &amp;wg, result)<br>}<br>firstReturned := &lt;-result<br>close(done)<br>wg.Wait()<br><br>fmt.Printf(&quot;Received an answer from #%v\\n&quot;, firstReturned)</pre><p>The trade off of such a set up is the use of additional resources for each replicated request, as they are identical copies of each other. A decision has to be made between speed and resource allocated.</p><p>For goroutines that have a very low chance of having vastly different runtimes compared to its peers, it likely isn’t worth it.</p><h3>Healing Unhealthy Goroutines</h3><p>Long running goroutines that perform work in the background can break. When they happen, it is difficult to manage them without external help. To increase your program’s reliability, these goroutines can be automatically restarted to “resolve” its own issues.</p><p>This bad goroutine can be called a ward, and we have another goroutine to heal / restart it, called the steward.</p><p>This is what the steward can look like.</p><pre>type startGoroutineFn func(<br> done &lt;-chan interface{},<br> pulseInterval time.Duration,<br>) (heartbeat &lt;-chan interface{})<br><br>func newSteward(<br> timeout time.Duration,<br> startGoroutine startGoroutineFn,<br>) startGoroutineFn {<br> return func(<br>  done &lt;-chan interface{},<br>  pulseInterval time.Duration,<br> ) (&lt;-chan interface{}) {<br>  heartbeat := make(chan interface{})<br><br>  go func() {<br>   defer close(heartbeat)<br><br>   var wardDone chan interface{}<br>   var wardHeartbeat &lt;-chan interface{}<br><br>   startWard := func() {<br>    if wardDone != nil {<br>     close(wardDone)<br>    }<br>    wardDone = make(chan interface{})<br>    wardHeartbeat = startGoroutine(or(wardDone, done), timeout/2)<br>   }<br><br>   startWard()<br><br>   pulse := time.Tick(pulseInterval)<br><br>  monitorLoop:<br>   for {<br>    timeoutSignal := time.After(timeout)<br>    for {<br>     select {<br>     case &lt;-pulse:<br>      select {<br>      case heartbeat &lt;- struct{}{}:<br>      default:<br>      }<br><br>     case &lt;-wardHeartbeat:<br>      continue monitorLoop<br><br>     case &lt;-timeoutSignal:<br>      log.Println(&quot;steward: ward unhealthy; restarting&quot;)<br>      close(wardDone)<br>      startWard()<br>      continue monitorLoop<br><br>     case &lt;-done:<br>      log.Println(&quot;steward: received done signal. Stopping.&quot;)<br>      close(wardDone)<br>      return<br>     }<br>    }<br>   }<br>  }()<br><br>  return heartbeat<br> }<br>}</pre><h3>In summary,</h3><p>this article explored key concurrency patterns in Go, drawing upon the comprehensive insights provided by Katherine Cox-Buday in “Concurrency in Go: Tools and Techniques for Developers.” By understanding these patterns, developers can write more efficient, robust, and scalable concurrent programs. As Cox-Buday (2017) elucidates, mastering Go’s concurrency primitives is essential for building modern, high-performance applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=653018c06c05" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Letter Combinations of a Phone Number — LeetCode]]></title>
            <link>https://medium.com/@zzhenyyang/letter-combinations-of-a-phone-number-leetcode-5c489699aac4?source=rss-d8396be88a61------2</link>
            <guid isPermaLink="false">https://medium.com/p/5c489699aac4</guid>
            <category><![CDATA[problem-solving]]></category>
            <category><![CDATA[backtracking]]></category>
            <category><![CDATA[leetcode]]></category>
            <dc:creator><![CDATA[Zhen Yang]]></dc:creator>
            <pubDate>Sun, 03 Nov 2024 04:29:43 GMT</pubDate>
            <atom:updated>2024-11-03T04:29:43.856Z</atom:updated>
            <content:encoded><![CDATA[<h3>Letter Combinations of a Phone Number — LeetCode</h3><p>Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent. Return the answer in <strong>any order</strong>.</p><p>A mapping of digits to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uvWjPMl7pThljlWG.png" /></figure><p><strong>Example 1:</strong></p><pre>Input: digits = &quot;23&quot;<br>Output: [&quot;ad&quot;,&quot;ae&quot;,&quot;af&quot;,&quot;bd&quot;,&quot;be&quot;,&quot;bf&quot;,&quot;cd&quot;,&quot;ce&quot;,&quot;cf&quot;]</pre><p><strong>Example 2:</strong></p><pre>Input: digits = &quot;&quot;<br>Output: []</pre><p><strong>Example 3:</strong></p><pre>Input: digits = &quot;2&quot;<br>Output: [&quot;a&quot;,&quot;b&quot;,&quot;c&quot;]</pre><h3>Approach</h3><p>We need to construct a string with the same length as the number of digits. To do this, we need to first map the digits to a string of characters. Then with backtracking, we build these characters which we append to an output array.</p><h3>Solution design</h3><p>Iterate through the given digits. We will use the example “23” for this explanation. 2 maps to these characters shown below. We can create 3 nodes, one for each of the characters.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/528/1*qKPRu28L9SKr93OFXU-rAQ.png" /></figure><p>For each of these nodes, we want to add the next character on them because there are still “unused” digits. The next digit, 3, maps to “def”. So we get a tree that looks like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i9W-GqHdXgUxwYcd23vbFw.png" /></figure><p>At this point, we can return the backtracking function because the length of digits is equal to the length of the string we built.</p><h3>Code implementation</h3><pre>/**<br> * @param {string} digits<br> * @return {string[]}<br> */<br>var letterCombinations = function(digits) {<br>    let output = []<br><br>    if (!digits) return output<br><br>    const digitToLetters = {<br>        &#39;2&#39;: &#39;abc&#39;,<br>        &#39;3&#39;: &#39;def&#39;,<br>        &#39;4&#39;: &#39;ghi&#39;,<br>        &#39;5&#39;: &#39;jkl&#39;,<br>        &#39;6&#39;: &#39;mno&#39;,<br>        &#39;7&#39;: &#39;pqrs&#39;,<br>        &#39;8&#39;: &#39;tuv&#39;,<br>        &#39;9&#39;: &#39;wxyz&#39;,<br>    }<br><br>    function backtracking(index, curString) {<br>        if (curString.length === digits.length) {<br>            output.push(curString)<br>            return<br>        }<br><br>        for (const char of digitToLetters[digits[index]]) {<br>            backtracking(index+1, curString + char)<br>        }<br>    }<br><br>    backtracking(0, &quot;&quot;)<br>    return output<br>};</pre><p>This solution got me a 0ms runtime which beats 100.00% of submissions🎉😃!</p><p>Thank you for reading my article 🙏. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5c489699aac4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Container With Most Water — LeetCode]]></title>
            <link>https://medium.com/@zzhenyyang/container-with-most-water-leetcode-585919b211cc?source=rss-d8396be88a61------2</link>
            <guid isPermaLink="false">https://medium.com/p/585919b211cc</guid>
            <category><![CDATA[problem-solving]]></category>
            <category><![CDATA[two-pointers]]></category>
            <category><![CDATA[leetcode]]></category>
            <dc:creator><![CDATA[Zhen Yang]]></dc:creator>
            <pubDate>Sat, 02 Nov 2024 01:26:53 GMT</pubDate>
            <atom:updated>2024-11-02T01:26:53.656Z</atom:updated>
            <content:encoded><![CDATA[<h3>Container With Most Water — LeetCode</h3><p>You are given an integer array height of length n. There are n vertical lines drawn such that the two endpoints of the ith line are (i, 0) and (i, height[i]).</p><p>Find two lines that together with the x-axis form a container, such that the container contains the most water.</p><p>Return <em>the maximum amount of water a container can store</em>.</p><p><strong>Notice</strong> that you may not slant the container.</p><p><strong>Example 1:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/801/0*eUKXvtZrSgJmNv_Z.jpg" /></figure><pre>Input: height = [1,8,6,2,5,4,8,3,7]<br>Output: 49<br>Explanation: The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49.</pre><p><strong>Example 2:</strong></p><pre>Input: height = [1,1]<br>Output: 1</pre><h3>Approach</h3><p>If we look at the constraints of the question, the length of the array can be up to 10⁵ which tells us a solution of O(n²) will timeout. A brute force solution would timeout. To come up with a O(n) solution isn’t too difficult thankfully, we just need 2 pointers.</p><p>Starting from the start and end of the array, calculate the area and keep the largest area ever calculated. We decide which of the two pointers to move based on their heights. We want to keep the pointer that is pointing to the tallest “bar”.</p><h3>Solution design</h3><p>The amount of water two columns can hold can be calculated by shorter column * distance between the two columns. The blue represents water. The height of the columns are taken from the array, and their positions their index in the array.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/870/1*CB5OvV8AUaGaLZU1Ar9p4w.png" /></figure><p>We will be using the same example as above to illustrate the solution. Initialize two pointers, green for the left and red for the right. Calculate the area / amount of water it can hold with the formula shown above.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/722/1*EIOldTtNs-tquHxf3uVbmQ.png" /></figure><p>Next, we to decide which of the two pointers to move. This is determined by the height of their columns. We want to keep the pointer with the taller column because it gives us a better chance of achieving the largest amount of water. Look at the green arrow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ODJzcT7Gr1JTClnQ3h0tnw.png" /></figure><p>The same process repeats itself, where we only keep the larger maxArea value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tviACxcnsUc12_khGBAT1Q.png" /></figure><p>As we keep going, the start pointer will eventually exceed the end pointer, which gives us our stopping criteria.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R-OV-ge9w5rOjmnu3ClmGg.png" /></figure><h3>Code implementation</h3><pre>/**<br> * @param {number[]} height<br> * @return {number}<br> */<br>var maxArea = function(height) {<br>    let maxArea = 0<br><br>    let start = 0<br>    let end = height.length - 1<br><br>    while (start &lt; end) {<br>        maxArea = Math.max(maxArea, (end-start)*Math.min(height[start], height[end]))<br>        <br>        height[start] &gt; height[end] ? end-- : start++<br>    }<br><br>    return maxArea<br>};</pre><p>This solution got me a 3ms runtime which beats 52.30% of submissions🎉😃!</p><p>Thank you for reading my article 🙏. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=585919b211cc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Construct Binary Tree from Preorder and Inorder Traversal — LeetCode]]></title>
            <link>https://medium.com/@zzhenyyang/construct-binary-tree-from-preorder-and-inorder-traversal-leetcode-9199ff0bfa13?source=rss-d8396be88a61------2</link>
            <guid isPermaLink="false">https://medium.com/p/9199ff0bfa13</guid>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[binary-tree]]></category>
            <category><![CDATA[recursion]]></category>
            <dc:creator><![CDATA[Zhen Yang]]></dc:creator>
            <pubDate>Thu, 31 Oct 2024 00:53:18 GMT</pubDate>
            <atom:updated>2024-10-31T00:53:18.446Z</atom:updated>
            <content:encoded><![CDATA[<h3>Construct Binary Tree from Preorder and Inorder Traversal — LeetCode</h3><p>Given two integer arrays preorder and inorder where preorder is the preorder traversal of a binary tree and inorder is the inorder traversal of the same tree, construct and return <em>the binary tree</em>.</p><p><strong>Example 1:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/277/0*oy2iSGj_WwVttOYP.jpg" /></figure><pre>Input: preorder = [3,9,20,15,7], inorder = [9,3,15,20,7]<br>Output: [3,9,20,null,null,15,7]</pre><p><strong>Example 2:</strong></p><pre>Input: preorder = [-1], inorder = [-1]<br>Output: [-1]</pre><h3>Approach</h3><p>The preorder and inorder traversal arrays of a tree give us different but essential information for the reconstruction of a tree. The preorder array tells us the root of the tree and its subtrees, while the inorder array gives us the direction of tree nodes, i.e. left or right.</p><p>With this, we can breakdown these two arrays recursively in a specific way to achieve our desired outcome.</p><h3>Solution design</h3><p>The first element of the preorder array gives us the root node. So we build this node. There are two direction we need to traverse, let’s begin with the left.</p><p>Find the index of node 3 in the inorder array. We can think of this as the mid point as 3 it is the root of a tree with left and right nodes. Now we keep the left side of the inorder array, split by 3, giving us an array of [9]. With the same index of the mid point 3, we keep the left side of the preorder array. This is underlined in green.</p><p>This works because the number of nodes on the left side of the inorder array is equal to the number of nodes on the left side of the preorder array.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F2HYOb-Wk93gLei4aHaWbg.png" /></figure><p>Now we build node 9, and cut the arrays like how we just did. Since the arrays are empty, we return the function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PDtLh0YFBrejiMGif7R6pw.png" /></figure><p>Now for the right. The preorder and inorder arrays only contain the right side nodes. The first node to be built is node 20.</p><p>Now there are still remaining nodes. These belong to the subtree where node 20 is the root. Starting with the left, we truncate preorder and inorder arrays to keep only the left side.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cXn2eUXk1b4-Bi2kDlwZYQ.png" /></figure><p>Then we do the same for the right.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/1*yxldmw8nR7pl9YSem7UnIQ.png" /></figure><h3>Code implementation</h3><pre>/**<br> * Definition for a binary tree node.<br> * function TreeNode(val, left, right) {<br> *     this.val = (val===undefined ? 0 : val)<br> *     this.left = (left===undefined ? null : left)<br> *     this.right = (right===undefined ? null : right)<br> * }<br> */<br>/**<br> * @param {number[]} preorder<br> * @param {number[]} inorder<br> * @return {TreeNode}<br> */<br>var buildTree = function(preorder, inorder) {<br>    if (!preorder.length || !inorder.length) return null<br><br>    const val = preorder[0]<br>    const node = new TreeNode(val)<br>    const mid = inorder.indexOf(val)<br><br>    node.left = buildTree(preorder.slice(1, mid+1), inorder.slice(0, mid))<br>    node.right = buildTree(preorder.slice(mid+1), inorder.slice(mid+1))<br><br>    return node<br>};</pre><p>This solution got me a 80ms runtime which beats 24.31% of submissions🎉😃!</p><p>Thank you for reading my article 🙏. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9199ff0bfa13" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unique Paths — LeetCode]]></title>
            <link>https://medium.com/@zzhenyyang/unique-paths-leetcode-ba6856cb750b?source=rss-d8396be88a61------2</link>
            <guid isPermaLink="false">https://medium.com/p/ba6856cb750b</guid>
            <category><![CDATA[grid]]></category>
            <category><![CDATA[dynamic-programming]]></category>
            <category><![CDATA[problem-solving]]></category>
            <category><![CDATA[leetcode]]></category>
            <dc:creator><![CDATA[Zhen Yang]]></dc:creator>
            <pubDate>Sat, 26 Oct 2024 15:04:52 GMT</pubDate>
            <atom:updated>2024-10-26T15:04:52.506Z</atom:updated>
            <content:encoded><![CDATA[<h3>Unique Paths — LeetCode</h3><p>There is a robot on an m x n grid. The robot is initially located at the <strong>top-left corner</strong> (i.e., grid[0][0]). The robot tries to move to the <strong>bottom-right corner</strong> (i.e., grid[m - 1][n - 1]). The robot can only move either down or right at any point in time.</p><p>Given the two integers m and n, return <em>the number of possible unique paths that the robot can take to reach the bottom-right corner</em>.</p><p>The test cases are generated so that the answer will be less than or equal to 2 * 10^9.</p><p><strong>Example 1:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/0*3cyz1KH9LegYiTYe.png" /></figure><pre>Input: m = 3, n = 7<br>Output: 28</pre><p><strong>Example 2:</strong></p><pre>Input: m = 3, n = 2<br>Output: 3<br>Explanation: From the top-left corner, there are a total of 3 ways to reach the bottom-right corner:<br>1. Right -&gt; Down -&gt; Down<br>2. Down -&gt; Down -&gt; Right<br>3. Down -&gt; Right -&gt; Down</pre><h3>Approach</h3><p>We can break this problem down into subproblems at each grid cell. At each cell, there are only two possible moves the bot can make — right and down. This calls for a dynamic programming solution.</p><h3>Solution design</h3><p>Let’s determine our base case. On the cells directly above and to the left of the finish line, there is only one possible move to get to the finish line.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/1*4wak0Cg4oMpnVJXHMvxgow.png" /></figure><p>Along the bottom and right side of the grid, we observe that is only one possible path, a straight line to the star. At each cell, we label the number of possible paths to the finish it can take.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/1*s0nlFuO8TGcUb7VYyYYXOw.png" /></figure><p>The number of possible paths at each cell can be simplified into the number of possible paths of its right and bottom cell. Therefore in the example on the right, we calculate the number of paths to 2 by taking the sum.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Cxa6WA0xrgPOIF01J4zOPg.png" /></figure><p>As we keep going like this, we will eventually reach the start of the grid, to calculate the total number of paths.</p><h3>Code implementation</h3><pre>/**<br> * @param {number} m<br> * @param {number} n<br> * @return {number}<br> */<br>var uniquePaths = function(m, n) {<br>    const grid = Array(m).fill().map(()=&gt;Array(n).fill())<br><br>    for (let i = 0; i &lt; n; i++) {<br>        grid[m-1][i] = 1<br>    }<br><br>    for (let i = 0; i &lt; m; i++) {<br>        grid[i][n-1] = 1<br>    }<br><br>    for (let r = m-2; r &gt;= 0; r--) {<br>        for (let c = n-2; c &gt;= 0; c--) {<br>            grid[r][c] = grid[r+1][c] + grid[r][c+1]<br>        }<br>    }<br><br>    return grid[0][0]<br>};</pre><p>This solution got me a 1ms runtime which beats 94.28% of submissions🎉😃!</p><p>Thank you for reading my article 🙏. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ba6856cb750b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Longest Palindromic Substring — LeetCode]]></title>
            <link>https://medium.com/@zzhenyyang/longest-palindromic-substring-leetcode-6529f71a69f4?source=rss-d8396be88a61------2</link>
            <guid isPermaLink="false">https://medium.com/p/6529f71a69f4</guid>
            <category><![CDATA[string]]></category>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[problem-solving]]></category>
            <category><![CDATA[palindrome]]></category>
            <dc:creator><![CDATA[Zhen Yang]]></dc:creator>
            <pubDate>Thu, 24 Oct 2024 15:18:46 GMT</pubDate>
            <atom:updated>2024-10-24T15:18:46.063Z</atom:updated>
            <content:encoded><![CDATA[<h3>Longest Palindromic Substring — LeetCode</h3><p>Given a string s, return <em>the longest palindromic substring </em>in s.</p><p><strong>Example 1:</strong></p><pre>Input: s = &quot;babad&quot;<br>Output: &quot;bab&quot;<br>Explanation: &quot;aba&quot; is also a valid answer.</pre><p><strong>Example 2:</strong></p><pre>Input: s = &quot;cbbd&quot;<br>Output: &quot;bb&quot;</pre><h3>Approach</h3><p>How do we check if a string is a palindrome? We can start from a perceived middle and start expanding to the left and right to check if the chracters are equal.</p><h3>Solution design</h3><p>There are two cases. Let’s look at the first case where the length of the string is odd. We start from the first character. A singular character is a palindome. Next, we expand from “b”. Green arrow represents left and red the right pointer.</p><p>When we move the left pointer, it points to a non-existent character, so we break this loop. The max palindrome possible with “b” at this position is 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/829/1*RT16cQJDLYkF_q_6wpIhAw.png" /></figure><p>We move on to the next letter. This time, left and right characters are equal, bringing the max length up to 3.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/835/1*Ay1ycY3_9_3bUtihf1GUcQ.png" /></figure><p>In the event that the string has an even length, we need a different approach.</p><p>We cannot start from a singular character. Instead, left can start from the current character, and red one character to the right. If they are equal, max length would be 2. If not, it is 0.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/280/1*pQijAgKnEq3iFJvQ3uKrsg.png" /></figure><p>The following is how the expansion would look like.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u2jogy_aE4nPUE6xK5Dw2g.png" /></figure><h3>Code implementation</h3><p>We have a simple expandAroundCenter function to move the left and right pointers, and returning the length of the max palindrome length it found.</p><p>To account for both odd and even palindromes, we will do two searches, just with different parameters as mentioned earlier. Then we keep the largest of the two.</p><p>At each step, we are also calculating the start and end indexes of the palindrome in the string by taking half the maxLen and moving left or right by that length to get the correct index.</p><pre>/**<br> * @param {string} s<br> * @return {string}<br> */<br>var longestPalindrome = function(s) {<br>    if (!s) {<br>        return &quot;&quot;<br>    }<br><br>    function expandAroundCenter(s, left, right) {<br>        while (left &gt;= 0 &amp;&amp; right &lt; s.length &amp;&amp; s[left] === s[right]) {<br>            left--<br>            right++<br>        }<br>        return right - left - 1<br>    }<br><br>    let start = 0<br>    let end = 0<br><br>    for (let i = 0; i &lt; s.length; i++) {<br>        const odd = expandAroundCenter(s, i, i)<br>        const even = expandAroundCenter(s, i, i+1)<br>        const maxLen = Math.max(odd, even)<br><br>        if (maxLen &gt; end - start) {<br>            start = i - Math.floor((maxLen - 1) / 2)<br>            end = i + Math.floor(maxLen / 2)<br>        }<br>    }<br><br>    return s.substring(start, end + 1)<br>};</pre><p>This solution got me a 25ms runtime which beats 97.71% of submissions🎉😃!</p><p>Thank you for reading my article 🙏. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6529f71a69f4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Binary Tree Right Side View — LeetCode]]></title>
            <link>https://medium.com/@zzhenyyang/binary-tree-right-side-view-leetcode-883b263e3d5d?source=rss-d8396be88a61------2</link>
            <guid isPermaLink="false">https://medium.com/p/883b263e3d5d</guid>
            <category><![CDATA[binary-tree]]></category>
            <category><![CDATA[breadth-first-search]]></category>
            <category><![CDATA[leetcode]]></category>
            <dc:creator><![CDATA[Zhen Yang]]></dc:creator>
            <pubDate>Mon, 21 Oct 2024 14:45:39 GMT</pubDate>
            <atom:updated>2024-10-21T14:45:39.687Z</atom:updated>
            <content:encoded><![CDATA[<h3>Binary Tree Right Side View — LeetCode</h3><h3>Problem 62: Binary Tree Right Side View</h3><p>Given the root of a binary tree, imagine yourself standing on the <strong>right side</strong> of it, return <em>the values of the nodes you can see ordered from top to bottom</em>.</p><p><strong>Example 1:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/401/0*-VsEKJApIswaoqr7.jpg" /></figure><pre>Input: root = [1,2,3,null,5,null,4]<br>Output: [1,3,4]</pre><p><strong>Example 2:</strong></p><pre>Input: root = [1,null,3]<br>Output: [1,3]</pre><p><strong>Example 3:</strong></p><pre>Input: root = []<br>Output: []</pre><h3>Approach</h3><p>Traverse the tree with regular breadth-first-search. The observation needed to be made is that the last element in the BFS queue is the right-most node.</p><h3>Solution design</h3><p>Initialize two arrays, the BFS queue, and the final output array. First, push the root node into queue. This is the end of the first horizontal level because there are no other nodes on this level.</p><p>So we push this node to the output array.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*63ixGciAo_U9pxO22OmE2A.png" /></figure><p>Now we get the first element in the queue and push its children to the back of the queue. The order is very important, left first then right. The last element in queue is the right most element. Therefore push its value to the output array.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e9HQJ4LCPVCS-UKAkBxttw.png" /></figure><p>The next element in line is node 2. Once again we push its children to the queue from left to right. But we do not stop there. Node 3, which belongs in the same level as node 2, is still in queue. We need to push its children as well. However it does not have any children, so no changes are made.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8gdCfEASKFiqXAUASdl6cw.png" /></figure><p>Expectedly, we take the last element in queue and push it to the output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jGLS4yeIAABz5YB4_rPRWQ.png" /></figure><p>The same pattern executes over and over again, until queue is empty. Then we return output.</p><h3>Code implementation</h3><p>To ensure that we use all nodes from the same level from the queue, we keep a copy of the length of the queue before we add more children to it. Then we use a for loop to shift() elements out of the queue to limit how many times shift is called.</p><p>It is important to push the last element of the queue to the output before we shift elements out of the queue because we will lose the root/first node.</p><pre>/**<br> * Definition for a binary tree node.<br> * function TreeNode(val, left, right) {<br> *     this.val = (val===undefined ? 0 : val)<br> *     this.left = (left===undefined ? null : left)<br> *     this.right = (right===undefined ? null : right)<br> * }<br> */<br>/**<br> * @param {TreeNode} root<br> * @return {number[]}<br> */<br>var rightSideView = function(root) {<br>    let output = []<br>    let queue = []<br><br>    if (!root) return output<br><br>    queue.push(root)<br>    while (queue.length &gt; 0) {<br>        output.push(queue[queue.length-1].val)<br><br>        const n = queue.length<br>        for (let i = 0; i &lt; n; i++) {<br>            const node = queue.shift()<br>            if (node.left) queue.push(node.left)<br>            if (node.right) queue.push(node.right)<br>        }<br>    }<br><br>    return output<br>};</pre><p>This solution got me a 0ms runtime which beats 100.00% of submissions🎉😃!</p><p>Thank you for reading my article 🙏. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=883b263e3d5d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Subsets — LeetCode]]></title>
            <link>https://medium.com/@zzhenyyang/subsets-leetcode-e82c40d546ae?source=rss-d8396be88a61------2</link>
            <guid isPermaLink="false">https://medium.com/p/e82c40d546ae</guid>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[backtracking]]></category>
            <category><![CDATA[problem-solving]]></category>
            <dc:creator><![CDATA[Zhen Yang]]></dc:creator>
            <pubDate>Sun, 20 Oct 2024 14:08:49 GMT</pubDate>
            <atom:updated>2024-10-20T14:08:49.434Z</atom:updated>
            <content:encoded><![CDATA[<h3>Subsets — LeetCode</h3><h3>Problem 61: Subsets</h3><p>Given an integer array nums of <strong>unique</strong> elements, return <em>all possible subsets (the power set)</em>.</p><p>The solution set <strong>must not</strong> contain duplicate subsets. Return the solution in <strong>any order</strong>.</p><p><strong>Example 1:</strong></p><pre>Input: nums = [1,2,3]<br>Output: [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]</pre><p><strong>Example 2:</strong></p><pre>Input: nums = [0]<br>Output: [[],[0]]</pre><h3>Approach</h3><p>Use recursion to form all possible subsets and push it to a final output array.</p><h3>Solution design</h3><p>Finding all subsets can be broken down into two decisions. To take the number, or not to take it. The recursive tree diagram illustrates this. Starting with 1, we make 2 recursion calls, one which pushes 1 into its subset, and another that does not, indicated by the empty list.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/683/1*syI_d_wGr0GXh9gLMJEc_Q.png" /></figure><p>Let’s focus on one branch of the tree. The next 2 paths to be made is to push 2 into the subset, or not push 2 into the subset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-lwySXmCclFUt0KDBsZVTA.png" /></figure><p>Continue sticking to the left branch, we perform the same operation, of pushing 3 into the subset, or not. At this point, we have come to the end of the nums array, and we can push this subset to the final output array as one of the many subsets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/854/1*cG803hmSLwhNf6FYOvwVfw.png" /></figure><p>The diagram has only focused on one branch. But this process is replicated throughout the tree at different branches, giving us a final tree like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AXaQzasiyQrHNfIz7xA2Vw.png" /></figure><h3>Code implementation</h3><p>The stopping criteria of the recursion function is the length of the array of possible number choices.</p><p>First we perform the first decision of pushing the number to the current array. Then we make a recursive call with this subset, while also removing the added number from the list of possible choices.</p><p>Next, we pop() from the subset as we move on to the second decision, choosing not to add the number to the subset. We make a new recursive call with this subset, while also removing the added number from the list of possible choices.</p><pre>/**<br> * @param {number[]} nums<br> * @return {number[][]}<br> */<br>var subsets = function(nums) {<br>    let output = [];<br><br>    const subset = (curr, remaining) =&gt; {<br>        if (remaining.length === 0) {<br>            output.push([...curr]);<br>            return;<br>        }<br><br>        curr.push(remaining[0]);<br>        subset(curr, remaining.slice(1));<br><br>        curr.pop();<br>        subset(curr, remaining.slice(1));<br>    };<br><br>    subset([], nums);<br>    return output;<br>};</pre><p>This solution got me a 0ms runtime which beats 100.00% of submissions🎉😃!</p><p>Thank you for reading my article 🙏. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e82c40d546ae" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spiral Matrix — LeetCode]]></title>
            <link>https://medium.com/@zzhenyyang/spiral-matrix-leetcode-c643ff90a3c2?source=rss-d8396be88a61------2</link>
            <guid isPermaLink="false">https://medium.com/p/c643ff90a3c2</guid>
            <category><![CDATA[problem-solving]]></category>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[matrix]]></category>
            <dc:creator><![CDATA[Zhen Yang]]></dc:creator>
            <pubDate>Sat, 19 Oct 2024 15:06:55 GMT</pubDate>
            <atom:updated>2024-10-19T15:06:55.398Z</atom:updated>
            <content:encoded><![CDATA[<h3>Spiral Matrix — LeetCode</h3><h3>Problem 60: Spiral Matrix</h3><p>Given an m x n matrix, return <em>all elements of the</em> matrix <em>in spiral order</em>.</p><p><strong>Example 1:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/242/0*7LH3c809w96B2EfX.jpg" /></figure><pre>Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]<br>Output: [1,2,3,6,9,8,7,4,5]</pre><p><strong>Example 2:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/322/0*MCL_Hb_vumTkyOXE.jpg" /></figure><pre>Input: matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]<br>Output: [1,2,3,4,8,12,11,10,9,5,6,7]</pre><h3>Approach</h3><p>For this question, we simply traverse the matrix in a spiral and push the values we encounter into a new array which we return. However there are edge cases that our solution has to cover, as well as methods to make the code shorter and more readable.</p><h3>Solution design</h3><p>We initialize many variables. x and y refers to the coordinates of the cell in the matrix which we are looking at. dx and dy refers to the direction in which we are travelling, left to right and top to bottom respectively. Lastly we have the output array.</p><p>We increment x and y by dx and dy respectively, pushing elements into the output array along the way.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lwrhIvfsOWIAJcU1UujpPg.png" /></figure><p>When we reach the end of the matrix, we perform a direction change. We want to move downwards while keeping x the same. Therefore we change the dx and dy values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dwgv5tyEWnwG3fjD8PsFMg.png" /></figure><p>We reach the bottom of the matrix, so we change directions once again. We set dy = 0 so y does not change, and dx = -1 as we are moving from right to left. This allows us to decrement the x value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J_YZflr0baJ5nhWNME-uyQ.png" /></figure><p>Again at the boundary, we want to move upwards, which means dy = -1.</p><p>But there a problem. We do not want to push duplicate values into the output. The boundary of the matrix shrinks with each loop made. Along the way, we also indicate if that cell has been visited before. If we run into such a cell, it is another condition for us to switch directions too.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JJsnVEUnNmFZ3IptV9ZQng.png" /></figure><h3>Code implementation</h3><p>There is a clever observation made here. Each change in direction can be generalized into a formula, dx = -dy and dy = dx. This observation removes the need for much if-else logic.</p><p>Also to indicate visited cells, we replace the value at each visited cell with “.” which we later use as a condition to switch directions.</p><pre>/**<br> * @param {number[][]} matrix<br> * @return {number[]}<br> */<br>var spiralOrder = function(matrix) {<br>    const rows = matrix.length;<br>    const cols = matrix[0].length;<br>    let x = 0;<br>    let y = 0;<br>    let dx = 1;<br>    let dy = 0;<br>    const res = [];<br><br>    for (let i = 0; i &lt; rows * cols; i++) {<br>        res.push(matrix[y][x]);<br>        matrix[y][x] = &quot;.&quot;;<br><br>        if (!(0 &lt;= x + dx &amp;&amp; x + dx &lt; cols &amp;&amp; 0 &lt;= y + dy &amp;&amp; y + dy &lt; rows) || matrix[y+dy][x+dx] === &quot;.&quot;) {<br>            [dx, dy] = [-dy, dx];<br>        }<br><br>        x += dx;<br>        y += dy;<br>    }<br><br>    return res;    <br>};</pre><p>This solution got me a 0ms runtime which beats 100.00% of submissions🎉😃!</p><p>Thank you for reading my article 🙏. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c643ff90a3c2" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>