<?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"><channel><title><![CDATA[Bitwise]]></title><description><![CDATA[Bitwise]]></description><link>https://bitwise.mrvineetraj.live</link><image><url>https://cdn.hashnode.com/res/hashnode/image/upload/v1746582208894/000436f6-d1aa-44b5-9601-29c4e5053a6d.png</url><title>Bitwise</title><link>https://bitwise.mrvineetraj.live</link></image><generator>RSS for Node</generator><lastBuildDate>Wed, 15 Apr 2026 22:28:41 GMT</lastBuildDate><atom:link href="https://bitwise.mrvineetraj.live/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Why Version Control Exists: The Pendrive Problem]]></title><description><![CDATA[So before Git and GitHub, what existed?Dinosaurs? Yes, technically.But after them, software developers entered a much darker age: the Plastic Era.
This was the time when code was shared using a sacred object known as the Pen Drive.
The Plastic Era of...]]></description><link>https://bitwise.mrvineetraj.live/why-version-control-exists-the-pendrive-problem</link><guid isPermaLink="true">https://bitwise.mrvineetraj.live/why-version-control-exists-the-pendrive-problem</guid><category><![CDATA[ChaiCode]]></category><category><![CDATA[Git]]></category><category><![CDATA[GitHub]]></category><category><![CDATA[Devops]]></category><dc:creator><![CDATA[Vineet Raj]]></dc:creator><pubDate>Sat, 03 Jan 2026 01:36:56 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1767404082505/5d6c6384-520f-4d9d-abef-10f61e1ccfc9.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>So before Git and GitHub, what existed?<br />Dinosaurs? Yes, technically.<br />But after them, software developers entered a much darker age: <strong>the Plastic Era</strong>.</p>
<p>This was the time when code was shared using a sacred object known as the <strong>Pen Drive</strong>.</p>
<h3 id="heading-the-plastic-era-of-code-sharing">The Plastic Era of Code Sharing</h3>
<p>If you’re wondering how code was shared using a pendrive, it’s exactly like managing a group PPT submission in college. You’ve seen these filenames:</p>
<ul>
<li><p><code>Final_PPT</code></p>
</li>
<li><p><code>Final_submission_ppt</code></p>
</li>
<li><p><code>final_submission_latest.ppt</code></p>
</li>
<li><p><code>final_REAL_submission_v2.ppt</code></p>
</li>
</ul>
<p>Most of the time, the only actual change was the theme color from blue to orange. Yet somehow, we had ten “versions” of the same file.</p>
<p>That was version control. Sort of. If you squint hard enough.</p>
<h3 id="heading-how-the-pendrive-workflow-actually-worked">How the Pendrive Workflow Actually Worked</h3>
<p>The process was dead simple:</p>
<ol>
<li><p>Write code on your machine</p>
</li>
<li><p>Copy it to a pendrive</p>
</li>
<li><p>Hand the pendrive to another developer</p>
</li>
<li><p>They make changes</p>
</li>
<li><p>Copy it back</p>
</li>
</ol>
<p>That pendrive became the <strong>single source of truth</strong>. Whoever had it owned reality.</p>
<p>This system looked cute and cooperative until someone said:</p>
<blockquote>
<p>“Why did you make changes in this file when I was working on it?”</p>
</blockquote>
<h3 id="heading-when-things-started-breaking">When Things Started Breaking</h3>
<p>Imagine this scenario.</p>
<ul>
<li><p><code>dev_1</code> is building Feature A and creates <code>lib/utils.ts</code> for some helper functions.</p>
</li>
<li><p><code>dev_3</code> is building Feature C, completely unrelated.</p>
</li>
<li><p>Irony hits. Both need a utility function.</p>
</li>
<li><p>Both create <code>lib/utils.ts</code>.</p>
</li>
<li><p>Both even name the function the same.</p>
</li>
<li><p>Output interfaces differ slightly.</p>
</li>
</ul>
<p>Now merge those changes using a pendrive.</p>
<p>Congratulations, you’ve unlocked confusion.</p>
<p>Now multiply this problem across 60% of your codebase.</p>
<p>At this point:</p>
<ul>
<li><p>You don’t know who wrote the function</p>
</li>
<li><p>You don’t know where it’s used</p>
</li>
<li><p>You don’t know which version is correct</p>
</li>
<li><p>You don’t know who to blame</p>
</li>
</ul>
<p>Peak productivity.</p>
<h3 id="heading-why-the-pendrive-was-the-problem">Why the Pendrive Was the Problem</h3>
<p>The pendrive wasn’t evil. It was just extremely bad at its job.</p>
<p>Some core issues:</p>
<ul>
<li><p><strong>Only one person could work at a time</strong> to avoid conflicts</p>
</li>
<li><p><strong>Development speed was painfully slow</strong></p>
</li>
<li><p><strong>No credibility</strong>. Who wrote what? Who fixed what?</p>
</li>
<li><p><strong>No history</strong>. Once something broke, it broke permanently</p>
</li>
<li><p><strong>No version control</strong>, just vibes and backups</p>
</li>
</ul>
<p>You might think, “Why not use <code>final_v1</code>, <code>final_v2</code>, etc.?”</p>
<p>Sure. But even a tiny change, like updating a theme color, required duplicating the entire project. Storage got wasted fast. Mental sanity even faster.</p>
<h3 id="heading-the-first-obvious-fix-the-cloud">The First Obvious Fix: The Cloud</h3>
<p>Next logical step: remove the physical object.</p>
<p>Instead of a pendrive:</p>
<ul>
<li><p>Store code on the cloud</p>
</li>
<li><p>Developers download, modify, and upload again</p>
</li>
</ul>
<p>This solved <strong>physical dependency</strong>, but not much else.</p>
<p>Problems still remained:</p>
<ul>
<li><p>Logs were weak or manual</p>
</li>
<li><p>Versioning still meant duplicates</p>
</li>
<li><p>Storage costs increased</p>
</li>
<li><p>Collaboration conflicts still happened</p>
</li>
</ul>
<p>So close. Still bad.</p>
<h3 id="heading-enter-version-control-systems">Enter Version Control Systems</h3>
<p>Eventually, developers got tired of this nonsense and did what developers do best: <strong>build a system to fix it</strong>.</p>
<p>Version Control Systems (VCS) solved multiple problems at once:</p>
<ul>
<li><p>Track <strong>who</strong> changed <strong>what</strong></p>
</li>
<li><p>Maintain complete <strong>history</strong></p>
</li>
<li><p>Optimize <strong>storage</strong></p>
</li>
<li><p>Enable real <strong>collaboration</strong></p>
</li>
<li><p>Allow safe <strong>merging</strong>, even on the same file</p>
</li>
</ul>
<p>Version control stopped being optional. It became mandatory for any serious software.</p>
<p>Merge conflicts still hurt, but now they’re like a bad breakfast. Annoying, survivable, and not career-ending.</p>
<h3 id="heading-how-version-control-actually-solves-the-issues">How Version Control Actually Solves the Issues</h3>
<ol>
<li><p><strong>A Clear Mechanism</strong><br /> Files are organized and tracked systematically.</p>
</li>
<li><p><strong>Collaboration and Credibility</strong><br /> Developers work on branches. Every change has an owner.</p>
</li>
<li><p><strong>Space Optimization</strong><br /> Only changed files are stored as new versions. Everything else is referenced.</p>
</li>
</ol>
<p>No unnecessary duplication. No guessing games.</p>
<h3 id="heading-types-of-version-control-systems">Types of Version Control Systems</h3>
<ul>
<li><p><strong>Local Version Control Systems (LVCS)</strong><br />  Changes are stored locally as patches on one machine.</p>
</li>
<li><p><strong>Centralized Version Control Systems (CVCS)</strong><br />  One central server holds the repository. Developers check out and commit changes.</p>
</li>
<li><p><strong>Distributed Version Control Systems (DVCS)</strong><br />  Every developer clones the full repository with complete history. This is where Git lives.</p>
</li>
</ul>
<h3 id="heading-conclusion">Conclusion</h3>
<p>Version control exists because copying files is not collaboration.</p>
<p>The pendrive era taught developers a painful lesson:<br /><strong>code needs memory, ownership, and structure</strong>.</p>
]]></content:encoded></item><item><title><![CDATA[Spinning Up Databases, Firewalls, and Backups — The Story of DataBridge]]></title><description><![CDATA[How It All Started
It all began with one random thought while I was procrastinating a deployment. I was sitting there wondering — is 512 MB of storage from Supabase or NeonDB’s free tier really enough for my project? Or should I host my own Postgres ...]]></description><link>https://bitwise.mrvineetraj.live/spinning-up-databases-firewalls-and-backups-the-story-of-databridge</link><guid isPermaLink="true">https://bitwise.mrvineetraj.live/spinning-up-databases-firewalls-and-backups-the-story-of-databridge</guid><category><![CDATA[full stack]]></category><category><![CDATA[development]]></category><category><![CDATA[TypeScript]]></category><category><![CDATA[ChaiCode]]></category><category><![CDATA[Devops]]></category><category><![CDATA[Database management system]]></category><category><![CDATA[PostgreSQL]]></category><category><![CDATA[deployment]]></category><category><![CDATA[Developer]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[React]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[trpc]]></category><category><![CDATA[student]]></category><category><![CDATA[#learning-in-public]]></category><dc:creator><![CDATA[Vineet Raj]]></dc:creator><pubDate>Sat, 08 Nov 2025 07:05:41 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1762588140346/f75224be-28fb-43ec-90ba-4e9f5f7a2ecf.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-how-it-all-started"><strong>How It All Started</strong></h2>
<p>It all began with one random thought while I was <em>procrastinating</em> a deployment. I was sitting there wondering — <em>is 512 MB of storage from Supabase or NeonDB’s free tier really enough for my project?</em> Or should I host my own Postgres database on a VPS?</p>
<p>I had $200 worth of GitHub Student credits sitting in DigitalOcean, so that option was tempting. But then reality hit: <em>what about security? Backups?</em> If I self-hosted, I’d have to spin up the database manually, handle access rules, and somehow manage visualization too. Which meant firing up <code>npx prisma studio</code> every time after pasting the connection string into an <code>.env</code> file. Pain.</p>
<p>That’s when the lightbulb moment hit , <em>why not build my own database provider platform?</em> One place where I could spin up databases, manage IP rules, automate backups, and maybe even handle data visualization , all from a clean web interface. It sounded overkill at first, but also kind of fun.</p>
<p>Then the doubt crept in: <em>is this even possible for me to build? am I good enough for that?</em></p>
<p>And that’s exactly how <strong>DataBridge</strong> was born: out of hesitation, caffeine, and curiosity.</p>
<p>Now let’s talk about how it evolved : the thought process, the challenges, and the very questionable decisions that somehow worked.</p>
<h2 id="heading-project-skeleton-and-architecture-initialization">Project Skeleton and Architecture Initialization</h2>
<p>Everything starts from a template. You first set up the basic utilities you know you’ll need before getting into the actual business logic. That’s exactly what I did.</p>
<p><strong>For the backend</strong>, I started by setting up an <code>Express</code> app and attaching <code>tRPC</code> to it. Later, I integrated <code>Passport.js</code> for <code>GitHub OAuth</code>. After that, I configured middlewares for both <code>Express</code> and <code>tRPC</code> so authenticated routes would work smoothly.</p>
<p>I also extended the codebase to include a few base classes. One handled standardized responses for both <code>Express</code> and <code>tRPC</code>, so I could maintain a consistent response structure across the project. Another handled custom error classes, keeping error management predictable and debugging less painful later.</p>
<p><strong>On the frontend side</strong>, I kept things simple. Just a clean layout with a sidebar and a <code>Zustand</code> store to maintain the user state. Nothing flashy yet, just enough to get the system moving.</p>
<p>Then came the more interesting part , the project-based database instance architecture.<br />Every time a user created a new project on my platform, I used a superuser credential to spin up a new <code>PostgreSQL</code> database. Each one came with a randomly generated username (unique per project) and a completely random password.</p>
<p>At this point, I had a small concern. If a user got their connection string, they might use it to spin up another database manually, which could cause issues. To prevent that, I added a simple clause to the <code>PostgreSQL</code> query: <code>NOCREATEDB</code>. This made sure users couldn’t create new databases on their own.</p>
<p>That felt like a solid fix… for a few minutes. Then I realized another problem.<br />In development mode, whenever <code>Prisma</code> applies schema changes, it creates a shadow database to track migrations. Since my project users didn’t have <code>CREATEDB</code> permission, <code>Prisma</code> immediately failed.</p>
<p>So I had to remove the <code>NOCREATEDB</code> restriction in development mode. It wasn’t ideal, but it let me move forward and keep building. I noted it down as something to revisit once the core system was stable.</p>
<h2 id="heading-enabling-search-batch-update-and-delete-on-tables">Enabling Search, Batch Update, and Delete on Tables</h2>
<p>I spent the next two days deep in <code>PostgreSQL</code> queries. The goal was to give users not just table visualization, but also the ability to perform full <code>CRUD</code> operations on their data. Every proper DBaaS does that, and I wanted DataBridge to feel complete.</p>
<p>So I decided to mimic that behavior. The idea was simple: for each table, I’d track its primary key, mark that column as <strong>non-editable</strong>, and allow users to modify only the other columns.</p>
<p>For example, suppose there’s a table called <code>user</code> with columns <code>id</code>, <code>name</code>, <code>email</code>, and <code>age</code>.<br />If a user wanted to update the <code>name</code>, I’d map the object using the primary key as the identifier and the updated values as the payload.</p>
<p>Here’s what it looked like in practice:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> dataToBeUpdated = {
  <span class="hljs-number">123456</span>: {
    name: <span class="hljs-string">"Vineet"</span>
  }
};
</code></pre>
<p>Using this structure, I could batch update multiple rows in one go. For each primary key, the system would map its corresponding updated data, transform it into an array, and then apply updates using a <code>CTE</code> (Common Table Expression).</p>
<p>This method made the update flow efficient and predictable while still giving users control over their table data.</p>
<p>After that, I also implemented the <code>Delete</code> functionality , allowing users to remove selected rows directly from the interface, again using the same safe query pattern.</p>
<h2 id="heading-monitoring-and-modified-access-of-user-databases">Monitoring and Modified Access of User Databases</h2>
<blockquote>
<p>Live Monitoring Dashboard: <a target="_blank" href="https://monitoring.databridge.unknownbug.tech">https://monitoring.databridge.unknownbug.tech</a></p>
</blockquote>
<p>Today was all about visibility. I integrated <code>Prometheus</code>, <code>Loki</code>, and <code>Grafana</code> into the platform to monitor everything happening inside the system, from query performance to server resource usage. The idea was to make sure I could see how every part of the infrastructure behaved under real workloads.</p>
<p>Until now, I was using the <strong>superuser credentials</strong> for almost every operation, including reading data from user project databases. That felt convenient but unsafe in the long run. So I changed the approach.</p>
<p>Now, every operation that reads or interacts with a user’s project data runs using the <strong>user’s own credentials</strong>. This separation prevents unnecessary privilege escalat<a target="_blank" href="https://monitoring.databridge.unknownbug.tech">i</a>on and makes the system cleaner and more secure.</p>
<p>It was a small change in code, but a big one in design philosophy, from “make it work” to “make it reliable and accountable.”</p>
<h2 id="heading-security-01-preventing-sql-injection">Security 0.1 : Preventing SQL Injection</h2>
<p>One of the first security layers I focused on was protecting the platform against SQL injection. Since most user actions , like searching, updating, or deleting rows , eventually ran raw <code>SQL</code> queries, it made sense to handle this properly before scaling further.</p>
<p>To fix this, I started using the <code>pg-format</code> package to <strong>parameterize every user input</strong> used in queries. Whether it was a search filter, a batch update, or a delete request, each input was sanitized and formatted safely through <code>pg-format</code> before execution.</p>
<p>This change eliminated the risk of malicious input sneaking through query strings and also made my query logic a lot cleaner. It was one of those small updates that quietly made the whole system feel more production-ready.</p>
<h2 id="heading-security-10-database-password-rotation">Security 1.0: Database Password Rotation</h2>
<p>This was one of those features that started with a random thought and turned into a whole architecture lesson. I was thinking about how to automatically rotate database passwords every month, but I honestly had no clue how to manage recurring tasks like that without creating some messy loop or a bunch of cron jobs that would eventually break.</p>
<p>That’s when I stumbled into <strong>event-driven architecture</strong> and started learning about <strong>queues</strong>. It clicked instantly, queues could handle delayed jobs, retries, and scheduling without overcomplicating the main flow. So I decided to integrate it here.</p>
<p>Now, whenever a user creates a new project, a job is added to the queue for password rotation with a delay of 30 days.<br />When that delay finishes, the worker automatically triggers a password rotation using <code>pg</code> commands, updates the stored credentials in the system, and then pushes a new job into the same queue with another 30-day delay.</p>
<p>This loop keeps running forever, making sure every project gets a fresh database password every 30 days starting from its creation date. It’s all automated, secure, and event-driven — no manual work, no static schedules.</p>
<p>What started as a random “how the hell do I even do this” moment ended up being my first real use of event-driven design inside the platform.</p>
<h2 id="heading-notification-management">Notification Management</h2>
<p>Once the queue system was in place, it made sense to extend that logic to handle notifications too. I wanted the platform to automatically inform users about key events , like password rotations, database status changes, or upcoming deletions , without me wiring separate functions for each use case.</p>
<p>So I built a <strong>notification queue</strong> that manages all notifications and categorizes them by platform, such as <code>email</code> and <code>discord</code>.</p>
<p>And yes, I actually went ahead and implemented <strong>Discord integration</strong> by designing a custom bot for the platform. It was one of those fun side features that turned out to be surprisingly useful.</p>
<p>Each notification job pushed into the queue carries two key pieces of information:</p>
<ol>
<li><p>A <strong>job name</strong> (like <code>password_rotated</code>, <code>database_deleted</code>, etc.) to identify which type of message needs to be sent.</p>
</li>
<li><p>An <strong>array of platform names</strong> indicating where the notification should go.</p>
</li>
</ol>
<p>For example, when a password rotation happens, a job is inserted into the queue with something like:</p>
<pre><code class="lang-typescript">{
  jobName: <span class="hljs-string">"password_rotated"</span>,
  platforms: [<span class="hljs-string">"mail"</span>, <span class="hljs-string">"discord"</span>]
}
</code></pre>
<p>The worker picks up this job and routes it to the respective integrations. If the user has connected Discord, the message is also sent through the bot in addition to email.</p>
<p>This design kept the notification flow flexible and scalable , I could add new platforms later (like Slack or Telegram) without rewriting any of the core logic.</p>
<h2 id="heading-platform-resource-optimization-idle-database-detection">Platform Resource Optimization: Idle Database Detection</h2>
<p>After building the core features, I started thinking about how to optimize platform resources. Databases sitting idle for weeks made no sense, they still consumed storage, memory, and compute. So I decided to automate the process of detecting and handling idle databases.</p>
<p>I created a <code>cron</code> job using the <code>node-cron</code> package to run daily checks. It scans all projects to see if any database has been inactive for the last 30 days. If it finds one, the platform automatically pauses that database and pushes a notification to the user through both mail and Discord by sending metadata into the notification queue.</p>
<p>After pausing the database, the system also inserts a new job into another queue named <code>delete_database</code>, this time with a delay of 7 days , basically a 7-day grace period.</p>
<p>When the worker eventually picks up that job, it fetches the project metadata again.<br />If the database is still inactive, it deletes it permanently.<br />If the user has resumed any activity on it during those 7 days, the deletion is skipped and the database stays active.</p>
<p>To make it user-friendly, I added a <strong>“Resume Database”</strong> button right on the dashboard so users can bring their paused databases back online anytime.</p>
<p>This feature saved both compute costs and clutter while keeping users in full control of their data , a good balance between automation and ownership.</p>
<h2 id="heading-security-15-encrypted-user-database-credentials">Security 1.5: Encrypted User Database Credentials</h2>
<p>After setting up password rotation, I realized another weak spot in the system , the database credentials themselves. Even if passwords were changing every 30 days, they were still stored in plain text at rest. That didn’t sit right with me.</p>
<p>So I built a small <strong>encryption service</strong> to handle credential security. It uses the <code>AES-256-GCM</code> algorithm to encrypt all database credentials before storing them anywhere inside the system.</p>
<p>Now, every time user credentials are written to the database, they’re first passed through this encryption layer. The decrypted version is only fetched at runtime, when absolutely required , for example, when establishing a database connection or performing rotation.</p>
<p>This way, even if someone somehow gained access to the database, all they’d see would be encrypted blobs instead of readable credentials. Simple idea, but it added a strong layer of safety without overcomplicating anything.</p>
<h2 id="heading-database-backups">Database Backups</h2>
<p>Once credentials were secured, the next step was to make sure no data was ever lost. I implemented another <strong>queue</strong> dedicated to generating database backups automatically.</p>
<p>Each project gets its own backup schedule starting from the day it’s created. The queue triggers a backup job every 7 days. These backups are stored for 30 days only after that, they’re automatically removed to save space.</p>
<p>To handle cleanup, I added a <code>cron</code> job that runs daily at midnight. It scans for backups older than 30 days and deletes them from the system.</p>
<p>On the frontend, users get a clean interface to view and download their backups directly from the dashboard.</p>
<p>Under the hood, each backup is generated using the <code>pg_dump</code> command. The dump file is stored temporarily on the server, compressed, and then uploaded to <code>Cloudinary</code>. I used <strong>signed URLs</strong> for secure access. Once the upload is complete, the local backup file is deleted from the server to avoid clutter.</p>
<p>When a user clicks “Download Backup,” the backend fetches the corresponding record, generates a temporary signed URL from <code>Cloudinary</code>, and returns it. That link stays valid for only 5 minutes , enough time to download, but short enough to stay safe.</p>
<p>It’s fully automated, lightweight, and reliable, the kind of system that just quietly works in the background while users sleep.</p>
<h2 id="heading-security-20-ip-firewall-rules-per-project">Security 2.0: IP Firewall Rules Per Project</h2>
<p>This part felt like the final boss of security , <strong>IP rules</strong>. It ended up solving a bunch of platform and user issues in one go, but getting there was way harder than it looked.</p>
<p>The main problem was simple on paper: I wanted to let users whitelist IP addresses for their individual databases. The catch? Postgres doesn’t support per-database IP restrictions out of the box. If I restricted the entire server to one IP, no one else would be able to access their databases.</p>
<p>That sent me digging through Postgres docs until I discovered the <code>pg_hba.conf</code> file , the core file that controls host-based authentication. If I could edit it dynamically, I could configure custom IP rules for each user project directly from there.</p>
<p>At first, it wasn’t that easy. I was already using a Docker volume mounted at <code>/var/lib/postgres/data</code> to persist database data between container restarts. Luckily, that’s also where <code>pg_hba.conf</code> lives. My first idea was to mount another volume to copy an updated version of the file there, but the data volume kept overwriting it.</p>
<p>I needed both volumes , one for the main database data and another for the dynamic configuration , to coexist without stepping on each other. The breakthrough came when I realized I could modify the <code>postgresql.conf</code> file to change the reference path for <code>pg_hba.conf</code>.</p>
<p>So I reconfigured Postgres to look for it in <code>/var/lib/postgres/conf</code> instead of the default location. After that, everything finally worked the way I wanted.</p>
<p>Now, every time a project is created, the system automatically adds an entry for it in the <code>pg_hba.conf</code> file with <code>0.0.0.0/0</code> so it’s publicly accessible by default. When users add or modify IP rules from the dashboard, the file is updated dynamically, and the Postgres server reloads with the new configuration.</p>
<p>The best part is how it indirectly solved another issue:<br />If someone somehow managed to create a database manually using the connection string, it wouldn’t have a matching entry in the <code>pg_hba.conf</code> file. That means it wouldn’t be accessible from anywhere, and my automated cleanup system would detect and remove it on its own.</p>
<p>It was messy, painful, and required more Docker restarts than I’d like to admit, but once it worked, it made the entire security layer feel airtight.</p>
<h2 id="heading-optimization-of-pghbaconf-updates">Optimization of <code>pg_hba.conf</code> Updates</h2>
<p>Once the dynamic IP rules started working, a new challenge appeared <strong>concurrent updates</strong>.</p>
<p>If one user added a new IP rule, the platform would immediately rewrite the <code>pg_hba.conf</code> file and trigger a Postgres reload. Doing this for a few users wasn’t a big deal, but I realized that if 100+ users tried adding or updating IP rules around the same time, it could start to hurt performance.</p>
<p>So instead of reloading the Postgres server instantly for every update, I implemented a smarter solution. I set up a <code>cron</code> job that runs every hour and rewrites all the IP rules directly from the database. This way, users might have to wait up to an hour for their new IP rule to become active, but it keeps the server stable and avoids unnecessary reloads.</p>
<p>Then came the second edge case. What if, in that one-hour window, <strong>no changes</strong> had been made at all? Running a reload for no reason would still waste resources.</p>
<p>To fix that, I added a simple <strong>dirty bit</strong> service. Every time an IP rule is added or removed, it marks a flag as “dirty.” When the hourly cron job runs, it checks that flag first.</p>
<ul>
<li><p>If it’s dirty, it knows something changed and proceeds to reload the IP rules.</p>
</li>
<li><p>If it’s clean, it skips the update completely.</p>
</li>
</ul>
<p>This small mechanism made the whole system more efficient and reliable , no redundant reloads, no downtime, and zero stress even under heavy usage.</p>
<hr />
<h2 id="heading-wrapping-it-up">Wrapping It Up</h2>
<p>Looking back, <strong>DataBridge</strong> started from one random thought while I was procrastinating a deployment and somehow turned into a complete DBaaS platform with automation, monitoring, security, and event-driven systems holding it all together.</p>
<p>Every feature I built taught me something new. Half the time I was just figuring things out as I went learning how queues work, breaking Docker volumes, debugging <code>pg_hba.conf</code> reloads at 2 a.m., and accidentally discovering half the architecture through mistakes.</p>
<p>But that’s what made it fun. DataBridge isn’t just another side project. It’s the story of how curiosity, confusion, and a few bad ideas eventually evolved into something real , a system that builds, monitors, protects, and cleans itself.</p>
<p>And maybe that’s the whole point , you don’t always need to know where you’re going. Sometimes you just start building, and the architecture finds <em>you</em>.</p>
<p><strong>Live Demo</strong> : <a target="_blank" href="https://databridge.unknownbug.tech">https://databridge.unknownbug.tech</a></p>
<p><strong>Source Code :</strong> <a target="_blank" href="https://github.com/MrVineetRaj/databridge">https://github.com/MrVineetRaj/databridge</a></p>
]]></content:encoded></item><item><title><![CDATA[Introduction to OOPs]]></title><description><![CDATA[Introduction
Object-Oriented Programming (OOP) is a programming paradigm (a style of writing code) based on the concept of objects which can contain data and code. The data is represented as fields (often called attributes or properties), and the cod...]]></description><link>https://bitwise.mrvineetraj.live/introduction-to-oops</link><guid isPermaLink="true">https://bitwise.mrvineetraj.live/introduction-to-oops</guid><category><![CDATA[OOPS]]></category><category><![CDATA[constructor]]></category><category><![CDATA[Java]]></category><dc:creator><![CDATA[Vineet Raj]]></dc:creator><pubDate>Fri, 05 Sep 2025 05:55:35 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1757051629255/874fbcda-e53e-4a7d-9401-49a462aad89b.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-introduction">Introduction</h2>
<p>Object-Oriented Programming (OOP) is a programming paradigm (a style of writing code) based on the concept of objects which can contain data and code. The data is represented as fields (often called attributes or properties), and the code is represented as procedures (often called methods). Objects are instances of classes, which act as blueprints for creating objects.  </p>
<p>It majorly consists of two things:</p>
<ul>
<li><p><strong><em>Class:</em></strong> <em>A class is a blueprint or template that defines the properties (attributes) and behaviors (methods) common to all objects of its type.</em></p>
</li>
<li><p><strong><em>Object:</em></strong> <em>An object is an instance of a class, representing a specific entity with its own unique state (attribute values) and behavior.</em></p>
</li>
</ul>
<h2 id="heading-difference-between-procedural-and-object-oriented-programming-language">Difference between procedural and Object oriented Programming language</h2>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>Label</strong></td><td><strong>Procedural</strong></td><td><strong>Object Oriented</strong></td></tr>
</thead>
<tbody>
<tr>
<td>Approach</td><td>Follows a step by step sequence</td><td>It does not have a particular flow control as here we define various methods attributes in an object representing real life entities</td></tr>
<tr>
<td>Data handling</td><td>if data declared once it’s globally available so may cause confusion</td><td>here Data is encapsulated within a object and it’s access is mostly restricted through methods</td></tr>
<tr>
<td><em>Code Reusability</em></td><td>Limited. while we can reuse functions no concepts of inheritance or polymorphism is there</td><td>very high as inheritance is introduced and polymorphism</td></tr>
<tr>
<td><em>Scalability</em></td><td>Hard to scale as adding new functionality means changing old code</td><td>Very high we can just inherit old class or just add one new method in old class</td></tr>
<tr>
<td><em>Modularity</em></td><td>Very low. we can modularize functions but functions logic is not properly structured</td><td>Very high as we can create seprate classes for seperate features so it is properly structured</td></tr>
<tr>
<td><em>Real-World Modeling</em></td><td>Not aligned with real world systems</td><td>very aligned with real world systems</td></tr>
</tbody>
</table>
</div><h2 id="heading-use-cases-of-object-oriented-programming"><strong>Use-Cases of Object Oriented Programming</strong></h2>
<blockquote>
<p><strong><em>Modularity</em></strong> : <em>The process of breaking down a complex problem into smaller, manageable, and reusable components (such as classes), enhancing code organization and maintainability.</em></p>
<p><strong><em>Code Reusability:</em></strong> <em>Refers to the ability to extend and reuse existing functionality, reducing the need to duplicate code and promoting maintainability.<br />Example:</em> <strong><em>Vehicle</em></strong> <em>class extended by</em> <strong><em>Car</em></strong> <em>and</em> <strong><em>Bike*</em></strong>.*</p>
<p><strong><em>Scalability:</em></strong> <em>Refers to the ability to effortlessly add new features or functionality without modifying existing code, ensuring the system can grow and adapt without disruption.</em></p>
<p><strong><em>Security:</em></strong> <em>Using OOP, users can protect sensitive data by encapsulating it within objects and exposing only the necessary functionality through controlled access methods, ensuring data integrity and security.<br />Example: private balance in a</em> <strong><em>Bank Account</em></strong> <em>class.</em></p>
</blockquote>
<p>» Due to above mentioned use-cases OOPs is better for large scale application</p>
<h2 id="heading-classes">Classes</h2>
<p>» class is the blueprint or template for creating an object.</p>
<p>It defines the set of attributes(data) and methods(function) that an object will have after being created from certain class</p>
<pre><code class="lang-cpp"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Employee</span> {</span> 
<span class="hljs-keyword">private</span>:
    <span class="hljs-keyword">int</span> salary; <span class="hljs-comment">// to store the salary of employee</span>

<span class="hljs-keyword">public</span>:
    <span class="hljs-built_in">string</span> employeeName; <span class="hljs-comment">// to store the name of employee</span>

    <span class="hljs-comment">// Method to set the employee name</span>
    <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">setName</span><span class="hljs-params">(<span class="hljs-built_in">string</span> s)</span> </span>{ 
        employeeName = s;
    }

    <span class="hljs-comment">// Method to set the salary</span>
    <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">setSalary</span><span class="hljs-params">(<span class="hljs-keyword">int</span> val)</span> </span>{ <span class="hljs-comment">// method</span>
        salary = val;
    }

    <span class="hljs-comment">// Method to get the salary</span>
    <span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">getSalary</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> salary;
    }
};
</code></pre>
<h2 id="heading-objects">Objects</h2>
<p>» It is the instance of certain class that holds data for attributes and method provided by that class</p>
<p>for above <code>Employee</code> class , object may look like</p>
<pre><code class="lang-cpp"><span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span> </span>{
    <span class="hljs-comment">// Creating an object of Employee class</span>
    Employee obj1;

    <span class="hljs-comment">// Setting different attributes of object 1 using available methods</span>
    obj1.setName(<span class="hljs-string">"Raj"</span>); <span class="hljs-comment">// Set name to "Raj"</span>
    obj1.setSalary(<span class="hljs-number">10000</span>); <span class="hljs-comment">// Set salary to 10,000</span>

    <span class="hljs-comment">// Creating another object of Employee class</span>
    Employee obj2;

    <span class="hljs-comment">// Setting different attributes of object 2 in a similar way</span>
    obj2.setName(<span class="hljs-string">"Rahul"</span>); <span class="hljs-comment">// Set name to "Rahul"</span>
    obj2.setSalary(<span class="hljs-number">15000</span>); <span class="hljs-comment">// Set salary to 15,000</span>

    <span class="hljs-comment">// Accessing the attributes of different objects</span>
    <span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">"Salary of "</span> &lt;&lt; obj1.employeeName &lt;&lt; <span class="hljs-string">" is "</span> &lt;&lt; obj1.getSalary() &lt;&lt; <span class="hljs-built_in">endl</span>;
    <span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">"Salary of "</span> &lt;&lt; obj2.employeeName &lt;&lt; <span class="hljs-string">" is "</span> &lt;&lt; obj2.getSalary() &lt;&lt; <span class="hljs-built_in">endl</span>;

    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}

