<?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 Siddharth Gupta on Medium]]></title>
        <description><![CDATA[Stories by Siddharth Gupta on Medium]]></description>
        <link>https://medium.com/@siddh.gupta99?source=rss-e072cea221fc------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*6rI29yuZZDr-3XD0qlJ-RQ.jpeg</url>
            <title>Stories by Siddharth Gupta on Medium</title>
            <link>https://medium.com/@siddh.gupta99?source=rss-e072cea221fc------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 13:27:23 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@siddh.gupta99/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[Level Up Your Compose Modifiers: Mastering the Node API]]></title>
            <link>https://proandroiddev.com/level-up-your-compose-modifiers-mastering-the-node-api-8ab7b274b9d1?source=rss-e072cea221fc------2</link>
            <guid isPermaLink="false">https://medium.com/p/8ab7b274b9d1</guid>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[apps]]></category>
            <dc:creator><![CDATA[Siddharth Gupta]]></dc:creator>
            <pubDate>Sun, 30 Mar 2025 23:31:38 GMT</pubDate>
            <atom:updated>2025-03-30T23:31:38.861Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jGmXgRtak1pgyJMGMlY7GA.png" /></figure><p>In my previous <a href="https://proandroiddev.com/custom-modifiers-in-jetpack-compose-a950e6f9eb72">article</a>, we explored the basics of creating custom modifiers in Jetpack Compose. We learned how to extend the `Modifier` interface to add custom behaviour to our composable. Today, we’re taking a step further by diving into the Node API, a more powerful approach to creating complex custom modifiers.</p><h4>Why Use the Node API?</h4><p>The Node API provides several advantages over the traditional approach:</p><p>1. <strong>Better Performance</strong>: The Node API is designed to be more efficient, especially for complex modifiers that need to interact with the layout system.</p><p>2. <strong>More Control</strong>: It gives you direct access to layout coordinates and positioning information, allowing for more sophisticated behaviours.</p><p>3. <strong>Lifecycle Management</strong>: The Node API provides better lifecycle management for modifiers, ensuring that resources are properly cleaned up.</p><p>4. <strong>Improved Testability</strong>: Modifiers built with the Node API are easier to test in isolation.</p><p>5. <strong>Enhanced Debugging</strong>: The API includes built-in inspector support, making it easier to debug issues with your custom modifiers.</p><blockquote>According to the <a href="https://developer.android.com/develop/ui/compose/custom-modifiers#implement-custom">Compose documentation</a>, the Node API is the recommended approach for creating custom modifiers that need to interact with the layout system or track position information.</blockquote><h4>Our Example: A trackVisibility Modifier</h4><p>Let’s build a custom modifier that tracks how visible a composable is on the screen and informs us of its state. We want to know:</p><ul><li>Is the composable visible at all?</li><li>What percentage of the composable is visible?</li><li>What are the screen bounds of the visible area?</li><li>Is the composable visible above a threshold?</li></ul><blockquote><strong><em>Visibility Tracking is an important aspect for media apps</em></strong></blockquote><blockquote><strong>- Reduced Resource Consumption</strong>: Only videos that are significantly visible are actively playing. This saves bandwidth, CPU, and battery.</blockquote><blockquote><strong>- Improved User Experience</strong>: Videos automatically play and pause as the user scrolls, creating a smooth, intuitive experience.</blockquote><blockquote><strong>- Optimised Performance</strong>: By pausing off-screen videos, we reduce the number of active media players, which prevents potential performance issues.</blockquote><p>This is more advanced than the examples in the previous blog post, but it’s a great way to demonstrate the power of the Node API.</p><p><strong>Step 1: Define the VisibilityInfo Data Class</strong></p><p>We start by creating a data class to hold the information our modifier will provide:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d2045d19a792c8e41870a7a52ce15d41/href">https://medium.com/media/d2045d19a792c8e41870a7a52ce15d41/href</a></iframe><p>This class provides a clear and concise way to encapsulate all the visibility details we care about.</p><p><strong>Step 2: Create the VisibilityTrackerNode</strong></p><p>Next, we define VisibilityTrackerNode, which will implement the core logic of our modifier:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/246892c413fb7278a3e09d2d358479ce/href">https://medium.com/media/246892c413fb7278a3e09d2d358479ce/href</a></iframe><p>Let’s examine the code in detail:</p><ul><li><strong>Modifier.Node(), GlobalPositionAwareModifierNode</strong>: This indicates that our class is a modifier node that’s also aware of its global position.</li><li><strong>thresholdPercentage</strong>: This variable indicates the threshold at which the element is considered “visible enough”.</li><li><strong>onVisibilityChanged</strong>: It’s a callback that receives VisibilityInfo to let you know about visibility changes.</li><li><strong>previousVisibilityPercentage</strong>: This variable keeps track of the last percentage reported to avoid excessive updates.</li><li><strong>minimumVisibilityDelta</strong>: Is the minimal difference to update the visibility info.</li><li><strong>onGloballyPositioned</strong>: This is where the magic happens. It’s called when the composable’s layout is determined.</li></ul><p><strong>Step 3: Create VisibilityTrackerElement</strong></p><p>Now, we need to create a ModifierNodeElement that will act as the factory for our VisibilityTrackerNode:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c68b4cc06d8fe66047c67602eb0edb16/href">https://medium.com/media/c68b4cc06d8fe66047c67602eb0edb16/href</a></iframe><ul><li><strong>ModifierNodeElement&lt;VisibilityTrackerNode&gt;</strong>: This is the base class for our element.</li><li><strong>create()</strong>: This method is called to instantiate a new VisibilityTrackerNode when the modifier is added to a composable.</li><li><strong>update()</strong>: This method is called when the modifier’s parameters change. We use it to update the thresholdPercentage and onVisibilityChanged callback in the VisibilityTrackerNode.</li><li><strong>equals and hashCode</strong>: These methods are used to determine if two VisibilityTrackerElement are the same. We check that the thresholdPercentage and onVisibilityChanged are the same.</li><li><strong>InspectorInfo.inspectableProperties</strong>: This method allow the inspection of this modifier from the inspector tool.</li></ul><p><strong>Step 4: Create the Modifier Extension</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/54e584d80b4811c3e2c1dc710474d075/href">https://medium.com/media/54e584d80b4811c3e2c1dc710474d075/href</a></iframe><ul><li><strong>Modifier.trackVisibilit</strong>y: This is a simple extension on Modifier.</li><li><strong>this then VisibilityTrackerElement(…</strong>): This is the crucial line. It’s how we link our VisibilityTrackerElement to the modifier chain.</li></ul><p><strong>Step 5: Using the Modifier</strong></p><p>Now, let’s see how our <em>trackVisibility</em> modifier can be incredibly useful in a real-world media player app.</p><p>Imagine you have a LazyColumn of video items, and you only want to play the video that’s currently visible on the screen.Here’s how we can leverage trackVisibility to achieve this efficiently:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c27a96215288dc67fb615a104948dd65/href">https://medium.com/media/c27a96215288dc67fb615a104948dd65/href</a></iframe><h4><strong>Key Takeaways from the Node API</strong></h4><p>When implementing custom modifiers with the Node API, keep these points in mind:</p><p>1. <strong>Separation of Concerns</strong>: The `ModifierNodeElement` handles creation and configuration, while the `ModifierNode` implements the actual behaviour.</p><p>2. <strong>Performance Considerations</strong>: Be mindful of how often your callbacks are triggered. In our example, we added a threshold to avoid excessive callbacks.</p><p>3. <strong>Proper Cleanup</strong>: If your modifier allocates resources, make sure to clean them up when the node is detached.</p><p>4. <strong>Inspector Support</strong>: Implement `inspectableProperties()` to make debugging easier.</p><p>5. <strong>Immutability</strong>: The `ModifierNodeElement` should be immutable, while the `ModifierNode` can be mutable.</p><h4>Conclusion</h4><p>The Node API provides a powerful way to create custom modifiers in Jetpack Compose. It gives you direct access to layout information and better control over the modifier lifecycle, enabling more complex behaviours than the traditional approach.</p><p>By understanding and leveraging the Node API, you can create sophisticated custom modifiers that enhance your Compose UI in ways that weren’t possible before. Whether you’re tracking visibility, implementing custom layouts, or adding complex interactions, the Node API gives you the tools you need to build powerful, reusable UI components.</p><p>Remember that while the Node API is more powerful, it’s also more complex. For simple modifiers, the traditional approach might still be sufficient. Choose the right tool for the job based on your specific requirements.</p><p>Happy composing!</p><p>— -</p><p><em>This article is a continuation of </em><a href="https://proandroiddev.com/custom-modifiers-in-jetpack-compose-a950e6f9eb72"><em>Custom Modifiers in Jetpack Compose</em></a><em>. If you’re new to custom modifiers, I recommend reading that article first to understand the basics before diving into the Node API.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8ab7b274b9d1" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/level-up-your-compose-modifiers-mastering-the-node-api-8ab7b274b9d1">Level Up Your Compose Modifiers: Mastering the Node API</a> was originally published in <a href="https://proandroiddev.com/">ProAndroidDev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Custom modifiers in Jetpack Compose]]></title>
            <link>https://proandroiddev.com/custom-modifiers-in-jetpack-compose-a950e6f9eb72?source=rss-e072cea221fc------2</link>
            <guid isPermaLink="false">https://medium.com/p/a950e6f9eb72</guid>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[apps]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[development]]></category>
            <dc:creator><![CDATA[Siddharth Gupta]]></dc:creator>
            <pubDate>Fri, 22 Nov 2024 04:11:37 GMT</pubDate>
            <atom:updated>2024-11-22T04:11:37.520Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Oe-DGannPg34NnFtp02TjA.png" /></figure><p>Modifiers in Jetpack Compose are a powerful tool for customising and enhancing UI components. They allow developers to modify the appearance, behaviour, and layout of composable functions without changing their core implementation.</p><h3>Key aspects of modifiers:</h3><ul><li><strong>Chainable:</strong> Modifiers can be chained together, allowing for multiple modifications to be applied sequentially.</li><li><strong>Reusable:</strong> Custom modifiers can be created and reused across different components, promoting code reusability.</li><li><strong>Extensible:</strong> Developers can create their own custom modifiers to add specific functionality.</li></ul><p>The Reusable and Extensible aspects is what make modifiers super powerful. Hence in this blog we’ll be looking at how to create custom modifiers.</p><h3>Three Ways</h3><ol><li>composed { }</li><li>@composable modifier factory</li><li>Modifier.Node API</li></ol><h3>Using composed() to Create Custom Modifiers</h3><p>The composed() function is a convenient way to create custom modifiers in Jetpack Compose. It allows you to define a modifier that can contain composable content.</p><p>Here’s a basic structure of using composed():</p><pre>fun Modifier.customModifier(<br>    // parameters<br>) = composed {<br>    // Your custom modifier logic here<br>    // Can include other composables<br>    this.then(<br>        // Additional modifiers<br>    )<br>}</pre><p>Key points about using composed():</p><ul><li><strong>Composable context:</strong> Inside composed{}, you have access to the composable context, allowing you to use other @Composable functions.</li><li><strong>State observation:</strong> You can observe state and trigger recomposition when needed.</li><li><strong>Chaining:</strong> Use this.then() to chain additional modifiers.</li></ul><p>Example of a custom modifier using composed():</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a39afbbefe4c97818f7c85b4c3d9740d/href">https://medium.com/media/a39afbbefe4c97818f7c85b4c3d9740d/href</a></iframe><p>This example creates a shimmer effect modifier that can be applied to any composable to add a shimmering animation.</p><h3>Using @Composable Modifier Factory to Create Custom Modifiers</h3><p>Another approach to creating custom modifiers in Jetpack Compose is using @Composable modifier factories. This method allows you to create modifiers that can use other @Composable functions and observe state changes.</p><p>Here’s the basic structure of a @Composable modifier factory:</p><pre>@Composable<br>fun Modifier.customModifier(<br>    // parameters<br>): Modifier {<br>    // Your custom modifier logic here<br>    return this.then(<br>        // Additional modifiers<br>    )<br>}</pre><p>Key points about using @Composable modifier factories:</p><ul><li><strong>Composable context:</strong> The function is marked with @Composable, giving you access to other composable functions and state.</li><li><strong>Return type:</strong> The function explicitly returns a Modifier.</li><li><strong>Flexibility:</strong> You can use remember, derivedStateOf, and other composable functions within the modifier.</li></ul><p>Example of a custom modifier using @Composable modifier factory:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d8a77e731258785c969c7bbd7b7cada2/href">https://medium.com/media/d8a77e731258785c969c7bbd7b7cada2/href</a></iframe><p>This example creates a pulsating scale effect modifier that can be applied to any composable to add a pulsating animation. The scale and duration of the pulse can be customised through parameters.</p><blockquote><em>This is an excellent </em><a href="https://engineering.teknasyon.com/composable-modifier-vs-composed-factory-in-jetpack-compose-6cbb675b0e7b"><em>article</em></a><em> which explains the key differences b/w the 2 approaches. Here is the summary:</em></blockquote><blockquote><em>1. </em><strong>Extractability</strong>: CMF is limited to use within the Composition scope, while composed() can be extracted and used more flexibly.</blockquote><blockquote>2. <strong>CompositionLocal resolution</strong>: CMF resolves CompositionLocal values at the call site, while composed() resolves them at the usage site.</blockquote><blockquote>3. <strong>State resolution</strong>: CMF resolves state only once at the call site, while composed() resolves state at the usage site for each Layout.</blockquote><blockquote>4. <strong>Performance</strong>: CMF performs better than composed() due to avoiding the expensive materialize() call.</blockquote><h3>The Recommended Way: New Modifier.Node API</h3><p>As we can see above, creating custom modifiers using composed { } makes more sense than using the <strong>CMF</strong> approach. Using <strong>CMF</strong> is ideal when you need inline modifiers or extract a modifier for using it in only one component. On the other hand, <strong>composed</strong> is useful when designing generic modifiers.</p><p>But here’s the catch, the <strong>composed</strong> way has few performance issues and the new recommended way of creating custom modifiers is to use the Modifier.Node API.</p><blockquote><strong><em>Compose 1.3</em></strong><em> introduced the </em>Modifier.Node<em> API where the team has migrated all the pre-defined modifiers to this new API. I would highly recommend to watch </em><a href="https://www.youtube.com/watch?v=BjGX2RftXsU"><em>this</em></a><em> youtube video of Android Dev Summit which explains why this change has been done.</em></blockquote><p>So if you want the best of both worlds — performance, extractability, skippability, reusable modifiers, use Modifier.Node API</p><p>There are three parts to implementing a custom modifier using Modifier.Node:</p><ul><li>A Modifier.Node implementation that holds the logic and state of your modifier.</li><li>A ModifierNodeElement that creates and updates modifier node instances.</li><li>An optional modifier factory as detailed above.</li></ul><p>ModifierNodeElement classes are stateless and new instances are allocated each recomposition, whereas Modifier.Node classes can be stateful and will survive across multiple recompositions, and can even be reused.</p><p>Here is the very basic example of drawing a circle of specific color as shared in the official documentation.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1c9a583ed459aa358d7c45c415f73a00/href">https://medium.com/media/1c9a583ed459aa358d7c45c415f73a00/href</a></iframe><p>Let’s breakdown to our process</p><h4><strong>Modifier.Node:</strong></h4><p>The first step is to create a class which implements the Modifier.Node along with DrawModifierNode. There are multiple factory nodes which compose provides out of the box. Here we want to draw something hence we are using the DrawModifierNode. If we wanted to do something with user inputs or gestures we might want to use PointerInputModifierNode</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ybo1ri0Ouh63eDGq0R0tsw.png" /><figcaption>Available nodes to override (image taken from Android Documentation)</figcaption></figure><h4>ModifierNodeElement<strong>:</strong></h4><p>A ModifierNodeElement is an immutable class that holds the data to create or update your custom modifier:</p><pre>// ModifierNodeElement<br>private data class CircleElement(val color: Color) : ModifierNodeElement&lt;CircleNode&gt;() {<br>    override fun create() = CircleNode(color)<br><br>    override fun update(node: CircleNode) {<br>        node.color = color<br>    }<br>}</pre><p>ModifierNodeElement implementations need to override the following methods:</p><ol><li>create: This is the function that instantiates your modifier node. This gets called to create the node when your modifier is first applied. Usually, this amounts to constructing the node and configuring it with the parameters that were passed in to the modifier factory.</li><li>update: This function is called whenever this modifier is provided in the same spot this node already exists, but a property has changed. This is determined by the equals method of the class. The modifier node that was previously created is sent as a parameter to the update call. At this point, you should update the nodes&#39; properties to correspond with the updated parameters. The ability for nodes to be reused this way is key to the performance gains that Modifier.Node brings; therefore, you must update the existing node rather than creating a new one in the update method. In our circle example, the color of the node is updated.</li></ol><p>Additionally, ModifierNodeElement implementations also need to implement equals and hashCode. update will only get called if an equals comparison with the previous element returns false.</p><h4>Modifier Factory:</h4><p>This is the public API surface of your modifier. Most implementations simply create the modifier element and add it to the modifier chain:</p><pre>// Modifier factory<br>fun Modifier.circle(color: Color) = this then CircleElement(color)</pre><h3>Summary</h3><p>In this blog post, we’ve explored the power and flexibility of custom modifiers in Jetpack Compose. We’ve covered three main approaches to creating custom modifiers:</p><ol><li>Using the Composable Modifier Function (CMF)</li><li>Using the composed { } function</li><li>Using the new Modifier.Node API (recommended)</li></ol><p>We’ve learned that while CMF and composed { } methods have their uses, the Modifier.Node API is now the recommended approach for creating custom modifiers. This new API offers better performance, reusability, and extensibility.</p><p>Key takeaways:</p><ul><li>The <em>Modifier.Node API</em> consists of three main parts: a Modifier.Node implementation, a ModifierNodeElement, and an optional modifier factory.</li><li>There are various types of modifier nodes available for different purposes, such as DrawModifierNode, LayoutModifierNode, and PointerInputModifierNode.</li><li>The ModifierNodeElement is responsible for creating and updating modifier node instances, which can be stateful and survive across recompositions.</li><li>The modifier factory provides a clean, public API for using your custom modifier.</li></ul><p>By mastering custom modifiers, especially using the Modifier.Node API, you can create more efficient, reusable, and powerful UI components in your Jetpack Compose applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a950e6f9eb72" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/custom-modifiers-in-jetpack-compose-a950e6f9eb72">Custom modifiers in Jetpack Compose</a> was originally published in <a href="https://proandroiddev.com/">ProAndroidDev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Histogram Area Problem]]></title>
            <link>https://medium.com/@siddh.gupta99/histogram-area-problem-8442a7f5150d?source=rss-e072cea221fc------2</link>
            <guid isPermaLink="false">https://medium.com/p/8442a7f5150d</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[problem-solving]]></category>
            <dc:creator><![CDATA[Siddharth Gupta]]></dc:creator>
            <pubDate>Mon, 03 Jun 2019 17:56:51 GMT</pubDate>
            <atom:updated>2019-06-03T17:56:51.014Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>(Optimal Solution Using Stack based approach)</blockquote><p>One of the important question asked during interviews is <strong><em>Maximum Histogram Problem.</em></strong></p><h3>PROBLEM :-</h3><p>Find the largest rectangular area possible in a given histogram where the largest rectangle can be made of a number of contiguous bars.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/330/0*aZY3bYs82vTzl_c_.png" /><figcaption>Histogram with red boundary showing maximum area</figcaption></figure><blockquote>We are given an array in which each index will display the height of respective bar in histogram and we need to find the largest area possible.</blockquote><h3>Solution :-</h3><blockquote><strong>1.) Understanding the problem</strong></blockquote><p>The major thing which needs special attention here is how we can calculate area of histogram, then we can apply different approaches.</p><p>So area of a single bar will be</p><pre>area_single_bar = arr[bar_index]*bar_height</pre><p>Now the optimal solution for solving it is using a <strong><em>stack. </em></strong>Now we will understand the solution by taking an example.</p><blockquote><strong>2.) Solving the problem</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/421/1*hDeR8veMJN3qrMIdaY3GVg.png" /></figure><p>Suppose we have our problem as shown above. So our array will be like:</p><pre>long hist[] = {1, 4, 3, 7, 1, 3, 6};</pre><h4>Don’t worry about the code now, I’ll explain it by the example.</h4><p>So we will maintain a stack for each index and perform following operations :-</p><ol><li>Iterate through the entire array.</li></ol><pre>while(i &lt; hist.length){}</pre><p>2. Now for each iteration we push the current index in our stack if either of these conditions satisfies :-</p><ul><li>If stack is empty</li><li>If element representing top of stack is smaller than element at current index.</li></ul><pre>if (s.isEmpty() || hist[(int)s.peek()] &lt;= hist[i]){<br>     s.push(i);<br>     i++;<br>}</pre><p>3. Otherwise we will pop all the element/bars from the stack which are of greater height than the current bar and find the area of region considering the <em>current bar as the minimum height bar</em> :-</p><p>Suppose we are currently popping this bar :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/408/1*6WF24Nppu5WQXnZMu17idA.png" /><figcaption>Current bar getting popped is hist[2] = 3</figcaption></figure><p>To find the area of region through this bar we need to find the next smaller bar to the right of this bar and smaller bar to the left of this bar.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/352/1*-z1htgquUmXyARYqlmp3Dg.png" /><figcaption>Next Smaller element to the left and right of the popping bar</figcaption></figure><p>Now the area it will cover will be (when the stack is not empty) :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/413/1*DfRTXSkSPZdBv3cEtz_q8Q.png" /></figure><p>Now let’s take the case if the stack is empty i.e we are at the bar which is of minimum height in histogram.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/365/1*q6rx1VwMQZItnfk4XyI_xQ.png" /></figure><pre>top_index = s.pop();</pre><pre>if(s.isEmpty())<br>     area_with_top = hist[(int)top_index] * i ; <br>else<br>     area_with_top = hist[(int)top_index]*(i - s.peek() - 1);</pre><p>4. After both conditions were done we will then check if the area we get is maximum or not.</p><pre>if (max_area &lt; area_with_top)<br>     max_area = area_with_top;</pre><p>5. At the end of all iterations we will check if the stack is empty or not and find the area as above.</p><pre>while (s.isEmpty() == false)<br>{<br>     top_index = s.peek();<br>     s.pop();<br>            <br>     if(s.isEmpty())<br>        area_with_top = hist[(int)top_index]*i;<br>     else<br>        area_with_top = hist[(int)top_index]*(i - s.peek() - 1);<br>            <br>     if (max_area &lt; area_with_top)<br>        max_area = area_with_top;<br>}</pre><h4>So the final code is shown below :</h4><pre>public static long getMaxArea(Stack&lt;Integer&gt; s, long hist[], int n) throws Exception{<br>    long max_area = 0;<br>    long top_index;<br>    long area_with_top;<br>      <br>    int i = 0;<br>    while (i &lt; n)<br>    {<br>       if (s.isEmpty() || hist[(int)s.peek()] &lt;= hist[i])<br>           s.push(i++);<br>      <br>       else{<br>          top_index = s.peek(); <br>          s.pop();  <br>                <br>          if(s.isEmpty())<br>              area_with_top = hist[(int)top_index]*i;<br>          else<br>            area_with_top = hist[(int)top_index]*(i - s.peek() - 1);<br>                <br>          if (max_area &lt; area_with_top)<br>               max_area = area_with_top;<br>       }<br>    }<br>      <br>    while (s.isEmpty() == false)<br>    {<br>        top_index = s.peek();<br>        s.pop();<br>            <br>        if(s.isEmpty())<br>           area_with_top = hist[(int)top_index]*i;<br>        else<br>           area_with_top = hist[(int)top_index]*(i - s.peek() - 1);<br>            <br>        if (max_area &lt; area_with_top)<br>            max_area = area_with_top;<br>    }<br>      <br>    return max_area;<br>}</pre><h3>Explanation :-</h3><p>We have this following histogram :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/337/1*c62QR37xOqde_UqnjHOVhg.png" /></figure><p><strong><em>1st iteration( i = 0) </em></strong>: Our stack is empty therefore, we push the first index in our stack and increment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/126/1*JaMZsv0iEtF-4A2RFeX17A.png" /><figcaption>Stack</figcaption></figure><p><strong><em>2nd iteration( i = 1)</em></strong> : Now top element of stack is less than the current element hence again we push the index in stack and increment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/151/1*6-cN8m1nkA9L4PiOX3mcJw.png" /></figure><p><strong><em>3rd iteration( i = 2)</em></strong> : Now since the top element of stack is greater than the current element hence we <strong>pop the top</strong> bar and find area due to it.</p><p>Therefore <strong>area due to bar at index 1 =</strong><em> hist[popped_element]*(Curr_index- stack_top -1)</em><strong> that is = 4*(2 - 0 -1) = 4 and max_area = 4.</strong></p><p>We again check 3rd bar with top of stack and since it is smaller we push it in the stack and increment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/145/1*WHIiZ11AtmfUziN6CjtS2w.png" /></figure><p><strong><em>4th iteration( i = 3)</em></strong> : Now again top of stack is smaller than current element hence we will push it in and increment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/130/1*zjbgstGAqE7xMTFwgulgvw.png" /></figure><p><strong><em>5th iteration( i = 4)</em></strong> : Now the top of stack is larger and hence we will pop the top element and find the area due to it and that is</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/154/1*dqnG2if_sP_dbB8Rr3QI9A.png" /></figure><p><strong>Area due to bar at index 3= 7*(4- 2 -1) = 7 and max_area = 7</strong></p><p>Now we again check the current bar with top of stack and it is smaller than top hence we will pop the top and find area due to it</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/149/1*Dig9jPXkikRH-gV_dIAziw.png" /></figure><p><strong>Element popped has <em>index 2</em> and <em>height 3</em> and area due to it = 3*(4- 0- 1) = 3*3 = 9 and max_area = 9</strong></p><p>Again we will check the current index and since it is equal to stack top we will push it and increment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/150/1*WrL8mHWqaCNblB7jG8ijPg.png" /><figcaption>State of Stack</figcaption></figure><p><strong><em>6th iteration(i = 5)</em></strong> : Since element[stack top] is smaller than the current element, hence we will push it in the stack and increment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/149/1*p9H1Y8DV3VZPepLMNfcc4A.png" /><figcaption>State of Stack</figcaption></figure><p><strong><em>7th iteration(i = 6)</em></strong> : Again top element is smaller than current element hence we will push it in the stack and increment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/143/1*xR_N1rGmZtBuiTgu7Ej_PQ.png" /></figure><p>Now after we iterated the complete array, we now check whether the stack is empty or not. Here the stack is not empty hence we will pop each bar and find its area.</p><p><strong>Area due to bar at index 6 is 6*(7- 5- 1) = 6 and max_area = 9</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/136/1*Q0CCnuGi_XTyzfWXJjckVA.png" /></figure><p><strong>Area due to bar at index 5 is 3*(7 -4 -1) = 6 and max_area = 9</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/136/1*c1emahZ8LF8wcMvjg4mPiw.png" /></figure><p><strong>Area due to bar at index 4 is 1*(7- 0- 1) = 6 and max_area = 9</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/136/1*ts0NPjrAfJ3ee4pXemq9lA.png" /></figure><p><strong>Area due to bar at index 0 is 1*(7) = 7 and max_area = 9</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/142/1*dYufDHQd-wZtNaVSI-W9-A.png" /><figcaption>Final stack is empty</figcaption></figure><p>Therefore for the above histogram we have <strong>maximum area = 9</strong> and since we take ’n’ steps, hence it’s time complexity is <strong><em>O(n)</em></strong>.</p><p>I hope that now you’ve understood the problem and it’s solution.</p><p>Thank You!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8442a7f5150d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>