<?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 Aditya Bhatia on Medium]]></title>
        <description><![CDATA[Stories by Aditya Bhatia on Medium]]></description>
        <link>https://medium.com/@tuubow?source=rss-8da661b0df2f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*PxgUk6yGH0yhf-WKokrcuQ.jpeg</url>
            <title>Stories by Aditya Bhatia on Medium</title>
            <link>https://medium.com/@tuubow?source=rss-8da661b0df2f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 10:05:11 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tuubow/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[Demystifying Kubernetes Operators]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@tuubow/demystifying-kubernetes-operators-36c695dbc2ce?source=rss-8da661b0df2f------2"><img src="https://cdn-images-1.medium.com/max/1582/1*D3GaEkGVKldiNo0fqoCpCg.png" width="1582"></a></p><p class="medium-feed-snippet">This article explores Kubernetes Operators, how they work, and the practical scenarios where they can make life easier for k8s application&#x2026;</p><p class="medium-feed-link"><a href="https://medium.com/@tuubow/demystifying-kubernetes-operators-36c695dbc2ce?source=rss-8da661b0df2f------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@tuubow/demystifying-kubernetes-operators-36c695dbc2ce?source=rss-8da661b0df2f------2</link>
            <guid isPermaLink="false">https://medium.com/p/36c695dbc2ce</guid>
            <category><![CDATA[kubernetes-operator]]></category>
            <category><![CDATA[controller]]></category>
            <category><![CDATA[custom-resource]]></category>
            <category><![CDATA[kubernetes]]></category>
            <dc:creator><![CDATA[Aditya Bhatia]]></dc:creator>
            <pubDate>Fri, 31 Jan 2025 15:22:07 GMT</pubDate>
            <atom:updated>2025-01-31T15:22:07.295Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Designing Fault-Tolerant Distributed Machine Learning Frameworks for GPU Clusters at Scale]]></title>
            <link>https://medium.com/@tuubow/designing-fault-tolerant-distributed-machine-learning-frameworks-for-gpu-clusters-at-scale-6b9836ff827f?source=rss-8da661b0df2f------2</link>
            <guid isPermaLink="false">https://medium.com/p/6b9836ff827f</guid>
            <category><![CDATA[distributed-ml]]></category>
            <category><![CDATA[mlops]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[fault-tolerance]]></category>
            <category><![CDATA[gpu-cluster]]></category>
            <dc:creator><![CDATA[Aditya Bhatia]]></dc:creator>
            <pubDate>Sat, 28 Dec 2024 23:48:44 GMT</pubDate>
            <atom:updated>2024-12-28T23:48:44.862Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Introduction</strong></p><p>Machine Learning (ML) tasks, especially those involving deep learning models, have seen rapid growth in complexity in recent years. As dataset sizes continue to explode and models become more sophisticated, distributed training on large GPU clusters has emerged as the de facto strategy to handle the scale and speed required for modern workloads. However, training at scale introduces new challenges, particularly around fault tolerance and robustness. GPU failures, network issues, straggler tasks, and other problems can degrade model performance, reduce throughput, and compromise the reliability of results.</p><p>In this article, I will explore how to design and implement fault-tolerant distributed ML frameworks for large GPU clusters. I will discuss the primary issues that arise when training at scale, including GPU failures and bottlenecks, along with mechanisms to mitigate downtime and optimize recovery. Techniques such as checkpointing, replication, speculative execution, and system-level design choices all play a role in creating systems that can handle failures gracefully.</p><p><strong>The Importance of GPU Clusters</strong></p><p>The primary drivers for distributed GPU training are performance and scale. Training a single model on massive datasets (e.g., billions of data points, large-scale image or text corpora) may take days or even weeks on a single GPU. By distributing the workload across multiple GPUs, we can significantly reduce the training time, sometimes from days to just hours . Furthermore, certain model architectures — such as those in computer vision or natural language processing — are so large that they do not even fit into the memory of a single GPU. Distributing such training across multiple accelerators is not only a convenience; it is a necessity.</p><p>However, as the number of GPUs in a cluster grows from tens to hundreds or thousands, failures become statistically inevitable . Single-GPU failures, network downtime, memory errors, and communication bottlenecks can bring the entire training process to a standstill. In a large-scale environment, the probability that at least one GPU or node fails during training is significantly higher than in a small-scale setup. Hence, designing robust distributed ML frameworks that continue operation despite partial failures becomes crucial.</p><p><strong>Key Challenges in Distributed Training at Scale</strong></p><p>1. <strong>GPU Failures</strong></p><p>GPUs are not immune to hardware failures. Prolonged usage at high computational intensities, power surges, or manufacturing defects can cause a GPU to fail mid-training.</p><p>2. <strong>Network Bottlenecks and Failures</strong></p><p>Distributed ML typically requires frequent communication of gradients or model parameters over the network (e.g., using AllReduce or parameter servers). Any delay or failure in this communication layer can slow down the training process significantly, or even halt it if the communication is essential for each iteration.</p><p>3. <strong>Straggler Tasks</strong></p><p>Even if all GPUs remain functional, some tasks might take longer to complete due to local resource contention, suboptimal code paths, or dataset load imbalances. These “stragglers” can stall the rest of the job, particularly in synchronous training setups.</p><p>4. <strong>Data Corruption</strong></p><p>Disk failures or memory corruption may compromise stored model checkpoints, or partial training data may get corrupted in transit. This leads to unreliable or lost model states.</p><p>5. <strong>Scalability vs. Performance Trade-off</strong></p><p>While fault-tolerant designs are necessary, introducing too many redundant processes, frequent checkpoints, or replication can lead to performance overhead due to communication delays between different systems. Finding the right balance is a key system design challenge.</p><p><strong>Fault-Tolerance Mechanisms: Minimizing Downtime</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z5euT1nXfo2Xn9GW6gw79g.png" /></figure><p>A variety of techniques exist to handle GPU and system failures in distributed ML:</p><p>1. <strong>Checkpointing</strong></p><p>Perhaps the most commonly used technique is checkpointing. At periodic intervals, the system saves the state of the model (weights, optimizer states, and other relevant variables) to persistent storage (e.g., a distributed file system). Should a failure occur, training can resume from the last saved checkpoint rather than restarting from scratch. Although checkpointing introduces overhead, advanced strategies — such as asynchronous or incremental checkpointing — can reduce the performance penalty.</p><p>2. <strong>Replication</strong></p><p>In replication-based approaches, workers or parameter servers maintain multiple copies of key data or model states. This can be done at the parameter-server level, where multiple servers hold the same global parameters and can take over if the primary server fails. Alternatively, entire workers can be replicated to provide redundancy — though this is costly in terms of compute resources. Replication helps ensure that progress is not lost if one replica fails and allows the training to continue and still be available if one of the worker node fails.</p><p>3. <strong>Erasure Coding</strong></p><p>Erasure coding is another approach used in distributed systems for fault tolerance. Instead of storing complete replicas, the system stores coded fragments of data across multiple nodes such that any subset of fragments can reconstruct the original data. This technique can be more storage-efficient than full replication while still offering protection against multiple node failures .</p><p>4. <strong>Failover and Live Migration</strong></p><p>Some distributed systems allow for live migration of tasks from a failed GPU or node to a healthy one. A resource manager (e.g., Kubernetes, Yarn, or Mesos) can detect failures and reassign tasks automatically. This ensures that a single node’s failure does not prevent the job from completing.</p><p>5. <strong>Speculative Execution</strong></p><p>Originally popularized in systems like MapReduce , speculative execution runs backup copies of slow or potentially failing tasks on additional nodes. Whichever copy finishes first is used, effectively mitigating the impact of stragglers or silent errors. While mostly beneficial in data processing frameworks, a similar approach can apply in synchronous ML training, particularly when stragglers hold up collective operations.</p><p><strong>Conclusion</strong></p><p>As deep learning continues to expand into complex domains — from computer vision and natural language processing to reinforcement learning and beyond — distributed training on large GPU clusters is increasingly necessary. Yet, with greater scale comes greater complexity: GPU hardware errors, software bugs, network failures, and data corruption can all introduce bottlenecks or halt the training pipeline. Consequently, designing fault-tolerant and robust distributed ML frameworks is essential.</p><p><strong>Checkpointing</strong>, <strong>speculative execution</strong>, <strong>replication</strong>, and <strong>robust cluster management</strong> serve as the key building blocks to maintain high availability and resiliency. As HPC and ML worlds converge, novel research and system designs are emerging to handle partial failures without halting or significantly delaying global training progress. Meanwhile, real-world production use cases demand cost-effective solutions that balance overhead with resilience.</p><p>By architecting systems from the ground up to handle failures gracefully and by continuously monitoring and optimizing these systems in real-world cluster environments, organizations can significantly reduce training downtime, improve iteration speed, and ultimately accelerate innovation.</p><p><strong>References</strong></p><p>1. Dean, J., Corrado, G., Monga, R., Chen, K., et al. (2012).</p><p><strong>Large Scale Distributed Deep Networks</strong>. <em>Advances in Neural Information Processing Systems (NeurIPS)</em>.</p><p>2. Schroeder, B., &amp; Gibson, G. (2007).</p><p><strong>Understanding Failures in Petascale Computers</strong>. <em>Journal of Physics: Conference Series, 78(1)</em>.</p><p>3. Agrawal, D., El Abbadi, A., &amp; Steinke, R. (1997).</p><p><strong>Eager Execution in Parallel and Distributed Databases</strong>. <em>Distributed and Parallel Databases, 5(3)</em>.</p><p>4. Plank, J. S., et al. (2009).</p><p><strong>A Performance Evaluation and Examination of Open-Source Erasure Coding Libraries for Storage</strong>. <em>In Proceedings of the 7th Conference on File and Storage Technologies (FAST)</em>.</p><p>5. Dean, J., &amp; Ghemawat, S. (2008).</p><p><strong>MapReduce: Simplified Data Processing on Large Clusters</strong>. <em>Communications of the ACM, 51(1)</em>.</p><p>6. Hindman, B., Konwinski, A., Zaharia, M., et al. (2011).</p><p><strong>Mesos: A Platform for Fine-Grained Resource Sharing in the Data Center</strong>. <em>In NSDI</em>.</p><p>7. Zaharia, M., Chowdhury, M., Franklin, M. J., Shenker, S., &amp; Stoica, I. (2010).</p><p><strong>Spark: Cluster Computing with Working Sets</strong>. <em>In HotCloud</em>.</p><p>8. Verma, A., Pedrosa, L., Korupolu, M. R., et al. (2015).</p><p><strong>Large-Scale Cluster Management at Google with Borg</strong>. <em>In EuroSys</em>.</p><p>9. Li, M., Anderson, D. G., Park, J. W., et al. (2014).</p><p><strong>Scaling Distributed Machine Learning with the Parameter Server</strong>. <em>In OSDI</em>.</p><p>10. Sergeev, A., &amp; Del Balso, M. (2018).</p><p><strong>Horovod: fast and easy distributed deep learning in TensorFlow</strong>. <em>arXiv:1802.05799</em>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6b9836ff827f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Array Partitioning and QuickSelect: A Guide to Efficient Algorithms]]></title>
            <link>https://medium.com/@tuubow/mastering-array-partitioning-and-quickselect-a-guide-to-efficient-algorithms-85a24dc89f36?source=rss-8da661b0df2f------2</link>
            <guid isPermaLink="false">https://medium.com/p/85a24dc89f36</guid>
            <category><![CDATA[quicksort]]></category>
            <category><![CDATA[quick-select]]></category>
            <category><![CDATA[coding-interviews]]></category>
            <category><![CDATA[median]]></category>
            <category><![CDATA[algorithms]]></category>
            <dc:creator><![CDATA[Aditya Bhatia]]></dc:creator>
            <pubDate>Thu, 26 Dec 2024 00:23:34 GMT</pubDate>
            <atom:updated>2024-12-27T01:02:06.047Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Unlock the secrets of efficient data manipulation with partitioning techniques and QuickSelect algorithms.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_7_dgwwk2V1Z6yBs" /></figure><p>In the vast world of computer science, array manipulation stands as a foundational skill. Whether you’re sorting data, searching for specific elements, or optimizing performance, understanding how to partition arrays efficiently is crucial. In this guide, I’ll delve into the art of partitioning arrays and explore how the QuickSelect algorithm leverages these techniques to solve complex problems with remarkable efficiency.</p><p><strong>Table of Contents</strong></p><p><a href="#5171">1. Introduction to Array Partitioning</a></p><p>2. <a href="#two-way-partitioning">Two-Way Partitioning</a></p><p>3. <a href="#three-way-partitioning">Three-Way Partitioning</a></p><p>4. <a href="#quickselect-algorithm">QuickSelect Algorithm</a></p><p>5. <a href="#applications">Real-World Applications</a></p><p>6. <a href="#conclusion">Conclusion</a></p><h4><strong>1. Introduction to Array Partitioning</strong></h4><p>Partitioning an array involves rearranging its elements based on a specific condition or pivot, dividing it into distinct sections. This concept is the backbone of several efficient algorithms, including QuickSort and QuickSelect.</p><p>Imagine you have a deck of cards, and you want to separate them into red and black suits. Partitioning allows you to do this efficiently without needing to sort the entire deck.</p><h4><strong>2. Two-Way Partitioning</strong></h4><p><strong>Understanding the Concept</strong></p><p>Two-way partitioning divides an array into two sections based on a condition. For example:</p><p>• <strong>Even-Odd Partitioning</strong>: Place all even numbers before odd numbers or vice-versa.</p><p>• <strong>Pivot Partitioning</strong>: Place all elements smaller than or equal to a pivot before larger ones.</p><p>• <strong>Zero-First Partitioning</strong>: Move all zeros to the beginning of the array.</p><p><strong>The Template</strong></p><p>We’ll use a generic template inspired by the <strong>Nico Lomuto partitioning scheme described in </strong><em>Programming Pearls book</em>: In such problems the array needs to be divided by a boundary separating the first partition and second partition. Let the index of this boundary be b1 all the indexes before this boundary belong to partition 1 and all the indexes after this boundary are either from partition 2 or unclassified. When a new element is seen while iterating the array, if the element belongs to first partition, the element is swapped by the b1, and then boundary is moved one step ahead. In such a way b1 identifies the first element of second partition.</p><pre>def two_way_partition(A):<br>    b1 = 0  # Boundary index for partition one<br>    for i in range(len(A)):<br>      # The condition function determines whether an element belongs to the first partition.<br>        if condition(A[i]):<br>            # Element at i is part of parition 1, swap element at i and boundary index of partition 1<br>            swap(A, b1, i)<br>            # Now element at b1 is in partition 1 so increment b1<br>            b1 += 1<br>     # At the end of the loop <br>     # A[:b1] belong to partition 1<br>     # A[b1:] belong to partition 2</pre><p><strong>Practical Examples</strong></p><p><strong>Even-Odd Partitioning</strong></p><pre>def even_odd_partition(A):<br>    even_idx = 0<br>    for i in range(len(A)):<br>         # Condition: If the number is even<br>        if A[i] % 2 == 0: <br>            swap(A, even_idx, i)<br>            even_idx += 1<br>    # A[:even_idx] are even<br>    # A[even_idx:] are odd</pre><p><strong>Pivot Partitioning</strong></p><pre>def pivot_partition(A, pivot):<br>    idx = 0<br>    for i in range(len(A)):<br>        if A[i] &lt;= pivot:<br>            swap(A, idx, i)<br>            idx += 1<br>    # A[:idx] &lt;= pivot<br>    # A[idx:] &gt; pivot</pre><p><strong>Zero-First Partitioning</strong></p><pre>def zero_first_partition(A):<br>    zero_idx = 0<br>    for i in range(len(A)):<br>        if A[i] == 0:<br>            swap(A, zero_idx, i)<br>            zero_idx += 1<br>    # A[:zero_idx] are all zero<br>    # A[zero_idx:] are != zero</pre><p><strong>Swap Function</strong></p><pre>def swap(A, i, j):<br>    A[i], A[j] = A[j], A[i]</pre><h4><strong>3. Three-Way Partitioning</strong></h4><p><strong>Extending the Concept</strong></p><p>Three-way partitioning divides the array into three sections:</p><p>1. Elements belonging to partition one.</p><p>2. Elements belonging to partition two.</p><p>3. Unclassified or elements belonging to partition three.</p><p><strong>The Template</strong></p><pre>def three_way_partition(A):<br>    b1 = b2 = 0<br>    for i in range(len(A)):<br>        # Is A[i] Belong to partition 1<br>        if condition1(A[i]):<br>            # Move A[i] to parition 1, by swaping it back.<br>            swap(A, b2, i)<br>            swap(A, b1, b2)<br>            b1 += 1<br>            b2 += 1<br>        # Is A[i] Belong to partion 2<br>        elif condition2(A[i]):<br>            swap(A, b2, i)<br>            b2 += 1<br>    # A[:b1] =&gt; Belong to partition 1<br>    # A[b1:b2] =&gt; Belong to partition 2<br>    # A[b2:] =&gt; Belong to partition 3</pre><p><a href="https://leetcode.com/problems/sort-colors"><strong>Dutch National Flag Problem</strong></a></p><p>One of the most famous examples is the <strong>Dutch National Flag Problem</strong>, where we sort an array of 0s, 1s, and 2s.</p><pre>def sortColors(nums: List[int]) -&gt; None:<br>        &quot;&quot;&quot;<br>        Do not return anything, modify nums in-place instead.<br>        &quot;&quot;&quot;<br>        def swap(A: List[List[int]], i, j: int) -&gt; int:<br>            A[i], A[j] = A[j], A[i]<br><br>        b1, b2, n = 0, 0, len(A)<br>        for i in range(n):<br>            if nums[i] == 0:<br>                swap(nums, b2, i)<br>                swap(nums, b1, b2)<br>                b2 += 1<br>                b1 += 1<br>            elif nums[i] == 1:<br>                swap(nums, b2, i)<br>                b2 += 1<br>    # nums[:b1] =&gt; Belong to partition 1 =&gt; 0<br>    # nums[b1:b2] =&gt; Belong to partition 2 =&gt; 1<br>    # nums[b2:] =&gt; Belong to partition 3 =&gt; 2</pre><p>Now the same template can be applied to more partition problems like 4 way partition, only it would be more tedius to write.</p><h4><strong>4. QuickSelect</strong></h4><p>Quick select is the algorithm to select kth element in the array. It is uses the same techniques as in the <a href="https://adityabhatia.com/algos-ds/sorting-all/#quicksort">Quick Sort</a> where partitioning is done based on randomly selected index. With the difference that once the partition is decided based on the random selected pivot condition partition, only single recursive call with the desired partition is made. This makes the code to be tail recursive and thus can also be written iteratively.</p><p>Complexity of procedures like selecting the kth largest element or median in the list can be reduced to O(N) in the average case, with randomly chosen pivot, from the O(nlogn) naive solution of actually sorting the underlying structure.</p><p><strong>How QuickSelect Works</strong></p><p>QuickSelect is similar to QuickSort but focuses on calling partition function like discussed above, that could contain the desired element. The core of the problem is still the partition function with modifications, which is discussed earlier. So let’s look at the modifications.</p><pre>def pivot_partition(A, lo, hi):<br>    # Get pivot index<br>    pi = random.randint(lo, hi)<br>    swap(A, pi, hi)<br>    b = lo<br>    for i in range(lo, hi):<br>        # Moves all the numbers smaller than selected pi to the left.<br>        if A[i] &lt; A[hi]:<br>            swap(A, b, i)<br>            b+= 1<br>    swap(A, hi, b)<br>    return b<br>    # A[:b] &gt; A[b]<br>    # A[b+1:] &lt;= A[b]</pre><p>In the partition function for quick select, a random pivot is selected and it’s position is determined by moving all the elements greater to the left of the pivot and all the elements smaller or equal to the right of the pivot. At the end the index of the pivot is returned.</p><p><strong>Implementing QuickSelect</strong></p><p>Quick select, gets or selects k th element in the sorted increasing order. This runs in O(n) average time, and uses the partition function described above. Usually the select body doesn’t change, the changes is mostly in the partition criteria which changes for different problems.</p><pre>def quickSelect(nums: List[int], k: int) -&gt; int:<br>    n = len(nums)<br>    lo, hi = 0, n - 1<br>    # k is 1-indexed<br>    k = k - 1<br>    while lo &lt;= hi:<br>        pi = pivot_partition(nums, lo, hi)<br>        if pi &lt; k:<br>            lo = pi + 1<br>        else:<br>            hi = pi - 1<br>    # when the loop stops, lo will be at the kth smallest element<br>    return nums[lo]</pre><h4><strong>5. Real-World Applications</strong></h4><p>Let’s look at some leet code problems for different partition criteria.</p><p><a href="https://leetcode.com/problems/kth-largest-element-in-an-array/"><strong>Finding the kth Largest Element</strong></a></p><p>Finding the kth largest element, is basically using quick select but finding the element from the end of the array. This can be done 1st largest element will be nothing but `nth` largest element in the sorted array, which can be given as `n — k + 1`</p><pre>def findKthLargest(nums: List[int], k: int) -&gt; int:<br>    return quickSelect(nums, len(nums) - k + 1)</pre><p>In the leetcode the above times out in python for one of the use case, where there are lot of same elements in the input. The code can further optimized by partitioning it in three ways, such that smaller are on left and equal are in middle and greater are on right. Optimization here is if k is in the equal section then don’t need to run partition function again.</p><p>The next two problem solutions, have similar concepts with minor changes to the partition function. I have written in go, just to capture the concept in another language.</p><p><a href="https://leetcode.com/problems/k-closest-points-to-origin/"><strong>K Closest Points to Origin</strong></a></p><p>Uses the same quick select as above by partitioning the points based on the manhattan distance from the origin. Once the `kth` element is found, returns the first `kth` element from the list.</p><pre>func distance(point []int) int {<br> return point[0]*point[0] + point[1]*point[1]<br>}<br><br>func partition(points [][]int, lo, hi int) int {<br> pi := rand.Intn(hi-lo+1) + lo<br> points[pi], points[hi] = points[hi], points[pi]<br> pivot := distance(points[hi])<br> for i := lo; i &lt; hi; i++ {<br>  if distance(points[i]) &lt; pivot {<br>   points[i], points[lo] = points[lo], points[i]<br>   lo++<br>  }<br> }<br> points[lo], points[hi] = points[hi], points[lo]<br> return lo<br>}<br><br>func kClosest(points [][]int, k int) [][]int {<br> // select body<br> lo, hi := 0, len(points)-1<br> for lo &lt;= hi {<br>  p := partition(points, lo, hi)<br>  if p &lt; k {<br>   lo = p + 1<br>  } else {<br>   hi = p - 1<br>  }<br> }<br> return points[:k]<br>}</pre><p><a href="https://leetcode.com/problems/top-k-frequent-elements/"><strong>Top K Frequent Elements</strong></a></p><p>The partition function is modified here to work with the frequency of the item stored in the 1st index of the items list. Otherwise the select body is same.</p><pre>func partition(items [][]int, lo, hi int) int {<br>    pi := rand.Intn(hi - lo + 1) + lo<br>    items[pi], items[hi] = items[hi], items[pi]<br>    b := lo<br>    for i := lo; i &lt; hi; i++ {<br>        // highest and equal frequency items to the left of b<br>        if items[i][1] &gt;= items[hi][1] {<br>            items[b], items[i] = items[i], items[b]<br>            b++<br>        }<br>    }<br>    items[b], items[hi] = items[hi], items[b]<br>    return b<br>}<br><br>func topKFrequent(nums []int, k int) []int {<br>    mp := map[int]int{}<br>    for _, v := range nums {<br>        mp[v]++<br>    }<br>    items := [][]int{}<br>    for v, f := range mp {<br>        items = append(items, []int{v, f})<br>    }<br>    // select body<br>    lo, hi := 0, len(items) - 1<br>    k = k - 1<br>    for lo &lt;= hi {<br>        pi := partition(items, lo, hi)<br>        if pi &lt; k {<br>            lo = pi + 1<br>        } else {<br>            hi = pi - 1<br>        }<br>    }<br>    // gathering results from items[:lo+1]<br>    sol := []int{}<br>    for i:= 0; i &lt;= lo; i++ {<br>        sol = append(sol, items[i][0])<br>    }<br>    return sol<br>}</pre><h4><strong>6. Conclusion</strong></h4><p>Mastering array partitioning and the QuickSelect algorithm opens doors to solving a myriad of problems efficiently. These techniques reduce time complexity and enhance performance, making them invaluable tools in any programmer’s arsenal.</p><p>Whether you’re preparing for coding interviews, optimizing applications, or just looking to deepen your understanding of algorithms, practicing these partitioning methods will undoubtedly pay off.</p><p>You can read more of my interview patterns here: <a href="https://adityabhatia.com/algos-ds/">https://adityabhatia.com/algos-ds/</a></p><p><em>Did you find this guide helpful? Share your thoughts and continue the conversation in the comments below!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=85a24dc89f36" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Zero to Binary Search Hero: How to Solve Any Binary Search Problem : Part — 1]]></title>
            <link>https://medium.com/@tuubow/from-zero-to-binary-search-hero-how-to-solve-any-binary-search-problem-part-1-efcece0983e8?source=rss-8da661b0df2f------2</link>
            <guid isPermaLink="false">https://medium.com/p/efcece0983e8</guid>
            <category><![CDATA[binary-search-python]]></category>
            <category><![CDATA[interview-questions]]></category>
            <category><![CDATA[coding-interviews]]></category>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[binary-search]]></category>
            <dc:creator><![CDATA[Aditya Bhatia]]></dc:creator>
            <pubDate>Mon, 14 Oct 2024 00:33:21 GMT</pubDate>
            <atom:updated>2025-01-03T00:29:03.162Z</atom:updated>
            <content:encoded><![CDATA[<h3>From Zero to Binary Search Hero: How to Solve Any Binary Search Problem : Part — 1</h3><p>Binary search is one of the most important and efficient algorithms you’ll need to master for coding interviews, especially when dealing with sorted arrays. In this guide, I’ll walk you through the essentials of binary search, cover common variations, and equip you with the tools to solve any binary search problem confidently.</p><p><strong>What Is Binary Search and Why Does It Matter?</strong></p><p>Imagine you’re flipping through a phone book to find a name. Instead of looking at each name one by one, you can go straight to the middle, check if the name is earlier or later in the alphabet, and then halve your search space. This is binary search in action — it eliminates half of the search space each time! It is quite natural for anyone given a dictionary will do that, but applying binary search in some of the computer problems requires some practice.</p><p>Binary search is faster than a linear search, with a time complexity of <strong>O(log n)</strong>. This makes it ideal for searching large, sorted datasets. Let’s dive into how to implement it.</p><p><strong>Step 1: The Basic Template for Binary Search</strong></p><p>Here’s a simple template to start with. The idea is to maintain a search window and shrink it iteratively by adjusting the middle point.</p><pre>def binarySearch(nums: List[int], target: int) -&gt; int:<br>    # st(start) points to first elem index, end points to last elem index<br>    st, end = 0, len(nums) - 1<br>    while st &lt;= end:<br>        # Get middle element<br>        mid = st + (end - st)//2<br>        # Check condition for the middle element<br>        if nums[mid] == target:<br>            # return true if matches the middle<br>            return mid<br>        # Move to right if the condition if all the elements to left the middle can be skipped<br>        if nums[mid] &lt; target:<br>            st = mid + 1<br>        else:<br>        # Else move to the right if all the elements to right of the middle can be skipped.<br>            end = mid - 1<br>    return -1</pre><p><strong>How It Works:</strong></p><p>1. <strong>Initial Setup</strong>: We define start and end to track the current window of interest.</p><p>2. <strong>Midpoint Calculation</strong>: We calculate the midpoint of the array by using mid = start + (end — start) // 2. It is basically (start + end)//2 written in a way which doesn’t overflow.</p><p>3. <strong>Comparison</strong>: If the middle element matches the target, we return its index. If not, we adjust the start or end to narrow down the search space.</p><p>4. <strong>Return -1</strong>: If the target is not found, we return -1.</p><p>The above template finds the element if it is present in the sorted array. Although the more interesting case is when the element is not found in the array. As we can see when that happens the function returns `-1`. But where does `start` and `end` point to before the function exists? Is there something we can learn from that.</p><p>Let’s take an example:</p><blockquote>Input : nums = [1, 5, 10, 12, 15, 19] , target = 13</blockquote><blockquote>Iteration 1 : nums = [1, 5, 10, 12, 15, 19] st = 0, end = 5 , mid = 0 + (5 — 0)//2 =&gt; 2, nums[mid] = 10 &lt; 13, st = mid + 1 =&gt; 3</blockquote><blockquote>Iteration 2: nums = [1, 5, 10, 12, 15, 19] st = 3, end = 5 , mid = 3 + (5 — 3)//2 =&gt; 4, nums[mid] = 15 &gt; 13, end= mid — 1 =&gt; 3</blockquote><blockquote>Iteration 3: nums = [1, 5, 10, 12, 15, 19] st = 3, end = 3, mid = 3 + (3–3)//2 =&gt; 3, nums[mid] = 12&lt; 13, st= mid +1 =&gt; 4<br>End of iteration as st = 4 &gt; end = 3</blockquote><p>As in this example we can see start will be 1 greater than end i.e. start = end + 1, in fact that is what while condition also says `while st ≤ end`, so it will continue till that happens.</p><h3><strong>Insight!</strong></h3><p>The insightful part of the above code is where start and end cross if the number is not found in the array. It can be inferred that the point where start and end will cross will partition the array into two parts lower = [:end] (end is also included) and higher = [start:] (start also included). All the elements if any in lower will be smaller than the target and all the elements in higher if any will be greater than the target. In the above example also you can see nums[:3] =&gt; [1, 5, 10, 12] are smaller than target 13 and nums[4:] =&gt; [15, 19] are greater than target 13.</p><p>Keeping that in mind, binary search code can be thought of partitioning the array such that all the elements to the left of the partition belongs to one category (less than) and elements to the right belong to another category (greater than). And element at `end` is last element of that category and the element at `st` is the first element of the other category.</p><p>It is upto the problem solver to define these categories based on the problem, and we will see examples. For example in vanilla binary search if the left category is less than target, right category is greater than or equalto the target then at end of the loop startwill point to the target if present and not returned earlier. If target not present than it will be the next higher element than the target.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/779/0*qY51B7hB7Wtd_QLG.png" /></figure><p>Out of bounds error is also usually the concern with these problems, and as it can be seen in the binary search if all the elements are lower than the target value then the partition boundary will be at the right end of the array, which can be quickly check if start is still less than the length of the array before return element at index start.</p><p>The previous code template, can be transformed based on discussion and also to make reusable for other problems also:</p><p><strong>Step 2: The Improvised Binary Search Template</strong></p><pre>def binarySearch(nums: List[int], target: int) -&gt; int:<br>    st, end = 0, len(nums) - 1<br>    while st &lt;= end:<br>        mid = st + (end - st)//2<br>        if nums[mid] &lt; target: # If in left parition, move the start to the right<br>            st = mid + 1<br>        else: # If in the right parition, move the end to the left<br>            end = mid - 1<br>    if st &lt; len(nums) and nums[st] == target:<br>        return st<br>    return -1</pre><p>Now let’s see how binary search is applied to some of the leet code problems:</p><ul><li><a href="https://leetcode.com/problems/first-bad-version/description/">First-bad-version</a></li></ul><p>In this problem as can be see the partition can be done into two categories good versions followed by bad versions.</p><p>As discussed above thinking of the problem in terms of partitions rather help to use the above template. Idea is to let the while loop run till the start and end crosses each other. When this happens, lets understand what does start and end represents.</p><ul><li>The position of start will the first element on the right partition i.e. first bad version.</li><li>End will point to the last element in the left partition i.e. last good version.</li></ul><p>The diagram below shows the end of the while loop.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/779/0*ffOhks_b4nJYE2s2.png" /></figure><pre>def firstBadVersion(n: int) -&gt; int:<br>    st, end = 1, n<br>    while st &lt;= end:<br>        mid = st + (end - st)// 2<br>        isBad = isBadVersion(mid)<br>        if isBad: # Belongs to right partition, look to the left by moving end to mid - 1<br>            end = mid - 1<br>        else: # Belongs to the left partition, look to the right by moving start to mid + 1 <br>            st = mid + 1<br>    return st # return the first bad version.</pre><p>Other similar easy problems you can try:</p><ul><li><a href="https://leetcode.com/problems/search-insert-position">https://leetcode.com/problems/search-insert-position</a></li><li><a href="https://leetcode.com/problems/find-smallest-letter-greater-than-target/">find-smallest-letter-greater-than-target</a></li></ul><p>Now let’s take it further, until now we look at two categories and finding one partition separating those categories. Now if we increase the category to more than two, thus finding two partitions between categories.</p><p>Let’s look at this problem:</p><ul><li><a href="https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/">find-first-and-last-position-of-element-in-sorted-array</a></li></ul><p>This problem does binary search to find the target, but if there are multiple targets then need to return the index of first and last target.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/779/0*E3mbV5yixPOwwFWL.png" /></figure><p>This can be interpreted as finding two partition boundaries i.e.</p><ol><li>Partition/Boundary 1: Left partition contains all element &lt; target and right partition &gt;= target. In that case the start points to index at the end of the loop to the start of =target partition if valid.</li><li>Partition/Boundary 2: Left partition contains all element &lt;= target and right partition &gt; target. In that case the end points to index at the end of the while loop to the end of =target partition.</li></ol><p>So basically we can run binary search twice by defining separate conditions.</p><pre>def searchRange(nums: List[int], target: int) -&gt; List[int]:<br>    st , end = 0, len(nums) - 1<br>    while st &lt;= end: # Find partition 1 boundary 1<br>        mid = st + (end - st)//2<br>        if nums[mid] &lt; target:<br>            st = mid + 1<br>        else:<br>            end = mid - 1<br>    if st == len(nums) or nums[st] != target: # If the target is not found<br>    # Reached end of array as all numbers were smaller than target.<br>    # Array doesn&#39;t have the target number<br>        return [-1, -1]<br>    first, end = st, len(nums) - 1<br>    while st &lt;= end: # Find partition 2 boundary 2<br>        mid = st + (end - st)//2<br>        if nums[mid] &lt;= target:<br>            st = mid + 1<br>        else:<br>            end = mid - 1<br>    return [first, end]</pre><p>Other similar problem:</p><ul><li><a href="https://leetcode.com/problems/check-if-a-number-is-majority-element-in-a-sorted-array/">check-if-a-number-is-majority-element-in-a-sorted-array</a></li></ul><p><strong>Conclusion:</strong></p><p>In this article I have covered a basic template for solving binary search interview problems. In the next article will cover some medium and hard problems using the same template.</p><p>If you like the article, please subscribe. I am planning to post more articles related to coding interview problems and would love to hear your feedback. You can also follow be on my blog http://adityabhatia.com</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=efcece0983e8" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>