<span class="hljs-comment">/*
Output : 
Salary of Raj is 10000
Salary of Rahul is 15000
*/</span>
</code></pre>
<p><mark>Note :</mark></p>
<ul>
<li><p>Class does not hold memory</p>
</li>
<li><p>Each object created by a class holds separate allocated memory</p>
</li>
</ul>
<h2 id="heading-attributes">Attributes</h2>
<p>» Inside an object <code>attributes</code> are something that holds data or you can say characteristics of that particular object</p>
<h2 id="heading-behaviours">Behaviours:</h2>
<p>» also called methods or function</p>
<p>It exists only to manipulate or change data for attributes of an object</p>
<h2 id="heading-constructor">Constructor</h2>
<p>» A special method in a class to initialize an object when it is created</p>
<blockquote>
<p><mark>Constructor name must math the name of class</mark></p>
</blockquote>
<p>» <em>If there is no constructor written for the given class, the language by-default triggers the</em> <strong><em>default constructor*</em></strong>.*</p>
<h3 id="heading-purpose-of-constructor">Purpose of Constructor</h3>
<ul>
<li><p>Object Initialization</p>
</li>
<li><p>Code Reusability</p>
</li>
<li><p>Ensures Default value</p>
</li>
</ul>
<h3 id="heading-types-of-constructor">Types of constructor</h3>
<p><strong><em>Non-parameterized Constructor</em></strong> <em>:</em> When a constructor does not take any arguments as the input, it is called a Non-parameterized Constructor.</p>
<p><strong><em>Parameterized Constructor :</em></strong> It is a type of constructor that accepts arguments to initialize attributes with specific values</p>
<p><strong><em>Copy Constructor :</em></strong> It enables the programmer to create a new object by copying the attributes of an existing object. Java doesn't have an explicit copy constructor like C++ does. However, a copy constructor can be implemented manually by creating a constructor that takes an object of the same class as a parameter and copies its attributes using Constructor Chaining. Here's an example:</p>
<pre><code class="lang-cpp"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Employee</span> {</span>
<span class="hljs-keyword">public</span>:
    <span class="hljs-built_in">string</span> employeeName; <span class="hljs-comment">// To store the name of the employee</span>
    <span class="hljs-keyword">int</span> salary;          <span class="hljs-comment">// To store the salary of the employee</span>

    <span class="hljs-comment">// Parameterized constructor</span>
    Employee(<span class="hljs-built_in">string</span> name, <span class="hljs-keyword">int</span> salary) {
        <span class="hljs-keyword">this</span>-&gt;employeeName = name;
        <span class="hljs-keyword">this</span>-&gt;salary = salary;
    }

    <span class="hljs-comment">// Copy Constructor</span>
    Employee(<span class="hljs-keyword">const</span> Employee &amp;employee) {
        <span class="hljs-comment">// Calling another constructor</span>
        <span class="hljs-keyword">this</span>-&gt;employeeName = employee.employeeName;
        <span class="hljs-keyword">this</span>-&gt;salary = employee.salary;
    }
};

