<?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 CHAYAN DATTA on Medium]]></title>
        <description><![CDATA[Stories by CHAYAN DATTA on Medium]]></description>
        <link>https://medium.com/@chayandatta?source=rss-a0df0810375c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*SEioVgqjeiP2BR8juHo7BQ.jpeg</url>
            <title>Stories by CHAYAN DATTA on Medium</title>
            <link>https://medium.com/@chayandatta?source=rss-a0df0810375c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 01:24:56 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@chayandatta/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[Demystifying Concurrency Control: Pessimistic vs Optimistic]]></title>
            <link>https://chayandatta.medium.com/demystifying-concurrency-control-pessimistic-vs-optimistic-0d76f6221c1c?source=rss-a0df0810375c------2</link>
            <guid isPermaLink="false">https://medium.com/p/0d76f6221c1c</guid>
            <category><![CDATA[scalability]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[backend]]></category>
            <dc:creator><![CDATA[CHAYAN DATTA]]></dc:creator>
            <pubDate>Sun, 28 Dec 2025 12:21:29 GMT</pubDate>
            <atom:updated>2025-12-28T12:30:15.563Z</atom:updated>
            <content:encoded><![CDATA[<p>When we move from small projects to systems that serve real users, one problem starts to show up very quickly: <br><strong>multiple users trying to update the same data at the same time.</strong> <br>This situation is known as <strong>concurrency</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y2H4UohVivUmxCGg0tuoIg.png" /><figcaption>Image generated by Gemini</figcaption></figure><p>To handle concurrency safely, databases and systems use something called <strong>Concurrency Control Mechanisms</strong>. <br>In our discussion, we broke this down into two major strategies:<br>1. <strong>Pessimistic Concurrency Control</strong><br>2. <strong>Optimistic Concurrency Control</strong></p><p>Let’s explore both in a simple, practical way.</p><h4>The Real-World Scenario</h4><p>Imagine we are building something like <strong>Yelp</strong> or <strong>Google Reviews</strong>.<br>There is a <strong>business table</strong> that stores:<br>- business_name<br>- address<br>- average_rating<br>- number_of_reviews<br>- …</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ihSTUdO-Doo0LNJw5mCYsQ.png" /><figcaption>self created diagram</figcaption></figure><p>Whenever a new review comes in, we:<br>Insert the review into a <strong>reviews table</strong><br>Update the <strong>average_rating</strong> and <strong>total_reviews</strong> in the business table.<br>Now picture two users adding reviews for the same restaurant at the same moment.</p><p>If our system does not handle concurrency well, we might accidentally lose one update or calculate the wrong average.</p><h4>Pessimistic Concurrency Control</h4><p>This approach assumes <strong>conflicts will happen</strong>. So it prevents them by using <strong>locks</strong>.<br><strong>User A:</strong> begins updating the business rating<br>&gt; The row for that restaurant is locked<br><strong>User B:</strong> second transaction must wait till the first transaction is completed<br><strong>User A:</strong> first transaction is completed (commit), the lock is released<br><strong>User B:</strong> reads updated data and starts the transaction</p><h4>Optimistic Concurrency Control</h4><p>This approach assumes <strong>conflicts are rare</strong> and lets transactions run <strong>without locking</strong>.<br><strong>User A:</strong> read data and calculate new values<br><strong>User B:</strong> read data and calculate new values<br>&gt; Before saving, each checks if the data is changed in between transaction<br>&gt; If it changed, the transaction rollback &amp; retries with updated values</p><h4>Which One Should You Choose?</h4><p>Start with <strong>Optimistic Concurrency Control</strong> because conflicts in review systems are usually rare. If the system starts to experience high write (ex. a business goes viral), monitor retry failures and <strong>adaptively switch</strong> to pessimistic locking for those hotspots.</p><p>We can use <strong>Adaptive Concurrency Control </strong>to automatically switch<br>If <strong>retry rate &gt; x %</strong>:<br>&gt; switch to <strong>pessimistic</strong> for that record<br>If retry rate drops below threshold<br>&gt; switch back to <strong>Optimistic</strong></p><p>We can build this, using:<br>- <strong>metrics</strong> (<br>retry_count [optimistic transactions retry count], <br>lock_wait_time [How long transactions are waiting for locks], <br>conflict_rate [Percentage of operations failing due to race conditions], <br>update_throughput [successful update count per second]<br>)<br>- <strong>monitoring</strong> (Grafana, AWS CloudWatch, Datadog)<br>- <strong>conditional database behavior </strong>(<br>Low conflict → Optimistic Concurrency<br>High conflict → Switch to Pessimistic<br>)<br>- <strong>feature flags</strong></p><h4>Final Takeaway:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6FdPVfZNoOGXToS1LDF1aQ.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0d76f6221c1c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How 10,000 requests per second almost killed my startup]]></title>
            <link>https://chayandatta.medium.com/how-10-000-requests-per-second-almost-killed-my-startup-185db997682e?source=rss-a0df0810375c------2</link>
            <guid isPermaLink="false">https://medium.com/p/185db997682e</guid>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[scalability]]></category>
            <dc:creator><![CDATA[CHAYAN DATTA]]></dc:creator>
            <pubDate>Fri, 26 Dec 2025 17:28:08 GMT</pubDate>
            <atom:updated>2025-12-26T17:35:02.751Z</atom:updated>
            <content:encoded><![CDATA[<p>And the strategy that finally stopped our backend from crashing</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y5uDGtlTsTQKxiv-DE16Qg.png" /><figcaption>Image generated by Gemini</figcaption></figure><p>We went live on a Tuesday.</p><p>Traffic started small.<br>Dozens of users became hundreds.<br>A tweet from a popular founder turned those hundreds into thousands.</p><p>And suddenly, it happened.</p><p><strong>10,000</strong> requests per second.<br>Our servers choked.<br>The database locked up.<br>The dashboards went dark.</p><p>And all we saw was this: <strong>429 Too Many Requests</strong></p><p>My dream startup was in flames, and the fire was our own success.<br><strong>Our problem wasn’t lack of demand.<br>Our problem was accepting every request like we had infinite capacity.</strong></p><p>In this article, I talk about the strategy that saved us and how you can use it before your app breaks.</p><p><strong>The Strategy That Saved Us:<br></strong>It’s called <strong>Rate Limiting</strong>, a simple idea that changes how a system behaves under pressure. It decides how often a user, token, or IP can hit an API within a fixed duration.</p><p>Accept some<br>Delay others<br>Reject what you can’t handle (politely)</p><p><strong>Frontend is the first line of defense.<br></strong>Your frontend can save 30–40<strong>%</strong> of unnecessary load just by being smart.</p><p><strong>Handle 429 gracefully:</strong></p><pre>&lt;script setup&gt;<br>&lt;!-- Handle 429 Gracefully --&gt;<br>const requestWithCooldown = async (url, options = {}) =&gt; {<br>  try {<br>    const res = await fetch(url, options);<br>    if (res.status === 429) {<br>      showAlert(&quot;We&#39;re handling too many requests! Please wait a moment.&quot;);<br>      return null;<br>    }<br>    return res.json();<br>  } catch (err) {<br>    console.error(err);<br>  }<br>};<br>&lt;/script&gt;</pre><p><strong>Throttle User Interactions:</strong></p><pre>&lt;script setup&gt;<br>import { ref } from &#39;vue&#39;;<br><br>const disabled = ref(false);<br><br>&lt;!-- Throttle User Interactions --&gt;<br>const throttledAction = () =&gt; {<br>  if (disabled.value) return;<br>  disabled.value = true;<br><br>  // Call your API here<br><br>  setTimeout(() =&gt; {<br>    disabled.value = false;<br>  }, 1000); // block repeated triggers<br>};<br>&lt;/script&gt;</pre><h4>Backend: The Gatekeeper</h4><p>Before scaling up your server or switching to Kubernetes, <strong>add control</strong>.<br>These immediately reduces accidental overload.</p><p><strong>Django REST Framework:</strong></p><pre># settings.py<br>REST_FRAMEWORK = {<br>    &#39;DEFAULT_THROTTLE_CLASSES&#39;: [<br>        &#39;rest_framework.throttling.UserRateThrottle&#39;,<br>        &#39;rest_framework.throttling.AnonRateThrottle&#39;,<br>    ],<br>    &#39;DEFAULT_THROTTLE_RATES&#39;: {<br>        &#39;user&#39;: &#39;10/minute&#39;,<br>        &#39;anon&#39;: &#39;5/minute&#39;,<br>    }<br>}</pre><p><strong>Fast API:</strong></p><pre>from fastapi import FastAPI<br>from slowapi import Limiter<br>from slowapi.util import get_remote_address<br><br>app = FastAPI()<br>limiter = Limiter(key_func=get_remote_address)<br><br>@app.get(&quot;/login&quot;)<br>@limiter.limit(&quot;10/minute&quot;)<br>def login():<br>    return {&quot;status&quot;: &quot;ok&quot;}</pre><p><strong>Why Redis Makes All This Actually Work<br></strong>If you scale horizontally (multiple servers), simple counters won’t work. Each instance tracks usage separately.<br>Redis solves this by acting as a <strong>shared brain</strong>:</p><pre>key: rate:ip:203.1.10.55<br>value: 8<br>expires: 60s</pre><p>This helps in:<br>- Global consistency.<br>- Instant resets.<br>- No double counting.</p><h4>Rate Limiting Models:</h4><ol><li><strong>Token Bucket:</strong> UX Friendly<br>Ideal when bursts are okay.</li></ol><p>How it works:<br>- Bucket holds tokens (capacity)<br>- Tokens refill at steady interval<br>- Each request consumes token</p><pre>[####------] → 4 tokens left</pre><p>Perfect for:<br>- Login attempts<br>- Search queries<br>- Retry buttons<br>- APIs that sometimes receive traffic spikes</p><p>2. <strong>Leaky Bucket:</strong> Stability First<br>Perfect for systems that must stay smooth.</p><p>How it works:<br>- Requests go into a queue.<br>- Processed at a fixed rate.</p><pre>⚡ ⚡ ⚡ ⚡ ⚡ ⚡ ⚡<br> ↓<br>[Queue] → → → [Slow, regular output]</pre><p>Best for:<br>- Payment pipelines<br>- High-value DB writes<br>- External billing APIs</p><p>Allow bursts, UX friendly: Token Bucket<br>Smooth traffic, high stability: Leaky Bucket<br>Production-grade system: Token Bucket + Leaky Bucket combo</p><p>Big companies already solved this problem, and they all use <strong>rate limiting</strong> in different forms:</p><p><strong>Stripe</strong>: <br>Stripe slows down incoming payment requests just a little so they can check for fraud and avoid charging the same customer multiple times if traffic spikes.</p><p><strong>Slack</strong>: <br>Slack limits how many messages an app or user can send at once. This stops bots or buggy apps from sending thousands of messages and crashing a workspace.</p><p><strong>Netflix</strong>: <br>Netflix controls how many requests hit their internal systems by using a bucket system at the network edges. This protects the services that handle video data and recommendations.</p><p><strong>Amazon</strong>:<br>During checkout, Amazon uses queues to slow down requests just enough to keep the database safe. This prevents order duplicates and errors if too many people buy at the same moment.</p><p>The fastest way to scale is not adding more servers.<br>It’s <strong>controlling the traffic you already have.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=185db997682e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is thon in Python venv]]></title>
            <link>https://chayandatta.medium.com/what-is-thon-in-python-venv-5749ecb6c06a?source=rss-a0df0810375c------2</link>
            <guid isPermaLink="false">https://medium.com/p/5749ecb6c06a</guid>
            <category><![CDATA[python3]]></category>
            <category><![CDATA[cpython]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[python-programming]]></category>
            <dc:creator><![CDATA[CHAYAN DATTA]]></dc:creator>
            <pubDate>Sat, 08 Nov 2025 10:03:07 GMT</pubDate>
            <atom:updated>2025-11-08T10:03:07.929Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*FiIX-6Wnjja1go7MFOpveg.png" /></figure><p>The executable named <strong>πthon</strong> found within a Python virtual environment (venv) is an Easter egg (<a href="https://github.com/python/cpython/pull/125035">https://github.com/python/cpython/pull/125035</a>).</p><p>The <strong>𝜋thon</strong> executable works exactly the same as python, python3 and python3.14</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XlG8mmaz3t7cDHQ6jxOFiA.png" /></figure><p>for this to work, you have to first activate the venv first</p><pre>source .venv/bin/activate</pre><p>then inside the activated virtual environment run 𝜋thon and you should see the same REPL as you should have seen when running python or python3</p><p>The name <strong>πthon</strong> is a pun on <strong>Python</strong> and <strong>π</strong> (<strong>Pi</strong>), <br>&gt; Python<br>&gt; Py + thon<br>&gt; Pi + thon<br>&gt; 𝜋 + thon<br>&gt; 𝜋thon<br>referencing the mathematical constant’s initial decimal digits: 3.14.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5749ecb6c06a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Efficient In-Memory Merge: Merging Two Sorted Arrays for Optimal Performance]]></title>
            <link>https://chayandatta.medium.com/efficient-in-memory-merge-merging-two-sorted-arrays-for-optimal-performance-da5fe0262271?source=rss-a0df0810375c------2</link>
            <guid isPermaLink="false">https://medium.com/p/da5fe0262271</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[CHAYAN DATTA]]></dc:creator>
            <pubDate>Fri, 22 Dec 2023 04:51:35 GMT</pubDate>
            <atom:updated>2023-12-22T04:52:24.592Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*p1gyf6QbbRqkVJ2W" /><figcaption>Photo by <a href="https://unsplash.com/@wherearemyshoesdude?utm_source=medium&amp;utm_medium=referral">M. R.</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>You are given two integer arrays nums1 and nums2, sorted in <strong>increasing order</strong>, and two integers m and n, representing the number of elements in nums1 and nums2 respectively.</p><p><strong>Merge</strong> nums1 and nums2 into a single array sorted in <strong>non-decreasing order</strong>.</p><p>The final sorted array should not be returned by the function, but instead be <em>stored inside the array </em>nums1. To accommodate this, nums1 has a length of m + n, where the first m elements denote the elements that should be merged, and the last n elements are set to 0 and should be ignored. nums2 has a length of n.</p><p><strong>Python solution :</strong></p><pre>class Solution:<br>    def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -&gt; None:<br>        while m and n:<br>            if nums1[m-1] &gt;= nums2[n-1]:<br>                nums1[m+n-1] = nums1[m-1]<br>                m -= 1<br>            else:<br>                nums1[m+n-1] = nums2[n-1]<br>                n -= 1<br>        if n &gt; 0:<br>            nums1[:n] = nums2[:n]</pre><p>Examine the last valid elements in nums1 and nums2. Transfer the larger one of the two elements to the very end of nums1.</p><p>If there are no more elements in the nums2 to copy, the process is complete.</p><p>If there are no more elements in nums1 to copy, perform a block copy of the remaining elements from nums2 to nums1.</p><p><strong>Golang solution:</strong></p><pre>func merge(nums1 []int, m int, nums2 []int, n int)  {<br>    i, j, k := m-1, n-1, m+n-1<br><br> for i &gt;= 0 &amp;&amp; j &gt;= 0 {<br>  if nums1[i] &gt;= nums2[j] {<br>   nums1[k] = nums1[i]<br>   i--<br>  } else {<br>   nums1[k] = nums2[j]<br>   j--<br>  }<br>  k--<br> }<br><br> for j &gt;= 0 {<br>  nums1[k] = nums2[j]<br>  j--<br>  k--<br> }<br>}</pre><p><strong>Rust solution :</strong></p><pre>impl Solution {<br>    pub fn merge(nums1: &amp;mut Vec&lt;i32&gt;, m: i32, nums2: &amp;mut Vec&lt;i32&gt;, n: i32) {<br>        let (mut m, mut n) = (m as usize, n as usize);<br><br>        while m &gt; 0 &amp;&amp; n &gt; 0 {<br>            if nums1[m - 1] &gt;= nums2[n - 1] {<br>                nums1[m + n - 1] = nums1[m - 1];<br>                m -= 1;<br>            } else {<br>                nums1[m + n - 1] = nums2[n - 1];<br>                n -= 1;<br>            }<br>        }<br><br>        if n &gt; 0 {<br>            nums1[..n].copy_from_slice(&amp;nums2[..n]);<br>        }<br>    }<br>}</pre><blockquote>Keyword <em>usize</em> is an unsigned integer type that represents the size of a pointer. Its size is platform-dependent and is typically either 32 or 64 bits, corresponding to the bit width of the memory addresses on the target system.</blockquote><blockquote>Keyword <em>mut</em> is short for &quot;mutable.&quot; It is used to declare a variable as mutable, meaning that its value can be changed after it is initially assigned. In Rust, variables are immutable by default, which means you cannot modify their values once they are assigned.</blockquote><blockquote><em>nums1[..n]</em> is a slice that includes the elements from index 0 to <em>n-1</em> (exclusive) of the vector <em>nums1</em> . The method <em>copy_from_slice</em> is then used to copy the elements from the second slice (<em>&amp;nums2[..n]</em>) to the first slice (<em>nums1[..n]</em>). This method performs a memory copy from the source slice to the destination slice, ensuring that the destination slice has enough space to accommodate the elements from the source slice. So this is essentially copying the first <em>n</em> elements from <em>nums2</em> to the beginning of <em>nums1</em>.</blockquote><blockquote>Time complexity: O(n)</blockquote><blockquote>Space complexity: O(1)</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=da5fe0262271" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[HTTP Noir: The Dark Art of Smuggling Bytes]]></title>
            <link>https://chayandatta.medium.com/http-noir-the-dark-art-of-smuggling-bytes-a471a0f990f5?source=rss-a0df0810375c------2</link>
            <guid isPermaLink="false">https://medium.com/p/a471a0f990f5</guid>
            <category><![CDATA[security]]></category>
            <category><![CDATA[http-request-smuggling]]></category>
            <category><![CDATA[hacking]]></category>
            <category><![CDATA[bug-bounty]]></category>
            <category><![CDATA[network]]></category>
            <dc:creator><![CDATA[CHAYAN DATTA]]></dc:creator>
            <pubDate>Sat, 09 Dec 2023 22:06:55 GMT</pubDate>
            <atom:updated>2023-12-09T22:06:55.593Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Oiapuayq8hrMyUps" /><figcaption>Photo by <a href="https://unsplash.com/@ybhrdwj?utm_source=medium&amp;utm_medium=referral">Yash Bhardwaj</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>This is a story about HTTP smuggling and how it is considered bad because it represents a security vulnerability that can be exploited by attackers to bring down the normal functionality of web applications, bypass security mechanisms, and potentially gain unauthorized access to sensitive information.</p><p><strong>What is HTTP?</strong> : HTTP stands for Hypertext Transfer Protocol, and it is a fundamental protocol used for communication on the internet, enabling the transfer of various types of data such as text, images, videos, etc. It is an application layer protocol within the TCP/IP model.</p><p>Notes about HTTP:</p><ul><li>HTTP is considered stateless, meaning each request from a client to a server is independent. Server does not remember info about the previous requests from (even) the same client.</li><li>HTTPS (Hypertext Transfer Protocol Secure) is an extension of HTTP that uses encryption (TLS/SSL) to secure the data which hides data like username, password when we log in to web apps.</li></ul><p><strong>What is application layer?</strong> : Application layer is the top layer of the Transmission Control Protocol/Internet Protocol (TCP/IP), which is a conceptual framework that standardizes the protocols used for communication over the internet. It consists of four layers: Network, Internet, Transport, and Application.</p><figure><img alt="TCP/IP" src="https://cdn-images-1.medium.com/max/465/1*x_PSmpKy8-NJk2tfQck-tQ.png" /><figcaption>TCP/IP four layer model</figcaption></figure><p><strong>What is TLS/SSL?</strong> : TLS (Transport Layer Security) and SSL (Secure Sockets Layer) are cryptographic protocols designed to provide secure communication over a computer network, such as the internet, which is used to hide our username and passwords and other sensitive information through the internet.</p><p>Most instances of HTTP request smuggling vulnerabilities starts from the HTTP/1 specification, which offers two methods for specifying the end of a request: the Content-Length header and the Transfer-Encoding header.</p><p>Content-Length header indicates the length of the message body in bytes, while theTransfer-Encoding header signals the use of chunked encoding, Which means the message body consists of one or more data chunks. Each chunk includes in the bytes size (expressed in hexadecimal) followed by a newline and the chunk contents.</p><p>There are 3 main ways to exploit HTTP request smuggling vulnerabilities:</p><ol><li><strong>CL.TE:</strong> attacker manipulates the Content-Length header of the front-end server and Transfer-Encoding header of the back-end server.</li><li><strong>TE.CL:</strong> attacker manipulates the Transfer-Encoding header of the front-end server and Content-Length header of the back-end server.</li><li><strong>TE.TE:</strong> attacker manipulates the Transfer-Encoding header twice in succession. The attacker exploits the system&#39;s interpretation of consecutive Transfer-Encoding headers, potentially causing confusion or mishandling of the request.</li></ol><p>CL = Content Length<br>TE = Transfer Encoding</p><pre>HTTP/1.1 -&gt; One TCP connection per HTTP req res cycle<br>If we want to get 100 photos, it used to call 100 requests for each photos<br><br>HTTP/2 -&gt; persistent call, It passes &quot;connection: Keep-alive&quot; as an header <br>which will be one req for 100 photos<br>But if we don&#39;t want that then we need to pass &quot;connection: close&quot; as an header</pre><p>Let’s understand this by using burp suite and intercepting requests.</p><h3><strong>CL.TE</strong></h3><p>In this example, the front-end server uses the Content-Length header and doesn’t support Transfer-Encoding, but the backend understands it, we intercept a request like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/903/1*f_DRHbhHGvKl0UklxOqbFg.png" /></figure><p>and then put it into repeater and change the request like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/974/1*p0qLDiw08zoQr-cSJKPpcw.png" /></figure><p>The server understands Transfer-Encoding which takes the body as chunked encoding, it processes the first chunk which has 0 in it and the server treats it as 0 length and terminates the request, leftover G is unprocessed and treated as the start of next request.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/971/1*hAWFqwXkyhO3kqun2M6E4g.png" /></figure><p>But on the second time, the G will get appended before POST, and the server will get a GPOST as method.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/488/1*yjs_kZJuq45MYO_wLbSI6w.png" /><figcaption>CL.TE</figcaption></figure><h3>TE.CL</h3><p>Here, the front-end server uses the Transfer-Encoding header and the back-end server uses the Content-Length header. We will perform a simple HTTP request smuggling attack.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/1*05we7gN4QlfR7949s_AyJg.png" /></figure><p>We intercept the request and send it to repeater, and change it like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/484/1*w4K3aJmI4MH-Q9hiO3848A.png" /></figure><p>The 5c is the hexadecimal of 92 which is the total value of the rest of the request body.</p><p>The server is sending Transfer-Encoding which we are passing as chunked and setting Content-length as 4. After the text Transfer-Encoding: chunked the server will see \r\n 2 times → 2 bytes and then 5c → 2 more bytes, which totals as 4 bytes, same as the mentioned Content-length and it ends the request and treats the rest as a separate request.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IGw7hfRiC9-6eZIEspuUFQ.png" /></figure><p>In this example the server understands Content-length so it will stop till 5c as it’ll match the exact Content-length passed and on the next request it’ll start from the GPOST.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h5VU1QqsoXkopD_9XQ-58w.png" /></figure><h3>TE.TE</h3><p>Here, the front-end and back-end servers both supports the Transfer-Encoding header.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OSQLCXlevg56e_9rRijRzA.png" /></figure><p>On the first request the server will accept Transfer-Encoding : chunked but on the second request the Transfer-Encoding is passed with some unknown element (here: HelloWorld) and this obfuscates Transfer-Encoding and the server switches to Content-Length here, and we make this exactly like a TE.CL experiment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aYJ0PLmh7JJyfU91bEaKRg.png" /></figure><h3>Mitigating HTTP smuggling Vulnerability:</h3><p>1. <strong>Update and Patch:</strong><br>Ensure that the web server, application server, and any intermediary devices are using the latest versions and have all security patches applied. Vendor updates often include security fixes, so staying up-to-date is crucial.</p><p>2. <strong>Security Headers:</strong><br>Implement security headers in the web application to enhance security. Headers like <em>Content-Length</em>, <em>Transfer-Encoding</em>, and <em>Connection</em> should be set explicitly to avoid ambiguity. Use the <strong>Content-Security-Policy</strong> header to control the resources that can be loaded.</p><p>3. <strong>Web Application Firewall (WAF):</strong><br>Implement a WAF that is configured to detect and block HTTP smuggling attacks. Latest WAFs often have rules specifically designed to identify and prevent various types of web attacks, including HTTP smuggling.</p><p>4. <strong>HTTP/2 Adoption:</strong><br>Consider updating to HTTP/2, which has a more robust framing mechanism than HTTP/1.1, making it less susceptible to some HTTP smuggling techniques.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a471a0f990f5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Learn Julia Basics: part-1]]></title>
            <link>https://blog.devgenius.io/learn-julia-basics-part-1-f3ab3dfa3b88?source=rss-a0df0810375c------2</link>
            <guid isPermaLink="false">https://medium.com/p/f3ab3dfa3b88</guid>
            <category><![CDATA[programming-languages]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[julia]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[tutorial]]></category>
            <dc:creator><![CDATA[CHAYAN DATTA]]></dc:creator>
            <pubDate>Sat, 19 Aug 2023 15:11:26 GMT</pubDate>
            <atom:updated>2023-08-21T09:17:06.839Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*C2ZliRe7vQmmKcUa" /><figcaption>Photo by <a href="https://unsplash.com/@huchenme?utm_source=medium&amp;utm_medium=referral">Hu Chen</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Who created Julia?</h3><p>Julia was originally released in 2012 by Alan Edelman, Stefan Karpinski, Jeff Bezanson, and Viral Shah.</p><h3>Why Julia was created?</h3><p>Julia addresses the “two-language problem” by providing a high-level and fast language that allows researchers to use a single language for both prototyping and production-level code, eliminating the need for a separate, lower-level language for computationally intensive tasks. Easy as Python and fast as C.</p><h3>Why the name?</h3><blockquote><em>That’s everybody’s favorite question. There’s no good reason, really. It just seemed like a pretty name. — Stefan Karpinski</em></blockquote><p>Fun fact: The julia extension actually used to be .j, later they changed it into .jl</p><h3>Printing in Julia:</h3><ol><li>Using the print() function to print a string or any other data type to the console.</li></ol><pre>julia&gt; print(&quot;without new line&quot;)<br>without new line<br>julia&gt;</pre><p>2. Using the println() function to print a string or any other data type to the console and append a newline character (\n) at the end.</p><pre>julia&gt; println(&quot;with new line&quot;)<br>with new line<br><br>julia&gt;</pre><p>3. Using the printf() function to print formatted output to the console, similar to C&#39;s printf function.</p><pre>julia&gt; using Printf<br>julia&gt; @printf &quot;to format the printed string, like this:  %i, %s&quot; 100 &quot;👍&quot;<br>to format the printed string, like this:  100, 👍<br>julia&gt;</pre><p>Also, @sprintf(&quot;%Fmt&quot;, args...) Return <a href="https://docs.julialang.org/en/v1/stdlib/Printf/#Printf.@printf">@printf</a> formatted output as string.</p><pre>julia&gt; @sprintf &quot;this is a %s %15.1f&quot; &quot;test&quot; 34.567<br>&quot;this is a test            34.6&quot;</pre><ul><li>The 15 specifies the total width of the printed field, including padding or signs, ensuring a minimum of 15 characters in the resulting string, including decimal point and leading spaces or signs.</li><li>The .1 specifies the floating-point number&#39;s precision for digits to the right of the decimal point. Here, it&#39;s 1, resulting in one digit to the right of the decimal point.</li></ul><p>4. Using the @show macro to print both the expression and its result, similar to Python&#39;s print() function with the repr option enabled.</p><pre>julia&gt; @show(&quot;@show macro Shows expression and result, returns final result value.&quot;)<br>&quot;@show macro Shows expression and result, returns final result value.&quot; = &quot;@show macro Shows expression and result, returns final result value.&quot;<br>&quot;@show macro Shows expression and result, returns final result value.&quot;<br><br>julia&gt;</pre><h3>Variables:</h3><pre>julia&gt; x = 10<br><br>julia&gt; typeof(x)<br>Int64</pre><p>Variable names must begin with a letter (A-Z or a-z), underscore, or a subset of Unicode code points greater than 00A0 also emojis are acceptable variable name.</p><h3>Ternary operation:</h3><p>a ? b : c, Instead of using if else we can use ternary operator, where a is the condition, if the condition is true then it evaluates b and if it is false then it evaluates c.</p><pre>julia&gt; println(10 &gt; 19 ? &quot;10 is greater than 19&quot; : &quot;10 is not greater than 19&quot;)<br>10 is not greater than 19</pre><h3>Arithmetic Operations:</h3><pre># Division<br>julia&gt; 10 / 15<br>0.6666666666666666</pre><pre># Fractions<br>julia&gt; 10 // 15<br>2//3<br># integer division, truncated to an integer<br>julia&gt; 10 ÷ 15<br>0<br>julia&gt; 15 ÷ 10<br>1</pre><pre># Inverse division<br>julia&gt; 10 \ 3<br>0.3</pre><pre># Modulus or Remainder<br>julia&gt; 11 % 4<br>3</pre><h3>Bitwise Operations:</h3><h4>Bitwise NOT ( ~ ):</h4><p>To calculate bitwise NOT (negation), think of <strong>~i=-i-1</strong></p><pre>julia&gt; x = 11<br>11</pre><pre>julia&gt; ~x<br>-12</pre><h4>Bitwise AND Operator ( <strong>&amp; </strong>):</h4><pre># Bitwise AND<br>julia&gt; 5 &amp; 3<br>1</pre><h4>Bitwise Inclusive OR ( | ):</h4><pre>julia&gt; 10 | 12<br>14</pre><pre>  1010<br>  1100<br>-------<br>  1110</pre><p>10 = 1010 and 12 = 1110 in binary.</p><p>1010 | 1100 = 1110, result: 1100 which is 14 in decimal.</p><h4>Bitwise Exclusive OR ( ⊻ ):</h4><pre>julia&gt; 10 ⊻ 12<br>6</pre><p>To show ⊻ symbol, in REPL do \xor and press the tab, it&#39;ll convert into ⊻ symbol.</p><pre>  1010<br>  1100<br>-------<br>  0110</pre><p>10 = 1010 and 12 = 1110 in binary. 1010 ⊻ 1100 = 0110 in binary, which is 6 in decimal.</p><h4>Logical Shift Right ( &gt;&gt;&gt; ):</h4><p>214 = 11010110 in binary, if we perform a logical shift right by 2 positions, then it&#39;ll be 00110101 = 53 in decimal, the bits have been shifted two positions to the right, and zeros have been inserted from the left.</p><pre>julia&gt; 214 &gt;&gt;&gt; 2<br>53</pre><h4>Arithmetic Shift Right ( &gt;&gt; ):</h4><pre>julia&gt; -42 &gt;&gt; 2<br>-11</pre><pre>value = -42  # Binary: 11111111_11111111_11111111_11010110 <br>             #(assuming 32-bit two&#39;s complement representation)<br>shifted_value = value &gt;&gt; 2  # Arithmetic shift right by 2 positions<br>println(shifted_value)  # Output: -11 <br>             #(Binary: 11111111_11111111_11111111_11110101)</pre><h4>Arithmetic Shift Left ( &lt;&lt; ):</h4><pre>julia&gt; -42 &lt;&lt; 2<br>-168</pre><pre>value = -42  # Binary: 11111111_11111111_11111111_11010110 <br>             #(assuming 32-bit two&#39;s complement representation)<br>shifted_value = value &lt;&lt; 2  # Arithmetic shift left by 2 positions<br>println(shifted_value)  # Output: -168 <br>                        # (Binary: 11111111_11111111_11111111_10110000)</pre><h3>For Loop:</h3><p>A “for loop” is a control flow structure that allows us to execute a block of code repeatedly for a specified number of times or over a sequence of values. For loops are particularly useful when we know in advance how many times we want to repeat a certain operation.</p><p>&gt; Different ways to make a for loop:</p><pre>julia&gt; arr = [1, 4, 5, 3]<br>4-element Vector{Int64}:<br> 1<br> 4<br> 5<br> 3</pre><pre>julia&gt; for i in arr<br>           println(i)<br>       end<br>1<br>4<br>5<br>3</pre><pre>julia&gt; for n in 1:3<br>           println(n)<br>       end<br>1<br>2<br>3</pre><pre>julia&gt; for i ∈ 1:4<br>           println(i)<br>       end<br>1<br>2<br>3<br>4</pre><h3>While Loop:</h3><p>It’s important to ensure that the condition within a while loop eventually becomes false; otherwise, the loop will run indefinitely, resulting in what is commonly referred to as an “infinite loop.” Infinite loops can lead to a program becoming unresponsive or crashing, so it’s crucial to design the loop conditions carefully.</p><pre>julia&gt; n = 0<br>0<br><br>julia&gt; while n &lt; 3<br>           n += 1<br>           println(n)<br>       end<br>1<br>2<br>3</pre><p>While loops are particularly useful when we need to repeat a block of code based on a condition that isn’t directly related to iterating over a range of values.</p><h3>Control statement:</h3><p>break, continue and zip function:</p><p>break control statement is used to break out of a loop of switch statement,</p><p>continue is also a control statement which is used to skip the current iteration of a loop and move to the next one.</p><p>zip function is used to combine two or more iterable (lists, tuples, array) into a single iterable tuples, where ith tuple contains the ith element from each of the input iterable.</p><pre>julia&gt; for i in 1:100<br>           println(i)<br>           if i == 5<br>               break<br>           end<br>       end<br>1<br>2<br>3<br>4<br>5</pre><pre>julia&gt; for i = 1:10<br>          if i % 3 != 0<br>              continue<br>          end<br>          println(i)<br>       end<br>3<br>6<br>9</pre><pre>julia&gt; for (j, k) in zip([1 2 3], [4 5 6 7])<br>          println((j,k))<br>       end<br>(1, 4)<br>(2, 5)<br>(3, 6)<br>julia&gt;</pre><pre>julia&gt; for (j, k) in zip([1 2 3], [4 5 6 7])<br>          println((j,k))<br>       end<br>(1, 4)<br>(2, 5)<br>(3, 6)<br><br>julia&gt;</pre><pre># This is a single line comment<br><br>#=<br>This is a multiline comment<br>=#</pre><p>While comments are incredibly helpful, it’s also important to write code that is self-explanatory and well-structured. Overusing comments or writing unclear code with the expectation that comments will fix it can lead to confusion and maintenance challenges down the line.</p><h3>String Interpolation:</h3><p>String interpolation is a programming concept that allows us to embed variables or expressions within a string</p><pre>julia&gt; a = 3<br>7<br><br>julia&gt; b = 5<br>5<br><br>julia&gt; str = &quot;a is $a. b is $b. a*b is $(a*b)&quot;;<br><br>julia&gt; println(str)<br>a is 3. b is 5. a*b is 15</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f3ab3dfa3b88" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/learn-julia-basics-part-1-f3ab3dfa3b88">Learn Julia Basics: part-1</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unlocking Productivity with Git Worktree: A Guide to Parallel Development]]></title>
            <link>https://chayandatta.medium.com/unlocking-productivity-with-git-worktree-a-guide-to-parallel-development-43f4b08bb9d5?source=rss-a0df0810375c------2</link>
            <guid isPermaLink="false">https://medium.com/p/43f4b08bb9d5</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[productivity]]></category>
            <category><![CDATA[git]]></category>
            <category><![CDATA[vim]]></category>
            <dc:creator><![CDATA[CHAYAN DATTA]]></dc:creator>
            <pubDate>Sat, 01 Jul 2023 12:35:15 GMT</pubDate>
            <atom:updated>2023-07-01T12:35:15.219Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XSSiQlJPsJMc590y" /><figcaption>Photo by <a href="https://unsplash.com/@yancymin?utm_source=medium&amp;utm_medium=referral">Yancy Min</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>What is git work tree?</h3><p>Git work tree is a feature of Git, which allows you to have multiple working trees associated with a single Git repository. A working tree is a directory on your file system that contains a checkout of a specific branch or commit from a Git repository. By using work trees, you can have multiple instances of your repository’s working directory, each pointing to different branches or commits, without needing to clone the entire repository multiple times.</p><p><strong>What does it mean?</strong> It means that if you are working on a Git branch of a project, and you have uncommitted changes, and suddenly you need to fix a bug 🐞, let’s say a production bug 🤯, what should you do? You could stash all your changes, switch to the other branch where you need to fix the bug, and then switch back to the previous branch and apply the stash. Alternatively, you could make a commit with incomplete work and hope that someone, or even yourself, will squash all the commits during the merge.</p><p>What if I tell you there is a better way</p><h3>Here comes the Git Work Tree</h3><p>Work trees are useful in various scenarios, such as:</p><ol><li>Working on multiple branches simultaneously: You can create multiple work trees, each associated with a different branch, allowing you to switch between branches quickly and easily. This can be helpful when you need to work on different features or bug fixes concurrently.</li><li>Isolating experimental changes: Work trees provide a convenient way to isolate experimental changes or work in progress without affecting the main working tree. You can create a separate work tree, make changes, test them, and discard the work tree when you no longer need it.</li><li>Building and testing different versions: If you need to build and test different versions or releases of your project, you can create work trees for each version and easily switch between them.</li></ol><h3>Let’s get started</h3><pre>git clone --bare &lt;repo url without the .git part&gt;</pre><p>remember to use the <strong>--bare</strong></p><p>once you clone the repo, change the directory</p><pre>cd &lt;your-repo-name&gt;.git</pre><p>now create a work tree: remember, the work tree name here is similar to branch name</p><pre>git worktree add main</pre><blockquote>Preparing worktree (new branch ‘main’)<br>HEAD is now at 7e767c1 &lt;commit message&gt;</blockquote><p>to check the status of this work tree branch</p><pre>git status @</pre><p>Now let’s create another work tree</p><pre>git worktree add non-main</pre><blockquote>Preparing worktree (new branch ‘non-main’)<br>HEAD is now at 7e767c1 &lt;commit-message&gt;</blockquote><p>now change directory to which ever work tree you want to work on</p><pre>cd main</pre><p>That’s it, you are done: whenever you want to change to non-main branch even if you have uncommitted files, it will not complain.</p><p>Just change the directory</p><pre>cd non-main</pre><p>and Voilà! , you are in the non-main branch</p><p>To see the list of git work trees</p><pre>/Users/chayan/&lt;repo&gt;.git            (bare)<br>/Users/chayan/&lt;repo&gt;.git/dev        7e767c1 [dev]<br>/Users/chayan/&lt;repo&gt;.git/main       7e767c1 [main]<br>/Users/chayan/&lt;repo&gt;.git/non-main   1f80297 [non-main]</pre><p>To remove one git work tree</p><pre>git worktree remove &lt;branch&gt;</pre><p>If you use <strong>Neovim</strong>, then there’s a great plugin available it which will make your life super easy, <a href="https://github.com/ThePrimeagen/git-worktree.nvim">here</a>’s the link.</p><h3>Here’s how to install the plugin.</h3><p>If you use Packer, then add this in your <strong>packer.lua</strong></p><pre>    use {<br>        &quot;ThePrimeagen/git-worktree.nvim&quot;,<br>        config = function()<br>            require(&quot;git-worktree&quot;).setup({})<br>            require(&quot;telescope&quot;).load_extension(&quot;git_worktree&quot;)<br>        end<br>    }</pre><p>and install the plugin using :<strong>PackerSync</strong></p><p>and remap the plugin using these 2 lines</p><pre>vim.keymap.set(&#39;n&#39;, &#39;&lt;leader&gt;gws&#39;, &#39;:Telescope git_worktree git_worktrees&lt;CR&gt;&#39;)<br>vim.keymap.set(&#39;n&#39;, &#39;&lt;leader&gt;gwc&#39;, &#39;:Telescope git_worktree create_git_worktree&lt;CR&gt;&#39;)</pre><p>After installing, once you use the shortcut, it’ll show the work trees like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vFzEBiUOng4nYU_rXH4bSQ.png" /></figure><p>change into whichever work tree you want to switch by selecting that.</p><p>It’s important to note that work trees share the same Git repository, so operations like commits, merges, and pulls will affect the repository as a whole, regardless of which work tree you’re using. However, changes to files in a specific work tree won’t affect the other work trees unless you explicitly synchronize them.</p><p>Git work tree is a powerful feature that provides flexibility and convenience when working on multiple branches or versions of a Git repository simultaneously, making it easier to manage complex development workflows.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=43f4b08bb9d5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Longest Substring Without Repeating Characters]]></title>
            <link>https://chayandatta.medium.com/longest-substring-without-repeating-characters-d43a592dd01d?source=rss-a0df0810375c------2</link>
            <guid isPermaLink="false">https://medium.com/p/d43a592dd01d</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[problem-solving]]></category>
            <category><![CDATA[interview-questions]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[algorithms]]></category>
            <dc:creator><![CDATA[CHAYAN DATTA]]></dc:creator>
            <pubDate>Wed, 17 May 2023 21:17:46 GMT</pubDate>
            <atom:updated>2023-05-17T21:17:46.184Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*v7DZdPbZk56pvOak" /><figcaption>Photo by <a href="https://unsplash.com/@jack_anstey?utm_source=medium&amp;utm_medium=referral">Jack Anstey</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>The problem of finding the length of the longest substring without repeating characters is a classic algorithmic problem.</p><p>The problem is to find the length of the longest substring in a given string s without any repeating characters. In other words, we need to find the maximum length of a substring in s that does not contain any duplicate characters.</p><p>For example, given the input string s = &quot;abcabcbb&quot;, the longest substring without repeating characters is &quot;<strong>abc</strong>&quot; with a length of 3. Another possible solution is &quot;<strong>bca</strong>&quot; with the same length.</p><pre>Example 1:<br>Input: s = &quot;abcabcbb&quot;<br>Output: 3<br>Explanation: The longest substring without repeating characters is &quot;abc&quot; with a length of 3.<br><br>Example 2:<br>Input: s = &quot;bbbbb&quot;<br>Output: 1<br>Explanation: Each character in the string is repeated, so the longest substring without repeating characters is any individual character, such as &quot;b&quot; with a length of 1.<br><br>Example 3:<br>Input: s = &quot;pwwkew&quot;<br>Output: 3<br>Explanation: The longest substring without repeating characters is &quot;wke&quot; with a length of 3. Note that the answer must be a substring, &quot;pwke&quot; is a subsequence and not a substring.<br><br>Example 4:<br>Input: s = &quot;&quot;<br>Output: 0<br>Explanation: An empty string has no repeating characters, so the longest substring without repeating characters has a length of 0.</pre><p>To solve this problem, we can use a sliding window approach. We maintain a window that expands from the left side while ensuring that there are no duplicate characters within the window. We also keep track of the maximum window size encountered so far, which represents the length of the longest substring without repeating characters.</p><p>In Python</p><pre>class Solution:<br>    def lengthOfLongestSubstring(self, s: str) -&gt; int:<br>        if len(s) &lt; 2:<br>            return len(s)<br>        window = []<br>        windowSize = 0<br>        for ele in s:<br>            while ele in window:<br>                window.pop(0)<br>            window.append(ele)<br>            windowSize = max(windowSize, len(window))<br>        return windowSize</pre><p>In Go</p><pre>func lengthOfLongestSubstring(s string) int {<br>    if len(s) &lt; 2 {<br>        return len(s)<br>    }<br>    window := &quot;&quot;<br>    windowSize := 0<br>    for _, ele := range s {<br>        for i, element := range window {<br>            if element == ele {<br>                window = window[i+1:]<br>                break<br>            }<br>        }<br>        window += string(ele)<br>        if len(window) &gt; windowSize {<br>      windowSize = len(window)<br>     }<br>    }<br>    return windowSize<br>}</pre><blockquote>The time complexity of the given code is O(n²), where n is the length of the input string s. This is because the inner while loop iterates over the window list and potentially removes elements from the front of the list. In the worst case, when all characters in s are unique, the while loop may need to iterate up to n times for each character in s. Therefore, the overall time complexity is quadratic.</blockquote><blockquote>The space complexity of the code is O(n), where n is the length of the input string s. This is because the window list is used to store unique characters temporarily. The size of the window list can grow up to the length of s in the worst case scenario where all characters are unique. Therefore, the space complexity is linear with respect to the input size.</blockquote><p>Is there a way to improve the time complexity further?</p><p>Yes,</p><ol><li>Initialize a dictionary/map, last_seen, to track the last-seen index of each character in the string s.</li><li>Set a start pointer to mark the start index of the current substring, and a max_len variable to store the maximum length encountered.</li><li>Iterate over each character in s.</li><li>If the current character is already present within the current window (i.e., its index is greater than or equal to start), update the start pointer to the index right after the previous occurrence of the character. This slides the window to the right, excluding the repeating character and any characters before it.</li><li>Update the last_seen dictionary with the current index of the character, marking its most recent occurrence.</li><li>Calculate the length of the current substring by subtracting start from the current index and adding 1.</li><li>Update the max_len variable if the current substring length is greater than the previous maximum length encountered.</li><li>After the iteration, return the value of max_len, which represents the length of the longest substring without repeating characters in the given string s.</li></ol><p>In Python</p><pre>class Solution:<br>    def lengthOfLongestSubstring(self, s: str) -&gt; int:<br>        if len(s) &lt; 2:<br>            return len(s)<br>        last_seen = dict()<br>        start, max_len = 0, 0<br><br>        for i, char in enumerate(s):<br>            if char in last_seen and last_seen[char] &gt;= start:<br>                start = last_seen[char] + 1<br>            last_seen[char] = i<br>            max_len = max(max_len, i-start+1)<br>        return max_len</pre><p>In Go</p><pre>func lengthOfLongestSubstring(s string) int {<br>    lastSeen := make(map[byte]int)<br>    start, maxLen := 0, 0<br><br>    for i, char := range s {<br>        if lastIdx, ok := lastSeen[byte(char)]; ok &amp;&amp; lastIdx &gt;= start {<br>            start = lastIdx + 1<br>        }<br>        lastSeen[byte(char)] = i<br>        currLen := i - start + 1<br>        if currLen &gt; maxLen {<br>            maxLen = currLen <br>        }<br>    }<br>    return maxLen<br>}</pre><p>Note: convert the char to byte(char) to match the map&#39;s key type, or the compiler will complain.</p><blockquote>This optimized solution achieves a linear time complexity of <strong>O(n)</strong>, where n is the length of the input string s, as we iterate over the string only once. The space complexity is <strong>O(m)</strong>, where m is the size of the character set (number of unique characters), due to the usage of the last_seen dictionary.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d43a592dd01d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Add Two Linked Lists]]></title>
            <link>https://chayandatta.medium.com/add-two-linked-lists-6d694281f05f?source=rss-a0df0810375c------2</link>
            <guid isPermaLink="false">https://medium.com/p/6d694281f05f</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[datastrucutre]]></category>
            <category><![CDATA[problem-solving]]></category>
            <dc:creator><![CDATA[CHAYAN DATTA]]></dc:creator>
            <pubDate>Tue, 16 May 2023 19:12:03 GMT</pubDate>
            <atom:updated>2023-05-16T19:12:03.307Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*buaYBq9reITvb77a" /><figcaption>Photo by <a href="https://unsplash.com/@fahrulazmi?utm_source=medium&amp;utm_medium=referral">Fahrul Azmi</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>The problem states that we are given two non-empty linked lists that represent two non-negative integers. The digits of these integers are stored in reverse order, where each node in the linked list represents a single digit. Our task is to add the two numbers represented by these linked lists and return the sum as a new linked list.</p><p>To illustrate the problem, let’s consider an example. Suppose we have two linked lists: l1 and l2.</p><pre>Linked List l1:    2 -&gt; 4 -&gt; 3<br>                  ___   ___   ___<br>                 |   | |   | |   |<br>                 | 2 | | 4 | | 3 |<br>                 |___| |___| |___|<br><br>Linked List l2:    5 -&gt; 6 -&gt; 4<br>                  ___   ___   ___<br>                 |   | |   | |   |<br>                 | 5 | | 6 | | 4 |<br>                 |___| |___| |___|</pre><p>Our goal is to add these two numbers: 342 + 465.</p><p>To solve this, we need to perform the addition operation digit by digit, considering any carry that occurs. We start from the least significant digit and move towards the most significant digit.</p><p>Here’s the step-by-step process:<br>1. Add the first digits from l1 and l2: 2 + 5 = 7. The result is 7.<br>2. Move to the next digits: 4 + 6 = 10. Since the sum is greater than 9, there is a carry. The result for this digit is 0, and we carry over the value 1 to the next step.<br>3. Move to the next digits: 3 + 4 + 1 (carry) = 8. The result is 8.<br>4. Since there are no more digits in either l1 or l2, we check if there is any remaining carry. In this case, there is none.<br>5. The final result is 708, which should be represented as a new linked list in reverse order: 8 → 0 → 7.</p><pre>final resultant linked list:    <br>                  8 -&gt; 0 -&gt; 7<br>                  ___   ___   ___<br>                 |   | |   | |   |<br>                 | 8 | | 0 | | 7 |<br>                 |___| |___| |___|<br></pre><p>Therefore, the function should return a linked list that represents the sum: 8 → 0 → 7.</p><p>Here’s the solution in Python</p><pre># Definition for singly-linked list.<br># class ListNode:<br>#     def __init__(self, val=0, next=None):<br>#         self.val = val<br>#         self.next = next<br>class Solution:<br>    def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -&gt; Optional[ListNode]:<br>        dummy = ListNode(0)<br>        curr = dummy<br>        carry = 0<br>        while l1 or l2 or carry:<br>            if l1:<br>                carry += l1.val<br>                l1 = l1.next<br>            if l2:<br>                carry += l2.val<br>                l2 = l2.next<br>            curr.next = ListNode(carry % 10)<br>            carry = carry // 10<br>            curr = curr.next<br>        <br>        return dummy.next</pre><p>Let’s try to solve in Golang</p><pre>/**<br> * Definition for singly-linked list.<br> * type ListNode struct {<br> *     Val int<br> *     Next *ListNode<br> * }<br> */<br>func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {<br>    dummy := &amp;ListNode{}<br>    curr := dummy<br>    carry := 0<br>    for l1 != nil || l2 != nil || carry != 0{<br>        if l1 != nil {<br>            carry += l1.Val<br>            l1 = l1.Next<br>        }<br>        if l2 != nil {<br>            carry += l2.Val<br>            l2 = l2.Next<br>        }<br>        curr.Next = &amp;ListNode{Val: carry % 10}<br>        carry = int(carry / 10)<br>        curr = curr.Next<br>    }<br>    return dummy.Next<br>}</pre><p>The time complexity of this solution is <strong>O(N)</strong>, where N is the length of the longer list among the two input linked lists. Since we iterate over the lists simultaneously, the number of iterations depends on the length of the longer list. Therefore, the time complexity is linear with respect to the length of the longer list.</p><p>The space complexity is also the same <strong>O(N)</strong>. We create a new linked list to store the result, which can have a <strong>maximum length of the input linked lists + 2 </strong>constant space. Hence, the space required is proportional to the length of the longer list plus a constant amount of space for the carry variable and the dummy head node.</p><blockquote>In summary, the solution has a linear time complexity and linear space complexity with respect to the length of the longer input list.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6d694281f05f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is the difference between using & import in Julia]]></title>
            <link>https://blog.devgenius.io/what-is-the-difference-between-using-import-in-julia-32bd81fbc738?source=rss-a0df0810375c------2</link>
            <guid isPermaLink="false">https://medium.com/p/32bd81fbc738</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[julialang]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[julia]]></category>
            <dc:creator><![CDATA[CHAYAN DATTA]]></dc:creator>
            <pubDate>Thu, 13 Apr 2023 20:05:46 GMT</pubDate>
            <atom:updated>2023-04-15T09:14:15.131Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pM0BluYndsV6NahC" /><figcaption>Photo by <a href="https://unsplash.com/@raimondklavins?utm_source=medium&amp;utm_medium=referral">Raimond Klavins</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Before understanding using &amp; import, let’s understand what is <strong>a module</strong> in Julia.</p><p>In Julia, modules are defined using the <strong>module</strong> keyword.</p><pre>module MyModule<br>  export myfunction<br>    <br>  function myfunction(x)<br>      return x^2<br>  end<br>end</pre><p>In this example, we define a module called <strong>MyModule</strong>, which exports a function called <strong>myfunction</strong> that takes a single argument <strong>x</strong> and returns its square. The <strong>export</strong> statement is used to make the <strong>myfunction</strong> function available outside the module.</p><p>To load a <em>module</em> from a package, we can use the <strong>using</strong> keyword:</p><pre>using MyModule<br><br>y = myfunction(2) # y = 4</pre><p>To load a module from a <em>locally</em> defined module, a dot needs to be added before the module name, like this:</p><pre>julia&gt; using .MyModule<br><br>julia&gt; myfunction(2)<br>4</pre><blockquote>Julia&#39;s modules are a unit of code in the Julia programming language that contain related functions, types, and data structures. They are used to organize code and to make it reusable in different parts of a project or in different projects. Modules help to reduce code duplication and improve maintainability.</blockquote><p>Names (referring to functions, types, global variables, and constants) can be added to the <em>export list</em> of a module with export. Typically, they are at or near the top of the module definition so that readers of the source code can find them easily</p><pre>module AnotherModule  <br>  export nice, makesquare, addtwo  <br>  <br>  makesquare(x) = x^2  <br>  addtwo(x, y) = x + y  <br>  nice(x) = &quot;nice $x&quot;<br>end</pre><pre>julia&gt; using .AnotherModule<br><br>julia&gt; nice(&quot;cat&quot;)<br>&quot;nice cat&quot;<br><br>julia&gt; addtwo(2, 3)<br>5<br><br>julia&gt; makesquare(3)<br>9</pre><p>In Julia, you can use the <strong>using</strong> and <strong>import</strong> statements to bring external modules and their functions into your current code.</p><p>The <strong>using</strong> statement is used to bring an entire module and its functions into your code, and it can be written as follows:</p><pre>using MyModule</pre><p>This statement will load the <strong>MyModule</strong> module and make all its functions available in your current code.</p><p>The <strong>import</strong> statement is used to bring specific functions from a module into your code. It can be written as follows:</p><pre>import MyModule.myfunction</pre><p>This statement will load only the <strong>myfunction</strong> function from the <strong>MyModule</strong> module and make it available in your current code.</p><p>You can also use the <strong>import</strong> statement to rename functions or modules, like this:</p><pre>import MyModule.myfunction as func</pre><p>This statement will load the <strong>myfunction</strong> function from the <strong>MyModule</strong> module and make it available in your current code as <strong>func</strong>.</p><p>To load this in a<strong> local </strong>development setup<strong>,</strong> you have to add dot(.) before module name for import also</p><pre>julia&gt; import .MyModule.myfunction as func<br><br>julia&gt; func(3)<br>9</pre><pre>julia&gt; import .AnotherModule.addtwo as add2<br><br>julia&gt; add2(3, 2)<br>5</pre><p>With <strong>using</strong>, you can directly call <strong>myfunction</strong> without needing to qualify it with the <strong>MyModule</strong> prefix.</p><p>On the other hand, <strong>import</strong> is used when you want to selectively bring in specific names from a module into your namespace. With <strong>import</strong>, you can choose which specific names you want to use, and you can rename them if you want to avoid naming conflicts.</p><p>In general, <strong>using</strong> is more convenient when you want to use multiple functions or types from a module, while <strong>import</strong> is more flexible and allows you to control the names and scope of the imported entities.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=32bd81fbc738" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/what-is-the-difference-between-using-import-in-julia-32bd81fbc738">What is the difference between using &amp; import in Julia</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>