<?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 Biswasshreyasi on Medium]]></title>
        <description><![CDATA[Stories by Biswasshreyasi on Medium]]></description>
        <link>https://medium.com/@biswasshreyasi16?source=rss-d60fbd8fdab3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*z35ipeUfcfwYCzs7</url>
            <title>Stories by Biswasshreyasi on Medium</title>
            <link>https://medium.com/@biswasshreyasi16?source=rss-d60fbd8fdab3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 08:42:05 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@biswasshreyasi16/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[Finding a Charger That’s Actually Free: KD Trees and Queues for EV Drivers]]></title>
            <link>https://medium.com/@biswasshreyasi16/finding-a-charger-thats-actually-free-kd-trees-and-queues-for-ev-drivers-4f1f7d496dbb?source=rss-d60fbd8fdab3------2</link>
            <guid isPermaLink="false">https://medium.com/p/4f1f7d496dbb</guid>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[kd-tree]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[electric-vehicles]]></category>
            <category><![CDATA[algorithms]]></category>
            <dc:creator><![CDATA[Biswasshreyasi]]></dc:creator>
            <pubDate>Fri, 02 Oct 2026 13:03:38 GMT</pubDate>
            <atom:updated>2026-10-02T13:03:38.260Z</atom:updated>
            <content:encoded><![CDATA[<p>Written by Aditya Bhoir (16014125005) &amp; Shreyasi Biswas (16014125007)</p><p><strong>Problem 25: EV charging station finder &amp; queue</strong></p><p>A KD tree whose nodes remember how many available stations sit below them turns nearest free charger from a full scan into a few dozen node visits. A doubly linked list plus a handle table makes every queue operation, including mid queue cancellations, O (1). A C implementation checked against brute force confirms the results.</p><h3>A. The problem in plain words</h3><p>You are driving an EV with 18% battery. You need a charging station that is</p><p>(a) reachable on the charge you have left</p><p>(b) free right now, or failing that has the shortest wait</p><p>(c ) fair to everyone else waiting.</p><p>There are thousands of stations, thousands of drivers asking at once, and station status flips every few seconds.</p><p>The core computational challenge is two problems glued together:</p><p>a) <strong>Spatial nearest neighbour search over a set whose eligibility keeps changing.</strong> A station is only a valid answer while it is available, and that changes constantly.</p><p>b) <strong>Fair, dynamic queue management</strong> with arrivals, departures and cancellations at every station.</p><h3>B. Why the naive approach fails</h3><p>The naive design keeps stations in an unsorted list and scans all of them per query, which is <strong>O(n)</strong>. With n = 50,000 stations and 10,000 queries per second, that is 500 million distance computations per second. A plain array as the waiting queue is just as bad because removing a cancelled driver from the middle shifts everything behind them, costing O(n).</p><p>Sorting by latitude alone does not rescue it. Two points with similar latitude can be hundreds of kilometres apart in longitude, so a one-dimensional order cannot answer ‘nearest’ in two dimensions.</p><h3>C. Proposed design</h3><h4>1. A KD tree augmented with availability counts</h4><p>Stations are stored in a KD tree built on their coordinates. To avoid latitude/longitude wraparound problems, each (lat, lon) is converted to 3D Cartesian coordinates on a sphere of radius 6371 km, and a 3-d tree is used (axes cycle x, y, z, splitting at the median).</p><p>The key idea:</p><p>the tree holds <strong>all</strong> stations, because locations rarely change, but each node also stores avail_count, the number of available stations in its subtree. During search, any subtree with avail_count == 0 is skipped immediately, so the search never walks through full or offline stations.</p><p>Availability updates stay cheap. An id to node table gives O(1) access to a station’s node, and parent pointers let us recompute counts up to the root in O(log n).</p><p>Battery awareness comes from bounding the search radius:</p><p>maxDist = battery_kWh x km_per_kWh x 0.8 (a 20% safety margin)</p><p>This both prunes the search and guarantees we never recommend an unreachable station.</p><h4>2. A per station queue: doubly linked list + handle table</h4><p>Each station has a FIFO queue implemented as a <strong>doubly linked list</strong>, plus a table driver_id -&gt; list node.</p><p>• Join the queue: append at the tail, <strong>O(1)</strong></p><p>• Serve the next driver: pop the head, <strong>O(1)</strong></p><p>• Cancel or no-show: look up the node through the table and unlink it, <strong>O(1)</strong></p><p>FIFO is the fairness guarantee: first come, first served.</p><h4>3. Putting them together</h4><p>a) Run the KD-tree search for the nearest <strong>available</strong> station within range. If found, recommend it.</p><p>b) If nothing is free, take the k nearest stations (k = 3 in the demo) and rank them by estimated time to charge:</p><p>total = travel_time + remaining_time_of_current_car + queue_length x avg_session_time</p><p>The middle term matters. A station marked ‘full’ with an empty queue is not free: someone is still plugged in, and ignoring their remaining session time makes busy stations look better than they are.</p><h3>D. Pseudocode</h3><p>BUILD(points, depth):<br> if points is empty: return null<br> axis = depth mod 3<br> sort points by coordinate[axis]<br> mid = median index<br> node = new Node(points[mid], axis)<br> node.left = BUILD(points[0..mid-1], depth+1)<br> node.right = BUILD(points[mid+1..end], depth+1)<br> node.avail_count = (node.station.available ? 1 : 0)<br> + count(node.left) + count(node.right)<br> return node<br> <br> NEAREST_AVAILABLE(node, query, best): // best.dist starts at maxDist<br> if node is null or node.avail_count == 0: return // availability pruning<br> d = distance(query, node.station)<br> if node.station.available and d &lt; best.dist:<br> best = (node.station, d)<br> near, far = side of node.split containing query, other side<br> NEAREST_AVAILABLE(near, query, best)<br> if |query[axis] — node.split| &lt; best.dist: // far side may hold something closer<br> NEAREST_AVAILABLE(far, query, best)<br> <br> SET_AVAILABILITY(station_id, status):<br> node = nodeOf[station_id]<br> node.station.available = status<br> while node is not null:<br> node.avail_count = recompute(node) // self + left + right<br> node = node.parent<br> <br> QUEUE_CANCEL(driver_id):<br> n = handle[driver_id]<br> n.prev.next = n.next; n.next.prev = n.prev // handle head/tail cases<br> delete handle[driver_id]</p><h3>E. Complexity analysis</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/792/1*P776j88ROZcC8fa-cDc8Jg.png" /></figure><p><strong>On the worst case.</strong></p><p>The expected O(log n) for nearest neighbour search holds for reasonably spread out data. Known worst case bounds are weaker:</p><p>a KD tree range query in k dimensions costs O(n^(1–1/k)), which is O(n^(2/3)) for our 3D tree, and an adversarial layout can force nearest neighbour search toward O(n).</p><p>In practice the maxDist bound and availability pruning keep real queries far from that, and the benchmark in section H shows it.</p><h3>F. Diagram</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/896/1*I9YbFlgatiN-yMGSxf8AOw.png" /></figure><h3>G. Real world constraints and edge cases</h3><p>• <strong>Stale data and sensor failure.</strong> A station with no heartbeat for a set timeout is marked offline through SET_AVAILABILITY(false), so it stops being recommended.</p><p>• <strong>Concurrent updates.</strong> Two drivers may race for the last free charger. Use a per-station lock or compare-and-swap on a version number; the loser is re-routed. Note that every update walks to the root, so the root’s counter becomes a contention hotspot at scale. Mitigations include atomic counters or batching count updates. A briefly stale count is safe in one direction: a count that is too high only wastes some visits, while one that is too low could hide a free station, so updates should be applied promptly.</p><p>• <strong>No-shows.</strong> A driver at the head of the queue who does not arrive within a timeout is removed in O(1) through the handle table.</p><p>• <strong>Battery too low for any station.</strong> The search returns null and the app triggers a roadside-assistance flow instead of failing silently (tested as Query 5 in the demo).</p><p>• <strong>Ties.</strong> Break by shorter queue, then by charger speed.</p><p>• <strong>New or removed stations.</strong> Insertion and deletion can unbalance the tree, so rebuild periodically, for example nightly.</p><p>• <strong>Distance realism.</strong> The code uses chord length in 3D, which closely approximates surface distance over short hops but is not road distance. The KD-tree is used to shortlist candidates quickly; road-network routing should refine the final choice.</p><p>• <strong>Wait-time model.</strong> Session length is assumed to be a constant 30 minutes, and the remaining time of the current car is an input. A real system would estimate both from charger power and the car’s reported state of charge.</p><h3>H. Implementation and results</h3><p>The full program is ev_charger_finder.c (build with gcc -O2 -Wall -o ev_charger_finder ev_charger_finder.c -lm).</p><p><a href="https://gist.github.com/shreyasi-biswas/719df0406b50399da0f617664aa6374b">https://gist.github.com/shreyasi-biswas/719df0406b50399da0f617664aa6374b</a></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a8de6bed6c2b08f58ae441cb2a551635/href">https://medium.com/media/a8de6bed6c2b08f58ae441cb2a551635/href</a></iframe><p>It has two parts.</p><p><strong>Part 1: functional demo on 10 Mumbai-area stations.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/795/1*keq0hik7D70rXBLVWtK4_Q.png" /></figure><p>The queue tests show D2 cancelled from the middle of Vidyavihar’s queue (D1, D2, D3 becomes D1, D3), then D1 served from the head.</p><p><strong>Part 2: benchmark with 20,000 random stations, 2,000 random queries,</strong> compared against a brute-force scan:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*ok59noKVcylOzI7HqLjLjA.png" /></figure><p>Two things stand out. First, the KD-tree already beats a scan by a factor of hundreds. Second, the availability counts matter most exactly when it hurts most: when only 1% of stations are free, an ordinary KD-tree wanders through hundreds of full stations, while the augmented tree stays at about 38 visits. After 100,000 random availability flips, the root count matched a recount from scratch, so the incremental updates keep the counts consistent.</p><h3>I. Limitations</h3><p>• The benchmark uses uniformly random station positions in a 40 km by 40 km box. Real stations cluster along highways and in cities, which can change visit counts.</p><p>• It measures nodes visited, not wall-clock time, and the demo is single-threaded.</p><p>• Distances are straight-line, not road-network.</p><p>• The wait model uses a fixed average session length.</p><h3>J. Conclusion</h3><p>A KD-tree with subtree availability counts, paired with linked-list queues and handle tables, replaces an O(n) scan with a near-logarithmic lookup and makes cancellations constant-time. The main lesson is to <em>augment</em> a classic structure so it reflects a constraint the real world keeps changing, here availability, rather than rebuilding or filtering around it.</p><h3>References</h3><p>a) J. L. Bentley, ‘Multidimensional binary search trees used for associative searching,’ <em>Communications of the ACM</em>, 18(9), 509–517, 1975.</p><p>b) J. H. Friedman, J. L. Bentley and R. A. Finkel, ‘An algorithm for finding best matches in logarithmic expected time,’ <em>ACM Transactions on Mathematical Software</em>, 3(3), 209–226, 1977.</p><p>c) T. H. Cormen, C. E. Leiserson, R. L. Rivest and C. Stein, <em>Introduction to Algorithms</em> (linked lists, hash tables), MIT Press.</p><h3>Appendix: key code excerpts</h3><p>/* Nearest AVAILABLE station; skips subtrees with no free station */<br> static void nearest_available(KDNode *n, const double q[3], Best *best, long *visited) {<br> if (!n) return;<br> if (g_prune &amp;&amp; n-&gt;avail_count == 0) return; /* availability pruning */<br> (*visited)++;<br> Station *s = &amp;stations[n-&gt;sid];<br> double d = dist(q, s-&gt;xyz);<br> if (s-&gt;available &amp;&amp; d &lt; best-&gt;d) { best-&gt;d = d; best-&gt;sid = n-&gt;sid; }<br> <br> double diff = q[n-&gt;axis] — s-&gt;xyz[n-&gt;axis];<br> KDNode *near_side = diff &lt; 0 ? n-&gt;left : n-&gt;right;<br> KDNode *far_side = diff &lt; 0 ? n-&gt;right : n-&gt;left;<br> nearest_available(near_side, q, best, visited);<br> if (fabs(diff) &lt; best-&gt;d)<br> nearest_available(far_side, q, best, visited);<br> }<br> <br> /* Flip availability and fix counts up to the root: O(log n) */<br> static void set_availability(int sid, int status) {<br> stations[sid].available = status;<br> if (status) stations[sid].remaining_min = 0;<br> for (KDNode *n = node_of[sid]; n; n = n-&gt;parent)<br> n-&gt;avail_count = node_avail_total(n);<br> }<br> <br> /* Cancel a driver from anywhere in a queue: O(1) via the handle table */<br> static int q_cancel(int driver) {<br> QNode *n = qnode_of[driver];<br> if (!n) return 0;<br> q_unlink(queue_of[driver], n);<br> qnode_of[driver] = NULL; free(n);<br> return 1;<br> }</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4f1f7d496dbb" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>