<span class="hljs-comment">// Main Class</span>
<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span> </span>{
    <span class="hljs-comment">/* Creating an object of Employee class and passing 
    values for the parameterized constructor */</span>
    <span class="hljs-function">Employee <span class="hljs-title">obj</span><span class="hljs-params">(<span class="hljs-string">"Raj"</span>, <span class="hljs-number">10000</span>)</span></span>;

    <span class="hljs-comment">// Creating a copy of obj using Copy constructor</span>
    <span class="hljs-function">Employee <span class="hljs-title">objCopy</span><span class="hljs-params">(obj)</span></span>;

    <span class="hljs-comment">// Printing the attibutes of copied object</span>
    <span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">"Name of the copied employee: "</span> &lt;&lt; objCopy.employeeName &lt;&lt; <span class="hljs-built_in">endl</span>;
    <span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">"Salary of the copied employee: "</span> &lt;&lt; objCopy.salary &lt;&lt; <span class="hljs-built_in">endl</span>;

    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}
</code></pre>
<p>» In java a constructor can also call other constructor with <strong>constructor chaining</strong> using <code>this()</code> keyword</p>
<p>» There also exist a concept called constructor overloading, that means creating multiple constructor with different number of arguments</p>
]]></content:encoded></item><item><title><![CDATA[Linked Lists in Data structure and Algorithms]]></title><description><![CDATA[Introduction
LinkedList is one of the most important topic in DSA as it is used in almost every other important topic so it is really important to learn LinkedList from scratch with strong foundation
Why LinkedLists ?
first question that come in our ...]]></description><link>https://bitwise.mrvineetraj.live/linked-lists-in-data-structure-and-algorithms</link><guid isPermaLink="true">https://bitwise.mrvineetraj.live/linked-lists-in-data-structure-and-algorithms</guid><dc:creator><![CDATA[Vineet Raj]]></dc:creator><pubDate>Sat, 19 Jul 2025 18:30:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1755369194792/30b667b2-8eec-4888-9edd-799e96ad6d88.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-introduction">Introduction</h1>
<p>LinkedList is one of the most important topic in DSA as it is used in almost every other important topic so it is really important to learn LinkedList from scratch with strong foundation</p>
<h2 id="heading-why-linkedlists">Why LinkedLists ?</h2>
<p>first question that come in our mind why to even learn LinkedLists when we have array and even vectors with dynamic size, so no vectors aren’t sufficient as vectors look like they are but how they work is like</p>
<p>let say you have defined a vector and it got one element means size is 1 now now if you try to insert new element it’s size will be double of current size</p>
<p>means if you have a vector of size 50 and you try to insert 51st element your vector will get 100 size filled so while it is dynamic it wastes lot of memories when working with huge data</p>
<p>While linked list s truly dynamic and we can just increase size of linkedlist decrease it as well</p>
<p>And you know what it is also good for space optimization as array use contagious locations for it’s assignment linkedlist on other hand use non contagious memory</p>
<p>and non contagious memory means randomly located chunks around our primary memory or RAM</p>
<p>so to keep track of it we have to keep details about the next node as if we lost it’s address we will never be able to get it and will become garbage in memory</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755369681907/7c1e1198-dce1-4367-9511-205fd348b2a6.png" alt class="image--center mx-auto" /></p>
<h2 id="heading-how-linkedlists">How LinkedLists ?</h2>
<pre><code class="lang-cpp"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Node</span> {</span>
<span class="hljs-keyword">private</span>:
    <span class="hljs-keyword">int</span> data; <span class="hljs-comment">// value stored at current node </span>
    Node* next; <span class="hljs-comment">// stores address of next node</span>
};
</code></pre>
<h1 id="heading-algorithm">Algorithm</h1>
<h2 id="heading-floyds-tortoise-and-hare-algorithm">Floyd's Tortoise and Hare algorithm</h2>
<h1 id="heading-problems">Problems</h1>
<h2 id="heading-traversal-in-linked-list-codehttpsgithubcommrvineetrajdsa-cppblobmainlinked-lists0120traversal20in20linked20listmd"><strong>Traversal in Linked List</strong> [<a target="_blank" href="https://github.com/MrVineetRaj/dsa-cpp/blob/main/linked-lists/01%20Traversal%20in%20Linked%20List.md"><code>code</code></a>]</h2>
<blockquote>
<p><code>Pattern</code> : Linear traversal :</p>
</blockquote>
<p><strong>Intuition :</strong></p>
<p>Linear traversal with a <code>curr</code> ptr until curr is not <code>null</code></p>
<p><strong>Logic :</strong></p>
<ul>
<li><p>Initialize <code>curr</code> node intially pointing at head</p>
</li>
<li><p>print value of node where <code>curr</code> node is pointing</p>
</li>
<li><p>move curr pointer</p>
</li>
<li><p>repeat till <code>curr</code> is not null</p>
</li>
</ul>
<blockquote>
<p>T.C : O(N)</p>
<p>S.C : O(1)</p>
</blockquote>
<h2 id="heading-deletion-of-the-kth-element-of-ll-codehttpsgithubcommrvineetrajdsa-cppblobmainlinked-lists0220deletion20of20the20head20of20llmd">Deletion of the Kth element of LL [<a target="_blank" href="https://github.com/MrVineetRaj/dsa-cpp/blob/main/linked-lists/02%20Deletion%20of%20the%20head%20of%20LL.md"><code>code</code></a>]</h2>
<blockquote>
<p><code>Pattern</code> : two pointer approach with one curr and a trailing prev pointer</p>
</blockquote>
<p><strong>Intuition :</strong></p>
<p>keep track index or element which is to be deleted and for doing so use linear search with curr and prev pointers</p>
<p><strong>Logic :</strong></p>
<ul>
<li><p>initialize both pointers with pointing to head</p>
</li>
<li><p>point prev to curr then move curr one step ahead</p>
</li>
<li><p>if curr is the node to be mark prec→next as curr→next</p>
</li>
<li><p>disconnect curr from LL and delete it</p>
</li>
</ul>
<blockquote>
<p>T.C : O(N)</p>
<p>S.C : O(1)</p>
</blockquote>
<h2 id="heading-insertion-at-the-kth-position-of-ll-codehttpsgithubcommrvineetrajdsa-cppblobmainlinked-lists0820insertion20at20the20kth20position20of20llmd"><strong>Insertion at the Kth position of LL</strong> [<a target="_blank" href="https://github.com/MrVineetRaj/dsa-cpp/blob/main/linked-lists/08%20Insertion%20at%20the%20Kth%20position%20of%20LL.md"><code>code</code></a>]</h2>
<blockquote>
<p><code>Pattern</code> : traversal with one pointer</p>
</blockquote>
<p><strong>Intuition :</strong></p>
<p>Move curr till curr is just before the desired position where we have to insert</p>
<p><strong>Logic :</strong></p>
<ul>
<li><p>move curr till curr→next is pointing toward desired position</p>
</li>
<li><p>now create newNode with desired value</p>
</li>
<li><p>insert newNode as newNode→next = curr→next and curr→next = newNode</p>
</li>
</ul>
<blockquote>
<p>T.C : O(N)</p>
<p>S.C : O(1)</p>
</blockquote>
<h2 id="heading-add-two-numbers-in-ll-codehttpsgithubcommrvineetrajdsa-cppblobmainlinked-lists1020add20two20numbers20in20llmd"><strong>Add two numbers in LL</strong> [<a target="_blank" href="https://github.com/MrVineetRaj/dsa-cpp/blob/main/linked-lists/10%20Add%20two%20numbers%20in%20LL.md"><code>code</code></a>]</h2>
<p>» The digits are stored in reverse order with each node storing one digit.</p>
<blockquote>
<p><code>Pattern</code> : two pointer pointing to start of each LL</p>
</blockquote>
<p><strong>Intuition :</strong></p>
<p>just move both pointers simultaneously while doing so keep adding there value and don’t forget the carry from previous sum store in the third LL which is supposed to be ans</p>
<p><strong>Logic :</strong></p>
<ul>
<li><p>initialize both pointers pointing to head of both list using curr1,curr2</p>
</li>
<li><p>calculate the sum by adding value of both curr nodes don’t forget about carry</p>
</li>
<li><p>if sum is more then 10 take module and store as sum node and update carry after deviding the sum with 10</p>
</li>
<li><p>keep doing above steps until any one hit NULL</p>
</li>
<li><p>at end just check if any curr is not NULL then append all the list in current directly</p>
</li>
<li><p>» Keep in mind you always have to maintain carry</p>
</li>
</ul>
<blockquote>
<p>T.C : O(max(N,M)</p>
<p>S.C : O(max(N,M) + 1) » if has carry then may need additional 1</p>
</blockquote>
<h2 id="heading-segregate-odd-and-even-nodes-in-ll-code">Segregate odd and even nodes in LL [<code>code</code>]</h2>
<p>» 1 Indexed list</p>
<p>» Group all the nodes with odd indices followed by all the nodes with even indices and return the reordered list.</p>
<blockquote>
<p><code>Pattern</code> : two pointer : moving with node→next→next each</p>
</blockquote>
<p><strong>Intuition :</strong></p>
<p>just keep track of head(given always) it will be head of odd indices element</p>
<p>mark evenHead for head→next if exist it will work as head of all the even indices element</p>
<p>now add other elements of odd and even indices to respective heads</p>
<p>finally point tail of odd indices list to evenHead and return head</p>
<p><strong>Logic :</strong></p>
<ul>
<li><p>as first element is from odd indices element → head of the odd indices elements : head</p>
</li>
<li><p>as second element is from even indices element → head of the even indices elements : evenHead</p>
</li>
<li><p>now use two new pointers <code>odd</code> and <code>even</code> pointing directly to the head of respect nodes → head and evenHead</p>
</li>
<li><p>now move those pointers with node→next = node→next→next</p>
</li>
<li><p>above step will make sure that for even indices node it says on even indices and on odd if node is at odd index</p>
</li>
<li><p>» consider proper order if you broke the list you will lose it</p>
</li>
</ul>
<blockquote>
<p>T.C : O(N)</p>
<p>S.C : O(1)</p>
</blockquote>
<h2 id="heading-sort-a-ll-of-0s-1s-and-2s-codehttpsgithubcommrvineetrajdsa-cppblobmainlinked-lists1220sort20a20ll20of200s201s20and202smd">Sort a LL of 0's, 1's and 2's [<a target="_blank" href="https://github.com/MrVineetRaj/dsa-cpp/blob/main/linked-lists/12%20Sort%20a%20LL%20of%200's%201's%20and%202's.md"><code>code</code></a>]</h2>
<p>» In case of LL it is always best to reorder the nodes to impress interviewer</p>
<blockquote>
<p><code>Pattern</code> : store required nodes in separate lists</p>
</blockquote>
<p><strong>Intuition :</strong></p>
<p>Store all the 0s,1s and 2s in their respective list</p>
<p><strong>Logic :</strong></p>
<ul>
<li><p>create new nodes zeroHead,oneHead,twoHead and respective curr element</p>
</li>
<li><p>traverse the list from head append various newHead based on the value of the curr&lt;head&gt; node and move curr&lt;zero,one,two&gt; accordingly</p>
</li>
<li><p>and note that do not make newNodes just mark like currZero→next = curr and then currZero = currZero→next</p>
</li>
<li><p>Attach tail of LL for zero, twos and ones accordingly and reurn zeroHead</p>
</li>
</ul>
<blockquote>
<p>T.C : O(N)</p>
<p>S.C : O(N)</p>
</blockquote>
<h2 id="heading-remove-nth-node-from-the-back-of-the-ll-codehttpsgithubcommrvineetrajdsa-cppblobmainlinked-lists1320remove20nth20node20from20the20back20of20the20llmd">Remove Nth node from the back of the LL [<a target="_blank" href="https://github.com/MrVineetRaj/dsa-cpp/blob/main/linked-lists/13%20Remove%20Nth%20node%20from%20the%20back%20of%20the%20LL.md"><code>code</code></a>]</h2>
<blockquote>
<p><code>Pattern</code> : two pointer: similar constant window concept</p>
</blockquote>
<p><strong>Intuition :</strong></p>
<p>Just like constant sliding window move the window till it’s end reaches the end of LL now delete the element where start of that window is pointing</p>
<p><strong>Logic :</strong></p>
<ul>
<li><p>Move a fast pointer to desired step ahead</p>
</li>
<li><p>now point a slow pointer to start</p>
</li>
<li><p>move slow and fast window simultaneously until next of fast pointer is null</p>
</li>
<li><p>now create a new pointer(temp) and point it to next of slow</p>
</li>
<li><p>point slow→next to temp→next</p>
</li>
<li><p>disconnect temp and then delete it</p>
</li>
</ul>
<blockquote>
<p>T.C : O(N)</p>
<p>S.C : O(1)</p>
</blockquote>
<h2 id="heading-reverse-a-ll-codehttpsgithubcommrvineetrajdsa-cppblobmainlinked-lists1420reverse20a20llmd">Reverse a LL [<a target="_blank" href="https://github.com/MrVineetRaj/dsa-cpp/blob/main/linked-lists/14%20Reverse%20a%20LL.md"><code>code</code></a>]</h2>
<blockquote>
<p><code>Pattern</code> : three pointers : prev, curr,next : game of logic</p>
</blockquote>
<p><strong>Intuition :</strong></p>
<p>It is just concept of pointers how to pint them and when to point them to remind order is also important as much as connect between nodes</p>
<blockquote>
<p>T.C : O(N)</p>
<p>S.C : O(1)</p>
</blockquote>
<h2 id="heading-add-one-to-a-number-represented-by-ll-codehttpsgithubcommrvineetrajdsa-cppblobmainlinked-lists1520add20one20to20a20number20represented20by20llmd"><strong>Add one to a number represented by LL</strong> [<a target="_blank" href="https://github.com/MrVineetRaj/dsa-cpp/blob/main/linked-lists/15%20Add%20one%20to%20a%20number%20represented%20by%20LL.md"><code>code</code></a>]</h2>
<blockquote>
<p><code>Pattern</code> : Linear traversal and concept of LL traversal</p>
</blockquote>
<p><strong>Intuition :</strong></p>
<p>it’s just when we add 1 we add it to right most digit of number and in LL it means to tail of of LL</p>
<p><strong>Logic :</strong></p>
<ul>
<li><p>Reverse the LL</p>
</li>
<li><p>Perform addition of one</p>
</li>
<li><p>Reverse back the LL</p>
</li>
<li><p>return head</p>
</li>
</ul>
<blockquote>
<p>T.C : O(N)</p>
<p>S.C : O(1)</p>
</blockquote>
<h2 id="heading-find-middle-of-linked-list-codehttpsgithubcommrvineetrajdsa-cppblobmainlinked-lists1620find20middle20of20linked20listmd">Find Middle of Linked List [<a target="_blank" href="https://github.com/MrVineetRaj/dsa-cpp/blob/main/linked-lists/16%20Find%20Middle%20of%20Linked%20List.md"><code>code</code></a>]</h2>
<blockquote>
<p><code>Pattern</code> : Fast and slow pointers <code>Floyd's Tortoise and Hare algorithm</code></p>
</blockquote>
<p><strong>Intuition :</strong></p>
<p>if a pointer moves two step at a time it will reach the end of LL while a pointer moving one step at a time will only reach the center</p>
<p><strong>Logic :</strong></p>
<ul>
<li><p>Initialize <code>slow</code> to head and <code>fast</code> to head-next</p>
</li>
<li><p>move fast like fast = fast→next→next</p>
</li>
<li><p>simultaneously move slow = slow→next</p>
</li>
<li><p>keep the loop till <code>fast != NULL &amp;&amp; fast-&gt;next != NULL</code></p>
</li>
<li><p>return slow it will be pointing to middle of the LL</p>
</li>
</ul>
<blockquote>
<p>T.C : O(N)</p>
<p>S.C : O(N)</p>
</blockquote>
<h2 id="heading-delete-the-middle-node-in-ll-codehttpsgithubcommrvineetrajdsa-cppblobmainlinked-lists1720delete20the20middle20node20in20llmd"><strong>Delete the middle node in LL</strong> [<a target="_blank" href="https://github.com/MrVineetRaj/dsa-cpp/blob/main/linked-lists/17%20Delete%20the%20middle%20node%20in%20LL.md"><code>code</code></a>]</h2>
<blockquote>
<p><code>Pattern</code> : Fast and slow pointers <code>Floyd's Tortoise and Hare algorithm</code> with a <code>prev</code> pointer</p>
</blockquote>
<p><strong>Intuition :</strong></p>
<p>Same as finding middle of LL but do it with a prev pointer point node just before slow pointer</p>
<blockquote>
<p>T.C : O(N)</p>
<p>S.C : O(N)</p>
</blockquote>
<h2 id="heading-problem-title-code">Problem Title [<code>code</code>]</h2>
<blockquote>
<p><code>Pattern</code> :</p>
</blockquote>
<p><strong>Intuition :</strong></p>
<p><strong>Logic :</strong></p>
<blockquote>
<p>T.C : O(N)</p>
<p>S.C : O(N)</p>
</blockquote>
]]></content:encoded></item><item><title><![CDATA[Arrays in Data structure and Algorithms]]></title><description><![CDATA[Array is one of the most important topic in DSA as it is used in every other topic so it is the basic necessity for solving DSA problems
Introduction
What is DSA ?
Nothing but a contagious way to store data of similar datatype ( eg: int, string , cha...]]></description><link>https://bitwise.mrvineetraj.live/arrays-in-data-structure-and-algorithms</link><guid isPermaLink="true">https://bitwise.mrvineetraj.live/arrays-in-data-structure-and-algorithms</guid><category><![CDATA[DSA]]></category><category><![CDATA[arrays]]></category><category><![CDATA[StriversA2ZDSA]]></category><dc:creator><![CDATA[Vineet Raj]]></dc:creator><pubDate>Fri, 04 Jul 2025 18:02:54 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1751652160342/161e3f42-7c3c-414e-91c7-f6218105cba8.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Array is one of the most important topic in DSA as it is used in every other topic so it is the basic necessity for solving DSA problems</p>
<h1 id="heading-introduction">Introduction</h1>
<p><strong>What is DSA ?</strong></p>
<p>Nothing but a contagious way to store data of similar datatype ( eg: <code>int</code>, <code>string</code> , <code>char</code> etc )</p>
<h2 id="heading-ways-to-declare-an-array"><strong>Ways to declare an Array ?</strong></h2>
<ol>
<li><strong>C-style Array</strong> (fixed-size on stack)</li>
</ol>
<pre><code class="lang-cpp"><span class="hljs-keyword">int</span> arr[<span class="hljs-number">5</span>];            <span class="hljs-comment">// uninitialized</span>
<span class="hljs-keyword">int</span> arr2[<span class="hljs-number">5</span>] = {<span class="hljs-number">1</span>, <span class="hljs-number">2</span>};  <span class="hljs-comment">// {1, 2, 0, 0, 0}</span>
<span class="hljs-keyword">int</span> arr3[] = {<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>}; <span class="hljs-comment">// size inferred: 3</span>
</code></pre>
<ol start="2">
<li><strong>std::array</strong> (C++11+, fixed size, safer than C-array)</li>
</ol>
<pre><code class="lang-cpp"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;array&gt;</span></span>

<span class="hljs-built_in">std</span>::<span class="hljs-built_in">array</span>&lt;<span class="hljs-keyword">int</span>, 5&gt; arr;                 <span class="hljs-comment">// default-initialized</span>
<span class="hljs-built_in">std</span>::<span class="hljs-built_in">array</span>&lt;<span class="hljs-keyword">int</span>, 5&gt; arr2 = {<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>};    <span class="hljs-comment">// {1, 2, 3, 0, 0}</span>
</code></pre>
<ul>
<li><p>Size is fixed at compile time</p>
</li>
<li><p>Has <code>.size()</code>, <code>.at()</code>, <code>.begin()</code>, <code>.end()</code>, etc.</p>
</li>
</ul>
<p>3. <strong>std::vector</strong> (dynamic size, most common in CP)</p>
<pre><code class="lang-cpp"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;vector&gt;</span></span>

<span class="hljs-built_in">std</span>::<span class="hljs-built_in">vector</span>&lt;<span class="hljs-keyword">int</span>&gt; v;                         <span class="hljs-comment">// empty</span>
<span class="hljs-function"><span class="hljs-built_in">std</span>::<span class="hljs-built_in">vector</span>&lt;<span class="hljs-keyword">int</span>&gt; <span class="hljs-title">v2</span><span class="hljs-params">(<span class="hljs-number">5</span>)</span></span>;                     <span class="hljs-comment">// {0, 0, 0, 0, 0}</span>
<span class="hljs-function"><span class="hljs-built_in">std</span>::<span class="hljs-built_in">vector</span>&lt;<span class="hljs-keyword">int</span>&gt; <span class="hljs-title">v3</span><span class="hljs-params">(<span class="hljs-number">5</span>, <span class="hljs-number">7</span>)</span></span>;                  <span class="hljs-comment">// {7, 7, 7, 7, 7}</span>
<span class="hljs-built_in">std</span>::<span class="hljs-built_in">vector</span>&lt;<span class="hljs-keyword">int</span>&gt; v4 = {<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>};         <span class="hljs-comment">// list initialization</span>
</code></pre>
<ul>
<li><p>Size can grow/shrink</p>
</li>
<li><p>Preferred in competitive programming / DSA</p>
</li>
<li><p>Has <code>.push_back()</code>, <code>.resize()</code>, etc.</p>
</li>
</ul>
<p>4. <strong>Dynamic Array via new/delete</strong> (Heap allocation)</p>
<pre><code class="lang-cpp"><span class="hljs-keyword">int</span>* arr = <span class="hljs-keyword">new</span> <span class="hljs-keyword">int</span>[<span class="hljs-number">5</span>];       <span class="hljs-comment">// uninitialized</span>
<span class="hljs-keyword">delete</span>[] arr;                <span class="hljs-comment">// don't forget to delete</span>
</code></pre>
<h1 id="heading-problems">Problems</h1>
<h2 id="heading-basic-problems-are">Basic Problems are</h2>
<ul>
<li><p>Linear Search</p>
</li>
<li><p>Largest Element</p>
</li>
<li><p>Second Largest Element</p>
</li>
<li><p>Maximum Consecutive Ones</p>
</li>
<li><p>Left Rotate Array by One</p>
</li>
<li><p>Left Rotate Array by k Places</p>
</li>
</ul>
<p>» <strong>Other Problems are</strong></p>
<h2 id="heading-move-zeros-to-end-codehttpsgithubcommrvineetrajdsa-cppblobmainarrays0120move20zeros20to20endmd">Move Zeros to End <a target="_blank" href="https://github.com/MrVineetRaj/dsa-cpp/blob/main/arrays/01%20Move%20Zeros%20to%20End.md"><code>code</code></a></h2>
<p><code>Two Pointer approach</code></p>
<ul>
<li><p>Keep both pointer at start <code>s = 0 , m = 0</code></p>
</li>
<li><p><code>m</code> scans all the elements</p>
</li>
<li><p><code>s</code> stays at index where next non-zero element should go</p>
</li>
<li><p>and if <code>m</code> ptr is at some non-zero element then swap the element with <code>s</code> ptr</p>
</li>
<li><p>and move both ptr by one</p>
</li>
<li><p>if <code>m</code> ptr is at 0 then just move it further</p>
</li>
<li><p>It will make sure that your</p>
<ul>
<li><p>before <code>s</code> all the elements are non zero and <code>s</code> will be swiping out your zeros to end</p>
</li>
<li><p>and as your <code>m</code> ptr is not moving any zero, it is moving only non zero to ptr <code>s</code> so all zero will eventually be by handled <code>s</code> and will be [ushed to end</p>
</li>
</ul>
</li>
</ul>
<h2 id="heading-remove-duplicates-from-sorted-array-codehttpsgithubcommrvineetrajdsa-cppblobmainarrays0220remove20duplicates20from20sorted20arraymd">Remove duplicates from sorted array <a target="_blank" href="https://github.com/MrVineetRaj/dsa-cpp/blob/main/arrays/02%20Remove%20duplicates%20from%20sorted%20array.md"><code>code</code></a></h2>
<p><code>Two Pointer</code></p>
<p>Define two ptrs <code>curr = 0</code> , <code>next = 0</code></p>
<ul>
<li><p><code>curr</code> stays at a index before which no duplicates exist</p>
</li>
<li><p><code>next</code> Scans the array and finds next distinct element to be placed after <code>curr</code></p>
</li>
</ul>
<p><strong>How it works</strong></p>
<ul>
<li><p><code>next</code> ptr picks an element and compares it with element at <code>curr</code> i</p>
<ul>
<li><p>if they are same <code>next</code> moves ahead by one step</p>
</li>
<li><p>if they are different moves <code>curr</code> by one step and and then swaps element at <code>curr</code> with element at <code>next</code> and moves <code>next</code> by one</p>
</li>
</ul>
</li>
<li><p>Return curr + 1 as length of subarray from <code>0 to curr</code></p>
</li>
</ul>
<h2 id="heading-find-missing-number-codehttpsgithubcommrvineetrajdsa-cppblobmainarrays0320find20missing20numbermd">Find missing number <a target="_blank" href="https://github.com/MrVineetRaj/dsa-cpp/blob/main/arrays/03%20Find%20missing%20number.md"><code>code</code></a></h2>
<p><code>math</code></p>
<ul>
<li><p>Just calculate sum of first <code>n</code> numbers</p>
</li>
<li><p>calculate the sum of elements of array</p>
</li>
<li><p>return their abs(difference)</p>
</li>
</ul>
<h2 id="heading-union-of-two-sorted-arrays-codehttpsgithubcommrvineetrajdsa-cppblobmainarrays0420union20of20two20sorted20arraysmd">Union of two sorted arrays <a target="_blank" href="https://github.com/MrVineetRaj/dsa-cpp/blob/main/arrays/04%20Union%20of%20two%20sorted%20arrays.md"><code>code</code></a></h2>
<p><code>two pointer</code></p>
<blockquote>
<p>The union of two arrays is an array where all values are distinct and are present in either the first array, the second array, or both.</p>
</blockquote>
<p>» Brute Force : using <code>set</code></p>
<p>» Optimal : using two <code>ptrs</code></p>
<p><strong>How it works</strong></p>
<p>» Will use power of arrays being sorted</p>
<ul>
<li><p><code>ptr1 = 0</code> for first array</p>
</li>
<li><p><code>ptr2 = 0</code> for second array</p>
</li>
<li><p>now run a loop till either of ptrs hit size of respective arrays</p>
</li>
<li><p><mark>and also make sure you skip all the duplicates in one array itself by internal </mark> <code>while loops</code></p>
</li>
<li><p>and keep inserting unique and distinct elements in ans array</p>
</li>
<li><p>and if any array has elements that are not pushed in ans array just push it in ans array</p>
</li>
<li><p>return ans</p>
</li>
</ul>
<h2 id="heading-intersection-of-two-sorted-arrays-codehttpsgithubcommrvineetrajdsa-cppblobmainarrays0520intersection20of20two20sorted20arraysmd">Intersection of two sorted arrays <a target="_blank" href="https://github.com/MrVineetRaj/dsa-cpp/blob/main/arrays/05%20Intersection%20of%20two%20sorted%20arrays.md"><code>code</code></a></h2>
<p><code>two ptr</code></p>
<blockquote>
<p>The intersection of two arrays is an array where all values are present in both arrays.</p>
</blockquote>
<p><strong>Same as</strong> <code>union of arrays</code> but here duplicated elements are allowed as they have same number of copies in each array</p>
<ul>
<li>just push element to ans array if both array has it</li>
</ul>
<h2 id="heading-leaders-in-an-array-codehttpsgithubcommrvineetrajdsa-cppblobmainarrays0620leaders20in20an20arraymd">Leaders in an Array <a target="_blank" href="https://github.com/MrVineetRaj/dsa-cpp/blob/main/arrays/06%20Leaders%20in%20an%20Array.md"><code>code</code></a></h2>
<p><strong><em>Just as question says</em></strong></p>
<blockquote>
<p>A leader in an array is an element whose value is strictly greater than all elements to its right in the given array. The rightmost element is always a leader. The elements in the leader array must appear in the order they appear in the nums array.</p>
</blockquote>
<h2 id="heading-rearrange-array-elements-by-sign-codehttpsgithubcommrvineetrajdsa-cppblobmainarrays0720rearrange20array20elements20by20signmd">Rearrange array elements by sign <a target="_blank" href="https://github.com/MrVineetRaj/dsa-cpp/blob/main/arrays/07%20Rearrange%20array%20elements%20by%20sign.md"><code>code</code></a></h2>
<ul>
<li><p>define two arrays</p>
<ul>
<li><p>one for positive elements</p>
</li>
<li><p>one for negative elements</p>
</li>
</ul>
</li>
<li><p>now place values from these two array to original array as requested in Problem statement</p>
</li>
</ul>
<blockquote>
<p><strong>Other way would be</strong></p>
<p>Create a new array&lt;ans array&gt; of same size and place elements in the ans array directly from given array using two pointers :</p>
<ul>
<li><p>one for positive elements at even indices</p>
</li>
<li><p>one for negative elements at odd indices</p>
</li>
</ul>
</blockquote>
<h2 id="heading-print-the-matrix-in-spiral-manner-codehttpsgithubcommrvineetrajdsa-cppblobmainarrays0820print20the20matrix20in20spiral20mannermd">Print the matrix in spiral manner <a target="_blank" href="https://github.com/MrVineetRaj/dsa-cpp/blob/main/arrays/08%20Print%20the%20matrix%20in%20spiral%20manner.md"><code>code</code></a></h2>
<blockquote>
<p>Do just as question says</p>
</blockquote>
<ul>
<li><p>will be solved using 4 ptrs</p>
<ul>
<li><code>l = 0</code> , <code>r = cols-1</code> , <code>t=0</code> , <code>b = rows- 1</code></li>
</ul>
</li>
<li><p>While moving pointers keep in mind about the bound or limit of how far a point can go</p>
</li>
</ul>
<h2 id="heading-pascals-triangle">Pascal's Triangle</h2>
<p><code>math</code></p>
<p><img src="https://www.mathsisfun.com/numbers/images/pascals-triangle-add.svg" alt="pascals triangle 1+3=4" class="image--center mx-auto" /></p>
<blockquote>
<ul>
<li><p>The first row has one element with a value of 1.</p>
</li>
<li><p>Each row has one more element in it than its previous row.</p>
</li>
<li><p>The value of each element is equal to the sum of the elements directly above it when arranged in a triangle format.</p>
</li>
</ul>
</blockquote>
<p><strong>For pascal triangle there are three type of questions</strong></p>
<h3 id="heading-print-an-element-at-r-rows-and-c-cols-of-pascals-triangle-codehttpsgithubcommrvineetrajdsa-cppblobmainarrays0920pascals20triangle20imd">Print an Element at <code>r</code> rows and <code>c</code> cols of Pascal’s Triangle <a target="_blank" href="https://github.com/MrVineetRaj/dsa-cpp/blob/main/arrays/09%20Pascal's%20Triangle%20I.md"><code>code</code></a></h3>
<p>$$\text{required_ans} = \binom{r - 1}{c - 1}$$</p><p>» <strong>Brute</strong> : Find factorial multiple times</p>
<p>» Optimal : Use formula</p>
<p>$$(n/1 )* ((n-1)/2) * ...$$</p><p>example :</p>
<p>for <code>n = 10</code> and <code>r = 7</code></p>
<p>$$\binom{10}{7} = (10/1)((10 - 1)/2)((10 - 2)/3)$$</p><h3 id="heading-print-each-element-of-rth-row-codehttpsgithubcommrvineetrajdsa-cppblobmainarrays1020pascals20triangle20iimd">Print each element of rth row <a target="_blank" href="https://github.com/MrVineetRaj/dsa-cpp/blob/main/arrays/10%20Pascal's%20Triangle%20II.md"><code>code</code></a></h3>
<pre><code class="lang-cpp">        <span class="hljs-keyword">for</span> row <span class="hljs-number">4</span> 
        simulating

        <span class="hljs-number">1</span>    <span class="hljs-number">1</span>*<span class="hljs-number">3</span>/<span class="hljs-number">1</span>    (<span class="hljs-number">1</span> * <span class="hljs-number">3</span> * <span class="hljs-number">2</span>)/( <span class="hljs-number">1</span> * <span class="hljs-number">2</span>)     (<span class="hljs-number">1</span> * <span class="hljs-number">3</span> * <span class="hljs-number">2</span> *<span class="hljs-number">1</span>)/(<span class="hljs-number">1</span> * <span class="hljs-number">2</span> * <span class="hljs-number">3</span>)
        <span class="hljs-number">1</span>    <span class="hljs-number">3</span>         <span class="hljs-number">3</span>                          <span class="hljs-number">1</span>
</code></pre>
<ul>
<li><p>here first element is <code>1</code></p>
</li>
<li><p>next element will be found by</p>
<ul>
<li><p>if x is <code>ith</code> element</p>
</li>
<li><p>then <code>(i+1)th</code> element</p>
</li>
<li><p>and it is in <code>nth</code> row</p>
</li>
<li><p>then</p>
</li>
</ul>
</li>
</ul>
<p>$$\text{required_ans} = (1*(n-1)(n-2)...(n-i+1))/ (123...*i)$$</p><ol start="3">
<li><h3 id="heading-print-all-n-rows-of-pascal-triangle-from-row-1-codehttpsgithubcommrvineetrajdsa-cppblobmainarrays1120pascals20triangle20iiimd">Print all n rows of pascal triangle from row 1 <a target="_blank" href="https://github.com/MrVineetRaj/dsa-cpp/blob/main/arrays/11%20Pascal's%20Triangle%20III.md"><code>code</code></a></h3>
</li>
</ol>
<p>Just repeat 2nd problem solution for each row</p>
<p>or</p>
<p>just implement what it is</p>
<ul>
<li><p>The first row has one element with a value of 1.</p>
</li>
<li><p>Each row has one more element in it than its previous row.</p>
</li>
<li><p>The value of each element is equal to the sum of the elements directly above it when arranged in a triangle format</p>
</li>
</ul>
<h2 id="heading-rotate-matrix-by-90-degrees-codehttpsgithubcommrvineetrajdsa-cppblobmainarrays1220rotate20matrix20by209020degreesmd"><strong>Rotate matrix by 90 degrees</strong> <a target="_blank" href="https://github.com/MrVineetRaj/dsa-cpp/blob/main/arrays/12%20Rotate%20matrix%20by%2090%20degrees.md"><code>code</code></a></h2>
<ul>
<li>Transpose → reverse each row</li>
</ul>
<h2 id="heading-two-sum-codehttpsgithubcommrvineetrajdsa-cppblobmainarrays1320two20summd">Two Sum <a target="_blank" href="https://github.com/MrVineetRaj/dsa-cpp/blob/main/arrays/13%20Two%20sum.md"><code>code</code></a></h2>
<ul>
<li><p>using map if order of element in ans has to be same</p>
</li>
<li><p>can also use sort</p>
</li>
</ul>
<h2 id="heading-three-sum-codehttpsgithubcommrvineetrajdsa-cppblobmainarrays1420three20summd">Three Sum <a target="_blank" href="https://github.com/MrVineetRaj/dsa-cpp/blob/main/arrays/14%20three%20sum.md"><code>code</code></a></h2>
<ul>
<li><p>Sorting is required</p>
</li>
<li><p>Also as it is asking about unique combinations of elements to sum to <code>0</code> <mark>Think about using a set</mark></p>
</li>
<li><p>Here three pointers will be used</p>
</li>
<li><p>one will be fixed at ith position (i = 0 → n-1)</p>
</li>
<li><p>other two will apply two sum in remaining elements and will compare three sum by adding value of item at ith index</p>
</li>
</ul>
<h2 id="heading-four-sum-codehttpsgithubcommrvineetrajdsa-cppblobmainarrays1520four20summd">Four Sum <a target="_blank" href="https://github.com/MrVineetRaj/dsa-cpp/blob/main/arrays/15%20Four%20Sum.md"><code>code</code></a></h2>
<blockquote>
<p>Same as three sum</p>
</blockquote>
<ul>
<li>Fix left most element and for rest elements apply three sum</li>
</ul>
<h2 id="heading-sort-an-array-of-0s-1s-and-2s-dutch-national-flag-algorithm-codehttpsgithubcommrvineetrajdsa-cppblobmainarrays1620sort20an20array20of200s201s20and202smd"><strong>Sort an array of 0's 1's and 2's : <mark>Dutch National Flag algorithm</mark></strong> <a target="_blank" href="https://github.com/MrVineetRaj/dsa-cpp/blob/main/arrays/16%20Sort%20an%20array%20of%200's%201's%20and%202's.md"><code>code</code></a></h2>
<p>may have to use 3 pointers</p>
<ul>
<li><p><code>s = 0</code> : before which all zeroes will be present</p>
</li>
<li><p><code>m = 0</code> : middle pointer <code>responsible for placing 0s and 2s at their desired position</code></p>
</li>
<li><p><code>e = n-1</code> : after which all twos will be present</p>
</li>
</ul>
<p><strong>Steps</strong></p>
<p>for m → 0 to e</p>
<ul>
<li><p>arr[m] == 1 : m++ and continue</p>
</li>
<li><p>arr[m] == 0 : swap element at m with elem at s and m++ and s++</p>
</li>
<li><p>arr[m] == 2 : swap element at m with elem at e and m++ and e—</p>
</li>
</ul>
<h2 id="heading-kadanes-algorithm-codehttpsgithubcommrvineetrajdsa-cppblobmainarrays1720kadanes20algorithmmd"><strong><mark>Kadane's Algorithm </mark></strong> <a target="_blank" href="https://github.com/MrVineetRaj/dsa-cpp/blob/main/arrays/17%20Kadane's%20Algorithm.md"><code>code</code></a></h2>
<ul>
<li><p>assume maxSum is minimum possible value</p>
</li>
<li><p>then iterate and keep adding every element to sum and compare it with maxSum</p>
</li>
<li><p>if sum &lt; 0 set sum = 0 and keep doing the same</p>
</li>
</ul>
<h2 id="heading-next-permutation-codehttpsgithubcommrvineetrajdsa-cppblobmainarrays1820next20permutationmd">Next Permutation <a target="_blank" href="https://github.com/MrVineetRaj/dsa-cpp/blob/main/arrays/18%20Next%20Permutation.md"><code>code</code></a></h2>
<blockquote>
<p>The next permutation of an array of integers is the next lexicographically greater permutation of its integers.</p>
<p>More formally, if all the permutations of the array are sorted in lexicographical order, then the next permutation of that array is the permutation that follows it in the sorted order.</p>
</blockquote>
<p>example :</p>
<p>for 1 3 2</p>
<p>next permutation is number strictly greater then this → 2 1 3</p>
<p><strong>Steps</strong></p>
<ul>
<li><p>Find the element for which arr[i] &lt; arr[i+1] <code>where i = n-2 → 0</code></p>
</li>
<li><p>now pivot at that index i</p>
</li>
<li><p>find the first element on right part of pivot which is greater then item at i</p>
</li>
<li><p>swap it at i and with item found at previous step</p>
</li>
<li><p>now reverse the right part of pivot <code>excluding the ith element</code></p>
</li>
</ul>
<h2 id="heading-majority-element-i-moores-voting-algorithm-codehttpsgithubcommrvineetrajdsa-cppblobmainarrays1920majority20element20imd">Majority Element I : <mark>Moore's voting algorithm </mark> <a target="_blank" href="https://github.com/MrVineetRaj/dsa-cpp/blob/main/arrays/19%20Majority%20Element%20I.md"><code>code</code></a></h2>
<blockquote>
<p>The majority element of an array is an element that appears more than n/2 times in the array. The array is guaranteed to have a majority element.</p>
</blockquote>
<p>In this algorithm we keep track of</p>
<ul>
<li><p>ans : element which is desired</p>
</li>
<li><p>cnt : freq of how many times ans repeated it self in the array</p>
</li>
</ul>
<p><strong>Steps</strong></p>
<ul>
<li><p>for every value of i ; i = 0→ n-1</p>
<ul>
<li><p>if cnt = 0 : we assume this is the ans</p>
</li>
<li><p>if cnt ≠ 0</p>
<ul>
<li><p>if ans = arr[i] : cnt++</p>
</li>
<li><p>else : cnt—</p>
</li>
</ul>
</li>
</ul>
</li>
</ul>
<p>now we will have a value in ans which is the possible ans as <mark>if element is appearing more than n/2 times </mark> means it will be the last one in ans variable</p>
<p>however it is possible that no item appear more that n/2 times ,</p>
<p>hence we count the freq of ans in complete array using for loop over complete array</p>
<ul>
<li><p>if it satisfies the condition of majority element: our ans</p>
</li>
<li><p>else return -1</p>
</li>
</ul>
<h2 id="heading-majority-element-ii-codehttpsgithubcommrvineetrajdsa-cppblobmainarrays2020majority20element-iimd">Majority Element-II <a target="_blank" href="https://github.com/MrVineetRaj/dsa-cpp/blob/main/arrays/20%20Majority%20Element-II.md"><code>code</code></a></h2>
<blockquote>
<p><strong>all</strong> elements which <strong>appear more than</strong> <strong>n/3</strong></p>
</blockquote>
<p>Modification to <code>moore voting element</code></p>
<ul>
<li>Only two possible ans will exist</li>
</ul>
<h2 id="heading-find-the-repeating-and-missing-number-codehttpsgithubcommrvineetrajdsa-cppblobmainarrays2120find20the20repeating20and20missing20numbermd">Find the repeating and missing number <a target="_blank" href="https://github.com/MrVineetRaj/dsa-cpp/blob/main/arrays/21%20Find%20the%20repeating%20and%20missing%20number.md"><code>code</code></a></h2>
<blockquote>
<p>A math problem always prefer it’s coding solution</p>
<p>solved using generation equations of sum of first n elements and sum of first n*n elements</p>
</blockquote>
<h2 id="heading-count-inversions-codehttpsgithubcommrvineetrajdsa-cppblobmainarrays2220count20inversionsmd"><strong>Count Inversions</strong> <a target="_blank" href="https://github.com/MrVineetRaj/dsa-cpp/blob/main/arrays/22%20Count%20Inversions.md"><code>code</code></a></h2>
<blockquote>
<p><strong>Brute force:</strong> Generate all pairs by scanning all other elements for each selected elements and return count of such numbers</p>
<p>optimal : merge sort</p>
</blockquote>
<h2 id="heading-maximum-product-sub-array-in-an-array-code-todo">Maximum product sub array in an Array <code>code : todo</code></h2>
<p>concept of <code>prefix</code> product and <code>suffix</code> product</p>
<ul>
<li><p>for even number of negative elements product of whole array will be positive</p>
</li>
<li><p>for odd number of negative elements there will be a single negative element that will cause whole product to be negative.</p>
<ul>
<li><p>hence ans would be either right part of that element</p>
</li>
<li><p>or left part of that element</p>
</li>
</ul>
</li>
<li><p>To handle case for zero just assign 1 to prefix product or suffix product if they get zero</p>
</li>
<li><p>For each iteration compare and store the max of suffix or prefix product or if prev stored was already bigger then move on</p>
</li>
<li><p>and return the final ans</p>
</li>
</ul>
<h2 id="heading-merge-two-sorted-arrays-without-extra-space-code-todo"><strong>Merge two sorted arrays without extra space</strong> <code>code : todo</code></h2>
<blockquote>
<p>just make sure all them elements in one array are strictly smaller then all elements of other array</p>
</blockquote>
<p>» Note : Array size of left array is given as total number of elements</p>
<p><strong>Steps</strong></p>
<ul>
<li><p>Consider two arrays left , right array</p>
</li>
<li><p>point one ptr at end of left array</p>
</li>
<li><p>point second ptr at start of right array</p>
</li>
<li><p>traverse both such that elements in left always smaller then right</p>
</li>
<li><p>push all the elements from right to left array</p>
</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Essential Docker Commands Every Beginner Should Learn]]></title><description><![CDATA[As in my previous article, I wrote steps for Docker installation and had a healthy discussion about sudo docker vs just docker. (Here I will write commands that start with docker)
What is the Problem?
Imagine you're working on multiple projects:

Pro...]]></description><link>https://bitwise.mrvineetraj.live/essential-docker-commands-every-beginner-should-learn</link><guid isPermaLink="true">https://bitwise.mrvineetraj.live/essential-docker-commands-every-beginner-should-learn</guid><category><![CDATA[Docker]]></category><category><![CDATA[Devops]]></category><category><![CDATA[Developer]]></category><category><![CDATA[100DaysOfCode]]></category><category><![CDATA[why docker]]></category><category><![CDATA[ChaiCode]]></category><dc:creator><![CDATA[Vineet Raj]]></dc:creator><pubDate>Thu, 19 Jun 2025 06:22:46 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1750313893715/31b89db2-945d-4770-9c29-fae5656cda40.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>As in my previous article, I wrote steps for Docker installation and had a healthy discussion about <code>sudo docker</code> vs just <code>docker</code>. (Here I will write commands that start with <code>docker</code>)</p>
<h1 id="heading-what-is-the-problem">What is the Problem?</h1>
<p>Imagine you're working on multiple projects:</p>
<ul>
<li><p>Project 1 needs Node.js version 18.x</p>
</li>
<li><p>Project 2 needs Node.js v20.x</p>
</li>
<li><p>Some projects need an older MongoDB version</p>
</li>
<li><p>Others need the current MongoDB version</p>
</li>
</ul>
<p>What would you do? Install and reinstall versions one by one? This approach is difficult because:</p>
<ul>
<li><p>Every version must be configured accordingly</p>
</li>
<li><p>Installed versions may conflict with each other</p>
</li>
<li><p>Managing dependencies becomes a nightmare</p>
</li>
</ul>
<h1 id="heading-what-is-the-solution">What is the Solution?</h1>
<p>Virtual machines are one solution, but they're resource-heavy and difficult to manage. You'd need to:</p>
<ul>
<li><p>Spin VMs on and off</p>
</li>
<li><p>Connect services between different VMs</p>
</li>
<li><p>Connect VM services with your local machine</p>
</li>
</ul>
<p><strong>Docker changes everything!</strong> It can:</p>
<ul>
<li><p>Spin environments up and down in seconds</p>
</li>
<li><p>Run services instantly</p>
</li>
<li><p>Connect all services with your local machine out of the box</p>
</li>
<li><p>Simply map ports to connect services</p>
<p>  <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1750313776476/feec0dcc-3516-4a2d-a7d7-1049f17ca0c1.png" alt class="image--center mx-auto" /></p>
</li>
</ul>
<h1 id="heading-docker-terminology">Docker Terminology</h1>
<ol>
<li><p><strong>Docker Image</strong>: A blueprint or template containing the code and dependencies needed to run a service. Think of it as a program stored on your machine, not executing but ready to run.</p>
</li>
<li><p><strong>Docker Container</strong>: A running instance of a Docker image. It's like a process - your program in execution. When you run a container, Docker creates a unique instance with its own environment.</p>
</li>
</ol>
<p>Each container is unique by default through a container ID, even if you don't pass any variables. You can also pass environment variables to customize containers.</p>
<blockquote>
<p><strong>Prerequisites</strong>: If you don't have Docker installed, refer to this article: <a target="_blank" href="https://blog.unknownbug.tech/docker-installation-guide">Docker installation guide</a></p>
</blockquote>
<h1 id="heading-docker-commands-for-images">Docker Commands for Images</h1>
<h2 id="heading-1-download-an-image">1. Download an Image</h2>
<p>Browse <a target="_blank" href="https://hub.docker.com/">Docker Hub</a> to find the image you need:</p>
<pre><code class="lang-bash">docker pull &lt;image_name&gt;
</code></pre>
<p><strong>Examples:</strong></p>
<pre><code class="lang-bash">docker pull postgres          <span class="hljs-comment"># Latest postgres version</span>
docker pull postgres:16       <span class="hljs-comment"># Specific postgres version</span>
docker pull node:18-alpine    <span class="hljs-comment"># Node.js 18 with Alpine Linux</span>
</code></pre>
<h2 id="heading-2-list-all-images">2. List All Images</h2>
<pre><code class="lang-bash">docker images
</code></pre>
<h2 id="heading-3-remove-an-image">3. Remove an Image</h2>
<pre><code class="lang-bash">docker rmi &lt;image_id_or_name&gt;
</code></pre>
<p><strong>Example:</strong></p>
<pre><code class="lang-bash">docker rmi postgres:16
</code></pre>
<h1 id="heading-docker-commands-for-containers">Docker Commands for Containers</h1>
<h2 id="heading-1-run-a-container">1. Run a Container</h2>
<pre><code class="lang-bash">docker run &lt;image_name&gt;
</code></pre>
<p><strong>Example:</strong></p>
<pre><code class="lang-bash">docker run hello-world
</code></pre>
<h2 id="heading-2-run-with-interactive-terminal">2. Run with Interactive Terminal</h2>
<pre><code class="lang-bash">docker run -it &lt;image_name&gt; /bin/bash
</code></pre>
<p><strong>Example:</strong></p>
<pre><code class="lang-bash">docker run -it ubuntu /bin/bash
</code></pre>
<h2 id="heading-3-run-in-background-with-port-mapping">3. Run in Background with Port Mapping</h2>
<pre><code class="lang-bash">docker run -d --name &lt;custom_container_name&gt; -p &lt;host_port&gt;:&lt;container_port&gt; &lt;image_name&gt;
</code></pre>
<p><strong>Examples:</strong></p>
<pre><code class="lang-bash"><span class="hljs-comment"># Redis server</span>
docker run -d --name my-redis -p 6379:6379 redis

