<?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 Madhura Mehendale on Medium]]></title>
        <description><![CDATA[Stories by Madhura Mehendale on Medium]]></description>
        <link>https://medium.com/@madhuramehendale?source=rss-ee5efea33790------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*J6dSZCb36AbCiVgI.</url>
            <title>Stories by Madhura Mehendale on Medium</title>
            <link>https://medium.com/@madhuramehendale?source=rss-ee5efea33790------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 08:29:44 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@madhuramehendale/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[What are APIs?]]></title>
            <link>https://madhuramehendale.medium.com/what-are-apis-6c98631c5dc4?source=rss-ee5efea33790------2</link>
            <guid isPermaLink="false">https://medium.com/p/6c98631c5dc4</guid>
            <category><![CDATA[https]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[fullstack-development]]></category>
            <dc:creator><![CDATA[Madhura Mehendale]]></dc:creator>
            <pubDate>Sun, 27 Jul 2025 11:37:04 GMT</pubDate>
            <atom:updated>2025-07-27T11:37:04.461Z</atom:updated>
            <content:encoded><![CDATA[<p>You’ve likely heard the term <em>API</em> mentioned frequently — but what exactly is it, and why is it so important? In this article, we’ll demystify APIs by explaining what they are, how they work, and why they are essential to modern software development.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WaHbRhx4aYcKMztMO3h8xA.jpeg" /></figure><p>Think of a typical web application, lets consider <em>amazon</em>. <em>Amazon</em> supports various features such as <strong>add to cart, order, make payment, search, filter</strong>, etc. Typically such application can be broadly divided into two parts the front end and the back end. The front end forms all the visual parts- <strong>buttons, search box, screen, modals</strong>, etc. These are the components the user interacts with. Another part is the backend. <strong><em>Backend</em></strong> is where business logic occurs. Backend also contains of the data base. In case of <em>amazon</em>, a database might contain <strong>users, products, orders</strong>, etc. Let’s walkthrough a simple user interaction — searching for a product. What does the backend do in this case? In the backend, the query is executed against the database in order to fetch the products that match this query in simple terms. Another common interaction is place an order — it includes backend tasks such as validation that all items are in stock, calculate the bill amount, process the payment, do necessary operations in the database, send confirmation on email/mobile, etc. I hope through this example, you get a high-level understanding of how the frontend and backend work together in a typical web application.</p><p>Now you may be thinking how are the backend and frontend connected? How do they communicate with each other? When the user enters a term for search, how does the backend know what the user entered? This is exactly when API comes into picture.</p><p><strong>API (Application Programming Interface)</strong> can be imagined as a <strong>gate or doorway</strong> in the backend that the frontend uses to <strong>send requests and receive data</strong>. It acts as the official channel through which the frontend communicates with the backend services, ensuring that both sides understand each other.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5EgxxoAiR_rBjpMsiKDrQw.png" /></figure><p>So, how does the frontend send data to the backend through an API? This happens through an <strong>HTTP</strong> request. Now, you might be wondering what exactly an HTTP request is. HTTP is a protocol through which most of the web communicates. Other common protocols include <strong>FTP</strong> (used for file transfers), <strong>DNS</strong> (used for address resolution), and <strong>SMTP</strong> (used for sending emails).</p><h3>HTTP Request</h3><p>An <strong>HTTP request</strong> is a message sent by a <strong>client (usually a browser or frontend)</strong> to a <strong>server (backend)</strong> asking for some action — like getting data, submitting a form, or updating something.</p><p>A HTTP request consist of the following parts.</p><ol><li>URL endpoint (Example- <a href="https://amazon.com/api/products?q=headphones">https://amazon.com/api/products?q=headphones</a>)</li><li>HTTP method (GET, POST, PUT, DELETE)</li><li>Headers</li><li>Query parameters</li><li>Body</li></ol><p>Let’s go through each of these with an example. Consider you want to search for a product on amazon, lets say you’re looking for an oven. You type <strong><em>oven</em></strong> in the search bar and hit the search button. You can find the following request in the network tab of the chrome developer tools as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ss200xu0L7yBVG6iSflhOw.png" /></figure><p>From the screenshot, we can gather some information about the http request.</p><p><strong>URL</strong> end point is — <a href="https://www.amazon.com/s?i=aps&amp;k=oven&amp;ref=nb_sb_noss&amp;url=search-alias%3Daps">https://www.amazon.com/s?i=aps&amp;k=oven&amp;ref=nb_sb_noss&amp;url=search-alias%3Daps</a></p><p><strong>HTTP</strong> method used is <strong>GET</strong>.</p><p><strong>Headers</strong>: There are a bunch of request headers including Accept, Accept-Headers, Accept-Encoding, etc.</p><p><strong>Query parameters:</strong> If you look closely at the URL endpoint, you will see a question mark, everything after the question mark with the format <strong><em>key=value</em></strong> forms a query parameter. In our example <em>i=aps</em>, <em>k=oven</em>, <em>ref=nb_sb_noss</em> and url=<em>search-alias%3Daps</em></p><p><strong>Body:</strong> Get requests don’t have a body, only PUT and POST will have a body. We will discuss more about this.</p><p>Lets dissect each part of the request. Now, you might be wondering I want to understand what a API is, why am I worried about this, don’t worry we will find this soon.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eG2L7hncW1MFNv6JE9lYag.jpeg" /><figcaption>Http request with the parts labeled</figcaption></figure><h4>URL endpoint</h4><p>You can think of a URL endpoint as a specific coordinate on the web — it tells you exactly where to send your request. It represents the final destination, typically a backend server that’s ready to receive and respond to the request. Here are some examples of URL endpoints.</p><p><em>https://api.openweathermap.org/data/2.5/weather?q=London&amp;appid=YOUR_API_KEY</em></p><p><em>https://api.twitter.com/2/tweets</em></p><h4>HTTP METHOD</h4><p>Depending on what kind of request you want to send, different HTTP methods are used.</p><p>Let’s say you want to retrieve some information — like all the headphones listed on Amazon, all tweets posted by John, or all Instagram posts with the hashtag #codingiscool. These are all examples of <strong>read operations</strong>, where data is simply fetched and returned to the frontend without making any changes to it. In HTTP, such requests typically use the <strong>GET</strong> method.</p><p>Suppose you want to add new data to a system — like signing up a new user on Instagram, placing a new order on Amazon, or posting a new tweet on X. In such cases, the HTTP method used is <strong>POST</strong>, which is typically used to <strong>send data to the server to create a new resource</strong>.</p><p>Let’s say you want to perform a delete operation — such as removing a tweet or deleting your Instagram profile. In such cases, the HTTP method used is <strong>DELETE</strong>.</p><p>Another commonly used method is <strong>PATCH</strong>, which is used for updates — such as changing your username or editing your profile information.</p><blockquote>By convention, developers try to maintain these rules while working on the frontend. These are like the common language shared accross developers.</blockquote><h4>Headers</h4><p><strong>Headers</strong> are key-value pairs sent along with HTTP <strong>requests</strong> and <strong>responses</strong>. They carry <strong>additional information (metadata)</strong> about the request or response.</p><p>Think of headers like the <strong>envelope details</strong> of a letter — they tell the server or client important info about the message contents, how to handle it, or who is sending it.</p><p><strong><em>Common request headers:</em></strong></p><ul><li>Content-Type: The format of the data sent (application/json)</li><li>Set-Cookie: Sets cookies in the browser</li><li>Cache-Control: Tells browsers and proxies how to cache the response</li><li>Access-Control-Allow-Origin: Manages cross-origin resource sharing (CORS). For more info on CORS, you can refer another <a href="https://medium.com/@madhuramehendale/introduction-to-csp-and-cors-a87cf01806c3">article</a> of mine.</li></ul><p>Response can also set such headers to indicate to the browser how to read the response. For each HTTP request, a backend server also sends a HTTP response, we will dig more into this later on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i4XSREgK6hTHj4PQVm48Pg.png" /><figcaption>HTTP Request Methods</figcaption></figure><h4>Body</h4><p>The <strong>body</strong> of an HTTP request is the part where you <strong>send data</strong> from the client to the server. It usually contains the information you want the server to process, like form data, JSON payloads, or file uploads. The body is typically sent in <strong>POST</strong> and <strong>PATCH</strong> requests. For example, if you want to create a new post on instagram, all the details of your post including the post content, tags, hastags, caption all are sent in the body of the <strong>POST</strong> request being made. Similarly if you want to update your user name, the new user name is sent in the body of the <strong>PATCH</strong> request. You might be wondering, what if I want to send some information in <strong>GET</strong> or <strong>DELETE</strong>, in these methods, any information necessary will be part of URL endpoint, usually in the part of the path or part of query parameters which we will look into next.</p><h4>Query Parameters</h4><p><strong>Query parameters</strong> are <strong>key-value pairs</strong> that are added to the <strong>end of a URL</strong> to <strong>send additional information</strong> with a request — usually to <strong>filter, sort, or search</strong> data. They are generally used in <strong>GET</strong> or <strong>DELETE</strong> methods. They come <strong>after a </strong><strong>? in the URL</strong>, and multiple parameters are separated by &amp;.</p><p>Lets say there is a search endpoint and you want to send a request, but you want to include multiple data in the search such as the <strong><em>keyword, filter only products below a price and sort products based on relevance</em></strong>. Since, this is just a read operation, it will be a GET request but no body here to send this information, in such cases we can make use of query parameters which will be part of the URL and will look something like this.</p><ul><li><strong>q</strong>: The search keyword, for example, “laptop”</li><li><strong>max_price</strong>: Filter to only include products below this price, e.g., 1000</li><li><strong>sort</strong>: Sort order, like “relevance”</li></ul><p>URL endpoint: <a href="https://www.amazon.com/s?k=wireless+headphones&amp;rh=p_36%3A-10000&amp;sort=relevanceblender">https://www.amazon.com/s?k=wireless+headphones&amp;rh=p_36%3A-10000&amp;sort=relevanceblender</a> (you can open the URL and check)</p><p>In <strong>DELETE</strong> methods, generally the query parameters are used to indicate what to delete. Example: userId=1431241</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*34d1b2yaak7Zcqxuja4_WA.png" /><figcaption>HTTP Request Parts</figcaption></figure><h3>API</h3><p>Now that we are clear about HTTP requests, lets understand how they are related to API. HTTP requests are sent from front end to backend asking for some information or asking to do some kind of operation. But who is listening to and responding to those requests on the backend. The API endpoints are what will process these requests and send a HTTP response back.</p><p>Think of API endpoints as <strong>specific addresses or doors</strong> on the backend server. When a request arrives at one of these endpoints, the backend knows exactly what to do — whether it’s fetching product details, adding an item to a cart, or processing a payment.</p><p>Behind these API endpoints, there’s usually something called an <strong>API controller</strong> (in many backend frameworks). The controller acts like a traffic manager. It <strong>receives the incoming requests</strong>, checks if the data sent is valid, interacts with the database or other services, and then <strong>sends the appropriate response</strong> back to the frontend.</p><p>For example, if the frontend sends a GET request to /api/products/123, the API controller responsible for products will handle this request by retrieving product number 123 from the database and returning its details in the response.</p><p>To sum up:</p><ul><li><strong>Frontend</strong> sends an HTTP request to a <strong>specific API endpoint</strong></li><li>The <strong>API endpoint</strong> is linked to a controller or handler on the backend</li><li>The controller processes the request, performs the necessary operations, and</li><li>Sends back an HTTP <strong>response</strong> with the requested data or status</li></ul><p>This communication between frontend and backend via HTTP requests and API endpoints is what powers most modern web and mobile applications.</p><p>The <strong>controller</strong> receives the request and does whatever it needs to do (update record, fetch record, etc) through the help of services and responds to the request with appropriate data. The <strong>METHOD </strong>that can be used by the HTTP request to access a particular API endpoint is defined within the controller, if the controller defines the method as GET then the frontend has to send a GET request. Similarly the controller has logic for reading and processing the query parameters, for reading and enacting the Headers as well as processing information in the body. If any of those are not as expected or don’t follow the API definition, the server will respond with an error.</p><h4>API Definition</h4><p>An <strong>API definition</strong> is a <strong>formal specification</strong> that describes:</p><ul><li>What <strong>endpoints</strong> are available (e.g., /api/products)</li><li>What <strong>HTTP methods</strong> to use (GET, POST, PUT, DELETE)</li><li>What <strong>data</strong> the client needs to send (body, headers, query params)</li><li>What <strong>response</strong> the server will return (status codes, JSON structure)</li><li>What <strong>errors</strong> can occur and how they’ll be formatted</li></ul><p><strong>Example of API definition/contract:</strong></p><pre>GET /api/products/{id}:<br>  summary: Get a product by ID<br>  parameters:<br>    - name: id<br>      in: path<br>      required: true<br>      type: string<br>  responses:<br>    200:<br>      description: Success<br>      content:<br>        application/json:<br>          example:<br>            id: 123<br>            name: &quot;Wireless Mouse&quot;<br>            price: 25.99<br>    404:<br>      description: Product not found</pre><blockquote>API contract is an agreement between the frontend and backend about how the endpoint will look like and how it will work. This is defined in order to bring clarity between the people who are developing and who are consuming it since people who work on frontend and backend might be different and the backend consists of API development and frontend sends the HTTP request. Hence, it is essential to have a mutual agreement regarding the functionalities.</blockquote><p>Now lets jump into the HTTP response and how they look like.</p><h3><strong>HTTP Response</strong></h3><p>HTTP response is sent by the backend (API controller) to the frontend, it is a response to the HTTP request being sent. An HTTP response typically has <strong>four main parts</strong>:</p><h4>Status Line</h4><ul><li>Indicates the <strong>HTTP version</strong>, <strong>status code</strong>, and a <strong>reason phrase</strong>.</li><li>Format:<br> HTTP/1.1 200 OK</li></ul><p>Example status codes:</p><ul><li>200 OK — Success</li><li>404 Not Found — Resource not found</li><li>500 Internal Server Error — Server error</li></ul><h4>Response Headers</h4><p>These are <strong>key-value pairs</strong> that provide metadata about the response. These are similar to request headers but they are sent by the backend to the frontend to inform the frontend about some details of the response and how it needs to handled.</p><p>Common headers include:</p><ul><li>Content-Type: Type of the returned content (e.g., application/json, text/html)</li><li>Content-Length: Size of the response body</li><li>Set-Cookie: Used to set cookies on the client</li><li>Cache-Control: Directives for caching the response</li></ul><h4>Blank Line</h4><p>A <strong>mandatory empty line</strong> separating the headers from the body.</p><h4>Response Body</h4><p>Response body is the actual data returned by the server. Suppose the request asked for headphones under a certain price range, the response body contains this data. The response can be in different formats — html, json, xml, etc</p><p>Example of a complete response.</p><pre>HTTP/1.1 200 OK<br>Content-Type: application/json<br>Cache-Control: no-cache<br><br>{<br>  &quot;id&quot;: 101,<br>  &quot;name&quot;: &quot;Wireless Mouse&quot;,<br>  &quot;price&quot;: 25.99<br>}</pre><p>By now, I hope you understand at a high level what is frontend and backend and how they communicate. I will be delving deeper into some topic here in the future, please keep an eye!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6c98631c5dc4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to build a chess Engine? Part 1]]></title>
            <link>https://madhuramehendale.medium.com/how-to-build-a-chess-engine-part-1-a515274a10a6?source=rss-ee5efea33790------2</link>
            <guid isPermaLink="false">https://medium.com/p/a515274a10a6</guid>
            <category><![CDATA[chess]]></category>
            <category><![CDATA[game-theory]]></category>
            <category><![CDATA[fun-projects]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[html]]></category>
            <dc:creator><![CDATA[Madhura Mehendale]]></dc:creator>
            <pubDate>Thu, 01 May 2025 10:45:02 GMT</pubDate>
            <atom:updated>2025-05-01T10:45:02.360Z</atom:updated>
            <content:encoded><![CDATA[<p>Chess is a complex game, featuring a variety of pieces, diverse moves, and an infinite number of possible board states. As a result, building a chess game is both a challenging and rewarding task. In this article, we’ll explore the key components required to build a chess game and implement them step by step, with a little help from ChatGPT.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OEgLga3RIcgTtXSzVy968Q.jpeg" /></figure><p>We’ll start from the ground up by building the game and creating the chessboard. Next, we’ll implement the movement logic for each piece and encode the rules of the game. Once the fundamentals are in place, we’ll explore game theory concepts to help the engine make intelligent decisions.</p><p>If you’re unfamiliar with chess and its rules, you can refer to <a href="https://www.youtube.com/watch?v=6Pqd7UFWr7M">this</a> video for a quick introduction.</p><h3>Modeling the Game</h3><p>We will use a simple <strong><em>8×8</em></strong> grid (a 2D array) to represent the chessboard. Each piece will be a character, and empty cells will be null. Here’s a simple code example to set it up</p><pre>// Initialize a simple 8x8 chessboard<br>const board = [<br>  [&quot;r&quot;, &quot;n&quot;, &quot;b&quot;, &quot;q&quot;, &quot;k&quot;, &quot;b&quot;, &quot;n&quot;, &quot;r&quot;], // 8th rank (Black&#39;s major pieces)<br>  [&quot;p&quot;, &quot;p&quot;, &quot;p&quot;, &quot;p&quot;, &quot;p&quot;, &quot;p&quot;, &quot;p&quot;, &quot;p&quot;], // 7th rank (Black&#39;s pawns)<br>  [null, null, null, null, null, null, null, null], // 6th rank (empty)<br>  [null, null, null, null, null, null, null, null], // 5th rank (empty)<br>  [null, null, null, null, null, null, null, null], // 4th rank (empty)<br>  [null, null, null, null, null, null, null, null], // 3rd rank (empty)<br>  [&quot;P&quot;, &quot;P&quot;, &quot;P&quot;, &quot;P&quot;, &quot;P&quot;, &quot;P&quot;, &quot;P&quot;, &quot;P&quot;], // 2nd rank (White&#39;s pawns)<br>  [&quot;R&quot;, &quot;N&quot;, &quot;B&quot;, &quot;Q&quot;, &quot;K&quot;, &quot;B&quot;, &quot;N&quot;, &quot;R&quot;]  // 1st rank (White&#39;s major pieces)<br>];</pre><p>Here, uppercase represents white pieces and lowercase represents black pieces. Quickly refer to the table below to understand what each character stands for.</p><ul><li>P or p → Pawn (♙ or ♟)</li><li>R or r → Rook (♖ or ♜)</li><li>N or n → Knight (♘ or ♞)</li><li>B or b → Bishop (♗ or ♝)</li><li>Q or q → Queen (♕ or ♛)</li><li>K or k → King (♔ or ♚)</li></ul><p>Let&#39;s utilise the array above, but simulate actual pieces in HTML for a better look.</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>&lt;head&gt;<br>  &lt;meta charset=&quot;UTF-8&quot;&gt;<br>  &lt;title&gt;Chess Board with Unicode Pieces&lt;/title&gt;<br>  &lt;style&gt;<br>    body {<br>      display: flex;<br>      justify-content: center;<br>      margin-top: 50px;<br>    }<br>    #chessboard {<br>      display: grid;<br>      grid-template-columns: repeat(8, 60px);<br>      grid-template-rows: repeat(8, 60px);<br>      border: 2px solid black;<br>    }<br>    .cell {<br>      display: flex;<br>      align-items: center;<br>      justify-content: center;<br>      width: 60px;<br>      height: 60px;<br>      font-size: 36px;<br>      font-family: &quot;Arial&quot;, sans-serif;<br>    }<br>    .white {<br>      background-color: #f0d9b5;<br>    }<br>    .black {<br>      background-color: #b58863;<br>    }<br>    .white-piece {<br>      color: white;<br>      text-shadow: 1px 1px 2px black;<br>    }<br>    .black-piece {<br>      color: black;<br>    }<br>  &lt;/style&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br><br>&lt;div id=&quot;chessboard&quot;&gt;&lt;/div&gt;<br><br>&lt;script&gt;<br>  const boardElement = document.getElementById(&#39;chessboard&#39;);<br><br>  const board = [<br>    [&#39;r&#39;,&#39;n&#39;,&#39;b&#39;,&#39;q&#39;,&#39;k&#39;,&#39;b&#39;,&#39;n&#39;,&#39;r&#39;],<br>    [&#39;p&#39;,&#39;p&#39;,&#39;p&#39;,&#39;p&#39;,&#39;p&#39;,&#39;p&#39;,&#39;p&#39;,&#39;p&#39;],<br>    [&#39;&#39;,&#39;&#39;,&#39;&#39;,&#39;&#39;,&#39;&#39;,&#39;&#39;,&#39;&#39;,&#39;&#39;],<br>    [&#39;&#39;,&#39;&#39;,&#39;&#39;,&#39;&#39;,&#39;&#39;,&#39;&#39;,&#39;&#39;,&#39;&#39;],<br>    [&#39;&#39;,&#39;&#39;,&#39;&#39;,&#39;&#39;,&#39;&#39;,&#39;&#39;,&#39;&#39;,&#39;&#39;],<br>    [&#39;&#39;,&#39;&#39;,&#39;&#39;,&#39;&#39;,&#39;&#39;,&#39;&#39;,&#39;&#39;,&#39;&#39;],<br>    [&#39;P&#39;,&#39;P&#39;,&#39;P&#39;,&#39;P&#39;,&#39;P&#39;,&#39;P&#39;,&#39;P&#39;,&#39;P&#39;],<br>    [&#39;R&#39;,&#39;N&#39;,&#39;B&#39;,&#39;Q&#39;,&#39;K&#39;,&#39;B&#39;,&#39;N&#39;,&#39;R&#39;]<br>  ];<br><br>  const pieceUnicode = {<br>    &#39;K&#39;: &#39;♔&#39;, &#39;Q&#39;: &#39;♕&#39;, &#39;R&#39;: &#39;♖&#39;, &#39;B&#39;: &#39;♗&#39;, &#39;N&#39;: &#39;♘&#39;, &#39;P&#39;: &#39;♙&#39;,<br>    &#39;k&#39;: &#39;♚&#39;, &#39;q&#39;: &#39;♛&#39;, &#39;r&#39;: &#39;♜&#39;, &#39;b&#39;: &#39;♝&#39;, &#39;n&#39;: &#39;♞&#39;, &#39;p&#39;: &#39;♟&#39;<br>  };<br><br>  function renderBoard() {<br>    boardElement.innerHTML = &#39;&#39;;<br>    for (let i = 0; i &lt; 8; i++) {<br>      for (let j = 0; j &lt; 8; j++) {<br>        const cell = document.createElement(&#39;div&#39;);<br>        const isWhiteSquare = (i + j) % 2 === 0;<br>        cell.className = &#39;cell &#39; + (isWhiteSquare ? &#39;white&#39; : &#39;black&#39;);<br>        cell.dataset.row = i;<br>        cell.dataset.col = j;<br><br>        const piece = board[i][j];<br>        if (piece) {<br>          const span = document.createElement(&#39;span&#39;);<br>          span.textContent = pieceUnicode[piece];<br>          span.className = piece === piece.toUpperCase() ? &#39;white-piece&#39; : &#39;black-piece&#39;;<br>          cell.appendChild(span);<br>        }<br><br>        boardElement.appendChild(cell);<br>      }<br>    }<br>  }<br><br>  renderBoard();<br>&lt;/script&gt;<br><br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>Simply copy the code, save it as an HTML file, and open it in your browser — the chessboard will render just like the example below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/607/1*xQ9llRmE81VW8zUObNLPiA.png" /></figure><p>We are ready with the board; let&#39;s move on to the movement logic.</p><h3>Movement logic</h3><p>Now we need to generate all possible moves for each piece on the board. This step is essential for the logic we’ll implement later to determine the best move the engine can make. For simplicity, we’ll assume the engine always plays the White pieces.</p><p>In chess, each piece has its own unique movement rules. Here’s an overview, which is essential for building the movement logic.</p><blockquote>♙ Pawn: Moves forward 1 step (or 2 steps on first move), captures diagonally.<br> ♖ Rook: Moves any number of squares vertically or horizontally.<br> ♘ Knight: Moves in an “L” shape (2 steps one way, 1 step perpendicular).<br> ♗ Bishop: Moves any number of squares diagonally.<br> ♕ Queen: Moves any number of squares vertically, horizontally, or diagonally.<br> ♔ King: Moves 1 square in any direction.</blockquote><p>We’ll develop the movement logic step by step for each piece. Let’s start with the simplest one — the pawn. We’ll define a generic function to generate all possible moves for the piece at a given (row, col) position, as shown below.</p><pre>function getLegalMoves(board, row, col)</pre><h4>Pawn</h4><p>Let’s write the function to generate legal moves for a pawn.</p><p>A pawn can move one square forward if the square is empty, or two squares forward from its starting position if both squares in front are empty. It can also capture an opponent’s piece by moving one square diagonally forward.</p><p>The image below shows typical pawn movement patterns in chess.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/257/1*ddJWQUB6_y-1Phc_JvYfeQ.jpeg" /><figcaption>Pawn Movement</figcaption></figure><p><em>Code —</em></p><pre>function getLegalMovesForPawn(board, row, col) {<br>  const moves = [];<br>  const piece = board[row][col];<br><br>  const isWhite = isWhitePiece(piece);<br>  const direction = isWhite ? -1 : +1;<br>  const startRow = isWhite ? 6 : 1;<br><br>  const forwardRow = row + direction;<br>  if (isInsideBoard(forwardRow, col) &amp;&amp; board[forwardRow][col] === null) {<br>    moves.push([forwardRow, col]);<br><br>    const twoForwardRow = row + 2 * direction;<br>    if (row === startRow &amp;&amp; board[twoForwardRow][col] === null) {<br>      moves.push([twoForwardRow, col]);<br>    }<br>  }<br><br>  for (let offset of [-1, +1]) {<br>    const diagCol = col + offset;<br>    if (isInsideBoard(forwardRow, diagCol)) {<br>      const targetPiece = board[forwardRow][diagCol];<br>      if (<br>        targetPiece &amp;&amp;<br>        ((isWhite &amp;&amp; isBlackPiece(targetPiece)) || (!isWhite &amp;&amp; isWhitePiece(targetPiece)))<br>      ) {<br>        moves.push([forwardRow, diagCol]);<br>      }<br>    }<br>  }<br><br>  return moves;<br>}<br><br>//helper function to determine if the move is within the board<br>function isInsideBoard(row, col) {<br>  return row &gt;= 0 &amp;&amp; row &lt; 8 &amp;&amp; col &gt;= 0 &amp;&amp; col &lt; 8;<br>}<br><br>//helper function to determine if the piece is white<br>function isWhitePiece(piece) {<br>  return piece &amp;&amp; piece === piece.toUpperCase();<br>}<br><br>//helper function to determine if the piece is black<br>function isBlackPiece(piece) {<br>  return piece &amp;&amp; piece === piece.toLowerCase();<br>}</pre><p>Some points on the code-</p><ul><li><strong><em>White pawns move upward</em></strong> (toward decreasing row numbers)</li><li><strong><em>Black pawns move downward</em></strong> (toward increasing row numbers)</li><li><strong><em>Diagonal moves</em></strong> (captures) are only allowed if an opponent’s piece is present on that diagonal square</li><li><strong><em>Two-square forward moves</em></strong> are only allowed from the pawn’s starting row and only if both squares ahead are empty</li></ul><h4>Knight</h4><p>A knight moves in L-shaped patterns in any direction, jumping over any pieces in its path. If the target cell contains an opponent’s piece, the move results in a capture; however, if the piece is of the same color, the move is not allowed. Refer to the image below to visualize the knight’s possible moves.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dUk5A-i7VSQDPoTPkUuypw.png" /><figcaption>Knight movements</figcaption></figure><p>Following is the code to get moves for the knight.</p><pre><br><br>function getLegalMovesForKnight(board, row, col) {<br>  const moves = [];<br>  const piece = board[row][col];<br>  if (!piece) return moves;<br><br>  const isWhite = isWhitePiece(piece);<br><br>  // All possible knight move offsets (row change, col change)<br>  const knightMoves = [<br>    [-2, -1], [-2, +1],<br>    [-1, -2], [-1, +2],<br>    [+1, -2], [+1, +2],<br>    [+2, -1], [+2, +1],<br>  ];<br><br>  for (const [dr, dc] of knightMoves) {<br>    const newRow = row + dr;<br>    const newCol = col + dc;<br>    if (isInsideBoard(newRow, newCol)) {<br>      const targetPiece = board[newRow][newCol];<br>      // Move allowed if square is empty OR has opponent&#39;s piece<br>      if (<br>        !targetPiece ||<br>        (isWhite &amp;&amp; isBlackPiece(targetPiece)) ||<br>        (!isWhite &amp;&amp; isWhitePiece(targetPiece))<br>      ) {<br>        moves.push([newRow, newCol]);<br>      }<br>    }<br>  }<br><br>  return moves;<br>}</pre><h4>Rook</h4><p>The rook moves vertically or horizontally — up, down, left, or right — for any number of squares. It can capture an opponent’s piece if one lies in its path. Refer to the image below for a visual representation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/225/1*8UyzTif3wjaVEtW1Futc0A.jpeg" /></figure><p><em>Code —</em></p><pre>function getLegalMovesForRook(board, row, col) {<br>  const moves = [];<br>  const piece = board[row][col];<br>  const isWhite = piece === piece.toUpperCase();<br><br>  const directions = [<br>    [1, 0],  // down<br>    [-1, 0], // up<br>    [0, 1],  // right<br>    [0, -1]  // left<br>  ];<br><br>  for (const [dr, dc] of directions) {<br>    let r = row + dr;<br>    let c = col + dc;<br><br>    while (isInsideBoard(r, c)) {<br>      const target = board[r][c];<br>      if (target === &#39;&#39;) {<br>        moves.push([r, c]);<br>      } else {<br>        const isTargetWhite = target === target.toUpperCase();<br>        if (isWhite !== isTargetWhite) {<br>          moves.push([r, c]); // capture opponent piece<br>        }<br>        break; // blocked after encounter with opponent&#39;s or same color piece<br>      }<br>      r += dr;<br>      c += dc;<br>    }<br>  }<br><br>  return moves;<br>}<br><br>// Helper function<br>function isInsideBoard(row, col) {<br>  return row &gt;= 0 &amp;&amp; row &lt; 8 &amp;&amp; col &gt;= 0 &amp;&amp; col &lt; 8;<br>}</pre><p>The code is fairly straightforward: each cell in the four cardinal directions is considered a valid move. As you can see, the number of valid moves for a rook is significantly higher compared to a knight or a pawn.</p><h4>Bishop</h4><p>The bishop can move diagonally across any number of cells, capturing an opponent’s piece if encountered. However, its movement is blocked if it encounters a piece of the same color or after making a capture.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/225/1*vjodvFXqGtA4fo0lifj0zg.jpeg" /></figure><p><em>Code —</em></p><pre>function getLegalMovesForBishop(board, row, col) {<br>  const moves = [];<br>  const piece = board[row][col];<br>  const isWhite = piece === piece.toUpperCase();<br><br>  const directions = [<br>    [1, 1],   // down-right<br>    [1, -1],  // down-left<br>    [-1, 1],  // up-right<br>    [-1, -1]  // up-left<br>  ];<br><br>  for (const [dr, dc] of directions) {<br>    let r = row + dr;<br>    let c = col + dc;<br><br>    while (isInsideBoard(r, c)) {<br>      const target = board[r][c];<br>      if (target === &#39;&#39;) {<br>        moves.push([r, c]);<br>      } else {<br>        const isTargetWhite = target === target.toUpperCase();<br>        if (isWhite !== isTargetWhite) {<br>          moves.push([r, c]); // capture opponent piece<br>        }<br>        break; // blocked after encounter<br>      }<br>      r += dr;<br>      c += dc;<br>    }<br>  }<br><br>  return moves;<br>}<br><br>// Helper function (reuse from before)<br>function isInsideBoard(row, col) {<br>  return row &gt;= 0 &amp;&amp; row &lt; 8 &amp;&amp; col &gt;= 0 &amp;&amp; col &lt; 8;<br>}</pre><h4>Queen</h4><p>The queen combines the movement abilities of both the rook and the bishop. It can move any number of cells in a straight line — diagonally, horizontally, or vertically — and continues in that direction until it encounters another piece or chooses to stop.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/1*G_DETjgN2dmZ2noi__KlrA.png" /><figcaption>Queen movements</figcaption></figure><p><em>Code —</em></p><pre>function getLegalMovesForQueen(board, row, col) {<br>  const moves = [];<br>  const piece = board[row][col];<br>  const isWhite = piece === piece.toUpperCase();<br><br>  const directions = [<br>    // Rook-like directions<br>    [1, 0], [-1, 0], [0, 1], [0, -1],<br>    // Bishop-like directions<br>    [1, 1], [1, -1], [-1, 1], [-1, -1]<br>  ];<br><br>  for (const [dr, dc] of directions) {<br>    let r = row + dr;<br>    let c = col + dc;<br><br>    while (isInsideBoard(r, c)) {<br>      const target = board[r][c];<br>      if (target === &#39;&#39;) {<br>        moves.push([r, c]);<br>      } else {<br>        const isTargetWhite = target === target.toUpperCase();<br>        if (isWhite !== isTargetWhite) {<br>          moves.push([r, c]); // capture opponent piece<br>        }<br>        break; // blocked<br>      }<br>      r += dr;<br>      c += dc;<br>    }<br>  }<br><br>  return moves;<br>}<br><br>// Helper function (reuse)<br>function isInsideBoard(row, col) {<br>  return row &gt;= 0 &amp;&amp; row &lt; 8 &amp;&amp; col &gt;= 0 &amp;&amp; col &lt; 8;<br>}</pre><p>As you can see, the queen’s moves include all straight lines — both horizontal and vertical — as well as all diagonal directions.</p><h4>King</h4><p>The king has the most restricted movement; it can move only one cell at a time in any direction — vertically, horizontally, or diagonally.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*POzCjQaPqZnCDeh2soqtrg.jpeg" /><figcaption>King moves</figcaption></figure><p><em>Code —</em></p><pre>function getLegalMovesForKing(board, row, col) {<br>  const moves = [];<br>  const piece = board[row][col];<br>  const isWhite = piece === piece.toUpperCase();<br><br>  const directions = [<br>    [1, 0], [-1, 0], [0, 1], [0, -1],     // straight<br>    [1, 1], [1, -1], [-1, 1], [-1, -1]    // diagonals<br>  ];<br><br>  for (const [dr, dc] of directions) {<br>    const r = row + dr;<br>    const c = col + dc;<br><br>    if (isInsideBoard(r, c)) {<br>      const target = board[r][c];<br>      if (target === &#39;&#39; || (isWhite !== (target === target.toUpperCase()))) {<br>        moves.push([r, c]);<br>      }<br>    }<br>  }<br><br>  return moves;<br>}<br><br>// Helper (same as before)<br>function isInsideBoard(row, col) {<br>  return row &gt;= 0 &amp;&amp; row &lt; 8 &amp;&amp; col &gt;= 0 &amp;&amp; col &lt; 8;<br>}</pre><h4><strong>Unified Movement</strong></h4><p>We have separate functions to handle the movement logic for each piece. Now, we need a common function that can handle the movement of any piece by invoking the appropriate function based on the piece type, as shown below.</p><pre>function getLegalMoves(board, row, col) {<br>  const piece = board[row][col];<br>  if (!piece) return [];<br><br>  const pieceType = piece.toLowerCase();<br><br>  switch (pieceType) {<br>    case &#39;p&#39;:<br>      return getLegalMovesForPawn(board, row, col);<br>    case &#39;r&#39;:<br>      return getLegalMovesForRook(board, row, col);<br>    case &#39;n&#39;:<br>      return getLegalMovesForKnight(board, row, col);<br>    case &#39;b&#39;:<br>      return getLegalMovesForBishop(board, row, col);<br>    case &#39;q&#39;:<br>      return getLegalMovesForQueen(board, row, col);<br>    case &#39;k&#39;:<br>      return getLegalMovesForKing(board, row, col);<br>    default:<br>      return [];<br>  }<br>}</pre><h3>Result</h3><p>We’re in a great spot now: the logic to compute all legal moves for any piece is fully integrated into the HTML file. When a cell is clicked, possible moves are highlighted, making it easy for the user to select and make a move directly on the board.</p><p><strong><em>Here is a small screen share of how it works —</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*yghLpLnyGP6F8lpznwgjUA.gif" /><figcaption>Chess recording</figcaption></figure><p>You can currently play both sides, as turn validation hasn’t been implemented yet. We’ll add that later when we develop the engine logic.</p><p>You can find all the code we have worked on so far from <a href="https://github.com/maddy1997/ChessGame/blob/main/index.html"><strong><em>here</em></strong></a>.</p><p>Find the GitHub repo for the same <a href="https://github.com/maddy1997/ChessGame"><strong><em>here</em></strong></a>.</p><p>I have also deployed the code, so you can interact with the game we have built so far <a href="https://maddy1997.github.io/ChessGame/"><strong><em>here</em></strong></a>.</p><p>If you want to try it out locally, simply clone the repo and open the index.html file in any browser, or just copy and paste the HTML code into a file on your machine.</p><p>Feel free to let me know if I missed anything, or fork the repo if you’d like to suggest improvements.</p><h4>Future Improvements</h4><p>In the upcoming parts, we’ll dive into more exciting aspects of the game, exploring game theory algorithms like minimax and alpha-beta pruning. Stay tuned for updates — until then, happy coding and see you soon!</p><p>Adding the entire code here as well for your reference.</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>&lt;head&gt;<br>  &lt;meta charset=&quot;UTF-8&quot;&gt;<br>  &lt;title&gt;Chess Board with Movable Pieces&lt;/title&gt;<br>  &lt;style&gt;<br>    body {<br>      display: flex;<br>      justify-content: center;<br>      margin-top: 50px;<br>    }<br><br>    #chessboard {<br>      display: grid;<br>      grid-template-columns: repeat(8, 60px);<br>      grid-template-rows: repeat(8, 60px);<br>      border: 2px solid black;<br>      user-select: none;<br>    }<br><br>    .cell {<br>      display: flex;<br>      align-items: center;<br>      justify-content: center;<br>      width: 60px;<br>      height: 60px;<br>      font-size: 36px;<br>      font-family: &quot;Arial&quot;, sans-serif;<br>      cursor: pointer;<br>      transition: all 0.2s ease;<br>    }<br><br>    .white {<br>      background-color: #f0d9b5;<br>    }<br><br>    .black {<br>      background-color: #b58863;<br>    }<br><br>    .white-piece {<br>      color: white;<br>      text-shadow: 1px 1px 2px black;<br>    }<br><br>    .black-piece {<br>      color: black;<br>    }<br><br>    .highlight {<br>      position: relative;<br>    }<br><br>    .highlight::after {<br>      content: &#39;&#39;;<br>      position: absolute;<br>      top: 50%;<br>      left: 50%;<br>      width: 40%;<br>      height: 40%;<br>      background-color: rgba(255, 215, 0, 0.5);<br>      border-radius: 50%;<br>      transform: translate(-50%, -50%);<br>      pointer-events: none;<br>    }<br><br>    .selected {<br>      outline: 2px solid #3399ff;<br>      box-shadow: 0 0 6px #3399ff;<br>    }<br><br>    .cell:hover {<br>      filter: brightness(1.1);<br>    }<br>  &lt;/style&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br><br>&lt;div id=&quot;chessboard&quot;&gt;&lt;/div&gt;<br><br>&lt;script&gt;<br>  const boardElement = document.getElementById(&#39;chessboard&#39;);<br><br>  const board = [<br>    [&#39;r&#39;, &#39;n&#39;, &#39;b&#39;, &#39;q&#39;, &#39;k&#39;, &#39;b&#39;, &#39;n&#39;, &#39;r&#39;],<br>    [&#39;p&#39;, &#39;p&#39;, &#39;p&#39;, &#39;p&#39;, &#39;p&#39;, &#39;p&#39;, &#39;p&#39;, &#39;p&#39;],<br>    [&#39;&#39;, &#39;&#39;, &#39;&#39;, &#39;&#39;, &#39;&#39;, &#39;&#39;, &#39;&#39;, &#39;&#39;],<br>    [&#39;&#39;, &#39;&#39;, &#39;&#39;, &#39;&#39;, &#39;&#39;, &#39;&#39;, &#39;&#39;, &#39;&#39;],<br>    [&#39;&#39;, &#39;&#39;, &#39;&#39;, &#39;&#39;, &#39;&#39;, &#39;&#39;, &#39;&#39;, &#39;&#39;],<br>    [&#39;&#39;, &#39;&#39;, &#39;&#39;, &#39;&#39;, &#39;&#39;, &#39;&#39;, &#39;&#39;, &#39;&#39;],<br>    [&#39;P&#39;, &#39;P&#39;, &#39;P&#39;, &#39;P&#39;, &#39;P&#39;, &#39;P&#39;, &#39;P&#39;, &#39;P&#39;],<br>    [&#39;R&#39;, &#39;N&#39;, &#39;B&#39;, &#39;Q&#39;, &#39;K&#39;, &#39;B&#39;, &#39;N&#39;, &#39;R&#39;]<br>  ];<br><br>  const pieceUnicode = {<br>    &#39;K&#39;: &#39;♔&#39;, &#39;Q&#39;: &#39;♕&#39;, &#39;R&#39;: &#39;♖&#39;, &#39;B&#39;: &#39;♗&#39;, &#39;N&#39;: &#39;♘&#39;, &#39;P&#39;: &#39;♙&#39;,<br>    &#39;k&#39;: &#39;♚&#39;, &#39;q&#39;: &#39;♛&#39;, &#39;r&#39;: &#39;♜&#39;, &#39;b&#39;: &#39;♝&#39;, &#39;n&#39;: &#39;♞&#39;, &#39;p&#39;: &#39;♟&#39;<br>  };<br><br>  let selectedCell = null;<br><br>  function renderBoard() {<br>    boardElement.innerHTML = &#39;&#39;;<br>    for (let i = 0; i &lt; 8; i++) {<br>      for (let j = 0; j &lt; 8; j++) {<br>        const cell = document.createElement(&#39;div&#39;);<br>        const isWhiteSquare = (i + j) % 2 === 0;<br>        cell.className = &#39;cell &#39; + (isWhiteSquare ? &#39;white&#39; : &#39;black&#39;);<br>        cell.dataset.row = i;<br>        cell.dataset.col = j;<br><br>        const piece = board[i][j];<br>        if (piece) {<br>          const span = document.createElement(&#39;span&#39;);<br>          span.textContent = pieceUnicode[piece];<br>          span.className = piece === piece.toUpperCase() ? &#39;white-piece&#39; : &#39;black-piece&#39;;<br>          cell.appendChild(span);<br>        }<br><br>        boardElement.appendChild(cell);<br>      }<br>    }<br>  }<br><br>  function isInsideBoard(row, col) {<br>    return row &gt;= 0 &amp;&amp; row &lt; 8 &amp;&amp; col &gt;= 0 &amp;&amp; col &lt; 8;<br>  }<br><br>  function isWhitePiece(piece) {<br>    return piece &amp;&amp; piece === piece.toUpperCase();<br>  }<br><br>  function isBlackPiece(piece) {<br>    return piece &amp;&amp; piece === piece.toLowerCase();<br>  }<br><br>  function getLegalMovesForPawn(board, row, col) {<br>    const moves = [];<br>    const piece = board[row][col];<br>    const isWhite = isWhitePiece(piece);<br>    const direction = isWhite ? -1 : +1;<br>    const startRow = isWhite ? 6 : 1;<br><br>    const forwardRow = row + direction;<br>    if (isInsideBoard(forwardRow, col) &amp;&amp; board[forwardRow][col] === &#39;&#39;) {<br>      moves.push([forwardRow, col]);<br><br>      const twoForwardRow = row + 2 * direction;<br>      if (row === startRow &amp;&amp; board[twoForwardRow][col] === &#39;&#39;) {<br>        moves.push([twoForwardRow, col]);<br>      }<br>    }<br><br>    for (let offset of [-1, +1]) {<br>      const diagCol = col + offset;<br>      if (isInsideBoard(forwardRow, diagCol)) {<br>        const targetPiece = board[forwardRow][diagCol];<br>        if (targetPiece &amp;&amp; ((isWhite &amp;&amp; isBlackPiece(targetPiece)) || (!isWhite &amp;&amp; isWhitePiece(targetPiece)))) {<br>          moves.push([forwardRow, diagCol]);<br>        }<br>      }<br>    }<br><br>    return moves;<br>  }<br><br>  function getLegalMovesForKnight(board, row, col) {<br>    const moves = [];<br>    const piece = board[row][col];<br>    const isWhite = isWhitePiece(piece);<br><br>    const knightMoves = [[-2, -1], [-2, 1], [-1, -2], [-1, 2], [1, -2], [1, 2], [2, -1], [2, 1]];<br>    for (const [dr, dc] of knightMoves) {<br>      const r = row + dr;<br>      const c = col + dc;<br>      if (isInsideBoard(r, c)) {<br>        const target = board[r][c];<br>        if (!target || (isWhite !== isWhitePiece(target))) {<br>          moves.push([r, c]);<br>        }<br>      }<br>    }<br>    return moves;<br>  }<br><br>  function getLegalMovesForRook(board, row, col) {<br>    const moves = [];<br>    const piece = board[row][col];<br>    const isWhite = isWhitePiece(piece);<br>    const directions = [[1, 0], [-1, 0], [0, 1], [0, -1]];<br><br>    for (const [dr, dc] of directions) {<br>      let r = row + dr;<br>      let c = col + dc;<br>      while (isInsideBoard(r, c)) {<br>        const target = board[r][c];<br>        if (target === &#39;&#39;) {<br>          moves.push([r, c]);<br>        } else {<br>          if (isWhite !== isWhitePiece(target)) {<br>            moves.push([r, c]);<br>          }<br>          break;<br>        }<br>        r += dr;<br>        c += dc;<br>      }<br>    }<br>    return moves;<br>  }<br><br>  function getLegalMovesForBishop(board, row, col) {<br>    const moves = [];<br>    const piece = board[row][col];<br>    const isWhite = isWhitePiece(piece);<br>    const directions = [[1, 1], [1, -1], [-1, 1], [-1, -1]];<br><br>    for (const [dr, dc] of directions) {<br>      let r = row + dr;<br>      let c = col + dc;<br>      while (isInsideBoard(r, c)) {<br>        const target = board[r][c];<br>        if (target === &#39;&#39;) {<br>          moves.push([r, c]);<br>        } else {<br>          if (isWhite !== isWhitePiece(target)) {<br>            moves.push([r, c]);<br>          }<br>          break;<br>        }<br>        r += dr;<br>        c += dc;<br>      }<br>    }<br>    return moves;<br>  }<br><br>  function getLegalMovesForQueen(board, row, col) {<br>    return getLegalMovesForRook(board, row, col).concat(getLegalMovesForBishop(board, row, col));<br>  }<br><br>  function getLegalMovesForKing(board, row, col) {<br>    const moves = [];<br>    const piece = board[row][col];<br>    const isWhite = isWhitePiece(piece);<br>    const directions = [[1, 0], [-1, 0], [0, 1], [0, -1], [1, 1], [1, -1], [-1, 1], [-1, -1]];<br><br>    for (const [dr, dc] of directions) {<br>      const r = row + dr;<br>      const c = col + dc;<br>      if (isInsideBoard(r, c)) {<br>        const target = board[r][c];<br>        if (!target || (isWhite !== isWhitePiece(target))) {<br>          moves.push([r, c]);<br>        }<br>      }<br>    }<br>    return moves;<br>  }<br><br>  function getLegalMoves(board, row, col) {<br>    const piece = board[row][col];<br>    if (!piece) return [];<br>    const type = piece.toLowerCase();<br><br>    switch (type) {<br>      case &#39;p&#39;: return getLegalMovesForPawn(board, row, col);<br>      case &#39;r&#39;: return getLegalMovesForRook(board, row, col);<br>      case &#39;n&#39;: return getLegalMovesForKnight(board, row, col);<br>      case &#39;b&#39;: return getLegalMovesForBishop(board, row, col);<br>      case &#39;q&#39;: return getLegalMovesForQueen(board, row, col);<br>      case &#39;k&#39;: return getLegalMovesForKing(board, row, col);<br>      default: return [];<br>    }<br>  }<br><br>  function clearHighlights() {<br>    document.querySelectorAll(&#39;.cell&#39;).forEach(cell =&gt; {<br>      cell.classList.remove(&#39;highlight&#39;);<br>      cell.classList.remove(&#39;selected&#39;);<br>    });<br>  }<br><br>  boardElement.addEventListener(&#39;click&#39;, function(event) {<br>    const cell = event.target.closest(&#39;.cell&#39;);<br>    if (!cell) return;<br><br>    const row = parseInt(cell.dataset.row);<br>    const col = parseInt(cell.dataset.col);<br><br>    if (selectedCell) {<br>      const selectedRow = parseInt(selectedCell.dataset.row);<br>      const selectedCol = parseInt(selectedCell.dataset.col);<br>      const legalMoves = getLegalMoves(board, selectedRow, selectedCol);<br><br>      const isMoveLegal = legalMoves.some(([r, c]) =&gt; r === row &amp;&amp; c === col);<br><br>      if (isMoveLegal) {<br>        board[row][col] = board[selectedRow][selectedCol];<br>        board[selectedRow][selectedCol] = &#39;&#39;;<br>        selectedCell = null;<br>        clearHighlights();<br>        renderBoard();<br>        return;<br>      }<br>    }<br><br>    const piece = board[row][col];<br>    if (piece) {<br>      selectedCell = cell;<br>      clearHighlights();<br>      cell.classList.add(&#39;selected&#39;);<br><br>      const moves = getLegalMoves(board, row, col);<br>      moves.forEach(([r, c]) =&gt; {<br>        const targetCell = document.querySelector(`.cell[data-row=&quot;${r}&quot;][data-col=&quot;${c}&quot;]`);<br>        if (targetCell) {<br>          targetCell.classList.add(&#39;highlight&#39;);<br>        }<br>      });<br>    } else {<br>      selectedCell = null;<br>      clearHighlights();<br>    }<br>  });<br><br>  renderBoard();<br>&lt;/script&gt;<br><br>&lt;/body&gt;<br>&lt;/html&gt;</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a515274a10a6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Complete Guide to LLD Interview: Part 3]]></title>
            <link>https://madhuramehendale.medium.com/complete-guide-to-lld-interview-part-3-c79a8afff2b7?source=rss-ee5efea33790------2</link>
            <guid isPermaLink="false">https://medium.com/p/c79a8afff2b7</guid>
            <category><![CDATA[lld]]></category>
            <category><![CDATA[low-level-design]]></category>
            <category><![CDATA[interview]]></category>
            <dc:creator><![CDATA[Madhura Mehendale]]></dc:creator>
            <pubDate>Sat, 22 Mar 2025 16:18:27 GMT</pubDate>
            <atom:updated>2025-03-22T16:18:27.864Z</atom:updated>
            <content:encoded><![CDATA[<p>This is the second in a series of articles on how to approach low-level design interviews. If you haven’t already, please check out part 1 <a href="https://madhuramehendale.medium.com/complete-guide-to-lld-interview-part-1-fcd9b8816407">here</a> and part 2 <a href="https://madhuramehendale.medium.com/complete-guide-to-lld-interview-part-2-7082dc57ba45">here</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/472/0*MZ1sQMqfcpdANU0y.png" /></figure><h4>Use case Diagrams</h4><p>This is usually not a required step, please clarify from the interviewer and proceed. Here you will mainly be listing the interaction a user would with the system. List all the relevant APIs for the application. Examples — In a movie booking application you might apis such — list all movies, list all seats, book a seat, cancel seat, etc. Also, define the parameters you would pass with each api. For example, in list all movies API, it would be a good idea to pass the city as it is of no use to the user to display movies playing other cities, book seat should have user information, along with screen and seat information, cancel should have the booking information, etc.</p><h4><strong>Class Diagrams</strong></h4><p>This step is quite critical. A good way to figure out all the relevant classes would be to identify all the nous from the requirements. Let&#39;s take the parking lot example and try this.</p><ol><li>There can be multiple <strong>floors</strong></li><li>Yes, there are charging <strong>slots</strong> in the system</li><li>Yes, there are separate slots for two-wheeler and four-wheeler <strong>vehicles</strong></li><li>The system needs manual intervention at <strong>entry and exit gates.</strong></li><li><strong>Pricing</strong> is based on the time, duration, and type of slot. We will discuss this in more detail later on.</li><li>Advance <strong>booking</strong> is not supported</li><li>The system is <strong>kiosk-based</strong>, which is installed at entry and exit gates</li><li>There can be multiple <strong>entry and exit gates</strong>.</li><li>Yes, when the car reaches the exit gate a <strong>bill</strong> is generated</li><li>All forms of <strong>payment</strong> are supported</li><li>There are no <strong>discount coupons</strong></li><li>Every floor can have multiple two-wheeler and four-wheeler slots</li><li>The system is valid for a single <strong>parking lot</strong>.</li><li>A <strong>preview</strong> has to be displayed, indicating the count and number of free slots available at a given time.</li><li>Yes, a <strong>token</strong> is generated at the entry gate, and it contains the slot assigned.</li></ol><p>Let&#39;s list all the nouns relevant to our design — Parking lot, Floor, Slot, Vehicle, Ticket, Bill, Slot, Entry Gate, Exit Gate, Preview.</p><p>There are some more nouns (Discount Coupong, kiosk biased, etc) that I haven’t considered as they don’t represent any data in the system.</p><p>Another way to identify the classes is to <strong><em>visualize </em></strong>the system. In the movie booking application, you can visualize the actions that take place within the app, such as when a <strong>User</strong> logs in, looks through <strong>theatres</strong>, and different <strong>shows</strong>, selects the <strong>seat, and </strong>performs the <strong>payment. </strong>To design a pen, you can visualize the Pen — The<strong> Pen </strong>has a <strong>refill</strong> which is filled with <strong>ink, </strong>and also<strong> </strong>has a<strong> cap </strong>and<strong> nib.</strong> The words marked in bold represent the nouns which form the classes in the system.</p><p>Another important way to obtain the classes would be to determine the relationship or mapping between different entities. For example, in a movie booking system, a relation between <strong>Show</strong> and <strong>Seat</strong> can form a new entity <strong>ShowSeat</strong>, which represents a seat within a given show. It is important to determine the cardinality along with the mapping. Cardinality defines how many instances of one entity can be related to how many instances of another entity.</p><p>Let us understand how to find cardinality between relations. Consider a course management system with entities — Course, Student, and Exam. Here, the student <strong>enrolls</strong> in a course is a relationship. Let’s try to find the cardinality of this relation.</p><p>Number of students that enroll in one course — many.</p><p>Number of courses a student can be enrolled in- many.</p><p>Hence this relation is m:m relation.</p><p>Consider another example- <strong>person</strong> holds a valid <strong>aadhaar card</strong>.</p><p>Number of aadhaar cards that can be held by a person — one</p><p>Number of people one aadhaar card can belong to — many.</p><p>You will have to draw a class diagram with all the classes, fields and relations. There is no need to follow 100% UML specifications, also don’t have to list helper classes, utility classes, services, etc. The class diagram should contain only classes related to the data model.</p><p>Once you identify all the classes, you also have to list all the fields related to the class and think of all the information that can be stored about this entity.For example, in the parking lot system lets try to identify the fields for a few entities-</p><p><strong>Parking lot — </strong>Id, Name, Address, List&lt;Floor&gt;, List&lt;EntryGate&gt;, List&lt;ExitGate&gt;</p><p><strong>Floor — </strong>Id, Level, List&lt;Slot&gt;, Capacity</p><p><strong>Slot — </strong>Id, SlotType, Status</p><p><strong>SlotType (ENUM) — </strong>FOUR WHEELER, TWO WHEELER, ELECTRIC CAR</p><p><strong>Status — </strong>AVAILABLE, BOOKED, MAINTENANCE</p><p><strong>VehicleType — </strong>TWO WHEELER, FOUR WHEELER, ELECTRIC CAR, LUXURY</p><p><strong>Vehicle — </strong>Registration number, VehicleType</p><p><strong>ElectricSlot — </strong>Charger</p><p><strong>Gate — </strong>Number, Operator, GateType</p><p>Adding the entire class diagram below for reference.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BPGAz1AVJmEkcYGL3m5ZHQ.png" /><figcaption>Parking lot- class diagram</figcaption></figure><p>Another optional step you can consider is to identify any design patterns that are utilized in the system. For example, in the parking lot design, there are two instances where you can use a strategy pattern — to determine the pricing and to assign the slot.</p><h4>Schema Design</h4><p>This might also be an optional step, depending on the system whether to represent schema design or class diagram but the schema design will be very close to class diagram. Some important points to note here — are normalization, primary key, and foreign key. I won’t delve deep into schema here.</p><h4>Coding</h4><p>It is okay to use any framework such as Spring, and Django in the machine coding round. Try to code all the models first. Don’t aim to cover all features. Pick features one by one and try to cover their end-to-end rather than first doing all controllers, repositories services, etc. Pick one feature and write the corresponding repository, controller, and service. No need to connect to a real database, it is sufficient to use in a memory database.</p><p>Refer this <a href="https://drive.google.com/file/d/1od2gihiINsWYTdAs5PyGw-n3AEP9O1vW/view?usp=drive_link">link</a> for the code for Parking lot Design.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c79a8afff2b7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Complete Guide to LLD Interview: Part 2]]></title>
            <link>https://madhuramehendale.medium.com/complete-guide-to-lld-interview-part-2-7082dc57ba45?source=rss-ee5efea33790------2</link>
            <guid isPermaLink="false">https://medium.com/p/7082dc57ba45</guid>
            <category><![CDATA[lld]]></category>
            <category><![CDATA[software]]></category>
            <category><![CDATA[software-interview]]></category>
            <category><![CDATA[low-level-design]]></category>
            <dc:creator><![CDATA[Madhura Mehendale]]></dc:creator>
            <pubDate>Sun, 02 Mar 2025 11:55:13 GMT</pubDate>
            <atom:updated>2025-03-02T11:55:13.279Z</atom:updated>
            <content:encoded><![CDATA[<p>This is the second in a series of articles on how to approach low-level design interviews. If you haven’t already, please check out part 1 <a href="https://madhuramehendale.medium.com/complete-guide-to-lld-interview-part-1-fcd9b8816407">here</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/472/1*VEmS_X8HCuo6oj5_UVoklQ.png" /></figure><p>In the previous article, we discussed in depth how the low-level design interviews are structured, the expectations around them, and the types of interviews you can expect. We will go over how to handle these interviews in detail in this post, which will offer a generic framework. These are the following steps in an LLD round that the candidate has to generally follow.</p><ol><li>Gathering requirements</li><li>Clarifying requirements</li><li>Use case Diagram</li><li>Class Diagrams</li><li>Schema Design</li><li>Code</li></ol><p>Let&#39;s dig deeper into each step.</p><h4>Gathering requirements</h4><p>This step is essential for understanding the scope of the question and the context in which the problem is being presented. If you are unfamiliar with the system, request an overview from the interviewer. If you already have some knowledge, summarize your understanding and ask specific questions, such as an overview of the environment or the type of application (e.g., web-based or desktop). Additionally, determine how users interact with the system — if it’s a web-based application, for instance, you may need to design API endpoints. Clarify whether the focus is solely on modeling and representing entities or if certain parts of the system need to be implemented.</p><p>You can also propose relevant features along with justifications. For example, in a game, consider asking whether difficulty levels, AI players, or player profiles should be included. In the case of a movie booking application, inquire whether it supports only movies or also extends to events like concerts and comedy shows.</p><p>Another effective approach to gathering requirements is to <strong>visualize the system</strong> — think about how a user would interact with the application and the different touchpoints in the process. Try to map out the entire flow and explain it to the interviewer. For example, if designing a Snake and Ladder game, ask whether the positions of snakes and ladders are fixed or randomly generated, or whether there is a maximum number of players allowed.</p><p>Let&#39;s take a concrete example and see how you gather requirements for a system</p><p><strong>Problem statement — Design a parking lot system</strong></p><p>Try to visualise the parking lot system, consider a use case and write out this journey. A vehicle comes into the parking lot through the entry gate (you can ask if there are multiple entry gates or a single entry gate). On entering the gate, what happens? After entering the gate, where can they go? Is a specific slot assigned to them to park, or can they park it any slot? After parking, they will exit through the exit gate and ask questions about the exit gate. How do they pay the bill at the exit gate? You can ask questions about the bill. How is the bill calculated? What are the contributing factors to the bill?</p><p>More questions-</p><ol><li>Is the parking on a single floor or multiple floors?</li><li>Are there charging amenities available for electric vehicles?</li><li>Are there separate slots for two-wheeler and four-wheeler vehicles?</li><li>Is this system fully automated, or is manual intervention required?</li><li>How does the pricing work? Is it hourly charged?</li><li>Is advance booking supported?</li><li>Is the system an app that the user who parks the vehicle can use or is it a kiosk that requires an operator at the physical parking lot?</li><li>Entry gates and exit gates- how many can be present? Single or multiple?</li><li>When a car reaches the exit gate, a bill is generated.</li><li>What forms of payment are supported? Cash, UPI, card, etc</li><li>Are there any discounts supported?</li><li>Does every floor have only one type of slot?</li><li>If the system to be built is used only for a single parking lot system and doesn’t have to know about other parking lots that is owned by the same company? The software is installed in isolation at a single parking lot and can be used to service that.</li><li>Does a preview of the available slots have to be displayed at the entry gate?</li><li>Is a token generated at the entry gate, and does the token contain the slot assigned?</li></ol><p>These are some questions that can be asked as part of requirements gathering. Be sure to ask a lot of questions so that you understand the scope of the system and exactly what it is you need to build. As a lot of the times, these questions are open-ended, and you are expected to drive the interview.</p><p>Let&#39;s quickly answer each of the questions as interviewer as we will be solving this question in its entirety in the article</p><ol><li>There can be multiple floors</li><li>Yes, there are charging slots in the system</li><li>Yes, there are separate slots for two-wheeler and four-wheeler vehicles</li><li>The system needs manual intervention at entry and exit gates.</li><li>Pricing is based on the time, duration, and type of slot. We will discuss this in more detail later on.</li><li>Advance booking is not supported</li><li>The system is kiosk-based, which is installed at entry and exit gates</li><li>There can be multiple entry and exit gates.</li><li>Yes, when the car reaches the exit gate a bill is generated</li><li>All forms of payment are supported</li><li>There are no discount coupons</li><li>Every floor can have multiple two-wheeler and four-wheeler slots</li><li>The system is valid for a single parking lot.</li><li>A preview has to be displayed, indicating the count and number of free slots available at a given time.</li><li>Yes, a token is generated at the entry gate, and it contains the slot assigned.</li></ol><p>We are done with requirements gathering; let&#39;s move onto the next step.</p><h4>Clarifying Requirements</h4><p>This step is to discuss various ways the system will behave under different circumstances and get clarity regarding the edge cases. Some examples of this can be: in a snake and ladder game, should the first move be 3 times 6 before allowing a second move? If two players end up in the same spot, what will happen? If I am at position 98 and get a four, would I win, or should I wait until I get a two? Ask questions about the current scope and future scope. For example, today, the Snake and Ladder game contains only snakes and ladders; can there be a new entity in the future such as frogs or lamps? Ask questions that impact the design of the system like class diagram, cardinality, schema, new entity, etc.</p><p>Let&#39;s apply this to our existing questions of parking lot.</p><p>You can ask the behaviour of the system under different scenarios.</p><ol><li>Can two two-wheelers park in four-wheeler slots if four-wheeler slots are filled?</li><li>If a charging point is present in a slot, will extra charges be applied?</li><li>Will the pricing strategy change in the future?</li></ol><p>Refer to the table below for the pricing strategy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/797/1*w59_Sr9xWD9W3Mf75wVsXA.png" /><figcaption>Pricing strategy</figcaption></figure><p>The pricing is a function of both the time and duration on top of the base value for two-wheelers and four-wheelers, which will be different.</p><p>Find the answers to the above questions here before going ahead.</p><ol><li>No, two-wheelers should not park in four-wheeler slots.</li><li>Yes, extra charges will apply.</li><li>Yes, the pricing strategy has to be flexible to involve other features in the future.</li></ol><p>By now, you should have a clear understanding of how to gather and clarify requirements, which are the initial steps in an LLD round. We have explored these two steps in detail, and I will be sharing another article soon to cover the remaining steps. Stay tuned!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7082dc57ba45" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Complete Guide to LLD Interview: Part 1]]></title>
            <link>https://madhuramehendale.medium.com/complete-guide-to-lld-interview-part-1-fcd9b8816407?source=rss-ee5efea33790------2</link>
            <guid isPermaLink="false">https://medium.com/p/fcd9b8816407</guid>
            <category><![CDATA[low-level-design]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[solid-design-principles]]></category>
            <category><![CDATA[design-interview]]></category>
            <dc:creator><![CDATA[Madhura Mehendale]]></dc:creator>
            <pubDate>Sat, 01 Feb 2025 14:21:12 GMT</pubDate>
            <atom:updated>2025-02-01T14:21:12.095Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OkAE7vl_aV62CyZZNJZ24g.png" /></figure><p>This is the first in a series of articles on how to approach low-level design interviews. Nowadays, such interviews are common and are conducted on top of DSA rounds as they give more insight into how a candidate can solve real-world problems and how prepared they are to contribute as soon as joining the company. In this article, let us understand a bit more about low level design and what are the expectations in such an interview.</p><h4>Low-level design: what is it?</h4><p>Low-level design contains two important parts of software development — requirements and implementation. Requirements include discussing and clarifying the requirements with various stakeholders involving product owners/managers, team members, and architects. This forms the foundation of what needs to be built and helps everyone align on the same page. The second part involves code design, the structure of code (classes, packages, methods), the relationship between classes, and how different classes interact with one another.</p><h4>Why is low-level design important?</h4><p>Low-level design is an important step in the software development cycle. This has to be done before any code implementation can start. It involves thoughts about the system in the long term and how it can be built to be extensible and maintainable. It also helps us write more readable code and helps us gain more clarity about the requirements.</p><h4>Who can expect a low-level design round?</h4><p>Startups can have an LLD round for candidates even with 0 years of experience. However, in MNCs, this will be part of interviews for someone with 2+ years of experience.</p><h4>What to know for LLD?</h4><p>To succeed in LLD, a candidate should possess a solid understanding of the following theoretical facets.</p><ol><li><strong>Object-oriented programming</strong>: Both practical and theoretical knowledge of concepts such as abstraction, polymorphism, and encapsulation, and different associations between objects such as composition.</li><li><strong>SOLID design principles</strong>: The candidate should be well-versed in SOLID design concepts, which support the maintenance of high-quality code. A useful resource for learning this is the Clean Code book. I’ll include a few additional resources at the bottom as well.</li><li><strong>Design patterns</strong>: A basic understanding of the types of design patterns and some common patterns such as strategy pattern, singleton pattern, factory pattern, etc are absolutely necessary.</li><li><strong>UML diagram (class diagrams)</strong>: The candidate should be able to represent a system in a class diagram indicating the relation between the classes. The annotations/syntax aren’t of much importance compared to the core understanding of classes and relations.</li><li><strong>Schema design (ER Diagrams)</strong>: Relational databases are represented using schema design (ER Diagrams), which resemble UML diagrams. Through a shared medium, both UML and ER diagrams assist the candidate in having a clear conversation with the interviewer while providing visual representation.</li></ol><p>To handle any LLD interview, it is imperative to have a firm grasp of the aforementioned topics. I have included resources for all the above in the references section.</p><h4>Types of LLD questions asked</h4><p>Usually, in LLD rounds you will be asked to design a real-world system. These systems can be of various types and the following are the broad classifications of the questions asked.</p><p><strong>Entity-based</strong>: These questions focus on defining entities and their relationships without requiring functional implementation. For example, you may be asked to design a <strong><em>pen</em></strong>, where the emphasis is on attributes and structure rather than behavior.</p><p><strong>Games</strong>: You will be asked to design a game, examples would be <strong><em>tictactoe, snake &amp; ladder, chess</em></strong>, etc outlining components like players, game rules, and interactions.</p><p><strong>Real-world applications: </strong>Web applications such as design a <strong><em>movie booking system, parking lot, splitwise, mailchimp, amazon</em></strong>, etc focusing on various functionalities and entity interactions.</p><p><strong>Engineering problems: </strong>You might be asked core engineering questions such as <strong><em>designing a distributed cache</em></strong>.</p><h4>Types of design rounds</h4><p>There are broadly two types of design rounds</p><h4>Abstract Round</h4><p>In non-startup tech companies, the focus is not on previous tech stacks used, so problem statements tend to be tech-agnostic. Examples include designing a pen or a parking lot. These rounds typically last an hour, and the key expectations include:</p><ul><li><strong>Requirement Gathering:</strong> Demonstrating the ability to ask relevant questions and steer the discussion effectively.</li><li><strong>Clarifying Requirements:</strong> Identifying edge cases and understanding specific functionalities.</li><li><strong>Use Case Diagram (Optional)</strong></li><li><strong>Class Diagram:</strong> Defining entities and models based on the requirements (excluding controllers, services, etc.).</li><li><strong>Schema Design:</strong> Considering cardinality, relationships, and normalization.</li></ul><p>Some companies may also require candidates to implement a class or a set of classes, usually on a Google Doc or paper. Common follow-up questions may involve handling concurrency or defining the cardinality of a relationship between entities.</p><h4>Machine Coding Round</h4><p>Startups commonly conduct machine coding rounds. These rounds present a detailed problem statement with clearly defined requirements, eliminating the need for additional clarifications or use case diagrams. The expectations include:</p><ul><li><strong>Class Diagram &amp; Schema Design</strong></li><li><strong>High-quality, Functional Code</strong> that adheres to coding principles.</li></ul><p><strong>Structure of a Machine Coding Round:</strong></p><ul><li><strong>20–30 minutes</strong>: Discussion and design.</li><li><strong>60–80 minutes</strong>: Coding implementation.</li><li><strong>20–30 minutes</strong>: Code discussion and follow-up questions.</li></ul><p>This is just an overview of how the interviews will look like. In our next blog, we will explore how to actually approach such interviews with detailed examples. Stay tuned!</p><h4>Reference material</h4><p><strong>Object Oriented Programming</strong>- Composition vs Inheritance (find the article <a href="https://www.digitalocean.com/community/tutorials/composition-vs-inheritance">here</a>)</p><p><strong>SOLID design principles</strong> — Clean Code by Robert Cecil Martin,Pablo’s SOLID Software Development (find the book <a href="https://lostechies.com/wp-content/uploads/2011/03/pablos_solid_ebook.pdf">here</a>)</p><p><strong>Design Patterns- </strong>Head First Design Patterns book, Quick review (<a href="https://refactoring.guru/design-patterns">link</a>)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fcd9b8816407" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Binary Search on Answer (Range)]]></title>
            <link>https://madhuramehendale.medium.com/binary-search-on-answer-range-f5fff2f85aa1?source=rss-ee5efea33790------2</link>
            <guid isPermaLink="false">https://medium.com/p/f5fff2f85aa1</guid>
            <category><![CDATA[koko-eating-bananas]]></category>
            <category><![CDATA[interview-preparation]]></category>
            <category><![CDATA[binary-search]]></category>
            <category><![CDATA[data-structure-algorithm]]></category>
            <category><![CDATA[data-structures]]></category>
            <dc:creator><![CDATA[Madhura Mehendale]]></dc:creator>
            <pubDate>Sun, 15 Dec 2024 15:54:22 GMT</pubDate>
            <atom:updated>2024-12-30T05:06:34.071Z</atom:updated>
            <content:encoded><![CDATA[<h3>Koko Eating Bananas</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gNMq3U5SpZoupnt6sCajhg.jpeg" /></figure><p>We are all familiar with the powerful binary search algorithm, which operates in <em>O(log n)</em> time. Today, we’ll explore a unique variation of binary search that doesn’t involve searching through an array or matrix. Instead, the search space consists of a range of values containing the answer. Such problems are a bit tricky but quite interesting. Let’s delve deeper into how to identify and solve such problems.</p><p>Let’s consider a problem to understand this concept better.</p><blockquote>Koko loves to eat bananas. There are n piles of bananas, the ith pile has piles[i] bananas. The guards have gone and will come back in h hours.</blockquote><blockquote>Koko can decide her bananas-per-hour eating speed of k. Each hour, she chooses some pile of bananas and eats k bananas from that pile. If the pile has less than k bananas, she eats all of them instead and will not eat any more bananas during this hour.</blockquote><blockquote>Koko likes to eat slowly but still wants to finish eating all the bananas before the guards return.</blockquote><blockquote>Return <em>the minimum integer</em> k <em>such that she can eat all the bananas within</em> h <em>hours</em>.</blockquote><p><strong>Example 1:</strong></p><pre>Input: piles = [3,6,7,11], h = 8<br>Output: 4</pre><p><strong>Example 2:</strong></p><pre>Input: piles = [30,11,23,4,20], h = 5<br>Output: 3</pre><p><strong>Example 3:</strong></p><pre>Input: piles = [30,11,23,4,20], h = 6<br>Output: 23</pre><p><strong>Constraints:</strong></p><ul><li>1 &lt;= piles.length &lt;= 104</li><li>piles.length &lt;= h &lt;= 109</li><li>1 &lt;= piles[i] &lt;= 109</li></ul><p>Leetcode link for the problem — <a href="https://leetcode.com/problems/koko-eating-bananas/description/">https://leetcode.com/problems/koko-eating-bananas/description/</a></p><p>The problem requires us to determine the minimum speed at which Koko should eat the bananas to finish all the piles within ‘<em>h</em>’ hours. The constraint is that she can only eat from one pile per hour, and even if she finishes a pile early, she cannot begin another within the same hour. Hence, the challenge lies in optimizing her eating speed to ensure all bananas are consumed within ‘h’ hours while keeping the speed as low as possible.</p><p>Let’s pause for a moment and consider how binary search can assist us here. Do we even have a suitable search space for applying binary search? Typically, the search space is a matrix or an array. Can we run binary search on the input array that represents the number of bananas in each pile? Does that make sense, given that the array is unsorted, and we’re not actually searching for any specific element within it? The problem asks us to determine the speed at which Koko should eat the bananas — a value that might not even be present in the array. Thus, applying binary search directly to the input array isn’t a logical approach. Take a moment to revisit the question and examples carefully to understand why searching the array itself isn’t the right path forward.</p><p>So what are our other options for a search space?</p><p>Let us put on our thinking caps here. A search space isn’t limited to arrays or matrices; binary search can be applied to any set of sorted numbers. For instance, a range of natural numbers from aaa to bbb can serve as our search space. For example, if <em>a</em>=8 and <em>b</em>=56, the search space includes all numbers from 8 to 56. We can perform a binary search on this range by treating 8 as the starting point and 56 as the endpoint.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0GfuYRgx96evtkREVE2O-w.png" /></figure><h3>Search Space</h3><p>Let’s try to identify a range that could potentially contain our answer. The goal is to determine the speed at which Koko should eat the bananas. To define this range, we need to think about the minimum and maximum possible speeds. The minimum speed Koko can have is 1, as a speed of 0 wouldn’t make sense. But is 1 a valid choice? Could there be a scenario where 1 is the correct answer? Consider this test case —</p><p><strong>Consider this test case-</strong></p><pre>Input: piles = [2,3,4], h = 10<br>Output: 1</pre><p>In the above scenario, even if Koko eats just one banana per hour, she can finish all 9 bananas within <em>h</em>=10 hours. This makes 1 the minimum possible speed needed to complete the task. Therefore, 1 can be taken as the starting point of the range.</p><p>Now, let’s consider the maximum possible speed (the end of the range). Your initial thought might be that the sum of all the bananas in the input represents the maximum speed. For example, if the speed is 9 in the scenario above, can Koko finish all the bananas in just one hour? No, she can’t. Why not? Why is it impossible for Koko to finish all 9 bananas in one hour, even if her speed is 9?</p><p>At first glance, it might seem that Koko can finish eating 9 bananas in one hour at a speed of 9. However, the constraint is that Koko can only eat from one pile per hour. Even if she finishes a pile early, she cannot move on to the next pile within the same hour and must wait until the next hour to continue.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wrFXrERylDlB3rDnQf3RLw.png" /></figure><p>In the example above, with input = [2,3,4], the maximum number of bananas Koko can eat in an hour, given she can only eat from one pile per hour, is 4. More generally, this maximum would be the largest number of bananas in a single pile. For instance, if the input is [4,5,6,7,9], Koko could eat up to 9 bananas in an hour. Thus, the maximum possible speed is 9.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JN50x_LjgNG3ZRi3kNMcEw.png" /></figure><h3>Navigating the search space</h3><p>Now that we’ve identified the range where our answer lies (from 1 to the maximum number of bananas in any pile), the next step is to define the search logic. As usual, we begin at the midpoint and decide whether to search in the left half or the right half. But how do we determine whether to move left or right in this specific problem?</p><p>Let’s assume we get ‘<em>S</em>’ as the mid-speed during our binary search. To decide whether to move left or right, we first need to check if it is possible for Koko to finish all the bananas at speed ‘<em>S</em>’ within ‘<em>h</em>’ hours. This can be validated by traversing through the array and determining if she can complete all piles under the given conditions.</p><p>For example:</p><pre>Input: piles = [3,6,7,11], h = 6</pre><p>For the given input, let’s check if it is possible to finish the bananas in 6 hours with a speed of 5.</p><p><strong>Hour 1:</strong></p><ul><li>Koko starts with the <strong>1st pile (3 bananas)</strong>.</li><li>Koko finishes the pile in 1 hour.</li><li><strong>Remaining piles:</strong> [6, 7, 11].</li></ul><p><strong>Hour 2:</strong></p><ul><li>Koko moves to the <strong>2nd pile (6 bananas)</strong>.</li><li>Koko eats 5 bananas in 1 hour.</li><li><strong>1 banana remains</strong> in the 2nd pile.</li><li><strong>Remaining piles:</strong> [1 (2nd pile), 7, 11].</li></ul><p><strong>Hour 3:</strong></p><ul><li>Koko eats the <strong>remaining 1 banana</strong> in the 2nd pile.</li><li><strong>Note:</strong> Koko cannot start a new pile in the same hour.</li><li><strong>Remaining piles:</strong> [7, 11].</li></ul><p><strong>Hour 4:</strong></p><ul><li>Koko starts on the <strong>3rd pile (7 bananas)</strong>.</li><li>Koko eats 5 bananas in 1 hour.</li><li><strong>2 bananas remain</strong> in the 3rd pile.</li><li><strong>Remaining piles:</strong> [2 (3rd pile), 11].</li></ul><p><strong>Hour 5:</strong></p><ul><li>Koko eats the <strong>remaining 2 bananas</strong> from the 3rd pile.</li><li><strong>Remaining piles:</strong> [11]</li></ul><p><strong>Hour 6:</strong></p><ul><li>Koko eats the <strong>5</strong> <strong>bananas</strong> from the 4th pile.</li><li><strong>Remaining piles:</strong> [6 (4th pile)]</li></ul><p>At the end of hour 6, if there are still 5 bananas remaining, it means Koko can’t finish all the bananas in 6 hours. Therefore, we discard all numbers from 1 to 6 in our search range and continue our search from 6 to 11, where 11 is the maximum speed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6T0muEWxD1PeePRUXY-cmg.png" /></figure><p>Let us try the same approach with 8.</p><p><strong>Hour 1:</strong></p><ul><li>Koko starts with the 1st pile (3 bananas).</li><li>Koko finishes the pile in 1 hour.</li><li>Remaining piles: [6, 7, 11].</li></ul><p><strong>Hour 2:</strong></p><ul><li>Koko moves to the 2nd pile (6 bananas).</li><li>Koko eats all 6 bananas in 1 hour.</li><li>Remaining piles: [7, 11].</li></ul><p><strong>Hour 3:</strong></p><ul><li>Koko starts with the 3rd pile (7 bananas).</li><li>Koko eats all 7 bananas in 1 hour.</li><li>Remaining piles: [11].</li></ul><p><strong>Hour 4:</strong></p><ul><li>Koko starts with the 4th pile (11 bananas).</li><li>Koko eats 8 bananas in 1 hour.</li><li>3 bananas remain in the 4th pile.</li><li>Remaining piles: [3 (4th pile)].</li></ul><p><strong>Hour 5:</strong></p><ul><li>Koko eats the remaining 3 bananas from the 4th pile in 1 hour.</li><li>Remaining piles: [].</li></ul><p>Koko can finish all the bananas in 5 hours with a speed of 8, but does that mean 8 is the answer? While 8 is a possible solution, we also need to ensure it is the smallest possible speed. If there’s a speed below 8 that allows Koko to finish all the bananas, that would be a better answer. However, now we know that we don’t need to search beyond 8, as the answer will either be 8 or lower. Therefore, our search range is now narrowed to 6 to 8.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uLsdtW4O33Y-_9Ctew-Tmg.png" /></figure><p>Let us try now with speed 6.</p><p><strong>Hour 1:</strong></p><ul><li>Koko starts with the 1st pile (3 bananas).</li><li>Koko finishes the pile in 1 hour.</li><li>Remaining piles: [6, 7, 11].</li></ul><p><strong>Hour 2:</strong></p><ul><li>Koko moves to the 2nd pile (6 bananas).</li><li>Koko eats all 6 bananas in 1 hour.</li><li>Remaining piles: [7, 11].</li></ul><p><strong>Hour 3:</strong></p><ul><li>Koko starts with the 3rd pile (7 bananas).</li><li>Koko eats 6 bananas in 1 hour.</li><li>1 banana remains in the 3rd pile.</li><li>Remaining piles: [1 (3rd pile), 11].</li></ul><p><strong>Hour 4:</strong></p><ul><li>Koko eats the remaining 1 banana from the 3rd pile in 1 hour.</li><li>Koko cannot start a new pile in the same hour.</li><li>Remaining piles: [11].</li></ul><p><strong>Hour 5:</strong></p><ul><li>Koko starts with the 4th pile (11 bananas).</li><li>Koko eats 6 bananas in 1 hour.</li><li>5 bananas remain in the 4th pile.</li><li>Remaining piles: [5 (4th pile)].</li></ul><p><strong>Hour 6:</strong></p><ul><li>Koko eats the remaining 5 bananas in the 4th pile.</li><li>Remaining piles: [].</li></ul><p>Finally, the answer is 6, as speeds below 6 don’t work (we checked with 5). We don’t need to consider any speeds above 6, since our goal is to find the minimum possible speed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mGfZbuV5R5LVhc5aeKIm-g.png" /></figure><p>I hope by now you have a clearer understanding of how to apply binary search on a range that contains potential answers. In the next section, we will explore how to identify such problems.</p><h4>Identification and Approach</h4><ol><li>Look for a range in which you can determine that the answer will lie. Identifying such a range is key to applying binary search effectively, as it helps narrow down the possible solutions and makes the search more efficient.</li><li>Determine how to check if a number within the range can be a valid answer. For instance, in our example, for each speed, we can assess whether Koko can finish all the bananas in ‘<em>h</em>’ hours. Typically, this logic operates with linear time complexity, taking <em>O(n)</em> time.</li><li>Determine how to navigate the range during binary search. What criteria will decide whether you should search in the left or right partition for the answer?</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ugirqp4FuhTscNa6cOPQog.png" /></figure><p>If you’ve identified the range, defined the search logic, and verified the conditions, you can apply the Binary Search on the range to solve the problem optimally. Such solutions usually run in <em>O(nlogn)</em> time. Please find the code for the above problem <a href="https://github.com/neetcode-gh/leetcode/blob/main/java%2F0875-koko-eating-bananas.java">here</a>.</p><h4>More examples of such problems</h4><p><a href="https://leetcode.com/problems/minimum-number-of-days-to-make-m-bouquets/description/">https://leetcode.com/problems/minimum-number-of-days-to-make-m-bouquets/description/</a></p><p><a href="https://leetcode.com/problems/capacity-to-ship-packages-within-d-days/description/">https://leetcode.com/problems/capacity-to-ship-packages-within-d-days/description/</a></p><p><a href="https://www.naukri.com/code360/problems/allocate-books_1090540?utm_source=youtube&amp;utm_medium=affiliate&amp;utm_campaign=codestudio_Striver_BinarySeries">https://www.naukri.com/code360/problems/allocate-books_1090540</a></p><p>I hope you found this article helpful. I plan to write more about data structures and algorithms, so stay tuned for future updates!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f5fff2f85aa1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What projects should you build?]]></title>
            <link>https://madhuramehendale.medium.com/what-projects-should-you-build-c070c30a1aa9?source=rss-ee5efea33790------2</link>
            <guid isPermaLink="false">https://medium.com/p/c070c30a1aa9</guid>
            <category><![CDATA[placement]]></category>
            <category><![CDATA[universit]]></category>
            <category><![CDATA[resume]]></category>
            <category><![CDATA[code]]></category>
            <category><![CDATA[projects]]></category>
            <dc:creator><![CDATA[Madhura Mehendale]]></dc:creator>
            <pubDate>Sun, 03 Nov 2024 06:56:34 GMT</pubDate>
            <atom:updated>2024-11-03T06:56:34.056Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="question mark with code in the background" src="https://cdn-images-1.medium.com/max/512/1*h1-a0KqkD-qad3uWpTjAvg.jpeg" /></figure><p>If you are a college/university student, most notably in your final year, you must be pondering this question. Since you don’t have prior experience, your projects would play a very important role in building your resume/profile. I get asked this question time and time again from many students as to what to build. So here are a few pointers to help you decide the same.</p><p>There are too many people building clones of existing apps, from video streaming to e-commerce; it would always be a positive for you to build something unique.</p><p>Although creating something original is always advantageous, it is not required of you as a student to create a completely original piece of software with significant impact. Here are a few pointers to help you decide what to build.</p><h3>Real problem</h3><p>You can build a solution to an existing real life problem you face day to day. It can be something as simple as a to-do list with features that you think will be helpful. For example, you can add a feature to make a phone call to the user for a scheduled task when the time arrives. This is just an example, but try to keep an eye on challenges you face every day and if this can be solved with simple, feasible solutions.</p><h3>Add-on feature</h3><p>In case you are building a clone project of existing apps (like Amazon, Netflix, BookMyShow, etc.), make sure you add an interesting add-on feature that is not available in the existing app. It doesn’t have to be something very complicated or ground-breaking; it just has to be something that would reflect the thoughts you have put into the project. It can be something as simple as converting images in an Amazon listing to 3D images or adding a voice note of the reviews.</p><h3>Specific Concept</h3><p>If you are passionate about a specific idea that you can build for a community or general public, it can be as simple as a library app for your college or an app that shows bus routes in your city. Such apps can even be published for public use or community use (within your university), which will give bonus points for your profile. Also, it would be a good idea to participate in as many hackathons as possible (even the ones conducted by government departments) if you are passionate about solving impactful problems.</p><h3>Utility Projects</h3><p>The simplest way to build any browser utility, such as changing fonts within a website or altering any UI aspect of a site is through browser extensions. Browser extensions are a great tool to build up functionality in a small amount of time. You can take up extension based projects initially, as they can be built quickly and will give you more practice with building stuff.</p><p>Include at least one project that offers full-stack functionality and a complete end-to-end experience, including a database, frontend, and backend APIs. Your resume will score higher as a result.</p><p>Please keep in mind that you can still build anything that interests you; the following items are merely suggestions to help you come up with creative ideas for your projects.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c070c30a1aa9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Is Java pass-by-reference or pass-by-value?]]></title>
            <link>https://madhuramehendale.medium.com/is-java-pass-by-reference-or-pass-by-value-a4619f89d63d?source=rss-ee5efea33790------2</link>
            <guid isPermaLink="false">https://medium.com/p/a4619f89d63d</guid>
            <category><![CDATA[core-java]]></category>
            <category><![CDATA[java-interview-questions]]></category>
            <category><![CDATA[pass-by-reference]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[pass-by-value]]></category>
            <dc:creator><![CDATA[Madhura Mehendale]]></dc:creator>
            <pubDate>Thu, 15 Aug 2024 17:54:16 GMT</pubDate>
            <atom:updated>2024-08-15T17:54:16.395Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Random ai generated image with animated girl and screens with code in the background." src="https://cdn-images-1.medium.com/max/1024/1*CN_IVrmdKbXJC3vG5SNAhA.png" /><figcaption>Random ai-generated image</figcaption></figure><p>Java has an interesting way of handling the passing of variables across methods. Officially, it’s considered to be pass-by-value (the reference of the variable is not passed). However, due to the way objects are handled, it might sometimes appear as though Java is using pass-by-reference.</p><p>Let’s see how Java deals with this in the case of variables vs in the case of objects through examples.</p><h4>Example 1</h4><pre>class HelloWorld {<br>    public static void main(String[] args) {<br>        int a = 10;<br>        System.out.println(&quot;A in main before update:: &quot;+a);<br>        update(a);<br>        System.out.println(&quot;A in main after update:: &quot;+a);<br>    }<br>    <br>    public static void update(int b){<br>        b= 20;<br>        System.out.println(&quot;A in update:: &quot;+b);<br>    }<br>}</pre><blockquote>Output -</blockquote><blockquote>A in main <strong>before</strong> update:: <strong>10</strong><br>A <strong>in</strong> update:: <strong>20</strong><br>A in main <strong>after</strong> update:: <strong>10</strong></blockquote><p>As you can see in the above example, the update method doesn’t in fact change the value of variable ‘<strong><em>a’ </em></strong>as it doesn’t have access to the variable ‘<strong><em>a’</em></strong> which is part of the <strong><em>main</em></strong> method. The value 10 is simply copied into the variable ‘<strong><em>b</em></strong>’ (of the <strong><em>update</em></strong> method) and its value is updated within the <strong><em>update</em></strong> method.</p><p>This is just a copy-by-value scenario.</p><h4>Example 2</h4><p>Let’s consider the example of an object.</p><pre>class HelloWorld {<br>    public static void main(String[] args) {<br>        Student student1 = new Student(&quot;John&quot;,14);<br>        System.out.println(&quot;John&#39;s age in main method before updateAge: &quot;+student1.age);<br>        updateAge(student1);<br>        System.out.println(&quot;John&#39;s age in main method after updateAge: &quot;+student1.age);<br>    }<br>    <br>    public static void updateAge(Student student2){<br>        student2.age = 20;<br>        System.out.println(&quot;John&#39;s age in udpateAge method: &quot;+s.age);<br>    }<br>}<br><br>class Student{<br>    String name;<br>    int age;<br>    <br>    public Student(String name, int age){<br>        this.name = name;<br>        this.age = age;<br>    }<br>}</pre><blockquote>Output-</blockquote><blockquote>John’s age in main method <strong>before</strong> updateAge: <strong>14</strong><br>John’s age <strong>in</strong> udpateAge method: <strong>20</strong><br>John’s age in main method <strong>after</strong> updateAge: <strong>20</strong></blockquote><p>From the above example, it’s clear that the <strong><em>updateAge</em></strong> is somehow able to modify the values within <strong><em>student1</em></strong> object which is a part of the <strong><em>main</em></strong> method. If Java is copy-by-value, how does <strong><em>updateAge</em></strong> method have access to the object <strong><em>student1</em></strong>? Are we actually passing the reference of <strong><em>student1</em></strong> to the <strong><em>updateAge</em></strong> method?</p><p>Well, I understand your confusion. The reason for the above behavior is that Java handles objects and primitive types differently. Does that mean Java is pass-by-reference for objects? Absolutely not. Let’s dig a bit deeper.</p><p>When you pass <strong><em>student1</em></strong> variable into the <strong><em>updateAge</em></strong> method, the entire <strong><em>student1</em></strong> object is not actually copied into <strong><em>student2,</em></strong> instead, a reference to the <strong><em>student1</em></strong> object is copied into the <strong><em>student2 </em></strong>variable. So technically <strong><em>student1</em></strong> and <strong><em>student2 </em></strong>point to the same location in memory. Hence, when the age variable within <strong><em>student2 </em></strong>is updated, the same change is reflected in <strong><em>student1</em></strong> as they both are pointing to the same object in memory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*INEo4CLVflGCkC2FjamLgA.png" /><figcaption>student1 and student2 are pointing to the same object</figcaption></figure><p>Does this mean <strong><em>udpateAge</em></strong> has access to the variable <strong><em>student1</em></strong> even though it’s technically passed by value? No, <strong><em>updateAge</em></strong> doesn’t have access to the variable <strong><em>student1</em></strong>, it only has access to the object that is being referenced by <strong><em>student1</em></strong>, basically the memory location to which <strong><em>student1</em></strong> is referring.</p><p>What does this mean? Let’s see another example.</p><h4>Example 3</h4><pre><br>class HelloWorld {<br>    public static void main(String[] args) {<br>        Student student1 = new Student(&quot;John&quot;,14);<br>        System.out.println(&quot;Student name and age in main before updateStudent method: &quot;+student1.name+&quot; &quot;+student1.age);<br>        updateStudent(student1);<br>        System.out.println(&quot;Student name and age in main after updateStudent method: &quot;+student1.name+&quot; &quot;+student1.age);<br>    }<br>    <br>    public static void updateStudent(Student student2){<br>        student2 = new Student(&quot;Pam&quot;,18);<br>        System.out.println(&quot;Student name and age in updateStudent method: &quot;+student2.name+&quot; &quot;+student2.age);<br>    }<br>}<br><br>class Student{<br>    String name;<br>    int age;<br>    <br>    public Student(String name, int age){<br>        this.name = name;<br>        this.age = age;<br>    }<br>}</pre><blockquote>Output-</blockquote><blockquote>Student name and age in main <strong>before</strong> updateStudent method: John 14<br>Student name and age <strong>in</strong> updateStudent method: Pam 18<br>Student name and age in main <strong>after</strong> updateStudent method: John 14</blockquote><p>What’s happening here? Even though you updated <strong><em>student2 </em></strong>in the <strong><em>updateStudent</em></strong> method so that it can point to the new object with the name Pam and age 18, the <strong><em>student1</em></strong> variable is still pointing to John, 14, why is this happening? In the previous example, we were able to update the age of the object <strong><em>student1</em></strong> was pointing to but why is it not changing here?</p><p>When you closely examine the code, you’ll notice that we’re updating the variable <strong><em>student2</em></strong> instead of modifying any properties of the <strong><em>student1</em></strong> object. The variable <strong><em>student2</em></strong> initially holds the reference (address) to the same object as <strong><em>student1</em></strong>. However, when we assign a new object to <strong><em>student2</em></strong>, we&#39;re not modifying the object itself but rather redirecting <strong><em>student2</em></strong> to point to a different object.</p><p>As a result, <strong><em>student2</em></strong> no longer references the same object as <strong><em>student1</em></strong>. This means the new object assigned to <strong><em>student2</em></strong> is not linked to <strong><em>student1</em></strong> because we don&#39;t have a direct reference to the <strong><em>student1</em></strong> variable itself—only to the object it originally pointed to. Therefore, within the <strong><em>updateStudent</em></strong> method, we can only modify the object properties of the same object that <strong><em>student1</em></strong> points to, but we cannot entirely reassign <strong><em>student1</em></strong> to a new object.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w7is9xOKoByfyX84vBcScg.png" /><figcaption>student1 and student2 are pointing to different objects</figcaption></figure><p>Thus, Java is in fact pass-by-value in two ways</p><ol><li>For the primitive type, the value of the variable itself is copied.</li><li>However, for object type, the reference to the object is being copied and not the object itself.</li></ol><p>The key point is that while you can modify the object that a reference points to, you cannot change the reference itself.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a4619f89d63d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Binary Search — A guide to partition the search space.]]></title>
            <link>https://madhuramehendale.medium.com/binary-search-a-guide-to-partition-the-search-space-17d664e15d40?source=rss-ee5efea33790------2</link>
            <guid isPermaLink="false">https://medium.com/p/17d664e15d40</guid>
            <category><![CDATA[interview-preparation]]></category>
            <category><![CDATA[data-structure-algorithm]]></category>
            <category><![CDATA[binary-search-algorithm]]></category>
            <category><![CDATA[binary-search]]></category>
            <dc:creator><![CDATA[Madhura Mehendale]]></dc:creator>
            <pubDate>Sun, 02 Jul 2023 09:53:19 GMT</pubDate>
            <atom:updated>2023-07-02T09:53:19.449Z</atom:updated>
            <content:encoded><![CDATA[<h3>Binary Search — A guide to partition the search space.</h3><figure><img alt="An image with a field of numbers 0 and 1" src="https://cdn-images-1.medium.com/max/1024/1*CTeNQ0ziRFau3UONOOHJkw.jpeg" /><figcaption>From <a href="https://gencraft.com/generate">https://gencraft.com/generate</a></figcaption></figure><p>We are all too familiar with the binary search algorithm. An optimal search on sorted data with log(n) time complexity. Yes, it seems like a dream come true. However, when it comes to solving coding questions around binary search, we do very often get stuck on defining the three most important variables involved high (also referred to as right), low (left) and mid. There are minute variations in calculating these variables and defining the base case (end of the search). In this article, we will understand how the search space and its limits vary based on the type of questions we are dealing with.</p><h4>Trivial Binary Search Implementation</h4><p>Let us first consider the standard binary search implementation which asks you to search for an element in a sorted (ascending array).</p><pre>binarySearch(arr,key){<br>  int left = 0;<br>  int right = arr.length-1;<br>  while(left&lt;=right){<br>    int mid = left + (right-left)/2;<br>    if(arr[mid] &gt; key){<br>      right = mid-1;<br>    }<br>    else if(arr[mid]&lt;key){<br>      left = mid+1;<br>    }<br>    else{<br>      return true;<br>    }<br>  }<br>  return false;<br>}</pre><p>This is the most common implementation of binary search where the ask is to find if an element exists in a sorted array.</p><p><strong>Let’s see how the solution fares in some corner cases-</strong></p><blockquote>Consider the size of the array is 1 which makes left =right=0 and mid = 0</blockquote><blockquote>a. if arr[mid] is not equal to key and greater than key, right = -1, left &lt; = right is false and loop breaks.</blockquote><blockquote>b. if arr[mid] is not equal to key and less then key , left = 1, left≤right is false and loop breaks</blockquote><blockquote>c. if arr[mid] is equal to key, return true loop breaks.</blockquote><p>We can conclude with some certainty that the above code doesn’t run into an infinite loop and the loops ends in every scenario. The mid here is set towards the left centre. However, this would still work as the mid moves either towards left or right and the search space in always split across the mid element and the search space reduces by half hence we don’t get stuck on a particular mid as we are always moving either towards left or right.</p><blockquote>There are also other ways to set mid, examples-</blockquote><blockquote>1. mid = (left+right)/2,</blockquote><blockquote>this can however run into an integer overflow with high values of right, although this equation itself is mathematically correct. If we solve the equation used in the above code <strong>(right-left)/2+left = right/2 — left/2 + 2left/2 = right/2 +left/2 = (right+left)/2</strong> which are actually the same.</blockquote><blockquote>2. mid = (right-left)/2 if right = 1, left = 1, then mid is 0. This equations is not correct.</blockquote><h3>First Variation of Binary Search</h3><p>Let’s consider another problem-</p><p><strong><em>Given an array with n elements, find the greatest element that’s less than the key.</em></strong></p><p>The above question is a small variation of the trivial binary search problem. Here, instead of finding a specific key in the array, the objective is to find a value that’s closest to the key but less than the key. Below is a possible solution for the question.</p><pre>int left = 0;<br>int right = arr.length-1;<br>while(left&lt;right){<br>  mid = (right-left)/2+left;<br>  if(arr[mid] &gt; key){<br>    right = mid-1;<br>  }<br>  else if(arr[mid] &lt;key){<br>    left = mid;<br>  }<br>}<br>return arr[left] &lt; key :arr[left] : -1;</pre><p><strong>Let’s consider the following scenario for the above code.</strong></p><blockquote>Consider left is 0 and right is 1, which makes mid = 0</blockquote><blockquote>If arr[0] is less than the <strong>key</strong> then <strong>left</strong> will again be set to 0 (which is <strong>mid</strong>), which makes <strong>left</strong> = 0, <strong>right</strong> =1 and the <strong>mid</strong> will be 0, which again makes <strong>left</strong> 0 and we are stuck in a loop. Our code looks fine, the equation to set mid is also correct, what is wrong here?</blockquote><blockquote>If you observe carefully when the value of mid is less than the <strong><em>key,</em></strong> the <strong><em>right</em></strong> always moves to the left of the <strong><em>mid</em></strong> (excluding the <strong><em>mid </em></strong>index from our search space, <strong><em>mid-1</em></strong>) since we know that <strong><em>mid</em></strong> could never be the answer.</blockquote><blockquote>However, if the value of <strong>mid</strong> is less than the <strong>key</strong>, then there are two possibilities-</blockquote><blockquote>1. First possibility being that there is another value to the right of <strong>mid</strong> which is greater than the value of <strong>mid</strong> but less than the <strong>key</strong> making it our solution. In this case, the value of mid is not actually our final answer.</blockquote><blockquote>2. The other possibility being that the current mid value is the answer hence we can’t completely discard the mid value from our search space due to which the left is maintained at mid only.</blockquote><h4>What is the fault in the logic?</h4><p>While calculating the value of <strong><em>mid, </em></strong>in case there are an even number of elements in the array the mid would always point towards the left centre.</p><blockquote><strong>Example</strong></blockquote><blockquote>If the array is <em>[1,4,5,6], </em>no element in the array divides the array into two equal parts, the centre in this case would be [4,5] which actually divides the array into two equal parts. However, we only value to be assigned to mid hence we need to choose if 4 or 5 would be the centre. In our equation <strong>(right-left)/2+left</strong>, we always choose the left centre (in this case 4) as the mid. The need to choose from 4 or 5 is inevitable, but the choice actually depends on how we are assigning left and right pointers within the loop.</blockquote><p>From the above example, it is clear that our choice of mid would always point towards the left centre. Now let us look at how we are assigning the left and right pointers.</p><blockquote>Consider another example [4,10] and the key is 8 which means our answer is actually 4. From the above logic, our code would work like this-</blockquote><blockquote>left = 0, right =0, mid = 0</blockquote><blockquote>4&lt;8, mid = left = 0</blockquote><blockquote>Steps 1 &amp; 2 execute repeatedly and we are stuck in a loop yet again!</blockquote><p>How do we escape this loop? In order to determine that we need to understand what’s the barrier that’s causing us to get stuck in the loop.</p><blockquote>If we observe carefully the left pointer always points to left centre(inclusive) and the right pointer points to left of the mid (exclusive).</blockquote><p>From the above statement, it is clear that the left pointer is causing the issue because there’s no way for the right pointer to be stuck as it always gets updated to a different value than before.</p><p><em>The problem lies in these two parts of the logic-</em></p><ol><li><em>mid = (right-left)/2+left;</em></li><li><em>left = mid;</em></li></ol><p>The above two lines are causing an infinite loop, in the first equation we set <strong><em>mid</em></strong> to <strong><em>left</em></strong> in some cases (<em>when right = left+1</em>) and set the <strong><em>left</em></strong> back to <strong><em>mid</em></strong> which is actually just re-assigning the <strong><em>left</em></strong> to itself.</p><p>The conceptual problem with the logic is we are always giving preference to the left centre which forms a barrier for the mid to move to the right centre. This is happening as both the mid equation and left equation give prominence to the <strong><em>left</em></strong> centre causing an imbalance in the way we formulate the search space.</p><blockquote>The way to fix this is to remove the imbalance (mid is towards left, left is also towards left), in order to bring balance to the above scenario we need to slightly modify our mid equation so that it points towards the right centre.</blockquote><p>In case of a conflict the mid should point to the ceiling rather than the floor post division by 2, so instead of <strong><em>(left+right)/2</em></strong> we get <strong><em>(left+right+1)/2</em></strong> the result doesn’t change in case of odd length arrays as <strong><em>(left+right)</em></strong> is even in such cases however in case of even length arrays <strong><em>(left+right) </em></strong>is odd which changes the value of <strong><em>mid</em></strong> to the next index, the result slights towards right so if <strong><em>(left+right)</em></strong> is 1, the result becomes <strong><em>(1+1)/2</em></strong> (which is <strong><em>1</em></strong>) instead of 0.</p><p>Now, the equation for mid would become <strong><em>left + (right-left+1)/2</em></strong>. So our final solution will look like this.</p><pre>int left = 0;<br>int right = arr.length-1;<br>while(left&lt;right){<br>  left = (right-left+1)/2+left;<br>  if(arr[mid] &gt; key){<br>    right = mid-1;<br>  }<br>  else if(arr[mid] &lt;key){<br>    left = mid;<br>  }<br>}<br>return arr[left] &lt; key :arr[left] : -1;</pre><p>Through the above code, we bring in some kind of balance to the logic. The mid sights towards right due to which left slights towards right and the right slights towards left removing any possibility of getting stuck in a loop.</p><h3>Another variation of Binary Search</h3><p>Consider the question.</p><p><strong><em>Given an array with n elements, find the least element that’s greater than the key.</em></strong></p><p>We can apply similar concepts as described for the first variation to conclude with the below answer</p><pre>int left = 0;<br>int right = arr.length-1;<br>while(left&lt;right){<br>  mid = (right-left)/2+left;<br>  if(arr[mid] &gt; key){<br>    right = mid;<br>  }<br>  else if(arr[mid] &lt;key){<br>    left = mid+1;<br>  }<br>}<br>return arr[left] &gt; key :arr[left] : -1;</pre><blockquote>In the above case, if <strong>left</strong> = 0, <strong>right</strong> = 1, mid will be 1, if <strong>mid</strong> is less than <strong><em>key</em></strong> , then <strong>left</strong> will be <strong>mid</strong> which is 1 and <strong>right</strong> is still 1 so we converge.</blockquote><h3>Base condition</h3><p>Another confusion in binary search is when to end the loop -</p><ol><li>while (left≤right) or</li><li>while(left&lt;right)</li></ol><p>This again depends on the problem you are solving, if the logic is just a trivial binary search (to find an element) then the first one works well (as there’s still a possibility that the left is not the key), but in cases you have to find an element closer to the key, second one will be more helpful as once left and right converge, the additional check of whether <strong><em>left</em></strong> element is actually less than or greater than key can be moved outside the loop.</p><blockquote>However if you want to keep the check inside the loop, when left = 0, right = 0, mid becomes 0, if mid value is less than key then left = mid(0) and again you will get stuck in a loop</blockquote><h3>Conclusion</h3><blockquote><strong><em>The idea is to keep updating left and right after each iteration, so that they are not stuck in an infinite loop.</em></strong></blockquote><p>Below are the points to keep in mind while designing the logic for binary search.</p><ol><li>Base case (for the while loop)</li><li>Setting the mid</li><li>Setting left and right</li></ol><p>The logic should never lead to an infinite loop. In order to be sure about this, the best way is to verify all cases of the logic with the below test cases.</p><ol><li>One element search space</li><li>Two element search space.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=17d664e15d40" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Effective Code Reviews]]></title>
            <link>https://madhuramehendale.medium.com/code-review-101-3ee58b250092?source=rss-ee5efea33790------2</link>
            <guid isPermaLink="false">https://medium.com/p/3ee58b250092</guid>
            <category><![CDATA[code-quality]]></category>
            <category><![CDATA[coding-practice]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[peer-review]]></category>
            <category><![CDATA[code-review]]></category>
            <dc:creator><![CDATA[Madhura Mehendale]]></dc:creator>
            <pubDate>Mon, 06 Feb 2023 05:31:55 GMT</pubDate>
            <atom:updated>2023-02-06T15:22:02.666Z</atom:updated>
            <content:encoded><![CDATA[<h4>10x developer</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*z3e5NLS1NWVFs-NpNF3xYg.jpeg" /><figcaption><a href="https://deepai.org/machine-learning-model/text2img">https://deepai.org/machine-learning-model/text2img</a></figcaption></figure><p>Code reviews are an essential part of the software development cycle. Code reviews should be taken seriously for a number of reasons, including code quality, functionality overview, performance issues, edge cases, exception handling, etc., even though they are not thought of as an interesting aspect of the job. t is important to treat code reviews as a team effort rather than as a battle between developers. Code reviews also help set standards across the team, and over time, serve as learning opportunities for team members, keeping everyone up to date. Code reviews essentially seem like a lower-level extension of pair programming.</p><p>Here are a few points which I have learnt from my 3 years of experience as a software engineer that can help you become a better reviewer.</p><h4>Look for obvious things</h4><p>Humans have a special capability on missing obvious errors while thinking about special use cases and scenarios. Simple things like <em>not pushing a newly added file, unused imports, unused variables, unused methods</em>, etc tend to happen a lot more than we anticipate. Things like these occur due to developers being busy focusing on a particular part of the code at a point in time, trying to make that work, and as a result losing sight of the forest for the trees. As a result, the responsibility of having multiple types of views of a code/feature falls on the reviewer as well; look for these during the first scan of the code, as they are easier to detect (due to current IDE capabilities) and won’t take long for the developer to fix.</p><h4>Code quality</h4><p>Here I have listed a few checkpoints for quality code. Although it is not an exhaustive list, it’s a good starting point to establish standards for the code to be pushed.</p><ol><li>Is the code readable? Is it reusable? Is it simple to understand? Is there code duplication?</li><li>Are methods well structured and not too long to make sense of? Are methods within a class ordered in some meaningful manner for readability?</li><li>Do method, class, and variable names make sense contextually and are they intuitive?</li><li>Is the code flexible for future enhancements, is it extensible? Is the code written against interfaces? Are SOLID principles being followed?</li><li>Are there too many unnecessary if-else statements, can the code be structured better using any low-level patterns such as strategy patterns?</li><li>Are there too many variations of a constructor? Would a builder pattern be better in this scenario?</li><li>There are many other simple things like formatting, using constants in place of string literals, and avoiding break and continue statements also contribute to code quality.</li></ol><p>Do the concepts and principles mentioned here seem unknown to you? Now would be the best time to dig deep and learn these principles, this will not only make you an excellent code reviewer but also a good software developer. You can start off your journey towards reusable, readable code through the book “Clean Code”. “Head First Design Patterns” is a good book to learn about low-level design patterns.</p><h4>Exception handling</h4><p>Many times, we only tend to notice the functional logic when it works. The happy path as they say. But it’s also important to cover failure scenarios as well. Here are a few checkpoints for the same.</p><ol><li>How are failure cases handled in the code? Are appropriate and narrow exceptions being caught?</li><li>Are the exceptions being logged in a way that would be helpful to debug at a later point? Are all the required details for debugging being logged?</li><li>How critical is this code/feature/API? What would be the impact if this fails? How can the failure be detected well before it has an impact on a large scale? Does the failure trigger appropriate alert frameworks set up in the organization?</li><li>Does a particular exception cause the overall failure of the operation or should it be possible to resume operation even after the error? Is any rollback required due to the exception?</li></ol><h4>Missing Data</h4><p>It wouldn’t be an exaggeration to say that a code base is a landmine of null/empty checks. Although a null check might seem trivial it can lead to much more serious issues down the line if skipped, and debugging this becomes a headache. As the age-old saying “prevention is better than cure”, it’s a lot more efficient to handle missing data in the code rather than getting into a rabbit hole of issues later. This is not to imply that a null check is required everywhere, it’s important to understand from a business logic point of view if there ever will be a case where a particular field will be null and if it’s a yes how it needs to be handled. It’s not suggested to add null checks everywhere without understanding the cause for the value being null and appropriate behavior in a scenario like that. In cases where you don’t expect the value to be null, it’s important to raise an alert towards this and throw an exception or fail the operation altogether in such cases. Basically, define a behavior for all kinds of cases, the behavior can also be a failure but it needs to be deliberated and decided as we don’t want any surprises in the future.</p><h4>Documentation</h4><p>This a very controversial topic as people feel that code should be self-explanatory which is true in most cases. Adding documentation to every line of code is never a good idea. However, there are situations where the code might not make sense, this could be due to specific behavior, a peculiar business logic, a caveat of the tech stack being used, etc where the code itself is not intuitive enough for the reviewer to infer any meaning out of it. It might seem out of place, unnecessary, and strange, in such cases it is a very good idea to add documentation explaining the purpose of the code. This is not only useful to the reviewer but also will help future developers who will work on the code to navigate more smoothly.</p><h4>Performance</h4><p>Another important aspect to keep in mind while reviewing code is the performance impact. Listing a couple of situations where performance could be a concern.</p><ol><li>Database queries returning large amounts of data.</li><li>Dependency on external APIs, blocking IO operations, or any other blocking APIs.</li><li>If you are developing an API, then the usage also will be an important aspect. Is the API called very frequently? In such cases caching can be a good mechanism to avoid the load of the database and improve time.</li><li>What will happen if your API is being used by multiple parallel users? Is it built to scale reasonably?</li><li>In the case of front-end development, performance issues can cause a lag or glitch in the UI which will have a huge impact on the user perception of the system.</li></ol><h4>Memory</h4><p>Memory optimizations also need to be covered as part of the review, these can be both with regards to run time memory as well as slow storage.</p><ol><li>Memory can be a concern if a huge amount of data is stored in the RAM for processing.</li><li>In cases where a file is being stored in the file system, it’s important to consider the required storage for the same and if the capacity requirement is being met.</li></ol><h4>Testing</h4><p>Code review should include looking for impact areas of the changes being made. What existing behavior/feature can be impacted due to the current change? What other persona needs to be tested? Are all scenarios covered as part of the test plan? Do you identify any missing areas of impact coverage from the code changes? It’s important to flag such observations so that the developer is made aware of these and can take further actions depending on the impact.</p><h4>Security</h4><p>Security validations need to be reviewed. Are you reading a file submitted by the user? If you are developing an API, are only the appropriate users able to access it? Are the sessions and cookies being validated? I understand these might be handled by different services/frameworks, but it’s important to have clarity regarding the behavior of the same with respect to your changes.</p><h4>Optimizations</h4><p>Look for any optimizations that can be made in the code.</p><ol><li>Does the code have duplicate queries, in which case it’s a better idea to query once and re-use the same value?</li><li>Is a particular method called several times and the method performs some IO or any blocking operations to get the result? Again, a good idea to store it in a variable and reuse it.</li><li>Are you performing unnecessary actions within a loop that only need to be performed once and can be done before or after the loop?</li></ol><h4>Functional Logic</h4><p>Functional logic is specific to the feature/requirement being developed. It’s important to validate the business logic and edge cases as a part of the code review.</p><p>Code reviews are a collaborative platform to exchange ideas, and share knowledge. It’s an opportunity for developers to utilize their expertise and learn unknown things as well. I like to live by one principle whenever I am working on anything which is to “code with caution”, I think it is a very good advice for a software developer, in the long run, to bring some amount of stability to the features being added.</p><p>Let me know in the comments what other points you look at during code reviews.</p><h4>References</h4><ol><li><em>Clean Code</em> by Robert Cecil Martin</li><li><em>Head First Design Patterns </em>by Eric Freeman, Elisabeth Robson, Bert Bates, Kathy Sierra</li><li><em>Google Java Style Guide </em><a href="https://google.github.io/styleguide/javaguide.html">here</a>.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3ee58b250092" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>