<?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 Anasibnebelal on Medium]]></title>
        <description><![CDATA[Stories by Anasibnebelal on Medium]]></description>
        <link>https://medium.com/@anasibnebelal400?source=rss-00a0d88f89eb------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*qS1l0LEgSfJuSaxaGPrUGA.jpeg</url>
            <title>Stories by Anasibnebelal on Medium</title>
            <link>https://medium.com/@anasibnebelal400?source=rss-00a0d88f89eb------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 19:50:12 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@anasibnebelal400/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[Building DevShelf with Prisma: Indexing 1M+ Open-Source Resources]]></title>
            <link>https://medium.com/@anasibnebelal400/building-devshelf-with-prisma-indexing-1m-open-source-resources-9cbef2524fd2?source=rss-00a0d88f89eb------2</link>
            <guid isPermaLink="false">https://medium.com/p/9cbef2524fd2</guid>
            <category><![CDATA[shadcn]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[prisma-orm]]></category>
            <category><![CDATA[prisma]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Anasibnebelal]]></dc:creator>
            <pubDate>Fri, 06 Nov 2026 02:23:48 GMT</pubDate>
            <atom:updated>2026-11-06T02:23:48.688Z</atom:updated>
            <content:encoded><![CDATA[<p><em>My engineering experience with Prisma ORM, Prisma Postgres, and Prisma Compute while building a high-performance developer resource discovery platform.</em></p><p>Building a search platform that indexes more than <strong>1 million open-source learning resources</strong> comes with some interesting engineering challenges.</p><p>That’s what I explored while building <strong>DevShelf</strong> — a discovery platform for developer tutorials, open-source projects, machine learning resources, and system architecture blueprints.</p><p>Beyond building the user interface, my main focus was designing an efficient data layer, handling large-scale ingestion, and keeping resource discovery responsive.</p><p>For this project, I used <strong>Next.js 16, TypeScript, Prisma ORM, Prisma Postgres, and Prisma Compute</strong>.</p><p>Here’s what I learned along the way.</p><h3>Architecture</h3><p>The infrastructure consists of four primary components:</p><figure><img alt="The infrastructure consists of four primary components." src="https://cdn-images-1.medium.com/max/1024/1*j7iTWuOTckc1u7lwQYSUwA.png" /><figcaption>The infrastructure consists of four primary components</figcaption></figure><ul><li><strong>Next.js 16:</strong> Application layer, request handling, and server-side rendering.</li><li><strong>Prisma ORM:</strong> Type-safe database queries, schema management, and bulk operations.</li><li><strong>Prisma Postgres:</strong> Persistent storage for resource records and metadata.</li><li><strong>Prisma Compute:</strong> Hosting and compute environment for the application.</li></ul><p>I particularly liked having application hosting and the PostgreSQL database within the same ecosystem.</p><h3>How Indexing and Search Work</h3><p>The foundation of DevShelf is a structured resource catalog.</p><figure><img alt="The foundation of DevShelf is a structured resource catalog." src="https://cdn-images-1.medium.com/max/1024/1*DO_HcdvmYBaIwjVtlwW4xA.png" /><figcaption>The foundation of DevShelf is a structured resource catalog.</figcaption></figure><p>Rather than storing resources as unstructured content, each resource follows a consistent data model containing:</p><ul><li>Title and description</li><li>Resource URL and author</li><li>Category and difficulty level</li><li>Technology tags</li><li>Creation date and GitHub stars</li></ul><p><strong>Indexing:</strong> I used Prisma’s createMany functionality for bulk resource ingestion, allowing me to populate the database with more than 1 million records efficiently.</p><p><strong>Search:</strong> Users can discover resources by searching across titles, descriptions, and technology tags.</p><p><strong>Filtering and sorting:</strong> The discovery interface supports category and difficulty filters, alongside sorting by popularity, newest resources, difficulty, and title.</p><p>At a high level, the request flows from the Next.js application through Prisma ORM to PostgreSQL, which provides the matching resource records for the results interface.</p><p>The objective was simple: make a large resource catalog feel fast and easy to navigate.</p><h3>What Worked Well</h3><blockquote><strong>1. Efficient Bulk Operations</strong></blockquote><p>Prisma’s createMany performed exceptionally well during large-scale ingestion. I handled over 1 million row insertions without noticeable memory spikes or performance degradation.</p><blockquote><strong>2. Sub-second Query Performance</strong></blockquote><p>Prisma Postgres delivered consistently sub-second search results during my development testing. This was particularly important for maintaining a responsive discovery experience.</p><blockquote><strong>3. Streamlined Deployment</strong></blockquote><p>Prisma Compute and its CLI tooling simplified infrastructure management and environment isolation. This reduced setup overhead and allowed me to focus more on application development.</p><h3>How I Evaluated Performance</h3><p>I used Prisma query logging and PostgreSQL monitoring to understand database behavior.</p><p>My evaluation focused on three areas:</p><ul><li><strong>Query latency:</strong> Inspected generated SQL queries and their reported durations through Prisma Client query events.</li><li><strong>Bulk insertion:</strong> Observed database activity during large-scale createMany operations.</li><li><strong>Database behavior:</strong> Reviewed PostgreSQL query activity and latency to understand how the database responded to indexing and search workloads.</li></ul><p>One important distinction: Prisma’s logged query duration measures elapsed time between the client issuing a query and receiving the database response. It is not exclusively PostgreSQL execution time.</p><p>These were development-level observations rather than standardized load-testing benchmarks. I am not presenting formal p95/p99 latency or throughput figures.</p><h3>What Could Be Better</h3><p>Despite the positive experience, I see three opportunities for improvement:</p><blockquote><strong>1. Granular Observability</strong></blockquote><p>More detailed visibility into background worker status, indexing progress, processing throughput, and failed operations would make large-scale ingestion easier to monitor.</p><blockquote><strong>2. Cold Start Optimization</strong></blockquote><p>Reducing initial cold-start latency on Prisma Compute would further benefit search-heavy, latency-sensitive applications.</p><blockquote><strong>3. Advanced Documentation</strong></blockquote><p>More production-oriented examples covering complex relational schemas, recursive relationships, and large-scale data modeling would be valuable for developers building sophisticated applications.</p><h3>💡 Final Thoughts</h3><p>Building DevShelf gave me an opportunity to explore Prisma beyond everyday CRUD operations.</p><p>Working with large-scale data ingestion, database queries, and deployment infrastructure helped me understand how important the data layer is when building resource-intensive applications.</p><blockquote><strong>My biggest takeaway: </strong>A scalable application isn’t just about storing more data. It’s about designing an efficient pipeline to ingest, organize, retrieve, and deliver that data.</blockquote><p>Overall, Prisma provided a strong foundation for DevShelf. There are areas I’d love to see improved, but the experience has been valuable from an engineering perspective.</p><p>I’m looking forward to continuing to improve DevShelf and exploring more of the Prisma ecosystem.</p><h3>🔗 Explore DevShelf</h3><p><strong>Live Project:</strong> <a href="https://shelf.anasi.me/"><strong>https://shelf.anasi.me</strong></a></p><p>Official Prisma References</p><ul><li><a href="https://www.prisma.io/docs/orm">Prisma ORM Documentation</a></li><li><a href="https://www.prisma.io/docs/orm/v7/prisma-client/queries/crud">Prisma Client — Bulk Operations</a></li><li><a href="https://www.prisma.io/docs/orm/v7/prisma-client/observability-and-logging/logging">Prisma Client — Query Logging</a></li><li><a href="https://www.prisma.io/postgres">Prisma Postgres</a></li><li><a href="https://www.prisma.io/compute">Prisma Compute</a></li></ul><p>#Prisma #PrismaORM #PostgreSQL #NextJS #TypeScript #SoftwareEngineering #WebDevelopment #DevShelf</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9cbef2524fd2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Sliding Window Rate Limiter from Scratch Using Node.js and TypeScript]]></title>
            <link>https://medium.com/@anasibnebelal400/building-a-sliding-window-rate-limiter-from-scratch-using-node-js-and-typescript-1f4f2496fc09?source=rss-00a0d88f89eb------2</link>
            <guid isPermaLink="false">https://medium.com/p/1f4f2496fc09</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[expressjs]]></category>
            <category><![CDATA[rate-limiting]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Anasibnebelal]]></dc:creator>
            <pubDate>Mon, 02 Nov 2026 04:26:47 GMT</pubDate>
            <atom:updated>2026-11-02T04:26:47.012Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>When building REST APIs, one of the important challenges is controlling how frequently clients can send requests.</p><p>Imagine an API that allows 100 requests per 15 minutes. What happens when a client sends 100 requests within the first few seconds? What happens when another client sends requests continuously to exhaust server resources?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4mBxBIQg12ibjVEV9V6Fig.png" /></figure><p>Without proper traffic control, an API can become vulnerable to:</p><ul><li>Brute-force attacks</li><li>Excessive API consumption</li><li>Request flooding</li><li>Denial-of-service attempts</li><li>Unnecessary database and server resource consumption</li></ul><p>This is where <strong>Rate Limiting</strong> becomes important.</p><p>In this article, I’ll explain how I implemented a reusable Sliding Window Rate Limiter middleware using TypeScript and Express.js, without depending on an external rate-limiting package.</p><h3>1. What Is Rate Limiting?</h3><p>Rate limiting is a technique used to control the number of requests a client can make to an API within a specified period.</p><p>For example:</p><pre>{<br>    windowMs: 60 * 1000,<br>    max: 100<br>}</pre><p>This configuration allows a client to make up to 100 requests within a rolling 60-second window.</p><p>When the client exceeds the limit, the server responds with:</p><pre>HTTP/1.1 429 Too Many Requests</pre><p>There are several approaches to implementing rate limiting:</p><ol><li>Fixed Window Counter</li><li>Sliding Window Log</li><li>Sliding Window Counter</li><li>Token Bucket</li><li>Leaky Bucket</li></ol><p>For this implementation, I chose the <strong>Sliding Window Log Algorithm</strong>.</p><h3>2. Why Sliding Window?</h3><p>A traditional Fixed Window algorithm divides time into fixed intervals.</p><p>For example, a client can make 100 requests between 10:00 and 10:01. The counter resets at 10:01.</p><p>However, this creates a boundary problem.</p><p>A client could send:</p><ul><li>100 requests at 10:00:59.</li><li>Another 100 requests at 10:01:00.</li></ul><p>This means the server could receive 200 requests within approximately two seconds despite having a limit of 100 requests per minute.</p><p>The Sliding Window approach solves this problem by evaluating requests within a continuously moving time interval.</p><p>Instead of resetting a counter, it tracks individual request timestamps and removes those that have expired.</p><h3>3. Understanding the Architecture</h3><p>The implementation uses three main concepts:</p><p><strong>A. Map</strong></p><p>JavaScript’s Map stores request histories separately for each client.</p><p><strong>B. Timestamps</strong></p><p>Each accepted request is recorded using Date.now().</p><p><strong>C. Cleanup Mechanism</strong></p><p>A background process removes inactive client records to prevent unnecessary memory consumption.</p><p>The data structure looks like this:</p><pre>interface WindowRecord {<br>    timestamps: number[];<br>    lastAccessed: number;<br>}</pre><pre>const store = new Map&lt;string, WindowRecord&gt;();</pre><p>An example of stored data:</p><pre>{<br>    &quot;user:101&quot;: {<br>        timestamps: [1000, 2000, 3000],<br>        lastAccessed: 3000<br>    },<br>    &quot;ip:192.168.1.10&quot;: {<br>        timestamps: [1500, 2500],<br>        lastAccessed: 2500<br>    }<br>}</pre><p>Each key represents an individual client, while its timestamps represent accepted requests within the active window.</p><h3>4. Step-by-Step Working Process</h3><h3>Step 1: Configure the Rate Limiter</h3><p>The implementation starts with a configurable factory function:</p><pre>createSlidingWindowLimiter({<br>    windowMs: 60 * 1000,<br>    max: 100<br>});</pre><p>It supports multiple options, including:</p><ul><li>windowMs: Duration of the sliding window.</li><li>max: Maximum allowed requests.</li><li>keyGenerator: Custom client identification.</li><li>skip: Conditional rate-limit bypass.</li><li>message: Custom error message.</li><li>statusCode: HTTP response status.</li><li>maxTrackedKeys: Maximum number of stored client records.</li><li>cleanupIntervalMs: Background cleanup frequency.</li></ul><p>This factory-based design makes the middleware reusable across different API endpoints.</p><h3>Step 2: Identify the Client</h3><p>Before checking the request limit, the middleware needs to identify the requester.</p><p>My implementation prioritizes:</p><ol><li>Authenticated user ID.</li><li>Client IP address.</li></ol><p>Example identifiers:</p><pre>user:12345<br>ip:192.168.1.10</pre><p>This allows authenticated users to have independent request histories rather than relying exclusively on IP addresses.</p><p>For security, forwarded IP headers should only be trusted when they are supplied by correctly configured reverse proxies.</p><h3>Step 3: Retrieve the Client’s Request History</h3><p>The middleware searches the Map:</p><pre>let record = store.get(key);</pre><p>If a record exists, it retrieves the existing timestamps.</p><p>Otherwise, it creates a new record:</p><pre>record = {<br>    timestamps: [],<br>    lastAccessed: now<br>};</pre><pre>store.set(key, record);</pre><p>This ensures that every client has an independent rate-limit counter.</p><h3>Step 4: Calculate the Sliding Window</h3><p>The algorithm calculates the beginning of the active time window:</p><pre>const now = Date.now();<br>const windowStart = now - windowMs;</pre><p>For example:</p><pre>Current time: 10:01:00<br>Window size:  60 seconds</pre><pre>Window start: 10:00:00</pre><p>Only requests occurring within the active interval are counted.</p><p>Mathematically:</p><p>(now - windowMs, now]</p><h3>Step 5: Remove Expired Timestamps</h3><p>This is the core operation:</p><pre>record.timestamps = record.timestamps.filter(<br>    (timestamp) =&gt; timestamp &gt; windowStart<br>);</pre><p>Suppose the client has these request timestamps:</p><pre>10:00:05<br>10:00:15<br>10:00:25<br>10:00:35<br>10:00:45</pre><p>A new request arrives at 10:01:10.</p><p>The active window starts at 10:00:10.</p><p>Therefore, the timestamp at 10:00:05 is removed because it has expired.</p><p>The remaining timestamps are:</p><pre>10:00:15<br>10:00:25<br>10:00:35<br>10:00:45</pre><p>The algorithm now knows that the client has four requests within the active window.</p><h3>Step 6: Validate the Request Limit</h3><p>After removing expired timestamps, the middleware calculates:</p><pre>const currentRequests = record.timestamps.length;</pre><p>Then checks:</p><pre>if (currentRequests &gt;= max) {<br>    // Reject request<br>}</pre><p>If the current request count has already reached the configured maximum, the incoming request is rejected.</p><p>Otherwise, the request is accepted.</p><h3>Step 7: Calculate Retry Information</h3><p>When a client exceeds the limit, the oldest active timestamp determines when the next request slot becomes available.</p><pre>const oldestTimestamp = record.timestamps[0];</pre><pre>const resetTimeMs = oldestTimestamp + windowMs;</pre><pre>const retryAfterSeconds = Math.max(<br>    1,<br>    Math.ceil((resetTimeMs - now) / 1000)<br>);</pre><p>For example:</p><pre>Oldest request: 10:00:10<br>Window:         60 seconds<br>Current time:   10:01:00</pre><pre>Next available slot: 10:01:10</pre><pre>Retry-After: 10 seconds</pre><p>This gives clients useful information about when they can retry.</p><h3>Step 8: Return HTTP 429</h3><p>When the request limit is exceeded:</p><pre>return res.status(429).json({<br>    success: false,<br>    error: {<br>        code: &#39;RATE_LIMIT_EXCEEDED&#39;,<br>        message: &#39;Too many requests.&#39;,<br>        retryAfter: retryAfterSeconds<br>    }<br>});</pre><p>The HTTP 429 response communicates that the client has exceeded the allowed request frequency.</p><h3>Step 9: Record Accepted Requests</h3><p>If the request is allowed:</p><pre>record.timestamps.push(now);</pre><p>The middleware then calculates the remaining request allowance:</p><pre>const remaining = Math.max(<br>    0,<br>    max - record.timestamps.length<br>);</pre><p>Finally, it updates the response headers and calls:</p><pre>next();</pre><p>The request continues to the next Express middleware or controller.</p><h3>5. Automatic Memory Cleanup</h3><p>Tracking every client indefinitely would eventually consume unnecessary memory.</p><p>To address this, I implemented a periodic cleanup mechanism:</p><pre>const cleanupTimer = setInterval(() =&gt; {<br>    const now = Date.now();<br>    const expiryThreshold = now - windowMs;</pre><pre>    for (const [key, record] of store.entries()) {<br>        if (record.lastAccessed &lt; expiryThreshold) {<br>            store.delete(key);<br>        }<br>    }<br>}, cleanupIntervalMs);</pre><p>This checks inactive client records periodically and removes those that are no longer needed.</p><p>I also used:</p><pre>cleanupTimer.unref();</pre><p>This prevents the cleanup timer from keeping the Node.js event loop alive by itself during application shutdown.</p><h3>6. Creating Different Rate Limiters</h3><p>One advantage of using a factory function is that the same algorithm can serve different API requirements.</p><p>For example:</p><p><strong>Global API limiter</strong></p><pre>export const slidingWindowLimiter =<br>    createSlidingWindowLimiter({<br>        windowMs: 15 * 60 * 1000,<br>        max: 100<br>    });</pre><p><strong>Authentication limiter</strong></p><pre>export const strictSlidingWindowLimiter =<br>    createSlidingWindowLimiter({<br>        windowMs: 15 * 60 * 1000,<br>        max: 15<br>    });</pre><p><strong>Per-minute limiter</strong></p><pre>export const perMinuteLimiter =<br>    createSlidingWindowLimiter({<br>        windowMs: 60 * 1000,<br>        max: 60<br>    });</pre><p>They all share the same underlying algorithm but use different configurations.</p><p>This makes the implementation easier to maintain and extend.</p><h3>7. Understanding the HTTP Headers</h3><p>Rate-limit headers provide clients with information about their current request allowance.</p><p>Common headers include:</p><p>HeaderDescriptionRateLimit-LimitMaximum request allowanceRateLimit-RemainingRemaining requestsRateLimit-ResetReset delay in the standardized formatRetry-AfterRecommended waiting timeX-RateLimit-LimitLegacy limit informationX-RateLimit-RemainingLegacy remaining allowanceX-RateLimit-ResetCommonly used Unix reset timestamp</p><p>These headers are particularly useful when building frontend applications that need to handle rate-limit errors gracefully.</p><h3>8. Performance and Complexity</h3><p>The implementation uses JavaScript Map for client identification and arrays for request history.</p><p>Its approximate time complexity is:</p><p>OperationComplexityMap lookupO(1) averageMap insertionO(1) averageTimestamp filteringO(n)Timestamp insertionO(1) amortizedFull memory cleanupO(k)</p><p>Here:</p><ul><li>n represents timestamps stored for one client.</li><li>k represents the total number of tracked clients.</li></ul><p>One limitation is that filtering timestamps requires traversing the entire active timestamp array for every incoming request.</p><p>For high-throughput applications, a queue or deque-based implementation can reduce unnecessary processing.</p><h3>9. Important Limitations and Production Considerations</h3><p>Although this implementation demonstrates the Sliding Window Log algorithm, it is important to understand its architectural limitations.</p><p><strong>In-memory storage</strong></p><p>JavaScript Map stores data inside a single Node.js process.</p><p>Consequently:</p><ul><li>Restarting the server resets all rate-limit records.</li><li>Multiple server instances maintain separate counters.</li><li>Serverless environments cannot guarantee shared request history.</li></ul><p>For distributed production environments, Redis is a better choice because multiple application instances can share rate-limit state.</p><p><strong>Client identification</strong></p><p>Never blindly trust client-provided IP headers. Configure trusted proxies correctly and use authenticated server-side identity where appropriate.</p><p><strong>Memory management</strong></p><p>A maximum key count prevents unlimited Map growth, but simply deleting the first inserted key can remove an active client’s record. A more robust eviction strategy is needed.</p><p><strong>Configuration validation</strong></p><p>Validate window duration, maximum requests, and cleanup intervals to prevent invalid configurations.</p><p><strong>Header correctness</strong></p><p>Ensure that standardized RateLimit headers use the correct formats and that reset information reflects the actual sliding-window expiration.</p><h3>10. Conclusion</h3><p>Building a rate limiter from scratch helped me understand how API traffic control works internally.</p><p>Instead of treating rate limiting as a black-box middleware, implementing the Sliding Window Log algorithm provided practical experience with:</p><ul><li>Request lifecycle management.</li><li>Time-based algorithms.</li><li>Data structures and memory management.</li><li>Express.js middleware architecture.</li><li>HTTP status codes and response headers.</li><li>API security and scalability considerations.</li></ul><p>This implementation is a useful foundation for understanding rate limiting. For a distributed production system, the next step would be replacing the in-memory Map with a shared Redis-backed store and introducing atomic request tracking.</p><p><strong>The main lesson:</strong> A good rate limiter should not only restrict excessive requests. It should do so predictably, efficiently, and without unnecessarily affecting legitimate users.</p><h3>References</h3><ul><li><a href="https://expressjs.com/">Express.js Documentation</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Status/429">MDN: HTTP 429 Too Many Requests</a></li><li><a href="https://redis.io/docs/latest/develop/use/patterns/rate-limiter/">Redis: Rate Limiter Patterns</a></li><li><a href="https://www.rfc-editor.org/rfc/rfc6585">RFC 6585: Additional HTTP Status Codes</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1f4f2496fc09" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Day My Query Took 2 Seconds (and How One Line Fixed It)]]></title>
            <link>https://medium.com/@anasibnebelal400/the-day-my-query-took-2-seconds-and-how-one-line-fixed-it-21c6072e7a0c?source=rss-00a0d88f89eb------2</link>
            <guid isPermaLink="false">https://medium.com/p/21c6072e7a0c</guid>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[prisma]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[Anasibnebelal]]></dc:creator>
            <pubDate>Mon, 05 Oct 2026 16:53:41 GMT</pubDate>
            <atom:updated>2026-10-05T16:53:41.350Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QihEKtEn1voBo-FXYc7qUQ.png" /><figcaption>With index vs without index in PostgerSQL</figcaption></figure><p><em>What I learned about database indexing while learning PostgreSQL and Prisma</em></p><p>I thought I was doing everything right.</p><p>I was building a small project with <strong>PostgreSQL</strong> and <strong>Prisma</strong>. The schema was clean, the code worked, and the app felt fast. Then I seeded my database with 1 million fake users to “test at scale,” and one simple search broke my confidence:</p><pre>SELECT * FROM users WHERE email = &#39;rahim@example.com&#39;;</pre><p>One row. One email. It took <strong>almost 2 seconds</strong>.</p><p>I stared at the screen. <em>Why is finding one person so slow?</em></p><p>That question led me to one of the most important concepts in databases: <strong>indexing</strong>.</p><h3>What Is a Database Index?</h3><p>Imagine a 1,000-page book and you need to find the word “PostgreSQL.”</p><p><strong>Option 1:</strong> Read every page from the beginning until you find it. <strong>Option 2:</strong> Open the <strong>index at the back of the book</strong>, find “PostgreSQL → page 482,” and jump straight there.</p><p>That’s exactly what a database index is: <strong>a separate, sorted lookup structure that tells the database where your data lives, so it doesn’t have to read everything.</strong></p><p>Without an index, PostgreSQL does a <strong>Sequential Scan</strong>. It checks every row, one by one. With an index, it does an <strong>Index Scan</strong>. It jumps almost directly to the row.</p><h3>How Does Indexing Work Behind the Scenes?</h3><p>When you create an index in PostgreSQL, it builds a <strong>B-Tree</strong> (balanced tree) by default.</p><p>Think of it like a game of “guess the number between 1 and 1,000,000”:</p><ul><li>Is it higher than 500,000? Yes → ignore the lower half.</li><li>Higher than 750,000? No → ignore the upper quarter.</li><li>…and so on.</li></ul><p>Each step throws away half of the remaining possibilities. Instead of checking <strong>1,000,000</strong> rows, the database needs only about <strong>20 steps</strong>.</p><p>That’s the magic. The index stores your column values in sorted order, along with pointers to the actual rows. Searching a sorted structure is dramatically faster than scanning everything.</p><p>You can see this yourself with EXPLAIN ANALYZE:</p><pre>--EXPLAIN ANALYZE<br>SELECT * FROM users WHERE email = &#39;rahim@example.com&#39;;</pre><p><strong>Before the index:</strong></p><pre>Seq Scan on users  (cost=0.00..25000.00 rows=1 ...)<br>Execution Time: ~1800 ms</pre><p><strong>After the index:</strong></p><pre>Index Scan using idx_users_email on users  (cost=0.42..8.44 rows=1 ...)<br>Execution Time: ~0.1 ms</pre><p><em>(Your exact numbers will differ, but the gap is usually jaw-dropping.)</em></p><p>From <strong>seconds to fractions of a millisecond</strong>. That was my “wow 😮” moment.</p><h3>When Do You Actually Need an Index?</h3><p>After my discovery, I wanted to index everything. Bad idea, as I learned soon after. Indexes are powerful, but they aren’t free.</p><h3>Add an index when a column is often used in:</h3><ul><li><strong>WHERE filters</strong>: WHERE email = &#39;...&#39;</li><li><strong>JOIN conditions</strong>: especially foreign keys like user_id</li><li><strong>ORDER BY</strong>: sorting by created_at</li><li><strong>Large tables</strong>: on 50 rows, nobody cares; on 5 million, everybody does</li></ul><h3>Be careful with indexes when:</h3><ul><li><strong>The table is small.</strong> A sequential scan is already fast.</li><li><strong>The table is write-heavy.</strong> Every INSERT, UPDATE, and DELETE must also update the index, so writes get slower.</li><li><strong>The column has very few unique values</strong>, like a gender or is_active boolean. The index barely narrows anything down.</li><li><strong>You index every column.</strong> Indexes consume disk space and slow down writes.</li></ul><p><strong>My rule of thumb now:</strong> <em>Index for the queries you actually run, not the ones you imagine.</em></p><h3>How to Create Indexes: SQL</h3><h3>1. Basic index</h3><pre>CREATE INDEX idx_users_email ON users(email);</pre><h3>2. Unique index (index + no duplicates)</h3><pre>CREATE UNIQUE INDEX idx_users_email_unique ON users(email);</pre><h3>3. Composite index (multiple columns)</h3><p>Useful when you filter on two columns together:</p><pre>CREATE INDEX idx_posts_author_created<br>ON posts(author_id, created_at DESC);</pre><blockquote><strong><em>Important lesson:</em></strong><em> column order matters. This index helps queries filtering by </em><em>author_id, or by </em><em>author_id + </em><em>created_at. It will </em><strong><em>not</em></strong><em> help much if you filter only by </em><em>created_at. Think of it like a phone book sorted by last name, then first name: you can&#39;t easily search by first name alone.</em></blockquote><h3>4. Drop an index</h3><pre>DROP INDEX idx_users_email;</pre><h3>5. In production, avoid locking your table</h3><pre>CREATE INDEX CONCURRENTLY idx_users_email ON users(email);</pre><h3>How to Create Indexes: Prisma</h3><p>The best part? Prisma lets you define indexes right in schema.prisma.</p><pre>model User {<br>  id        Int      @id @default(autoincrement())<br>  email     String   @unique          // unique constraint, which also creates an index<br>  name      String<br>  city      String<br>  createdAt DateTime @default(now())<br>  posts     Post[]<br>  @@index([city])                      // single-column index<br>}<br><br>model Post {<br>  id        Int      @id @default(autoincrement())<br>  title     String<br>  authorId  Int<br>  createdAt DateTime @default(now())<br>  author    User     @relation(fields: [authorId], references: [id])<br>  @@index([authorId, createdAt(sort: Desc)])   // composite index with sort order<br>  @@index([title], name: &quot;idx_post_title&quot;)     // custom index name<br>}</pre><p>Then apply it with a migration:</p><pre>npx prisma migrate dev --name add_indexes</pre><p>Prisma generates the SQL for you and runs it on your database.</p><h3>Quick reference</h3><p>Goal Prisma syntax Primary key @id Unique + index @unique Single index @@index([field]) Composite index @@index([a, b]) Composite unique @@unique([a, b]) Custom name @@index([field], name: &quot;my_idx&quot;) Sort order @@index([field(sort: Desc)])</p><h3>A gotcha that surprised me</h3><p>In PostgreSQL, <strong>foreign keys are not automatically indexed</strong>. In the example above, authorId is a foreign key, and if I didn&#39;t add an index on it, fetching &quot;all posts by this user&quot; would slow down as the table grows. Always index your foreign keys.</p><pre>model Order {<br>  id                      String      @id @db.Uuid<br>  orderNumber             String      @unique @db.VarChar(30)<br>  customerId              String<br>  status                  OrderStatus @default(PLACED)<br>  subtotal                Decimal     @db.Decimal(12, 2)<br>  deliveryFee             Decimal     @db.Decimal(12, 2)<br>  totalAmount             Decimal     @db.Decimal(12, 2)<br>  currency                String      @default(&quot;BDT&quot;) @db.VarChar(3)<br>  customerNote            String?<br>  shippingAddressSnapshot Json<br>  placedAt                DateTime?   @db.Timestamptz(6)<br>  createdAt               DateTime    @db.Timestamptz(6)<br>  updatedAt               DateTime    @db.Timestamptz(6)<br>  delivery                Delivery?<br>  disputes                Dispute[]<br>  items                   OrderItem[]<br>  customer                User        @relation(fields: [customerId], references: [id])<br>  payments                Payment[]<br><br>  @@index([customerId]) // We have set the index with user ID<br>  @@index([status])<br>  @@index([placedAt])<br>  @@map(&quot;orders&quot;)<br>  @@schema(&quot;public&quot;)<br>}</pre><h3>The Lessons I Took Away</h3><ol><li><strong>Indexes turn full scans into targeted lookups</strong>, often the difference between seconds and milliseconds.</li><li><strong>They’re built on sorted B-Trees</strong>, which is why they scale so well.</li><li><strong>They’re a trade-off</strong>: faster reads, slower writes, more storage.</li><li><strong>Use </strong><strong>EXPLAIN ANALYZE</strong> before and after. Measure, don&#39;t guess.</li><li><strong>Index what you query</strong>: WHERE, JOIN, and ORDER BY columns.</li><li><strong>Prisma makes it easy</strong>, but you still need to understand what’s happening underneath.</li></ol><h3>Final Thoughts</h3><p>That 2-second query taught me more than any tutorial. Before, “database performance” sounded like something only senior engineers worried about. Now I know it often starts with a single line of code.</p><p>If you’re learning PostgreSQL or Prisma right now, try this experiment: seed a big table, run a slow query, add an index, and watch the difference EXPLAIN ANALYZE. You won&#39;t forget it.</p><p><em>Have you had your own “slow query” moment? I’d love to hear about it in the comments. 👇</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=21c6072e7a0c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Is a Constant Value Changeable in JavaScript? Let's Explore!]]></title>
            <link>https://medium.com/@anasibnebelal400/is-a-constant-value-changeable-in-javascript-lets-explore-3be3911bf3d8?source=rss-00a0d88f89eb------2</link>
            <guid isPermaLink="false">https://medium.com/p/3be3911bf3d8</guid>
            <category><![CDATA[datastrucutre]]></category>
            <category><![CDATA[problem-solving]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Anasibnebelal]]></dc:creator>
            <pubDate>Sun, 01 Feb 2026 15:26:16 GMT</pubDate>
            <atom:updated>2026-02-01T15:28:11.542Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/479/1*BJtzlPpztilmoy3x_yrJAw.png" /></figure><p>If we declare a variable by using the <strong>const </strong>keyword. Should it not be Changeable?</p><blockquote>This fact is true if the data type is others except <strong>Array and Object</strong></blockquote><pre>// Trying to update value<br><br>const n=10<br>n=20</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/979/1*CC5Zb9a6qV8pzY0TfWdG8g.png" /><figcaption>const keyword can’t be redeclared for Integer</figcaption></figure><p>What if we declare an array,</p><pre>// Declaration of Array and Updation.<br><br>const arr = [10, 20, 30, 40, 50]<br>arr.push(100)<br>arr.push(200)<br>arr.push(300)<br>console.log(arr)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/977/1*5c-fejacpVyrefe7e0GZjQ.png" /><figcaption>Output for Constant Array</figcaption></figure><p>For an Object</p><pre>// <br><br>const obj={<br>    name:&quot;Anas Ibn Belal&quot;,<br>    uni:&quot;Bangladesh University of Business and Technology BUBT&quot;,<br>    year:3<br>}<br>obj.uni=&quot;BUBT&quot;<br>console.log(obj)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/987/1*1dT5B9GhpOgE32Qe3hjC8Q.png" /><figcaption>No Error while updation</figcaption></figure><h3>Then why are Arrays and Objects changeable? The reason behind this is -</h3><blockquote>A const keyword in JavaScript prevents <strong>reassignment</strong> of the variable identifier itself, not the mutation of the value it holds. For arrays and objects, which are <strong>complex data types</strong>, the variable holds a <em>reference</em> to a memory location, and it is this reference that remains constant.</blockquote><h4>Analogy</h4><blockquote>A common analogy is that the const variable is a constant label or street address, but the contents of the house at that address can change. You can&#39;t move the house to a new street, but you can change the furniture inside</blockquote><p>Thanks for reading so far. Please follow me to get more information.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3be3911bf3d8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Web Cache & Redis- faster data access and fewer database queries.]]></title>
            <link>https://medium.com/@anasibnebelal400/web-cache-redis-faster-data-access-and-fewer-database-queries-c37c566a387d?source=rss-00a0d88f89eb------2</link>
            <guid isPermaLink="false">https://medium.com/p/c37c566a387d</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[anasibnbelal]]></category>
            <category><![CDATA[cache]]></category>
            <category><![CDATA[redis]]></category>
            <category><![CDATA[setup]]></category>
            <dc:creator><![CDATA[Anasibnebelal]]></dc:creator>
            <pubDate>Fri, 07 Nov 2025 19:11:36 GMT</pubDate>
            <atom:updated>2025-11-07T19:11:36.310Z</atom:updated>
            <content:encoded><![CDATA[<p>Suppose we have 10¹⁸ users with data in the database. If we want to get them all at once, then it will take a huge amount of time. How to optimize this?</p><blockquote><strong><em>Here comes the concept of Caching Data.</em></strong></blockquote><h4><strong>What is Web Cache?</strong></h4><p>A web cache is a system that stores copies of web resources (such as HTML pages, images, scripts, or API responses) so they can be served faster on subsequent requests.</p><h4>How does web caching work?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BzwFIjz-VwbV5iK1aeaUdQ.png" /><figcaption>Fig: Workflow of WebCaching</figcaption></figure><h4>Real Life Example of Caching Benefits</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/573/1*9lbO4jsdJ5EXrxOHb7W6BQ.png" /><figcaption>Fig: Before Using Caching (<strong>80 ms total</strong>)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/575/1*xT7hZHhCjAzM6p7xa0sa3g.png" /><figcaption>Fig: After Using Caching (11<strong> ms total</strong>)</figcaption></figure><blockquote>Web caching stores copies of web resources for faster access, reducing the time needed to retrieve data from a database.</blockquote><h4>How to Set Up Redis Locally?</h4><p><strong>Step 1:</strong> Install <a href="https://docs.docker.com/desktop/setup/install/windows-install/">Docker Desktop</a> and create an account on <a href="https://hub.docker.com/">DockerHub</a>.<br><strong>Step 2:</strong> Sign in to Docker Desktop using your Docker Hub Account.<br><strong>Step 3:</strong> Pull the Docker Image of Redis-Stack and start the container.<br><strong>Step 4:</strong> This will provide 2 localhost URLs. One for connectClient, another for web view of Redis Database.</p><h4><strong>Interface of Redis Webview Database</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/588/1*qG8UG4t_s4JWRddy6qwEZw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tltHCtDhe5h_Wv7rOZw1yg.png" /></figure><blockquote>Thanks for Being with me .<br>Keep Supporting…</blockquote><blockquote><strong>Follow me for more projects &amp; updates 👇</strong></blockquote><blockquote>👉 🐙<a href="https://github.com/anas20023"> GitHub</a><br>👉 <a href="https://www.linkedin.com/in/anasibelal004/">💼 LinkedIn</a><br>👉 <a href="https://www.facebook.com/anasib2000004/">📘 Facebook</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c37c566a387d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[XOR Magic !!]]></title>
            <link>https://medium.com/@anasibnebelal400/xor-magic-4f002bf53381?source=rss-00a0d88f89eb------2</link>
            <guid isPermaLink="false">https://medium.com/p/4f002bf53381</guid>
            <category><![CDATA[bitmasking]]></category>
            <category><![CDATA[problem-solving]]></category>
            <category><![CDATA[xor]]></category>
            <category><![CDATA[dsa-problem]]></category>
            <category><![CDATA[competitive-programming]]></category>
            <dc:creator><![CDATA[Anasibnebelal]]></dc:creator>
            <pubDate>Sat, 23 Aug 2025 15:19:05 GMT</pubDate>
            <atom:updated>2025-08-23T15:26:28.244Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>XOR Magic !!</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Mb3SRgDAgGjShUoZ6MMl6Q.png" /><figcaption>The magical bit manipulation operator.</figcaption></figure><p>The magical bit manipulation operator.</p><p>I have given a Problem, an array of <strong>N</strong> elements where each element occurs <strong>exactly twice </strong>except for a number, which occurs once. I have to determine that element.<br>Looks very easy problem. Isn’t it?<br><strong>But the trouble is with constraints.</strong></p><p><strong>Problem Constraints</strong></p><ul><li>1 &lt;= <strong>|N|</strong> &lt;= 2000000</li><li>0 &lt;= A[i] &lt;= INTMAX</li></ul><blockquote><strong>NOTE:</strong> Your algorithm should have a linear runtime complexity. Could you implement it<strong> without using extra memory</strong>?</blockquote><p>So, I think this should be accepted using a HashMap from the C++ STL. I have tried and Got Memory Limit Exceeded(for using HashMap). My Wrong Solution:</p><pre>// A is the Vector of size N<br>map&lt;int,int&gt;mp;<br><br>  for(int i=0;i&lt;n1;i++){<br>      mp[A[i]]++;<br>  }<br>  for(auto &amp;[f,s]:mp){<br>      if(s==1){<br>          return f;<br>      }<br>  }</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B8BBJuaSyr88cmAx-mWzQg.png" /></figure><h3><strong>How does XOR work here?</strong></h3><p><strong>Let’s take a Test Case Example</strong></p><blockquote>Input= [ 1 , 2 , 1 , 2 , 3 ]</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*MSOz9Lwj7OIUKgI6Rgo5yA.png" /><figcaption><strong>Fig 1: </strong>Reordering the elements</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/751/1*QzZss-OjBLgL4lZg9za2Yg.png" /><figcaption><strong>Fig 2:</strong> a^b means Bitwise XOR of a and b</figcaption></figure><p><strong>Final answer is = 3. </strong>The desired single element.</p><h3>Implementation in C++</h3><pre>//// A is the Vector of size N<br>int singleNumber(vector&lt;int&gt;&amp; A) {<br>    int ans= 0;<br>    for(int num : A) {<br>        ans^= num;   // keep XORing<br>    }<br>    return ans;<br>}</pre><p><strong>🚀 Let’s Connect</strong><br> Follow me for more projects &amp; updates 👇</p><p>👉 🐙<a href="https://github.com/anas20023"> GitHub</a><br> 👉 <a href="https://www.linkedin.com/in/anasibelal004/">💼 LinkedIn</a><br> 👉 <a href="https://www.facebook.com/anasib2000004/">📘 Facebook</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4f002bf53381" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fast or Reliable? Understanding TCP and UDP the Easy Way]]></title>
            <link>https://medium.com/@anasibnebelal400/fast-or-reliable-understanding-tcp-and-udp-the-easy-way-e707c492645d?source=rss-00a0d88f89eb------2</link>
            <guid isPermaLink="false">https://medium.com/p/e707c492645d</guid>
            <category><![CDATA[udp-protocol]]></category>
            <category><![CDATA[computer-networking]]></category>
            <category><![CDATA[networking]]></category>
            <category><![CDATA[udp]]></category>
            <category><![CDATA[tcp]]></category>
            <dc:creator><![CDATA[Anasibnebelal]]></dc:creator>
            <pubDate>Sun, 03 Aug 2025 17:21:41 GMT</pubDate>
            <atom:updated>2025-08-03T17:21:41.457Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-DrOP-sZveD4bRC2r4uSxw.jpeg" /></figure><h3><strong>What Are TCP and UDP?</strong></h3><h4>TCP (Transmission Control Protocol)</h4><p>A <strong>connection-oriented</strong> protocol. Think of it like a phone call — both parties connect, talk, and confirm that every word was heard.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/779/1*YWY9ZUNVjBsfnh3QaByGJw.png" /><figcaption>TCP Conection</figcaption></figure><h4>UDP (User Datagram Protocol)</h4><p>A <strong>connectionless</strong> protocol. It’s more like sending letters in the mail — fast, lightweight, and doesn’t care if one gets lost.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*SPrw1YBZsdWMbD9iKOq9yA.png" /><figcaption>UDP Connection</figcaption></figure><h3>Difference between TCP and UDP</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JLIvvTD4KMfoQO4PB01OKg.png" /><figcaption>Key differences between TCP and UDP</figcaption></figure><h3>Implementations</h3><blockquote>TCP</blockquote><ul><li><strong>Web Browsers</strong> (HTTP/HTTPS)</li><li><strong>Email Clients</strong> (SMTP, IMAP)</li><li><strong>File Transfer</strong> (FTP, SFTP)</li></ul><blockquote>UDP</blockquote><ul><li><strong>Online Games</strong> (e.g., CS: GO, Fortnite)</li><li><strong>Live Streaming</strong> (Twitch, YouTube Live)</li><li><strong>VoIP Calls</strong> (Zoom, WhatsApp)</li></ul><h3>At the End, we can say that,</h3><p><strong>TCP is reliable. UDP is fast.</strong><br> Use <strong>TCP</strong> when accuracy matters.<br> Use <strong>UDP</strong> when speed is king.<br> Know the difference — build smarter.</p><p>Thanks for reading! 🙌<br> Feel free to <strong>connect with me on </strong><a href="https://www.linkedin.com/in/anasibelal004/"><strong>LinkedIn</strong> </a>and <strong>check out my work on </strong><a href="https://github.com/anas20023/"><strong>GitHub</strong></a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e707c492645d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[In many programming contests, a problem sometimes arises as a subproblem where we need to identify…]]></title>
            <link>https://medium.com/@anasibnebelal400/in-many-programming-contests-a-problem-sometimes-arises-as-a-subproblem-where-we-need-to-identify-8596c74aa129?source=rss-00a0d88f89eb------2</link>
            <guid isPermaLink="false">https://medium.com/p/8596c74aa129</guid>
            <category><![CDATA[data-structure-algorithm]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[problem-solving]]></category>
            <category><![CDATA[dynamics-365]]></category>
            <category><![CDATA[number-theory]]></category>
            <dc:creator><![CDATA[Anasibnebelal]]></dc:creator>
            <pubDate>Wed, 25 Jun 2025 19:17:37 GMT</pubDate>
            <atom:updated>2025-06-25T19:18:25.171Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lSEzx9tE0u8SGsBtT1fu4g.png" /></figure><p>In many programming contests, a problem sometimes arises as a subproblem where we need to identify the <strong><em>digital sum, which is the sum of the digits.</em></strong></p><p>Do we Know How to solve that Easy and Small SubProblem? And what could be the complexity of that?</p><p><strong>Let&#39;s assume we have a number x = 10. </strong>Then, how to Get the Sum? <br>Simply <strong>1 + 0=1.</strong> If we have <strong>x=123456? </strong>then answer is <strong>21</strong>.</p><p>If we have a Large Number? like: <strong>x=154824656767139875.</strong> Then? Can we generalize this?</p><blockquote>YES</blockquote><blockquote>If we start from the end of the number, take each digit as part of a sum, delete it, and continue this process until the first digit —</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2TWBysV33MgGLYUMjrV7mQ.png" /><figcaption>Taking Sum and Deleting Digits</figcaption></figure><blockquote>We can simplify the process by repeatedly dividing the number by 10, which removes the last digit each time.and <strong>sum=sum+last digit</strong></blockquote><h3><strong>So what About Complexity?</strong></h3><p><strong>Time Complexity: </strong><strong>O(log₁₀(n)) Why?</strong></p><p>Each division by 10 chops off one digit from the number. So if the number has d digits:</p><ul><li>You’ll do this operation d times.</li><li>The number of digits in n is approximately log₁₀(n).</li></ul><blockquote><em>Example: </em><em>n = 12345 has 5 digits → 5 steps → </em><em>log₁₀(12345) ≈ 4.09</em></blockquote><p>In terms of bits:</p><ul><li>Each division by 10 is not a constant-time operation in low-level computation.</li><li>But in high-level algorithm analysis, we treat it asO(log₁₀(n)), or equivalently, O(log(n)) (just with different bases — doesn&#39;t matter for Big O).</li></ul><p><strong>Code Snippets (C++ and Python)</strong></p><pre>int Get_Sum(int x)<br>{<br>    int sum = 0;<br>    while (x != 0)<br>    {<br>        sum += x % 10;<br>        x /= 10;<br>    }<br>    return sum;<br>}</pre><pre>def get_sum(n):<br>    total = 0<br>    while n &gt; 0:<br>        total += n % 10  <br>        n //= 10         <br>    return total</pre><p>Do you want to solve this Subproblem? Visit <a href="https://codeforces.com/contest/1926/problem/C"><strong>Codeforces</strong></a></p><blockquote>If you like this Content and learn something from it, then don’t forget to clap ❤</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8596c74aa129" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Upsolving Is Important After Any Contest]]></title>
            <link>https://medium.com/@anasibnebelal400/why-upsolving-is-important-after-any-contest-915a1ec45515?source=rss-00a0d88f89eb------2</link>
            <guid isPermaLink="false">https://medium.com/p/915a1ec45515</guid>
            <category><![CDATA[graph]]></category>
            <category><![CDATA[competitive-programming]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[dfs]]></category>
            <category><![CDATA[cpp]]></category>
            <dc:creator><![CDATA[Anasibnebelal]]></dc:creator>
            <pubDate>Tue, 03 Jun 2025 21:07:28 GMT</pubDate>
            <atom:updated>2025-06-05T09:58:10.765Z</atom:updated>
            <content:encoded><![CDATA[<p>I recently participated in BIUPC (BUBT Intra-University Programming Contest). There was a problem on Trees and DFS (Problem J).</p><p>After reading the statement, I drew the given tree on paper and visualized the process as described in the problem.</p><p>There was a line in the statement: “<em>It is guaranteed that there will be a single path from the source to any node</em>.” In the pressure of the contest situation, I misunderstood this line and thought the tree was directed. So, I implemented the algorithm assuming it was an directed graph. After submission, I received a &#39;Wrong Answer&#39; on Test Case 3, which was very disappointing in that high-pressure moment. (I had already attempted a graph problem using BFS [Problem G] earlier and received a Wrong Answer on Test Case 55.)</p><p>I spent a lot of time on both Problem G and Problem J.</p><p>As a result, my final ranking position was poor. However, today I revisited Problem J and realized my misunderstanding. I corrected my approach and was able to solve it successfully.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/495/1*60yy8O6lLFCAa4bPy3OX8g.png" /><figcaption>Undirected Graph[Tree]</figcaption></figure><pre>for (int i = 1; i &lt;n; i++)<br>    {<br>        int v1,v2;cin&gt;&gt;v1&gt;&gt;v2;<br>        g[v1].push_back(v2);<br>        g[v2].push_back(v1); // i missed this line :(<br>    }</pre><p>The Contest is now open to everyone.</p><p>Contest Link: <a href="https://codeforces.com/contestInvitation/a158a5ad152a4d5e71e9d0dde431b37954a09530"><strong>BIUPC-2025 Spring Final Round (Senior Division)</strong></a><strong><br></strong>(Accept the invite first)</p><p>Problem Link: <a href="https://codeforces.com/gym/612803/problem/J">Problem J</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=915a1ec45515" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>