<span class="hljs-comment"># PostgreSQL database</span>
docker run -d --name my-postgres -p 5432:5432 -e POSTGRES_PASSWORD=mypassword postgres

<span class="hljs-comment"># MongoDB</span>
docker run -d --name my-mongo -p 27017:27017 mongo
</code></pre>
<blockquote>
<p><strong>Best Practice</strong>: Map host and container ports to the same number (e.g., 6379:6379) for consistency.</p>
</blockquote>
<h2 id="heading-4-list-running-containers">4. List Running Containers</h2>
<pre><code class="lang-bash">docker ps
</code></pre>
<h2 id="heading-5-list-all-containers-including-stopped">5. List All Containers (including stopped)</h2>
<pre><code class="lang-bash">docker ps -a
</code></pre>
<h2 id="heading-6-container-lifecycle-management">6. Container Lifecycle Management</h2>
<pre><code class="lang-bash"><span class="hljs-comment"># Stop a running container</span>
docker stop &lt;container_id_or_name&gt;

<span class="hljs-comment"># Start a stopped container</span>
docker start &lt;container_id_or_name&gt;

<span class="hljs-comment"># Restart a container</span>
docker restart &lt;container_id_or_name&gt;

<span class="hljs-comment"># Remove a container (must be stopped first)</span>
docker rm &lt;container_id_or_name&gt;

