<?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 vikrant on Medium]]></title>
        <description><![CDATA[Stories by vikrant on Medium]]></description>
        <link>https://medium.com/@vikkrraant?source=rss-1aef823c4347------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*M7aF6MIPiJn4zpEC.jpg</url>
            <title>Stories by vikrant on Medium</title>
            <link>https://medium.com/@vikkrraant?source=rss-1aef823c4347------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 18:26:06 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@vikkrraant/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[Algorithms Are Just Real Life, Formalized]]></title>
            <link>https://vikkrraant.medium.com/algorithms-are-just-real-life-formalized-eb2031194130?source=rss-1aef823c4347------2</link>
            <guid isPermaLink="false">https://medium.com/p/eb2031194130</guid>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[scala]]></category>
            <category><![CDATA[computer-science]]></category>
            <dc:creator><![CDATA[vikrant]]></dc:creator>
            <pubDate>Sun, 08 Feb 2026 05:10:19 GMT</pubDate>
            <atom:updated>2026-02-08T05:10:19.803Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w29Xv_yuYUDDx-HW85e9ZA.jpeg" /></figure><p>We often struggle to connect algorithms to the real world. But most algorithms <em>start</em> as real-world problems. If you pause long enough, patterns begin to emerge.</p><p>In this post, I want to walk through one such example , where a very ordinary, human problem quietly turns into a classic algorithm we all know.</p><h3>Real Life Problem</h3><p>A man runs a mid-sized auditorium. Before every show, he faces the same question:</p><blockquote>How should seating, aisles, and safety staff be arranged?</blockquote><p>He doesn’t know the audience in advance. Planning for every edge case wastes resources.Planning for an “average” audience doesn’t really work either.</p><h3>How He Solved It</h3><p>Over time, he starts noticing patterns. Certain age and body-type combinations show up far more often than others. So he begins planning resources around the <em>few audience types that appear most frequently</em>, while keeping a small buffer for the rest. Once he does that, comfort improves. Operations get smoother.</p><p>Nothing fancy, just better decisions.</p><h3>Which Algorithm Is This?</h3><p>If you step back, this maps almost perfectly to the <strong>Top K Frequent Elements</strong> problem.We usually solve it for integers in a list. Here, the “elements” are <strong>audience profiles</strong> age and body-type combinations.</p><p>First, define what an audience profile looks like:</p><pre>case class Profile(age: Int, height: Int, weight: Int)</pre><p>What we want is a function like this:</p><pre>def topKFrequentProfiles(profiles: List[Profile], k: Int): List[Profile]</pre><p>It takes historical audience data and returns the few profiles that show up most often. The approach is straightforward:</p><blockquote>Count how often each profile appears → Keep only the most frequent ones using a small heap → Ignore the rest</blockquote><pre>def topKFrequentProfiles(profiles: List[Profile], k: Int): List[Profile] = {<br>  val profileCount = profiles.foldLeft(Map.empty[Profile, Int]) {<br>    case (acc, profile) =&gt;<br>      acc.updated(profile, acc.getOrElse(profile, 0) + 1)<br>  }<br><br>  val minHeap =<br>    scala.collection.mutable.PriorityQueue.empty[(Profile, Int)](<br>      Ordering.by[(Profile, Int), Int](_._2).reverse<br>    )<br><br>  profileCount.foreach { pc =&gt;<br>    minHeap.enqueue(pc)<br>    if (minHeap.size &gt; k) minHeap.dequeue()<br>  }<br><br>  minHeap.toList.map(_._1)<br>}</pre><h3>Closing Thought</h3><p>The interesting part isn’t the code. It’s realizing that many algorithms already exist in the real world. We just give them names later.</p><p>Once you start seeing problems this way, algorithms stop feeling abstract. They start feeling inevitable.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eb2031194130" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Curiosity > Evaluation.]]></title>
            <link>https://vikkrraant.medium.com/curiosity-evaluation-fae774f85d54?source=rss-1aef823c4347------2</link>
            <guid isPermaLink="false">https://medium.com/p/fae774f85d54</guid>
            <category><![CDATA[team-building]]></category>
            <dc:creator><![CDATA[vikrant]]></dc:creator>
            <pubDate>Tue, 27 Jan 2026 05:49:03 GMT</pubDate>
            <atom:updated>2026-01-27T05:49:03.902Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/251/0*hjbLgK39_wbCgD-K" /></figure><h3>Pattern I see</h3><p>There’s a pattern I keep noticing.</p><p>We often spend more time trying to find what a person <em>doesn’t</em> know than understanding what they <em>do</em> know.</p><p>Once you see it, it’s hard to ignore.</p><ul><li>Meetings reward critique, not synthesis.</li><li>Interviews reward elimination, not discovery.</li><li>Social media rewards dunking, not depth.</li></ul><h3>A Better Way</h3><p>In a professional setting , especially when you’re operating <strong>inside a team or building one, </strong>optimizing for <em>signal</em> beats gap-hunting on almost every axis that matters.</p><p>Strong teams aren’t built by minimizing individual gaps. They’re built by recognizing signal: <strong>how someone thinks, what they’ve learned through experience, and where they consistently create impact. </strong>No one knows everything. High-performing teams succeed by <strong>stacking strengths</strong>, not by minimizing individual blind spots</p><p>When I am participating a discussion (team meeting or interview) , My bias is simple: “<strong>optimize for signal, not for gotchas.”</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fae774f85d54" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Every wall lea a door !]]></title>
            <link>https://vikkrraant.medium.com/every-wall-lea-a-door-27eecbb3986c?source=rss-1aef823c4347------2</link>
            <guid isPermaLink="false">https://medium.com/p/27eecbb3986c</guid>
            <category><![CDATA[life-lessons]]></category>
            <category><![CDATA[philosophy]]></category>
            <dc:creator><![CDATA[vikrant]]></dc:creator>
            <pubDate>Tue, 13 Jan 2026 06:08:56 GMT</pubDate>
            <atom:updated>2026-01-13T06:08:56.465Z</atom:updated>
            <content:encoded><![CDATA[<h3>Every wall leads to a door !</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/699/0*AKSmyyp84CSsngMx" /></figure><p>When something is useful, people want it. When people want it, they start pushing against whatever limits exist. Curiosity grows naturally, and it doesn’t wait for permission.</p><p>If a building has a long detour to reach an entrance, people create a dirt path across the grass. That “desire path” wasn’t designed by architects; it emerged from repeated behavior. Eventually, someone paves it.</p><p>Access tends to expand over time. Once something becomes useful or valuable, more people want to reach it. As access increases, curiosity naturally grows. People start asking more questions, exploring boundaries, and testing limits. When direct access is restricted or inconvenient, people look for alternatives.</p><p>Walls are rarely permanent. Most walls end. Not with a dramatic collapse, but with a small opening that gets used again and again. Access expands, curiosity pushes forward, workarounds become refined, and eventually the wall isn’t a wall anymore. Not because permission was given, but because demand made them unavoidable.</p><p>If you’re facing a wall and don’t see a door, it may not mean you’re stuck. It may mean the door hasn’t been created yet. Many meaningful changes start when someone questions the wall itself and tries a different route. Progress often comes not from asking for permission, but from designing a better path. If the wall is real and the need is real, creating a door is sometimes the most practical thing you can do.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=27eecbb3986c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Safe Internet for Kids: Not a Technology Problem]]></title>
            <link>https://vikkrraant.medium.com/safe-internet-for-kids-not-a-technology-problem-a682ea39e0ba?source=rss-1aef823c4347------2</link>
            <guid isPermaLink="false">https://medium.com/p/a682ea39e0ba</guid>
            <category><![CDATA[kids]]></category>
            <category><![CDATA[ai-safety]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[psychological-safety]]></category>
            <category><![CDATA[parenting]]></category>
            <dc:creator><![CDATA[vikrant]]></dc:creator>
            <pubDate>Thu, 08 Jan 2026 06:06:49 GMT</pubDate>
            <atom:updated>2026-01-08T06:06:49.496Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EuscvaNrAUAnEhil8DDEmw.png" /></figure><p>Most conversations about kids and the internet start with the same question:</p><blockquote><strong><em>How do we stop kids from seeing bad things online?</em></strong></blockquote><p>It sounds like the right thing to ask, and it comes from a good place.But it quietly assumes that the internet is something we can fully control. It also assumes that we can somehow seal off all the sharp edges.</p><p>Which anyone who has dealt with both kids and technology knows is not really true.</p><h3>The Reality</h3><p>The internet keeps changing every day . No parent can realistically pre-approve everything a child might see over the next ten years.</p><p>And when online safety is mostly framed as long lists of “don’ts” and scary examples , kids don’t actually become safer. They become quieter.</p><blockquote><strong><em>Curiosity doesn’t go away; it simply moves underground</em></strong></blockquote><p>Safe browsing was never about creating a perfectly clean and sanitized internet anyway, and trying to do that is neither realistic nor healthy.</p><h3>From Control to Capability</h3><p>When kids are trusted with thinking tools instead of only restrictions, something interesting happens. <strong>They become more honest about what they see and experience. They start asking better questions, not because they are scared, but because they are trying to understand.</strong></p><p>Over time, they build internal guardrails that do not depend on apps, filters, or constant supervision, and those guardrails travel with them wherever they go online.</p><p>This shift <strong>“from control to capability”</strong> does not make parenting easier, but it does make it far more effective, and once you start looking at online safety this way, it is very hard to unsee.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a682ea39e0ba" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Iterator : Deserve more love!]]></title>
            <link>https://vikkrraant.medium.com/iterator-deserve-more-love-794fc6d7ad30?source=rss-1aef823c4347------2</link>
            <guid isPermaLink="false">https://medium.com/p/794fc6d7ad30</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[iterators]]></category>
            <dc:creator><![CDATA[vikrant]]></dc:creator>
            <pubDate>Sun, 14 Dec 2025 05:19:51 GMT</pubDate>
            <atom:updated>2025-12-14T05:19:51.517Z</atom:updated>
            <content:encoded><![CDATA[<h3>Iterator : <strong>Deserve more love!</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gHTHdyzHBzQ9m1x2ZeQc0Q.jpeg" /></figure><h3>Problem Statement</h3><p>Let’s say you have your own TimeStampclass with a method addMinutes(m:Int=5):Timestamp .Your goal is to generate a sequence of timestamps starting at start, ending at end, with each timestamp spaced 5 minutes apart.</p><p>How would you solve it? with a loop or with an Iterator?</p><h4>The Loop approach</h4><p>The most common solution looks like this:</p><pre>val buffer = scala.collection.mutable.ListBuffer[TimeStamp]()<br>var current = start<br>while (current &lt;= end) {<br>  buffer += current<br>  current = current.addMinutes(stepMinutes)<br>}<br>buffer.toList</pre><p>This works.It’s explicit.And it’s what most of us would write without thinking twice.</p><h4>The Iterator approach</h4><pre>Iterator<br>  .iterate(start)(_.addMinutes(5))<br>  .takeWhile(_ &lt;= end)<br>  .toList</pre><p>Isnt it looks more elegant? It certainly <em>reads</em> better.</p><p>So the obvious question is:</p><p><strong>If this is so clean, why don’t we see it more often in production code?</strong></p><h3>Understanding the difference</h3><p>At the core of it , we need to undersrtand two scenarios — Traversal and Generation.</p><h4><strong>Traversal</strong></h4><p>Think</p><blockquote>“I already have the values. I’m just visiting them.”</blockquote><p>Like going over a list and doing an operartion on all element. Thats where we should use for, map &amp; while</p><h4>Generation</h4><p>Now Think like</p><blockquote>“I don’t have the values yet. I know how to get the next one.”</blockquote><p>This is a very different problem. Here, you’re not traversing data ,you’re <strong>generating it</strong>. This is where Iterator fits naturally. And our timestamp example falls squarely into this categorySome more example</p><h3>Iterate is about <strong>processes</strong>, not collections.</h3><p>This is the key idea. Iterator.iterate models <strong>state evolution</strong>.</p><p>Consider this pattern:</p><blockquote>Start somewhere → apply a step → stop when a condition is met</blockquote><p>If you see above , then try using Iterator. And you will get beautiful code. This is where Iterator.iterate shines.</p><h4>Real world example</h4><ul><li>Paginating an API</li><li>Retrying with backoff</li><li>Polling job status</li><li>Advancing time windows</li><li>Walking parent pointers</li><li>Generating schedules</li></ul><h3>Final Thoughts</h3><p>A simple question to ask yourself:</p><blockquote><strong><em>“Given a value, can I deterministically produce the next value?”</em></strong></blockquote><p>If the answer is <strong>yes</strong>, you’re holding an <strong>iterator-shaped problem</strong>.</p><p>Loops are great for control. Collections are great for data. Iterators quietly excel at modeling <strong>progress</strong>.</p><p>They may be the least loved tool in everyday programming, but they deserve far more attention than they get.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=794fc6d7ad30" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sorting:The Invisible Algorithm That Runs Your Life]]></title>
            <link>https://vikkrraant.medium.com/sorting-the-invisible-algorithm-that-runs-your-life-ff8b95f1a883?source=rss-1aef823c4347------2</link>
            <guid isPermaLink="false">https://medium.com/p/ff8b95f1a883</guid>
            <category><![CDATA[layoffs]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[sorting-algorithms]]></category>
            <category><![CDATA[life]]></category>
            <category><![CDATA[backend]]></category>
            <dc:creator><![CDATA[vikrant]]></dc:creator>
            <pubDate>Wed, 19 Nov 2025 05:36:22 GMT</pubDate>
            <atom:updated>2025-11-19T05:36:22.229Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KSvWy0ieD5XLwJHt.jpg" /></figure><p>Most people think sorting is a computer science chapter we studied in college : quicksort, mergesort, O(n log n), blah blah.</p><p>In reality <strong>Sorting is the invisible algorithm that decides your daily life. </strong>Every app you open, every service you use, every decision that feels <strong>“personalized” </strong>is really <em>just sorting.</em></p><h3>Sorting is not a CS topic. It’s a life topic.</h3><p>Sorting isn’t about arrays, comparisons, or Big-O notation.</p><p>Sorting is how the world decides:</p><ul><li>Who picks you up</li><li>Who feeds you</li><li>What you buy</li><li>What you see</li><li><strong>What job you get</strong></li><li><strong>Whether you keep that job</strong></li></ul><p>We are living inside thousands of <strong>multi-level sorting algorithms</strong>, constantly reordering the world around us. <strong>Once you see it, you can’t unsee it.</strong></p><p><strong>Cleverly, ruthlessly, and constantly</strong>.. Sorting is the invisible algorithm that decides your daily life.</p><h4>Uber: Why that driver gets your ride</h4><p>Possibly sorted in this order</p><ul><li>Closest driver</li><li>Higher rating</li><li>Longest idle time</li><li>Lowest cancellation rate</li></ul><h4><strong>Food Delivery : Which restaurant appears first?</strong>️</h4><ul><li>Sponsored</li><li>Faster delivery</li><li>Better rating</li><li>Lower fees</li><li>Alphabetical fallback</li></ul><h4>Amazon: Why this product shows before that one</h4><p>Search for anything headphones, vacuum cleaner, iPhone.Amazon sorts millions of products for you.</p><ul><li>Sponsored listing</li><li>Query relevance (text + embeddings)</li><li>Rating</li><li>Number of reviews</li><li>Price</li><li>Prime availability</li><li>Shipping speed</li></ul><h4>You got a Job</h4><p>Sorting can literally change your career trajectory.</p><ul><li>Years of relevant experience</li><li>Skills match (keyword → semantic)</li><li>Tech screening score</li><li>Culture-fit signals</li><li>Submission timestamp</li></ul><h4>You got fired from a job</h4><p>It sounds harsh, but during mass layoffs companies often make decisions using structured ranking criteria , a sorting problem disguised as a human process.</p><p>Typical priority order:</p><ul><li>Business-critical role</li><li>Scarce / hard-to-hire skill</li><li>Impact trajectory (performance trend)</li><li>Team dependency / bus facto</li><li>Tenure</li><li>Cost layer</li><li>Last-joined fallback</li></ul><h3>Final thought</h3><p>Sorting shapes our digital experience, economic opportunities, and personal choices. If you understand sorting deeply, you understand how modern life actually works.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ff8b95f1a883" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Runway vs. Platform Scheduling: Same Problem, Different Worlds]]></title>
            <link>https://vikkrraant.medium.com/runway-vs-platform-scheduling-same-problem-different-worlds-806de128e945?source=rss-1aef823c4347------2</link>
            <guid isPermaLink="false">https://medium.com/p/806de128e945</guid>
            <category><![CDATA[railways]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[airlines]]></category>
            <category><![CDATA[systems-thinking]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[vikrant]]></dc:creator>
            <pubDate>Mon, 10 Nov 2025 06:15:04 GMT</pubDate>
            <atom:updated>2025-11-10T06:15:04.119Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uUeZV5AKU2V0pq9yR-XOkQ.png" /></figure><h3>Why “Which Train Arrives Where” Isn’t the Same as “Which Flight Lands Where”</h3><p>At first glance, it sounds like the same scheduling problem:</p><blockquote>“A system decides which platform a train should arrive on.”</blockquote><blockquote>“A system decides which runway a flight should land on.”</blockquote><p>Both are about <strong>allocating a limited physical resource: “</strong>platforms” or “runways”, to a stream of arrivals. Both need to avoid collisions, minimize waiting, and ensure smooth flow.</p><p>So they must be the same problem, right? I had this question in my had for long, so I digged deeper. HEre is what I found</p><h3>The Core Nature</h3><h4>Which Flight land where?</h4><p><strong>Air Traffic Control</strong> adjusts order every few minutes! Landings are <strong>sequenced live</strong> by ATC as aircraft approach. It is a Continuous, real-time operation.</p><p>If flights are getting delayed, often Controller can change landing order to absorb delay.</p><h4>Which train arrives on which platform?</h4><p>It is mostly pre-planned. Arrivals and departures are <strong>pre-scheduled</strong> in a published timetable.</p><p>If trains are delayed, it will have ripple effect. delaye Propagate downstream more quickly, one late train affects many.</p><h3>The True Source of Complexity &amp; Constraints</h3><p>One is a <strong>real-time optimization</strong> problem, and the other is a <strong>network constraint</strong> problem. Both are hard, just in very different ways.</p><p>Flights are complex because <strong>everything moves. </strong>Trains are complex because <strong>nothing can move freely. </strong>My thoughts are</p><ul><li>ATC works for <strong>Minimize delay, maximize runway utilization. </strong>While railway planning focus more on <strong>Avoid deadlocks, minimize cross-route interference.</strong></li><li>ATC assignment is about <strong>who lands next, </strong>while Platform assignment is about <strong>where a train can safely go</strong>.</li></ul><h3>Execution Environment</h3><p><strong>Airports</strong> are like orchestras with moving instruments. ATC can reorder landings (“Flight 312, go around”; “204, cleared to land”) within minutes of arrival. The <strong>landing order</strong> is not fixed, it’s optimized dynamically to maintain safe separation and throughput. Every aircraft must maintain a <strong>minimum gap. </strong>In effect, the system is solving a <strong>job sequencing problem</strong></p><p><strong>Train</strong> arrivals and departures are <strong>pre-determined</strong> in the national timetable, often planned <strong>months in advance</strong>. Trains <strong>share tracks</strong>, not open airspace.If one stops, it blocks that entire section.a train can’t simply switch to “any empty platform.” It must be one that: Is <strong>physically connected</strong> to its entry track. Is <strong>long enough</strong> for its consist &amp; Doesn’t conflict with another train’s <strong>approach or departure path</strong></p><p><strong>Other aspect of train (which makes me think it is more complex problem)</strong></p><ul><li><strong>Movement is constrained, </strong>trains can only use specific routes</li><li><strong>Resources are networked</strong>, not independent like runways.</li><li><strong>Reordering is difficult</strong></li></ul><h3>🧭 Closing Thought</h3><p>Both are scheduling problems — but in different dimensions. One juggles time; the other juggles space.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=806de128e945" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Big-O Ends Where Reality Begins — Lessons From a Simple Fibonacci Function]]></title>
            <link>https://vikkrraant.medium.com/big-o-ends-where-reality-begins-lessons-from-a-simple-fibonacci-function-f88a22a48ba8?source=rss-1aef823c4347------2</link>
            <guid isPermaLink="false">https://medium.com/p/f88a22a48ba8</guid>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[jvm]]></category>
            <category><![CDATA[runtime]]></category>
            <category><![CDATA[algorithms]]></category>
            <dc:creator><![CDATA[vikrant]]></dc:creator>
            <pubDate>Thu, 06 Nov 2025 05:43:55 GMT</pubDate>
            <atom:updated>2025-11-06T05:43:55.883Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Big-O Ends Where Reality Begins — Lessons From a Simple Fibonacci Function</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qnhMgJuwSWxlXDNFhAm9Og.png" /></figure><h3>Everyone loves Big-O.</h3><p>It’s clean. Predictable. Mathematical. It tells you whether your code scales linearly, quadratically, or catastrophically. <br>But once your code leaves the whiteboard and hits production, <strong>Big-O becomes the least interesting letter in the room</strong>.</p><p>Because in the real world, your program isn’t running in an algorithm textbook ,it’s running on a CPU with opinions, a JIT compiler with ambitions, and a cache that sometimes forgets things for fun.</p><h3>🧮 Case Study: Two Fibonacci Implementations</h3><p>Let’s look at two versions of Fibonacci in Scala:</p><h4>Iterative</h4><pre><br><br>def calcFibonacciIterative(n: Int): Long = {<br> n match<br> case 0 =&gt; 0L<br> case 1 =&gt; 1L<br> case _ =&gt;<br> (2 to n).foldLeft(0L, 1L) { case ((a, b), _) =&gt;<br> (b, a + b)<br> }._2<br>}<br></pre><h4>Recursive (Memoized)</h4><pre>def calcFibonacciMem(n: Int): Long = {<br> val lookup = scala.collection.mutable.HashMap.empty[Int, Long]<br><br> def calcFibonacciMemInternal(nn: Int): Long = {<br>   if (nn == 0) return 0L<br>   if (nn == 1) return 1L<br>   lookup.get(nn) match<br>     case Some(res) =&gt; res<br>     case None =&gt;<br>       val res = calcFibonacciMemInternal(nn — 1) + calcFibonacciMemInternal(nn — 2)<br>       lookup += (nn -&gt; res)<br>       res<br>   }<br> calcFibonacciMemInternal(n)<br>}<br></pre><p>Both are <strong>O(n)</strong> in time complexity and <strong>O(n)</strong> in space, yet they behave very differently when measured.</p><h4>When You Benchmark Them</h4><p>If you run the <strong>iterative</strong> version by itself, it’ll usually finish faster . No recursion, no hash map lookups, no tuple allocations.</p><p>But here’s where it gets interesting: <br>If you run both in the <strong>same program</strong>, one right after the other, the <strong>second </strong>one always appears faster.</p><p>That’s because:</p><p>- The <strong>JVM JIT compiler</strong> optimizes heavily on code paths that have already executed. <br>- The <strong>CPU cache</strong> already holds the code, stack frames, and even the recent numeric data. <br>- The <strong>runtime environment</strong> learns from previous runs — branch prediction and instruction caching kick in.</p><p>In other words, <strong>both implementations share part of the “hot” runtime environment. Your second run benefits from the optimizations accumulated during the first.</strong></p><p>So even though both are <strong>O(n)</strong>, and the iterative version is logically leaner, the recursive version might “win” simply because the system warmed up.</p><h4>What This Teaches Us</h4><p>Big-O gives the <strong>shape</strong> of performance . Real performance depends on <strong>everything else</strong>:</p><p>1. <strong>Constant factors</strong> — The hidden multipliers behind *O(k·n)*. <br>2. <strong>Runtime optimization</strong> — JIT, caching, and branch prediction. <br>3. <strong>Memory locality</strong> — How your data sits in cache or heap. <br>4. <strong>I/O, GC, threading, synchronization</strong> — The unsung heroes and villains of real workloads. <br>5. <strong>Measurement artifacts</strong> — Order of tests, warm-up effects, even println statements.</p><h3>How to put it in practice?</h3><ul><li><strong>Keep processes long-lived.</strong> The JIT gets smarter over time (tiered compilation). Rapid restarts = perpetual cold starts.</li><li><strong>Avoid noisy first hits.</strong> Don’t let the first real user call trigger class loading, reflection, regex compilation, DB pool creation, etc.</li><li><strong>Run representative work before taking traffic.</strong> Execute the same code paths and payload shapes your real requests will hit. JIT compiles based on what it sees. Build singletons, load config, open pools, warm caches.<br>Precompute regexes, JSON codecs, protobuf schemas, templates, ML models. If possible , touch critical code paths once (or a few times) with real-like payloads.</li><li>Keep hot logic in one place; don’t scatter the critical loop across many tiny methods (helps inlining).</li><li>Send N “shadow” or synthetic requests through the full stack (routing → handlers → DB) at startup.</li><li>Touch critical code paths once (or a few times) with real-like payloads.</li></ul><h3>TL;DR</h3><p>- Big-O is necessary but not sufficient. <br>- Performance in production is shaped by hardware, runtime behavior, and environment state. <br>- Always **measure** , don’t just rely on asymptotic reasoning. <br>- And if one Fibonacci looks faster than the other, it might just be because your CPU already had coffee. ☕️</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f88a22a48ba8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Math and Micro-Optimization: A Dinner Table Lesson on Prime Numbers]]></title>
            <link>https://vikkrraant.medium.com/math-and-micro-optimization-a-dinner-table-lesson-on-prime-numbers-c29c466ea3d4?source=rss-1aef823c4347------2</link>
            <guid isPermaLink="false">https://medium.com/p/c29c466ea3d4</guid>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[prime-numbers]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[vikrant]]></dc:creator>
            <pubDate>Fri, 17 Oct 2025 04:56:04 GMT</pubDate>
            <atom:updated>2025-10-17T04:56:04.372Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bKvMAaj9hTAoK4x2.png" /></figure><h3>How it started?</h3><p>My daughter’s learning number theory in her math class, and over dinner we ended up talking about prime numbers. I thought why not flex my math + programming muscles and see how efficiently I can check if a number is prime?</p><p>This optimization journey went from 4938 ms → 8 ms, ending not with a math trick, but with a JVM + CPU insight.</p><h3>Refresher</h3><p>A prime is a number that divides only by 1 and itself. (And nope, 1 is not prime!) We’ll test using 2147483647 a bug 32-bit prime and see how fast we can validate it.</p><p>Let’s code</p><h4>The brute-force way</h4><p>Check divisibility by every number from 2 up to num — 1. <strong>Took 4953 ms</strong></p><pre>  def isPrime(num: Int): Boolean = {<br>    num match {<br>      case _ if num &lt; 2 =&gt; false<br>      case _ =&gt;<br>        2 to (num -1) forall( n =&gt; num % n != 0)<br>    }<br>  }</pre><h4>Skip even numbers!</h4><p>If num isn’t divisible by 2, we can skip all other evens. <strong>Took 3081 ms</strong></p><pre>def isPrimeFaster(num: Int): Boolean = {<br>    num match {<br>      case _ if num &lt; 2 =&gt; false<br>      case _ if num == 2 =&gt; true<br>      case _ if num % 2 == 0 =&gt; false<br>      case _ =&gt;<br>        (3 to (num-1) by 2) forall(n =&gt; num % n != 0)<br>    }<br>  }</pre><h4>Skip 3 as well</h4><p>Same logic , if not divisible by 3, skip all multiples of 3 too. Took 2614 ms</p><pre>def isPrimeMoreFaster(num: Int): Boolean = {<br>    num match {<br>      case _ if num &lt; 2 =&gt; false<br>      case _ if num == 2 || num == 3 =&gt; true<br>      case _ if num % 2 == 0  || num % 3 == 0 =&gt; false<br>      case _ =&gt;<br>        (5 to (num-1) by 6) forall(n =&gt; num % n != 0)<br>    }<br>  }</pre><h4>Real breakthrough</h4><p>You don’t need to go all the way up to num. Just go up to √num ,if no divisor exists before that, none will after. <strong>Took 11.6 ms</strong></p><pre>def isPrimeMostFaster(num: Int): Boolean = {<br>  num match {<br>    case _ if num &lt; 2 =&gt; false<br>    case _ if num == 2 || num == 3 =&gt; true<br>    case _ if num % 2 == 0 || num % 3 == 0 =&gt; false<br>    case _ =&gt;<br>      val limit = Math.sqrt(num).toInt<br>      (5 to (limit - 1) by 6) forall (n =&gt; num % n != 0)<br>  }<br>}</pre><h4>Move from Int → Long</h4><p>Surprisingly, it gets faster again! Why? Modern CPUs (and JVMs) are 64-bit, so Long arithmetic runs natively, while Int math needs conversions &amp; overflow checks. <strong>Took 8.03 ms</strong></p><pre>  def isPrimeBigNumber(num: Long): Boolean = {<br>    num match {<br>      case _ if num &lt; 2 =&gt; false<br>      case _ if num == 2 || num == 3 =&gt; true<br>      case _ if num % 2 == 0 || num % 3 == 0 =&gt; false<br>      case _ =&gt;<br>        val limit = Math.sqrt(num).toInt<br>        (5 to (limit - 1) by 6) forall (n =&gt; num % n != 0)<br>    }<br>  }</pre><h3>🧠 Takeaways</h3><p><strong>Math still matters.</strong> Knowing where to stop (√n) is pure mathematical wisdom.</p><p><strong>Systems matter too.</strong> Hardware and runtime can make or break performance.</p><p><strong>Curiosity scales.</strong> A dinner table question turned into a JVM-level discovery.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c29c466ea3d4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Thinking Backward ]]></title>
            <link>https://vikkrraant.medium.com/thinking-backward-db95a791824a?source=rss-1aef823c4347------2</link>
            <guid isPermaLink="false">https://medium.com/p/db95a791824a</guid>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[backend]]></category>
            <dc:creator><![CDATA[vikrant]]></dc:creator>
            <pubDate>Sat, 11 Oct 2025 05:05:45 GMT</pubDate>
            <atom:updated>2025-10-11T05:05:45.377Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BnAUZxidPi9FNelpUsthUQ.png" /></figure><p>We engineers are trained to think left-to-right. We read that way. We loop that way. We even reason about time that way.</p><p>But many elegant algorithms actually think in reverse!</p><p>They look from the future backward, not from the past forward. When you traverse from right to left, you already know the <em>best possible future</em>, and you can make present decisions with total confidence.</p><p>I call this mindset: <strong>Thinking Backward.</strong></p><p>And two small problems illustrate it perfectly. one with digits, one with dollars.</p><h3>🔢 The Maximum Swap Problem</h3><p>You’re given a number like 2736. You can swap two digits once to get the largest possible number.</p><p>We’re going to scan the digits <strong>right to left</strong>. At every step, we remember the <strong>best future digit</strong> (maxIdx), and if the current digit is smaller, we’ve found our swap. The leftmost such improvement always wins because earlier digits carry more positional weight.</p><p><strong>That’s as greedy as it gets. </strong>just “if the future looks better, take it.”</p><pre>def maximumSwapFunctional(num: Int): Int = {<br>  val digits = num.toString.map(_.asDigit).toVector<br>  val n = digits.length<br><br>  val (_, swap) = digits.zipWithIndex.reverse.foldLeft((n - 1, Option.empty[(Int, Int)])) {<br>    case ((maxIdx, swapOpt), (d, i)) =&gt;<br>      val newMaxIdx = if (d &gt; digits(maxIdx)) i else maxIdx<br>      val newSwapOpt = if (d &lt; digits(newMaxIdx)) Some((i, newMaxIdx)) else swapOpt<br>      (newMaxIdx, newSwapOpt)<br>  }<br><br>  swap match {<br>    case Some((x, y)) =&gt;<br>      digits.updated(x, digits(y)).updated(y, digits(x)).mkString.toInt<br>    case None =&gt;<br>      num<br>  }<br>}</pre><h3>💹 The Stock Profit Problem</h3><p>Now, a different world, but the same approach. You’re given daily stock prices, and you can buy once and sell once to make the most profit.</p><p>Here too we go <strong>right to left</strong>. We carry the <strong>best future sell price</strong>, and for each earlier day, we ask: “If I bought today and sold at the best future price, would that be better than what I’ve seen so far?” just the <strong>future whispering to the past</strong>.</p><pre>def maxProfitFunctional(prices: Vector[Int]): Int = {<br>  val (_, maxProfit) = prices.zipWithIndex.reverse.foldLeft((prices.last, 0)) {<br>    case ((maxPrice, bestProfit), (price, _)) =&gt;<br>      val profit = maxPrice - price<br>      val newBestProfit = bestProfit.max(profit)<br>      val newMaxPrice = maxPrice.max(price)<br>      (newMaxPrice, newBestProfit)<br>  }<br>  maxProfit<br>}</pre><h3>Both Are Greedy</h3><p>Both problems are classic <strong>greedy algorithms</strong> in disguise.</p><p>A greedy algorithm makes the best local choice at each step, hoping (and in these cases, guaranteeing) that it leads to the global optimum.</p><h3>️Final Thought</h3><p>Thinking backward sometimes is the best way forward.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=db95a791824a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>