<?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 levendlee on Medium]]></title>
        <description><![CDATA[Stories by levendlee on Medium]]></description>
        <link>https://medium.com/@levendlee?source=rss-e166e70515dc------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*vS5mzsMpacNA9_pcxonYUQ.jpeg</url>
            <title>Stories by levendlee on Medium</title>
            <link>https://medium.com/@levendlee?source=rss-e166e70515dc------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 02:16:58 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@levendlee/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[Efficient Compute for ML]]></title>
            <link>https://medium.com/@levendlee/efficient-compute-for-ml-8413b1a547e6?source=rss-e166e70515dc------2</link>
            <guid isPermaLink="false">https://medium.com/p/8413b1a547e6</guid>
            <dc:creator><![CDATA[levendlee]]></dc:creator>
            <pubDate>Tue, 09 Jan 2024 07:58:38 GMT</pubDate>
            <atom:updated>2024-01-21T22:14:16.306Z</atom:updated>
            <content:encoded><![CDATA[<p>Welcome to my site! Please feel free to leave comments on posts for discussions!</p><p>Based on my observation, data and compute are the biggest challenges of machine learning engineering.</p><ul><li>Data determines the ultimate quality of the model in theory.</li><li>Compute determines the ultimate quality of the model in practice.</li></ul><p>The recent success of large language models heavily relies on using massively large amount of compute on massively large amount of data to achieve the best model quality, aside from all the modeling researches and advancements.</p><p>For compute perspective, the challenges and popular solutions can be decomposed at different levels.</p><ul><li><strong><em>Reduce computation workload</em></strong></li><li><strong><em>Reduce parameters to be trained</em></strong></li><li><em>Selective</em>: Tune part of the layers. Keep others frozen.</li><li><em>Additive</em>: Tune added layers. Keep original frozen.</li><li><strong><em>LoRA</em></strong>: Low rank matrix adoption to be added on weights for fine-tuning.</li><li><strong><em>Prompt tuning</em></strong>: Fine-turning a soft-prompt, learning the embedding vector.</li><li><strong><em>Reduce parameters size</em></strong></li><li><strong><em>Keep model architecture</em></strong></li><li><strong><em>Change model architecture</em></strong></li><li><strong><em>Knowledge Distillation</em></strong>: Distill knowledge from large teacher model to small student model.</li><li><strong><em>Natural architecture search</em></strong>: Search model architecture with best quality under compute constraints.</li><li><strong><em>Reduce parameter precision</em></strong></li><li><strong><em>Mixed precision</em></strong>: Using reduced precision (FP16/BF16/FP8/…) floating-point representation to accelerate compute/io with dedicated tensor cores.</li><li><strong><em>Quantization</em></strong>: Using integer representation (INT8/INT4/INT2/…) with affine transformation to accelerate compute/io with dedicated tensor cores.</li><li><strong><em>Improve computation efficiency</em></strong></li><li><strong><em>Communication efficiency</em></strong></li><li><em>Inter-datacenter communication</em>: As far as I know, we haven’t reach to a state to use intra-datacenter communication. Even if we have, it should be completely over network and handled by distributed-system.</li><li><strong><em>Intra-datacenter, inter-node communication</em></strong>: Hardware solutions provided by vendors. For example, Nvidia provides <a href="https://www.nvidia.com/en-us/data-center/nvlink/">NVSwitch</a> to fulfill fast communication across multiple nodes.</li><li><strong><em>Intra-node communication</em></strong>: Hardware solutions provided by vendors. For example, Nvidia provides <a href="https://www.nvidia.com/en-us/data-center/nvlink/">NVLink</a> to fulfill fast communication across multiple GPUs inside the same node.</li><li><strong><em>Host-device communication</em></strong>: Software solutions provided by frameworks. For example, Google provides asynchronous device-host communication in XLA/TPU runtime to overlap with computation.</li><li><strong><em>Intra-device communication</em></strong>: Mostly handled by compilers or kernel engineers. The communication goes through memory at different levels or goes through registers.</li><li><strong><em>Compute &amp; Memory Efficiency</em></strong></li><li><strong><em>Reduce Online Computation</em></strong></li><li><strong><em>Improve parallelism</em></strong></li><li><strong><em>Model level parallelism</em></strong>: Implements parallelism at model level. <strong>Not only involves computation parallelism, but also involves memory efficiency and intra-node/inter-node communication.</strong></li><li>Data parallelism (zero data parallelism).</li><li>Model parallelism (tensor parallelism, pipeline parallelism).</li><li>FlexFlow.</li><li><strong><em>Software level parallelism</em></strong>: Implements parallelism at software level. <strong>Not only involves computation parallelism, but also involves memory efficiency.</strong></li><li>Programming language: CUDA. Triton. OpenCL. C++ threads.</li><li>Template expressions (Based on PLs): CUTLASS. Blaze. Eigen.</li><li>Precompiled libraries (Based on PLs): CuDNN. CuBLAS. CuSparse. MKL.</li><li>Compilers (Horizontal fusions. Tree reductions. etc): XLA. TensorRT. Triton.</li><li><strong><em>Hardware level parallelism</em></strong>: Executes parallelism defined at software.</li><li>Thread Blocks: Parallel/Sequential across different SMs.</li><li>Warps: Sequential on the same SM.</li><li>Threads: Parallel across the same warp.</li><li>SIMD: Parallel across the same thread.</li><li>Instruction: Intrinsics utilizing tensor cores on xPU improves compute efficiency.</li><li><strong><em>Improve memory efficiency</em></strong></li><li><strong><em>Model level memory efficiency</em></strong>:</li><li><em>Reduce parameters size</em> and <em>Reduce parameter precision</em> techniques applies here. As it reduced the total amount of data to be transferred.</li><li><em>Improve communication efficiency</em> techniques applies here. As it reduces the latency of data transfers.</li><li><strong><em>Software level memory efficiency</em></strong>:</li><li><strong><em>Vertical fusion</em></strong> techniques applies here. As it eliminates the need to transfer data by keeping it on or close to registers. Vertical fusion is mostly done by keeping intermediates on caches.</li><li><em>Model level parallelism</em> section defined pipeline parallelism and part of collective ops (e.g. reduce_scatter) are essentially doing vertical fusions.</li><li><em>Software level parallelism</em> section defined techniques can do fusions.</li><li>Programming language: Developer explicitly defined manual fusion.</li><li>Template expressions (Based on PLs): Developer implicitly defined manual fusion with the help of C++ templates.</li><li>Precompiled libraries (Based on PLs): Pre-defined and implemented fusions.</li><li>Compilers (Vertical fusion): Automatic fusions through pattern matching.</li><li><strong><em>Compute/Memory overlap</em></strong> techniques applies here. As it hides the latency of data transfer by overlapping it with compute. It can be applied at multiple levels through different ways. Examples are:</li><li><strong><em>Asynchronous I/O</em></strong> (d2d, h2d, d2h) with the help of compiler/runtime scheduling.</li><li><strong><em>Software pipeline (SW Prefetching)</em></strong> with the help of compiler optimization or developer manual optimization.</li><li><strong><em>HW Prefetching</em></strong> using instructions/modifiers provided the underlying hardware. It can also be done automatically at hardware level.</li><li><strong><em>Hardware level memory efficiency</em></strong>:</li><li><strong><em>Caching</em></strong> avoids reloading data from memory. Improves efficiency. It is about transparent caching that isn’t managed by developers. (AKA, not including shared memory, but includes L1,L2 cache).</li><li>Hardware specific optimization tricks can make read/write faster. Examples are:</li><li><strong><em>Memory coalescing</em></strong>: Within each wrap, having multiple threads accessing continuous <em>global memory</em> at the same time, and coalesce the memory request.</li><li><strong><em>Memory swizzling</em></strong> and <strong><em>Bank conflicts</em></strong>, Within each wrap, avoid having multiple threads accessing different <em>shard memory</em> bank at the same time trough swizzling.</li></ul><p>Blogs tend to have a very common structure. Upsidedown is not here to repeat old formulas as we, the humans, do not fit into the same boxes. This Theme Design is not here for certainty but freshness. It is here to invert things, proposing a brand new way to convey personal blogs. More than being yet another WordPress blog theme, Upsidedown is designed with the Site Editor and it is full of ambition. Maybe it is the best choice for your blog.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1/0*449Cw1PvbDg23JF3" /></figure><p><em>Originally published at </em><a href="https://levendlee.com/2024/01/08/efficient-compute-for-ml/"><em>http://levendlee.com</em></a><em> on January 9, 2024.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8413b1a547e6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Generative AI with Large Language Models 1/3]]></title>
            <link>https://medium.com/@levendlee/generative-ai-with-large-language-models-1-3-e54d87d78bd8?source=rss-e166e70515dc------2</link>
            <guid isPermaLink="false">https://medium.com/p/e54d87d78bd8</guid>
            <dc:creator><![CDATA[levendlee]]></dc:creator>
            <pubDate>Tue, 12 Sep 2023 05:07:33 GMT</pubDate>
            <atom:updated>2023-12-19T04:34:48.266Z</atom:updated>
            <content:encoded><![CDATA[<h3>Components</h3><h3>1. Tokenization</h3><p>Converts words into tokens using a specific tokenizer.</p><h3>2. Embedding</h3><h4>2.1 Input/Output Embedding</h4><ul><li>Converts tokens into high-dimensional vectors using a fixed representation learned through training.</li><li>Each token occupies a unique location, related tokens are located close to each other.</li></ul><h4>2.2 Positional encoding</h4><ul><li>Input/output tokens are processed in parallel.</li><li>Adds a positional encoding to each token embedding to preserve the information on word orders.</li></ul><h3>3. Attention</h3><ul><li>The attention layer analyzes the relationships between different tokens in the sequence in parallel to capture the contextural dependencies.</li><li>The multi-head attention layer combines multiple attention layers (typically 12–100) to train and run in parallel. With randomly initialized weights, different attentions will learn different aspects of the languages.</li><li>Self attention has Q, K, V as the same before projection. Cross attention has Q, K as the same before projection, V as different.</li></ul><h3>4. Feed-Forward</h3><ul><li>Takes a concatenation of the multi-head attention layer outputs to predict the probability of all tokens.</li><li>Normalizes output as probabilities using softmax.</li></ul><h3>5. Encoder</h3><ul><li>Stacks of a multi-head attention layer (self-attention) followed by a feed foward layer on input embeddings.</li><li>Creates a deep representation of the structure and meaning of the input sequence.</li></ul><h3>6. Decoder</h3><ul><li>Stacks of two multi-head attention layers (self-attention + cross-attention) followed by a feed-forward layer on output embeddings and encoder outputs.</li><li>Create a prediction of output probabilities.</li></ul><h3>Functions</h3><ul><li>A starter sequence token is added to the input of the decoder.</li><li>Triggers the decoder to predict the next token based on contextual understandings of generated output tokens (self-attention) and input tokens (cross-attention).</li><li>Passes the output token back to the input of the decoder to trigger the generation of the next token until the model predicts an end-of-sequence token.</li></ul><h3>References</h3><h3>Workflow</h3><h3>Prompt Engineering</h3><ul><li>Prepends content of inputs to direct the model to provide the desired outputs.</li><li>Zero/One/Few-shot inference: Provide zero/one/few completed examples in the prompt.</li><li>In-context learning (ICL).</li><li>Constraint is the model’s context window, the amount of memory available to use for prompt. Usually, 5/6 shots are enough.</li></ul><h3>Generative Configuration</h3><ul><li>Max number of new tokens. (Outputs are also limited by the terminating conditions)</li><li>Greedy vs random sampling on output tokens.</li><li>Top-K: Choose only from the top k tokens with the highest probability.</li><li>Top-P: Choose only from top tokens that the total combined probability &lt;= P.</li><li>Temperature: A scaling factor applied within the final softmax layer that impacts the probability distribution of the next token.</li><li>Low-temperature results in reduced variability.</li><li>High-temperature results in increased randomness. Probability is more evenly spread out among candidates, making outputs more creative.</li></ul><h3>Generative AI Lifecycle</h3><h3>Example 1</h3><ol><li>Scope: Define the use case.</li><li>Select: Choose an existing model or pretrain your own.</li><li>Adapt and align: Prompt engineering / Fine tuning / Align with human feedback. Evaluate.</li><li>Application integration: Optimize and deploy the model for inference. Augment model and build LLM-powered applications.</li></ol><h3>Example 2</h3><ol><li>Prep data.</li><li>Select a pre-trained model.</li><li>Fine-tuning with labeled data.</li><li>Distillation with unlabeled data.</li><li>Service with distilled student model.</li></ol><h3>Variants of Transformers</h3><p>ArchitectureExamplesTraining MethodTraining ObjectiveBest Use Cases</p><p>Encoder only (Autoencoding models)</p><p>BERT</p><p>Masked language modeling (MLM): input tokens are randomly masked; Bi-directional representation of input token: the model has an understanding of full context.</p><p>Predict the masked tokens to reconstruct the original sentence (Denoising objective)</p><p>Sentence classification tasks: sentiment analysis; Token-level tasks: named entity recognition word classification.</p><p>Decoder only (Autoregressive models)</p><p>GPT, BLOOM, PaLM, LLaMA</p><p>Causal language modeling (CLM): masks the input sequence and can only see the input tokens leading up to the token in question; Context is unidirectional.</p><p>Predict the next token based on the previous sequence of tokens.</p><p>Text generation. Show strong zero-short inference abilities, an can often perform a range of tasks well.</p><p>Encoder-decoder models</p><p>T5, MUM</p><p>Pre-train the encoder using span corruption, which makes a random sequence of input tokens. Those mass sequences are then replaced with a unique sentinel token; Sentinel tokens are special tokens added to the vocabulary, but do not correspond to any actual work from the input text; The decoder is then taken with reconstructing the mask token sequences auto-regressively.</p><p>Predict the original token (the output is the sentinel token followed by the predicted tokens).</p><p>Translation; Summarization; Question-answering.</p><h3>Challenges to train LLMs</h3><h3>Memory requirement</h3><ul><li>Quantization.</li><li>Partitions with multi-GPU strategies.</li><li>Data parallel training (DDP).</li><li>Model parallel training (ZeRO, Zero redundancy optimizer).</li><li>Fully sharded data parallel.</li></ul><h3>Scaling laws of LLMs</h3><ul><li>Power law relationship — training loss vs compute/dataset/model size.</li><li>From DeepMind Chinchilla paper:</li><li>Larger model might not lead to better results.</li><li>Without sufficient training data, the models could be under-trained.</li><li>The compute optimal # of tokens is 20x the # of model parameters.</li></ul><p>Follow codelab to run all cells on dialogue summarization examples.</p><p>Transformer models and tokenizers from : <a href="https://github.com/huggingface">Hugging face</a></p><p><em>Originally published at </em><a href="https://levendlee.wordpress.com/2023/09/12/generative-ai-with-large-language-models-1-3/"><em>http://levendlee.wordpress.com</em></a><em> on September 12, 2023.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e54d87d78bd8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dynamic Programming — The Intervals]]></title>
            <link>https://medium.com/@levendlee/dynamic-programming-the-intervals-afd4c4f72a05?source=rss-e166e70515dc------2</link>
            <guid isPermaLink="false">https://medium.com/p/afd4c4f72a05</guid>
            <dc:creator><![CDATA[levendlee]]></dc:creator>
            <pubDate>Sat, 04 Jan 2020 20:53:25 GMT</pubDate>
            <atom:updated>2023-12-19T04:40:10.979Z</atom:updated>
            <content:encoded><![CDATA[<h3>Dynamic Programming — The Intervals</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/0*FUSakQU3k0UTEua3.jpg" /></figure><p>The definition of dynamic programming int the textbook is solving a complex problem by breaking it down into simple problems. However, I think it is much more like mathematical induction, proving the basic conclusion and proving the relationship of the complex result and the simple result.</p><p>Most dynamic programming problems are in 1D and 2D.</p><ul><li>For the easy and medium problems, the 1D dynamic programming is mostly based on the intervals <strong><em>starting at the origin </em></strong>and ending at any indices, and the 2D dynamic programming is mostly based on the areas <strong><em>staring at the origin </em></strong>and ending at any point.</li><li>For the hard problems, there could be 2D and 3D dynamic programmings. The 2D dynamic programming can be based on the intervals s<strong>tarting and ending at any indices.</strong></li></ul><p>Here are 2 examples of dynamic programming based on intervals:</p><p><a href="https://leetcode.com/problems/burst-balloons/">312. Burst Balloons</a> <a href="https://github.com/levendlee/leetcode/blob/master/c%2B%2B/312-H.cpp">My solution.</a></p><p>First of all, as the bursting can be in any order, we cannot use 1D dp based on intervals starting at the origin. Consequently, we shall use 2D dp based on intervals starting at any indices.</p><p>Secondly, we notice that based on the order of bursting, the left side and the right side of the target balloons can change. Furthermore, the left side and right side of the target intervals can change. This will make the result of the smaller intervals unusable for the larger intervals.</p><p>To fix this issue, we take the following method:</p><ul><li>assume the left side and the right side of the interval are not burst</li><li>try all the balloons as the last one to burst</li><li>calculate the reward of bursting the left subinterval and the right subinterval, plus the reward of bursting this balloon with the left side and right side of the entire interval.</li></ul><p>In this method, <em>the entire interval and subintervals have fixed left and right side, the result won’t change and are reusable</em>.</p><p>The coding part is a 2D dp. dp[i][j] stands for the maximum reward of bursting all the balloons between i (inclusive) and j (inclusive). The dp needs to start small intervals and concludes to large intervals, as the <em>current result is build based on the previous result of small intervals</em>.</p><p><a href="https://leetcode.com/problems/minimum-cost-to-merge-stones/">1000. Minimum Cost to Merge Stones</a> <a href="https://github.com/levendlee/leetcode/blob/master/c%2B%2B/1000-H.cpp">My solution.</a></p><p>Similarly, the merging can be in any order, we shall use 2D dp based on intervals starting at any indices.</p><p>Secondly, we notice that based on the order of merging, the left stones can change. To fix this issue, we take the following method:</p><ul><li>assume all the intervals are merged as much as possible</li><li>try all the left subintervals that could be merged into the first stone</li><li>calculate the reward of merging the left subinterval and the right subinterval, and the rewards of merging the left stones if then can be merged.</li></ul><p>In this method, the entire interval will always be merged as much as possible and the merge will always happen with stones of size K. <em>Even though we don’t know what stones are left at the final merge but we do know that the sum of the stones will be the sum of the interval at the original state.</em></p><p>The coding part is a 2D dp. Similar to 312.</p><p><em>Originally published at </em><a href="https://levendlee.wordpress.com/2020/01/04/dynamic-programming-the-intervals/"><em>http://levendlee.wordpress.com</em></a><em> on January 4, 2020.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=afd4c4f72a05" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Binary Search — The Limits]]></title>
            <link>https://medium.com/@levendlee/binary-search-the-limits-2c5af37b6c1e?source=rss-e166e70515dc------2</link>
            <guid isPermaLink="false">https://medium.com/p/2c5af37b6c1e</guid>
            <dc:creator><![CDATA[levendlee]]></dc:creator>
            <pubDate>Thu, 26 Dec 2019 20:47:04 GMT</pubDate>
            <atom:updated>2023-12-19T04:39:44.298Z</atom:updated>
            <content:encoded><![CDATA[<h3>Binary Search — The Limits</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/0*fDC1gaEdJMBhXF05.jpg" /></figure><p>There are lots of hard difficulty problems in leetcode that is using binary search for a simple solution. The common pattern of these problems are 1) the sequence is sorted. 2) there are limits (explicit or implicit) to the desired output. 3) there is a target (explicit or implicit) that can be binary searched and checked against the limits. One common use case scenario is <strong><em>min-max problems</em></strong>.</p><p><a href="https://leetcode.com/problems/kth-smallest-number-in-multiplication-table/">668. Kth Smallest Number in Multiplication Table</a></p><ul><li>The multiplication table is sorted row-wise / column-wise.</li><li>The limit is a known ranking.</li><li>The target is the unknown upper bound of the first kth elements.</li></ul><p>This entry was posted in <a href="https://levendlee.wordpress.com/category/computer-science/">Computer Science</a>, <a href="https://levendlee.wordpress.com/category/computer-science/data-structures-algorithms/">Data Structures &amp; Algorithms</a> on by .</p><p><em>Originally published at </em><a href="https://levendlee.wordpress.com/2019/12/26/binary-search-the-limits/"><em>http://levendlee.wordpress.com</em></a><em> on December 26, 2019.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2c5af37b6c1e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Sliding Window Problem]]></title>
            <link>https://medium.com/@levendlee/the-sliding-window-problem-690147b8043f?source=rss-e166e70515dc------2</link>
            <guid isPermaLink="false">https://medium.com/p/690147b8043f</guid>
            <dc:creator><![CDATA[levendlee]]></dc:creator>
            <pubDate>Thu, 26 Dec 2019 20:11:31 GMT</pubDate>
            <atom:updated>2023-12-19T04:38:55.458Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/200/0*OwSrg2QgOnH9HRgJ.jpg" /></figure><p>The sliding window problem commonly presents a sequence and asks a property a subsequence that satisfied certain restrictions. The subsequence can be consecutive or non-consecutive. The unknown property could be size, sum, max/min, etc. Similarly, the known restriction could be size, sum, max/min, etc. One important character of the sliding window problem is that the subsequence is in order.</p><p>Most sliding window problems can be solved using a deque, using two pointers or using a dynamic programming approach.</p><p>Besides, taking accumulative sums of the input sequence is a common preprocessing step, changing the problem of sums into the problem of differences.</p><ul><li>Two pointers: Keep two pointers that mark the start and the end of the sliding window. <strong>All elements in the current subsequence are candidates for future start points.</strong> This is applied <strong><em>when both sides of the sliding window matter.</em></strong></li><li>Deque: Keep a deque that is the curial elements that could be both the start/end of the sliding window. Compared to the two-pointers method, <strong><em>not all elements in the current subsequence are candidates for future start points</em></strong>. This is applied <strong><em>when both sides of the sliding window matter.</em></strong></li><li>Dynamic programming: Keep a 1d array that marks the end of the sliding window and a specific summary of all the subsequences ends with the specific element. This is applied <strong><em>when only one side of the sliding window matter.</em></strong></li></ul><p><a href="https://leetcode.com/problems/shortest-subarray-with-sum-at-least-k/">862. Shortest Subarray with Sum at Least K (Hard)</a></p><p>This problem uses a deque. The deque maintains the possible locations of <em>the start/end of the subsequence </em>. The mechanism to determine a node is no longer good for a start is that</p><ol><li>The current subsequence already has a sum larger or equal to K, leaving it as a candidate cannot find a shorter subsequence.</li><li>The current visiting node is smaller or equal to an old node. The old node cannot do better than the new node.</li></ol><p>With the restriction of rule 2, the dequeue is intrinsically keeping an increasing sequence.</p><p><em>Originally published at </em><a href="https://levendlee.wordpress.com/2019/12/26/the-sliding-window-problem/"><em>http://levendlee.wordpress.com</em></a><em> on December 26, 2019.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=690147b8043f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Binary Search Tree]]></title>
            <link>https://medium.com/@levendlee/binary-search-tree-77641096afa7?source=rss-e166e70515dc------2</link>
            <guid isPermaLink="false">https://medium.com/p/77641096afa7</guid>
            <dc:creator><![CDATA[levendlee]]></dc:creator>
            <pubDate>Thu, 26 Dec 2019 16:46:00 GMT</pubDate>
            <atom:updated>2023-12-19T04:38:22.834Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/200/0*vLMOkLwSJ31zYRYP.jpg" /></figure><p>Most tree problems can be solved using recursions, using O(N) time complexity and O(logN) space complexity. based on the pattern that each tree can be divided into root, a left subtree, and a right subtree, and the subtrees are essentially trees again.</p><p>For a binary search tree, its main property is that all the nodes on the left subtree are smaller than the root node, and all the nodes on the right subtree are larger than the root node. This gives us the opportunity to visit one of the subtrees, instead of both of the subtrees, achieving O(logN) time complexity and O(logN) space complexity.</p><p><a href="https://leetcode.com/problems/insert-into-a-binary-search-tree/">701. Insert into a Binary Search Tree</a></p><p>Insert to left subtree if the root value is larger than the target, insert to right subtree if the root value is smaller than the target, and create a single node tree is the tree is empty. Update the left pointer / right pointer to points to the tree after insertion.</p><p><a href="https://leetcode.com/problems/delete-node-in-a-bst/">450. Delete Node in a BST</a></p><p>Delete in the left subtree if the root value is larger than the target, delete in the right subtree if the root value is smaller than the target, and delete the root node if it is equal to the target.</p><p>When the root is deleted, if the original tree has only one node, return an empty tree; if the original tree has only one child, promote the child as the root; if the original tree has two children, promote the right child as the root, find the successor of the deleted root, and demote the left child as the left child of the successor.</p><p><a href="https://leetcode.com/problems/split-bst/">776. Split BST</a></p><p>Find the root of the smaller tree and the larger tree on each level of recursion. When the root is larger than the target, the smaller nodes of the left subtree is the smaller nodes of the current tree, and the root is calculated from the recursion; the larget nodes of the left subtree, the root, and the right subtree is the larger nodes of the current tree, and the root is the current node. Vice versa.</p><p><em>Originally published at </em><a href="https://levendlee.wordpress.com/2019/12/26/the-bst-problems/"><em>http://levendlee.wordpress.com</em></a><em> on December 26, 2019.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=77641096afa7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Calculator Problem]]></title>
            <link>https://medium.com/@levendlee/the-calculator-problem-af764c6a1359?source=rss-e166e70515dc------2</link>
            <guid isPermaLink="false">https://medium.com/p/af764c6a1359</guid>
            <dc:creator><![CDATA[levendlee]]></dc:creator>
            <pubDate>Mon, 23 Dec 2019 17:41:18 GMT</pubDate>
            <atom:updated>2023-12-19T04:37:34.359Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/200/0*2mGatAgdOlo3IX_X.jpg" /></figure><p>The calculator problem is all about evaluating a mathematical expression. It is essentially a mini interpreter (including a lexer and a parser).</p><p>A general method to handle these problems is writing a mini interpreter from lexing, parsing, AST generation, and evaluation. However, it is still too much code for a technical interview, especially given the specific scenarios, lots of these codes will be redundant.</p><p><a href="https://leetcode.com/problems/basic-calculator/">224. Basic Calculator</a></p><p>This problem includes parentheses, + and — operators. There is no negative operator and no * or / operators. The input is guaranteed to be well-formed.</p><p>Based on the conditions, we need to evaluate the subexpression inside parentheses independently by using stacks.</p><ul><li><strong><em>Keep a stack of the intermediate results of the current expressions/subexpressions.</em></strong></li><li><strong><em>Keep a stack of the operators of the expressions/subexpressions.</em></strong></li></ul><p>The strategy is evaluating from left to right.</p><p>Without parentheses, calculate the result with the left-hand side value (as the current result, from the top of the value stack), the operator (from the unvisited chars), and the right-hand side value (from the unvisited chars). Replace the top of the value stack with the calculated value (as the new current result).</p><p>At parentheses, push the operator and the initial value (0) to the stacks when we start a subexpression. Pop the operator and the final result from the stacks when we finish a subexpression. Update the current result with the operator and the operand (which is the result of the subexpression) and move on.</p><p><a href="https://leetcode.com/problems/basic-calculator-ii/">227. Basic Calculator II</a></p><p>Compared to (1), this problem doesn’t include parentheses but includes * or / operators. The input is still guaranteed to be well-formed.</p><p>Based on the conditions, we need to evaluate the * or / operators firstly and the + or — operator secondly by using lists. <strong><em>We can think all the expressions contain and only contains * or / operators as subexpressions.</em></strong> It is much similar to (2), but the expressions won’t be nested and we won’t need to use stacks.</p><p><a href="https://leetcode.com/problems/basic-calculator-iii/">772. Basic Calculator III</a></p><p>Compared to (1) and (2), this problem is the most common case. It includes * or / operators, includes parentheses and includes negative numbers.</p><p>The strategy is to keep two stacks, one as the numbers, the other as the operators, including ‘(‘ and ‘)’. Whenever we meet operators, we first clear the operator with higher precedence: pop the two operands from the number stack, one operator from the operator stack, do the calculation, and push the result to the number stack. We can keep doing this until there is no precedence. It is intrinsically evaluating the expressions in a bottom-up approach.</p><ul><li>For the + and — operators, the precedent calculations will be +, -, * and / operators on the left-hand side until parentheses.</li><li>For the * and / operators, the precedent calculations will be * and / operators on the left-hand side until parentheses.</li></ul><p>Besides, a the end of a pair of parentheses and at the end of the expression, we need to handle the uncleared calculation.</p><p>For negative numbers, simply keep a status mark, at the beginning of the expression, or a subexpression surrounded by parentheses, or right after an operator, the next minus operator must be a unary operator, in other words, the negative sign. We can simply add a zero before the sign, transferring -x to 0-x, making the minus operator as a binary operator again and following the rules.</p><p><a href="https://leetcode.com/problems/basic-calculator-iv/">770. Basic Calculator IV</a></p><p>It is quite similar to (2). Except that the operands are polynomial terms instead of integers. The trick here is to design polynomial classes and add operator overloading. It is relatively easy to do in object-oriented languages, such as c++ / python.</p><p><em>Originally published at </em><a href="https://levendlee.wordpress.com/2019/12/23/calculator-problem/"><em>http://levendlee.wordpress.com</em></a><em> on December 23, 2019.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=af764c6a1359" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Topology Sort]]></title>
            <link>https://medium.com/@levendlee/topology-sort-9f75e62ed654?source=rss-e166e70515dc------2</link>
            <guid isPermaLink="false">https://medium.com/p/9f75e62ed654</guid>
            <dc:creator><![CDATA[levendlee]]></dc:creator>
            <pubDate>Sun, 01 Dec 2019 21:37:15 GMT</pubDate>
            <atom:updated>2023-12-19T04:29:07.681Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/200/0*Us9jTWX1GoR8Crjl.jpg" /></figure><p><a href="https://leetcode.com/problems/sort-items-by-groups-respecting-dependencies/">Leetcode 1203 : Sort Items by Groups Respecting Dependencies</a></p><p>This question is a typical topology sort question. It applies two restrictions on the result:</p><ol><li>the order of the items</li><li>the items in the same group must be adjacent to each other</li></ol><p>If we decompose the first restriction into two parts, it becomes</p><ul><li>the order of the items in the same group</li><li>the order of the items in the different group</li></ul><p>Based on the second restriction, we must put the items in the same group together. If item A is in group C, item B is in group D, and item A comes before item B, it means group C comes before group D. The two restrictions can further be reinterpreted as:</p><ol><li>the order of the items in the same group</li><li>the order of the groups</li></ol><p>It breaks down into two topology sorts. The first sort figures out the order of the items in the same group and the second sort figures out the order of the groups. Then we concentrate all the groups together and get the final result.</p><p>There is a small problem with the items that have no group. It can be solved by assigning all of them a unique group id so that they can be considered a group with only one item.</p><p>Here is <a href="https://github.com/levendlee/leetcode/blob/master/c++/1203-H.cpp">the link</a> to my C++ implementation. Beat 98.4% on runtime and 100.0% on memory usage.</p><p>This entry was posted in <a href="https://levendlee.wordpress.com/category/computer-science/">Computer Science</a>, <a href="https://levendlee.wordpress.com/category/computer-science/data-structures-algorithms/">Data Structures &amp; Algorithms</a> on by .</p><p><em>Originally published at </em><a href="https://levendlee.wordpress.com/2019/12/01/test/"><em>http://levendlee.wordpress.com</em></a><em> on December 1, 2019.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9f75e62ed654" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>