<span class="hljs-comment"># Force remove a running container</span>
docker rm -f &lt;container_id_or_name&gt;
</code></pre>
<h1 id="heading-interacting-with-active-containers">Interacting with Active Containers</h1>
<h2 id="heading-1-execute-commands-inside-a-container">1. Execute Commands Inside a Container</h2>
<pre><code class="lang-bash">docker <span class="hljs-built_in">exec</span> -it &lt;container_id_or_name&gt; bash
</code></pre>
<p><strong>Examples:</strong></p>
<pre><code class="lang-bash"><span class="hljs-comment"># Access PostgreSQL CLI</span>
docker <span class="hljs-built_in">exec</span> -it my-postgres psql -U postgres

<span class="hljs-comment"># Access Redis CLI</span>
docker <span class="hljs-built_in">exec</span> -it my-redis redis-cli

<span class="hljs-comment"># General bash access</span>
docker <span class="hljs-built_in">exec</span> -it my-container bash
</code></pre>
<h2 id="heading-2-view-container-logs">2. View Container Logs</h2>
<pre><code class="lang-bash">docker logs &lt;container_id_or_name&gt;

<span class="hljs-comment"># Follow logs in real-time</span>
docker logs -f &lt;container_id_or_name&gt;

<span class="hljs-comment"># Show last 100 lines</span>
docker logs --tail 100 &lt;container_id_or_name&gt;
</code></pre>
<h2 id="heading-3-copy-files-between-container-and-host">3. Copy Files Between Container and Host</h2>
<pre><code class="lang-bash"><span class="hljs-comment"># Copy from container to host</span>
docker cp &lt;container_id&gt;:/path/to/file ./<span class="hljs-built_in">local</span>/path

