<?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 Sakshi Gaur on Medium]]></title>
        <description><![CDATA[Stories by Sakshi Gaur on Medium]]></description>
        <link>https://medium.com/@sakshigaur_74312?source=rss-3f561f03e406------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*OWePr2Bt6pkrgnq9</url>
            <title>Stories by Sakshi Gaur on Medium</title>
            <link>https://medium.com/@sakshigaur_74312?source=rss-3f561f03e406------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 20:40:56 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sakshigaur_74312/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[Starting My AI Learning Journey]]></title>
            <link>https://medium.com/@sakshigaur_74312/starting-my-ai-learning-journey-bb33070b5903?source=rss-3f561f03e406------2</link>
            <guid isPermaLink="false">https://medium.com/p/bb33070b5903</guid>
            <dc:creator><![CDATA[Sakshi Gaur]]></dc:creator>
            <pubDate>Tue, 01 Dec 2026 12:44:28 GMT</pubDate>
            <atom:updated>2026-12-01T12:44:28.965Z</atom:updated>
            <content:encoded><![CDATA[<p><em>I’m learning AI one step at a time — and sharing what I discover along the way.</em></p><p>I’ve spent much of my career building backend systems: working with services, data, queues, and the challenges of making software reliable at scale. Lately, I’ve been thinking about how artificial intelligence is changing the way we build and use software.</p><p>So I’m starting a new learning journey: <strong>understanding AI, building with it, and documenting what I learn.</strong></p><p>I’m not starting this as an expert. I’m starting with curiosity — and with the belief that the best way to understand something is to keep learning, ask questions, and try things for myself.</p><h3>Why I want to learn AI</h3><p>AI can sometimes seem like a collection of new tools and fast-moving announcements. I want to go beyond trying the latest tool and understand the ideas behind it.</p><p>I want to learn how AI systems work, what they can and cannot do, and how engineers can use them to solve real problems. I’m also curious about how my experience in backend engineering connects to this field: how AI features fit into existing systems, how data flows through them, and what it takes to make them useful and dependable.</p><h3>What I plan to explore</h3><p>I’ll work through the fundamentals before rushing into advanced topics. My learning will include:</p><ul><li><strong>Core concepts in machine learning and generative AI</strong></li><li><strong>Large language models and how people build applications with them</strong></li><li><strong>Embeddings, retrieval, and retrieval-augmented generation</strong></li><li><strong>AI agents, tools, and workflows</strong></li><li><strong>Evaluation, reliability, privacy, and responsible use</strong></li><li><strong>Small projects that turn concepts into practice</strong></li></ul><p>I expect the plan to change as I learn more. That’s part of the process.</p><h3>How I’ll document the journey</h3><p>I’ll share notes, explanations, experiments, and mistakes — not just polished results. When I learn a new concept, I’ll try to explain it in simple language. When I build something, I’ll write about what worked, what didn’t, and what I’d change next time.</p><p>My goal is to make these articles useful to other people who are also learning. If a topic feels confusing, I’ll try to break it down. If I find a practical example that makes an idea click, I’ll share it.</p><h3>Starting with curiosity</h3><p>There’s a lot to learn, and I don’t expect to understand it all at once. I’m beginning with the basics, staying open to new ideas, and making room to learn by building.</p><p>This article is my starting point. I’ll keep documenting the journey as I go.</p><p>If you’re learning AI too, I’d love to hear what you’re exploring — and what you found most useful when you were starting out.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bb33070b5903" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Designing BookMyShow: A Deep Dive into Seat Booking, Locking, and Concurrency in detail]]></title>
            <link>https://medium.com/@sakshigaur_74312/designing-bookmyshow-a-deep-dive-into-seat-booking-locking-and-concurrency-dfc64f39bae9?source=rss-3f561f03e406------2</link>
            <guid isPermaLink="false">https://medium.com/p/dfc64f39bae9</guid>
            <category><![CDATA[lld]]></category>
            <category><![CDATA[bookmyshow]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <dc:creator><![CDATA[Sakshi Gaur]]></dc:creator>
            <pubDate>Sun, 17 May 2026 07:34:49 GMT</pubDate>
            <atom:updated>2026-11-22T11:49:17.758Z</atom:updated>
            <content:encoded><![CDATA[<p>Designing a movie ticket booking system like BookMyShow looks simple at first. A user selects a movie, chooses a show, picks seats, makes payment, and receives a ticket.</p><p>But the real complexity starts when thousands of users try to book the same popular show at the same time.</p><p>The most important question is:</p><p><strong>How do we ensure that the same seat is never booked by two users?</strong></p><p>This article explains a low-level design of BookMyShow with a strong focus on concurrency, seat locking, payment handling, and failure scenarios.</p><h3>1. Understanding the Core Flow</h3><p>A typical booking flow looks like this:</p><ol><li>User searches for a movie.</li><li>User selects a city and theatre.</li><li>User chooses a show.</li><li>User views available seats.</li><li>User selects seats.</li><li>System temporarily locks those seats.</li><li>User completes payment.</li><li>On successful payment, booking is confirmed.</li><li>If payment fails or times out, seats are released.</li></ol><p>At a high level, this is simple.</p><p>But internally, the system must carefully manage seat state transitions.</p><h3>2. Important Entities</h3><p>The core entities in the system are:</p><pre>User<br>Movie<br>City<br>Theatre<br>Screen<br>Seat<br>Show<br>ShowSeat<br>Booking<br>Payment</pre><p>The most important entity is ShowSeat.</p><p>A physical seat belongs to a screen.</p><p>For example:</p><pre>Screen 1 -&gt; Seat A1</pre><p>But the same physical seat can be reused across multiple shows.</p><p>So we need a separate entity called ShowSeat.</p><p>Example:</p><pre>Seat A1 for 10 AM show<br>Seat A1 for 2 PM show<br>Seat A1 for 7 PM show</pre><p>Each one has its own availability status.</p><h3>3. Why ShowSeat Is Important</h3><p>A common mistake is to store availability directly in the Seat table.</p><p>That is incorrect.</p><p>A seat is physical.</p><p>Availability is show-specific.</p><p>So we should model it like this:</p><pre>Seat = physical seat<br>ShowSeat = seat availability for a specific show</pre><p>Example:</p><pre>Seat A1 can be booked for 10 AM<br>Seat A1 can still be available for 2 PM<br>Seat A1 can be locked for 7 PM</pre><p>This separation keeps the design clean and scalable.</p><h3>4. Seat State Machine</h3><p>Every show seat can be in one of these states:</p><pre>AVAILABLE<br>LOCKED<br>BOOKED</pre><p>The valid flow is:</p><pre>AVAILABLE -&gt; LOCKED -&gt; BOOKED</pre><p>If payment fails or user does not pay within time:</p><pre>LOCKED -&gt; AVAILABLE</pre><p>A booked seat should not become available again unless there is a cancellation flow.</p><p>So the core transition is:</p><pre>AVAILABLE<br>   |<br>   v<br>LOCKED<br>   |<br>   v<br>BOOKED</pre><p>And timeout flow:</p><pre>LOCKED<br>   |<br>   v<br>AVAILABLE</pre><h3>5. Database Design</h3><p>The most important table is show_seats.</p><pre>CREATE TABLE show_seats (<br>    show_seat_id BIGSERIAL PRIMARY KEY,<br>    show_id BIGINT NOT NULL,<br>    seat_id BIGINT NOT NULL,<br>    status VARCHAR(30) NOT NULL,<br>    locked_by BIGINT,<br>    lock_id VARCHAR(100),<br>    locked_until TIMESTAMP,<br>    price NUMERIC(10,2),<br>    version INT NOT NULL DEFAULT 0,</pre><pre>    UNIQUE(show_id, seat_id)<br>);</pre><p>The unique constraint is very important:</p><pre>UNIQUE(show_id, seat_id)</pre><p>It ensures that for a given show, a seat appears only once.</p><h3>6. Booking Table</h3><pre>CREATE TABLE bookings (<br>    booking_id BIGSERIAL PRIMARY KEY,<br>    user_id BIGINT NOT NULL,<br>    show_id BIGINT NOT NULL,<br>    status VARCHAR(30) NOT NULL,<br>    total_amount NUMERIC(10,2),<br>    idempotency_key VARCHAR(100) UNIQUE,<br>    created_at TIMESTAMP DEFAULT now(),<br>    updated_at TIMESTAMP DEFAULT now()<br>);</pre><p>Booking states can be:</p><pre>INITIATED<br>PENDING_PAYMENT<br>CONFIRMED<br>FAILED<br>EXPIRED<br>CANCELLED</pre><h3>7. Why Seat Locking Is Needed</h3><p>Suppose two users select the same seat at the same time.</p><pre>User A selects A1<br>User B selects A1</pre><p>Without proper locking, both may see the seat as available and both may try to book it.</p><p>This leads to double booking.</p><p>So before payment, the system should temporarily lock the seat.</p><p>The lock gives the user a short time window, usually 5 minutes, to complete payment.</p><h3>8. Seat Locking Flow</h3><p>When a user selects seats and clicks continue:</p><ol><li>System receives seat lock request.</li><li>System checks idempotency key.</li><li>System creates booking in INITIATED state.</li><li>System tries to lock all selected seats.</li><li>If all seats are locked successfully, booking moves to PENDING_PAYMENT.</li><li>If any seat is unavailable, entire transaction rolls back.</li><li>User is redirected to payment page.</li></ol><h3>9. Atomic Conditional Update</h3><p>The safest way to lock a seat is using an atomic database update.</p><pre>UPDATE show_seats<br>SET status = &#39;LOCKED&#39;,<br>    locked_by = :userId,<br>    lock_id = :lockId,<br>    locked_until = :expiryTime,<br>    version = version + 1<br>WHERE show_id = :showId<br>  AND seat_id = :seatId<br>  AND status = &#39;AVAILABLE&#39;;</pre><p>This query succeeds only if the seat is currently available.</p><p>If two users run this query at the same time, only one will update the row successfully.</p><p>The other request will get update count as 0.</p><p>That means the seat is already locked or booked.</p><p>This is the heart of the concurrency design.</p><h3>10. Locking Multiple Seats</h3><p>Users usually book multiple seats together.</p><p>Example:</p><pre>A1, A2, A3</pre><p>The requirement is:</p><p>Either all seats should be locked, or none should be locked.</p><p>This should be done inside a database transaction.</p><p>If locking any seat fails, the transaction should roll back.</p><pre>@Transactional<br>public Booking lockSeats(Long userId, Long showId, List&lt;Long&gt; seatIds, String idempotencyKey) {<br>    Optional&lt;Booking&gt; existing = bookingRepo.findByIdempotencyKey(idempotencyKey);</pre><pre>    if (existing.isPresent()) {<br>        return existing.get();<br>    }</pre><pre>    Booking booking = bookingRepo.create(userId, showId, &quot;INITIATED&quot;, idempotencyKey);</pre><pre>    String lockId = UUID.randomUUID().toString();<br>    LocalDateTime expiry = LocalDateTime.now().plusMinutes(5);</pre><pre>    for (Long seatId : seatIds) {<br>        int updated = showSeatRepo.lockSeat(showId, seatId, userId, lockId, expiry);</pre><pre>        if (updated == 0) {<br>            throw new SeatAlreadyLockedException();<br>        }<br>    }</pre><pre>    bookingRepo.updateStatus(booking.getBookingId(), &quot;PENDING_PAYMENT&quot;);</pre><pre>    return booking;<br>}</pre><p>If any seat fails, the exception rolls back the whole transaction.</p><h3>11. Why Java Locks Are Not Enough</h3><p>We should not rely only on:</p><pre>synchronized<br>ReentrantLock<br>ConcurrentHashMap</pre><p>These work only inside one JVM.</p><p>But in production, there will be multiple application servers.</p><pre>App Server 1<br>App Server 2<br>App Server 3</pre><p>A Java lock on App Server 1 does not protect App Server 2.</p><p>So the final concurrency control must happen at a shared layer like:</p><pre>Database<br>Redis<br>Distributed lock</pre><p>For this design, the database atomic update is the source of truth.</p><h3>12. Optimistic Locking</h3><p>Another option is optimistic locking.</p><p>We keep a version column in show_seats.</p><pre>UPDATE show_seats<br>SET status = &#39;LOCKED&#39;,<br>    version = version + 1<br>WHERE show_id = :showId<br>  AND seat_id = :seatId<br>  AND status = &#39;AVAILABLE&#39;<br>  AND version = :oldVersion;</pre><p>If another transaction changed the row, the version will not match and update will fail.</p><p>Optimistic locking is useful when:</p><pre>Reads are high<br>Contention is moderate<br>We want non-blocking behavior<br>Retries are acceptable</pre><h3>13. Pessimistic Locking</h3><p>Pessimistic locking means we explicitly lock rows before updating.</p><pre>SELECT *<br>FROM show_seats<br>WHERE show_id = :showId<br>  AND seat_id IN (:seatIds)<br>FOR UPDATE;</pre><p>This blocks other transactions from modifying those rows.</p><p>It is useful under high contention, but it has disadvantages:</p><pre>More waiting<br>Lower throughput<br>Possible deadlocks</pre><p>For BookMyShow, atomic conditional update is usually cleaner.</p><h3>14. Redis Lock: Do We Need It?</h3><p>Redis can be used as a fast first layer.</p><p>Example:</p><pre>SET seat_lock:5001:A1 lock_123 NX EX 300</pre><p>This means:</p><pre>Lock this seat only if key does not already exist.<br>Expire the lock after 5 minutes.</pre><p>But Redis should not be the only source of truth.</p><p>The final correctness should still be protected by the database.</p><p>A good interview answer is:</p><blockquote><em>Redis can reduce database load during high traffic, but the database conditional update remains the final guard against double booking.</em></blockquote><h3>15. Payment Flow</h3><p>Once seats are locked, the user is redirected to payment.</p><p>Payment can succeed, fail, timeout, or send duplicate callbacks.</p><p>So payment confirmation must also be idempotent.</p><p>On payment success:</p><pre>UPDATE show_seats<br>SET status = &#39;BOOKED&#39;,<br>    version = version + 1<br>WHERE lock_id = :lockId<br>  AND locked_by = :userId<br>  AND status = &#39;LOCKED&#39;<br>  AND locked_until &gt; now();</pre><p>This confirms only seats that are:</p><pre>Currently locked<br>Locked by the same user<br>Not expired</pre><h3>16. What If Payment Succeeds After Lock Expiry?</h3><p>This is a very common interview follow-up.</p><p>Suppose the lock expires after 5 minutes.</p><p>At 5 minutes 5 seconds, payment success callback comes.</p><p>Should we confirm the booking?</p><p>No.</p><p>Before confirming, we check:</p><pre>AND locked_until &gt; now()</pre><p>If the lock expired, booking should not be confirmed.</p><p>The system can then trigger refund or mark payment as refund pending.</p><h3>17. Expiry Worker</h3><p>If user does not complete payment within 5 minutes, locked seats should be released.</p><p>A background worker can run every few seconds.</p><pre>UPDATE show_seats<br>SET status = &#39;AVAILABLE&#39;,<br>    locked_by = NULL,<br>    lock_id = NULL,<br>    locked_until = NULL,<br>    version = version + 1<br>WHERE status = &#39;LOCKED&#39;<br>  AND locked_until &lt; now();</pre><p>It also updates booking status:</p><pre>UPDATE bookings<br>SET status = &#39;EXPIRED&#39;<br>WHERE status = &#39;PENDING_PAYMENT&#39;<br>  AND created_at &lt; now() - interval &#39;5 minutes&#39;;</pre><p>This ensures locked seats do not remain blocked forever.</p><h3>18. Race Condition: Payment vs Expiry Worker</h3><p>One difficult case is:</p><pre>Payment success callback arrives<br>Expiry worker also runs at the same time</pre><p>Both may try to update the same booking.</p><p>The solution is to use conditional state updates.</p><p>Payment confirmation:</p><pre>UPDATE show_seats<br>SET status = &#39;BOOKED&#39;<br>WHERE lock_id = :lockId<br>  AND status = &#39;LOCKED&#39;<br>  AND locked_until &gt; now();</pre><p>Expiry worker:</p><pre>UPDATE show_seats<br>SET status = &#39;AVAILABLE&#39;<br>WHERE lock_id = :lockId<br>  AND status = &#39;LOCKED&#39;<br>  AND locked_until &lt; now();</pre><p>Only one can succeed.</p><p>This prevents inconsistent state.</p><h3>19. Idempotency</h3><p>Idempotency is extremely important in this system.</p><p>The user may double-click.</p><p>The browser may retry.</p><p>The payment gateway may send duplicate callbacks.</p><p>So we use:</p><pre>X-Idempotency-Key</pre><p>For booking:</p><pre>idempotency_key VARCHAR(100) UNIQUE</pre><p>For payment:</p><pre>gateway_reference_id VARCHAR(100) UNIQUE</pre><p>If the same request comes again, we return the already created booking or payment result.</p><p>We do not create duplicate bookings.</p><h3>20. Full Booking Flow</h3><p>The complete flow is:</p><pre>1. User selects movie.<br>2. User selects show.<br>3. User opens seat layout.<br>4. User selects seats.<br>5. Booking service receives lock request.<br>6. Booking service checks idempotency key.<br>7. Booking service creates booking in INITIATED state.<br>8. Booking service locks selected seats using atomic DB update.<br>9. If any seat fails, transaction rolls back.<br>10. If all seats lock, booking becomes PENDING_PAYMENT.<br>11. User is redirected to payment.<br>12. Payment gateway processes payment.<br>13. Gateway sends callback.<br>14. Payment service verifies callback.<br>15. Booking service checks booking state and lock expiry.<br>16. If valid, seats move from LOCKED to BOOKED.<br>17. Booking becomes CONFIRMED.<br>18. Notification is sent to user.<br>19. If payment fails or timeout happens, seats are released.</pre><h3>21. High-Level Flow Diagram</h3><pre>User selects seats<br>        |<br>        v<br>Booking Service<br>        |<br>        v<br>Check idempotency key<br>        |<br>        v<br>Create booking INITIATED<br>        |<br>        v<br>Lock seats using atomic DB update<br>        |<br>        v<br>All seats locked?<br>   /             \<br> No               Yes<br> |                 |<br>Rollback        Booking PENDING_PAYMENT<br> |                 |<br>Return error     Redirect to payment<br>                   |<br>                   v<br>             Payment callback<br>                   |<br>                   v<br>           Payment success?<br>             /          \<br>           No            Yes<br>           |              |<br>      Release seats    Confirm seats<br>           |              |<br>      Booking failed   Booking confirmed</pre><h3>22. Important Design Patterns</h3><h3>State Pattern</h3><p>Booking and seat status transitions should be controlled.</p><pre>AVAILABLE -&gt; LOCKED -&gt; BOOKED<br>PENDING_PAYMENT -&gt; CONFIRMED<br>PENDING_PAYMENT -&gt; EXPIRED</pre><h3>Strategy Pattern</h3><p>Payment providers can be implemented using strategy pattern.</p><pre>interface PaymentStrategy {<br>    PaymentResponse pay(PaymentRequest request);<br>}</pre><p>Implementations:</p><pre>RazorpayPaymentStrategy<br>StripePaymentStrategy<br>PaytmPaymentStrategy</pre><h3>Repository Pattern</h3><p>Repositories hide database logic.</p><pre>BookingRepository<br>ShowSeatRepository<br>PaymentRepository</pre><h3>Observer Pattern</h3><p>Once booking is confirmed, notification can be sent asynchronously.</p><pre>BookingConfirmedEvent -&gt; Email/SMS/WhatsApp</pre><h3>23. Common Interview Follow-Ups</h3><h3>How do you prevent double booking?</h3><p>Use atomic conditional update:</p><pre>UPDATE show_seats<br>SET status = &#39;LOCKED&#39;<br>WHERE show_id = ?<br>  AND seat_id = ?<br>  AND status = &#39;AVAILABLE&#39;;</pre><p>Only one request can update successfully.</p><h3>What if two users select the same seat?</h3><p>Both may try, but only one update succeeds.</p><p>The second user gets seat unavailable.</p><h3>What if payment succeeds after expiry?</h3><p>Do not confirm booking.</p><p>Check lock expiry before confirming.</p><p>If expired, trigger refund.</p><h3>What if payment callback comes twice?</h3><p>Use unique gateway reference ID or payment idempotency key.</p><p>Return already processed result.</p><h3>What if app crashes after locking seats?</h3><p>Expiry worker releases locked seats after timeout.</p><h3>What isolation level is needed?</h3><p>Usually READ COMMITTED is enough with atomic conditional updates.</p><p>SERIALIZABLE is safer but often overkill and reduces throughput.</p><h3>How do you avoid deadlocks?</h3><p>Always process selected seat IDs in sorted order.</p><pre>Collections.sort(seatIds);</pre><p>This prevents circular waits.</p><h3>25. Final Thoughts</h3><p>BookMyShow is not difficult because of entities like movie, theatre, and screen.</p><p>The real difficulty is seat consistency.</p><p>The interviewer is mainly checking whether we can handle:</p><pre>Double booking<br>Concurrent seat selection<br>Payment timeout<br>Payment callback duplication<br>Lock expiry<br>Race between payment and expiry worker<br>Idempotency<br>Distributed app servers</pre><p>A good design should keep the database as the final source of truth and use conditional updates to protect seat state transitions.</p><p>Redis can improve performance, but correctness should not depend only on Redis.</p><p>The key principle is:</p><blockquote><em>A seat should move from AVAILABLE to LOCKED to BOOKED using controlled, atomic, and idempotent state transitions.</em></blockquote><p>That is the foundation of a reliable ticket booking system.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dfc64f39bae9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[624. Maximum Distance in Arrays]]></title>
            <link>https://medium.com/@sakshigaur_74312/624-maximum-distance-in-arrays-0378e33bdaf2?source=rss-3f561f03e406------2</link>
            <guid isPermaLink="false">https://medium.com/p/0378e33bdaf2</guid>
            <dc:creator><![CDATA[Sakshi Gaur]]></dc:creator>
            <pubDate>Fri, 16 Aug 2024 14:26:07 GMT</pubDate>
            <atom:updated>2024-08-16T14:26:07.507Z</atom:updated>
            <content:encoded><![CDATA[<p>You are given m arrays, where each array is sorted in ascending order. The task is to pick two integers from two different arrays and calculate their distance, defined as the absolute difference between the two numbers. Your goal is to find the maximum distance possible between any two such integers.</p><p><strong>Example 1:</strong></p><pre>Input: arrays = [[1,2,3],[4,5],[1,2,3]]<br>Output: 4<br>Explanation: One way to reach the maximum distance 4 is to pick 1 in the first or third array and pick 5 in the second array.</pre><p><strong>Example 2:</strong></p><pre>Input: arrays = [[1],[1]]<br>Output: 0</pre><h4>Approach and Solution</h4><p>To solve this problem efficiently, we need to take advantage of the fact that the arrays are sorted. The key observation is that the maximum distance will always be between the smallest and largest elements in different arrays.</p><p><strong>Step-by-Step Breakdown:</strong></p><p>To solve this problem efficiently, we need to take advantage of the fact that the arrays are sorted. The key observation is that the maximum distance will always be between the smallest and largest elements in different arrays.</p><p><strong>Initialize Variables: Start by storing the first array’s minimum and maximum values as globalMin and globalMax. Also, initialize a variable ans to store the maximum distance found.</strong></p><p><strong>Iterate Through Remaining Arrays: For each subsequent array:</strong></p><p><strong>Calculate the potential maximum distance by comparing its maximum element with the globalMin and its minimum element with the globalMax.</strong></p><p><strong>Update ans with the maximum of the current distance and the previous maximum.</strong></p><p><strong>Update globalMin and globalMax to reflect the smallest and largest elements encountered so far.</strong></p><p><strong>Return the Result: After iterating through all arrays, ans will contain the maximum distance.</strong></p><p>Here is the Java implementation of the above approach:</p><pre>import java.util.List;<br><br>class Solution {<br>    public int maxDistance(List&lt;List&lt;Integer&gt;&gt; arrays) {<br>        List&lt;Integer&gt; firstArray = arrays.get(0);<br><br>        int globalMin = firstArray.get(0);<br>        int globalMax = firstArray.get(firstArray.size() - 1);<br>        int ans = 0;<br><br>        for (int i = 1; i &lt; arrays.size(); i++) {<br>            List&lt;Integer&gt; currentArray = arrays.get(i);<br>            int currentMin = currentArray.get(0);<br>            int currentMax = currentArray.get(currentArray.size() - 1);<br><br>            ans = Math.max(ans, Math.abs(currentMax - globalMin));<br>            ans = Math.max(ans, Math.abs(currentMin - globalMax));<br><br>            globalMin = Math.min(globalMin, currentMin);<br>            globalMax = Math.max(globalMax, currentMax);<br>        }<br>        return ans;<br>    }<br>}</pre><h4>Time Complexity Analysis</h4><p>The time complexity of this solution is O(m), where m is the number of arrays. This is because we iterate through each array exactly once. The space complexity is O(1), as we only use a few additional variables for storing intermediate results.</p><h4>Conclusion</h4><p>This problem is a classic example of how understanding the properties of the input data — in this case, sorted arrays — can lead to a more efficient solution. By focusing on the minimum and maximum values across arrays, we reduce the complexity and arrive at the correct solution quickly.</p><p>This method is not only efficient but also easy to understand and implement, making it a valuable approach in scenarios where you need to find the maximum distance between elements in sorted arrays.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0378e33bdaf2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Leetcode -1169. Invalid Transactions]]></title>
            <link>https://medium.com/@sakshigaur_74312/leetcode-1169-invalid-transactions-71a96bfc51d9?source=rss-3f561f03e406------2</link>
            <guid isPermaLink="false">https://medium.com/p/71a96bfc51d9</guid>
            <dc:creator><![CDATA[Sakshi Gaur]]></dc:creator>
            <pubDate>Sat, 03 Aug 2024 04:46:39 GMT</pubDate>
            <atom:updated>2024-08-03T04:46:39.436Z</atom:updated>
            <content:encoded><![CDATA[<p>Problem Statement — <br>A transaction is possibly invalid if:</p><ul><li>the amount exceeds $1000, or;</li><li>if it occurs within (and including) 60 minutes of another transaction with the <strong>same name</strong> in a <strong>different city</strong>.</li></ul><p>You are given an array of strings transaction where transactions[i] consists of comma-separated values representing the name, time (in minutes), amount, and city of the transaction.</p><p>Return a list of transactions that are possibly invalid. You may return the answer in <strong>any order</strong>.</p><p><strong>Example 1:</strong></p><pre>Input: transactions = [&quot;alice,20,800,mtv&quot;,&quot;alice,50,100,beijing&quot;]<br>Output: [&quot;alice,20,800,mtv&quot;,&quot;alice,50,100,beijing&quot;]<br>Explanation: The first transaction is invalid because the second transaction occurs within a difference of 60 minutes, have the same name and is in a different city. Similarly the second one is invalid too.</pre><p><strong>Example 2:</strong></p><pre>Input: transactions = [&quot;alice,20,800,mtv&quot;,&quot;alice,50,1200,mtv&quot;]<br>Output: [&quot;alice,50,1200,mtv&quot;]</pre><p><strong>Example 3:</strong></p><pre>Input: transactions = [&quot;alice,20,800,mtv&quot;,&quot;bob,50,1200,mtv&quot;]<br>Output: [&quot;bob,50,1200,mtv&quot;]</pre><p><strong>Constraints:</strong></p><ul><li>transactions.length &lt;= 1000</li><li>Each transactions[i] takes the form &quot;{name},{time},{amount},{city}&quot;</li><li>Each {name} and {city} consist of lowercase English letters, and have lengths between 1 and 10.</li><li>Each {time} consist of digits, and represent an integer between 0 and 1000.</li><li>Each {amount} consist of digits, and represent an integer between 0 and 2000.</li></ul><h3>Step-by-Step Solution</h3><p>We’ll follow these steps:</p><ol><li>Parse the transactions and store them as objects.</li><li>Use a map to group transactions by the person’s name.</li><li>Identify transactions that meet the invalid criteria.</li><li>Return the list of invalid transactions.</li></ol><h3>Step 1: Define a Transaction Class</h3><p>We’ll start by defining a Transaction class to encapsulate the details of each transaction. This will make our code more organized and easier to understand.</p><pre>class Transaction {<br>    String name;<br>    int time;<br>    int amount;<br>    String city;<br>    int index;<br><br>    Transaction(String name, int time, int amount, String city, int index) {<br>        this.name = name;<br>        this.time = time;<br>        this.amount = amount;<br>        this.city = city;<br>        this.index = index;<br>    }<br>}</pre><h3>Step 2: Parse Transactions and Store Them</h3><p>Next, we’ll write a method to parse the transactions and store them in a map. The map will group transactions by the person’s name.</p><pre>import java.util.*;<br><br>class Solution {<br>    public List&lt;String&gt; invalidTransactions(String[] transactions) {<br>        Map&lt;String, List&lt;Transaction&gt;&gt; transactionMap = new HashMap&lt;&gt;();<br>        Set&lt;Integer&gt; invalidIndices = new HashSet&lt;&gt;();<br><br>        // Parse transactions and store them in the map by name<br>        for (int i = 0; i &lt; transactions.length; ++i) {<br>            String[] parts = transactions[i].split(&quot;,&quot;);<br>            String name = parts[0];<br>            int time = Integer.parseInt(parts[1]);<br>            int amount = Integer.parseInt(parts[2]);<br>            String city = parts[3];<br>            Transaction transaction = new Transaction(name, time, amount, city, i);<br>            <br>            transactionMap.computeIfAbsent(name, k -&gt; new ArrayList&lt;&gt;()).add(transaction);<br>            <br>            if (amount &gt; 1000) {<br>                invalidIndices.add(i);<br>            }<br>            <br>            for (Transaction t : transactionMap.get(name)) {<br>                if (!city.equals(t.city) &amp;&amp; Math.abs(time - t.time) &lt;= 60) {<br>                    invalidIndices.add(i);<br>                    invalidIndices.add(t.index);<br>                }<br>            }<br>        }<br><br>        // Collect invalid transactions<br>        List&lt;String&gt; invalidTransactions = new ArrayList&lt;&gt;();<br>        for (int index : invalidIndices) {<br>            invalidTransactions.add(transactions[index]);<br>        }<br>        return invalidTransactions;<br>    }<br>}</pre><h3>Step 3: Identify Invalid Transactions</h3><p>We’ll iterate through each transaction and check if it meets any of the invalid criteria.</p><ul><li>If the amount exceeds $1000, we mark the transaction as invalid.</li><li>We also check if there’s another transaction within 60 minutes in a different city by the same person.</li></ul><h3>Step 4: Collect and Return Invalid Transactions</h3><p>Finally, we collect all invalid transactions and return them as a list.</p><h3>Testing</h3><p>Let’s add a main method to test our solution with some sample transactions.</p><pre>public static void main(String[] args) {<br>    Solution solution = new Solution();<br>    String[] transactions = {<br>        &quot;Alice,20,800,NewYork&quot;, &quot;Alice,50,1200,SanFrancisco&quot;, &quot;Alice,75,100,SanFrancisco&quot;,<br>        &quot;Bob,30,300,NewYork&quot;, &quot;Bob,90,1200,LosAngeles&quot;, &quot;Bob,150,200,NewYork&quot;,<br>        &quot;Charlie,10,700,NewYork&quot;, &quot;Charlie,20,600,Boston&quot;, &quot;Charlie,25,300,NewYork&quot;,<br>        &quot;David,40,200,Chicago&quot;, &quot;David,50,500,Chicago&quot;, &quot;David,60,400,NewYork&quot;,<br>        &quot;Eve,110,100,SanFrancisco&quot;, &quot;Eve,120,1300,SanFrancisco&quot;, &quot;Eve,130,500,LosAngeles&quot;,<br>        &quot;Frank,40,900,Chicago&quot;, &quot;Frank,45,1100,LosAngeles&quot;, &quot;Frank,70,600,Chicago&quot;<br>    };<br>    <br>    List&lt;String&gt; invalid = solution.invalidTransactions(transactions);<br>    for (String s : invalid) {<br>        System.out.println(s);<br>    }<br>}</pre><h3>Time Complexity Analysis</h3><p>To analyze the time complexity of our solution, let’s break down the operations step by step.</p><ol><li><strong>Parsing Transactions</strong>:</li></ol><p>We iterate over each transaction once to parse it and store it in the map.Let nnn be the number of transactions.Time complexity for parsing all transactions: O(n)</p><p><strong>2.Checking for Invalid Transactions</strong>:</p><ul><li>For each transaction, we check if it meets the invalid criteria (amount &gt; 1000).</li><li>For each transaction, we also compare it against all other transactions with the same name to check the time and city conditions.</li><li>In the worst case, if there are nnn transactions and all have the same name, we may need to compare each transaction with every other transaction with the same name.</li><li>Time complexity for this step: O(n²)</li></ul><p><strong>3.Collecting Invalid Transactions</strong>:</p><ul><li>We collect invalid transactions based on the indices stored in a set.</li><li>Time complexity for collecting results: O(n).</li></ul><h3>Overall Time Complexity</h3><p>Combining the above steps, the overall time complexity is dominated by the pairwise comparison step:</p><p>O(n)+O(n²)+O(n) =O(n²)</p><p>Thus, the time complexity of the solution is O(n²).</p><h3>Space Complexity Analysis</h3><ol><li><strong>Storage of Transactions</strong>:</li></ol><ul><li>We use a map to store lists of transactions by name.</li><li>In the worst case, we store all transactions in the map.</li><li>Space complexity for storing transactions: O(n)</li></ul><ol><li><strong>Storing Indices of Invalid Transactions</strong>:</li></ol><ul><li>We use a set to store indices of invalid transactions.</li><li>In the worst case, all transactions are invalid, so we store nnn indices.</li><li>Space complexity for storing indices: O(n)</li></ul><h3>Overall Space Complexity</h3><p>Combining the storage requirements:</p><p>O(n)+O(n)=O(n)</p><p>Thus, the space complexity of the solution is O(n).</p><h3>Conclusion</h3><ul><li><strong>Time Complexity:</strong> O(n²)</li><li><strong>Space Complexity:</strong> O(n)</li></ul><p>This analysis indicates that while the solution is space-efficient, the time complexity is quadratic, which may become a bottleneck for very large datasets. Further optimizations may be required for handling larger inputs efficiently.</p><h3>Conclusion</h3><p>In this guide, we demonstrated a straightforward approach to detect potentially invalid transactions using Java. By defining a Transaction class and utilizing maps and sets, we effectively organized and processed the data to identify invalid transactions.</p><p>This solution is beginner-friendly and highlights key Java concepts such as classes, lists, maps, and basic control structures. Feel free to experiment with the code and try out different scenarios to deepen your understanding.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=71a96bfc51d9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Leetcode 1765. Map of Highest Peak]]></title>
            <link>https://medium.com/@sakshigaur_74312/leetcode-1765-map-of-highest-peak-899b989e60e9?source=rss-3f561f03e406------2</link>
            <guid isPermaLink="false">https://medium.com/p/899b989e60e9</guid>
            <dc:creator><![CDATA[Sakshi Gaur]]></dc:creator>
            <pubDate>Wed, 12 Jun 2024 07:41:25 GMT</pubDate>
            <atom:updated>2024-06-12T07:41:25.308Z</atom:updated>
            <content:encoded><![CDATA[<h3>Problem Description</h3><p>Given a matrix isWater representing a map with land and water cells, the task is to assign each cell a height based on certain rules. Cells with isWater[i][j] == 0 are land, and cells with isWater[i][j] == 1 are water. Water cells must have a height of 0, while land cells must be assigned a non-negative height. The key requirement is that any pair of adjacent cells must differ in height by at most 1. The goal is to maximize the highest height in the matrix while following the aforementioned conditions. The solution should return a new matrix, height, where height[i][j] represents the height of cell (i, j).</p><p>Link of the question : <a href="https://leetcode.com/problems/map-of-highest-peak/description/">https://leetcode.com/problems/map-of-highest-peak/description/</a></p><p><strong>Introduction</strong></p><p>In terrain analysis, determining the elevation of land based on the proximity to water sources is essential for various applications, from flood prediction to landscape modeling. Given a 2D grid where each cell represents either water or land, we need to compute the elevation for land cells such that each land cell’s elevation is the minimum distance to the nearest water cell. This task can be efficiently accomplished using the Breadth-First Search (BFS) algorithm.</p><p>In this article, we will guide you through a step-by-step implementation of this problem in Java, leveraging BFS to ensure an optimal and systematic approach to calculating the highest peaks.</p><p><strong>Problem Definition</strong></p><p>Consider a 2D integer grid arr where:</p><ul><li>arr[i][j] = 1 indicates water.</li><li>arr[i][j] = 0 indicates land.</li></ul><p>Our goal is to generate a new grid where the value at each cell represents its elevation, defined as the shortest distance from any water cell. Water cells retain an elevation of 0.</p><p><strong>Approach</strong></p><p>To solve this problem, we use BFS due to its nature of exploring all nodes at the present depth before moving on to nodes at the next depth level. This characteristic makes BFS ideal for finding the shortest path in an unweighted grid, ensuring that the closest water cell to any land cell is found first.</p><p><strong>Steps for Implementation</strong></p><h3>1. Data Structures and Initialization</h3><ul><li><strong>Queue</strong>: We use a LinkedList to facilitate BFS. It will store the coordinates of cells to be processed.</li><li><strong>Visited Array</strong>: A boolean array helps track whether a cell has been visited to avoid re-processing.</li><li><strong>Direction Arrays</strong>: Arrays dx and dy represent movement in four cardinal directions: right, down, left, and up.</li></ul><h3>2. Algorithm Steps</h3><ol><li><strong>Initialize the Grid and BFS Queue</strong>: Identify water cells and enqueue their coordinates, setting their elevation to 0. Initialize land cells with -1 to indicate they have not been visited.</li><li><strong>BFS Traversal</strong>: Dequeue cells one by one, explore their neighbors, update the neighbors’ elevation, and enqueue them if they haven’t been visited yet.</li><li><strong>Distance Calculation</strong>: The elevation of each land cell is computed as 1 more than the elevation of its nearest water cell.</li></ol><h3>3. Java Code Implementation</h3><p>Below is the complete code for the solution:</p><pre>import java.util.LinkedList;<br>import javafx.util.Pair; // For Pair class usage<br><br>class Solution {<br>    // Direction arrays for movement in 4 directions: right, down, left, up<br>    int[] dx = {1, 0, -1, 0};<br>    int[] dy = {0, 1, 0, -1};<br>    <br>    public int[][] highestPeak(int[][] arr) {<br>        int row = arr.length;<br>        int col = arr[0].length;<br>        int[][] ans = new int[row][col];<br>        boolean[][] visited = new boolean[row][col];<br>        <br>        // Initialize the answer array and the BFS queue<br>        LinkedList&lt;Pair&lt;Integer, Integer&gt;&gt; pq = new LinkedList&lt;&gt;();<br>        <br>        // Enqueue all water cells<br>        for (int i = 0; i &lt; row; i++) {<br>            for (int j = 0; j &lt; col; j++) {<br>                if (arr[i][j] == 1) {<br>                    ans[i][j] = 0; // Water cell height is 0<br>                    pq.addLast(new Pair&lt;&gt;(i, j));<br>                    visited[i][j] = true;<br>                } else {<br>                    ans[i][j] = -1; // Unvisited land cells<br>                }<br>            }<br>        }<br>        <br>        // Perform BFS to calculate highest peak for each land cell<br>        bfs(pq, ans, visited, row, col);<br>        <br>        return ans;<br>    }<br>    <br>    private void bfs(LinkedList&lt;Pair&lt;Integer, Integer&gt;&gt; pq, int[][] ans, boolean[][] visited, int row, int col) {<br>        // Process each cell in the BFS queue<br>        while (!pq.isEmpty()) {<br>            Pair&lt;Integer, Integer&gt; cell = pq.removeFirst();<br>            int currentX = cell.getKey();<br>            int currentY = cell.getValue();<br>            <br>            // Explore 4 possible directions<br>            for (int i = 0; i &lt; 4; i++) {<br>                int newX = currentX + dx[i];<br>                int newY = currentY + dy[i];<br>                <br>                // Check if new coordinates are valid and unvisited<br>                if (isValid(newX, newY, row, col) &amp;&amp; !visited[newX][newY]) {<br>                    ans[newX][newY] = ans[currentX][currentY] + 1;<br>                    pq.addLast(new Pair&lt;&gt;(newX, newY));<br>                    visited[newX][newY] = true;<br>                }<br>            }<br>        }<br>    }<br>    <br>    private boolean isValid(int x, int y, int row, int col) {<br>        return x &gt;= 0 &amp;&amp; x &lt; row &amp;&amp; y &gt;= 0 &amp;&amp; y &lt; col;<br>    }<br>}</pre><p><strong>Detailed Explanation:</strong></p><p><strong>Initialization</strong>:</p><ul><li>Grid Setup: The ans array initializes the elevation grid. Water cells are set to 0 because they are the source of elevation, while land cells are initially -1, indicating they need processing.</li><li>Queue: The pq queue contains water cell coordinates. Starting from water ensures BFS calculates the shortest path to the nearest water cell for every land cell.</li><li>Visited Tracking: The visited array prevents re-processing cells, ensuring each cell is only handled once.</li></ul><p><strong>Enqueue Water Cells</strong>:</p><ul><li><strong>Grid Iteration</strong>: The nested loops iterate through the grid. If a cell is water (arr[i][j] == 1), it is enqueued in pq, marked as visited, and its elevation set to 0.</li></ul><p><strong>BFS Traversal</strong>:</p><p><strong>Processing Queue</strong>: Dequeue a cell and explore its neighbors. For each valid neighbor (within grid bounds and not visited), update its elevation as ans[currentX][currentY] + 1, mark it visited, and enqueue it.</p><p><strong>Valid Cell Check</strong>:</p><ul><li><strong>Boundary Check</strong>: The isValid method ensures that the new coordinates are within the grid limits, thus preventing out-of-bound errors.</li></ul><p><strong>Conclusion</strong></p><p>By leveraging BFS, this algorithm effectively computes the elevation for land cells based on their shortest distance to water cells. This BFS-based method ensures efficiency, making it suitable for handling large grids typical in terrain analysis problems.</p><p>This implementation not only solves the given problem but also serves as a robust framework for tackling similar grid-based challenges where distance calculations from multiple sources are required.</p><h3>Time Complexity</h3><p>To determine the time complexity, consider the following steps of the algorithm:</p><p><strong>Initialization</strong>:</p><ul><li>Iterate through each cell to enqueue water cells and initialize the ans array.</li><li>Time Complexity: O(N×M)O(N \times M)O(N×M), where NNN is the number of rows and MMM is the number of columns in the grid.</li></ul><p><strong>BFS Traversal</strong>:</p><ul><li>Each cell is processed exactly once. For each cell, we check up to 4 neighboring cells.</li><li>Dequeuing a cell and enqueuing its neighbors also takes constant time per cell.</li><li>Time Complexity: O(N×M)O(N \times M)O(N×M), as each cell is processed once, and each operation on the queue is constant time.</li></ul><p><strong>Overall Time Complexity</strong>: The initialization and BFS traversal both contribute to a linear complexity relative to the number of cells. Thus, the overall time complexity is: O(N×M)O(N \times M)O(N×M)</p><h3>Space Complexity</h3><p>The space complexity includes the space used for the BFS queue, the ans array, and the visited array.</p><p><strong>Queue (</strong><strong>pq)</strong>:</p><ul><li>In the worst case, the queue may contain all cells in the grid at some point, especially if the entire grid is land with a single water cell expanding outwards.</li><li>Space Complexity: O(N×M)O(N \times M)O(N×M).</li></ul><p><strong>Answer Array (</strong><strong>ans)</strong>:</p><ul><li>Stores the elevation of each cell.</li><li>Space Complexity: O(N×M)O(N \times M)O(N×M).</li></ul><p><strong>Visited Array (</strong><strong>visited)</strong>:</p><ul><li>Keeps track of whether each cell has been processed.</li><li>Space Complexity: O(N×M)O(N \times M)O(N×M).</li></ul><p><strong>Overall Space Complexity</strong>: The space used is dominated by the storage of the grid and auxiliary structures, leading to: O(N×M)O(N \times M)O(N×M)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=899b989e60e9" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>