<?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 Rajesh kaki on Medium]]></title>
        <description><![CDATA[Stories by Rajesh kaki on Medium]]></description>
        <link>https://medium.com/@rajeshkakiofc?source=rss-f54ad082edc0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*UjOqGQMvs1bEv8BiSa7s-A.jpeg</url>
            <title>Stories by Rajesh kaki on Medium</title>
            <link>https://medium.com/@rajeshkakiofc?source=rss-f54ad082edc0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 17:35:54 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rajeshkakiofc/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[Calculating End Dates for Claims Using LEAD and Edge Case Handling — EXL SQL Interview Question.]]></title>
            <link>https://medium.com/@rajeshkakiofc/calculating-end-dates-for-claims-using-lead-and-edge-case-handling-exl-sql-interview-question-129ebebf8717?source=rss-f54ad082edc0------2</link>
            <guid isPermaLink="false">https://medium.com/p/129ebebf8717</guid>
            <category><![CDATA[sql-server]]></category>
            <category><![CDATA[exl-interview-question]]></category>
            <category><![CDATA[sql-date-functions]]></category>
            <dc:creator><![CDATA[Rajesh kaki]]></dc:creator>
            <pubDate>Mon, 29 Sep 2025 06:41:21 GMT</pubDate>
            <atom:updated>2025-09-29T06:41:21.866Z</atom:updated>
            <content:encoded><![CDATA[<h3>Calculating End Dates for Claims Using LEAD and Edge Case Handling — EXL SQL Interview Question.</h3><h4>How I Approached a Sequential Claim Period Problem Using Window Functions and Custom Logic</h4><p><strong>About the Data:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/295/1*2h665jbA-33B9S9NcPW4BQ.png" /></figure><p>Output :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/410/1*E7c_1_CxmXMdT-PS328PqA.png" /></figure><p>The table contains claim information with the following columns:</p><ul><li>claim_name: Name of the insurance claim</li><li>start_date: Starting date of the claim (in Mon DD format)</li></ul><p>The goal was to calculate the end_date for each claim such that:</p><ul><li>It ends <strong>1 day before</strong> the next claim’s start date.</li><li>The <strong>last claim</strong> should end on &#39;2022-12-31&#39;.</li></ul><p><strong>My SQL Query:</strong></p><pre>WITH cte AS (<br>  SELECT <br>    claim_name,<br>    CAST(start_date + &#39; 2022&#39; AS DATE) AS start_date<br>  FROM claims_data<br>)<br>SELECT <br>  claim_name,<br>  start_date,<br>  ISNULL(DATEADD(DAY, -1, LEAD(start_date) OVER (ORDER BY start_date)), &#39;2022-12-31&#39;) AS end_date<br>FROM cte;</pre><p><strong>Explanation of My Approach and Techniques Used:</strong></p><p><strong>Problem Breakdown:</strong></p><ul><li>I needed to calculate the claim end_date based on the start_date of the next row.</li><li>There was no existing end_date column or format to use directly.</li><li>Also, the input date was partial (Mon DD), which required conversion.</li></ul><ol><li><strong>Step-by-Step Thought Process:</strong></li></ol><p><strong>Date Parsing with Year Assumption:</strong><br> Since only Mon DD format was given, I assumed all claims belong to the year 2022.<br> I used:</p><pre>CAST(start_date + &#39; 2022&#39; AS DATE)</pre><p><strong>Window Function for Next Row Reference:</strong><br> To get the start_date of the next claim, I applied the LEAD() function:</p><ul><li>LEAD(start_date) OVER (ORDER BY start_date)</li></ul><p><strong>Calculating </strong><strong>end_date:</strong><br> To end the current claim <strong>one day before</strong> the next begins, I used DATEADD(DAY, -1, ...).</p><p><strong>Handling the Last Row Edge Case:</strong><br> For the last claim, where LEAD(start_date) would return NULL, I used ISNULL() to replace it with &#39;2022-12-31&#39;.</p><p><strong>Why This Works Well:</strong></p><ul><li>The solution handles all cases without any loops or subqueries.</li><li>It leverages LEAD() for forward referencing and DATEADD() for relative date logic.</li><li>Ensures correct chronological chaining of claims and handles the tail case elegantly.</li></ul><p>This type of question tests your practical understanding of <strong>window functions</strong>, <strong>date manipulation</strong>, and <strong>handling NULLs</strong>, which are essential in real-time analytics and reporting use cases.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=129ebebf8717" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Amazon SQL Interview Problem: Users with Unique Product Purchases Across Multiple Days]]></title>
            <link>https://medium.com/@rajeshkakiofc/amazon-sql-interview-problem-users-with-unique-product-purchases-across-multiple-days-f0400c51d4b8?source=rss-f54ad082edc0------2</link>
            <guid isPermaLink="false">https://medium.com/p/f0400c51d4b8</guid>
            <category><![CDATA[amazon-sql]]></category>
            <category><![CDATA[sql-server]]></category>
            <category><![CDATA[leetcode-sql]]></category>
            <category><![CDATA[sql-interview-questions]]></category>
            <dc:creator><![CDATA[Rajesh kaki]]></dc:creator>
            <pubDate>Mon, 22 Sep 2025 15:32:18 GMT</pubDate>
            <atom:updated>2025-09-22T15:32:18.300Z</atom:updated>
            <content:encoded><![CDATA[<h4>Tracking Loyal Shoppers: Finding Users Who Bought Unique Products Across Multiple Purchase Days Using Just GROUP BY and HAVING</h4><p>The task is based on analyzing a purchase_history table that logs which users bought which products on what date. The goal is to identify <strong>users who meet two strict conditions</strong>:</p><ol><li>They made purchases on <strong>more than one distinct date</strong></li><li>They <strong>never purchased the same product more than once</strong>, across all dates</li></ol><p>This type of question tests the use of <strong>GROUP BY</strong>, <strong>HAVING</strong>, and a solid understanding of how to use <strong>aggregations to enforce uniqueness</strong> and <strong>multi-day behavior</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/349/1*7C46XDHidnxz1PPlURTpWQ.png" /></figure><h3>SQL Query</h3><pre>select userid <br>from purchase_history<br>group by userid<br>having count(distinct purchasedate) &gt; 1 and count(productid) = count(distinct productid)</pre><h3>My Thought Process and Step-by-Step Approach</h3><p>When I first looked at the question, I realized this is not just about distinct purchases — it’s also about enforcing <strong>non-repetition of products</strong> over <strong>multiple days</strong>. So I broke the problem down into <strong>two distinct filters</strong> using SQL aggregation.</p><h4>Step 1: Grouping by User</h4><p>I started with GROUP BY userid because we need to evaluate each user independently — their purchase behavior across different products and dates.</p><h4>Step 2: Count of Distinct Purchase Dates</h4><p>To ensure that a user has purchased on <strong>more than one day</strong>, I used:</p><pre>count(distinct purchasedate) &gt; 1</pre><p>This filters out users who made all purchases on a single day, which violates the first condition.</p><h4>Step 3: Detecting Duplicate Product Purchases</h4><p>Now for the tricky part — identifying users who <strong>never bought the same product twice</strong>. If a user bought the same product on multiple dates, the count of total products will exceed the count of distinct products. To capture only users with unique product purchases, I used:</p><pre>count(productid) = count(distinct productid)</pre><p>This comparison is the key insight. If a product was bought more than once (regardless of when), the two counts would differ, and such users would be excluded.</p><h4>Step 4: Combining the Conditions</h4><p>With both filters ready, I placed them inside the HAVING clause to apply them after grouping. This lets SQL evaluate each user as a group, and only include those who passed both tests.</p><h3>Why This Approach Works</h3><p>The solution is efficient because:</p><ul><li>It avoids subqueries and unnecessary joins</li><li>It pushes all filtering into the HAVING clause, keeping the logic clean and performant</li><li>It relies only on GROUP BY, COUNT, and DISTINCT, which are fundamental tools in SQL interview questions</li></ul><p>By approaching the problem logically — first filtering by date diversity, then by product uniqueness — I was able to design a concise solution that’s easy to test and scale.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f0400c51d4b8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Uber SQL Interview Question: Detecting Profit Rides Using LEAD() Window Function]]></title>
            <link>https://medium.com/@rajeshkakiofc/uber-sql-interview-question-detecting-profit-rides-using-lead-window-function-2f345a18700a?source=rss-f54ad082edc0------2</link>
            <guid isPermaLink="false">https://medium.com/p/2f345a18700a</guid>
            <category><![CDATA[profit-rides]]></category>
            <category><![CDATA[uber-sql]]></category>
            <category><![CDATA[sql-server]]></category>
            <category><![CDATA[leetcode-sql]]></category>
            <dc:creator><![CDATA[Rajesh kaki]]></dc:creator>
            <pubDate>Mon, 22 Sep 2025 11:20:27 GMT</pubDate>
            <atom:updated>2025-09-22T11:20:27.261Z</atom:updated>
            <content:encoded><![CDATA[<h4>This interview problem from Uber presents an insightful challenge related to analyzing driver ride patterns. Specifically, the goal is to calculate two metrics for each driver. <strong>Total Rides</strong> they performed, <strong>Profit Rides</strong>, defined as those where the drop-off location of one ride matches the pick-up location of the very next ride (for the same driver)</h4><p>This is realistic in logistics and ride-sharing companies where minimizing empty return travel boosts profitability.</p><h4>Problem Statement</h4><p>For each driver, I needed to:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/627/1*6EBHogNHc7g7cnxYE9jCiQ.png" /></figure><ol><li><strong>Count the total number of rides</strong> they’ve completed.</li><li><strong>Count the number of “profit rides”</strong>, where the <strong>end location of one ride matches the start location of the next ride</strong> for the same driver.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/322/1*FGHTpdqUyd1d5aI2jQaOvw.png" /></figure><p>These “profit rides” indicate minimal idle time and efficient route chaining — ideal behavior in a ride-sharing logistics network.</p><h3>My Initial Thought Process</h3><p>When I read the problem, I immediately knew this required <strong>comparing sequential rows</strong> within the same group (i.e., same driver). In SQL, comparing a row with the next one (or previous one) is a textbook case for <strong>window functions</strong>.</p><p>Self-joins would work but are bulky, especially when performance matters. So I reached for the tool made for this job: LEAD().</p><pre>with start_end_loc as (<br>    select <br>        id,<br>        end_loc,<br>        lead(start_loc) over(partition by id order by end_time) as next_loc<br>    from drivers<br>)<br>select <br>    id,<br>    count(*) as total_rides,<br>    sum(case when end_loc = next_loc then 1 else 0 end) as profit_rides<br>from start_end_loc<br>group by id;</pre><h3>Explaining the Query Step-by-Step</h3><h4>Step 1: CTE — start_end_loc</h4><p>Here’s what I did in this CTE:</p><ul><li><strong>Goal</strong>: For each trip, find the start location of the very next trip by the same driver.</li><li>I used LEAD(start_loc) to <strong>peek into the next row</strong> for each driver (partitioned by id).</li><li>I ordered the rows by end_time, ensuring that the next trip is truly the next in time.</li><li>This let me compare end_loc of the current trip with the start_loc of the next trip without joining the table to itself</li></ul><blockquote><em>LEAD() is a powerful window function for accessing the next row’s value </em>within a group<em>. Without it, we would need a self-join or correlated subquery.</em></blockquote><h4>Step 2: Aggregating the Results</h4><p>In the final result:</p><ul><li>count(*) counts all the rides for each driver — the <strong>total rides</strong>.</li><li>sum(case when end_loc = next_loc then 1 else 0 end) gives us the number of times the <strong>end location of a ride matched the start location of the next ride</strong> — these are the <strong>profit rides</strong>.</li></ul><p>By wrapping this in a GROUP BY id, I neatly summarized the metrics per driver.</p><h3>Why This Approach is Efficient and Scalable</h3><p>I considered other approaches like self-joins or correlated subqueries, but they quickly become inefficient, especially with large datasets. Using <strong>LEAD()</strong> makes the query:</p><ul><li><strong>Linear</strong> in performance (one pass over each partition)</li><li><strong>Readable</strong> and easier to maintain</li><li><strong>Closer to business logic</strong>, i.e., <em>“Compare each trip’s end location with the next one’s start location”</em></li></ul><h3>Business Interpretation</h3><p>This type of analysis is <strong>directly aligned with Uber’s operational goals</strong> — reducing dead miles, optimizing driver assignment, and improving customer wait times. The “profit ride” count can be a leading metric for:</p><ul><li>Driver incentive calculations</li><li>Route optimization algorithms</li><li>Predictive dispatching</li></ul><h3>Summary</h3><ul><li>I used <strong>LEAD()</strong> to compare consecutive rides.</li><li>I <strong>partitioned by driver id</strong> and <strong>ordered by trip end time</strong>.</li><li>I calculated total and profit rides using a <strong>simple aggregation</strong> with CASE.</li><li>All logic was wrapped into a <strong>single clean query</strong>, ready for dashboards or ETL pipelines</li></ul><p>This is one of those interview problems that looks simple on the surface but reveals how SQL can model temporal logic and real-world movement — all without writing procedural code.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2f345a18700a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Identify Inserts and Deletes Using Full Outer Join — SQL Delta Tracking in Real-Time Systems]]></title>
            <link>https://medium.com/@rajeshkakiofc/identify-inserts-and-deletes-using-full-outer-join-sql-delta-tracking-in-real-time-systems-e469fe1017d7?source=rss-f54ad082edc0------2</link>
            <guid isPermaLink="false">https://medium.com/p/e469fe1017d7</guid>
            <category><![CDATA[sql-case-study]]></category>
            <category><![CDATA[sql-server]]></category>
            <category><![CDATA[delta-tracking]]></category>
            <category><![CDATA[leetcode-sql]]></category>
            <dc:creator><![CDATA[Rajesh kaki]]></dc:creator>
            <pubDate>Mon, 22 Sep 2025 10:39:55 GMT</pubDate>
            <atom:updated>2025-09-22T10:39:55.664Z</atom:updated>
            <content:encoded><![CDATA[<h3>Identify Inserts and Deletes Using Full Outer Join — SQL Delta Tracking in Real-Time Systems</h3><h4>In high-volume transactional systems where real-time changes like INSERT, UPDATE, and DELETE are frequent, tracking delta changes becomes crucial—especially for downstream analytics, reporting, or replication pipelines. But what if we have <strong>no timestamps</strong> to rely on?</h4><h3>Problem Setup</h3><p>We have two tables:</p><ul><li>tbl_orders → live production table (current state)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/289/1*kww-fOHM52YbPas02TDITw.png" /></figure><ul><li>tbl_orders_copy → snapshot from last night at 12:00 AM (previous state)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/255/1*jiylPN_j0X8z6WgKDmj8fA.png" /></figure><p>My goal was to:</p><ul><li>Identify records present in tbl_orders but missing from tbl_orders_copy → <strong>Inserts</strong></li><li>Identify records present in tbl_orders_copy but missing from tbl_orders → <strong>Deletes</strong></li></ul><p>Here’s how I solved it using two different approaches: one intuitive and one performance-optimized.</p><h3>Approach 1: Using NOT IN + UNION</h3><pre>SELECT order_id, &#39;D&#39; AS flag<br>FROM tbl_orders_copy<br>WHERE order_id NOT IN (SELECT order_id FROM tbl_orders)</pre><pre>UNION</pre><pre>SELECT order_id, &#39;I&#39; AS flag<br>FROM tbl_orders<br>WHERE order_id NOT IN (SELECT order_id FROM tbl_orders_copy)</pre><h3>Why This Works:</h3><ul><li>The first query fetches all order_ids that were <strong>present before but now missing</strong> → they’ve been <strong>deleted</strong>.</li><li>The second query fetches all order_ids that are <strong>newly inserted</strong> after the snapshot.</li><li>UNION merges both results into a single output.</li></ul><h3>🔍 Techniques Used:</h3><ul><li>NOT IN for anti-joins (i.e., checking non-existence).</li><li>UNION to combine both logical branches.</li><li>Hard-coded flags &#39;I&#39; and &#39;D&#39; for insert/delete labels.</li></ul><h3>Caveats:</h3><ul><li>NOT IN can behave unexpectedly with NULL values, but here it&#39;s safe because order_id is a primary key (no NULLs).</li><li>May be <strong>less efficient</strong> on large datasets due to repeated subqueries (especially if tables have no indexes).</li></ul><h3>Approach 2: Using FULL OUTER JOIN + COALESCE</h3><pre>SELECT <br>  COALESCE(a.order_id, b.order_id) AS order_id,<br>  CASE <br>    WHEN a.order_id IS NULL THEN &#39;D&#39;<br>    WHEN b.order_id IS NULL THEN &#39;I&#39;<br>  END AS flag<br>FROM tbl_orders_copy a<br>FULL OUTER JOIN tbl_orders b<br>ON a.order_id = b.order_id<br>WHERE a.order_id IS NULL OR b.order_id IS NULL</pre><h3>Why I Switched to This:</h3><p>This version is much <strong>cleaner and scalable</strong>, especially when you need to track differences <strong>in both directions</strong> (inserts and deletes).</p><h3>Techniques Used:</h3><ul><li>FULL OUTER JOIN: This retains records from both tables—even when there’s no match. Perfect for diff comparison.</li><li>COALESCE: Since either a.order_id or b.order_id could be NULL, I used COALESCE(a.order_id, b.order_id) to always get the non-null value.</li><li>Conditional CASE statement:</li><li>If a.order_id is NULL → means the record was <strong>not in snapshot</strong> → <strong>Inserted</strong></li><li>If b.order_id is NULL → means the record is <strong>gone from current table</strong> → <strong>Deleted</strong></li></ul><h3>Performance Advantage:</h3><ul><li>This avoids subqueries altogether.</li><li>With proper indexing on order_id, it&#39;s <strong>highly performant</strong>, even on large transactional systems.</li></ul><h3>Real-World Application: Change Data Capture (CDC)</h3><p>This problem is more than an interview exercise — it reflects <strong>how data engineering works in real-time systems</strong>:</p><ul><li>Think about CDC in Kafka or Debezium: detecting inserts/deletes is essential for syncing systems.</li><li>In data lakes and ELT pipelines, detecting what changed lets us <strong>incrementally update</strong> fact/dim tables.</li><li>In cloud tools like Snowflake, similar delta detection techniques power <strong>zero-copy clones</strong> and <strong>streaming inserts</strong>.</li></ul><p>If you’re working with a few hundred or thousand rows, both will work fine. But for <strong>10K+ transactions per day</strong>, always lean toward the <strong>FULL OUTER JOIN version</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e469fe1017d7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Airbnb SQL Case Study: Finding Substitutable Rentals Based on Exact Amenity Matches]]></title>
            <link>https://medium.com/@rajeshkakiofc/airbnb-sql-case-study-finding-substitutable-rentals-based-on-exact-amenity-matches-22a0c3cb2416?source=rss-f54ad082edc0------2</link>
            <guid isPermaLink="false">https://medium.com/p/22a0c3cb2416</guid>
            <category><![CDATA[airbnb-sql]]></category>
            <category><![CDATA[sql-server]]></category>
            <category><![CDATA[leetcode-sql]]></category>
            <category><![CDATA[sql-hard]]></category>
            <dc:creator><![CDATA[Rajesh kaki]]></dc:creator>
            <pubDate>Fri, 19 Sep 2025 14:56:45 GMT</pubDate>
            <atom:updated>2025-09-19T14:56:45.191Z</atom:updated>
            <content:encoded><![CDATA[<h4>fascinating real-world-style question that feels very aligned with how data teams at companies like Airbnb might think. The problem revolves around <strong>rental substitutability</strong> — how similar two rental listings are based on the <em>exact match of amenities</em>. This seemingly simple requirement taught me some deeper concepts in SQL: string aggregation, grouping, and deduplication.</h4><h3>Problem Statement</h3><p>We are given a list of Airbnb rentals, each associated with a list of amenities (like pool, kitchen, hot tub, etc.). The goal is to determine how many <strong>unique sets of rentals</strong> have the <strong>same exact set of amenities</strong>, regardless of the order.</p><p>In other words:</p><ul><li>If rental 1 has kitchen, pool and rental 2 also has kitchen, pool, that’s a valid match.</li><li>If rental 3 has kitchen, pool, fireplace and rental 4 only has kitchen, pool, that’s <em>not</em> a valid match—because the sets aren’t exactly equal.</li></ul><p>So we need to:</p><ol><li>Convert each rental’s list of amenities into a single aggregated signature.</li><li>Group the rentals by this amenity signature.</li><li>Count how many amenity sets appear more than once.</li><li>Return how many rental pairs share the same <em>exact</em> amenity set.</li></ol><p>Sample input —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/280/1*l1jaa5sSR7IS6zveWfwxyA.png" /></figure><h3>Step-by-Step Thought Process</h3><p>To solve this, I first thought about representing each rental’s list of amenities in a <strong>consistent order</strong>. Since we’re comparing <strong>set equality</strong>, order should not matter. This immediately pointed me toward the STRING_AGG() function in SQL Server.</p><p>Let me walk you through the logic.</p><h3>Final SQL Query</h3><pre>WITH cte AS (<br>  SELECT <br>    rental_id, <br>    STRING_AGG(amenity, &#39;, &#39;) WITHIN GROUP (ORDER BY amenity) AS amenities,<br>    COUNT(*) AS cnt<br>  FROM rental<br>  GROUP BY rental_id<br>)<br>SELECT COUNT(*) AS matching_count<br>FROM (<br>  SELECT amenities<br>  FROM cte<br>  WHERE cnt &gt; 1<br>  GROUP BY amenities<br>  HAVING COUNT(*) &gt; 1<br>) x;</pre><h3>Function Breakdown and My Reasoning</h3><h4>1. STRING_AGG(amenity, &#39;, &#39;) WITHIN GROUP (ORDER BY amenity)</h4><p>This is the key to normalization. By sorting and aggregating all amenities per rental in a consistent comma-separated string, I convert each rental’s amenities into a comparable “signature”. This way:</p><ul><li>kitchen, pool and pool, kitchen become the same: kitchen, pool</li></ul><h4>2. COUNT(*) AS cnt</h4><p>I used this to ensure the rental has more than one amenity. Rentals with only one amenity are unlikely to match others and can sometimes introduce unnecessary noise.</p><h4>3. Grouping and Filtering</h4><p>The inner GROUP BY amenities HAVING COUNT(*) &gt; 1 identifies how many amenity &quot;sets&quot; appear more than once (i.e., two or more rentals share exactly the same amenities). But to count the number of matching rentals—not groups—we need the outer query.</p><h3>What’s Returned</h3><p>This query returns <strong>only the count of matching rentals</strong>, not the pairs themselves. For example, if three rentals have exactly the same amenities, they are considered a match group of size 3 — but they form 3 pairs: (A-B), (A-C), and (B-C).</p><p>If we wanted to find the actual <strong>matching pairs</strong>, we could extend the logic using self-joins or ROW_NUMBER techniques.</p><h3>Real-World Relevance</h3><p>This problem is deceptively powerful. While at first glance it feels like simple string processing, it simulates what teams at Airbnb, Booking.com, or OYO might do when clustering listings or powering their <strong>“Similar Listings”</strong> or <strong>“You might also like”</strong> features.</p><p>By converting relational rows into normalized strings and grouping them, I practiced skills that are directly useful for product recommendation systems, deduplication pipelines, and ETL workflows.</p><h3>Key Takeaways</h3><ul><li><strong>Normalize unordered lists</strong> using STRING_AGG(... ORDER BY ...)</li><li>Group data at a <strong>set level</strong> rather than row level when looking for matches</li><li>Filter for duplicates with HAVING COUNT(*) &gt; 1</li><li>Always think about how real-world data might appear unordered or messy — and how SQL can help bring structure to it</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=22a0c3cb2416" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Calculating Running Ledger Balance from Daily Transactions- SQL]]></title>
            <link>https://medium.com/@rajeshkakiofc/calculating-running-ledger-balance-from-daily-transactions-sql-1d4a38d56479?source=rss-f54ad082edc0------2</link>
            <guid isPermaLink="false">https://medium.com/p/1d4a38d56479</guid>
            <category><![CDATA[running-total]]></category>
            <category><![CDATA[visa-interview]]></category>
            <category><![CDATA[sql-server]]></category>
            <category><![CDATA[visa-sql]]></category>
            <dc:creator><![CDATA[Rajesh kaki]]></dc:creator>
            <pubDate>Fri, 19 Sep 2025 12:04:39 GMT</pubDate>
            <atom:updated>2025-09-19T12:06:00.957Z</atom:updated>
            <content:encoded><![CDATA[<h4><em>Real-World SQL Case Study from a Finance Dataset</em></h4><p>When working with transaction records in a banking or wallet-like system, it’s essential to compute the running balance day by day. In this scenario, I was given a transaction table with daily deposits and withdrawals and asked to calculate the running ledger balance as it would appear at the end of each day.</p><p>Let me walk you through how I approached this using SQL, focusing on breaking the problem into two clear steps.</p><h3>Step 1: Compute Net Amount Per Day (Deposits — Withdrawals)</h3><p>The first part of the problem was to find the <strong>net movement</strong> of funds per day. The raw trans table had each transaction stored with type (deposit or withdrawal), amount, and the timestamp (transaction_date).</p><p>Input —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/571/1*KQOvOpxYOJeJRWbY55XQbQ.png" /></figure><p>Output —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/342/1*PF5PPaYTqZtBJ8OJfho0MA.png" /></figure><p>I wanted to:</p><ul><li><strong>Group all transactions by day</strong></li><li><strong>Sum deposits and subtract withdrawals</strong> for that day</li></ul><p>I did this using a CASE WHEN inside a SUM, grouped by CAST(transaction_date AS DATE):</p><pre>WITH day_total AS (<br>  SELECT <br>    CAST(transaction_date AS DATE) AS date,<br>    SUM(CASE WHEN type = &#39;deposit&#39; THEN amount ELSE 0 END) -<br>    SUM(CASE WHEN type = &#39;withdrawal&#39; THEN amount ELSE 0 END) AS amount<br>  FROM trans<br>  GROUP BY CAST(transaction_date AS DATE)<br>)</pre><p>The result of this CTE (day_total) gave me the <strong>net change</strong> for each date. For example:</p><ul><li>On 2022-07-08, there was a deposit of 178.55 and two withdrawals (25.90 + 45.99), resulting in a net gain of 106.66</li><li>On 2022-07-10, all three deposits summed to 65.90 + 32.60 = 98.50, and no withdrawals, giving a net gain of 98.50</li></ul><h3>Step 2: Compute the Cumulative Running Balance</h3><p>The next step was to calculate the <strong>cumulative sum</strong> of the net amounts day by day, in chronological order. This is what I would expect in a traditional passbook or ledger — each day’s balance includes the effect of all prior days.</p><p>For that, I used the SUM(...) OVER(ORDER BY date) window function:</p><pre>SELECT <br>  date, <br>  SUM(amount) OVER(ORDER BY date) AS balance_amount<br>FROM day_total</pre><p>This ensured that:</p><ul><li>For 2022-07-08, the balance was simply the net amount on that day (106.66)</li><li>For 2022-07-10, the cumulative total became 106.66 + 98.50 = 205.16</li></ul><p>The final output matched perfectly with the expected running balances.</p><h3>Why I Used These SQL Techniques</h3><p>Let me explain why each function/technique was chosen:</p><ul><li><strong>CAST(date AS DATE):</strong> To extract the date portion from a datetime value so I could group all transactions that occurred on the same calendar day.</li><li><strong>CASE WHEN in </strong><strong>SUM():</strong> This is a clean and efficient way to apply conditional logic in aggregation—very helpful when you want to treat different types differently (deposits vs. withdrawals).</li><li><strong>CTE (Common Table Expression):</strong> Used for modular and readable SQL. It allowed me to logically separate the net computation and the running total calculation.</li><li><strong>SUM() OVER(ORDER BY date):</strong> A classic window function to calculate running totals across rows while maintaining order. Very efficient and avoids self-joins or nested queries.</li></ul><h3>Final Thoughts</h3><p>This exercise is a great representation of how <strong>SQL can be used for ledger-style reporting</strong>, which is critical in finance, fintech, accounting, and budgeting systems. It also highlights the importance of:</p><ul><li>Using window functions for progressive computations</li><li>Properly segmenting business logic into steps using CTEs</li><li>Leveraging conditional aggregation to extract insights from transactional records</li></ul><p>Whether you’re working on a bank ledger, wallet balance tracker, or even a credit points system, this pattern is universally applicable.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1d4a38d56479" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Microsoft SQL Interview Question (DE) : Budget-Constrained Hiring Strategy Based on Experience —…]]></title>
            <link>https://medium.com/@rajeshkakiofc/microsoft-sql-interview-question-de-budget-constrained-hiring-strategy-based-on-experience-d01c3b002f98?source=rss-f54ad082edc0------2</link>
            <guid isPermaLink="false">https://medium.com/p/d01c3b002f98</guid>
            <category><![CDATA[window-functions]]></category>
            <category><![CDATA[sql-server]]></category>
            <category><![CDATA[leetcode-sql]]></category>
            <category><![CDATA[microsoft-interview-sql]]></category>
            <dc:creator><![CDATA[Rajesh kaki]]></dc:creator>
            <pubDate>Tue, 26 Aug 2025 10:14:41 GMT</pubDate>
            <atom:updated>2025-08-26T10:14:41.184Z</atom:updated>
            <content:encoded><![CDATA[<h3>Microsoft SQL Interview Question (DE) : Budget-Constrained Hiring Strategy Based on Experience — SQL Window Function Case Study</h3><h4>Let’s say a company has a total salary <strong>budget of 70,000</strong> units and they want to hire employees from a pool of <strong>Junior</strong> and <strong>Senior</strong> candidates.</h4><p>Their objective is to:</p><ul><li>Hire <strong>as many Seniors as possible</strong> first, starting from the lowest salary.</li><li>Then, with the <strong>remaining budget</strong>, consider <strong>Junior</strong> candidates (also sorted by salary ascending).</li><li>The selection must <strong>not exceed the 70,000 budget</strong> in total.</li></ul><p>Let’s take a look at the dataset:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/324/1*OA16Wsc7IsRDOdYpNG5fmw.png" /></figure><p>OUTPUT :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/329/1*r0UU6g4jjTLTgJFaXQFTQA.png" /></figure><h3>Approach 1: Simple, readable step-by-step query</h3><pre>WITH cte AS (<br>  SELECT *,<br>         SUM(salary) OVER (PARTITION BY experience ORDER BY salary) AS est_bud<br>  FROM candidates<br>),</pre><pre>senior AS (<br>  SELECT * <br>  FROM cte <br>  WHERE experience = &#39;Senior&#39; AND est_bud &lt; 70000<br>),</pre><pre>junior AS (<br>  SELECT *,<br>         CASE <br>           WHEN (SUM(CASE WHEN experience = &#39;Junior&#39; THEN salary ELSE 0 END)<br>                 OVER (PARTITION BY experience ORDER BY salary)<br>                 &lt; 70000 - (SELECT MAX(est_bud) FROM senior))<br>           THEN 1 ELSE 0 <br>         END AS rnk<br>  FROM cte<br>  WHERE experience = &#39;Junior&#39;<br>)</pre><pre>SELECT emp_id, experience, salary FROM junior WHERE rnk = 1<br>UNION <br>SELECT emp_id, experience, salary FROM senior;</pre><h3>Thought Process:</h3><ol><li><strong>CTE 1 — Budget Estimation (</strong><strong>cte)</strong>:<br> For each employee, we calculate a cumulative salary sum (est_bud) <strong>within each experience group</strong>, ordered by ascending salary. This helps us simulate sequential hiring until we cross the budget.</li><li><strong>CTE 2 — Senior Selection</strong>:<br> We first try to hire as many <strong>Seniors</strong> as possible until their cumulative budget is less than 70,000.</li><li><strong>CTE 3 — Junior Selection</strong>:<br> Then, for <strong>Juniors</strong>, we calculate how much budget is left and filter in only those whose cumulative salary fits in the <strong>remaining</strong> amount.</li><li><strong>Final Output</strong>:<br> We use a UNION to combine the selected Seniors and Juniors to form the final hiring list.</li></ol><h3>Approach 2: Condensed Window Function Method</h3><p>This version optimizes the logic into fewer steps and uses conditional aggregation to compare budgets within the same query block.</p><pre>WITH senior AS (<br>  SELECT *, <br>         CASE <br>           WHEN SUM(CASE WHEN experience = &#39;Senior&#39; THEN salary ELSE 0 END) <br>                OVER (PARTITION BY experience ORDER BY salary) &lt; 70000 <br>                AND experience = &#39;Senior&#39; <br>           THEN 1 ELSE 0 <br>         END AS senior_aprv<br>  FROM candidates<br>),</pre><pre>cte AS (<br>  SELECT *,<br>         CASE <br>           WHEN SUM(CASE WHEN experience = &#39;Junior&#39; THEN salary ELSE 0 END) <br>                OVER (PARTITION BY experience ORDER BY salary) &lt; <br>                SUM(CASE WHEN experience = &#39;Senior&#39; AND senior_aprv = 1 <br>                         THEN salary ELSE 0 END) <br>                OVER () <br>                AND experience = &#39;Junior&#39;<br>           THEN 1 ELSE 0 <br>         END AS junior_aprv<br>  FROM senior<br>)</pre><pre>SELECT emp_id, experience, salary<br>FROM cte <br>WHERE senior_aprv = 1 OR junior_aprv = 1;</pre><h3>Explanation of Window Functions Used:</h3><ul><li>SUM(...) OVER (PARTITION BY experience ORDER BY salary):<br> Used to create a <strong>cumulative salary sum</strong>, ordered within experience group. Helps simulate sequential budget allocation.</li><li>CASE WHEN ... THEN 1 ELSE 0 END:<br> Used to flag which employees fall <strong>within the acceptable cumulative budget</strong> slice.</li><li>UNION:<br> Combines two filtered subsets: one of approved seniors, and one of juniors who can fit within the leftover budget.</li></ul><h3>Why This Is Powerful in SQL Interviews</h3><ul><li>This question was asked in multiple interviews and tests <strong>real-world budget slicing</strong>, <strong>window functions</strong>, and <strong>conditional logic</strong>.</li><li>Interviewers are checking:</li><li>Your ability to simulate <strong>sequential logic</strong> using declarative SQL.</li><li>Your understanding of <strong>partitioned window aggregates</strong>.</li><li>How you prioritize one group (Seniors) and fallback to the other (Juniors).</li></ul><h3>Summary</h3><p>In this case study, I tackled a budget-constrained hiring challenge using SQL. I first used a multi-step approach to simulate budget allocation for hiring Seniors first and Juniors afterward. Then I refined that into a tighter query using CASE, SUM, and OVER() window functions to flag eligible employees.</p><p>This example showcases how SQL can be used beyond traditional data analysis — even for <strong>business logic simulation</strong> and <strong>resource allocation problems</strong>.</p><p>If you’re prepping for interviews, especially for roles at product companies or consulting firms, mastering <strong>partitioning + running total</strong> logic like this is a must.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d01c3b002f98" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Walmart Labs SQL Interview Question: Identifying Callers Whose First and Last Call Was to the Same…]]></title>
            <link>https://medium.com/@rajeshkakiofc/walmart-labs-sql-interview-question-identifying-callers-whose-first-and-last-call-was-to-the-same-24322c9de202?source=rss-f54ad082edc0------2</link>
            <guid isPermaLink="false">https://medium.com/p/24322c9de202</guid>
            <category><![CDATA[sql-server]]></category>
            <category><![CDATA[walmart-labs-sql]]></category>
            <category><![CDATA[leetcode-sql]]></category>
            <dc:creator><![CDATA[Rajesh kaki]]></dc:creator>
            <pubDate>Mon, 25 Aug 2025 07:46:22 GMT</pubDate>
            <atom:updated>2025-08-25T07:46:22.885Z</atom:updated>
            <content:encoded><![CDATA[<h3>Walmart Labs SQL Interview Question: Identifying Callers Whose First and Last Call Was to the Same Recipient on a Given Day</h3><p>During one of the Walmart Labs Senior Data Analyst interviews, I encountered a practical real-world SQL problem that tested both temporal logic and precision with aggregation. The question was:</p><p><strong>Problem Statement</strong><br> You’re given a table phonelog with details of call history:</p><pre>Callerid | Recipientid | Datecalled</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/444/1*8NF9miR6LZHN-IbqKRqJGQ.png" /></figure><p>You need to write a SQL query to <strong>identify callers whose first and last call on the same day were made to the same recipient</strong>. In other words, for each caller, if their earliest and latest call (by timestamp) for a given date was made to the same person, return that caller along with the date and recipient.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/383/1*NgcijiocrhXVm4uVn0DT3A.png" /></figure><h3>Thought Process</h3><p>The problem boils down to:</p><ol><li>Identifying <strong>first</strong> and <strong>last</strong> calls made by each caller on each date.</li><li>Comparing the recipients of both calls.</li><li>Returning the match where both are equal.</li></ol><h3>Step-by-Step Breakdown</h3><h4>Step 1: Normalize the Date</h4><p>To make daily grouping easier, we extract only the date portion from the datetime value using CAST().</p><pre>cast(datecalled as date) AS date_str</pre><p>This gives us a uniform date to group calls per day.</p><h4>Step 2: Get First and Last Call Time</h4><p>We use MIN() and MAX() aggregation functions to fetch the first and last call <strong>timestamps</strong> for each (caller, date) combination.</p><pre>WITH cte AS (<br>  SELECT <br>    callerid,<br>    CAST(datecalled AS date) AS date_str,<br>    MIN(datecalled) AS fst,<br>    MAX(datecalled) AS lst<br>  FROM phonelog<br>  GROUP BY callerid, CAST(datecalled AS date)<br>)</pre><p>This CTE returns the earliest and latest datetime of calls made by each caller for each day.</p><h4>Step 3: Fetch Corresponding Recipients</h4><p>Now that we have the fst and lst timestamps for each (caller, date), we join this CTE with the original phonelog table to find out the actual recipientid for both calls.</p><pre>SELECT c.callerid, c.date_str, p1.recipientid<br>FROM cte c<br>INNER JOIN phonelog p1 ON c.callerid = p1.callerid AND c.fst = p1.datecalled<br>INNER JOIN phonelog p2 ON c.callerid = p2.callerid AND c.lst = p2.datecalled<br>WHERE p1.recipientid = p2.recipientid;</pre><p>Here’s what each part is doing:</p><ul><li>p1 gives the recipient of the first call.</li><li>p2 gives the recipient of the last call.</li><li>The WHERE clause ensures we&#39;re only returning cases where <strong>both recipients are the same.</strong></li></ul><h3>Why This Approach?</h3><ul><li><strong>Aggregation:</strong> We use MIN() and MAX() to get exact call boundaries.</li><li><strong>Joining Back:</strong> Since MIN()/MAX() gives us only timestamps, we re-join with the original table to fetch the corresponding recipient.</li><li><strong>Temporal Analysis:</strong> It’s a classic example of tracking changes and comparing events within the same group (caller per day).</li></ul><p>This is highly useful for any <strong>call behavior analytics</strong>, such as detecting repetitive calls or first-last user interactions — a pattern commonly analyzed in telco or customer support domains.</p><h3>Final Thoughts</h3><p>This SQL scenario might appear simple at first glance, but it tests your ability to:</p><ul><li>Work with timestamps</li><li>Use aggregation and self-joins strategically</li><li>Think in terms of <strong>event chronology</strong></li></ul><p>An excellent example of real-world data wrangling, especially relevant in interviews for telecom analytics, customer behavior tracking, or product usage logging.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=24322c9de202" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LeetCode SQL Hard 1412: Quiet Students in Every Exam — Two Approaches- one using window functions…]]></title>
            <link>https://medium.com/@rajeshkakiofc/leetcode-sql-hard-1412-quiet-students-in-every-exam-two-approaches-one-using-window-functions-b3e54ab15b9c?source=rss-f54ad082edc0------2</link>
            <guid isPermaLink="false">https://medium.com/p/b3e54ab15b9c</guid>
            <category><![CDATA[sql-server]]></category>
            <category><![CDATA[leetcode-1412]]></category>
            <category><![CDATA[exists-sql]]></category>
            <dc:creator><![CDATA[Rajesh kaki]]></dc:creator>
            <pubDate>Mon, 25 Aug 2025 06:41:58 GMT</pubDate>
            <atom:updated>2025-08-25T06:41:58.537Z</atom:updated>
            <content:encoded><![CDATA[<h3>LeetCode SQL Hard 1412: Quiet Students in Every Exam — Two Approaches- one using <strong>window functions and CTEs</strong>, and another using <strong>EXISTS and NOT EXISTS</strong> logic.</h3><h4>While preparing for SQL-heavy interviews, I came across an interesting <strong>LeetCode Hard SQL problem</strong> (Problem 1412) that really sharpened my window function and filtering skills. The challenge was to find <strong>“quiet” students</strong> — students who took at least one exam, but <strong>never</strong> scored either the highest or lowest marks in <strong>any</strong> of the exams they appeared in.</h4><h3>Problem Understanding</h3><p>You’re given two tables:</p><pre>students(student_id, student_name)<br>exams(exam_id, student_id, score)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/324/1*foDJttXURYfkxrsIs8orKQ.png" /></figure><p>A student is considered “quiet” if:</p><ul><li>They’ve taken <strong>at least one</strong> exam</li><li>In <strong>none</strong> of their exams did they score the <strong>highest</strong> or <strong>lowest</strong> mark for that exam</li></ul><p>The final result should return:</p><ul><li>student_id, student_name</li><li>Ordered by student_id</li></ul><h3>My Thought Process</h3><p>I immediately knew I needed to:</p><ol><li>Identify the <strong>highest and lowest</strong> score per exam</li><li>Check which students scored those extreme values</li><li>Eliminate them from the final result</li></ol><p>But I also had to ensure the <strong>quiet check applies to every exam</strong> they’ve taken — not just one. So if a student scored between high and low in some exams, but hit a max or min in another — they shouldn’t be in the result.</p><h3>Approach 1: CTE + Window Functions + Filtering</h3><pre>WITH cte AS (<br>  SELECT *, <br>         MAX(score) OVER(PARTITION BY exam_id) AS highest_mark,<br>         MIN(score) OVER(PARTITION BY exam_id) AS lowest_mark<br>  FROM exams<br>),<br>high_low_id AS (<br>  SELECT DISTINCT student_id<br>  FROM cte<br>  WHERE score = highest_mark OR score = lowest_mark<br>)</pre><pre>SELECT DISTINCT s.student_id, s.student_name<br>FROM cte c<br>JOIN students s ON c.student_id = s.student_id<br>WHERE c.score &gt; c.lowest_mark <br>  AND c.score &lt; c.highest_mark<br>  AND s.student_id NOT IN (SELECT * FROM high_low_id)<br>ORDER BY s.student_id;</pre><h4>What this does:</h4><ul><li><strong>CTE (</strong><strong>cte)</strong>: Adds two columns per row: the highest and lowest score for that exam using:</li><li>MAX(score) OVER(PARTITION BY exam_id) MIN(score) OVER(PARTITION BY exam_id)</li><li><strong>CTE (</strong><strong>high_low_id)</strong>: Collects all students who <strong>ever</strong> scored a max or min in any exam.</li><li><strong>Final filter</strong>: Joins with the students table, keeps only those rows where:</li><li>The score is strictly <strong>between</strong> the high and low for that exam</li><li>The student is <strong>not</strong> in the high_low_id list (i.e., never scored an extreme)</li></ul><p>This approach gives a <strong>precise and reliable</strong> result, and I like that it shows clearly who is disqualified due to high or low performance.</p><h3>Approach 2: EXISTS and NOT EXISTS Filtering</h3><p>For comparison, I also built a solution using <strong>conditional filtering</strong> logic. This one is more set-based and declarative.</p><pre>WITH bounds AS (<br>  SELECT exam_id,<br>         MAX(score) AS hi,<br>         MIN(score) AS lo<br>  FROM exams<br>  GROUP BY exam_id<br>)</pre><pre>SELECT s.student_id, s.student_name<br>FROM students s<br>WHERE EXISTS (<br>  SELECT 1 <br>  FROM exams e <br>  WHERE e.student_id = s.student_id<br>)<br>AND NOT EXISTS (<br>  SELECT 1<br>  FROM exams e<br>  JOIN bounds b ON e.exam_id = b.exam_id<br>  WHERE e.student_id = s.student_id<br>    AND (e.score = b.hi OR e.score = b.lo)<br>)<br>ORDER BY s.student_id;</pre><h4>Thought process here:</h4><ul><li>bounds holds the min and max scores for every exam</li><li>I first ensure that each student <strong>has taken</strong> at least one exam (EXISTS)</li><li>Then, I eliminate students who <strong>scored</strong> either the min or max score in any exam (NOT EXISTS)</li><li>Clean, readable logic without needing window functions</li></ul><h3>Comparing Both Techniques</h3><p>Feature Window Function Approach EXISTS/NOT EXISTS Approach Code Complexity Moderate — needs CTE and window imple — uses plain SQL joins Performance DB-dependent, can be optimized Often faster on indexed datasets Filtering granularity Very explicit (high, low separation) Logic-based (set inclusion/exclusion) Window Function Exposure Great for learning partition logic Ideal for beginners to intermediates</p><h3>Final Thoughts</h3><p>This was one of those SQL questions that not only tested my understanding of GROUP BY, joins, and window functions — but also made me think about how <strong>multiple exams</strong> must be considered <strong>cumulatively</strong>. That’s what made the NOT IN and NOT EXISTS filtering conditions the <strong>crucial logic</strong> to solve it correctly.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b3e54ab15b9c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reversing an Array — Extra Space vs. In-Place]]></title>
            <link>https://medium.com/@rajeshkakiofc/reversing-an-array-extra-space-vs-in-place-2e2803326a78?source=rss-f54ad082edc0------2</link>
            <guid isPermaLink="false">https://medium.com/p/2e2803326a78</guid>
            <category><![CDATA[geeksforgeeks]]></category>
            <category><![CDATA[dsa-problem]]></category>
            <category><![CDATA[reverse-array]]></category>
            <category><![CDATA[python-programming]]></category>
            <dc:creator><![CDATA[Rajesh kaki]]></dc:creator>
            <pubDate>Mon, 25 Aug 2025 05:10:29 GMT</pubDate>
            <atom:updated>2025-08-25T05:10:29.280Z</atom:updated>
            <content:encoded><![CDATA[<h3>Reversing an Array — Extra Space vs. In-Place</h3><h4>Two Ways I Solved the Same Problem</h4><p>One of the simplest but most fundamental problems in DSA is:</p><blockquote><em>Reverse an array.</em></blockquote><p>It may look trivial, but it’s a great example to understand the <strong>trade-off between space and time efficiency</strong>.<br> I solved it in <strong>two different ways</strong>:</p><ol><li>Using extra space</li><li>Doing it in-place</li></ol><h3>1. Approach 1 — Using Extra Space</h3><p>Here’s my first thought:</p><ul><li>Create a new array x of the same size.</li><li>Fill it by placing each element of the original array into the reverse position.</li></ul><pre>def reverse(arr):<br>    n = len(arr)<br>    x = [0] * n  # extra array<br>    for i in range(n):<br>        x[n - 1 - i] = arr[i]<br>    return x</pre><h3>Execution Step by Step</h3><ul><li>n = 5 (length of array)</li><li>I create a new list x = [0, 0, 0, 0, 0].</li><li>Now I loop i from 0 to 4:</li><li>i = 0: place arr[0] = 1 at x[4] → x = [0, 0, 0, 0, 1]</li><li>i = 1: place arr[1] = 2 at x[3] → x = [0, 0, 0, 2, 1]</li><li>i = 2: place arr[2] = 3 at x[2] → x = [0, 0, 3, 2, 1]</li><li>i = 3: place arr[3] = 4 at x[1] → x = [0, 4, 3, 2, 1]</li><li>i = 4: place arr[4] = 5 at x[0] → x = [5, 4, 3, 2, 1]</li></ul><p>Final result: [5, 4, 3, 2, 1]</p><p><strong>What’s happening?</strong> I’m basically building a new array from the back. Every element is placed in the opposite index.</p><p><strong>Complexity Analysis:</strong></p><ul><li><strong>Time Complexity:</strong> O(n) (loop runs once through the array)</li><li><strong>Space Complexity:</strong> O(n) (because of the extra array x)</li></ul><p><strong>Thoughts:</strong><br> Simple and easy to implement, but it <strong>doubles memory usage</strong> — not efficient if the array is very large.</p><h3>2. Approach 2 — In-Place Reversal</h3><p>Next, I optimized it:</p><ul><li>Swap elements from start and end, moving towards the center.</li><li>No extra array needed.</li></ul><pre>def reverse(arr):<br>    n = len(arr)<br>    for i in range(n // 2):<br>        arr[i], arr[n - 1 - i] = arr[n - 1 - i], arr[i]<br>    return arr</pre><h3>Execution Step by Step</h3><ul><li>n = 5</li><li>The loop runs from i = 0 to 2 (n//2 = 2):</li><li>i = 0: swap arr[0] and arr[4] → [5, 2, 3, 4, 1]</li><li>i = 1: swap arr[1] and arr[3] → [5, 4, 3, 2, 1]</li><li>Loop ends (middle element 3 stays in place).</li></ul><p>Final result: [5, 4, 3, 2, 1]</p><p><strong>What’s happening?</strong> I’m swapping from both ends, moving inward. Each pair of elements gets reversed in-place.</p><p><strong>Complexity Analysis:</strong></p><ul><li><strong>Time Complexity:</strong> O(n/2) → O(n)</li><li><strong>Space Complexity:</strong> O(1) (done in-place, just swapping values)</li></ul><p><strong>Thoughts:</strong><br> This is the <strong>optimal solution</strong> — minimal space usage while keeping time complexity the same.</p><h3>Final Takeaways</h3><ul><li>Extra-space reversal is easy to understand, but uses O(n) memory.</li><li>In-place reversal is better in practice: same time complexity but only O(1) space.</li><li>This simple problem is a great example of the <strong>time vs. space trade-off</strong> we always face in DSA.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2e2803326a78" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>