<?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 Tech Sauce on Medium]]></title>
        <description><![CDATA[Stories by Tech Sauce on Medium]]></description>
        <link>https://medium.com/@techsauce?source=rss-32c92f65c2e9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*dmbNkD5D-u45r44go_cf0g.png</url>
            <title>Stories by Tech Sauce on Medium</title>
            <link>https://medium.com/@techsauce?source=rss-32c92f65c2e9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 18:47:20 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@techsauce/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[How to Design a Ticket Booking System (e.g., Ticketmaster)?]]></title>
            <link>https://techsauce.medium.com/how-to-design-a-ticket-booking-system-e-g-ticketmaster-6011406962ef?source=rss-32c92f65c2e9------2</link>
            <guid isPermaLink="false">https://medium.com/p/6011406962ef</guid>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[system-design-course]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[tech-interview]]></category>
            <category><![CDATA[architecture]]></category>
            <dc:creator><![CDATA[Tech Sauce]]></dc:creator>
            <pubDate>Thu, 26 Jun 2025 22:14:29 GMT</pubDate>
            <atom:updated>2025-06-26T22:14:29.036Z</atom:updated>
            <content:encoded><![CDATA[<p>Ever wondered how Ticketmaster handles a Taylor Swift concert tickets on-sale without crashing?</p><p>Let’s simulate this system design interview.</p><p><strong>Interviewer:</strong> I’d like you to design an online ticket booking system, something like Ticketmaster or Live Nation.</p><p><strong>Candidate:</strong> Sure. This is an interesting problem with some unique challenges, especially around <em>concurrency</em> and <em>high-demand events</em>.</p><h3>Step 1: Understand and Clarify Requirements</h3><p><strong>Candidate:</strong> I’ll follow a structured approach. First, I’ll clarify the requirements, then move to a high-level design, deep-dive into specific components, address bottlenecks and scaling, discuss trade-offs, and finally, wrap up.</p><p>So, first let me understand and clarify the requirements.</p><p>My understanding is that we need a system where <strong>users</strong> can <em>browse events</em>, <em>select seats</em>, <em>book tickets, and make payments</em>. <strong>Promoters</strong> should also be able to <strong>create</strong> <strong>and manage events</strong>. Are there any other core functionalities we should consider?</p><p><strong>Interviewer:</strong> That’s a good summary. Let’s focus on the user-facing side for now — Browse, selecting, and booking. We can assume the event management part is handled by a separate internal system.</p><p><strong>Candidate:</strong> Understood. Now, let me break down the requirements.</p><p><strong>Functional Requirements:</strong></p><ul><li>Users can <strong><em>search</em></strong> for events by name, venue, or date.</li><li>Users can <strong><em>view</em></strong> event details, including seating maps and ticket prices.</li><li>Users must be able to <strong><em>select specific seats</em></strong> or a quantity of tickets in a specific section.</li><li>Once seats are selected, they should be <strong>held or reserved</strong> for a short period (e.g., 10 minutes) to allow the user to complete the purchase.</li><li>Users can <strong><em>complete the purchase</em></strong> using a payment gateway.</li><li>After purchase, users <strong><em>receive a confirmation</em></strong> and the e-tickets.</li></ul><p><strong>Non-Functional Requirements:</strong></p><ul><li><strong>High Availability:</strong> The system must be highly available, especially during major on-sale events. A few minutes of downtime can mean millions in lost revenue.</li><li><strong>Low Latency:</strong> Searching for events and viewing seat maps should be fast to provide a good user experience.</li><li><strong>Consistency:</strong> This is critical. We absolutely cannot sell the same seat to two different users. The system needs <strong>strong consistency</strong>, especially <em>in the booking and payment flow.</em></li><li><strong>Scalability:</strong> The system must handle massive, sudden traffic spikes. A popular concert going on sale can attract millions of users in a very short time.</li></ul><p>Does this align with your expectations?</p><p><strong>Interviewer:</strong> Yes, that’s a perfect breakdown. Can you estimate the scale we should be designing for?</p><p><strong>Candidate:</strong> Absolutely. Let’s do some back-of-the-envelope calculations.</p><p><strong>Scale Estimation:</strong></p><ul><li>Let’s assume we have <strong>10 million active users</strong> per month.</li><li>On an average day, we might have <strong>2 million daily active users (DAU)</strong>.</li><li>However, the traffic isn’t evenly distributed. Let’s say a major event for an artist like Taylor Swift goes on sale. We could have <strong>5 million users</strong> trying to access the system in the first 10 minutes.</li><li>This translates to a peak request rate. 5 million users in 10 minutes is</li></ul><p>5,000,000 / (10∗60) ≈ 8,333 requests per second (RPS).</p><p>This is just for initial page loads. The actual interactions (selecting seats, holding tickets) will generate even more traffic. Let’s design for a peak of <strong>50,000 RPS</strong>.</p><ul><li><strong>Storage:</strong> If we sell 100 million tickets a year, and each ticket record with user info, event info, etc., takes about 2 KB, that’s</li></ul><p>100,000,000 ∗ 2 KB = 200 GB of ticket data per year.</p><p>Over 5 years, that’s 1 TB. We also need to store event data, venue maps, and user profiles, so storage needs are significant but manageable.</p><p>The <em>key challenge</em> isn’t storage volume; it’s handling the <em>massive concurrent write operations</em> during a ticket release. The <strong>50k RPS</strong> figure is our critical benchmark for scalability.</p><p><strong>Interviewer:</strong> Excellent. You’ve clearly defined the problem and the scale. Let’s move on to the design.</p><p>Want to get access to <strong><em>frequently asked system design interview questions</em></strong>, <strong><em>with complete solutions</em></strong> broken down using 6-step framework as illustrated in this post, then get hold of the book <strong><em>“</em></strong><a href="https://www.amazon.com/Handbook-System-Interview-Success-Follow-ebook/dp/B0FDYC527S/"><strong><em>HANDBOOK FOR SYSTEM DESIGN INTERVIEW SUCCESS</em></strong></a><strong><em>”.</em></strong> Its practical, real-world interview scenarios will give you a repeatable framework and the confidence to handle any question that comes your way. <strong><em>Be interview ready</em></strong>!</p><h3>Step 2: High-Level Design</h3><p><strong>Candidate:</strong> Great. Now for <strong>High-Level Design</strong>. I’ll start with the major services and then define the API and data models.</p><p>At a high level, the system can be broken down into a few key services:</p><ul><li><strong>Client (Web/Mobile):</strong> The user interface.</li><li><strong>API Gateway:</strong> A single entry point for all client requests, handling routing, rate limiting, and authentication.</li><li><strong>Event Service:</strong> Manages event information, including search and details. This is mostly a <strong><em>read-heavy</em></strong> service.</li><li><strong>Booking Service:</strong> The core service that handles the complex logic of seat selection, reservation, and payment processing. This is extremely <strong><em>write-heavy</em></strong>.</li><li><strong>Payment Service:</strong> Integrates with <em>third-party</em> payment gateways.</li><li><strong>Notification Service:</strong> Sends emails or push notifications with ticket confirmations.</li><li><strong>Databases:</strong> We’ll likely need <em>different types of databases</em> for different services.</li></ul><p>Here is a simple diagram showing how these components interact.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0DDRaFPuuofLN1iW" /></figure><p><strong>API Endpoints</strong></p><p>Now, let’s define the core <strong>API Endpoints</strong>. The API would be RESTful.</p><ul><li>GET /api/v1/events?search={params}: Search for events.</li><li>GET /api/v1/events/{eventId}: Get details for a specific event, including the seating map.</li><li>POST /api/v1/tickets/hold: Request to reserve specific seats.</li></ul><p><strong>Request Body:</strong> { “eventId”: “uuid”, “seats”: [“A1”, “A2”], “userId”: “uuid” }</p><p><strong>Response:</strong> { “holdId”: “uuid”, “expiresAt”: “timestamp” }</p><ul><li>POST /api/v1/tickets/book: Confirm the booking for a held set of tickets.</li></ul><p><strong>Request Body:</strong> { “holdId”: “uuid”, “paymentToken”: “string” }</p><p><strong>Response:</strong> { “bookingId”: “uuid”, “tickets”: […] }</p><p><strong>Data Models</strong></p><p>Here is the data model with a specific database type.</p><p><strong>Events Table (SQL or NoSQL DocumentDB):</strong></p><ul><li>eventId (Primary Key)</li><li>eventName</li><li>venueId</li><li>startTime, endTime</li><li>description</li></ul><p><strong>Venues Table (SQL):</strong></p><ul><li>venueId (Primary Key)</li><li>venueName</li><li>address</li><li>seatingChart (Could be JSON or a link to a file)</li></ul><p><strong>Tickets Table (SQL for ACID properties):</strong></p><ul><li>ticketId (Primary Key)</li><li>eventId</li><li>seatId</li><li>userId (Null until booked)</li><li>status (e.g., ‘available’, ‘held’, ‘booked’)</li><li>holdId (Null until held)</li><li>holdExpiresAt (Null until held)</li><li>bookingId</li></ul><p><strong>Bookings Table (SQL):</strong></p><ul><li>bookingId (Primary Key)</li><li>userId</li><li>totalAmount</li><li>paymentStatus</li></ul><p>For the <strong>Tickets</strong> table, using a relational database like PostgreSQL makes sense because we need strong <em>transactional guarantees</em> (ACID) to avoid double-booking a seat.</p><p>The <strong>Events</strong> data is less relational and could live in a NoSQL database like MongoDB for flexibility.</p><p><strong>Interviewer:</strong> This is a good high-level plan. You mentioned the booking flow is the most critical part. Let’s dive deep into that.</p><h3>Step 3: Deep Dive into Specific Components</h3><p>The biggest challenge is handling the <strong>‘thundering herd’ </strong>problem. When a popular event goes on sale, thousands of users will try to book the same limited set of premium seats simultaneously. A naive ‘SELECT and UPDATE’ approach on the database will lead to race conditions and database locks, grinding the system to a halt.</p><p>Here’s my proposed solution to manage this:</p><ol><li><strong>Decouple Reservation from Booking:</strong> We’ll use a message queue to handle the high volume of reservation requests. When a user tries to hold a seat, the request isn’t processed synchronously. Instead, it’s placed onto a queue.</li><li><strong>Use a Distributed Lock Manager:</strong> To ensure that only one process can attempt to reserve a specific seat at a time, we’ll use a distributed lock (e.g., implemented with Redis or Zookeeper).</li><li><strong>Use a Pub/Sub Model for Status Updates:</strong> After the reservation request is processed, we need to inform the user whether they got the seats or not. A publish-subscribe model is perfect for this. The backend publishes the result, and the client, which has subscribed to a specific channel, receives the update via a WebSocket.</li></ol><p>Let’s walk through the flow:</p><ol><li>User selects seats and clicks ‘Hold’.</li><li>The client sends a “POST /api/v1/tickets/hold” request to the API Gateway.</li><li>The Booking Service receives the request, generates a unique requestId, and immediately publishes a message to a Kafka topic, let’s call it <strong>ticket-hold-requests</strong>. The message contains { requestId, eventId, seats, userId }.</li><li>The Booking Service responds to the client with a 202 Accepted status and the requestId.</li><li>The client opens a WebSocket connection to a notification service, subscribing to updates for that requestId. The UI shows a “Holding your seats…” message.</li><li>A pool of <strong>Reservation Workers</strong> consumes messages from the <strong>ticket-hold-requests</strong> topic.</li><li>For each message, a worker attempts to acquire a distributed lock for each requested seat (e.g., a lock key could be lock:{eventId}:{seatId}).</li><li>If it acquires all locks, it updates the Tickets table, setting their status to ‘held’, and populates holdId and holdExpiresAt. It then releases the locks.</li><li>The worker publishes the result (‘success’ or ‘fail’) to a <strong>ticket-hold-results</strong> topic.</li><li>The Notification Service consumes from this results topic and pushes the update to the correct client via the WebSocket.</li><li>If successful, the client starts a 10-minute countdown timer. If not, it informs the user the seats are no longer available.</li></ol><p>This asynchronous approach prevents the API from being blocked and protects the database from being overwhelmed. It essentially creates an orderly queue for a chaotic process.</p><p>Here is the <strong>Enhanced Design Diagram</strong> illustrating this flow:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VtoOT-L19mXcQFFx" /></figure><p><strong>Interviewer:</strong> I like the asynchronous, decoupled approach. It handles the concurrency problem elegantly. But what are the new bottlenecks in this design, especially during that peak rush?</p><p>Want to get access to <strong><em>frequently asked system design interview questions</em></strong>, <strong><em>with complete solutions</em></strong> broken down using 6-step framework as illustrated in this post, then get hold of the book <strong><em>“</em></strong><a href="https://www.amazon.com/Handbook-System-Interview-Success-Follow-ebook/dp/B0FDYC527S/"><strong><em>HANDBOOK FOR SYSTEM DESIGN INTERVIEW SUCCESS</em></strong></a><strong><em>”.</em></strong> Its practical, real-world interview scenarios will give you a repeatable framework and the confidence to handle any question that comes your way. <strong><em>Be interview ready</em></strong>!</p><h3>Step 4: Identify Bottlenecks and Scale the Design</h3><p><strong>Candidate:</strong> Sure, I will address the potential bottlenecks now.</p><p>Even with the queue, we have a few potential bottlenecks:</p><ol><li><strong>Database Hotspots:</strong> For a single popular event, all the write operations (updating ticket status) will be concentrated on a small set of rows in the <strong>Tickets</strong> table related to that <strong>eventId</strong>. This can overwhelm a single database server, even with our queuing system.</li><li><strong>The “On-Sale” Moment:</strong> At the exact second the tickets go on sale, the Event Service will be hammered with requests for the event details and seating map. This is a “<strong>read” bottleneck</strong>.</li><li><strong>Reservation Worker Pool:</strong> If the rate of incoming requests is higher than the rate at which workers can process them, the queue will grow indefinitely, leading to long wait times for users.</li><li><strong>Payment Gateway:</strong> The payment gateway might have its own rate limits, and a flood of simultaneous payment requests could cause failures.</li></ol><p>Here’s how we can address these:</p><ul><li><strong>Solving Database Hotspots with Sharding:</strong> The <strong>Tickets</strong> table is our biggest concern. We can <strong>shard</strong> the database. A simple sharding key would be <strong>eventId</strong>. All tickets for a given event go to the same shard. This distributes the load across different database servers. For a massive global event (like the Olympics), we could even “shard” by <strong>eventId</strong> and <strong>seatSection</strong> to further distribute the write load.</li><li><strong>Solving Read Bottlenecks with Caching:</strong> For the “on-sale” moment, we can aggressively cache static event data and seating maps. We can pre-load all the details for a highly anticipated event into a distributed cache like <strong>Redis</strong> or <strong>Memcached</strong>. The data can even be pushed to a <strong>Content Delivery Network (CDN)</strong>, so users around the world get the data from a server near them, reducing latency and load on our Event Service.</li><li><strong>Scaling the Workers:</strong> The Reservation Workers are stateless, so we can use an <strong>auto-scaling group</strong>. We can monitor the size of the Kafka queue (<strong>ticket-hold-requests</strong>). If the queue depth exceeds a certain threshold, we automatically spin up more worker instances to increase the processing rate.</li><li><strong>Throttling Payments:</strong> We can throttle requests to the payment gateway from our side to avoid hitting their rate limits. If a payment fails due to a temporary gateway issue, we can have a retry mechanism with exponential backoff.</li></ul><p>Here is the <strong>Final Optimized Architecture Diagram</strong> incorporating these scaling solutions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*40-IQw0afBIWDe-2" /></figure><p><strong>Interviewer:</strong> This looks like a very robust and scalable design. You’ve clearly thought through the major failure points. Now, let’s talk about some of the choices you made. Why SQL for the Tickets DB? Why not a NoSQL database?</p><h3>Step 5: Discuss Trade-offs and Alternatives</h3><p><strong>Candidate:</strong> Of course.</p><p><strong>SQL (PostgreSQL) vs. NoSQL (e.g., DynamoDB) for the Tickets Table:</strong></p><ul><li><strong>My Choice: SQL.</strong> I chose a relational database like PostgreSQL for the Tickets and Bookings tables primarily for its <strong>strong ACID guarantees</strong>. When it comes to booking a specific, unique item like a seat, preventing double-spending (or double-booking) is paramount. SQL transactions (BEGIN, COMMIT, ROLLBACK) are perfect for this. The operation ‘check if a seat is available and update its status’ needs to be atomic.</li><li><strong>Trade-off:</strong> The downside of SQL is that it can be harder to scale horizontally. My sharding strategy addresses this, but it adds operational complexity.</li><li><strong>Alternative: NoSQL.</strong> We <em>could</em> use a NoSQL database like DynamoDB with conditional writes (e.g., UpdateItem only if status is ‘available’). This could offer better scalability and performance. However, managing transactions across multiple items (e.g., booking two seats at once) becomes much more complex in the application code. Given the extreme importance of consistency here, I believe the trade-off of using a battle-tested relational database is worth it.</li></ul><p><strong>Distributed Locking: Redis vs. Zookeeper:</strong></p><ul><li><strong>My Choice: Redis.</strong> I suggested Redis for distributed locking because it’s extremely fast (in-memory) and relatively simple to implement (using commands like SETNX — SET if Not eXists). For a short-lived lock needed for a quick database update, its performance is ideal.</li><li><strong>Trade-off:</strong> The standard Redis lock is not foolproof (e.g., a node can crash after acquiring a lock). There are more robust algorithms like Redlock, but they add complexity.</li><li><strong>Alternative: Zookeeper.</strong> Zookeeper provides a much more robust, CP (Consistent and Partition-Tolerant) locking mechanism. It’s designed for coordination and is safer. However, it’s more complex to set up and manage and has higher latency than Redis. For our use case, where lock contention is high but the critical section is short, the performance of Redis is a better fit, accepting the minimal risk.</li></ul><p><strong>Communication: WebSockets vs. Long Polling:</strong></p><ul><li><strong>My Choice: WebSockets.</strong> For sending the ‘hold successful’ message back to the client, I chose WebSockets because they provide a persistent, bi-directional connection. This is efficient as the server can push a message to the client instantly with very low overhead.</li><li><strong>Trade-off:</strong> WebSockets can be stateful on the server-side, meaning the server has to keep track of every open connection. This can be a scaling challenge for the Notification Service, requiring a robust connection manager.</li><li><strong>Alternative: Long Polling.</strong> The client could repeatedly poll an HTTP endpoint. The server would hold the connection open until it has an update. This is simpler to implement and is stateless from a server perspective. However, it’s less efficient, creates more overhead per message, and has higher latency than WebSockets. For a real-time feel, WebSockets are superior.”</li></ul><p><strong>Interviewer:</strong> Excellent analysis. You’ve clearly articulated the reasoning behind your technology choices.</p><h3>Step 6: Wrap Up</h3><p>To summarize, we’ve designed a highly available and scalable ticket booking system. The core strategy is to handle the immense load of on-sale events by creating an asynchronous, decoupled booking flow. We use a <strong>message queue (Kafka)</strong>to absorb the initial ‘thundering herd’ of reservation requests, process them in an orderly fashion with <strong>auto-scaled workers</strong>, and use <strong>distributed locks (Redis)</strong> to ensure data integrity. The database is <strong>sharded by eventId</strong> to handle write hotspots, and a multi-layer <strong>caching strategy (CDN and Redis)</strong> handles read traffic. Finally, we communicate the results back to the user in real-time using <strong>WebSockets</strong>.</p><p><strong>Future Considerations and Improvements:</strong></p><ul><li><strong>Fairness and Anti-Bot Measures:</strong> We haven’t discussed preventing bots from snatching up all the tickets. We could implement a <strong>‘virtual queue’ or ‘waiting room’</strong> before the on-sale even begins, randomly assigning spots to users. We would also need sophisticated bot detection using CAPTCHAs, IP rate limiting, and behavioral analysis.</li><li><strong>Dynamic Pricing:</strong> The system could be extended to support dynamic pricing based on demand, similar to how airlines price tickets.</li><li><strong>Analytics Pipeline:</strong> We are generating a huge amount of valuable data. We could stream all events (searches, clicks, bookings) into a data lake (like S3) and use a processing engine like Spark to generate insights for promoters on sales trends and user behavior.</li><li><strong>Geospatial Searches:</strong> For users looking for “events near me,” we could integrate geohashing and a spatial index to perform these queries efficiently.</li></ul><p><strong><em>Please follow me</em></strong> if you found this post useful!</p><p>Want to get access to <strong><em>frequently asked system design interview questions</em></strong>, <strong><em>with complete solutions</em></strong> broken down using 6-step framework as illustrated in this post, then get hold of the book <strong><em>“</em></strong><a href="https://www.amazon.com/Handbook-System-Interview-Success-Follow-ebook/dp/B0FDYC527S/"><strong><em>HANDBOOK FOR SYSTEM DESIGN INTERVIEW SUCCESS</em></strong></a><strong><em>”.</em></strong> Its practical, real-world interview scenarios will give you a repeatable framework and the confidence to handle any question that comes your way. <strong><em>Be interview ready</em></strong>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6011406962ef" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Scalability Explained for Beginners]]></title>
            <link>https://techsauce.medium.com/scalability-explained-for-beginners-36c7c3bbcda9?source=rss-32c92f65c2e9------2</link>
            <guid isPermaLink="false">https://medium.com/p/36c7c3bbcda9</guid>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[scalability]]></category>
            <category><![CDATA[software-architecture]]></category>
            <dc:creator><![CDATA[Tech Sauce]]></dc:creator>
            <pubDate>Wed, 27 Nov 2024 01:13:39 GMT</pubDate>
            <atom:updated>2024-11-27T01:13:39.034Z</atom:updated>
            <content:encoded><![CDATA[<h4>In this post, we will go through the key techniques software architects use to make systems scalable, using simple analogies.</h4><p>Imagine you run a small bakery in your town. At first, <em>a single oven</em> is enough to bake cakes and serve customers. But as your bakery becomes popular, more customers visit, and your single oven isn’t enough to handle all the orders. You either need a <strong><em>bigger oven or more ovens</em></strong> to keep up with the demand. This is the essence of <strong>scalability</strong> in software systems.</p><blockquote>In the tech world, scalability is about ensuring that systems <em>can handle more</em> “customers” (users) or “orders” (requests) as they grow in popularity, without breaking down or slowing to a crawl.</blockquote><p>Let’s explore what scalability means and how to achieve it using simple concepts.</p><h3>What is Scalability?</h3><p>Scalability refers to a <em>system’s ability to handle increasing amounts of workload</em> or to accommodate growth in its user base without a drop in performance.</p><p>A scalable system works well whether it’s serving 10 users or 10 million users.</p><p>There are two main ways to scale:</p><h4><strong>Vertical Scaling (Scale Up)</strong>:</h4><ul><li>Add <em>more power</em> to a single machine (e.g., a bigger oven in the bakery).</li><li>Examples: Adding more CPU, memory, or storage to a server.</li></ul><h4><strong>Horizontal Scaling (Scale Out)</strong>:</h4><ul><li>Add <em>more machines</em> to share the work (e.g., more ovens in the bakery).</li><li>Examples: Adding more servers to handle traffic.</li></ul><h3>Techniques to Build Scalable Systems</h3><p>Let’s walk through the key techniques software architects use to make systems scalable, using simple analogies.</p><h3>1. Load Balancing: Sharing the Workload</h3><p>Imagine you’ve hired multiple bakers in your bakery, but customers all line up in front of one baker, leaving the others idle. This creates a bottleneck. You need someone to direct customers to the next available baker to ensure all bakers are equally busy.</p><p>In software, this “someone” is a <strong>load balancer</strong>, which distributes requests among multiple servers so no single server gets overwhelmed.</p><p>For example, websites like Amazon or Google have millions of users. Load balancers ensure requests are spread across hundreds or thousands of servers.</p><h3>2. Caching: Storing Reusable Data</h3><p>Imagine a customer who always orders the same type of cake. Instead of baking a fresh cake every time, you could keep a ready-made one on hand. This saves time and effort.</p><p>In software, <strong>caching</strong> works the same way. It stores frequently used data (like search results or images) so it can be delivered faster without reprocessing.</p><p>For example, when you watch a YouTube video, it might already be cached on a nearby server, so it loads faster.</p><h3>3. Database Scaling: Managing Growing Data</h3><p>As your bakery grows, your recipe book may become too large to manage. You might:</p><ul><li><strong>Duplicate the book</strong> so multiple bakers can read it simultaneously (replication).</li><li><strong>Split the book</strong> into sections (e.g., cakes, cookies) and give each section to a different baker (sharding).</li></ul><p>In software, databases also need scaling techniques like:</p><ul><li><strong>Replication</strong>: Copying data to multiple servers for faster reads.</li><li><strong>Sharding</strong>: Splitting data across multiple databases to balance the load.</li></ul><p>For example, social media platforms like Instagram use sharding technique to handle billions of photos efficiently.</p><h3>4. Asynchronous Processing: Don’t Make Customers Wait</h3><p>Imagine a customer places a large order that will take hours to complete. Instead of making them wait, you take the order and let them pick it up later. This way, you can serve other customers in the meantime.</p><p>In software, tasks like sending emails or generating reports can be done in the background using <strong>asynchronous processing</strong>.</p><p>For example, when you upload a video on a YouTube, it processes it in the background while you continue using the site.</p><h3>5. Stateless Systems: Keeping it Simple</h3><p>Imagine if every time a customer returned, they had to go to the same baker who served them before. This complicates things as you hire more bakers. Instead, if all bakers know the customer’s order preferences (stored in a shared book), any baker can serve them.</p><p>In software, <strong>stateless systems</strong> don’t store user information on the server. Instead, they store it in a centralized place (like a database), making it easier to handle many users.</p><h3>6. Elastic Scaling: Adapting to Demand</h3><p>Imagine your bakery gets busier during holidays and quieter afterward. You’d want the flexibility to hire more bakers temporarily and scale back when demand drops.</p><p>In software, <strong>elastic scaling</strong> lets systems automatically adjust their resources based on demand, saving costs during quiet times.</p><p>For example, e-commerce sites handle huge traffic spikes during Black Friday by scaling up their servers temporarily.</p><h3>7. Observability: Keeping an Eye on Things</h3><p>As your bakery grows, you need ways to monitor how each baker and oven are performing. Are some bakers too slow? Are some ovens overheating?</p><p>In software, <strong>observability</strong> tools monitor the system to ensure everything runs smoothly. These tools track:</p><ul><li>Logs: Record events like errors.</li><li>Metrics: Measure system performance (e.g., how fast orders are processed).</li><li>Traces: Show how requests flow through the system.</li></ul><p>For example, tools like Prometheus and Grafana are used to monitor large systems.</p><h3>8. Fault Tolerance: Handling Failures Gracefully</h3><p>What if an oven in your bakery breaks? If you have backup ovens or can redistribute work to the other ovens, your bakery won’t stop functioning.</p><p>In software, <strong>fault tolerance</strong> ensures that even if a server or service fails, the system continues to operate.</p><p>For example, when Netflix has some server down because of hardware/software failure, it can still stream movies by rerouting traffic to backup servers.</p><h3>9. Event-Driven Design: Handling Bursty Workloads</h3><p>Imagine customers calling in orders instead of waiting in line. You jot down the orders and process them in the background. This allows you to handle sudden spikes in demand without overwhelming your staff.</p><p>In software, <strong>event-driven design</strong> uses queues to process tasks as they come in, ensuring scalability.</p><p>For example, online ticketing systems process millions of orders for concerts or sports events without crashing.</p><h3>Conclusion: Putting It All Together</h3><p>Scalability is like running a well-organized, expanding bakery.</p><p>By distributing work, reusing data, handling tasks in the background, and being prepared for growth, software systems can serve millions — or even billions — of users efficiently.</p><p>To build a scalable system:</p><ol><li><strong>Start Small</strong>: Focus on a simple solution that works for your current needs.</li><li><strong>Iterate and Improve</strong>: Add techniques like caching, load balancing, and database scaling as demand grows.</li><li><strong>Plan for the Future</strong>: Design systems that can grow with your users.</li></ol><p>Remember, scalability isn’t just about handling more users — it’s about doing so efficiently and reliably. Like a bakery that grows from a single shop to a global chain, scalable systems are built step by step, one technique at a time.</p><p>If you found this post useful, <strong>please follow me</strong> on Medium.</p><p>If you’re gearing up for coding interviews, <a href="https://www.amazon.com/Handbook-Coding-Interviews-K-PATIL/dp/B0DGLXXB6B"><strong><em>Handbook for Coding Interviews</em></strong></a><strong><em> </em></strong>book is the perfect prep guide. This book is packed with all the necessary <strong><em>coding patterns</em></strong> and complete solutions to the <em>most frequently</em> asked coding interview questions.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=36c7c3bbcda9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Four types of Graph representations]]></title>
            <link>https://techsauce.medium.com/four-types-of-graph-representations-40e300f5f679?source=rss-32c92f65c2e9------2</link>
            <guid isPermaLink="false">https://medium.com/p/40e300f5f679</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[graph-representation]]></category>
            <category><![CDATA[coding-interviews]]></category>
            <category><![CDATA[coding-interview-problems]]></category>
            <category><![CDATA[graph]]></category>
            <dc:creator><![CDATA[Tech Sauce]]></dc:creator>
            <pubDate>Sun, 10 Nov 2024 00:15:38 GMT</pubDate>
            <atom:updated>2024-11-10T00:15:38.704Z</atom:updated>
            <content:encoded><![CDATA[<h4>In this post, we will go through four types of Graphs representations with code in Java and their applications.</h4><p>Let’s go through four different types of graph representations with Java code examples and discuss their advantages for the operations of <em>finding all edges,</em> <em>finding all adjacent nodes</em>, and <em>checking if an edge exists</em> <em>between two given nodes</em>.</p><h3>1. Edge List</h3><p>An edge list is a simple way to represent a graph <strong><em>as a collection of all edges</em></strong>. Each edge is stored as a pair of vertices. This representation is compact but not the most efficient for querying adjacency or edge existence.</p><pre>import java.util.ArrayList;<br>import java.util.List;<br><br>class Edge {<br>    int src;<br>    int dest;<br><br>    Edge(int src, int dest) {<br>        this.src = src;<br>        this.dest = dest;<br>    }<br><br>    @Override<br>    public String toString() {<br>        return &quot;(&quot; + src + &quot; -&gt; &quot; + dest + &quot;)&quot;;<br>    }<br>}<br><br>public class EdgeListGraph {<br>    List&lt;Edge&gt; edges;<br><br>    public EdgeListGraph() {<br>        this.edges = new ArrayList&lt;&gt;();<br>    }<br><br>    public void addEdge(int src, int dest) {<br>        edges.add(new Edge(src, dest));<br>    }<br><br>    public List&lt;Edge&gt; getEdges() {<br>        return edges;<br>    }<br>    <br>    public boolean hasEdge(int src, int dest) {<br>        for (Edge edge : edges) {<br>            if (edge.src == src &amp;&amp; edge.dest == dest) {<br>                return true;<br>            }<br>        }<br>        return false;<br>    }<br>}</pre><p><strong>Space Complexity</strong>: O(E), where E is the number of edges. It is space-efficient for storing edges directly but does not store any adjacency information for nodes.</p><p><strong>Time Complexity for common operations</strong>:</p><ul><li><strong>Find all edges</strong>: O(1); simply return the list of edges.</li><li><strong>Find all adjacent nodes</strong>: O(E); requires scanning through all edges.</li><li><strong>Check if an edge exists</strong>: O(E); requires iterating through the list to find a match.</li><li><strong>Suitability</strong>: Best for applications where edge enumeration is needed, such as in algorithms that process all edges (e.g., Kruskal’s algorithm for MST). Not optimal for adjacency queries or checking edge existence frequently.</li></ul><p><strong>Pros</strong>:</p><ul><li>Simple and space-efficient for sparse graphs.</li><li>Easy to implement and iterate over all edges.</li></ul><p><strong>Cons</strong>:</p><ul><li>Inefficient for adjacency and edge existence checks.</li><li>Not suitable for dense graphs or where frequent adjacency queries are needed.</li></ul><h3>2. Adjacency List</h3><p>An adjacency list represents the graph <em>using an array or list of lists</em>, <em>where </em><strong><em>each</em></strong><em> </em><strong><em>vertex points to a list of its adjacent vertices</em></strong>. It is space-efficient for sparse graphs.</p><pre>import java.util.ArrayList;<br>import java.util.HashMap;<br>import java.util.List;<br>import java.util.Map;<br><br>public class AdjacencyListGraph {<br>    Map&lt;Integer, List&lt;Integer&gt;&gt; adjList;<br><br>    public AdjacencyListGraph() {<br>        this.adjList = new HashMap&lt;&gt;();<br>    }<br><br>    public void addEdge(int src, int dest) {<br>        adjList.computeIfAbsent(src, k -&gt; new ArrayList&lt;&gt;()).add(dest);<br>    }<br><br>    public List&lt;Integer&gt; getAdjacentNodes(int node) {<br>        return adjList.getOrDefault(node, new ArrayList&lt;&gt;());<br>    }<br><br>    public boolean hasEdge(int src, int dest) {<br>        return adjList.containsKey(src) &amp;&amp; adjList.get(src).contains(dest);<br>    }<br>}</pre><p><strong>Space Complexity</strong>: O(V+E), where V is the number of vertices. Efficient for sparse graphs as it only stores existing edges.</p><p><strong>Time Complexity for Operations</strong>:</p><ul><li><strong>Find all edges</strong>: O(V+E); iterate through all adjacency lists.</li><li><strong>Find all adjacent nodes</strong>: O(1) on average; direct access via the list.</li><li><strong>Check if an edge exists</strong>: O(degree of the node); scan through the list of adjacent nodes.</li><li><strong>Suitability</strong>: Ideal for most graph algorithms (e.g., BFS, DFS) and for graphs that are sparse. Works well when you need to iterate over neighbors of a node.</li></ul><p><strong>Pros</strong>:</p><ul><li>Space-efficient for sparse graphs.</li><li>Direct and fast access to adjacent nodes.</li><li>Easier to traverse for most graph algorithms.</li></ul><p><strong>Cons</strong>:</p><ul><li>Edge existence checks are slower compared to an adjacency matrix, especially if a node has a high degree.</li><li>Not optimal for very dense graphs due to increased lookup time.</li></ul><h3>3. Adjacency Map</h3><p>An adjacency map is similar to an adjacency list but <strong><em>uses a map of maps</em></strong>. This provides direct access to the edge.</p><pre>import java.util.HashMap;<br>import java.util.Map;<br><br>public class AdjacencyMapGraph {<br>    Map&lt;Integer, Map&lt;Integer, Integer&gt;&gt; adjMap;<br><br>    public AdjacencyMapGraph() {<br>        this.adjMap = new HashMap&lt;&gt;();<br>    }<br><br>    public void addEdge(int src, int dest, int weight) {<br>        adjMap.computeIfAbsent(src, k -&gt; new HashMap&lt;&gt;()).put(dest, weight);<br>    }<br><br>    public Map&lt;Integer, Integer&gt; getAdjacentNodes(int node) {<br>        return adjMap.getOrDefault(node, new HashMap&lt;&gt;());<br>    }<br><br>    public boolean hasEdge(int src, int dest) {<br>        return adjMap.containsKey(src) &amp;&amp; adjMap.get(src).containsKey(dest);<br>    }<br>}</pre><p><strong>Space Complexity</strong>: O(V+E) in the average case, with some additional overhead for the map structure. This representation can be more memory-intensive than adjacency lists due to the underlying hash table.</p><p><strong>Time Complexity for Operations</strong>:</p><ul><li><strong>Find all edges</strong>: O(V+E); iterate through the map.</li><li><strong>Find all adjacent nodes</strong>: O(1); direct access via the map.</li><li><strong>Check if an edge exists</strong>: O(1) on average, assuming efficient hash function implementation.</li><li><strong>Suitability</strong>: Works well when you need fast lookups and potentially need to store additional information such as weights. Good for weighted graphs or when edge existence checks are common.</li></ul><p><strong>Pros</strong>:</p><ul><li>Fast lookup and edge existence checks.</li><li>Supports weighted edges and additional metadata easily.</li><li>More flexible and allows direct map operations for complex graph structures.</li></ul><p><strong>Cons</strong>:</p><ul><li>More space-intensive than an adjacency list due to the overhead of hash maps.</li><li>Performance depends on the efficiency of the hash function (potential collisions).</li></ul><h3>4. Adjacency Matrix</h3><p>An adjacency matrix uses a 2D array to represent the graph, where a cell at <em>(i, j) </em>indicates the presence of an edge from vertex i to vertex j. It uses O(V²) space and is most useful for dense graphs.</p><pre>public class AdjacencyMatrixGraph {<br>    int[][] matrix;<br>    int size;<br><br>    public AdjacencyMatrixGraph(int size) {<br>        this.size = size;<br>        this.matrix = new int[size][size];<br>    }<br><br>    public void addEdge(int src, int dest) {<br>        matrix[src][dest] = 1; // 1 indicates an edge exists; modify for weighted graphs if needed.<br>    }<br><br>    public boolean hasEdge(int src, int dest) {<br>        return matrix[src][dest] != 0;<br>    }<br><br>    public void printAdjacentNodes(int node) {<br>        System.out.print(&quot;Adjacent nodes of &quot; + node + &quot;: &quot;);<br>        for (int i = 0; i &lt; size; i++) {<br>            if (matrix[node][i] != 0) {<br>                System.out.print(i + &quot; &quot;);<br>            }<br>        }<br>        System.out.println();<br>    }<br>}</pre><p><strong>Space Complexity</strong>: O(V²), regardless of the number of edges. This is space-inefficient for sparse graphs, but it can be appropriate for dense graphs.</p><p><strong>Time Complexity for Operations</strong>:</p><ul><li><strong>Find all edges</strong>: O(V²); iterate through the entire matrix.</li><li><strong>Find all adjacent nodes</strong>: O(V); iterate over a row in the matrix.</li><li><strong>Check if an edge exists</strong>: O(1); direct access via matrix indexing.</li><li><strong>Suitability</strong>: Best suited for dense graphs where E is close to V², or when you need very fast edge existence checks.</li></ul><p><strong>Pros</strong>:</p><ul><li>Fastest edge existence check O(1)) of all representations.</li><li>Simple to implement for small, dense graphs.</li><li>Ideal for certain algorithms that require checking edge existence frequently.</li></ul><p><strong>Cons</strong>:</p><ul><li>High space complexity makes it impractical for sparse graphs.</li><li>Iterating over neighbors or finding all edges requires O(V) or O(V²), which can be slow for large graphs.</li><li>Does not inherently store edge weights unless modified (e.g., using non-zero values for weights).</li></ul><h3><strong>Summary of Tradeoffs</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*nQkiJmvOmZS__aMz3B7sVw.png" /></figure><h4><strong>Choosing the Right Representation</strong>:</h4><ul><li>Use <strong>edge list</strong> for <em>simple</em> or edge-centric problems.</li><li>Use <strong>adjacency list</strong> for traversal-heavy or <em>sparse</em> graph algorithms.</li><li>Use <strong>adjacency map</strong> when <em>fast</em> lookups and flexibility (e.g., weighted graphs) are needed.</li><li>Use <strong>adjacency matrix</strong> when edge existence checks need to be constant time and space isn’t a concern (<em>dense</em> graphs).</li></ul><p>If you’re gearing up for coding interviews, <a href="https://www.amazon.com/Handbook-Coding-Interviews-K-PATIL/dp/B0DGLXXB6B"><strong><em>Handbook for Coding Interviews</em></strong></a><strong><em> </em></strong>book is the perfect prep guide. This book is packed with all the <strong><em>coding patterns</em></strong> and complete solutions to the <em>most frequently</em> asked coding interview questions.</p><p>If you found this post useful, <strong>please follow me</strong> on Medium. More to come.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=40e300f5f679" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Top-Down vs Bottom-Up Depth-First Search]]></title>
            <link>https://techsauce.medium.com/top-down-vs-bottom-up-depth-first-search-498f68e6b680?source=rss-32c92f65c2e9------2</link>
            <guid isPermaLink="false">https://medium.com/p/498f68e6b680</guid>
            <category><![CDATA[coding-interview-problems]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[depth-first-search]]></category>
            <category><![CDATA[coding-interviews]]></category>
            <category><![CDATA[algorithms]]></category>
            <dc:creator><![CDATA[Tech Sauce]]></dc:creator>
            <pubDate>Tue, 05 Nov 2024 19:24:27 GMT</pubDate>
            <atom:updated>2024-11-05T19:24:27.969Z</atom:updated>
            <content:encoded><![CDATA[<h4>In this post, we’ll explore two variations of depth-first search (DFS) algorithm to solve the binary tree based coding interview question.</h4><p>Depth-first search (DFS) algorithm can be used in two different ways for solving specific problems: <strong>top-down</strong> and <strong>bottom-up</strong>.</p><p>Each approach has unique benefits depending on the type of problem. We’ll go over how each approach works, along with examples and code to help you understand the differences between them.</p><h3>What is Depth-First Search (DFS)?</h3><p>Depth-First Search is a traversal method for trees or graphs where we start at the root (or any arbitrary node) and explore each branch all the way down to the leaves.</p><p>This is done recursively, where each recursive call represents moving down a level in the tree.</p><h3>Top-Down DFS Approach</h3><p>In a <strong>top-down</strong> approach, we <em>pass information from the root down to the leaves</em>. For each recursive call, we typically carry some data from the root level of the tree downwards, <em>updating it at each level as we go</em>.</p><p>This approach is helpful in problems where we need to keep track of information such as the path from the root to the current node.</p><h4>Example: Find the Maximum Depth of a Binary Tree</h4><p>In this example, we’ll use the top-down approach to find the maximum depth of a binary tree by tracking the depth as we move from the root to each leaf node.</p><h4>Code for Top-Down DFS</h4><pre>class Solution {    <br>    private int maxDepth = 0;<br><br>    public int maxDepth(TreeNode root) {<br>        if (root == null)<br>            return 0;<br>        <br>        dfs(root, 0);  // Start the DFS traversal with depth 0<br>        return maxDepth;<br>    }<br><br>    // TOP-DOWN DFS: Pass depth down from parent to children<br>    private void dfs(TreeNode node, int currentDepth) {<br>        currentDepth++;  // Increment depth as we go down each level<br><br>        // If the current depth is greater than the maxDepth, update maxDepth<br>        maxDepth = Math.max(maxDepth, currentDepth);<br><br>        // Traverse the left and right children if they exist<br>        if (node.left != null) {<br>            dfs(node.left, currentDepth);<br>        }<br>        if (node.right != null) {<br>            dfs(node.right, currentDepth);<br>        }<br>    }<br>}</pre><h4>Explanation of Top-Down DFS</h4><ol><li><strong>Starting at the Root</strong>: We begin by calling dfs(root, 0), with a depth of 0.</li><li><strong>Incrementing Depth</strong>: At each recursive call, we increase the depth by 1 as we move down each level.</li><li><strong>Updating </strong><strong>maxDepth</strong>: At each node, we compare currentDepth with maxDepth. If currentDepth is greater, we update maxDepth.</li><li><strong>Base Case</strong>: If a node has no children (i.e., it’s a leaf), the function returns without further recursion, as that node’s depth is already counted when entering the dfs call.</li></ol><h4>Illustration of Top-Down DFS</h4><p>Consider this binary tree:</p><pre>       1<br>      / \<br>     2   3<br>    / \<br>   4   5</pre><p>Here’s how the traversal proceeds:</p><ol><li>We start at the root node (1) with currentDepth = 1.</li><li>Moving to node 2, the depth becomes 2.</li><li>Going down to node 4, currentDepth becomes 3. Since node 4 is a leaf, we backtrack and explore node 5, also reaching a depth of 3.</li><li>The maximum depth of the tree is ultimately found to be 3 after exploring all paths.</li></ol><h3>Bottom-Up DFS Approach</h3><p>In a <strong>bottom-up</strong> approach, we solve the problem <em>by gathering information from the leaves</em> up to the root. Instead of passing data down, we calculate values at each level based on the values from lower levels.</p><p>This approach is useful when we need to make decisions based on information collected from subtrees.</p><h4>Example: Find the Maximum Depth of a Binary Tree</h4><p>We’ll solve the same problem using a bottom-up approach.</p><h4>Code for Bottom-Up DFS</h4><pre>class Solution {<br>    public int maxDepth(TreeNode root) {<br>        if (root == null) {<br>            return 0;<br>        }<br>        return dfs(root);<br>    }<br><br>    // BOTTOM-UP DFS: No information is passed down; we return depth from children<br>    private int dfs(TreeNode node) {<br>        // Base case: if node is a leaf, depth is 1<br>        if (node.left == null &amp;&amp; node.right == null) {<br>            return 1;<br>        }<br><br>        // Calculate the maximum depth of the left subtree<br>        int leftDepth = 0;<br>        if (node.left != null) {<br>            leftDepth = 1 + dfs(node.left);<br>        }<br><br>        // Calculate the maximum depth of the right subtree<br>        int rightDepth = 0;<br>        if (node.right != null) {<br>            rightDepth = 1 + dfs(node.right);<br>        }<br><br>        // Return the larger depth between the two subtrees<br>        return Math.max(leftDepth, rightDepth);<br>    }<br>}</pre><h4>Explanation of Bottom-Up DFS</h4><ol><li><strong>Starting at the Leaves</strong>: We start from the root but only start returning values once we reach the leaves.</li><li><strong>Calculating Depths from Subtrees</strong>: For each node, we calculate the maximum depth of its left and right subtrees.</li><li><strong>Combining Results Upwards</strong>: We return the maximum depth from the left and right subtrees, adding 1 to account for the current node’s depth.</li><li><strong>Final Result</strong>: When we reach back to the root, we compute the maximum depth of the entire tree based on the depth of left subtree and right subtree.</li></ol><h4>Illustration of Bottom-Up DFS</h4><p>For the same binary tree:</p><pre>       1<br>      / \<br>     2   3<br>    / \<br>   4   5</pre><p>Here’s how the traversal proceeds:</p><ol><li>Starting from the root, we recursively move down each path.</li><li>At the leaf nodes (4 and 5), we return a depth of 1.</li><li>For node 2, the maximum depth between its left and right children is 2.</li><li>The depth for node 3 is 1 since it has no children.</li><li>Finally, at the root (1), the maximum depth between its left and right children is 3, which is the maximum depth of the tree.</li></ol><h3>Key Differences Between Top-Down and Bottom-Up DFS</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/501/1*KzAqTIRkQkqACs7aDdnLsQ.png" /></figure><h3>Summary</h3><ul><li><strong>Top-Down DFS</strong> is suitable for problems where you need to track cumulative information (e.g., paths or distances from the root).</li><li><strong>Bottom-Up DFS</strong> is useful when you need to gather results from subtrees and combine them at each level.</li></ul><p>Each approach has its strengths, and understanding when to use each can greatly improve your problem-solving skills.</p><p>If you’re gearing up for coding interviews, <a href="https://www.amazon.com/Handbook-Coding-Interviews-K-PATIL/dp/B0DGLXXB6B"><strong><em>Handbook for Coding Interviews</em></strong></a><strong><em> </em></strong>book is the perfect prep guide. This book is packed with all the <strong><em>coding patterns</em></strong> and complete solutions to the most frequently asked coding interview questions.</p><p>If you found this post useful, <strong>please follow me</strong> on Medium. More to come.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=498f68e6b680" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Solving the “Longest Happy String” Coding Interview Question]]></title>
            <link>https://techsauce.medium.com/solving-the-longest-happy-string-coding-interview-question-acdb6cffc4c7?source=rss-32c92f65c2e9------2</link>
            <guid isPermaLink="false">https://medium.com/p/acdb6cffc4c7</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[coding-interview-problems]]></category>
            <category><![CDATA[leetcode-medium]]></category>
            <category><![CDATA[coding-interviews]]></category>
            <category><![CDATA[technical-interview]]></category>
            <dc:creator><![CDATA[Tech Sauce]]></dc:creator>
            <pubDate>Sat, 28 Sep 2024 06:28:38 GMT</pubDate>
            <atom:updated>2024-09-28T06:31:32.977Z</atom:updated>
            <content:encoded><![CDATA[<h4>In this blog post, I’ll walk you through the step-by-step approach to solving this problem efficiently using a greedy algorithm in Java.</h4><h3>Problem Statement</h3><p>You are tasked with constructing the <strong>longest possible string</strong> that meets the following criteria:</p><ol><li>The string consists only of the letters &#39;a&#39;, &#39;b&#39;, and &#39;c&#39;.</li><li>The string must not contain the substrings &quot;aaa&quot;, &quot;bbb&quot;, or &quot;ccc&quot;.</li><li>The number of &#39;a&#39; characters is limited by a given integer a.</li><li>The number of &#39;b&#39; characters is limited by a given integer b.</li><li>The number of &#39;c&#39; characters is limited by a given integer c.</li></ol><p>You need to return the <strong>longest possible valid string</strong>. If there are multiple solutions, you can return any. If it is impossible to construct such a string, return an empty string.</p><h3>Understanding the Problem</h3><p>The core of this problem is about <strong>balance</strong> — we need to ensure that no character appears more than twice consecutively while also making sure that the resulting string is <strong>as long as possible</strong>.</p><p>We can solve this problem using <strong>greedy approach</strong>, where we always prioritize <strong>adding the most frequent character</strong>, as long as it doesn’t create an invalid substring.</p><h3>Clarifying Constraints</h3><p>Before we start solving the problem, let’s clarify the constraints:</p><ul><li>We are allowed to use a maximum of a &#39;a&#39;s, b &#39;b&#39;s, and c &#39;c&#39;s.</li><li>The string must not contain more than two consecutive identical characters. So substrings like &quot;aaa&quot;, &quot;bbb&quot;, and &quot;ccc&quot; are forbidden.</li></ul><h3>Approach: Greedy Algorithm Using a Max-Heap</h3><p>The key insight here is that we should <strong>greedily</strong> add characters in a way that <strong><em>maximizes the length of the string</em></strong> while avoiding three consecutive identical characters. To achieve this, we can use a <strong>max-heap</strong> (priority queue) to keep track of the remaining counts of each character.</p><h4>Steps:</h4><ol><li><strong>Initialize a Max-Heap</strong>: We’ll use a priority queue to always extract the character with the highest remaining count.</li><li><strong>Greedy Selection</strong>: Continuously add the character with the highest count <strong><em>unless it would violate the rule</em></strong> of no three consecutive identical characters.</li><li><strong>Termination</strong>: If no valid characters are left to add without violating the rules, we stop and return the result.</li></ol><h3>Java Solution</h3><p>Let’s implement the solution in Java.</p><pre>import java.util.PriorityQueue;<br><br>class HappyStringGenerator {<br><br>    // Helper class to store character and its remaining count<br>    static class CharCount implements Comparable&lt;CharCount&gt; {<br>        char ch;<br>        int count;<br><br>        CharCount(char ch, int count) {<br>            this.ch = ch;<br>            this.count = count;<br>        }<br><br>        // Custom comparator to create max heap (higher count comes first)<br>        @Override<br>        public int compareTo(CharCount other) {<br>            return other.count - this.count;<br>        }<br>    }<br><br>    public String generateHappyString(int a, int b, int c) {<br>        // Max-heap to store characters and their remaining counts<br>        PriorityQueue&lt;CharCount&gt; maxHeap = new PriorityQueue&lt;&gt;();<br><br>        // Add &#39;a&#39;, &#39;b&#39;, and &#39;c&#39; to the heap if their count is &gt; 0<br>        if (a &gt; 0) maxHeap.add(new CharCount(&#39;a&#39;, a));<br>        if (b &gt; 0) maxHeap.add(new CharCount(&#39;b&#39;, b));<br>        if (c &gt; 0) maxHeap.add(new CharCount(&#39;c&#39;, c));<br><br>        StringBuilder result = new StringBuilder();<br><br>        while (!maxHeap.isEmpty()) {<br>            // Fetch the most frequent character<br>            CharCount current = maxHeap.poll();<br><br>            // Check if the last two characters are the same as the current one<br>            int length = result.length();<br>            if (length &gt;= 2 &amp;&amp; result.charAt(length - 1) == current.ch &amp;&amp; result.charAt(length - 2) == current.ch) {<br>                // If we form a triple, pick the second most frequent character instead<br>                if (maxHeap.isEmpty()) {<br>                    break;  // No valid character left to add<br>                }<br><br>                CharCount next = maxHeap.poll();<br>                result.append(next.ch);<br>                next.count--;<br><br>                if (next.count &gt; 0) {<br>                    maxHeap.add(next);<br>                }<br><br>                // Push the current character back into the heap<br>                maxHeap.add(current);<br>            } else {<br>                // Append the most frequent character<br>                result.append(current.ch);<br>                current.count--;<br><br>                if (current.count &gt; 0) {<br>                    maxHeap.add(current);<br>                }<br>            }<br>        }<br><br>        return result.toString();<br>    }<br><br>    // Main method for testing<br>    public static void main(String[] args) {<br>        HappyStringGenerator generator = new HappyStringGenerator();<br><br>        // Example test case<br>        System.out.println(generator.generateHappyString(1, 1, 7));<br>    }<br>}</pre><h3>Key Concepts</h3><ul><li><strong>Greedy Algorithm</strong>: The greedy approach works here because we always try to add the character that still has the most occurrences left, while making sure that we don’t violate the condition of three consecutive characters.</li><li><strong>Max-Heap</strong>: Using a priority queue (max-heap) allows us to efficiently track and update the character with the highest remaining count.</li></ul><h3>Time and Space Complexity</h3><ul><li><strong>Time Complexity</strong>: Each insertion and extraction from the max-heap takes O(log 3) = O(1) time, and we perform this operation for each character in the final string. So the total time complexity is <strong>O(a + b + c)</strong>.</li><li><strong>Space Complexity</strong>: The space complexity is <strong>O(1)</strong> since the size of the heap is at most 3, regardless of the input values.</li></ul><p>If you’re preparing for coding interviews and want to master problem-solving techniques, I recommend the book <strong>“</strong><a href="https://www.amazon.com/Handbook-Coding-Interviews-K-PATIL/dp/B0DGLXXB6B"><strong>Handbook for Coding Interviews</strong></a><strong>” </strong>for detailed explanations of coding patterns and solutions to the most common coding interview questions.</p><p>If you found this post useful, <strong>please follow me</strong> on Medium.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=acdb6cffc4c7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Finding the Length of the Longest Substring Without Repeating Characters]]></title>
            <link>https://techsauce.medium.com/finding-the-length-of-the-longest-substring-without-repeating-characters-0a76ae287bae?source=rss-32c92f65c2e9------2</link>
            <guid isPermaLink="false">https://medium.com/p/0a76ae287bae</guid>
            <category><![CDATA[sliding-windows]]></category>
            <category><![CDATA[coding-interview-problems]]></category>
            <category><![CDATA[sliding-window-approach]]></category>
            <category><![CDATA[coding-interview-prep]]></category>
            <category><![CDATA[coding-interviews]]></category>
            <dc:creator><![CDATA[Tech Sauce]]></dc:creator>
            <pubDate>Fri, 13 Sep 2024 23:10:37 GMT</pubDate>
            <atom:updated>2024-09-14T00:51:37.326Z</atom:updated>
            <content:encoded><![CDATA[<h4>In this post, we will solve this popular coding interview question using sliding window pattern.</h4><h3>Problem Statement</h3><p>Given a string s, you need to find the length of the longest substring that contains no repeating characters.</p><p>A substring is a contiguous sequence of characters within a string. The main objective is to identify the longest possible substring without any character repetition and return its length.</p><h3>Examples</h3><p>Let’s go through a few examples to understand the expected input and output:</p><p><strong>Example 1:</strong></p><ul><li>Input: s = &quot;abcabcbb&quot;</li><li>Output: 3</li><li>Explanation: The longest substring without repeating characters is &quot;abc&quot; with a length of 3.</li></ul><p><strong>Example 2:</strong></p><ul><li>Input: s = &quot;bbbbb&quot;</li><li>Output: 1</li><li>Explanation: The longest substring without repeating characters is &quot;b&quot; with a length of 1.</li></ul><p><strong>Example 3:</strong></p><ul><li>Input: s = &quot;pwwkew&quot;</li><li>Output: 3</li><li>Explanation: The longest substring without repeating characters is &quot;wke&quot;. Note that the answer must be a substring, &quot;pwke&quot; is not a substring as it is not contiguous.</li></ul><p><strong>Example 4 (Edge Case):</strong></p><ul><li>Input: s = &quot;&quot;</li><li>Output: 0</li><li>Explanation: The input string is empty, so the length of the longest substring is 0.</li></ul><p><strong>Example 5:</strong></p><ul><li>Input: s = &quot; &quot;</li><li>Output: 1</li><li>Explanation: The input string contains only one character (a space), so the length is 1.</li></ul><h3>Brute Force Approach</h3><p>The brute force approach involves checking every possible substring of s and determining if it has all unique characters. We would then keep track of the maximum length of substrings without repeating characters.</p><blockquote>To check if a substring has all unique characters, we can use a data structure like a Set.</blockquote><h4>Steps</h4><ol><li>Generate all possible substrings of s.</li><li>For each substring, check if all characters are unique.</li><li>Track the length of the longest substring with unique characters.</li><li>Return the maximum length found.</li></ol><h4>Time and Space Complexity</h4><ul><li><strong>Time Complexity:</strong> O(N³), where N is the length of the string s. Generating all substrings takes O(N²) time, and checking if each substring has all unique characters takes O(N) time in the worst case.</li><li><strong>Space Complexity:</strong> O(N), as we may use a set to store characters of a substring.</li></ul><h4>Brute Force Code in Java</h4><p>Here is the implementation of the brute force approach in Java for reference.</p><blockquote>Note: In a real interview, it is not a good idea to write code for brute force approach, just explain the time and space complexity of the brute force approach and move on to the optimal solution.</blockquote><pre>public class LongestSubstringBruteForce {<br><br>    public static int lengthOfLongestSubstringBruteForce(String s) {<br>        int maxLength = 0; // Variable to store the maximum length<br><br>        // Iterate over all possible substrings<br>        for (int i = 0; i &lt; s.length(); i++) {<br>            for (int j = i; j &lt; s.length(); j++) {<br>                if (allUnique(s, i, j)) {<br>                    maxLength = Math.max(maxLength, j - i + 1);<br>                }<br>            }<br>        }<br><br>        return maxLength; <br>    }<br><br>    // Helper function to check if all characters in the substring are unique<br>    private static boolean allUnique(String s, int start, int end) {<br>        Set&lt;Character&gt; set = new HashSet&lt;&gt;();<br>        for (int i = start; i &lt;= end; i++) {<br>            char ch = s.charAt(i);<br>            if (set.contains(ch)) {<br>                return false; // Character is repeated<br>            }<br>            set.add(ch);<br>        }<br>        return true; // All characters are unique<br>    }<br><br>    public static void main(String[] args) {<br>        String test1 = &quot;abcabcbb&quot;;<br>        String test2 = &quot;bbbbb&quot;;<br>        String test3 = &quot;pwwkew&quot;;<br>        String test4 = &quot;&quot;;<br>        String test5 = &quot; &quot;;<br><br>        System.out.println(&quot;Brute Force - Length of Longest Substring: &quot; + lengthOfLongestSubstringBruteForce(test1)); // Output: 3<br>        System.out.println(&quot;Brute Force - Length of Longest Substring: &quot; + lengthOfLongestSubstringBruteForce(test2)); // Output: 1<br>        System.out.println(&quot;Brute Force - Length of Longest Substring: &quot; + lengthOfLongestSubstringBruteForce(test3)); // Output: 3<br>        System.out.println(&quot;Brute Force - Length of Longest Substring: &quot; + lengthOfLongestSubstringBruteForce(test4)); // Output: 0<br>        System.out.println(&quot;Brute Force - Length of Longest Substring: &quot; + lengthOfLongestSubstringBruteForce(test5)); // Output: 1<br>    }<br>}</pre><h3>Optimal Approach: Sliding Window Technique</h3><p>We can use Sliding Window approach to solve this problem efficiently in O(N) time complexity. We can either use HashSet or HashMap data structure to help keep track of repeating characters. Let’s look at both the variations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*h2VVtX1UaSfBjBywEAn1uQ.gif" /><figcaption>Sliding Window Technique Illustration</figcaption></figure><h4>Using HashSet</h4><p>Let’s use HashSet to track the characters. We use two pointers (left and right) to represent the <em>current window of characters</em> without duplicates.</p><p>As we slide the window across the string:</p><ol><li>Expand the window by moving the right pointer to include new characters.</li><li>If a duplicate character is encountered, move the left pointer to the right until all characters in the window are unique again.</li><li>Track the maximum window size during this process.</li></ol><h4>Steps:</h4><ol><li>Initialize two pointers (left and right) and a Set to keep track of characters in the current window.</li><li>Expand the window by moving the right pointer.</li><li>If the character at right is not in the set, add it to the set and update the maximum length.</li><li>If the character is already in the Set, remove characters from the left of the window until the duplicate is removed.</li><li>Repeat until the right pointer reaches the end of the string.</li></ol><h4>Java Code</h4><pre>import java.util.HashSet;<br>import java.util.Set;<br><br>public class LongestSubstringOptimal {<br><br>    // Function to find the length of the longest substring without repeating characters<br>    public static int lengthOfLongestSubstringOptimal(String s) {<br>        int maxLength = 0; // Variable to store the maximum length<br>        int left = 0; // Left pointer for the sliding window<br>        Set&lt;Character&gt; set = new HashSet&lt;&gt;(); // Set to store characters in the current window<br><br>        // Iterate over the characters using the right pointer<br>        for (int right = 0; right &lt; s.length(); right++) {<br>            // If the character at &#39;right&#39; is a duplicate, shrink the window from the left<br>            while (set.contains(s.charAt(right))) {<br>                set.remove(s.charAt(left)); // Remove the character at &#39;left&#39;<br>                left++; // Move the left pointer to the right<br>            }<br><br>            // Add the character at &#39;right&#39; to the set<br>            set.add(s.charAt(right));<br><br>            // Update the maximum length of the substring<br>            maxLength = Math.max(maxLength, right - left + 1);<br>        }<br><br>        return maxLength; // Return the length of the longest substring without repeating characters<br>    }<br><br>    // Main method to test the optimal approach<br>    public static void main(String[] args) {<br>        String test1 = &quot;abcabcbb&quot;;<br>        String test2 = &quot;bbbbb&quot;;<br>        String test3 = &quot;pwwkew&quot;;<br>        String test4 = &quot;&quot;;<br>        String test5 = &quot; &quot;;<br><br>        System.out.println(&quot;Optimal - Length of Longest Substring: &quot; + lengthOfLongestSubstringOptimal(test1)); // Output: 3<br>        System.out.println(&quot;Optimal - Length of Longest Substring: &quot; + lengthOfLongestSubstringOptimal(test2)); // Output: 1<br>        System.out.println(&quot;Optimal - Length of Longest Substring: &quot; + lengthOfLongestSubstringOptimal(test3)); // Output: 3<br>        System.out.println(&quot;Optimal - Length of Longest Substring: &quot; + lengthOfLongestSubstringOptimal(test4)); // Output: 0<br>        System.out.println(&quot;Optimal - Length of Longest Substring: &quot; + lengthOfLongestSubstringOptimal(test5)); // Output: 1<br>    }<br>}</pre><h4>Time and Space Complexity</h4><ul><li><strong>Time Complexity:</strong> O(N), where N is the length of the string. Each character is processed at most twice (once by the right pointer and at most once by the left pointer).</li><li><strong>Space Complexity:</strong> O(M), where M is the size of the character set. This could be up to 256 if all characters in the string are unique.</li></ul><h4>Using HashMap</h4><p>The sliding window technique combined with a HashMap provides an<em> even more efficient way</em> to find the length of the longest substring without repeating characters.</p><blockquote>Using a HashMap, we can directly map each character to its most recent index, allowing us to quickly move the left pointer of our window whenever a duplicate character is encountered.</blockquote><p>The idea is to use a HashMap to keep track of characters and <strong><em>their most recent positions</em></strong>.</p><p>When a duplicate character is found within the current window, we can directly move the left pointer to the position after the duplicate&#39;s previous occurrence. This allows us to efficiently skip over duplicates without shrinking the window one character at a time.</p><h4>Steps:</h4><ol><li>Use a HashMap to store characters and their latest indices.</li><li>Initialize two pointers (left and right), representing the window&#39;s bounds.</li><li>Move the right pointer to expand the window:</li></ol><ul><li>If the current character is already in the map and its index is greater than or equal to left, move the leftpointer to map.get(char) + 1 to skip the duplicate.</li><li>Update the character’s index in the HashMap.</li><li>Calculate the maximum window length.</li></ul><p>4. Continue until the right pointer reaches the end of the string.</p><h4>Java Code</h4><pre>import java.util.HashMap;<br><br>public class LongestSubstringWithHashMap {<br><br>    public static int lengthOfLongestSubstring(String s) {<br>        // HashMap to store the last occurrence index of each character<br>        HashMap&lt;Character, Integer&gt; charIndexMap = new HashMap&lt;&gt;();<br>        int maxLength = 0; // Maximum length of substring<br>        int left = 0; // Left pointer for the sliding window<br><br>        // Iterate over the characters using the right pointer<br>        for (int right = 0; right &lt; s.length(); right++) {<br>            char currentChar = s.charAt(right);<br><br>            // If the character is already in the map and its index is within the current window<br>            if (charIndexMap.containsKey(currentChar) &amp;&amp; charIndexMap.get(currentChar) &gt;= left) {<br>                // Move the left pointer to the right of the last occurrence of the current character<br>                left = charIndexMap.get(currentChar) + 1;<br>            }<br><br>            // Update the last occurrence index of the current character<br>            charIndexMap.put(currentChar, right);<br><br>            // Update the maximum length of the substring<br>            maxLength = Math.max(maxLength, right - left + 1);<br>        }<br><br>        return maxLength; // Return the length of the longest substring without repeating characters<br>    }<br><br>    // Main method to test the optimal approach using HashMap<br>    public static void main(String[] args) {<br>        String test1 = &quot;abcabcbb&quot;;<br>        String test2 = &quot;bbbbb&quot;;<br>        String test3 = &quot;pwwkew&quot;;<br>        String test4 = &quot;&quot;;<br>        String test5 = &quot; &quot;;<br><br>        System.out.println(&quot;HashMap - Length of Longest Substring: &quot; + lengthOfLongestSubstring(test1)); // Output: 3<br>        System.out.println(&quot;HashMap - Length of Longest Substring: &quot; + lengthOfLongestSubstring(test2)); // Output: 1<br>        System.out.println(&quot;HashMap - Length of Longest Substring: &quot; + lengthOfLongestSubstring(test3)); // Output: 3<br>        System.out.println(&quot;HashMap - Length of Longest Substring: &quot; + lengthOfLongestSubstring(test4)); // Output: 0<br>        System.out.println(&quot;HashMap - Length of Longest Substring: &quot; + lengthOfLongestSubstring(test5)); // Output: 1<br>    }<br>}</pre><h4>Time and Space Complexity</h4><ul><li><strong>Time Complexity:</strong> O(N), where N is the length of the string. <em>Each character is processed at most once.</em></li><li><strong>Space Complexity:</strong> O(M), where M is the size of the character set, which can be up to 256 for ASCII.</li></ul><p>For more such in-depth explanations, problem-solving techniques, and coding interview patterns, consider purchasing the <strong>“</strong><a href="https://www.amazon.com/Handbook-Coding-Interviews-K-PATIL-ebook/dp/B0DGFRWGLQ"><strong>Handbook for Coding Interviews</strong></a><strong>” </strong>available on <a href="https://www.amazon.com/Handbook-Coding-Interviews-K-PATIL-ebook/dp/B0DGFRWGLQ">Amazon.com</a>. This book is a comprehensive guide to acing coding interviews with detailed solutions to the most frequently asked coding interview questions.</p><p>If you found this post useful, <strong>please follow me</strong> on Medium. More to come!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0a76ae287bae" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Finding the Longest Common Prefix in an Array of Strings]]></title>
            <link>https://techsauce.medium.com/finding-the-longest-common-prefix-in-an-array-of-strings-0f5da478990e?source=rss-32c92f65c2e9------2</link>
            <guid isPermaLink="false">https://medium.com/p/0f5da478990e</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[coding-interview-problems]]></category>
            <category><![CDATA[technical-interview]]></category>
            <category><![CDATA[coding-interviews]]></category>
            <category><![CDATA[strings-in-java]]></category>
            <dc:creator><![CDATA[Tech Sauce]]></dc:creator>
            <pubDate>Fri, 13 Sep 2024 01:13:22 GMT</pubDate>
            <atom:updated>2024-09-13T03:52:03.253Z</atom:updated>
            <content:encoded><![CDATA[<h4>Let’s solve this tricky problem often asked in coding interviews.</h4><h3>Problem Statement</h3><p>Given an array of strings, your task is to find the longest common prefix amongst all the strings.</p><p>The common prefix is the initial part of each string that is shared by all strings in the array. If there is no common prefix, return an empty string &quot;&quot;.</p><h3>Problem Constraints</h3><ul><li>The input array of strings can have a length of 0 or more.</li><li>All strings contain lowercase English letters.</li></ul><h3>Examples</h3><p>Let’s go through a few examples to understand the expected input and output:</p><p><strong>Example 1:</strong></p><ul><li>Input: [&quot;interview&quot;, &quot;internet&quot;, &quot;internal&quot;, &quot;interval&quot;]</li><li>Output: &quot;inter&quot;</li><li>Explanation: All strings share the prefix “inter”.</li></ul><p><strong>Example 2:</strong></p><ul><li>Input: []</li><li>Output: &quot;&quot;</li><li>Explanation: Since the array is empty, the result is an empty string.</li></ul><p><strong>Example 3:</strong></p><ul><li>Input: [&quot;a&quot;]</li><li>Output: &quot;a&quot;</li><li>Explanation: With only one string in the array, the prefix is the entire string itself.</li></ul><h3>Brute Force Approach</h3><p>In the brute force approach, we compare characters <strong>one by one</strong> from the start of each string in the array, checking character by character for each index until a mismatch is found.</p><h4>Steps:</h4><ol><li>Start with the first character of the first string and compare it with the first character of all other strings.</li><li>If all strings have the same character at the current index, move to the next character.</li><li>Stop when you encounter a mismatch or reach the end of one of the strings.</li><li>The characters checked so far form the longest common prefix.</li></ol><h4>Example:</h4><p>For input [&quot;flower&quot;, &quot;flow&quot;, &quot;flight&quot;], the brute force approach compares each character:</p><pre>1. Compare &#39;f&#39; in all strings: &#39;f&#39; matches.<br>2. Compare &#39;l&#39; in all strings: &#39;l&#39; matches.<br>3. Compare &#39;o&#39; in all strings: mismatch found (3rd string starts with &#39;i&#39; instead of &#39;o&#39;).</pre><p>The longest common prefix is “fl”.</p><h4>Code</h4><p>Here is the implementation of brute force approach in Java:</p><pre>public class LongestCommonPrefixBruteForce {<br><br>    // Function to find the longest common prefix using brute force approach<br>    public static String longestCommonPrefixBruteForce(String[] strs) {<br>        if (strs == null || strs.length == 0) {<br>            return &quot;&quot;; // Edge case: if the input array is empty, return an empty string<br>        }<br><br>        // Start with the first string and compare each character with the corresponding character in other strings<br>        for (int i = 0; i &lt; strs[0].length(); i++) {<br>            char currentChar = strs[0].charAt(i); // Current character from the first string<br><br>            // Compare this character with the same position in all other strings<br>            for (int j = 1; j &lt; strs.length; j++) {<br>                // If we reach the end of any string or find a mismatch, return the result up to this point<br>                if (i &gt;= strs[j].length() || strs[j].charAt(i) != currentChar) {<br>                    return strs[0].substring(0, i);<br>                }<br>            }<br>        }<br><br>        // If no mismatch was found, the entire first string is the common prefix<br>        return strs[0];<br>    }<br><br>    // Main method to test the brute force approach<br>    public static void main(String[] args) {<br>        String[] test1 = {&quot;flower&quot;, &quot;flow&quot;, &quot;flight&quot;};<br>        String[] test2 = {&quot;dog&quot;, &quot;racecar&quot;, &quot;car&quot;};<br>        String[] test3 = {&quot;interview&quot;, &quot;internet&quot;, &quot;internal&quot;, &quot;interval&quot;};<br>        String[] test4 = {&quot;a&quot;};<br>        String[] test5 = {};<br><br>        System.out.println(&quot;Brute Force - Longest Common Prefix: &quot; + longestCommonPrefixBruteForce(test1)); // Output: &quot;fl&quot;<br>        System.out.println(&quot;Brute Force - Longest Common Prefix: &quot; + longestCommonPrefixBruteForce(test2)); // Output: &quot;&quot;<br>        System.out.println(&quot;Brute Force - Longest Common Prefix: &quot; + longestCommonPrefixBruteForce(test3)); // Output: &quot;inter&quot;<br>        System.out.println(&quot;Brute Force - Longest Common Prefix: &quot; + longestCommonPrefixBruteForce(test4)); // Output: &quot;a&quot;<br>        System.out.println(&quot;Brute Force - Longest Common Prefix: &quot; + longestCommonPrefixBruteForce(test5)); // Output: &quot;&quot;<br>    }<br>}</pre><h4>Time Complexity:</h4><ul><li><strong>O(N * M)</strong> where N is the number of strings and M is the length of the shortest string. This is because in the worst case, every character of every string must be checked until a mismatch is found.</li></ul><h4>Space Complexity:</h4><ul><li><strong>O(1)</strong>, no extra space beyond the input array is used.</li></ul><h3>Optimal Approach</h3><p>In the optimal approach, we start with the first string as the initial prefix and iteratively shorten it as needed by comparing it with each subsequent string. We compare entire prefixes at once, instead of individual characters, which reduces the number of comparisons.</p><h4>Steps:</h4><ul><li>Initialize the prefix as the first string.</li><li>Compare this prefix with each of the remaining strings:</li><li>If the current string does not start with the prefix, progressively shorten the prefix until it matches or becomes empty.</li><li>If at any point the prefix becomes empty, return an empty string (no common prefix).</li><li>After comparing with all strings, return the final prefix.</li></ul><h4>Example:</h4><p>For input [&quot;flower&quot;, &quot;flow&quot;, &quot;flight&quot;], the optimal approach follows these steps:</p><pre>1. Initialize prefix = &quot;flower&quot;.<br>2. Compare with &quot;flow&quot;: shorten prefix to &quot;flow&quot; because &quot;flower&quot; is longer than &quot;flow&quot;.<br>3. Compare with &quot;flight&quot;: shorten prefix from &quot;flow&quot; to &quot;fl&quot; (because &quot;flight&quot; doesn&#39;t start with &quot;flo&quot;).</pre><p>The longest common prefix is “fl”.</p><h4>Code</h4><p>Here is the implementation of optimal approach in Java:</p><pre>public class LongestCommonPrefixOptimal {<br><br>    // Function to find the longest common prefix using the optimal approach<br>    public static String longestCommonPrefixOptimal(String[] strs) {<br>        if (strs == null || strs.length == 0) {<br>            return &quot;&quot;; // Edge case: if the input array is empty, return an empty string<br>        }<br><br>        // Initialize the prefix as the first string<br>        String prefix = strs[0];<br><br>        // Iterate over the rest of the strings in the array<br>        for (int i = 1; i &lt; strs.length; i++) {<br>            // Reduce the prefix while it does not match the start of the current string<br>            while (strs[i].indexOf(prefix) != 0) {<br>                // Shorten the prefix by removing the last character<br>                prefix = prefix.substring(0, prefix.length() - 1);<br><br>                // If the prefix is reduced to an empty string, return an empty string<br>                if (prefix.isEmpty()) {<br>                    return &quot;&quot;;<br>                }<br>            }<br>        }<br><br>        return prefix; // Return the final longest common prefix<br>    }<br><br>    // Main method to test the optimal approach<br>    public static void main(String[] args) {<br>        String[] test1 = {&quot;flower&quot;, &quot;flow&quot;, &quot;flight&quot;};<br>        String[] test2 = {&quot;dog&quot;, &quot;racecar&quot;, &quot;car&quot;};<br>        String[] test3 = {&quot;interview&quot;, &quot;internet&quot;, &quot;internal&quot;, &quot;interval&quot;};<br>        String[] test4 = {&quot;a&quot;};<br>        String[] test5 = {};<br><br>        System.out.println(&quot;Optimal - Longest Common Prefix: &quot; + longestCommonPrefixOptimal(test1)); // Output: &quot;fl&quot;<br>        System.out.println(&quot;Optimal - Longest Common Prefix: &quot; + longestCommonPrefixOptimal(test2)); // Output: &quot;&quot;<br>        System.out.println(&quot;Optimal - Longest Common Prefix: &quot; + longestCommonPrefixOptimal(test3)); // Output: &quot;inter&quot;<br>        System.out.println(&quot;Optimal - Longest Common Prefix: &quot; + longestCommonPrefixOptimal(test4)); // Output: &quot;a&quot;<br>        System.out.println(&quot;Optimal - Longest Common Prefix: &quot; + longestCommonPrefixOptimal(test5)); // Output: &quot;&quot;<br>    }<br>}</pre><h4>Time Complexity:</h4><ul><li><strong>O(N * M)</strong> where N is the number of strings and M is the length of the shortest string. This is because each string is compared against the current prefix, but we reduce the number of character comparisons by eliminating mismatches early.</li></ul><h4>Space Complexity:</h4><ul><li><strong>O(1)</strong>, no extra space beyond the input array is used.</li></ul><h3>Key Differences:</h3><ul><li><strong>Brute force</strong> compares each character of all strings one by one.</li><li><strong>Optimal approach</strong> compares whole prefixes at once, reducing unnecessary character comparisons by eliminating mismatches early.</li></ul><p>If you’re seeking a comprehensive guide to ace your coding interviews, I highly recommend <a href="https://www.amazon.com/Handbook-Coding-Interviews-K-PATIL-ebook/dp/B0DGFRWGLQ"><strong>Handbook for Coding Interviews</strong></a>. This book covers all the essential topics to fully prepare you for technical interviews.</p><p>If you found this post useful, follow me on Medium, more to come!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0f5da478990e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Solving Course Schedule Coding Interview Question]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-snippet">In this post, we will solve very popular coding interview question called &#x201C;Course Schedule&#x201D; by applying Graph Algorithms.</p><p class="medium-feed-link"><a href="https://techsauce.medium.com/solving-course-schedule-coding-interview-question-845a69f63b56?source=rss-32c92f65c2e9------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://techsauce.medium.com/solving-course-schedule-coding-interview-question-845a69f63b56?source=rss-32c92f65c2e9------2</link>
            <guid isPermaLink="false">https://medium.com/p/845a69f63b56</guid>
            <category><![CDATA[problem-solving]]></category>
            <category><![CDATA[graph]]></category>
            <category><![CDATA[graph-interview-question]]></category>
            <category><![CDATA[course-schedule]]></category>
            <category><![CDATA[coding-interviews]]></category>
            <dc:creator><![CDATA[Tech Sauce]]></dc:creator>
            <pubDate>Fri, 12 Jul 2024 23:11:18 GMT</pubDate>
            <atom:updated>2024-07-12T23:16:50.164Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Graph Representations: A Comprehensive Guide]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://techsauce.medium.com/graph-representations-a-comprehensive-guide-b47114afc221?source=rss-32c92f65c2e9------2"><img src="https://cdn-images-1.medium.com/max/600/0*OOIcrvIL6UQ_9Di1" width="600"></a></p><p class="medium-feed-snippet">In this post, we will look at various graph representations and how to translate the representation to the code in Java.</p><p class="medium-feed-link"><a href="https://techsauce.medium.com/graph-representations-a-comprehensive-guide-b47114afc221?source=rss-32c92f65c2e9------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://techsauce.medium.com/graph-representations-a-comprehensive-guide-b47114afc221?source=rss-32c92f65c2e9------2</link>
            <guid isPermaLink="false">https://medium.com/p/b47114afc221</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[coding-interviews]]></category>
            <category><![CDATA[graph-representation]]></category>
            <category><![CDATA[coding-interview-problems]]></category>
            <category><![CDATA[graph]]></category>
            <dc:creator><![CDATA[Tech Sauce]]></dc:creator>
            <pubDate>Wed, 15 May 2024 17:11:47 GMT</pubDate>
            <atom:updated>2024-07-12T23:17:45.673Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Guide to Designing a Scalable API Rate Limiter]]></title>
            <link>https://techsauce.medium.com/guide-to-designing-a-scalable-api-rate-limiter-890dfb4428cf?source=rss-32c92f65c2e9------2</link>
            <guid isPermaLink="false">https://medium.com/p/890dfb4428cf</guid>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[scalable-systems]]></category>
            <category><![CDATA[rate-limiting]]></category>
            <category><![CDATA[api-rate-limiter]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <dc:creator><![CDATA[Tech Sauce]]></dc:creator>
            <pubDate>Thu, 02 May 2024 20:23:31 GMT</pubDate>
            <atom:updated>2024-05-02T20:23:31.419Z</atom:updated>
            <content:encoded><![CDATA[<h4>In this guide, we will explore how to design a scalable API rate limiter and delve into its scaling strategies.</h4><p>In the world of web development and API management, ensuring that your services remain both reliable and responsive under varying loads is crucial. One effective tool to achieve this is an API rate limiter. This component not only helps in preventing abuse but also manages the load on your infrastructure, ensuring that all users have a fair access level.</p><p>An API rate limiter is a mechanism that controls the number of API requests that a user can make within a specified time period. The primary goals are to prevent abuse of the API (intentional or not) and to manage the load on the underlying infrastructure.</p><h3>Key Components of an API Rate Limiter</h3><ol><li>Request Identifier: Identifies who is making the request. This could be based on the user’s IP address, API token, or user ID.</li><li>Rate Limiting Algorithm: The logic that determines whether a request should be allowed or blocked based on the number of requests made in a given time frame.</li><li>Data Store: A system to track the count of requests made by each identifier.</li></ol><h3>Common Rate Limiting Algorithms</h3><h4>1. Fixed Window Counter</h4><p>This algorithm divides the time into fixed windows (e.g., per minute or per hour) and allows a set number of requests in each window. It’s simple to implement but can allow bursts of traffic at the boundary of the time windows.</p><h4>2. Sliding Log</h4><p>A more complex approach where each request is logged with a timestamp, and the system counts the requests in the sliding window. This approach prevents boundary bursts but requires more storage and computational power.</p><h4>3. Token Bucket</h4><p>This method uses tokens to control access. Each request costs a token, and tokens regenerate over time. This allows for some burstiness but smoothens out the rate over longer periods.</p><h4>4. Leaky Bucket</h4><p>Similar to the token bucket but enforces a more consistent output rate, regardless of burst inputs. It’s useful for smoothing out traffic patterns.</p><h3>Implementation Steps</h3><h4>Step 1: Define Rate Limits</h4><p>Determine how many requests per time interval are appropriate, considering your server capacity and the user’s need.</p><h4>Step 2: Choose the Right Algorithm</h4><p>Select an algorithm based on your specific requirements for accuracy, burst handling, and server load.</p><h4>Step 3: Implementing with Redis as a Data Store</h4><p>Using Redis, an in-memory data structure store, for implementing rate limiting is efficient and scalable.</p><p>Here’s a basic example using the Fixed Window Counter approach:</p><p><strong>Python:</strong></p><pre>import redis<br>import time<br><br>redis_client = redis.StrictRedis(host=&#39;localhost&#39;, port=6379, db=0)<br><br>def is_rate_limited(user_id, limit=100):<br>    key = f&quot;rate_limit:{user_id}:{int(time.time() // 60)}&quot;  # 1-minute window<br>    current_count = redis_client.get(key)<br>    if current_count is None or int(current_count) &lt; limit:<br>        redis_client.incr(key)<br>        redis_client.expire(key, 60)  # expire in 60 seconds<br>        return False<br>    else:<br>        return True</pre><p><strong>Java:</strong></p><pre>import redis.clients.jedis.Jedis;<br><br>public class RateLimiter {<br>    private final Jedis jedis;<br>    private final int limit;<br><br>    public RateLimiter(String redisHost, int redisPort, int limit) {<br>        this.jedis = new Jedis(redisHost, redisPort);<br>        this.limit = limit;  // Limit for requests per minute<br>    }<br><br>    public boolean isRateLimited(String userId) {<br>        String key = &quot;rate_limit:&quot; + userId + &quot;:&quot; + System.currentTimeMillis() / 60000; // 1-minute window<br>        String currentCount = jedis.get(key);<br>        <br>        if (currentCount == null) {<br>            // No requests in the current minute, set the key with an expiry of 60 seconds<br>            jedis.setex(key, 60, &quot;1&quot;);<br>            return false;<br>        } else {<br>            int count = Integer.parseInt(currentCount);<br>            if (count &lt; limit) {<br>                jedis.incr(key);  // Increment the count<br>                return false;<br>            } else {<br>                return true;  // Limit exceeded<br>            }<br>        }<br>    }<br><br>    public static void main(String[] args) {<br>        RateLimiter rateLimiter = new RateLimiter(&quot;localhost&quot;, 6379, 100);<br>        String userId = &quot;user123&quot;;<br><br>        // Simulate a series of API requests<br>        for (int i = 0; i &lt; 105; i++) {<br>            boolean limited = rateLimiter.isRateLimited(userId);<br>            System.out.println(&quot;Request &quot; + (i + 1) + &quot;: &quot; + (limited ? &quot;Rate limit exceeded&quot; : &quot;Request allowed&quot;));<br>        }<br>    }<br>}</pre><h3>Scaling the Rate Limiter</h3><h4>Horizontal Scaling</h4><p>Deploy multiple instances of the rate limiter with a load balancer to distribute the requests. Ensure that the data store (e.g., Redis) can handle the increased load and is properly clustered.</p><h4>Data Store Clustering</h4><p>Use a clustered data store solution to manage the state across multiple rate limiter instances. Redis Cluster can automatically split your dataset among multiple nodes, which is beneficial for performance and high availability.</p><h4>Rate Limiting at the Edge</h4><p>Implement rate limiting as close to the user as possible, such as at the load balancer or API gateway level. This reduces the load on your backend servers and can also reduce latency.</p><h3>Conclusion</h3><p>Designing a scalable API rate limiter involves choosing the right algorithm and backing technology that matches your specific needs for rate accuracy, burst handling, and infrastructure load management. By carefully planning and implementing these systems, you can ensure that your API remains robust and fair under all load conditions.</p><p>If you found this article useful, please <strong>follow me</strong> on Medium. More to come!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=890dfb4428cf" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>