<span class="hljs-comment"># Copy from host to container</span>
docker cp ./<span class="hljs-built_in">local</span>/file &lt;container_id&gt;:/path/to/destination
</code></pre>
<h1 id="heading-practical-examples">Practical Examples</h1>
<h2 id="heading-setting-up-a-development-environment">Setting up a Development Environment</h2>
<pre><code class="lang-bash"><span class="hljs-comment"># PostgreSQL database</span>
docker run -d --name dev-postgres -p 5432:5432 -e POSTGRES_PASSWORD=dev123 postgres:16

<span class="hljs-comment"># Redis cache</span>
docker run -d --name dev-redis -p 6379:6379 redis:7-alpine

<span class="hljs-comment"># MongoDB database</span>
docker run -d --name dev-mongo -p 27017:27017 mongo:7
</code></pre>
<h2 id="heading-cleanup-commands">Cleanup Commands</h2>
<pre><code class="lang-bash"><span class="hljs-comment"># Stop all running containers</span>
docker stop $(docker ps -q)

<span class="hljs-comment"># Remove all stopped containers</span>
docker rm $(docker ps -aq)

<span class="hljs-comment"># Remove unused images</span>
docker image prune

<span class="hljs-comment"># Remove everything (use with caution!)</span>
docker system prune -a
</code></pre>
<h1 id="heading-next-steps">Next Steps</h1>
<p>Now that you understand basic Docker commands, you're ready to:</p>
<ul>
<li><p>Set up development environments quickly</p>
</li>
<li><p>Test different software versions without conflicts</p>
</li>
<li><p>Share consistent environments with your team</p>
</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Graph Theory in Data structure and Algorithms]]></title><description><![CDATA[Graphs ! an important from DSA for interview preparation point of view as it’s assumed to be most complicated topic that most learner fail to recognize patterns of questions or you can say they are not able to relate other topics like tree,matrices e...]]></description><link>https://bitwise.mrvineetraj.live/graph-theory-in-data-structure-and-algorithms</link><guid isPermaLink="true">https://bitwise.mrvineetraj.live/graph-theory-in-data-structure-and-algorithms</guid><category><![CDATA[GraphProblems]]></category><category><![CDATA[DSA]]></category><category><![CDATA[graphs]]></category><category><![CDATA[BFS]]></category><category><![CDATA[StriversA2ZDSA]]></category><category><![CDATA[DFS]]></category><category><![CDATA[spanning tree]]></category><category><![CDATA[MinimumSpanningTree]]></category><category><![CDATA[PrimsAlgorithm ]]></category><category><![CDATA[dijkstra]]></category><category><![CDATA[KruskalAlgorithm ]]></category><category><![CDATA[MST]]></category><dc:creator><![CDATA[Vineet Raj]]></dc:creator><pubDate>Tue, 20 May 2025 02:40:13 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1747708795064/7bafec3d-83f5-41fc-a316-46b646103dcd.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p><strong>Graphs !</strong> an important from DSA for interview preparation point of view as it’s assumed to be most complicated topic that most learner fail to recognize patterns of questions or you can say they are not able to relate other topics like tree,matrices etc to correlate it with graphs but but in this article we will be starting from basic and then will be going beyond basics by that i mean will try to cover all important algorithms and problems on graph theory however for problems will be writing problem title and basic idea or you can say an hint to how can you approach it and then will be attaching a link if want to see complete solution. for now solutions are in only c++</p>
<h1 id="heading-introduction">Introduction</h1>
<p>So here we are introduction to graph a <strong>non-linear</strong> data structure, or you can say non linear way to represent data</p>
<p>A graph consists of <strong>Nodes</strong> and <strong>Edges</strong></p>
<p>Further graphs are categorized in multiple types</p>
<ul>
<li><p><strong>Directed Graph :</strong> When edges are directed</p>
</li>
<li><p><strong>Weighted graph :</strong> When edges have a weight assigned to it</p>
</li>
<li><p><strong>Cyclic Graph :</strong> when nodes are connected such a way that when you start from one node you can reach that node again after traversing all the nodes</p>
</li>
<li><p><strong>Acyclic Graph :</strong> Opposite to cyclic one i.e when you can’t reach at initial node</p>
</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1747704951851/5747986b-3ddd-430c-b483-b0f52aac1496.png" alt="graph_component_and_types" class="image--center mx-auto" /></p>
<p>In above image it’s shown types of graph along with components</p>
<hr />
<h2 id="heading-intuition"><strong>Intuition</strong></h2>
<p>Consider it as a state now think of all the cities as node and roads as edge now</p>
<ul>
<li><p>If you can move on road from going cityX → cityY and cityY → cityX then it could mean graph is undirected graph because of those undirected edges</p>
</li>
<li><p>If you can go from cityX → cityY but if cityY → cityX is not possible then it means it’s undirected graph</p>
</li>
<li><p>Now if you have to pay taxes to travel on roads then it means a weighted edge or graph is a weighted graph</p>
</li>
<li><p>And if you go like cityX → cityY → cityZ → cityX : it means you can reach back to cityX without touching other cities twice <strong>A cyclic graph is here (</strong> in above figure there are cycles in undirected graph but for directed one it’s not forming a single cycle )</p>
</li>
<li><p>If no cycles then <strong>Acyclic graph</strong></p>
</li>
</ul>
<p>So you can see whatever it name suggests just add that attribute to edge or node and graph becomes that</p>
<h2 id="heading-degree-of-graph">Degree of graph</h2>
<p>$$graphDegree = \sum_{i=start}^{end} nodeDegree$$</p><p>So here <code>nodeDegree</code> means number of edges connected to <code>ith</code> node</p>
<p>For <strong>Directed Graph</strong> it could be said as</p>
<ul>
<li><p>Indegree : for incoming edge to node</p>
</li>
<li><p>outdegree : for outgoing edge to node</p>
</li>
</ul>
<p>Example :</p>
<p><img src="https://static.takeuforward.org/premium/notes/mrvineetraj/ProblemSetter-hDqnV497" alt class="image--center mx-auto" /></p>
<h2 id="heading-how-we-take-input-and-store-graphs">How we take input and store graphs ?</h2>
<p><strong>Adjacency Matrix :</strong> when we store data in a 2d matrix of size <code>n X n</code> where n is number of nodes</p>
<pre><code class="lang-cpp"> <span class="hljs-comment">// For Weighted , undirected graph</span>
{
  <span class="hljs-keyword">int</span> numberOfNodes = <span class="hljs-number">0</span>;
  <span class="hljs-built_in">cin</span> &gt;&gt; numberOfNodes;

  <span class="hljs-built_in">vector</span>&lt;<span class="hljs-keyword">int</span>&gt; adjMatrix[numberOfNodes];

  <span class="hljs-keyword">int</span> numberOfEdges = <span class="hljs-number">0</span>;
  <span class="hljs-built_in">cin</span> &gt;&gt; numberOfEdges;

  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; numberOfEdges; i++)
  {
    <span class="hljs-comment">// input in format startingNodeOfEdge , ending node of edge , weight of edge</span>
    <span class="hljs-keyword">int</span> starting, ending, weight;  <span class="hljs-comment">// for unweighted graph, edge weight is assumed 1</span>
    <span class="hljs-built_in">cin</span> &gt;&gt; starting &gt;&gt; ending &gt;&gt; weight;

    adjMatrix[starting][ending] = weight;
    adjMatrix[ending][starting] = weight; <span class="hljs-comment">// if it is a directed graph then we will not do this</span>
  }
}
</code></pre>
<blockquote>
<p><strong>Analysis</strong></p>
<p>Time Complexity : O(E)</p>
<p>Space Complexity : O(N²) {best,avg,optimal case }</p>
</blockquote>
<p><strong>Adjacency Lists :</strong> Here we store a vector mapped to every node storing the info about which nodes are connected to which node</p>
<pre><code class="lang-cpp">{
  <span class="hljs-comment">// undirected and unweighted graph</span>
  <span class="hljs-keyword">int</span> numberOfNodes = <span class="hljs-number">0</span>;
  <span class="hljs-built_in">cin</span> &gt;&gt; numberOfNodes;

  <span class="hljs-function"><span class="hljs-built_in">vector</span>&lt;<span class="hljs-built_in">vector</span>&lt;<span class="hljs-keyword">int</span>&gt;&gt; <span class="hljs-title">adjList</span><span class="hljs-params">(numberOfNodes)</span></span>;

  <span class="hljs-keyword">int</span> numberOfEdges = <span class="hljs-number">0</span>;
  <span class="hljs-built_in">cin</span> &gt;&gt; numberOfEdges;

  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; numberOfEdges; i++)
  {
    <span class="hljs-comment">// input in format startingNodeOfEdge , ending node of edge</span>
    <span class="hljs-keyword">int</span> starting, ending; 
    <span class="hljs-built_in">cin</span> &gt;&gt; starting &gt;&gt; ending;

    adjList[starting].push_back(ending);
    adjList[ending].push_back(starting);  <span class="hljs-comment">// if it is a directed graph then we will not do this</span>
  }
}
</code></pre>
<blockquote>
<p><strong>Analysis</strong></p>
<p>Time Complexity : O(E)</p>
<p>Space Complexity : O(N²) {worst case : when all the nodes are connected to each other }</p>
<p>Implement adjList for weighted graphs</p>
</blockquote>
<p>Hint ????</p>
<p>For a weighted graph instead of mapping nodes with each node we could have mapped it with pair of node and it’s weight</p>
<hr />
<h1 id="heading-algorithms-related-to-graphs">Algorithms related to graphs</h1>
<blockquote>
<p>Note : Just remember if applying graph you would need an <code>Array to track visited nodes</code> a <code>queue</code> or a <code>stack</code></p>
</blockquote>
<h2 id="heading-traversal-technique-breadth-first-search-bfs">Traversal Technique : Breadth First Search ( BFS )</h2>
<p><strong>Focus on word breadth !</strong></p>
<p>It means</p>
<ul>
<li><p>if we arrive at any node then we will go through each and every neighbour node first say neighbours are at level 1</p>
</li>
<li><p>then we get back to first neighbour</p>
</li>
<li><p>Now we apply step one with assuming the first neighbour at level 1 is our starting node</p>
</li>
<li><p>We travers all node at level 2 now when done</p>
</li>
<li><p>when we traverse back we go back to the second neighbour of level 1</p>
</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1747708570906/29ee73bb-04c0-4291-a4e6-bd27aed212e3.png" alt class="image--center mx-auto" /></p>
<p><strong>Implementation</strong></p>
<pre><code class="lang-cpp">
   <span class="hljs-function"><span class="hljs-built_in">vector</span>&lt;<span class="hljs-keyword">int</span>&gt; <span class="hljs-title">bfsOfGraph</span><span class="hljs-params">(<span class="hljs-keyword">int</span> V, <span class="hljs-built_in">vector</span>&lt;<span class="hljs-keyword">int</span>&gt; adj[])</span> </span>{
        <span class="hljs-comment">// to keep track of visited nodes</span>
        <span class="hljs-function"><span class="hljs-built_in">vector</span>&lt;<span class="hljs-keyword">bool</span>&gt; <span class="hljs-title">visited</span><span class="hljs-params">(V,<span class="hljs-literal">false</span>)</span></span>;
        <span class="hljs-built_in">vector</span>&lt;<span class="hljs-keyword">int</span>&gt; ans;

        <span class="hljs-comment">// this loop will take care of disconnetcted components</span>
        <span class="hljs-keyword">for</span>(<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; V; i++){
            <span class="hljs-comment">// if a node is not visited means there is one graph component is there which is not traversed</span>
            <span class="hljs-keyword">if</span>(!visited[i]){
                <span class="hljs-comment">//to cover that one component</span>
                <span class="hljs-built_in">queue</span>&lt;<span class="hljs-keyword">int</span>&gt; q;
                q.push(i); <span class="hljs-comment">// assumed that one unvisited node as source node</span>
                ans.push_back(i);
                visited[i] = <span class="hljs-literal">true</span>;

                <span class="hljs-comment">// now traversing it's negihbouring nodes</span>
                <span class="hljs-keyword">while</span>(!q.empty()){
                    <span class="hljs-keyword">int</span> currNode = q.front();
                    q.pop();

                    <span class="hljs-keyword">for</span>(<span class="hljs-keyword">auto</span> it:adj[currNode]){
                        <span class="hljs-keyword">if</span>(!visited[it]){
                            q.push(it);
                            ans.push_back(it);
                            visited[it] = <span class="hljs-literal">true</span>;
                        }
                    }
                }
            }
        }

        <span class="hljs-keyword">return</span> ans;
    }
</code></pre>
<hr />
<h2 id="heading-traversal-technique-depth-first-search">Traversal Technique : Depth First Search</h2>
<p>Focus on word <strong>Depth</strong></p>
<p>It means we will do something like inorder traversal of tree, i.e</p>
<ul>
<li><p>Will take a source node</p>
</li>
<li><p>go to it’s first neighbouring node which is not visited</p>
</li>
<li><p>Will assume it is our source node and then will go to it’s first not visited neighbouring node</p>
</li>
<li><p>and will keep going to depth till we don’t get neighbouring nodes</p>
</li>
<li><p>and then when we don’t have any node to visit we trace back</p>
</li>
<li><p>and try to cover other non visited nodes</p>
</li>
</ul>
<pre><code class="lang-cpp">    <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">dfs</span><span class="hljs-params">(
        <span class="hljs-keyword">int</span> node,
        <span class="hljs-built_in">vector</span>&lt;<span class="hljs-keyword">int</span>&gt; adj[],
        <span class="hljs-built_in">vector</span>&lt;<span class="hljs-keyword">bool</span>&gt; &amp;visited,
        <span class="hljs-built_in">vector</span>&lt;<span class="hljs-keyword">int</span>&gt; &amp;traversal
    )</span></span>{
        visited[node] = <span class="hljs-literal">true</span>;

        traversal.push_back(node);

        <span class="hljs-keyword">for</span>(<span class="hljs-keyword">auto</span> it:adj[node]){
            <span class="hljs-keyword">if</span>(!visited[it]){
                <span class="hljs-comment">// calling the recursionjust after finding , first unvisited node</span>
                dfs(it,adj,visited,traversal);
            }
        }
    }

<span class="hljs-comment">// got number of node and adj list as input to the function</span>
    <span class="hljs-function"><span class="hljs-built_in">vector</span>&lt;<span class="hljs-keyword">int</span>&gt; <span class="hljs-title">dfsOfGraph</span><span class="hljs-params">(<span class="hljs-keyword">int</span> V, <span class="hljs-built_in">vector</span>&lt;<span class="hljs-keyword">int</span>&gt; adj[])</span> </span>{
        <span class="hljs-function"><span class="hljs-built_in">vector</span>&lt;<span class="hljs-keyword">bool</span>&gt; <span class="hljs-title">visited</span><span class="hljs-params">(V,<span class="hljs-literal">false</span>)</span></span>;
        <span class="hljs-built_in">vector</span>&lt;<span class="hljs-keyword">int</span>&gt; traversal;
        <span class="hljs-comment">// traversing visited array to track unvisted graph nodes</span>
        <span class="hljs-keyword">for</span>(<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; V;i++){
            <span class="hljs-keyword">if</span>(!visited[i]){
                <span class="hljs-comment">// for unvisted node </span>
                <span class="hljs-comment">// taking it as a source and traversing the graph such that it visits all connected nodes</span>
                dfs(i,adj,visited,traversal);
            }
        }
        <span class="hljs-keyword">return</span> traversal;
    }
