<?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 Jolyon on Medium]]></title>
        <description><![CDATA[Stories by Jolyon on Medium]]></description>
        <link>https://medium.com/@jolyon129?source=rss-b88df0d46a35------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*5vwngnCBEGdVqUUxiEJ8DQ@2x.jpeg</url>
            <title>Stories by Jolyon on Medium</title>
            <link>https://medium.com/@jolyon129?source=rss-b88df0d46a35------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 03:02:05 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jolyon129/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[Practical Synchronization with Go]]></title>
            <link>https://medium.com/@jolyon129/practical-synchronization-with-go-3bb725e547d7?source=rss-b88df0d46a35------2</link>
            <guid isPermaLink="false">https://medium.com/p/3bb725e547d7</guid>
            <dc:creator><![CDATA[Jolyon]]></dc:creator>
            <pubDate>Thu, 26 Mar 2020 02:19:12 GMT</pubDate>
            <atom:updated>2020-07-21T06:14:38.349Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gbrFm1MpZcuFCGNo.png" /></figure><h3>Introduction</h3><p>Go is such a beautiful language when it comes to manipulating threads and concurrency programming. Even though I’ve only used it for a month, I cannot get over with the convenience and efficiency of goroutines and sync packages. This out-of-box feature makes it much easier to practice concurrency patterns(Java is so opposed to this).</p><p>This post is inspired by <a href="https://www.youtube.com/watch?v=UzzcUS2OHqo&amp;t=40s">MIT 6.824 Lecture 5:GO, Threads, and Raft</a>. You can watch the lecture first and then come back for the summary notes.</p><p>Here we only focus on the practical usage of WaitGroup/Semaphore, mutex, condition variable, and channel.</p><p>Channel is used everwhere in Go but still we should try to avoid <strong>buffered channel</strong> if possible. Only the first three primitives are standard synchronization primitives and can be easily generalized to other languages.</p><h3>WaitGroup</h3><p>WaitGroup works like the semaphore. They both have an internal counter. However, WaitGroup will block the thread until the counter is 0 while the semaphore block until the counter is greater than 0. The associated operations are wg.Add()(increase by 1), wg.Done()(decrease by 1), wg.Wait().</p><p>A simple usage of waitGroup is to wait some other thread finished first.</p><pre>package main<br>import &quot;sync&quot;<br><br>func main() {<br>    var a string<br>    var wg sync.WaitGroup<br>    wg.Add(1)<br>    go func() {<br>    // Refer to variables from the enclosing scope <br>        a = &quot;hello world&quot;<br>        wg.Done()<br>    }()<br>    wg.Wait()<br>    println(a)<br>}</pre><p>main spawns a goroutine, and the anonymous function executes before the println(a) because of the wg.Done(). Note that the anonymous function is a closure. It can refer to the variable a from the enclosing scope.</p><p>Here, we can use unbuffered channel to do the same thing, but again, channel is exclusive to go, and there is always an alternative way to do the same thing with standard primitives. Those synchronization primitives are more easy to reason.</p><p>Only use channel when it makes your life easier.</p><pre>import &quot;fmt&quot;<br>func main() {<br>    var a string<br>    var ch = make(chan int)<br>    go func() {<br>    // Refer to variables from the enclosing scope <br>        a = &quot;hello world&quot;<br>        ch&lt;-1<br>    }()<br>    &lt;-ch<br>    fmt.Println(a)<br>}</pre><h3>Semaphore Barrier with WaitGroup</h3><p>A more common usage is to implement <a href="https://vladfeinberg.com/2017/01/24/semaphore-barrier.html">barriers</a>: To wait for a group of threads to finish first.</p><pre>package main<br>import &quot;sync&quot;<br><br>func main() {<br>    var wg sync.WaitGroup<br>  // Eg: Send RPC to all clients<br>    for i := 0; i &lt; 5; i++ {<br>        wg.Add(1)<br>    // Have to make a copy of the i from outer scope<br>    // Otherwise the x will change and end up to 5. <br>        go func(x int) {<br>            sendRPC(x)<br>            wg.Done()<br>        }(i)<br>    }<br>    wg.Wait()<br>}<br><br>func sendRPC(i int) {<br>    println(i)<br>}</pre><p>In this example, main sends RPC requests to 5 clients and wait for their executions.</p><p>The variable i is passed by copying the value instead of using a closure. The main will block until all 5 goroutines finished.</p><h3>Mutex</h3><p>Mutex is used whenever multiple threads try to access to some share memory/data.</p><p>The following is a bank example. Two accounts transfer money to each other in two threads.( defer mu.Unlock() should not be used here because its in a loop instead of a enclosing function. )</p><pre>// bank.go<br>package main<br><br>import &quot;sync&quot;<br>import &quot;time&quot;<br>import &quot;fmt&quot;<br><br>func main() {<br>    alice := 10000<br>    bob := 10000<br>    var mu sync.Mutex<br><br>    total := alice + bob<br><br>    go func() {<br>        for i := 0; i &lt; 1000; i++ {<br>            mu.Lock()<br>      // defer mu.Unlock()<br>            alice -= 1<br>            bob += 1<br>            mu.Unlock()<br>        }<br>    }()<br>    go func() {<br>        for i := 0; i &lt; 1000; i++ {<br>            mu.Lock()<br>      // defer mu.Unlock()<br>            bob -= 1<br>            alice += 1<br>            mu.Unlock()<br>        }<br>    }()<br><br>    start := time.Now()<br>    for time.Since(start) &lt; 1*time.Second {<br>        mu.Lock()<br>        if alice+bob != total {<br>            fmt.Printf(&quot;observed violation, alice = %v, bob = %v, sum = %v\n&quot;, alice, bob, alice+bob)<br>        }<br>        mu.Unlock()<br>    }<br>  fmt.Printf(&quot;alie+bob= %v\n&quot;, alice+bob)<br>}</pre><p>When you have multiple shared instance, it’s better to use embedded mutex as a field in a struct. Ref: <a href="https://stackoverflow.com/questions/44949467/when-do-you-embed-mutex-in-struct-in-go">When do you embed mutex in struct in Go?</a></p><pre>var account struct {<br>    sync.Mutex<br>    money int<br>}<br><br>alice := account{<br>    money: 10000<br>}<br>bob := account{<br>    money: 10000<br>}</pre><p>In this example, since we need automatically mutate two variants at the same time( alice-=1 and bob+=1), use a global mutex to specify a critical section is more straightforward.</p><h3>Cancel periodic tasks with a shared variable and mutex</h3><p>We often what to do something periodically in the background, and when some service terminate, we also want to kill these background thread so that no random threads are running in the background. An easy way to do that is to use a shared variable protected by a mutex.</p><pre>func main() {<br>    time.Sleep(1 * time.Second)<br>    println(&quot;started&quot;)<br>    go periodic()<br>    time.Sleep(5 * time.Second) // wait for a while so we can observe what ticker does<br>    mu.Lock()<br>    done = true<br>    mu.Unlock()<br>    println(&quot;cancelled&quot;)<br>    time.Sleep(3 * time.Second) // observe no output<br>}<br><br>// Run something perioidically in background until the<br>// controller decide to kill them<br>func periodic() {<br>    for {<br>        println(&quot;tick&quot;)<br>        time.Sleep(1 * time.Second)<br>        mu.Lock()<br>        if done {<br>      mu.Unlock()<br>            return<br>        }<br>        mu.Unlock()<br>    }<br>}<br></pre><h3>Condition Variable</h3><p>Condition variable is used a lot in practice. <br> It has three operations and is always paired with mutex( cond:=sync.NewCond(&amp;mu)):</p><ul><li>cond.Broadcast(): wakes all goroutines on the cond</li><li>cond.Singal(): only wake one goroutine(random choice)</li><li>cond.Wait(): Automatically unlock the mutex(c.L) and suspend the current goroutine(go into sleep and cannot come back unless awoken by the above operations). When awoken up, Wait() will try to grab the lock again.</li></ul><p>Consider the example of vote counting. One client launches a vote and sends requests to other clients. The organizer can only continue until it gets a quorum(get over half of the votes).</p><p>Naively we can implement this by using an infinite for-loop with a mutex(busy-waiting), instead of the condition variable. However, it is not nice because the busy-waiting can burn up 100% cpu on a single core.</p><pre>// Busy-waiting without condition variables<br>func main() {<br>  rand.Seed(time.Now().UnixNano())<br>  count := 0<br>  finished := 0<br>  var mu sync.Mutex<br>  for i := 0; i &lt; 10; i++ {<br>    go func() {<br>      vote := requestVote()<br>      mu.Lock()<br>      defer mu.Unlock()<br>      if vote {<br>        count++<br>      }<br>      finished++<br>    }()<br>  }<br>  // Busy-waiting is always not good. Burn up 100% CPU on<br>  // one core. <br>  for {<br>    mu.Lock()<br>    if count &gt;= 5 || finished == 10 {<br>      break<br>    }<br>    mu.Unlock()<br>  }<br>  if count &gt;= 5 {<br>    println(&quot;received 5+ votes!&quot;)<br>  } else {<br>    println(&quot;lost&quot;)<br>  }<br>  mu.Unlock()<br>}</pre><p>The main thread keeps looping and testing until it gets a quorum. Notice it needs to both check count(how many of yes) and finished(how many voted) to fully observe the vote is finished.</p><p>A better solution is to use a condition variable to do that. The cond.wait() let the current main thread go to sleep and give up the lock, so other threads have more time slot to manipulate the data. And the main thread only resumes when others wake it up.</p><pre>func main() {<br>  rand.seed(time.now().unixnano())<br>  count := 0<br>  finished := 0<br>  var mu sync.mutex<br>  cond := sync.newcond(&amp;mu)<br><br>  for i := 0; i &lt; 10; i++ {<br>    go func() {<br>      vote := requestvote()<br>      mu.lock()<br>      defer mu.unlock() // remember to unlock the mutex after broadcasting<br>      if vote {<br>        count++<br>      }<br>      finished++<br>      // broadcast to the threads that waitting on the condition variable.<br>      cond.broadcast()<br>    }()<br>  }<br>  mu.lock()   // the lock here also avoid the lost-wakeup issue.<br>  for count &lt; 5 &amp;&amp; finished != 10 {<br>    // this will block the current thread and give up its lock atomically <br>    // so that other threads can make progress.<br>    cond.wait()<br>    // if someone wakes this up. the current thread will try to grab the<br>    // lock again. and then check the count and finished while holding <br>    // the lock<br>  }<br>  if count &gt;= 5 {<br>    println(&quot;received 5+ votes!&quot;)<br>  } else {<br>    println(&quot;lost&quot;)<br>  }<br>  mu.unlock()<br>}<br>func requestVote() bool {<br>  time.Sleep(time.Duration(rand.Intn(100)) * time.Millisecond)<br>  return rand.Int() % 2 == 0<br>}</pre><p>There is a particular pattern we need to follow when using condition variables. For the side that might make changes to a critical section that will change the outcome of the condition test, you always lock first then manipulate the data. Then call broadcast and call unlock afterward.</p><p>Similarly, when you’re checking the condition you grab the lock first. Then you’re always checking the condition in a loop and call wait() inside it. And unlock whenever we are done. The condition test will only execute when you grab the lock(When waked up, the end of wait() will grab the lock again).</p><pre>mu.Lock()<br>// do something that might affect the condition<br>cond.Broadcast()<br>mu.Unlock()<br><br>----<br><br>mu.Lock()<br>while condition == false {<br>    cond.Wait()<br>}<br>// now condition is true, and we have the lock<br>mu.Unlock()</pre><p><em>Originally published at </em><a href="https://dev.to/jolyon129/practical-synchronization-with-go-2nck"><em>https://dev.to</em></a><em> on March 26, 2020.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3bb725e547d7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Interprocess/Interthread Communication Notes]]></title>
            <link>https://medium.com/@jolyon129/interprocess-interthread-communication-notes-31519af4cc7c?source=rss-b88df0d46a35------2</link>
            <guid isPermaLink="false">https://medium.com/p/31519af4cc7c</guid>
            <category><![CDATA[os]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Jolyon]]></dc:creator>
            <pubDate>Thu, 12 Dec 2019 03:08:00 GMT</pubDate>
            <atom:updated>2020-02-28T16:53:02.655Z</atom:updated>
            <content:encoded><![CDATA[<p>This post is a summary note for <a href="https://www.amazon.com/Modern-Operating-Systems-Andrew-Tanenbaum/dp/013359162X">MOS</a> 2.3, 2.6, and includes all theoretical knowledge about concurrence, interprocess communication.</p><p>I find it’s quite helpful that understanding these theories behind the concurrence before trying to dig into the implements of some libraries of concurrence.</p><h3>The problem of shared resources: Race Conditions</h3><p>When it comes to concurrency, it is all about communication between processes or threads. There are three main issues:</p><ol><li>How to pass information</li><li>How to make sure two or more processes do not get in each other’s way</li><li>How to assure the proper sequence when dependencies are required.</li></ol><p>A more specific problem of issue 3 is <strong>race conditions</strong>.</p><p>Race conditions are the situation when, in the setting of two or more processes/threads running with shared resources, the final result depends on who runs precisely when. The race conditions are really common because of the preemptive scheduler. You cannot predict which thread would be blocked or get running.</p><h3>The idea to avoid race conditions: Mutual Exclusion</h3><p>The solution is <strong>mutual exclusion</strong>, that is, some way of making sure that if one process is using a shared resource, the others cannot access them at the same time. The part of the program where the shared resources are accessed is called the <strong>critical region/section</strong>. In another word, we want to make sure only one process enters the critical region at the same time.</p><h3>Mutual Exclusion with Busy Waiting</h3><p>In the early times, there are ways to achieve mutual exclusion through while loop. However, that causes a common problem: useless busy waiting.</p><h4>Spinlock</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/674/1*5m-jv4JvUk0v3zZqQ-0EqA.png" /></figure><p>Besides busy waiting, another con of a spinlock is that a<strong> slow noncritical region</strong> of a process blocks other processes, which is totally unnecessary.</p><h4>Peterson’s Solution:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/635/1*h12Gia4gUW5jLYO6dKxOoA.png" /></figure><h4>The TSL Instruction:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/676/1*0aXihKHkTJw77w5OZZTuPA.png" /></figure><p>The TSL Instruction and Peterson’s solutions are mostly the same.</p><h3>Sleep, wakeup, and lost wakeup</h3><p>To avoid useless busy waiting, we can make use of two system calls: sleep and wakeup. The idea is simple: we can just replace the while loop in Peterson&#39;s Solution with a single test and sleep. But this will raise another problem: lost wakeup.</p><p>Lost wakeup is a situation when you try to wake up a process/thread which is about to sleep, whereas it hasn&#39;t fallen into sleep. And that process will never wake up again because it misses the wakeup call.</p><h3>Semaphores</h3><p>Semaphores are a special variable used to solve the lost-wakeup problem. A semaphore is an integer variable associated with only two operations: up/P and down/V, and we cannot access the semaphore directly.</p><p>The down operation checks whether a semaphore is greater than 0. If it does, the process decrements the semaphore by one and continues; if it doesn&#39;t, the process will get blocked and wait until somebody increments the semaphore by calling up. It is essential to mention that up and down operations are atomic. The atomicity is implemented by a lock variable and TSL or XCHG instruction.</p><p>In practice, we use semaphores in two different ways:</p><ol><li>The mutex semaphore is used for mutual exclusion</li><li>The other use of semaphore is for <strong>synchronization</strong>, which guarantees that certain event sequences do or do not occur(e.g., try to put a new item in a full buffer).</li></ol><p>Here is the solution of producer and consumer with semaphore. The full and empty semaphores are used to synchronization, while the mutex semaphore is used for mutual exclusion</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/737/1*UrW7vTsl53JrdzAz6O5YAA.png" /></figure><p>Semaphores are powerful.</p><h3>Mutexes and condition variables</h3><p>Mutexes are a simplified version of semaphores. A mutex is a shared variable that only consists of two states: unlocked or locked. It is associated with two operations. Notice that here mutex_lock and mutex_unlock, are actually not atomic, but synchronized and indivisible.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/661/1*gXTYDylyeIvBiCSXtqSsug.png" /></figure><p>Mutexes can be easily implemented in user space provided TSLinstruction is available, and hence it has a smaller cost than semaphores.</p><p>Notice that the difference between enter_region and mutex_lockis that a mutex will call thread_yield to yield its running time to the scheduler.</p><p>Mutexes are useful for blocking access to a critical region. While sometimes, we also want to block a thread when some conditions not met, and that is when condition variables come in handy. Condition variables are another synchronized mechanism and are often paired with mutexes.</p><p>In the producer-consumer problem, we can use mutex to achieve mutual exclusion, so that only the producer is accessing the buffer, but we still need condition variable to make sure the buffer is not full so that we can put a new item in it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/581/1*Z1uBwp-KMRM55yZZpEYDIw.png" /></figure><p>Notice that the method Pthread_cond_wait(cond, mutex) need be passed into the mutex parameter. The reason is that when the producer realizes the buffer is full, we need to unlock the mutexinside the function Pthread_cond_wait so that the consumer could access the buffer to consume one item.</p><p>And after Pthread_cond_wait execute, it trys to grab the lock mutex The program can not continue until the Pthread_cond_wait access the lock.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/755/1*SymtjW1_Dn2eFuMJJbXfyA.png" /></figure><p>The statement that puts a thread to sleep should always check the condition to make sure it is satisfied before continuing, as the thread might have been awakened due to a UNIX signal or some other reason.</p><p>Conditional variables, unlike semaphores, have no memory, which means if no thread is waiting for the conditional variables, the signal is lost. In other words, the cond_wait must be called before the cond_signal. <strong>This is why we need to pair with </strong><strong>mutexand why we need to call </strong><strong>mutex_lock first in the above code</strong></p><h3>Monitors</h3><p>The mutex and semaphore are powerful enough, but they are not easy to use. In the example of Fig.2-28, if the order of the two down in consumer were reversed in order, the program will become <strong>deadlock.</strong></p><p>A monitor is a high-level synchronization primitive. It is a struct/collection/object that contains local variables, procedures. We can use a monitor identifier to indicate it. Processes cannot access the internal data structure of the monitor while they can call the procedures in it at will.</p><p>The most important property of the monitor is that only one procedure inside the monitor can be executed at a time. This provides a straightforward way to achieve mutual exclusion.</p><pre>It is sufficient to know that by turning all the critical regions into monitor procedures, no two processes will ever execute their critical regions at the same time.</pre><p>But still, conditional variables are needed to block procedures when it cannot meet some criteria.</p><h3>Monitor with conditional variables</h3><p>The new question arises when it comes to pairing monitors with conditional variables. If a procedure inside the monitor decides to signal on some conditional variables, should the procedure get blocked? Because the monitor is allowed to execute one procedure at a time. Well, there are three proposals to handle this situation.</p><ol><li>Let the new awakened procedure runs and suspended the current one.</li><li>The signal statement can only be allowed to appear as the final statement in a monitor procedure.</li><li>Let the current procedure keep running(the one called signal), and wake the waiting procedure only after the current one exiting.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/571/1*fT3axKEoox-uffXMzHN1gA.png" /></figure><h3>Barriers</h3><p>Barriers are used to block a process in a group of processes until all of them are ready to proceed into the next phase.</p><h3>Read-Copy-Update</h3><p>Read-copy-update is a way to avoid using locks. The trick is that ensure each reader either read the old version of the data or the new version of the data. And update the data only until there is no reader accessing the old data.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=31519af4cc7c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Leetcode 470 Generate random7 using random5]]></title>
            <link>https://medium.com/@jolyon129/470-generate-random7-using-random5-c48ff8b00790?source=rss-b88df0d46a35------2</link>
            <guid isPermaLink="false">https://medium.com/p/c48ff8b00790</guid>
            <category><![CDATA[leetcode]]></category>
            <dc:creator><![CDATA[Jolyon]]></dc:creator>
            <pubDate>Thu, 18 Jul 2019 23:13:56 GMT</pubDate>
            <atom:updated>2019-12-14T21:59:06.826Z</atom:updated>
            <content:encoded><![CDATA[<p>Thanks to Vivekanand Kiruban from the <a href="https://www.quora.com/How-do-you-design-a-rand7-function-using-a-rand5-function">link</a>.</p><p>There are three concepts in geometric distribution you need to know before you solve these kinds of questions. They are straightforward to understand.</p><h3>Expanding a zero-based random</h3><p>Let’s say you have a random10 which returns a number from 0 to 9. How would you build random100 that can return from 0 to 99?</p><p>You can call random10 to generate each digit.</p><pre>random100 = 10*random10() + 1*random10()<br>random1000 = 100*random10() + 10*random10() + 1*random10()</pre><p>If we change our definition of random, now random10 will return a number from 1 to 10, can we use the above formula to generate random100(1 to 100)?</p><p>The answer is no. If you think about it, the 10*random10() + 1*random10() can only return a number from 2 to 101, instead of 1 to 100.</p><p>You need to tweak the formula a little bit. Specifically, you need to zero-based your random.</p><pre>random100 = 10*(random10()-1) + 1*(random10()-1) + 1</pre><p>Notice that we need to add 1 in the end because 10*(random10()-1) + 1*(random10()-1) will result in a number from 0 to 99, and what we want is 1 to 100.</p><h3>Discarding and Rolling again</h3><p>If you have a six sided dice and want to use it, determine “Head or Tail,” what you will do? Let’s if you get 1, say heads, if you get 2, say tails, and if you get anything else, you discard them by rolling again. This approach will guarantee an equivalent to H/T, but notice you may be rolling the die many times.</p><h3>Folding to Map</h3><p>In the above example of dice, another solution you have is mapping the other values into H or T. For example, 1,2,3 (= heads), 4,5,6 (= tails). When it comes to implementation, we can use the modulo operator to do that.</p><p>E.g.,</p><pre>random3 = random6 % 3 // Assuming the random here is zero-based</pre><h3>Use the three concepts</h3><p>What we have right now is 1-based random7, and we need to generate random10. Here are the steps we are going to go through:</p><ol><li>zero-based random7: random7-1(0..6)</li><li>expanding zero-based random7 to zero-based random49: (random7-1)*7 + (random7-1)</li><li>discarding the number over 40 by rolling again, then we get zero-based random40:</li></ol><pre>while(random40&gt;=40){<br>    random40 = (random7-1)*7 + (random7-1)<br>}</pre><p>4. folding zero-based random40 to one-based random10</p><pre>random10 = random40%10+1</pre><p>The complete code:</p><pre>class Solution extends SolBase {<br>    public int rand10() {<br>        int rand40 = Integer.MAX_VALUE;<br>        while (rand40 &gt;= 40) {<br>            rand40 = (rand7() - 1) * 7 + rand7() - 1;<br>        }<br>        return rand40 % 10 + 1;<br>    }<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c48ff8b00790" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Leetcode 765. Couples Holding Hands]]></title>
            <link>https://medium.com/@jolyon129/765-couples-holding-hands-a9ce4d50b25e?source=rss-b88df0d46a35------2</link>
            <guid isPermaLink="false">https://medium.com/p/a9ce4d50b25e</guid>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Jolyon]]></dc:creator>
            <pubDate>Tue, 16 Jul 2019 18:51:23 GMT</pubDate>
            <atom:updated>2019-12-14T22:00:27.342Z</atom:updated>
            <content:encoded><![CDATA[<h3>765. Couples Holding Hands</h3><p><a href="https://leetcode.com/problems/couples-holding-hands/">https://leetcode.com/problems/couples-holding-hands/</a></p><p>The solutions to these kinds of problems all come down to one mathematical idea, permutation graph, no matter you are using union-find, greedy, or cycle decomposition. And once you understand the concept of permutation graph, you will know how to think about it when you next time encountering them. So, I’m going to detour a little bit to talk about the permutation graph.</p><h3>Permutation Graph and Graph Decomposition</h3><p>The permutation graph theory clams that given a pair of permutation, e.g, group1:a,b,a,c,a,d,c and group2:b,c,d,a,a,c,a, if we connect the edge from group1 to group2, we can represent this pair of permutation by a graph. Based on observation, if at one position i, we have group1[i]=group[i], then this vertex should have a self-connected edge.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*isI1TOU8CFEsuz9s0n89cg.png" /></figure><p>To transform group2 into group1, we need to make swapping so that we can remove edges between two vertices(in other words, let them become self-connected edges).</p><p>Then, another observation you need is that for any cycle in our graph, the minimal steps to remove all non-self-connected edges for a cycle is the number of edges minus 1,#edges-1. Hence, the total number of swap:</p><p>#swap=∑(Ck−1)#<em>swap</em>=∑(<em>Ck</em>​−1) where C1,…,Ck<em>C</em>1​,…,<em>Ck</em>​ are the lengths of the cycles(connected components) in our graph.</p><p>If we want to minimize the total #swap, we need to find a way to decompose our graph into different cycles so that each cycle is as small as possible(Because the number of edges is fixed, but if the more cycles we ended with, the more times #swap is minus by 1).</p><p>The more general visual example is given in this post: (854. K-Similar Strings)[]. Actually, in this question, we don’t need to decompose the graph because each vertex only has 2 degrees and there is only one way to decompose the graph. I’ll talk this later.</p><p>For more detailed information about cycle decomposition, you can check this <a href="https://www.youtube.com/watch?v=6CwiYoEsEPI">video</a></p><p>Those are all the prerequisite knowledge to solve this question. Let’s back to our problem.</p><h3>Union-Find</h3><p>The problem defines a bunch of couples, e.g, [0,1] , [1,2], [3,4]. Without loss of generality, Let’s name [0,1] couple A, [2,3] couple B and so on. To smooth our understanding, let’s say we have a function named ‘coupleOf()’. According to our definition, we have coupleOf(0)=A, coupleOf(1)=A, ‘coupleOf(2)=B’, coupleOf(3)=B. A,B can denote vertices in the graph and for each pair in the row, row[2*i] and row<a href="https://medium.com/i=0,1,2,3">2*i+1</a>, we connect the edge from coupleOf(row[2*i]) to coupleOf(row[2*i+1]).</p><p>Given a row = [0,2,3,4,5,1,6,8,7,9], we can visualize them as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZfO9A8Fi_UhHGbPVaSIIpg.png" /></figure><p>According to permutation graph theory, the minimal step of optimal swapping(the swap which at least help match one couple) is #swap=∑(Ck−1)#<em>swap</em>=∑(<em>Ck</em>​−1) where C1,…,Ck<em>C</em>1​,…,<em>Ck</em>​ are the lengths of the cycles(connected components) in our graph.</p><p>Notice that in this question, every vertex only has 2 degrees, and there is only one way to decompose our graph into cycles(which is very obvious) so that the problem could be reduced into #swap = #(vertex) - #num(components). In the end, we only need to count the number of connected components, and this can be solved by using DFS or Union-Find.</p><h3>Greedy Policy</h3><p>So far, we have already found a way to solve this question in O(n) time. If you look at the graph above more carefully, there is a greedy policy. Since there is only one way to decompose graph, any swap that helps match at least one couple is a greedy action.</p><p>Specifically, we can use one loop to precompute a hash map, position, which used to store the position of each person. Then we loop over the row again, whenever we find a pair of people not match, we can find where the corresponding mate is in position and swap them. We keep doing these greedy actions and count how many swapping we need.</p><pre>class Solution(){<br>    private int count = 0;<br>    private HashMap&lt;Integer, Integer&gt; position = new HashMap&lt;&gt;();</pre><pre>    public int minSwapsCouples(int[] row) {<br>        for (int i = 0; i &lt; row.length; i++) {<br>            this.position.put(row[i], i);<br>        }<br>        for (int g = 0; g &lt; row.length / 2; g++) {<br>            int c1 = row[2*g];<br>            int c2 = row[2*g+1];<br>            if((c1%2==0 &amp;&amp; c2!=c1+1) || (c1%2!=0 &amp;&amp;c2!=c1-1)){<br>                int source_int = row[2 * g];<br>                int target_pos = source_int<br>                        % 2 == 0 ? position.get(source_int + 1) : position.get(source_int - 1);<br>                swap(row, 2 * g+1, target_pos);<br>                count++;<br>            }<br>        }<br>        return count;<br>    }</pre><pre>    private void swap(int[] row, int i, int j) {<br>        int tmp = row[i];<br>        row[i] = row[j];<br>        row[j] = tmp;<br>        this.position.put(row[i], i);<br>        this.position.put(row[j], j);<br>    }<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a9ce4d50b25e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[188 Best Time to Buy and Sell Stock IV]]></title>
            <link>https://medium.com/@jolyon129/188-best-time-to-buy-and-sell-stock-iv-17178bb13cae?source=rss-b88df0d46a35------2</link>
            <guid isPermaLink="false">https://medium.com/p/17178bb13cae</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[dynamic-programming]]></category>
            <dc:creator><![CDATA[Jolyon]]></dc:creator>
            <pubDate>Thu, 11 Jul 2019 04:10:24 GMT</pubDate>
            <atom:updated>2020-04-12T01:25:57.521Z</atom:updated>
            <content:encoded><![CDATA[<h3>Leetcode 188 Best Time to Buy and Sell Stock IV</h3><p>The DP solution to this question is really brilliant. We start with writing down its optimal substructure and then try to simplify it.</p><p>To make it easier to understand, let’s make some notations.</p><p>dp[k, i]: The maximum profit up to the day i (inclusive) with at most k transactions.</p><p>sell[k, i]: The maximum profit up to the day i(inclusive) with at most k transactions and selling on the day i.</p><p>Then we have the following dp formula:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-YsB25mlFM0yS4ihbhSGWw.png" /></figure><p>Initially, dp[0,i] = 0, sell[0,i]=0, dp[k,0] =0, sell[k, 0] = 0.</p><p>So far, we can write the solution based exactly on the dp formula. However, there is still some improvement we can make.</p><p>First, if there are enough numbers of transactions, specifically, when k is larger than prices.length/2 , we can buy and sell as much as we want. In this case, we don’t need to use DP to solve it. Instead, we can just sum all the positive benefit compared to the previous day. This means that we could add a quickSolve to this kind of case.</p><pre>// if(k&gt;prices.length/2)<br>    private int quickSolve(int k, int[] prices) {<br>        int ans = 0;<br>        for (int i = 1; i &lt; prices.length; i++) {<br>            if(prices[i]&gt;prices[i-1]){<br>                ans += prices[i] - prices[i-1];<br>            }<br>        }<br>        return ans;<br>    }</pre><p>Besides, we can get rid of the array sell, because sell[k][i] only depends on the state sell[k,i-1] and we can use a temp variable to store the previous result, sell[k,i-1] without storing it in an array. Of course, the prerequisite is that we need to loop over k on the outer loop, so that each inner loop only change the i variable.</p><pre>public int maxProfit(int k, int[] prices) {<br>        int sell;<br>        int diff;<br>        if(k&gt;prices.length/2){<br>            return quickSolve(k, prices);<br>        }<br>        int[][] dp = new int[k + 1][prices.length];<br>        // Initialize<br>        for (int i = 0; i &lt; prices.length; i++) {<br>            dp[0][i] = 0;<br>        }<br>        // Initialize<br>        for (int i = 0; i &lt; k+1; i++) {<br>            dp[i][0] = 0;<br>        }<br>        for(int t=1;t&lt;k+1;t++){<br>            sell = 0;<br>            for(int i=1;i&lt;prices.length;i++){<br>                diff = prices[i]-prices[i-1];<br>                sell = Math.max(sell, dp[t-1][i-1])+diff;<br>                dp[t][i] = Math.max(sell, dp[t][i-1]);<br>            }<br>            <br>        }<br>        return dp[k][prices.length-1];<br>    }</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=17178bb13cae" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Leetcode 962 Maximum Width Ramp]]></title>
            <link>https://medium.com/@jolyon129/962-maximum-width-ramp-c31d747859fb?source=rss-b88df0d46a35------2</link>
            <guid isPermaLink="false">https://medium.com/p/c31d747859fb</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[leetcode]]></category>
            <dc:creator><![CDATA[Jolyon]]></dc:creator>
            <pubDate>Mon, 08 Jul 2019 19:05:01 GMT</pubDate>
            <atom:updated>2020-04-12T01:28:32.129Z</atom:updated>
            <content:encoded><![CDATA[<h3>O(nlogn)</h3><p>We can use a new array to store the index of the sorted array, let’s say idx_arr[]. In this array, try to find the largest value of idx_arr[j]-idx[i], so that i&lt;j and idx_arr[i]&lt; idx_arr[]. The new question can be solved by one loop in O(n).</p><pre>def maxWidthRamp(self, A):<br>    idx_arr = sorted(range(len(A)), key= lambda x: A[x])<br>    ans = 0<br>     # m indicates the smallest value so far<br>    m = float(&#39;inf&#39;)<br>    for i in range(len(idx_arr)):<br>        ans = max(ans, i-m)<br>        m = min(idx_arr[i], m)<br>    return ans</pre><h3>O(n)</h3><p>Since we only need to find the maximum, we can try to eliminate our candidates and solve this by using the sliding window. First, we generate a new array,right_max[] which stores the largest number on the right for the current index. For example, right_max[i] = 5 means that from the index i(including itself), the largest number on the right in A[i...] is 5. The right_max can be generated by using dp in O(n) and naturally, the right_max list should be decreasing order.</p><p>Then we can use a sliding window, the tricky part is that the left pointer is on the original array while the right pointer is on the right_max. The left pointer i on the A list contract the window and the right pointer j on the right_max expand the window.</p><p>In the loop over A, we try to find the first j such that right_max[j] is smaller than A[j], and the answer for the current index i would be j-i-1. Then we keep the size of the window unchanged and move the whole window one step forward and iterate the next i</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KU-GZgN5TaMdC3lK9kj30g.png" /></figure><pre>def maxWidthRamp_linear(self, A):<br>    right_max = [None]* len(A)<br>    for i in range(len(A)-1,-1,-1):<br>        if i == len(A)-1:<br>            right_max[i] = A[i]<br>        else:<br>            right_max[i] = max(A[i],right_max[i+1])<br>    <br>    i, j = 0, 1<br>    ans = 0<br>    while i &lt;len(A):<br>        if j &gt;=len(A):<br>            break<br>        while j &lt; len(A) and A[i] &lt;= right_max[j]:<br>            j +=1<br>        ans = max(ans, j-i-1)<br>        i += 1<br>    <br>    return ans</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c31d747859fb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Merge-sort based recursion]]></title>
            <link>https://medium.com/@jolyon129/merge-sort-based-recursion-901f9d643aa0?source=rss-b88df0d46a35------2</link>
            <guid isPermaLink="false">https://medium.com/p/901f9d643aa0</guid>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[merge-sort]]></category>
            <category><![CDATA[leetcode-hard]]></category>
            <dc:creator><![CDATA[Jolyon]]></dc:creator>
            <pubDate>Fri, 05 Jul 2019 19:01:24 GMT</pubDate>
            <atom:updated>2020-02-28T16:47:53.402Z</atom:updated>
            <content:encoded><![CDATA[<h3>Leetcode: Merge-sort based recursion</h3><p>Recently, I ran into serveral coding questions that keep exploiting the same idea in the solutions: merge-sort based recursion. e.g., <a href="https://leetcode.com/problems/reverse-pairs/">493</a>, <a href="https://leetcode.com/problems/count-of-smaller-numbers-after-self/">315</a>, <a href="https://leetcode.com/problems/reverse-pairs/">493</a>.</p><p>I made a summary and want share the fundamental idea under the hood.</p><p>Let’s take leetcode #493 as an example. It requires us to count the important pairs so that i &lt; j and nums[i] &gt; 2*nums[j]. If we put these requirements in the setting of merge sort, where the left and right part of the subarray are already sorted, we can find the solution in O(n) time. We can make use of characteristics in these two sorted parts. So, the basic idea is to break down the array and solve for the subproblems.</p><p>To smooth the following discussion, let’s assume the input array is nums, with a total of n Elements. Let nums[i, j] denote the subarray starting from index `i `to index j (excluding j). T(i, j) is the problem applied to this subarray (for example, for Reverse Pairs, T(i, j) will represent the total number of important reverse pairs for subarray nums[i, j] (excluding jth element))).</p><p>During each recursion of merge sort, we have two sorted subarrays, nums[i,mid], nums[j,mid] and the boundary lo and hi. For each i in the left sorted subarray, We need to find the first j_1 in the right part such that nums[i]&gt;2nums[j_1]. Then the solution to the current index i is j_1-i. We keep looping the left part and sum up the numbers.</p><p>Besides, we also need to sort the array. The basic idea is the same, but you need to be familiar with how to write merge sort without merge function and how to handle with the index correctly.</p><pre>def reversePairs(self, nums: List[int]) -&gt; int:<br>    # Not including the index hi<br>    def merge_sort(lo,hi):<br>        if lo +1&gt;= hi:<br>            return 0 <br>        # Memorize this<br>        # The mid is actually the begining of the right part of array<br>        mid = (hi-lo)//2 + lo<br>        count = merge_sort(lo,mid)+ merge_sort(mid,hi)<br>        j,t = mid, mid<br>        # cache used to store the temporay array in sorted order<br>        cache = [None]*(hi-lo)<br>        cache_i = 0<br>        for i in range(lo, mid):<br>            # Find the first j such that nums[i] &gt; 2*nums[j]<br>            while j &lt; hi and nums[i] &gt; 2*nums[j]:<br>                j = j+1<br>            # Add up the current number<br>            count += j - mid<br>            # Sort the array<br>            while t &lt; hi and nums[t] &lt; nums[i]:<br>                cache[cache_i] = nums[t]<br>                cache_i+=1<br>                t +=1<br>            cache[cache_i] = nums[i]<br>            cache_i += 1<br>        # Use cache to sort the original array<br>        for i in range(lo, t):<br>            if cache[i] is not None:<br>                nums[i] = cache[i-lo]<br>        <br>        return count</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=901f9d643aa0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Leetcode 854 K-Similar Strings]]></title>
            <link>https://medium.com/@jolyon129/854-k-similar-strings-7b68772217d0?source=rss-b88df0d46a35------2</link>
            <guid isPermaLink="false">https://medium.com/p/7b68772217d0</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[leetcode]]></category>
            <dc:creator><![CDATA[Jolyon]]></dc:creator>
            <pubDate>Sat, 29 Jun 2019 20:16:36 GMT</pubDate>
            <atom:updated>2020-04-12T01:27:44.541Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://leetcode.com/problems/k-similar-strings/solution/">https://leetcode.com/problems/k-similar-strings/solution/</a></p><p>This is a leetcode hard question, and I spent one whole day on this one. I tried two different ways to solve it:</p><ol><li>Cycle Decomposition by BFS and traceback</li><li>BFS in Search Space</li></ol><p>The former one is the reason why it took me so many time, and in the end, I still failed on some edge cases. The latter is pretty straightforward once we can find the optimal choice. Even though I still want to take some time to explain what is cycle decomposition. I hope this is useful for you.</p><h3>Cycle Decomposition (Failed)</h3><p>There is a mathematical idea behind this question. Each pair of an anagram is a pair of permutation and can be visualized by using a graph. This graph is called a <a href="https://en.wikipedia.org/wiki/Permutation_graph">permutation graph</a>. We can solve this question based on the mathematical idea, but it turned out the solution is very complicated and includes many edge cases. But it’s still worth to mention how we can do that.</p><p>For example, we have A=&#39;abacadc&#39;, B=&#39;bcdaaca&#39;. Let each character be a vertex in a graph and connect the edge from A to B, and then we have edges: A[0]-&gt;B[0],A[1]-&gt;B[1] and so on. This can be drawn as the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*H10p45Q6kkTsvhOF0h0JdQ.png" /></figure><p>If at position i, A[i] = B[i], then there should be a self-connected edge. Besides this, notice that for each cycle inside the graph, for example, a-&gt;b-&gt;c-&gt;a, it requires us to swap at least edge-1 times to remove all non-self-connected edge. This is an important observation we need.</p><p>To solve this question, we want to transform the whole graph so that there is no non-self-connected edge, which means we need to find an optimal way to break down the graph into different cycles and then the times of swapping we need are the sum of edge-1 in each cycle we get.</p><p>The process of break down the graph into cycles is called <a href="https://en.wikipedia.org/wiki/Cycle_decomposition">cycle decomposition</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/167/1*K7hn_ZZhgQH4P46hBMynfA.png" /></figure><p>where <em>Ck</em>​ is the lengths of the cycles in some cycle decomposition.</p><p>To make the #swap as small as possible, we need to find a way to do cycle decomposition so that we can maximize the number of cycles in a cycle decomposition. And this leads to a possible solution to the answer.</p><p>The core idea is to use BFS and traceback to find a minimal-sized cycle inside the graph, and once we find one we remove the edges of that cycle in the graph and try to find the second one.</p><p>However, after investing over 5 hours into this method, I still have some edge cases that cannot be solved. One of them is how to deal with multiple same-direction edges and when to stop adding edge into the queue of BFS. Anyway, I find it is not trivial to solve them and its kind of impossible to use this method in a real interviewing setting.</p><h3>Explore in Search Space (Succeed)</h3><p>Still, we have A=&#39;abacadc&#39;, B=&#39;bcdaaca&#39;.</p><p>We want to transform B into A, let i be the first index that A[i]!=B[i], and we need to find j so that B[j]==A[i] where i&lt;j and B[j]!=A[j]. Then we swap B[i] and B[j], plus one to the step we take, and we are one or two steps closer to the target A. The whole process could be visualized in a search tree space.</p><p>We know that for an n-size string B, we at most need to swap n–1 time to convert it to A. And there could be finite possible pair of (i, j​) at each root and taking any one of them will contribute to one child of the original string B.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MvTnZScOoc6P1ZQR7lzOHg.png" /></figure><p>By exploring this search tree space, we try to find the optimal path to minimize the step(the depth of the tree). We can use DFS or BFS to solve this, and BFS would give a better time complexity.</p><p>So, yeah, we can use BFS to solve it. No cycle decomposition.</p><pre>def kSimilarity(self, A: str, B: str) -&gt; int:<br>    if B == A:<br>        return 0<br>    queue = deque()<br>    visited = set()<br>    queue.append({&#39;value&#39;: B, &#39;idx&#39;: -1})<br>    visited.add(B)<br>    step = 0<br>    while queue:<br>        level_size = len(queue)<br>        for _ in range(level_size):                 <br>            node = queue.popleft()<br>            <br>            if node[&#39;value&#39;] == A:<br>                return step<br>            <br>            for i in range(node[&#39;idx&#39;]+1, len(A)):<br>                if A[i] != node[&#39;value&#39;][i]:<br>                    break<br>           <br>            new_lst = list(node[&#39;value&#39;])<br>            for j in range(i+1, len(B)):  <br>                if new_lst[j] == A[i] and A[j] != new_lst[j]:<br>                    new_lst[j], new_lst[i] = new_lst[i], new_lst[j]<br>                    new_str = &#39;&#39;.join(new_lst)<br>                    if new_str not in visited:<br>                        visited.add(new_str)<br>                        queue.append({&#39;value&#39;: new_str, &#39;idx&#39;: i})</pre><pre>new_lst[j], new_lst[i] = new_lst[i], new_lst[j]<br>        step += 1</pre><pre>return step</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7b68772217d0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Leetcode 730 Count Different Palindromic Subsequences]]></title>
            <link>https://medium.com/@jolyon129/leetcode-730-count-different-palindromic-subsequences-b04bc36b9874?source=rss-b88df0d46a35------2</link>
            <guid isPermaLink="false">https://medium.com/p/b04bc36b9874</guid>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[leetcode]]></category>
            <dc:creator><![CDATA[Jolyon]]></dc:creator>
            <pubDate>Sat, 29 Jun 2019 15:10:36 GMT</pubDate>
            <atom:updated>2019-07-11T04:07:23.889Z</atom:updated>
            <content:encoded><![CDATA[<p>Before we go down to how to solve it, there are some facts we need to realize.</p><p>First, what we are looking for are subsequences, not substrings. And there are only four kinds of characters for the construction of the input string.</p><p>We need to use dynamical programming to solve this. The question is how to find the optimal substructure. Let’s take a look at some trivial examples.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DCy7JsfG2CRyqiyveIBa5Q.png" /></figure><p>We observe that the palindrome will only take one of these following forms:a_a, b_b, c_c, d_d a, b, c, d, so we could try to find all of the numbers of the different types of palindrome and then add them up.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QEOUYuaS1Mcz-uHes20x5Q.png" /></figure><p>This isn’t over. We haven’t found the optimal substructure. Let’s try to find an optimal substructure for one of the forms, a_a.</p><p>To find the possible forms of palindrome, we need two other arrays to find the next position of occurrence of ‘a,’ ‘b,’ ‘c,’ ‘d.’ Let them be next[i][x] and prevous[j][x]. So next[i][&#39;a&#39;] would return the position of next occurrence of ‘a’ starting from the current position i(including i itself) We can precompute these two variables to speed up.</p><pre># Occur_position is a running array<br>occur_pos = [None] * 4<br>for i in range(N):<br>    # occur_postion[k] stores the position of item whose value is char &#39;a&#39;+k, and the one <br>    # which is the nearest one to the current position i!<br>    occur_pos[A[i]] = i<br>    prv[i] = occur_pos.copy()</pre><pre>occur_pos = [None] * 4<br>for i in range(N-1, -1, -1):<br>    occur_pos[A[i]] = i<br>    nxt[i] = occur_pos.copy()</pre><p>Moreover, then the optimal substructure should look like the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MKIsDwFZ0XhT_KQX-r1j9Q.png" /></figure><p>The code would be</p><pre>def dp(i,j):<br>            if memo[i][j] is not None:<br>                return memo[i][j]<br>            ans = 0<br>            if i &lt;= j:<br>                for x in range(4):<br>                    i0 = nxt[i][x]<br>                    j0=  prev[j][x]<br>                    if i0 is None or j0 is None:<br>                        continue<br>                    if i&lt;= i0 &lt;= j:<br>                        ans +=1<br>                    if i&lt;= i0 &lt; j0 &lt;=j:<br>                        ans += 1<br>                        ans += dp(i0+1, j0-1)<br>            ans %= modulo<br>            memo[i][j] = ans<br>            return ans</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b04bc36b9874" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>