</code></pre>
<hr />
<h2 id="heading-topological-sorting-using-dfs-and-stack">Topological Sorting : using DFS and stack</h2>
<blockquote>
<p>Topological order is in which if node u is connected to node v then u must appear before node v, no matter how earlier but must be earlier then node v</p>
<p>Note : It is only possible for a directed acyclic graph ( DAG ) , as for others it will not be possible to print the order</p>
</blockquote>
<p>Here we are just</p>
<ul>
<li><p>using a stack that will keep track of nodes in which they are traversed</p>
</li>
<li><p>Last or terminal node will be inserted into stack first as we are <strong>inserting node after DFS is complete</strong></p>
</li>
<li><p>Later will just omit the stack and will print their order in which stack popped the set of nodes</p>
</li>
</ul>
<pre><code class="lang-cpp">    <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">dfs</span><span class="hljs-params">(<span class="hljs-keyword">int</span> node,<span class="hljs-built_in">vector</span>&lt;<span class="hljs-keyword">int</span>&gt; adj[],<span class="hljs-built_in">stack</span> &lt;<span class="hljs-keyword">int</span>&gt; &amp;st,<span class="hljs-keyword">int</span> vis[])</span></span>{
        vis[node] = <span class="hljs-number">1</span>;
        <span class="hljs-keyword">for</span>(<span class="hljs-keyword">auto</span> it:adj[node]){
            <span class="hljs-keyword">if</span>(!vis[it])  dfs(it,adj,st,vis);
        }
        <span class="hljs-comment">// normal DFS with this additional stack call</span>
        st.push(node);
    }
    <span class="hljs-function"><span class="hljs-built_in">vector</span>&lt;<span class="hljs-keyword">int</span>&gt; <span class="hljs-title">dfsTopo</span><span class="hljs-params">(<span class="hljs-keyword">int</span> V,<span class="hljs-built_in">vector</span>&lt;<span class="hljs-keyword">int</span>&gt; adj[])</span></span>{
        <span class="hljs-keyword">int</span> vis[V] = {<span class="hljs-number">0</span>};
        <span class="hljs-built_in">stack</span>&lt;<span class="hljs-keyword">int</span>&gt; st;

        <span class="hljs-comment">// traversing like normal DFS but with additional argument of stack</span>
        <span class="hljs-keyword">for</span>(<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; V; i++){
            <span class="hljs-keyword">if</span>(vis[i] == <span class="hljs-number">0</span>){
                dfs(i,adj,st,vis);
            }
        }

        <span class="hljs-comment">// storing ther order when Traversal is completed</span>
        <span class="hljs-built_in">vector</span>&lt;<span class="hljs-keyword">int</span>&gt; order;
        <span class="hljs-keyword">while</span>(!st.empty()){
            order.push_back(st.top());
            st.pop();
        }

        <span class="hljs-keyword">return</span> order;
    }
</code></pre>
<hr />
<h2 id="heading-topological-sorting-khans-algo-using-bfs">Topological Sorting : Khan’s Algo. ( using BFS )</h2>
<blockquote>
<p>Topological order is in which if node u is connected to node v then u must appear before node v, no matter how earlier but must be earlier then node v</p>
<p>Note : It is only possible for a directed acyclic graph ( DAG ) , as for others it will not be possible to print the order</p>
</blockquote>
<p>Here additional ideas are</p>
<ul>
<li><p>Store count of indegree edges as if it i zero means there are not any other node on which current node depends</p>
</li>
<li><p>And if a node does not depends on any other node then it means</p>
<ul>
<li><p>The node is root node</p>
</li>
<li><p>Parent nodes are already processed</p>
</li>
</ul>
</li>
<li><p>Hence we can start processing and recording those nodes with zero indegree</p>
</li>
<li><p><strong>rest is simple BFS</strong></p>
</li>
</ul>
<pre><code class="lang-cpp"> <span class="hljs-function"><span class="hljs-built_in">vector</span>&lt;<span class="hljs-keyword">int</span>&gt; <span class="hljs-title">khansAlgo</span><span class="hljs-params">(<span class="hljs-keyword">int</span> V,<span class="hljs-built_in">vector</span>&lt;<span class="hljs-keyword">int</span>&gt; adj[])</span></span>{
        <span class="hljs-comment">// to track indegree edges to track if a node is depends on other node</span>
        <span class="hljs-keyword">int</span> indegreeEdges[V] = {<span class="hljs-number">0</span>};
        <span class="hljs-keyword">int</span> vis[V] = {<span class="hljs-number">0</span>};

        <span class="hljs-keyword">for</span>(<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; V;i++){
            <span class="hljs-keyword">for</span>(<span class="hljs-keyword">auto</span> node:adj[i]){
                indegreeEdges[node]++;
            }
        }

        <span class="hljs-built_in">vector</span>&lt;<span class="hljs-keyword">int</span>&gt; ans;

        <span class="hljs-comment">// normal bfs with addition of indegreeEdges array </span>
        <span class="hljs-built_in">queue</span>&lt;<span class="hljs-keyword">int</span>&gt; q;
        <span class="hljs-keyword">for</span>(<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; V; i++){
            <span class="hljs-keyword">if</span>(indegreeEdges[i] == <span class="hljs-number">0</span>){
                q.push(i);
                vis[i] = <span class="hljs-number">1</span>;
            }
        }

        <span class="hljs-keyword">while</span>(!q.empty()){
            <span class="hljs-keyword">int</span> currNode = q.front();

            ans.push_back(currNode);
            q.pop();

            <span class="hljs-keyword">for</span>(<span class="hljs-keyword">int</span> it:adj[currNode]){
                <span class="hljs-keyword">if</span>(!vis[it]){
                    indegreeEdges[it]--;
                    <span class="hljs-keyword">if</span>(indegreeEdges[it] == <span class="hljs-number">0</span>){
                        q.push(it);
                        vis[it]=<span class="hljs-number">1</span>;
                    }
                }
            }
        }

        <span class="hljs-keyword">return</span> ans;
    }
</code></pre>
<hr />
<h2 id="heading-disjoint-set-union">Disjoint Set Union</h2>
<blockquote>
<p>» Why ?</p>
<p>» Because , sometime we don’t have to print path between two nodes we just have to tell that if a path is possible or not. And BFS or DFS takes significant time for doing this like O(E+V) time complexity for processing each of the pair so if n pair then <code>O(n*(E + V ) )</code> which is waste here because we just had to say yes or no for weather path exist or not</p>
</blockquote>
<p>Here Comes the <strong>Disjoint Set Union</strong> in picture that takes constant time or <code>O( 4 * alpha )</code> Time complxity where alpha is almost equal to 1 hence <strong>Constant Time</strong></p>
<p><strong>How it Works ?</strong></p>
<p>It stores the parent or ultimate parent of each node and say if ultimate parent of both nodes is different than it says path not possible else it’s possible</p>
<p>And for parent it is decided based on rank of each node or size of each node like</p>
<ul>
<li><p>if size_u &gt; size_v</p>
<ul>
<li>u will be parent of v</li>
</ul>
</li>
<li><p>if size_u == size_v</p>
<ul>
<li><p>any one can become anyone’s parent but</p>
</li>
<li><p>one that became parent , you must increase it’s rank or size by one.</p>
</li>
</ul>
</li>
</ul>
<p>» keep in mind that we never compare parent we compare parents of parent until node becomes parent of itself or you can say ultimate parent of node</p>
<p>» <mark>We can even store ultimate parent of node in our parent array as we don’t need to know direct parent we just want to know root of that cluster or tree or whatever data structure it’s forming, and when we store ultimate parent directly it is called </mark> <strong><mark>Path Compression</mark></strong></p>
<p><strong>How to use it ?</strong></p>
<p>Basically it’s a class that comes with 5 function or methods</p>
<ul>
<li><p><strong>DisjointSet(int n) :</strong> it initializes required arrays and fills in req. values</p>
</li>
<li><p><strong>findUPar(int u)</strong> : it returns ultimate parent of <strong>u</strong></p>
</li>
<li><p><strong>find(int u, int v) :</strong> it returns a boolean value for weather u and v are connected by a path or not</p>
</li>
<li><p><strong>unionByRank(int u, int v) :</strong> it joins clusters whose roots are node u and node v based on there rank</p>
</li>
<li><p><strong>unionBySize(int u, int v) :</strong> it joins clusters whose roots are node u and node v based on there size</p>
</li>
</ul>
<pre><code class="lang-cpp"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">DisjointSet</span> {</span>
    <span class="hljs-built_in">vector</span>&lt;<span class="hljs-keyword">int</span>&gt; rank,parent,size;

<span class="hljs-keyword">public</span>:
    DisjointSet(<span class="hljs-keyword">int</span> n) {
        rank.resize(n+<span class="hljs-number">1</span>,<span class="hljs-number">0</span>);
        parent.resize(n+<span class="hljs-number">1</span>);       
        size.resize(n + <span class="hljs-number">1</span>, <span class="hljs-number">1</span>);
        <span class="hljs-keyword">for</span>(<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>;i &lt; n;i++){
            parent[i] = i;
        }
    }

    <span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">findUPar</span><span class="hljs-params">(<span class="hljs-keyword">int</span> node)</span></span>{
        <span class="hljs-keyword">if</span>(node == parent[node])
            <span class="hljs-keyword">return</span> node;

        <span class="hljs-keyword">return</span> parent[node] = findUPar(parent[node]);
    }

    <span class="hljs-function"><span class="hljs-keyword">bool</span> <span class="hljs-title">find</span><span class="hljs-params">(<span class="hljs-keyword">int</span> u, <span class="hljs-keyword">int</span> v)</span> </span>{
        <span class="hljs-keyword">return</span> (findUPar(u) == findUPar(v));
    }

    <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">unionByRank</span><span class="hljs-params">(<span class="hljs-keyword">int</span> u, <span class="hljs-keyword">int</span> v)</span> </span>{
        <span class="hljs-keyword">int</span> ulp_u = findUPar(u);
        <span class="hljs-keyword">int</span> ulp_v = findUPar(v);

        <span class="hljs-keyword">if</span>(ulp_u == ulp_v) <span class="hljs-keyword">return</span>;

        <span class="hljs-keyword">if</span>(rank[ulp_u] &lt; rank[ulp_v]){
            parent[ulp_u] = ulp_v;
        }<span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span>(rank[ulp_u] &gt; rank[ulp_v]){
            parent[ulp_v] = ulp_u;
        }<span class="hljs-keyword">else</span>{
            parent[ulp_v] = ulp_u;
            rank[ulp_u]++;
        }
    }

    <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">unionBySize</span><span class="hljs-params">(<span class="hljs-keyword">int</span> u, <span class="hljs-keyword">int</span> v)</span> </span>{
        <span class="hljs-keyword">int</span> ulp_u = findUPar(u);
       <span class="hljs-keyword">int</span> ulp_v = findUPar(v);

       <span class="hljs-keyword">if</span> (ulp_u == ulp_v) <span class="hljs-keyword">return</span>;

       <span class="hljs-keyword">if</span> (size[ulp_u] &lt; size[ulp_v]) {
           parent[ulp_u] = ulp_v;

           size[ulp_v] += size[ulp_u];
       }
       <span class="hljs-keyword">else</span> {
           parent[ulp_v] = ulp_u;
           size[ulp_u] += size[ulp_v];

       }
    }
};
</code></pre>
<hr />
<h2 id="heading-spanning-tree">Spanning Tree</h2>
<blockquote>
<p>A <strong>spanning tree</strong> is a subset of a</p>
<ul>
<li><p>weighted graph</p>
</li>
<li><p>in which there are N nodes(i.e. all the nodes present in the original graph) and</p>
</li>
<li><p>N-1 edges and</p>
</li>
<li><p>all nodes are reachable from each other.</p>
</li>
</ul>
</blockquote>
<p>Example</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1748081129507/d93e56c8-efd2-4ac4-9324-7403ebe997a7.png" alt class="image--center mx-auto" /></p>
<p>For above graph below is a possible spanning tree</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1748081149894/882a18b7-2c91-4169-8568-7f4698a6745b.png" alt class="image--center mx-auto" /></p>
<p>» <strong>Note :</strong> If we draw all possible spanning trees and compared the sum of there edge weights then spanning tree with minimum sum of edge weights is called a <strong>Minimum Spanning Tree or MST</strong></p>
<hr />
<h2 id="heading-minimum-spanning-tree-prims-algo">Minimum Spanning Tree : Prim’s Algo.</h2>
<p>It is same as doing BFS on a connected graph as a Spanning tree exist only for connected graphs</p>
<p>Difference with BFS is</p>
<ul>
<li><p>Instead of queue we use priority queue ( min-heap )</p>
</li>
<li><p>It helps us to visit a node only when reachable at minimum cost from certain node</p>
</li>
</ul>
<pre><code class="lang-cpp"> <span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">primsMST</span><span class="hljs-params">(<span class="hljs-keyword">int</span> V, <span class="hljs-built_in">vector</span>&lt;<span class="hljs-built_in">vector</span>&lt;<span class="hljs-keyword">int</span>&gt;&gt; adj[])</span> </span>{
        <span class="hljs-comment">// your min heap that will record all the nodes with wt from parent </span>
       <span class="hljs-built_in">priority_queue</span>&lt;P,<span class="hljs-built_in">vector</span>&lt;P&gt;,greater&lt;P&gt;&gt; pq;  <span class="hljs-comment">// {weight, node} </span>
       pq.push({<span class="hljs-number">0</span>,<span class="hljs-number">0</span>}); <span class="hljs-comment">// inserted first node as it's wt from parent will be 0 as no parent initally</span>

       <span class="hljs-keyword">int</span> sum = <span class="hljs-number">0</span>;
       <span class="hljs-function"><span class="hljs-built_in">vector</span>&lt;<span class="hljs-keyword">bool</span>&gt; <span class="hljs-title">vis</span><span class="hljs-params">(V,<span class="hljs-literal">false</span>)</span></span>; <span class="hljs-comment">// visited array to keep track of node taht are vsted once</span>
       <span class="hljs-keyword">while</span>(!pq.empty()){
            <span class="hljs-keyword">int</span> wt = pq.top().first;
            <span class="hljs-keyword">int</span> node = pq.top().second;

            pq.pop(); <span class="hljs-comment">// popping element of smallest wt from it's parent</span>

            <span class="hljs-comment">// if node is visted previously means we recorded an edge with </span>
            <span class="hljs-comment">// comarativly smaller weight and hence we will not record the current edge and will pop it out</span>
            <span class="hljs-keyword">if</span>(vis[node]) <span class="hljs-keyword">continue</span>; 

            <span class="hljs-comment">// if it was not recorded previously means it's the shortest edge weight possible</span>
            vis[node] = <span class="hljs-literal">true</span>;
            sum+=wt; <span class="hljs-comment">// record th weight</span>

            <span class="hljs-comment">// push neighbour node with wt according to dist between neighours and current node as it's parent</span>
            <span class="hljs-keyword">for</span>(<span class="hljs-keyword">auto</span> it:adj[node]){
                <span class="hljs-keyword">if</span>(!vis[it[<span class="hljs-number">0</span>]]){
                    pq.push({it[<span class="hljs-number">1</span>],it[<span class="hljs-number">0</span>]}); <span class="hljs-comment">// if neighbour is unvisted then push it in min-heap</span>
                }
            }
       }

       <span class="hljs-keyword">return</span> sum;
    }
</code></pre>
<hr />
<h2 id="heading-minimum-spanning-tree-kruskal-algo">Minimum Spanning Tree : Kruskal Algo.</h2>
<ul>
<li>For this we use <strong>DisjointSet</strong> ( already discussed in article )</li>
</ul>
<pre><code class="lang-cpp"><span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">kruskalMST</span><span class="hljs-params">(<span class="hljs-keyword">int</span> V,<span class="hljs-built_in">vector</span>&lt;<span class="hljs-built_in">vector</span>&lt;<span class="hljs-keyword">int</span>&gt;&gt; adj[])</span></span>{
        <span class="hljs-built_in">vector</span>&lt;<span class="hljs-built_in">pair</span>&lt;<span class="hljs-keyword">int</span>, <span class="hljs-built_in">pair</span>&lt;<span class="hljs-keyword">int</span>, <span class="hljs-keyword">int</span>&gt;&gt;&gt; edges;
        <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; V; i++) {
            <span class="hljs-keyword">for</span> (<span class="hljs-keyword">auto</span> it : adj[i]) {
                <span class="hljs-keyword">int</span> v = it[<span class="hljs-number">0</span>]; 
                <span class="hljs-keyword">int</span> wt = it[<span class="hljs-number">1</span>];
                <span class="hljs-keyword">int</span> u = i;
                edges.push_back({wt, {u, v}});
            }
        }

        <span class="hljs-function">DisjointSet <span class="hljs-title">ds</span><span class="hljs-params">(V)</span></span>;
        sort(edges.begin(), edges.end());
        <span class="hljs-keyword">int</span> sum = <span class="hljs-number">0</span>;

        <span class="hljs-keyword">for</span> (<span class="hljs-keyword">auto</span> it : edges) {
            <span class="hljs-keyword">int</span> wt = it.first; 
            <span class="hljs-keyword">int</span> u = it.second.first; 
            <span class="hljs-keyword">int</span> v = it.second.second; 

            <span class="hljs-keyword">if</span> (ds.findUPar(u) != ds.findUPar(v)) {
                sum += wt;
                ds.unionBySize(u, v);
            }
        }

        <span class="hljs-keyword">return</span> sum;
    }
</code></pre>
<hr />
<h1 id="heading-problems">Problems</h1>
<h2 id="heading-number-of-provinces-codehttpsgithubcommrvineetrajdsa-cppblobmaingraphs0120number20of20provincesmd">Number of provinces : <a target="_blank" href="https://github.com/MrVineetRaj/dsa-cpp/blob/main/graphs/01%20Number%20of%20provinces.md"><code>code</code></a></h2>
<p>Same as BFS or DFS</p>
<ul>
<li><p>Just with additional counter</p>
</li>
<li><p>Increment counter when going to traverse new component</p>
</li>
</ul>
<h2 id="heading-number-of-islands-codehttpsgithubcommrvineetrajdsa-cppblobmaingraphs0220number20of20islandsmd">Number of islands : <a target="_blank" href="https://github.com/MrVineetRaj/dsa-cpp/blob/main/graphs/02%20Number%20of%20islands.md"><code>code</code></a></h2>
<p>Simple traversal but with</p>
<ul>
<li><p>queue that show cell address like <code>{row,col}</code> means queue of pair&lt;int,int&gt;</p>
</li>
<li><p>And it’s adj node would be based on delta values from below array</p>
</li>
</ul>
<pre><code class="lang-cpp">    <span class="hljs-keyword">int</span> dRow[] = {<span class="hljs-number">-1</span>, <span class="hljs-number">-1</span>, <span class="hljs-number">-1</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>};
    <span class="hljs-keyword">int</span> dCol[] = {<span class="hljs-number">-1</span>, <span class="hljs-number">0</span>, <span class="hljs-number">1</span>, <span class="hljs-number">-1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">-1</span>, <span class="hljs-number">0</span>, <span class="hljs-number">1</span>};
</code></pre>
<h2 id="heading-flood-fill-algorithm-codehttpsgithubcommrvineetrajdsa-cppblobmaingraphs0320flood20fill20algorithmmd">Flood fill algorithm : <a target="_blank" href="https://github.com/MrVineetRaj/dsa-cpp/blob/main/graphs/03%20Flood%20fill%20algorithm.md"><code>code</code></a></h2>
<p>Simple traversal</p>
<ul>
<li><p>Here we don’t need any visited array</p>
</li>
<li><p>just use given image matrix it self</p>
</li>
<li><p>if given new color is same as initial color means already satisfied so we will just return</p>
</li>
<li><p>Allowed directions</p>
</li>
<li><pre><code class="lang-cpp">          <span class="hljs-keyword">int</span> dRow[] = {<span class="hljs-number">-1</span>, <span class="hljs-number">-1</span>, <span class="hljs-number">-1</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>}; 
          <span class="hljs-keyword">int</span> dCol[] = {<span class="hljs-number">-1</span>, <span class="hljs-number">0</span>, <span class="hljs-number">1</span>, <span class="hljs-number">-1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">-1</span>, <span class="hljs-number">0</span>, <span class="hljs-number">1</span>};
</code></pre>
</li>
</ul>
<h2 id="heading-number-of-enclaves-codehttpsgithubcommrvineetrajdsa-cppblobmaingraphs0420number20of20enclavesmd">Number of enclaves : <a target="_blank" href="https://github.com/MrVineetRaj/dsa-cpp/blob/main/graphs/04%20Number%20of%20enclaves.md"><code>code</code></a></h2>
<p>Question asks return number of cells from which we can’t get on boundary for any number of steps in 4 direction</p>
<ul>
<li><p>Just apply BFS or DFS on possible boundary land cells</p>
</li>
<li><p>And it will mark all the cell visited, where we can reach from boundary</p>
</li>
<li><p>For cells that we can’t return their number</p>
</li>
</ul>
<h2 id="heading-rotten-oranges-codehttpsgithubcommrvineetrajdsa-cppblobmaingraphs0520rotten20orangesmd">Rotten Oranges : <a target="_blank" href="https://github.com/MrVineetRaj/dsa-cpp/blob/main/graphs/05%20Rotten%20Oranges.md"><code>code</code></a></h2>
<p>Question says if an orange is rotten then it will rot other fresh oranges in horizontal and vertical direction in one minute so return the total time taken to rot all fresh oranges</p>
<ul>
<li><p>Must be a graph such that in all of his component atleast one rotten orange must exist</p>
</li>
<li><p>BFS would be required with source node as rotten oranges at time t = 0</p>
</li>
<li><p>It’s queue will be tracking time at which inserted orange was rotten</p>
</li>
<li><p>And for BFS insert all the rotten oranges in the queue before processing BFS</p>
</li>
<li><p>As every rotten orange at a moment will simultaneously rot other connected fresh oranges</p>
</li>
<li><p>At every insertion of rotten orange you have to increment the time at which his parent was rotten</p>
</li>
</ul>
<h2 id="heading-distance-of-nearest-cell-having-one-codehttpsgithubcommrvineetrajdsa-cppblobmaingraphs0620distance20of20nearest20cell20having20onemd">Distance of nearest cell having one : <a target="_blank" href="https://github.com/MrVineetRaj/dsa-cpp/blob/main/graphs/06%20Distance%20of%20nearest%20cell%20having%20one.md"><code>code</code></a></h2>
<p>Same as Rotten Orange but instead of time here you have to store currDist</p>
<ul>
<li><p>Firstly insert all the available ones in queue and that’s done</p>
</li>
<li><p>now just apply bfs with that queue and a visted array</p>
</li>
</ul>
<h2 id="heading-surrounded-regions-codehttpsgithubcommrvineetrajdsa-cppblobmaingraphs0720surrounded20regionsmd">Surrounded Regions : <a target="_blank" href="https://github.com/MrVineetRaj/dsa-cpp/blob/main/graphs/07%20Surrounded%20Regions.md"><code>code</code></a></h2>
<p>Question says return a matrix after converting all the ‘O’s as ‘X’ if the set from which that ’O’ belong is surrounded by ‘X’</p>
<p><strong>Intiution</strong></p>
<p>Just see boundary ‘O’s are not surrounded by ‘X’ so just consider those ‘O’s and traverse on matrix assuming those ‘O’s as source and for every other ‘O’ that could be approached will be marked as ‘O’s in set which not surrounded by ‘X’ and for other ‘O’s just convert them to ‘X’</p>
<h2 id="heading-number-of-distinct-islands-codehttpsgithubcommrvineetrajdsa-cppblobmaingraphs0820number20of20distinct20islandsmd">Number of distinct Islands : <a target="_blank" href="https://github.com/MrVineetRaj/dsa-cpp/blob/main/graphs/08%20Number%20of%20distinct%20islands.md"><code>code</code></a></h2>
<p>In question it says distinct islands by which it means they must be distinct in their orientation too</p>
<p>example</p>
<p>Below matrix has only 3 distinct islands</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1748095509689/71584a9d-bedf-4dac-a681-c5947b1aabca.png" alt class="image--center mx-auto" /></p>
<p>Below matrix has only 1 distinct islands</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1748095571236/f600f18c-c5a7-45d3-a5be-f45700f98654.png" alt class="image--center mx-auto" /></p>
<p><strong>Intiution</strong></p>
<p>Unique → use set</p>
<ul>
<li><p>For Solving this question you can use BFS and insert the node to temp array</p>
</li>
<li><p>insert that temp array into a set</p>
</li>
<li><p>but before inserting that temp array make sure you converted it’s top - left element as base {2,3} → {0,0} and now relative address of othr cell of that island would be {2,4},{3,3},{3,4} to {0,1},{1,0} and {1,1}</p>
</li>
<li><p>Now sort the temp array and then insert it to set</p>
</li>
<li><p>return size of set as your ans</p>
</li>
</ul>
<h2 id="heading-detect-a-cycle-in-an-undirected-graph-codehttpsgithubcommrvineetrajdsa-cppblobmaingraphs0920detect20a20cycle20in20an20undirected20graphmd">Detect a cycle in an undirected graph : <a target="_blank" href="https://github.com/MrVineetRaj/dsa-cpp/blob/main/graphs/09%20Detect%20a%20cycle%20in%20an%20undirected%20graph.md"><code>code</code></a></h2>
<p>In undirected graph it is really easy to detect a cycle</p>
<ul>
<li>as if a node going to visit a nnode [nnonde =&gt; neighbour node] but if that nnode says it’s already visited but if that nnode was not the parent of the node which means someone else visited the node so it is a cycle</li>
</ul>
<h2 id="heading-detect-a-cycle-in-an-directed-graph-codehttpsgithubcommrvineetrajdsa-cppblobmaingraphs1120detect20a20cycle20in20a20directed20graphmd">Detect a cycle in an directed graph : <a target="_blank" href="https://github.com/MrVineetRaj/dsa-cpp/blob/main/graphs/11%20Detect%20a%20cycle%20in%20a%20directed%20graph.md"><code>code</code></a></h2>
<p>Now here the confusion comes like if a node is visited and it’s not a parent to current node that does not mean it’s a cycle as here it’s directed from node to nnode right ?</p>
<p>So here we can apply <strong>DFS</strong> ( as it goes in straight line ( in depth ) )</p>
<ul>
<li><p>We will be also keeping a pathtraversed array that will keep track if a visited node is from same path on which i am running</p>
</li>
<li><p>That is when i am going in depth i have to mark pathTraversed as 1 and when i am backtracking i have to keep converting pathTraversed back to 0</p>
</li>
<li><p>and hence if i reach a node which is visited also for which pathTraversed is 1</p>
</li>
<li><p>Means i did encountered that node in same path and again i am here so it is a cycle</p>
</li>
<li><p>therefore return true</p>
</li>
</ul>
<hr />
<p>I am Vineet Raj on a journey to complete DSA in depth and I am writing such article for every topic so if you want to revise complete topic from single article you would love my articles !</p>
]]></content:encoded></item><item><title><![CDATA[Docker Installation Guide]]></title><description><![CDATA[If you are not able to install docker or for running docker commands you have to use sudo or even if you downloaded few images from docker and yet not able to see them in docker desktop…
Then you are at right place here in this article I will discuss...]]></description><link>https://bitwise.mrvineetraj.live/docker-installation-guide</link><guid isPermaLink="true">https://bitwise.mrvineetraj.live/docker-installation-guide</guid><category><![CDATA[ChaiCode]]></category><category><![CDATA[Docker]]></category><category><![CDATA[install-docker-ubuntu]]></category><dc:creator><![CDATA[Vineet Raj]]></dc:creator><pubDate>Wed, 07 May 2025 01:37:16 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1746581763546/91d47391-c177-48c9-953e-f7792c9fded4.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>If you are <strong>not able to install docker</strong> or for running docker commands you <strong>have to use</strong> <code>sudo</code> or even if you downloaded few <strong>images from docker and yet not able to see them in docker desktop</strong>…</p>
<p>Then you are at right place here in this article I will discuss these problems and why it might not be working for you and what’s the solution</p>
<p>I will be focusing on <code>LINUX</code> OS how ever if you are in virtual machine or may be trying to run on <code>wsl</code> and getting these errors then follow the article you are going to understand root cause of it and will be able to solve it</p>
<hr />
<h1 id="heading-docker-installation">Docker Installation</h1>
<p>There are many ways to install to docker as mentioned on there docs</p>
<ul>
<li><p>Docker Engine</p>
</li>
<li><p>Docker Desktop</p>
</li>
</ul>
<p>And many other option that you may want to install but for this article let’s focus on these two</p>
<p>After running commands from there official docs for <a target="_blank" href="https://docs.docker.com/engine/install/ubuntu/">installation</a> you will find this one command</p>
<pre><code class="lang-bash"><span class="hljs-comment"># Add Docker's official GPG key:</span>
sudo apt-get update
sudo apt-get install ca-certificates curl 
sudo install -m 0755 -d /etc/apt/keyrings 
sudo curl -fsSL https://download.docker.com/linux/ubuntu/gpg -o /etc/apt/keyrings/docker.asc
sudo chmod a+r /etc/apt/keyrings/docker.asc

<span class="hljs-comment"># Add the repository to Apt sources:</span>
<span class="hljs-built_in">echo</span> \
  <span class="hljs-string">"deb [arch=<span class="hljs-subst">$(dpkg --print-architecture)</span> signed-by=/etc/apt/keyrings/docker.asc] https://download.docker.com/linux/ubuntu \
  <span class="hljs-subst">$(. /etc/os-release &amp;&amp; echo <span class="hljs-string">"<span class="hljs-variable">${UBUNTU_CODENAME:-<span class="hljs-variable">$VERSION_CODENAME</span>}</span>"</span>)</span> stable"</span> | \
  sudo tee /etc/apt/sources.list.d/docker.list &gt; /dev/null
sudo apt-get update
</code></pre>
<pre><code class="lang-bash">sudo apt-get install docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin
</code></pre>
<p>Now when you run this command you get the <strong>docker-engine for you OS</strong> mark that Point <strong><em>for your whole OS not just current user</em></strong></p>
<p>Another method docker desktop you can download it from <a target="_blank" href="https://docs.docker.com/desktop/">here</a></p>
<p>For Ubuntu Commands are</p>
<pre><code class="lang-bash">sudo apt install gnome-terminal
</code></pre>
<pre><code class="lang-bash">sudo apt-get update
sudo apt-get install ./docker-desktop-amd64.deb
</code></pre>
<blockquote>
<p>You may get error like below at end and it’s normal just ignore it</p>
<pre><code class="lang-bash">N: Download is performed unsandboxed as root, as file <span class="hljs-string">'/home/user/Downloads/docker-desktop.deb'</span> couldn<span class="hljs-string">'t be accessed by user '</span>_apt<span class="hljs-string">'. - pkgAcquire::Run (13: Permission denied)</span>
</code></pre>
</blockquote>
<p>Now Start you docker</p>
<pre><code class="lang-bash">systemctl --user start docker-desktop
</code></pre>
<h1 id="heading-why-sudo-everytime">Why <code>sudo</code> everytime ?</h1>
<p>So when you download docker engine it’s for you Whole OS and If it is for you OS not just current user then to control it you must have to give permission to read and write at OS level with <code>sudo</code> keyword and when you install <code>Docker Desktop</code> it gets downloaded on user level.</p>
<p>And now as we know every image downloaded from docker must be visible on the Docker Desktop but you may end up with “<strong><em>not able to see my downloaded images in my Docker Desktop”</em></strong> yep because your docker is running on OS level not on User level</p>
<p>Now some of you say We are able to run with just <code>docker</code> and then our images are seen in Docker Desktop but when we run commands with <code>sudo docker</code> our docker images can’t be seen in docker desktop and may be you will not be able to run many commands with just docker and you might have to use <code>sudo docker</code></p>
<p>So I experienced the same problem, tried many ways to solve the issue but failed again and again. One article which was most suitable and almost solved the problem is An <a target="_blank" href="https://medium.com/devops-technical-notes-and-manuals/how-to-run-docker-commands-without-sudo-28019814198f">article from Andrey Byhalenko</a></p>
<p>But still not able to get the solution that satisfied me and that <code>sudo</code> key word altogether and then I got to know about those contexts as mentioned earlier OS context for docker engine ( for which have to use <code>sudo</code> ) and other context that comes with docker desktop as it is not just a software it’s a bundle of complete docker ecosystem on user level not os level</p>
<p>means when you use <code>sudo docker</code> context for docker images are switched to OS level and when you use <code>docker</code> context remains docker desktop</p>
<p>Multiple context multiple ways and lot’s of confusion</p>
<p>So by giving it a thought I ended up like why do I even need 2 contexts of docker ?</p>
<p>So just remove one context that could be any one</p>
<ul>
<li><p>If you are fine working with sudo and do not need graphical interface and can work with docker cli go for OS level context or docker engine</p>
</li>
<li><p>If you think that GUI is important can’t do it with CLI and want to live without <code>sudo docker</code> command just uninstall docker engine and install docker desktop</p>
</li>
</ul>
<h1 id="heading-if-you-are-going-with-docker-desktop">If you are going with Docker Desktop</h1>
<p>You have to run commands after installation of docker desktop</p>
<pre><code class="lang-bash">systemctl --user status docker-desktop
</code></pre>
<p>It may prompt</p>
<pre><code class="lang-bash">○ docker-desktop.service - Docker Desktop
     Loaded: loaded (/usr/lib/systemd/user/docker-desktop.service; disabled; pr&gt;
     Active: inactive (dead)
</code></pre>
<p>So what it says? it says that docker is not running currently and will not be running automatically after you login to you account ( as it’s an user level context so need to be user specific ) so you have to start docker desktop manually whenever you want to use it.</p>
<p>And if you think no I want my docker to start just after login to my account then run commands</p>
<pre><code class="lang-bash">systemctl --user start docker-desktop
systemctl --user <span class="hljs-built_in">enable</span> docker-desktop
</code></pre>
<p>And now if you run command</p>
<pre><code class="lang-bash">systemctl --user status docker-desktop
</code></pre>
<p>You will get something like</p>
<pre><code class="lang-bash">● docker-desktop.service - Docker Desktop
     Loaded: loaded (/usr/lib/systemd/user/docker-desktop.service; enabled; pre&gt;
     Active: active (running) since Wed 2025-05-07 06:47:28 IST; 1min 18s ago
   Main PID: 45142 (com.docker.back)
      Tasks: 149 (<span class="hljs-built_in">limit</span>: 9289)
     Memory: 2.9G (peak: 2.9G)
        CPU: 2min 4.885s
</code></pre>
<p>So now you system will start docker every time you login into that context</p>
<hr />
<p>And yeah that’s the process that i thought was easy and i ended up working with docker easily</p>
<p>User level context is amazing if you only have one user account on you linux OS</p>
<p>Hope It solves you problem</p>
<hr />
]]></content:encoded></item></channel></rss>