<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Vinesh Thakkar on Medium]]></title>
        <description><![CDATA[Stories by Vinesh Thakkar on Medium]]></description>
        <link>https://medium.com/@vinesh.thakkar?source=rss-c5266b52f4bc------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*zdJomheN67whvvF7FREozg.jpeg</url>
            <title>Stories by Vinesh Thakkar on Medium</title>
            <link>https://medium.com/@vinesh.thakkar?source=rss-c5266b52f4bc------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 14:36:31 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@vinesh.thakkar/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[From Plates to Lines: Understanding Stacks and Queues in Java]]></title>
            <link>https://medium.com/@vinesh.thakkar/from-plates-to-lines-understanding-stacks-and-queues-in-java-c118c76221ad?source=rss-c5266b52f4bc------2</link>
            <guid isPermaLink="false">https://medium.com/p/c118c76221ad</guid>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[queue]]></category>
            <category><![CDATA[stack]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[dsa-courses]]></category>
            <dc:creator><![CDATA[Vinesh Thakkar]]></dc:creator>
            <pubDate>Sun, 27 Jul 2025 16:04:43 GMT</pubDate>
            <atom:updated>2025-07-27T16:04:43.032Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Welcome to the type of Data Structures, Where Order Matters!</strong></p><p>Imagine you’re stacking plates in your kitchen or waiting in a long line at your favorite food stall. Believe it or not, you’re already using two of the most powerful concepts in computer science <strong>Stacks</strong> and <strong>Queues</strong>.</p><p>In Java, these aren’t just buzzwords; they are the foundation of countless algorithms, from undo features in editors to task scheduling in operating systems.</p><h4>What is a Stack?</h4><p>In computer science, a <strong>stack </strong>is a linear data structure based on the Last In, First Out (LIFO) principle. It is an abstract data type that consists of a set of similar elements, such as objects, integers, or characters, which are added and removed from the top of the stack.</p><p>In a stack, the element that is added last is the first one to be removed. This means that the order of elements is reversed when they are retrieved. For example, if you push elements A, B, and C onto a stack, the order of retrieval would be C, B, and A.</p><h4><strong>Operations </strong>of Stack</h4><p>The basic operations associated with a stack are:</p><ul><li><strong>Push: </strong>The operation of adding an element to the top of the stack.</li><li><strong>Peek or Top: </strong>Retrieving the topmost element without removing it.</li><li><strong>Pop:</strong> Removing the topmost element from the stack.</li><li><strong>IsEmpty: </strong>Checking if the stack is empty.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/814/0*vmCjzaSh8asRgTHL.png" /><figcaption>Visual representation of Stack — source programiz</figcaption></figure><h3>Primary Operations of Stack</h3><p>When we are discussing the operations of Stack, they include below two essential operations.</p><pre><strong>push()</strong> — Inserting an element to the stack<br><strong>pop()</strong> — Removing an element from the stack</pre><p>To use a stack in an efficient way, we need to check the status of the stack too. For that purpose, the following functionalities added to the stack.</p><pre><strong>peek() </strong>— get the top element of the stack, without removing the element.<br><strong>isFull()</strong> — check if the stack isfull.<br><strong>isEmpty()</strong> — check if the stack is empty</pre><h3>Algorithm</h3><ol><li>We use a pointer called <strong>TOP</strong> to keep track of the top item in the stack.</li><li>At the beginning, <strong>TOP</strong> is set to <strong>-1</strong>. This helps us know that the stack is empty if <strong>TOP == -1</strong>.</li><li>When we <strong>push</strong> (add) an item into the stack, we first increase <strong>TOP</strong> by 1 and then place the item at that position.</li><li>When we <strong>pop</strong> (remove) an item from the stack, we take the item from the <strong>TOP</strong> position and then decrease <strong>TOP</strong> by 1.</li><li>Before adding a new item (push), we check if the stack is already full.</li><li>Before removing an item (pop), we check if the stack is already empty.</li></ol><h3>Implementation of the Stack using Java</h3><pre>// Stack implementation using an array in Java<br>class Stack {<br>    private int[] stackArray;  // Array to store stack elements<br>    private int top;           // Index of the top element<br>    private int capacity;      // Maximum size of the stack<br><br>    // Constructor to create a stack of given size<br>    Stack(int size) {<br>        stackArray = new int[size];<br>        capacity = size;<br>        top = -1;  // Stack is empty initially<br>    }<br><br>    // Method to add an element to the stack<br>    public void push(int value) {<br>        if (isFull()) {<br>            System.out.println(&quot;Stack Overflow! Cannot push &quot; + value);<br>            return;<br>        }<br>        stackArray[++top] = value;<br>        System.out.println(&quot;Pushed: &quot; + value);<br>    }<br><br>    // Method to remove and return the top element of the stack<br>    public int pop() {<br>        if (isEmpty()) {<br>            System.out.println(&quot;Stack Underflow! Nothing to pop.&quot;);<br>            return -1;<br>        }<br>        return stackArray[top--];<br>    }<br><br>    // Method to check if the stack is empty<br>    public boolean isEmpty() {<br>        return top == -1;<br>    }<br><br>    // Method to check if the stack is full<br>    public boolean isFull() {<br>        return top == capacity - 1;<br>    }<br><br>    // Method to print all elements in the stack<br>    public void displayStack() {<br>        if (isEmpty()) {<br>            System.out.println(&quot;Stack is empty.&quot;);<br>            return;<br>        }<br><br>        System.out.println(&quot;Stack elements:&quot;);<br>        for (int i = 0; i &lt;= top; i++) {<br>            System.out.println(stackArray[i]);<br>        }<br>    }<br>}<br><br>// Main class to test the stack<br>public class Solution {<br>    public static void main(String[] args) {<br>        Stack myStack = new Stack(5); // Creating a stack of size 5<br><br>        myStack.push(1);<br>        myStack.push(2);<br>        myStack.push(3);<br>        myStack.push(4);<br><br>        myStack.pop();  // Removing the top element<br><br>        System.out.println(&quot;\nAfter popping the top element:&quot;);<br>        myStack.displayStack();  // Displaying remaining elements<br>    }<br>}<br></pre><pre><br><strong>Output:<br></strong><br>Pushed: 1<br>Pushed: 2<br>Pushed: 3<br>Pushed: 4<br><br>After popping the top element:<br>Stack elements:<br>1<br>2<br>3<br></pre><h4>Explanation of the Code:</h4><h4>1. Class Structure</h4><p>We’ve created a Stack class that uses an array to store elements. It also keeps track of:</p><ul><li>top: the index of the top element in the stack.</li><li>capacity: the maximum size of the stack.</li></ul><h4>2. Constructor</h4><pre>Stack(int size)</pre><ul><li>Initializes the array to the given size.</li><li>Sets top to -1 to indicate that the stack is empty at the beginning.</li></ul><h4>3. Push Operation</h4><pre>public void push(int x)</pre><ul><li>Before inserting, it checks if the stack is full using isFull().</li><li>If there’s space, it increases the top and inserts the element at that index.</li></ul><h4>4. Pop Operation</h4><pre>public int pop()</pre><ul><li>Checks if the stack is empty using isEmpty().</li><li>If not, it returns the top element and decreases top.</li></ul><h4>5. Main Method</h4><ul><li>A Stack object of size 5 is created.</li><li>It pushes 4 elements into the stack.</li><li>Then it pops the top element (which is 4).</li><li>Finally, it prints the remaining elements in the stack.</li></ul><h3>Bonus: Java’s Built-in Stack Class</h3><p>While it’s great to understand how a stack works under the hood, <strong>Java already provides a built-in Stack implementation</strong> in the java.util package. This makes it super easy to use stacks without writing everything from scratch.</p><pre>import java.util.Stack;<br><br>public class BuiltInStackDemo {<br>    public static void main(String[] args) {<br>        Stack&lt;Integer&gt; stack = new Stack&lt;&gt;();<br><br>        // Pushing elements<br>        stack.push(10);<br>        stack.push(20);<br>        stack.push(30);<br><br>        // Popping top element<br>        stack.pop();<br><br>        // Printing the stack<br>        System.out.println(&quot;Current Stack: &quot; + stack);<br>    }<br>}</pre><p>Output:<br><em>Current Stack: [10, 20]</em></p><h4>Key Methods Available:</h4><ul><li>push(item) – Add item to top of the stack</li><li>pop() – Remove and return top item</li><li>peek() – View top item without removing</li><li>isEmpty() – Check if the stack is empty</li><li>search(item) – Returns the 1-based position from the top of the stack</li></ul><h3>Stack Errors: What Can Go Wrong?</h3><p>When working with stacks, there are two common types of errors:</p><h4>1. Underflow (Trying to Pop from an Empty Stack)</h4><p>This happens when you try to remove an element from the stack, but the stack is already empty.<br> It’s like trying to take something out of an empty box — there’s nothing to remove!</p><p>To avoid this, you should <strong>always check if the stack is empty</strong> before popping, using the isEmpty() method.</p><h4>2. Overflow (Trying to Push into a Full Stack)</h4><p>This happens when you try to add (push) an element into the stack, but there’s no more space left.<br> In some implementations, the stack has a <strong>fixed size</strong>, so it can only hold a limited number of elements.</p><p>Overflow can also happen in programs with <strong>deep or infinite recursion</strong>, where too many function calls fill up the stack memory.</p><h3>Time Complexity of Stack Operations</h3><p>The good news is that <strong>all basic stack operations</strong> are very fast!</p><p>Time Complexity</p><p>push()O(1)</p><p>pop()O(1)</p><p>isEmpty()O(1)</p><p>size()O(1)</p><p>All these operations run in constant time, meaning they take the same amount of time no matter how many elements are in the stack. That’s because they only deal with the <strong>top element</strong>, not the whole stack.</p><h3>Real-Life Applications of Stack</h3><p>Stacks are used in many areas of computer science and problem-solving. Here are some real examples:</p><h4>1. Balanced Parentheses</h4><p>When you write code, the editor uses a stack to check if every opening bracket (, {, [ has a matching closing one ), }, ].<br> If any are missing or out of order, you get an error. This helps with writing clean, bug-free code.</p><h4>2. Backtracking</h4><p>Stacks are great for situations where you need to go back and try something else.</p><p>For example:<br> Imagine solving a <strong>maze</strong>. Every time you reach a point with multiple paths, you remember the other paths by pushing them onto a stack. If you hit a dead end, you pop the last saved path and try it.</p><p>This is used in games, AI algorithms, puzzle solvers, and more.</p><h4>3. Function Calls (Activation Records)</h4><p>When a function is called, the computer stores all its details (like variables and return address) on a <strong>stack</strong>.</p><p>Once the function finishes, the stack “pops” all the data off. This is how your program knows where to go back after the function ends.</p><h4>4. Reversing a Word</h4><p>If you push each letter of a word into a stack, then pop them out, the word will come out reversed.<br> Because stacks follow <strong>LIFO</strong> (Last In, First Out), the last letter added comes out first.</p><h4>5. Expression Evaluation (In Compilers)</h4><p>When evaluating math expressions like 2 + 4 / 5 * (7 - 9), compilers often convert them to <strong>postfix or prefix notation</strong> using a stack.<br> This makes it easier to calculate the result correctly and efficiently.</p><h4>6. Browser History</h4><p>Every time you visit a web page, the browser saves that page’s URL on a <strong>stack</strong>.</p><p>When you press the <strong>Back</strong> button, the browser pops the last URL and takes you to the previous page.</p><h3>Summary</h3><p>Stacks are simple but powerful data structures. They’re used in many areas from code editors and compilers to web browsers and games. Understanding how stacks work helps you write better, more efficient programs and debug issues faster.</p><p>If you’ve ever clicked the back button, used undo in a text editor, or called a function in code congrats, you’ve already used a <strong>stack</strong>!</p><p>Now that you’ve got a solid understanding of <strong>Stacks</strong>, it’s time to flip the flow!</p><p>In the next blog, we’ll dive into <strong>Queues </strong>another powerful data structure that works just like waiting in line at a ticket counter. You’ll learn how queues solve real-world problems where <strong>first-come, first-served</strong> matters.</p><p>Trust me, if you found stacks interesting, queues will open up a whole new way of thinking!</p><p>👉 <strong>Stay tuned the Queue adventure is coming up next! until then happy coding :)</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c118c76221ad" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Call for Change: The True Meaning of Respecting Women in Every Space]]></title>
            <link>https://medium.com/@vinesh.thakkar/a-call-for-change-the-true-meaning-of-respecting-women-in-every-space-15a39caceb62?source=rss-c5266b52f4bc------2</link>
            <guid isPermaLink="false">https://medium.com/p/15a39caceb62</guid>
            <category><![CDATA[women-in-tech]]></category>
            <category><![CDATA[women]]></category>
            <category><![CDATA[gossip]]></category>
            <category><![CDATA[respect-women]]></category>
            <dc:creator><![CDATA[Vinesh Thakkar]]></dc:creator>
            <pubDate>Sun, 30 Mar 2025 10:45:15 GMT</pubDate>
            <atom:updated>2025-03-31T04:47:42.692Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/626/0*w4Z8k_gwEc4X8Ia4.jpg" /></figure><p>Respect is the foundation of any healthy society, yet when it comes to women, it’s often overlooked or misunderstood. The truth is, respecting women isn’t just about avoiding negative comments it’s about creating environments where they feel valued, heard, and empowered.👩‍💼🌟</p><p>We live in a modern world today but our thoughts are still stuck to the age old stereotypes. There’s a serious need for us to change the way we think.<strong> All women deserve respect in all cases.</strong> And there is no scope of ifs and buts in this statement.</p><p>This blog aims to shed light on how we can all contribute to a culture of respect by making small yet meaningful changes in our daily interactions. By understanding the true essence of respect, we can start to make a difference in the way women are treated, not just in words, but in actions that matter.</p><p>Coming from a software background, I’ve noticed how small changes in workplace behavior can make a big difference. Here’s how we can foster respect in every interaction</p><h4>1. Talk Nice, Talk Right🗣️</h4><p>How we talk about people says a lot about us. Gossiping, making unnecessary comments, or cracking jokes on someone especially women ? Not cool. A simple rule: if you wouldn’t say it to her face with a smile, don’t say it at all.</p><p>Instead you should do this:</p><ul><li>Keep compliments about work, not appearance. “Great presentation!” is way better than “Nice dress.”</li><li>Shut down disrespectful talk when you hear it. A simple “Hey, that’s not cool” works wonders.</li><li>Skip the gossip train ; it never leads anywhere good.</li></ul><h4>2. Give Credit Where It’s Due 🙌</h4><p>Ever seen someone share a brilliant idea in a meeting only to have it ignored, and then five minutes later, someone else repeats it and suddenly it’s genius? Yeah, let’s stop that.</p><p>Instead you should do this:</p><ul><li>If a female colleague shares a great idea, back her up. “Hey, that was a great point by {her name}!”.</li><li>Support women in leadership. More diversity = better decisions for everyone.</li></ul><h4>3. Create an Inclusive Workplace 🤝</h4><p>A great workplace is one where everyone feels included, heard, and valued. Make sure women feel safe and supported in all work places.</p><h3>Final thoughts 💭❤️</h3><p>Respecting women isn’t about grand gestures — it’s about small, everyday actions that add up to a better workplace for everyone.</p><p>Imagine a workplace where every woman feels heard, valued, and supported a place where respect is a way of life, not just a policy. It starts with small actions: speaking up for a colleague, offering encouragement, and treating everyone with fairness. These moments create real change. At the core, respect is about lifting each other up not because we have to, but because it’s right.</p><p>💡 So, let’s not just say we respect women; let’s show it, in every word, in every action, every single day.</p><blockquote>📢 “Men of quality respect women’s equality” — Jeremiah Say</blockquote><p>At the end I would like to say that Respect isn’t about making women feel powerful it’s about recognizing that they always were.<br>I hope after reading this blog you as a men should ensure that every women should feel safe and respected , and if already you are a MEN who respects women I would like to congratulate you , raised well.😁</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=15a39caceb62" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AWS 101: The Sky’s the Limit — An Intro to Cloud Computing and EC2]]></title>
            <link>https://medium.com/@vinesh.thakkar/aws-101-the-skys-the-limit-an-intro-to-cloud-computing-and-ec2-d1857e984bad?source=rss-c5266b52f4bc------2</link>
            <guid isPermaLink="false">https://medium.com/p/d1857e984bad</guid>
            <category><![CDATA[ec2]]></category>
            <category><![CDATA[servers]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Vinesh Thakkar]]></dc:creator>
            <pubDate>Sat, 01 Mar 2025 13:55:07 GMT</pubDate>
            <atom:updated>2025-03-03T04:49:14.100Z</atom:updated>
            <content:encoded><![CDATA[<h3>AWS 101: The Sky’s the Limit — An Intro to Cloud Computing and EC2</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/0*5BrFBSpGh7TO6qay.jpg" /></figure><p><strong>Welcome to the AWS Series!</strong> 🚀</p><p>If you’re completely new to <strong>Amazon Web Services (AWS)</strong> and have no idea where to start, don’t worry ,you’re in the right place! This series is made for <strong>beginners</strong>, and we’ll start from scratch, slowly building up to more advanced topics.</p><h4>Content of this blog</h4><ol><li>Introduction to Cloud.</li><li>Regions and availability zones.</li><li>EC2 introduction.</li><li>SSH.</li><li>Security group</li><li>Creating an EC2 Instance.</li><li>Destroy the EC2 instance that we created so that you will not get billed.</li></ol><h4>Introduction to cloud</h4><p>Imagine you need a powerful computer to run an application, store data, or host a website. Instead of <strong>buying expensive hardware</strong>, maintaining servers, and handling security yourself, <strong>what if you could just “rent” computing power, storage, and other resources whenever you need them?</strong> That’s exactly what <strong>cloud computing</strong> offers.</p><p>Cloud computing is the <strong>on-demand delivery of IT resources</strong> (such as servers, storage, databases, and networking) over the internet. Instead of managing physical hardware, you use services from cloud providers like <strong>Amazon Web Services (AWS), Microsoft Azure, and Google Cloud</strong> — paying only for what you use.</p><p>Now suppose you want to built a <strong>Node.js app</strong> that listens on <strong>port 8080</strong>, and now you want the world to access it. Before cloud computing, setting this up was a real challenge. You would have to:</p><ul><li><strong>Purchase a public static IP</strong> so users can visit your app at http://&lt;your_IP&gt;:8080.</li><li><strong>Keep your laptop running 24/7</strong> to ensure your app is always available.</li><li><strong>Manage hardware limitations</strong> — if too many users visit, your laptop’s CPU and RAM might not handle the load, requiring expensive upgrades.</li><li><strong>Secure your setup</strong> against cyber threats, physical damage, and even disasters like floods or theft.</li></ul><p>Back in the day, anyone wanting to host an online service had to deal with all of this on their own. But today, <strong>cloud providers like AWS, Azure, and Google Cloud</strong> handle these complexities for us — offering <strong>scalability, security, and reliability</strong> at a fraction of the cost.</p><p>That’s the power of cloud computing, and in this series, we’ll explore how AWS makes it all seamless! 🚀</p><h4>Regions and availability zones</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Fl1blLKbMOMl920V.png" /></figure><p><strong>Regions</strong></p><p>An AWS Region is a geographic area containing multiple AWS data centers, each functioning as an independent environment. It’s essential to carefully select the region when creating resources, as they are not accessible across different regions.</p><p>Regions enable users to deploy resources like servers and databases strategically, considering factors such as latency, legal compliance, and disaster recovery. For instance, if your business operates in India, choosing the Mumbai region ensures lower latency, as data travels a shorter distance. The farther the resource, the higher the latency, leading to slower performance.</p><p><strong>Latency (for beginners):</strong> It refers to the time taken for a data packet to travel from one location to another. A website with low latency loads quickly without buffering.</p><p>Each AWS Region has a unique identifier; for example, Mumbai’s region is labeled as <strong>“ap-south-1”</strong>.</p><p><strong>Availability zones (AZ’s)</strong></p><p>Availability Zones are isolated locations within a Region. Each AWS Region has multiple Availability Zones, typically three or more.</p><p>Example: In the Mumbai region (ap-south-1), AWS can have its physical data centers kept in different locations of Mumbai within a 100 km radius. These locations inside Mumbai are called Availability Zones.</p><p>Availability Zones provide redundancy and ensure high availability. By deploying your resources across multiple AZs, you protect your applications from failure in a single data center.</p><p>Mumbai has 3 data centers currently:</p><ul><li>ap-south-1a</li><li>ap-south-1b</li><li>ap-south-1c</li></ul><p>“a”, “b”, “c”, are suffix that is attached after the region code for different availability zones.</p><p>When you see it is written <em>ap-south-1</em>, then it is a region</p><p>When you see it is written <em>ap-south-1a</em>, then it is an availability zone inside a region.</p><h3>EC2 (Amazon Elastic Compute Cloud) Introduction</h3><p>AWS provides many services, and in this blog series, we will learn about the most important ones used in industries.</p><p>Our journey begins with understanding the <strong>EC2 service</strong> in AWS.</p><p>Imagine you are building a website using <strong>Python Flask, Node.js, or Spring Boot</strong> on your personal laptop. It works fine on <strong>localhost</strong>, but only you can access it. Now, you want to make it available on the internet so anyone can visit your website by typing <strong>http://mywebsite.com</strong> in their browser.</p><p>To do this, you need a computer that is <strong>always online</strong>, has a <strong>public IP address</strong>, and can run your application <strong>24/7</strong>. If you could somehow get such a powerful computer, upload your code, and start your app, people could access it by visiting <strong>http://&lt;server_IP&gt;:8080</strong> from anywhere.</p><p>However, your <strong>personal laptop does not have a public IP</strong>, meaning others <strong>cannot access your website</strong>. This is where <strong>AWS EC2</strong> comes in. Think of EC2 as a <strong>virtual laptop in the cloud</strong> that you can rent. You can install software, upload files, and run your applications just like you do on your personal computer.</p><p>The best part? <strong>AWS offers a free EC2 instance for one year</strong> when you create an account. In this blog series, we’ll use the <strong>free-tier EC2 instance</strong> to deploy applications without any cost. 🚀</p><blockquote>The virtual machine (EC2) that we launch is known as an <strong>Instance</strong>.</blockquote><h4>Instance:</h4><p>An <strong>instance</strong> is a virtual computer in AWS that runs an <strong>operating system</strong> like Linux or Windows. It comes with different configurations of <strong>CPU, memory, and storage</strong>, just like a regular computer. In this blog series, we will use <strong>Linux Ubuntu</strong> for our learning.</p><h4>Instance Type:</h4><p>The <strong>instance type</strong> determines the hardware power of the instance, such as the number of <strong>CPUs, RAM, and storage capacity</strong>. Some examples include:</p><ul><li><strong>t2.micro</strong> — A small, general-purpose instance (suitable for beginners).</li><li><strong>m5.large</strong> — A more powerful instance for handling larger applications.</li></ul><p>Don’t worry! We’ll explore these options practically in upcoming blogs.</p><h4>Elastic IP Address:</h4><p>An <strong>Elastic IP</strong> is a <strong>static public IP address</strong> that you can attach to your instance, making it accessible from anywhere on the internet. This ensures that even if your instance restarts, the <strong>IP remains the same</strong>, so your website or application stays reachable.</p><h4>SSH (Secure Shell)</h4><p>Suppose you rented an EC2 machine on AWS. How will access that EC2 machine, download your code on that machine ? etc.</p><p>For this, we use something called SSH. It lets you access the “terminal” of the EC2 machine from your local laptop. We run some SSH commands on our local laptop terminal and magically our local laptop terminal turns into the terminal of the EC2 machine. Now, you can do <em>git clone</em>, <em>mkdir</em>, <em>ls</em> or anything and that will run on that EC2 machine.</p><p>While creating the EC2 machine we have to give “SSH from anywhere” access to the security group of EC2. So, that it lets us SSH from our laptop. Then, we have to download a key-pair “.pem” file and run SSH commands in the same directory where that pem file is present and our SSH connection is successful. Never share “.pem” file with anyone otherwise they can do SSH from their machine and hack your system. We will do all these practically in this blog.</p><h4>Security Group</h4><p>A <strong>Security Group</strong> is a set of rules that control the traffic allowed to and from your EC2 instances. Think of it as a firewall that specifies which traffic is allowed based on IP address, port, and protocol.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gzpuLrq7tASK8wWU.png" /></figure><ul><li><strong>Inbound Rules</strong>: Define which traffic is allowed to come from outside world to your EC2. Example: You may set SSH (Port 22) traffic only from your IP address. Now, only you can SSH into your EC2 machine terminal. You can expose Port 8080 to allow from anywhere so that anyone in the world can access your app which is running on Port 8080.</li><li><strong>Outbound Rules</strong>: Define which traffic is allowed to go outside our EC2 instance to the world. Example: Suppose your database instance is hosted somewhere else then you only allow your EC2 IP address to connect to your database. So, no one else backend can make the connection to your DB.</li></ul><p>When you create a Security Group in AWS then you can name this security group and attach it to any EC2 Instance. One security group can be attached to multiple EC2 servers and one EC2 server can have multiple security groups attached to it.</p><h4>We will launch our first EC2 instance.</h4><p>Go to <a href="https://aws.amazon.com/console/">AWS Console</a> &gt; Search “EC2” on the search bar &gt; Go to EC2 and Click on Launch Instance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6Z8Sc14oVvNwHvkQu5AjkA.png" /><figcaption>Image for launching instance of EC2</figcaption></figure><ol><li>Give any name to your Instance I’ve given <strong>myWebServer </strong>and select Linux free-tier as OS Image. Then select Instance Type which is under free-tier. For me in the United states region, it is “t2-micro”.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NpzTHowFQ8j0GM-eAswnoA.png" /></figure><p>2. Scroll down and select “Create security group”. It will create a new security group. If you have any existing Security Group created then you can assign that. But we don’t have so we will create one. Give “Allow SSH traffic from anywhere” access. It will permit to do SSH from any laptop anywhere.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v1CAkV8AWJ9e7lWuFR93XQ.png" /></figure><p>3. Scroll down and click on Create new key pair. If you have any existing one then you can assign that but we don’t have so we will generate a new key pair and download it. SSH will happen only in the same folder on your laptop where your key pair is present. I have told these in the above section of the blog.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t1GPGz2sh6MX6zd9EJmxbg.png" /></figure><p>4. Give any name to your key-pair and click on “Create Key pair” button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/510/1*EiVGS8qqr3urrUxBEDnEsw.png" /></figure><p>5. Scroll down and configure storage settings. By default, it is given 8 GB storage so we will go with it. This EBS Storage is also a very important topic.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3pLST5cXzFAgj635D9UEvQ.png" /></figure><p>Then click on Launch Instance.</p><p>Wait for 2–3 minutes then your instance state will come under the “Running” State.</p><p>Congrats, you have created your first EC2 instance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MVB7cvnDXXZnrO5OLpbFZA.png" /></figure><blockquote>Very Important: Terminate the instance that you have created after the use. Otherwise, you might get a bill if you are not in the free-tier.</blockquote><h4>Key Things Beginners Should Know About EC2:</h4><ol><li><strong>Instance:</strong></li></ol><ul><li>An instance is a <strong>virtual machine</strong> running on AWS.</li><li>It can have different configurations of <strong>CPU, RAM, and storage</strong>, based on your needs.</li><li>You can install <strong>Linux or Windows</strong> as the operating system.</li></ul><p>2. <strong>Instance Type:</strong></p><ul><li>Defines the <strong>hardware power</strong> of your instance.</li></ul><p>Example:</p><ul><li><strong>t2.micro</strong> (small, free-tier eligible, good for beginners).</li><li><strong>m5.large</strong> (more powerful, used for high-performance applications).</li></ul><p>3. <strong>Public &amp; Private IP:</strong></p><ul><li>Every EC2 instance gets a <strong>private IP</strong> (accessible inside AWS only).</li><li>If you want to access it from the internet, you need a <strong>public IP</strong> or an <strong>Elastic IP (static IP that doesn’t change even after rebooting).</strong></li></ul><p>4. <strong>Security Groups:</strong></p><ul><li>Acts as a <strong>firewall</strong> to control <strong>which traffic can reach your instance</strong>.</li><li>By default, <strong>all traffic is blocked</strong>, and you need to allow required ports (like port <strong>22 for SSH access</strong> or port <strong>80 for a web server</strong>)</li></ul><p>5. <strong>Key Pair (SSH Key):</strong></p><ul><li>To connect to your EC2 instance securely, AWS provides a <strong>Key Pair</strong> (a private key file).</li><li>This key is needed to log in using <strong>SSH (for Linux instances)</strong> or <strong>RDP (for Windows instances).</strong></li></ul><h3>This is the End of this Blog.</h3><blockquote>So, that was all about<strong> Cloud computing</strong> <strong>EC2 </strong>instances! I hope you now have a clear understanding of how they work and why they are important. Stay tuned for our next session, where we’ll explore more exciting AWS services. See you soon!🐱‍🏍</blockquote><p>Happy coding .👩‍💻</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d1857e984bad" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cracking the Binary Search : How It Really Works(Part-2/3)]]></title>
            <link>https://medium.com/@vinesh.thakkar/cracking-the-binary-search-how-it-really-works-part-2-3-2f137d0ffd28?source=rss-c5266b52f4bc------2</link>
            <guid isPermaLink="false">https://medium.com/p/2f137d0ffd28</guid>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[recursive]]></category>
            <category><![CDATA[binary-search]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Vinesh Thakkar]]></dc:creator>
            <pubDate>Tue, 04 Feb 2025 12:48:46 GMT</pubDate>
            <atom:updated>2025-02-14T08:25:37.549Z</atom:updated>
            <content:encoded><![CDATA[<h3>Cracking the Binary Search : How It Really Works(Part-2/2)</h3><p>Welcome to the second part of this Binary search series , if you are not aware about the binary search or you’re absolute fresher to this topic you can check out our <a href="https://medium.com/@vinesh.thakkar/cracking-the-binary-search-how-it-really-works-9276ebdcdbfb"><strong>first part </strong></a><strong>.</strong> Now lets kick start to the second part in which we’ll be covering two implementations of Binary search.<strong>🚀</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*yLNFn-xzoOre3q5Z.png" /></figure><p>As mentioned earlier this series will cover six key points about Binary Search over three posts this is the second one:</p><ol><li>Real-life examples and a coding problem demonstration.😊</li><li><strong>Iterative and recursive implementations of Binary Search and it’s time complexity.😉</strong></li></ol><h3>Iterative implementation</h3><p>We will use a couple of pointers i.e. <strong>low</strong> and <strong>high</strong> to apply binary search. Initially, the low pointer should point to the first index and the high pointer should point to the last index.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/601/1*ePpSiQF60vKYpCPcp_Ibeg.png" /></figure><p>The <strong>search space</strong> refers to the entire range between the low and high pointers, including both boundaries. In binary search, the search space must always be <strong>sorted</strong>.</p><p>Now we’ll apply binary search on this array</p><h4>Step 1: Divide the Search Space into Two Halves</h4><p>To split the search space, we determine the middle element by using a pointer mid:</p><p>mid=(low+high) / 2</p><p>( / )means division .</p><h4>Step 2: Compare the Middle Element with the Target</h4><p>Once we identify the middle element, three possible scenarios arise:</p><ol><li><strong>If </strong><strong>arr[mid] == target</strong> → The target is found, and we return its index.</li><li><strong>If </strong><strong>target &gt; arr[mid]</strong> → The target lies in the <strong>right half</strong> of the array, so the next search space shifts accordingly.</li><li><strong>If </strong><strong>target &lt; arr[mid]</strong> → The target lies in the <strong>left half</strong> of the array, requiring a shift in the search space.</li></ol><h4>Step 3: Narrowing Down the Search Space</h4><p>Based on where the target is likely to be found, we adjust the pointers:</p><ul><li>If the target is in the <strong>left half</strong>, update high = mid - 1.</li><li>If the target is in the <strong>right half</strong>, update low = mid + 1.</li></ul><p>This process continues until either the target is found or the search space becomes invalid (high &lt; low). The search space ceases to exist when the high pointer moves before low, meaning the element is not present in the array.</p><h4>DryRun of this example:</h4><h4>Target : 12</h4><figure><img alt="Dry run of the above array" src="https://cdn-images-1.medium.com/max/618/1*V6LpxgRIf7PylQBr6x1UvA.png" /></figure><h4><strong>Note: If the target is not present in the array, low and high will cross each other</strong></h4><h3>Recursive implementation</h3><ul><li><strong>Base case:</strong> If left &gt; right, return -1 (element not found).</li><li>Calculate mid = left + (right - left) / 2.</li><li>Compare arr[mid] with target:</li><li>If arr[mid] == target, return mid.</li><li>If arr[mid] &lt; target, search the right half (binarySearch(arr, mid+1, right, target)).</li><li>Otherwise, search the left half (binarySearch(arr, left, mid-1, target)).</li><li>This process continues recursively until the target is found or left &gt; right.</li></ul><pre>class BinarySearchRecursive {<br>    public static int binarySearch(int[] arr, int left, int right, int target) {<br>        if (left &gt; right)<br>            return -1; // Base case: target not found<br><br>        int mid = left + (right - left) / 2;<br><br>        // Check if target is at mid<br>        if (arr[mid] == target)<br>            return mid;<br><br>        // If target is greater, search in the right half<br>        if (arr[mid] &lt; target)<br>            return binarySearch(arr, mid + 1, right, target);<br><br>        // Otherwise, search in the left half<br>        return binarySearch(arr, left, mid - 1, target);<br>    }<br><br>    public static void main(String[] args) {<br>        int[] arr = {2, 4, 7, 10, 14, 19, 23};<br>        int target = 10;<br>        int result = binarySearch(arr, 0, arr.length - 1, target);<br>        System.out.println(result != -1 ? &quot;Element found at index &quot; + result : &quot;Element not found&quot;);<br>    }<br>}</pre><h4>Iterative vs Recursive: Which One to Use?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/646/1*2iTBBwvpzjoLq-wMtBdR0A.png" /></figure><h4>Time Complexity analysis :</h4><h4>Best Case -&gt; O(1)</h4><p><em>Best case is when the element is at the middle index of the array. It takes only one comparison to find the target element. So the best case complexity is </em><strong><em>O(1)</em></strong><em>.</em></p><h4>Average case -&gt; O(logN)</h4><p><em>Consider array </em><strong><em>arr[]</em></strong><em> of length </em><strong><em>N</em></strong><em> and element </em><strong><em>X</em></strong><em> to be found. There can be two cases:</em></p><ul><li><strong><em>Case1: </em></strong><em>Element is present in the array</em></li><li><strong><em>Case2: </em></strong><em>Element is not present in the array.</em></li></ul><p><em>There are </em><strong><em>N</em></strong><em> Case1 and </em><strong><em>1</em></strong><em> Case2. So total number of cases = </em><strong><em>N+1</em></strong><em>. Now notice the following:</em></p><ul><li><em>An element at index N/2 can be found in </em><strong><em>1</em></strong><em> comparison</em></li><li><em>Elements at index N/4 and 3N/4 can be found in </em><strong><em>2</em></strong><em> comparisons.</em></li><li><em>Elements at indices N/8, 3N/8, 5N/8 and 7N/8 can be found in </em><strong><em>3</em></strong><em> comparisons and so on.</em></li></ul><p><em>Based on this we can conclude that elements that require:</em></p><ul><li><em>1 comparison = 1</em></li><li><em>2 comparisons = 2</em></li><li><em>3 comparisons = 4</em></li><li><strong><em>x</em></strong><em> comparisons = </em><strong><em>2x-1</em></strong><em> where </em><strong><em>x</em></strong><em> belongs to the range </em><strong><em>[1, logN]</em></strong><em> because maximum comparisons = maximum time N can be halved = maximum comparisons to reach 1st element = logN.</em></li></ul><p><em>So, total comparisons<br>= 1*(elements requiring 1 comparisons) + 2*(elements requiring 2 comparisons) + . . . + logN*(elements requiring logN comparisons)<br>= 1*1 + 2*2 + 3*4 + . . . + logN * (2logN-1)<br>= 2logN * (logN — 1) + 1<br>= </em><strong><em>N * (logN — 1) + 1</em></strong></p><p><em>Total number of cases = </em><strong><em>N+1</em></strong><em>.</em></p><p><em>Therefore, the average complexity = (</em><strong><em>N*(logN — 1) + 1)/N+1</em></strong><em> = </em><strong><em>N*logN / (N+1) + 1/(N+1)</em></strong><em>. Here the dominant term is N*logN/(N+1) which is approximately </em><strong><em>logN</em></strong><em>. So the average case complexity is</em><strong><em> O(logN)</em></strong></p><h4>Worst case -&gt; O(logN)</h4><p><em>The worst case will be when the element is present in the first position. As seen in the average case, the comparison required to reach the first element is </em><strong><em>logN</em></strong><em>. So the time complexity for the worst case is </em><strong><em>O(logN)</em></strong><em>.</em></p><p>That’s it for <strong>Part 2 and final part </strong>of our Binary Search series! I hope you enjoyed this series of Binary search if you have any queries feel free to ask in comments section , till then wait for exiting upcoming series and practice like you have never win and perform like you never lost 😉.</p><p>Happy coding 👔</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2f137d0ffd28" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cracking the Binary Search : How It Really Works]]></title>
            <link>https://medium.com/@vinesh.thakkar/cracking-the-binary-search-how-it-really-works-9276ebdcdbfb?source=rss-c5266b52f4bc------2</link>
            <guid isPermaLink="false">https://medium.com/p/9276ebdcdbfb</guid>
            <category><![CDATA[binary-search-algorithm]]></category>
            <category><![CDATA[dsa-courses]]></category>
            <category><![CDATA[binary-search]]></category>
            <category><![CDATA[data-structures]]></category>
            <dc:creator><![CDATA[Vinesh Thakkar]]></dc:creator>
            <pubDate>Sun, 26 Jan 2025 16:19:33 GMT</pubDate>
            <atom:updated>2025-02-10T04:18:50.039Z</atom:updated>
            <content:encoded><![CDATA[<h3>Cracking the Binary Search : How It Really Works(Part-1/2)</h3><p>Welcome to the first blog in our <strong>Binary Search</strong> series! This series will cover everything you need to know about how binary search works. We’ll be exploring the concepts step by step, using <strong>Java </strong>as our primary language. So, let’s dive in — are you excited?😃</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uG3hXltrc8PrXcsF.png" /></figure><p>The flow of the series will be as following:-</p><ul><li>Finding the Needle: <strong>Real-Life Uses of Binary Search</strong></li><li>The Problem Solver: <strong>Binary Search in Action</strong></li><li>Step-by-Step: Iterative <strong>Binary Search Explained</strong></li><li>Divide and Recur:<strong> Recursive Binary Search Unveiled</strong></li><li>The Efficiency Factor: <strong>Understanding Binary Search Complexity</strong></li><li>Avoiding Pitfalls: <strong>Managing Overflow in Binary Search</strong></li></ul><p>This series will cover six key points about Binary Search over two posts:</p><ol><li><strong>Real-life examples and a coding problem demonstration.😊</strong></li><li>Iterative and recursive implementations of Binary Search and it’s time complexity.😉</li></ol><h3>From Scroll to Search: How Binary Search Finds Vinesh in real life with example</h3><p><strong>Problem Statement:</strong> Imagine you’re looking for Vinesh’s number in a contact list on your phone.📲</p><p><strong>Method 1(Normal search):</strong> One way to find Vinesh’s 😁number is to scroll through the entire list, checking each name one by one until you find him. This is called a <strong>linear search</strong>, and it can take a while if the list is long, since you have to check every name.</p><p><strong>Method 2 (Binary search):</strong> Now, let’s think about the fact that your contact list is in alphabetical order(sorted alphabetically) 📜. Instead of scrolling through every name, you decide to speed things up by jumping to the middle of the list. Let’s say you land on a name like <strong>“Rajeev”</strong> 🧑‍💻. Since <strong>“Vinesh”</strong> comes alphabetically after <strong>“Rajeev”</strong> 🔠, you know Vinesh must be in the second half of the list. ⚡</p><p>So, you narrow your search to the second half of the list and try again. This time, you land on <strong>“Ravi”</strong> 🧑‍💻. Since <strong>“Vinesh”</strong> comes after <strong>“Ravi”</strong> 🔠, you know you should be looking further down the list. You keep doing this — cutting the list in half each time — until, finally, you find <strong>“Vinesh”</strong> 🎯.</p><p>By focusing on smaller chunks of the list instead of checking every single name, you get to <strong>Vinesh</strong> much faster ⚡. This is the magic of <strong>binary search</strong> — it helps you zero in on the right spot quickly, rather than wasting time scrolling through everything.</p><p><strong>NOTE :- Binary search only works on a sorted search space.📝</strong></p><p>In binary search, we generally divide the search space into two equal halves and then try to locate which half contains the target. According to that, we shrink the search space size.</p><p>Here is the pseudocode for binary search.</p><p><strong>Step 1:</strong> Start with the entire search space (e.g., the whole list or range).</p><p><strong>Step 2:</strong> Find the middle element.</p><p><strong>Step 3:</strong> Compare the middle element with the target value.</p><ul><li>If the target is equal to the middle element, you’ve found the target.</li><li>If the target is smaller, focus on the left half.</li><li>If the target is larger, focus on the right half.</li></ul><p><strong>Step 4:</strong> Repeat the process on the new half (left or right) until the target is found or the search space is empty</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iKJgV2xGLj0gdyM5wNYXIQ.jpeg" /><figcaption>Visualization of binary search - 1</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9D8VinEWqaZmB7VpNpt9mw.jpeg" /><figcaption>Visualization of binary search - 2</figcaption></figure><h3>Implementing Binary Search in Java: Step-by-Step Code Explanation</h3><ul><li>Binary search is an efficient algorithm used to search for a target value in a <strong>sorted array</strong> by repeatedly dividing the search space in half.</li><li>It works by comparing the target with the middle element of the array and adjusting the search space accordingly, either narrowing it to the left half or the right half.</li></ul><p><strong>Step 1</strong>: Initialize the Array and Variables</p><pre>int arr[] = {1,2,3,4,5,6};<br>int target = 2;<br>int mid = arr[arr.length/2];<br>int start = 0;<br>int end = arr.length-1;</pre><ul><li><strong>Array</strong> arr[]: This is the sorted array in which we will search for the target (2).</li><li><strong>Target</strong>: We are looking for the value 2 in the array.</li><li><strong>Mid</strong>: Initially, we calculate the middle index of the array with arr.length / 2.</li><li><strong>Start and End</strong>: We set start to the beginning of the array (0) and end to the last index of the array (arr.length - 1).</li></ul><p><strong>Step 2</strong>: The While Loop</p><pre>        while (start&lt;=end) {<br>            if(arr[mid] == target)<br>            {<br>                System.out.println(&quot;Target found&quot;);<br>                System.out.println(mid);<br>                break;<br>            }<br>             if(target&gt;mid)<br>            {<br>                start = mid+1;<br>                end = arr.length-1;<br>                mid = (start + end)/2;<br>            }<br>             else{<br>                 end  = mid-1;<br>                 mid = (start + end)/2;<br>             }<br>        }</pre><ul><li>The loop continues as long as the start index is less than or equal to the end index. This ensures we only search within the valid range of the array.</li><li>We check if the element at the middle index arr[mid] is equal to the target value.</li><li>If it is, we print <strong>“Target found”</strong> and the index of the target (mid). Then, the loop is terminated with break.</li></ul><p><strong>If Target is Greater than Mid Value</strong></p><ul><li>If the target is greater than the middle value, the target must be in the right half of the array, so we adjust the start index to mid + 1 and keep the end index the same.</li><li>We recalculate the mid index for the new range (right half of the array).</li></ul><p><strong>If Target is Less than Mid Value</strong></p><ul><li>If the target is smaller than the middle value, the target must be in the left half of the array, so we adjust the end index to mid - 1.</li><li>We recalculate the mid index for the new range (left half of the array).</li></ul><p><strong>Step 3: When Target is Not Found</strong></p><ul><li>If the target value isn’t found by the time start exceeds end, the loop will terminate, and the program will end without printing anything.</li></ul><p>Integrating all in one:</p><pre>public class BinarySearch {<br>    public static void main(String[] args) {<br>        int arr[] = {1,2,3,4,5,6};<br>        int target = 2;<br>        int mid = arr[arr.length/2];<br>        int start = 0;<br>        int end = arr.length-1;<br><br>        while (start&lt;=end) {<br>            if(arr[mid] == target)<br>            {<br>                System.out.println(&quot;Target found&quot;);<br>                System.out.println(mid);<br>                break;<br>            }<br>             if(target&gt;mid)<br>            {<br>                start = mid+1;<br>                end = arr.length-1;<br>                mid = (start + end)/2;<br>            }<br>             else{<br>                 end  = mid-1;<br>                 mid = (start + end)/2;<br>             }<br>        }<br>         System.out.println(&quot;Target not found&quot;);<br>    }<br>}</pre><h3>Key Points to Remember:</h3><ul><li><strong>Binary Search</strong> works only on <strong>sorted </strong>arrays or search spaces.</li><li>By comparing the middle element to the target, we can determine whether to search the left or right half of the array, cutting the search space in half with each step.</li><li>It’s much more efficient than a <strong>linear search</strong> (O(n)) when dealing with large datasets.</li></ul><h3>Real-World Applications</h3><p>Binary search is not only limited to searching in arrays. It’s widely used in various applications like:</p><ul><li><strong>Finding elements in databases</strong></li><li><strong>Searching in large files</strong> or directories</li><li><strong>Efficient searching in algorithms</strong> for problems like finding the square root, solving puzzles, etc.</li></ul><h3>Conclusion</h3><p>Now that you have a better understanding of how binary search works and how to implement it in Java, you can start using this powerful algorithm to solve problems in your own projects. The key is remembering that it’s best suited for sorted data, and it will always outperform linear search in terms of speed for large datasets.</p><p>Feel free to experiment with the code, tweak it, and even try it on different kinds of search problems.</p><p>I hope this explanation helped you understand the binary search algorithm and how it can be implemented in Java. If you have any questions or suggestions, feel free to leave a comment below!</p><h3>What’s Next?</h3><blockquote>In the next post, we’ll dive deeper into the next two points of our binary search series. We’ll explore <strong>Iterative vs. Recursive Binary Search</strong> and discuss <strong>how to implement binary search both iteratively and recursively</strong>. Stay tuned to see how these approaches can affect performance and when to use each one.</blockquote><p>See you in the next post! 🚀👨‍💻</p><p>Happy coding! 👨‍💻</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9276ebdcdbfb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Ultimate Linked List Guide: Become a Hero with All Methods and Theory in Java (Part-4).]]></title>
            <link>https://medium.com/@vinesh.thakkar/the-ultimate-linked-list-guide-become-a-hero-with-all-methods-and-theory-in-java-part-4-0f91da6b77e5?source=rss-c5266b52f4bc------2</link>
            <guid isPermaLink="false">https://medium.com/p/0f91da6b77e5</guid>
            <category><![CDATA[data-structure-algorithm]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[linked-lists]]></category>
            <dc:creator><![CDATA[Vinesh Thakkar]]></dc:creator>
            <pubDate>Sat, 14 Dec 2024 18:04:29 GMT</pubDate>
            <atom:updated>2024-12-14T18:04:29.396Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>In Part 3, we explored the <strong>deletion </strong>and <strong>updation </strong>methods for linked lists. If you’re unfamiliar with these concepts, feel free to check them out in detail <a href="https://medium.com/@vinesh.thakkar/the-ultimate-linked-list-guide-become-a-hero-with-all-methods-and-theory-in-java-part-3-0aacee924828">here</a><strong>.</strong></blockquote><p>Welcome to <strong>Part 4</strong> of our Linked List series! 🚀 In this chapter, we’ll dive into <strong>searching </strong>techniques and explore some classic <strong>DSA </strong>problems using linked lists.</p><p>Problems covered in this part</p><ul><li><a href="https://leetcode.com/problems/remove-nth-node-from-end-of-list/">Remove Nth Node From End of List</a></li><li><a href="https://leetcode.com/problems/intersection-of-two-linked-lists/">Intersection of Two Linked Lists</a></li><li><a href="https://leetcode.com/problems/middle-of-the-linked-list/">Middle of the Linked List</a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/691/1*266Xn4ilhFOnAtZfOWz3iQ.png" /></figure><p>Think of Data Structures and Algorithms DSA as the toolkit every coder needs to solve problems more efficiently. For beginners, learning DSA is like learning the <strong>rules of a game</strong> — it helps you think more logically and figure out the best way to tackle any coding challenge. It’s not just about writing code; it’s about understanding how to break down big problems into smaller, easier-to-solve challenges. Once you get the hang of it, you’ll be able to solve problems faster and smarter.</p><p>So, let’s dive deep into <strong>DSA (Data Structures and Algorithms)</strong>. I’ll be solving problems using the <strong>LeetCode</strong> platform and sharing my approaches, and solutions here. Let’s explore DSA step by step and sharpen our problem-solving skills together!</p><h3>Problem -1 : <a href="https://leetcode.com/problems/remove-nth-node-from-end-of-list/">Remove Nth Node From End of List</a>.</h3><p><strong>Problem statement → Given the </strong><strong>head of a linked list, remove the </strong><strong>nth node from the end of the list and return its head</strong>.</p><p>Now let’s understand the problem first<br><strong>What is given?</strong><br>You are given the <strong>head</strong> of a linked list and a number n.</p><p><strong>What is the task?</strong><br>You need to <strong>remove the n-th node</strong> from the <strong>end of the list</strong> and return the new head of the linked list.</p><blockquote>Input : head = [1,2,3,4,5], n = 2</blockquote><blockquote>Output : [1,2,3,5]</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/542/0*pONCwjPkFQzwbgUm.jpg" /></figure><p>Let’s start by understanding the algorithm , there are several approaches to solve this problem but we’ll be using the optimized one but going through linked list only once.</p><p>Imagine two friends, <strong>Fast</strong> 🏃‍♂️ and <strong>Slow</strong> 🐢. They will work together to find and remove the target node!</p><p><strong>1.Start Together</strong> 👫:</p><ul><li>Place both <strong>Fast</strong> 🏃‍♂️ and <strong>Slow</strong> 🐢 at the <strong>head</strong> of the linked list.</li><li>Think of the head as the starting line! 🏁</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/691/1*ez8QiEWSwM1eNCnFFVMnig.png" /></figure><p><strong>2.Move Fast Ahead</strong> ⏩:</p><ul><li>If n = 2, move <strong>Fast</strong> 🏃‍♂️ <strong>2 steps ahead</strong> in the list.</li><li>Why? So that there’s exactly n nodes of distance between <strong>Fast</strong> and <strong>Slow</strong>.</li><li>After this step, <strong>Fast</strong> will be ahead, and <strong>Slow</strong> will still be chilling at the start. 😎</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/691/1*A2GrQL4BRFaNX2UEJBxPFg.png" /></figure><p><strong>3.Move Together</strong> 🚶‍♂️🐢:</p><ul><li>Now, make <strong>Fast</strong> and <strong>Slow</strong> move <strong>one step at a time</strong> together through the list.</li><li>Fast 🏃‍♂️ keeps moving <strong>until it reaches the end</strong> (fast.next == null).</li><li>When Fast is at the last node, <strong>Slow</strong> 🐢 will be <strong>right before the node we want to delete</strong>! 🎯</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/691/1*QjNmtO2mJvvfqUohl_pz7A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/691/1*95sJaCbp8ntFYE-lIOdNLA.png" /></figure><p><strong>4.Snip It Out! ✂️</strong></p><ul><li>Now that <strong>Slow</strong> is just before the target node, we simply say:<br>slow.next = slow.next.next</li><li>This makes <strong>Slow</strong> skip the next node and point directly to the one after it.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/691/1*NENnZlambjL4WAMKu0KamQ.png" /></figure><p><strong>5.Return the Head 🎁</strong>:</p><ul><li>The list is now fixed, and the unwanted node is gone! 🎊</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/571/1*i2WttYZWAqEen7uI6CsNIg.png" /></figure><h4>🎊 Why is this Cool?</h4><ul><li>You don’t need to count the total nodes! 🚫</li><li>You just use <strong>two pointers</strong> to solve it in <strong>one pass</strong>! ✅</li></ul><pre>class Solution {<br>    public ListNode removeNthFromEnd(ListNode head, int n) {<br>        // Create a dummy node to handle edge cases (like removing the head node)<br>        ListNode dummy = new ListNode(0, head);  <br>        ListNode slow = dummy; // Slow pointer 🐢<br>        ListNode fast = head;  // Fast pointer 🏃‍♂️<br><br>        // Step 1: Move the fast pointer `n` steps ahead<br>        for (int i = 0; i &lt; n; i++) {<br>            fast = fast.next;<br>        }<br><br>        // Step 2: Move slow and fast pointers one step at a time until fast reaches the end<br>        while (fast != null) {<br>            fast = fast.next;   // Fast moves ahead<br>            slow = slow.next;   // Slow follows<br>        }<br><br>        // Step 3: Remove the target node<br>        slow.next = slow.next.next;<br><br>        // Step 4: Return the new head<br>        return dummy.next;        <br>    }<br>}</pre><h4>⏳ Time Complexity:</h4><ul><li><strong>O(n) n is the size of linked list</strong></li></ul><h4>📦 Space Complexity:</h4><ul><li>The space complexity is <strong>O(1)</strong> (constant space).</li></ul><p>Now I think you’re comfortable with this problem now. Let’s move on to the next one. 🚀</p><h3>Problem - 2 : <a href="https://leetcode.com/problems/intersection-of-two-linked-lists/">Intersection of Two Linked Lists</a></h3><p><strong>Problem statement :- Given the heads of two singly linked-lists </strong><strong>headA and </strong><strong>headB, return <em>the node at which the two lists intersect</em>. If the two linked lists have no intersection at all, return </strong><strong>null.</strong></p><p>For example, the following two linked lists begin to intersect at node c1:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/742/0*tqdCCT3m6Zq6IJAU.png" /></figure><h4>Understanding the Problem 🤔</h4><p>Think of two roads:</p><ul><li>One long road 🛣️ (linked list A)</li><li>One shorter road 🚗 (linked list B)</li></ul><p>They <strong>merge</strong> at a particular point.<br>Our job is to <strong>find that merge point</strong> (intersection node).</p><blockquote><strong>Key Idea 💡</strong></blockquote><blockquote>When two linked lists <strong>intersect</strong>, they share the same nodes <strong>from the intersection point onwards</strong>. 🚦</blockquote><blockquote>So, the plan is simple:</blockquote><blockquote>- Find the <strong>length</strong> of both lists.</blockquote><blockquote>- Move the pointer of the <strong>longer list</strong> ahead by the difference in lengths.</blockquote><blockquote>- From there, move both pointers together until they meet at the intersection node.</blockquote><h4><strong>Step-by-Step Solution 📝</strong></h4><ol><li><strong>Find the Length of Both Lists</strong> 📏:</li></ol><ul><li>Count the number of nodes in <strong>list A</strong> → call it m.</li><li>Count the number of nodes in <strong>list B</strong> → call it n.</li><li>Find the <strong>difference</strong>: diff = |m - n|.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*SPqjcs91ruWy3j-4rspp-Q.png" /></figure><p><strong>2. Adjust the Starting Point</strong> ⏩:</p><ul><li>Move the pointer of the <strong>longer list</strong> ahead by diff steps.</li><li>Now both lists have the <strong>same number of nodes left</strong> to traverse. 🎯</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/791/1*NDrr-D7IGgSC99hhES1YPA.png" /></figure><p><strong>3. Move Together 🏃‍♂️🐢</strong>:</p><ul><li>Move both pointers one step at a time.</li><li>The point where they <strong>meet</strong> is the <strong>intersection node</strong>.</li><li>If they don’t meet, return null.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/791/1*Cfj9PRQtDD827brb-hx8Tg.png" /></figure><p>By aligning the lists to start at the same distance from the <strong>end</strong>, we ensure that the pointers will meet at the intersection node, if it exists.</p><pre>public class Solution {<br>    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {<br>        // Step 1: Find the lengths of both lists<br>        int lengthA = getLength(headA);<br>        int lengthB = getLength(headB);<br><br>        // Step 2: Find the difference in lengths<br>        int diff = Math.abs(lengthA - lengthB);<br><br>        // Step 3: Move the pointer of the longer list ahead by &#39;diff&#39; steps<br>        ListNode longer = lengthA &gt; lengthB ? headA : headB;<br>        ListNode shorter = lengthA &gt; lengthB ? headB : headA;<br><br>        for (int i = 0; i &lt; diff; i++) {<br>            longer = longer.next;<br>        }<br><br>        // Step 4: Move both pointers together until they meet<br>        while (longer != null &amp;&amp; shorter != null) {<br>            if (longer == shorter) { // Intersection found<br>                return longer;<br>            }<br>            longer = longer.next;<br>            shorter = shorter.next;<br>        }<br><br>        // Step 5: If no intersection, return null<br>        return null;<br>    }<br><br>    // Helper function to calculate the length of a linked list<br>    private int getLength(ListNode head) {<br>        int length = 0;<br>        while (head != null) {<br>            length++;<br>            head = head.next;<br>        }<br>        return length;<br>    }<br>}</pre><h4>⏳ Time Complexity:</h4><ul><li><strong>O(m + n)</strong>: Calculating lengths + traversing the lists.</li></ul><h4>📦 Space Complexity:</h4><ul><li><strong>O(1)</strong>: No extra space used</li></ul><h3>Problem -3 <a href="https://leetcode.com/problems/middle-of-the-linked-list/">Middle of the Linked List</a></h3><p><strong>Problem statement :- Given the head of a singly linked list, find and return the middle node of the list</strong>. If there are <strong>two middle nodes</strong> (in the case of an even-length list), return the <strong>second middle node</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/544/0*g4IYBOevXMHV9gFs.jpg" /><figcaption>For odd list</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/664/0*GuQrP81zcGz5gYBR.jpg" /><figcaption>For even list return second middle node</figcaption></figure><blockquote>🧠 Key Idea: Again Slow and Fast Pointer Strategy</blockquote><blockquote>We use two pointers:</blockquote><blockquote><strong>Slow Pointer</strong> 🐢: Moves <strong>1 step</strong> at a time.</blockquote><blockquote><strong>Fast Pointer</strong> 🏃‍♂️: Moves <strong>2 steps</strong> at a time.</blockquote><blockquote>By the time the <strong>fast pointer</strong> reaches the <strong>end</strong> of the list, the <strong>slow pointer</strong> will be at the <strong>middle node</strong>.</blockquote><h3>📝 Step-by-Step Solution</h3><ol><li><strong>Initialize both pointers at the head of the list:</strong></li></ol><ul><li>slow = head 🐢</li><li>fast = head 🏃‍♂️</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/791/1*Or-yS96XbzqqMY4adJugNA.png" /></figure><p><strong>2. Move the pointers using a while loop:</strong></p><ul><li>Move slow by <strong>1 step</strong> → slow = slow.next.</li><li>Move fast by <strong>2 steps</strong> → fast = fast.next.next.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/791/1*nYZTtjZH5HcCYlUivea-7A.png" /><figcaption>Here fast is moved 2 times and slow one time</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/791/1*n_eGyF5xo_O8POh0cKOq_g.png" /><figcaption>Again fast is 2X of slow</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/791/1*xZ_v5d0nbJsWmSAAoCwomQ.png" /><figcaption>Now fast has reached to null</figcaption></figure><p><strong>3. Terminate the loop when:</strong></p><ul><li><strong>Odd Length</strong> → fast.next == null (fast reaches the end).</li><li><strong>Even Length</strong> → fast == null (fast skips over null).</li></ul><p><strong>4. Return the node where </strong><strong>slow stops — that’s the middle of the list. 🎯</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/791/1*sWgwbUQ936ZQbyKo9Jecow.png" /></figure><pre>class Solution {<br>    public ListNode middleNode(ListNode head) {<br>        // Step 1: Initialize slow and fast pointers<br>        ListNode slow = head;  // 🐢 moves 1 step at a time<br>        ListNode fast = head;  // 🏃‍♂️ moves 2 steps at a time<br><br>        // Step 2: Traverse the list<br>        while (fast != null &amp;&amp; fast.next != null) {<br>            slow = slow.next;       // Move slow pointer by 1 step<br>            fast = fast.next.next;  // Move fast pointer by 2 steps<br>        }<br><br>        // Step 3: Return the middle node<br>        return slow;<br>    }<br>}</pre><h4>⏳ Time Complexity:</h4><ul><li><strong>O(n)</strong>: We traverse the list once, where n is the length of the list.</li></ul><h4>📦 Space Complexity:</h4><ul><li><strong>O(1)</strong>: We use only two pointers (constant space).</li></ul><h3>🎉 That’s a Wrap for This Part! 🚀</h3><p>In this part, we tackled some fundamental <strong>DSA challenges</strong> using optimal and efficient approaches, focusing on <strong>two-pointer techniques</strong> for linked lists. I hope you enjoyed the journey and learned something <strong>amazing</strong> along the way!</p><p>But guess what? <strong>This is just the beginning!</strong> 😎</p><p>In the <strong>next and final part</strong>, we’ll dive into even more challenging and exciting problems that will level up your <strong>DSA skills</strong> and make you a <strong>coding pro</strong>. 💪</p><p>Until next time…<br><strong>Happy Coding! 🚀🔥</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0f91da6b77e5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Ultimate Linked List Guide: Become a Hero with All Methods and Theory in Java (Part-3).]]></title>
            <link>https://medium.com/@vinesh.thakkar/the-ultimate-linked-list-guide-become-a-hero-with-all-methods-and-theory-in-java-part-3-0aacee924828?source=rss-c5266b52f4bc------2</link>
            <guid isPermaLink="false">https://medium.com/p/0aacee924828</guid>
            <category><![CDATA[linked-lists]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[node]]></category>
            <category><![CDATA[deletion]]></category>
            <dc:creator><![CDATA[Vinesh Thakkar]]></dc:creator>
            <pubDate>Wed, 20 Nov 2024 12:03:12 GMT</pubDate>
            <atom:updated>2024-11-20T12:03:12.585Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>In Part 2, we explored the <strong>insertion</strong> and <strong>display</strong> methods for linked lists. If you’re unfamiliar with these concepts, feel free to check them out in detail <a href="https://medium.com/@vinesh.thakkar/the-ultimate-linked-list-guide-become-a-hero-with-all-methods-and-theory-in-java-part-2-3c98d4422ffd"><strong>here</strong></a><strong>.</strong></blockquote><p>Welcome to <strong>Part 3</strong> of our Linked List series! 🚀 In this chapter, we’ll explore two exciting and essential operations: <strong>deletion</strong> and <strong>updation</strong> of nodes.</p><p>These are like your cleanup and editing tools for a linked list, giving you full control to remove or update nodes as needed. Sounds fun, right? Let’s get started! 😄</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/763/1*lxvLj2fgxwQa2_Ozq2Jt0w.png" /><figcaption>Deletion in linked list image from DevsCall</figcaption></figure><p><strong>Deletion</strong> is one of the most fundamental operations in a linked list. Whether you’re removing a node from the <strong>beginning</strong>, <strong>middle</strong>, or <strong>end</strong>, or <strong>clearing the entire list,</strong> mastering deletion is key to efficiently managing your linked list.</p><p>In this section, we’ll cover various deletion techniques, such as removing the first node, deleting at a specific index, clearing the entire list, and even deleting all nodes with a specific value. Let’s dive into each method step by step and understand how deletion works! 🚀</p><ol><li><strong>Deleting first node</strong></li></ol><p>The <strong>deleteAtFirst()</strong> method is one of the simplest ways to remove a node from a linked list. It removes the very first node, also known as the <strong>head</strong>, and makes the second node (if it exists) the new head. Let’s break this down step by step!</p><pre>        void deleteAtFirst() {<br>            if (head == null) {<br>                System.out.println(&quot;No nodes to delete&quot;);<br>            } else {<br>                head = head.next;<br>            }<br>        }</pre><p><strong>Check if the List is Empty</strong></p><pre>if (head == null) {<br>                System.out.println(&quot;No nodes to delete&quot;);<br>            }</pre><ul><li>Before doing anything, we check if the list is empty (head == null).</li><li>If it is, there’s nothing to delete, and we simply inform the user with a friendly message</li></ul><p><strong>Move the Head to the Next Node</strong></p><pre>else {<br>       head = head.next;<br>}</pre><ul><li>If the list is <strong>not empty</strong>, we update the head pointer to the next node in the list (head.next).</li><li>This effectively <strong>removes the first node</strong> because the original head node is no longer referenced by the list!</li></ul><blockquote><strong>Imagine you have a linked list that looks like this:</strong><br>[10] → [20] → [30] → null</blockquote><blockquote><strong>Before Deletion:</strong><br>head → [10] → [20] → [30] → null</blockquote><blockquote><strong>After Calling </strong><strong>deleteAtFirst():</strong><br>head → [20] → [30] → null</blockquote><p>2. <strong>Deleting last node</strong></p><p>The <strong>deleteLast()</strong> method lets us remove the final node in the linked list, also known as the <strong>tail</strong>. This operation ensures the integrity of the list while cleanly disconnecting the last node. Let’s walk through how it works, step by step!</p><pre>        void deleteLast() {<br>            if (head == null) {<br>                System.out.println(&quot;List is empty&quot;);<br>                return;<br>            }<br>            if (head.next == null) {<br>                head = null;<br>                tail = null;<br>                return;<br>            }<br>            Node temp = head;<br>            while (temp.next != tail) {<br>                temp = temp.next;<br>            }<br>            temp.next = null;<br>            tail = temp;<br>        }</pre><p>The Logic Behind deleteLast()</p><p><strong>Check if the List is Empty:</strong></p><ul><li>If the list is empty (head == null), there’s nothing to delete. We print a message and exit the method.</li></ul><p><strong>Handle the Case with One Node:</strong></p><pre>if (head.next == null) {<br>    head = null;<br>    tail = null;<br>    return;<br>}</pre><ul><li>If the list has only one node, we remove it by setting both head and tail to null.</li><li>This clears the list completely.</li></ul><p><strong>Traverse to the Second Last Node:</strong></p><pre>Node temp = head;<br>while (temp.next != tail) {<br>    temp = temp.next;<br>}</pre><ul><li>For longer lists, we use a temporary pointer (temp) to find the <strong>second-to-last node</strong>, i.e., the node just before the current tail.</li></ul><p><strong>Update the Tail:</strong></p><pre>temp.next = null;<br>tail = temp;</pre><ul><li>We disconnect the last node by setting the next pointer of the second-to-last node (temp) to null.</li><li>Then, we update the tail pointer to reference this second-to-last node.</li></ul><blockquote><strong>Let’s visualize a linked list before and after deletion:</strong></blockquote><blockquote><strong>Before Deletion:</strong><br>head → [10] → [20] → [30] → null<br>tail → [30]</blockquote><blockquote><strong>Steps to Delete the Last Node:</strong></blockquote><blockquote>Traverse to the second-to-last node: [20].</blockquote><blockquote>Set its next to null.</blockquote><blockquote>Update tail to point to [20].</blockquote><blockquote><strong>After Deletion:</strong><br>head → [10] → [20] → null<br>tail → [20]</blockquote><p>The last node [30] is successfully removed, and the list remains intact! 🎉.</p><p>3. <strong>Deleting nodes at a specific index</strong></p><p>The <strong>deleteAtIndex()</strong> method allows us to carefully remove a node from any position in the linked list. This operation is a bit more <strong>intricate</strong> than removing the first or last node, as it involves carefully navigating to the target index. Let’s explore how this works, step by step! 🚀</p><pre>  void deleteAtIndex(int index) {<br>            Node ll = head;<br><br>            if (index == 0) {<br>                deleteAtFirst();<br>                return;<br>            }<br>            for (int i = 0; i &lt; index - 1; i++) {<br>                if (ll == null || ll.next == null) {<br>                    System.out.println(&quot;Index out of bounds&quot;);<br>                    return;<br>                }<br>                ll = ll.next;<br>            }<br>            ll.next = ll.next.next;<br>        }</pre><p>The Logic Behind deleteAtIndex()</p><p><strong>Handle the Case for Index 0:</strong></p><ul><li>If the target index is 0, we delegate the operation to the deleteAtFirst() method, which efficiently removes the head node.</li></ul><p><strong>Traverse to the Node Before the Target Index:</strong></p><pre>for (int i = 0; i &lt; index - 1; i++) {<br>    if (ll == null || ll.next == null) {<br>        System.out.println(&quot;Index out of bounds&quot;);<br>        return;<br>    }<br>    ll = ll.next;<br>}</pre><ul><li>Using a loop, we move a pointer (ll) to the node <strong>just before</strong> the target index.</li><li>If we reach the end of the list before finding this node, we display an “Index out of bounds” message and stop.</li></ul><p><strong>Remove the Target Node:</strong></p><ul><li><em>ll.next = ll.next.next;</em></li><li>The next pointer of the node at index - 1 is updated to skip over the target node and point directly to the node after it.</li><li>This effectively removes the node at the specified index, as it’s no longer referenced in the list.</li></ul><blockquote><strong>Let’s visualize a deletion scenario step by step:</strong></blockquote><blockquote><strong>Before Deletion:</strong><br>head → [10] → [20] → [30] → [40] → null</blockquote><blockquote><strong>Deleting the Node at Index 2 (value </strong><strong>[30]):</strong></blockquote><blockquote>Traverse to the node at index 1 ([20]).</blockquote><blockquote>Update its next pointer to skip over [30] and point to [40].</blockquote><blockquote><strong>After Deletion:</strong><br>head → [10] → [20] → [40] → null</blockquote><p>The node [30] is successfully removed, and the list structure remains intact! 🎉</p><p>Why this method works !!</p><ul><li>It can delete any node at any valid position, making it incredibly flexible.</li><li>It ensures out-of-bounds indices are gracefully handled with clear feedback.</li></ul><p>4. Delete All nodes</p><p>The <strong>deleteAll()</strong> method wipes the slate clean by removing every node from the linked list. It’s like hitting the reset button — the entire list is cleared, leaving no trace of the previous nodes. Let’s explore how this works! 🌟</p><pre>        void deleteAll() {<br>            head = null;<br>            tail = null;<br>            System.out.println(&quot;All nodes deleted&quot;);<br>        }</pre><p>The Logic Behind deleteAll()</p><p><strong>Reset the Head and Tail:</strong></p><ul><li>Setting both head and tail to null effectively disconnects the entire linked list.</li><li>Since there are no references to any nodes, they are automatically <strong>garbage-collected</strong> in Java.</li></ul><p><strong>Why it’s useful</strong></p><ul><li>Quickly clears the entire linked list, saving time compared to deleting nodes one by one.</li><li>Perfect for starting over or reinitializing a linked list.</li></ul><p>The <strong>deleteAll()</strong> method is a simple yet powerful tool to reset your linked list. It’s the ultimate clean-up operation, ensuring no dangling references are left behind</p><blockquote>As a <strong>bonus</strong>, let’s add another exciting method to our linked list toolkit: <strong>deleteAllSpecificValue</strong></blockquote><p>This method will allow you to delete <strong>every single occurrence</strong> of a specific value in the linked list — no matter where it appears. Whether it’s at the beginning, middle, or end, this method will remove them all!</p><pre> void deleteAllValue(int value) {<br>            if (head == null) {<br>                System.out.println(&quot;List is empty&quot;);<br>                return;<br>            }<br>            while (head != null &amp;&amp; head.data == value) {<br>                head = head.next;<br>            }<br><br>            Node temp = head;<br><br>            while (temp != null &amp;&amp; temp.next != null) {<br>                if (temp.next.data == value) {<br>                    temp.next = temp.next.next;<br>                } else {<br>                    temp = temp.next;<br>                }<br>            }<br><br>            tail = temp;<br>        }</pre><p>Let’s break it down step by step. 🚀</p><p><strong>Check if the List is Empty:</strong></p><ul><li>First, we check if the list is empty. If the list is null, there are no nodes to delete, and we simply inform the user.</li></ul><p><strong>Remove Matching Values at the Head:</strong></p><pre>while (head != null &amp;&amp; head.data == value) {<br>    head = head.next;<br>}</pre><ul><li>The first step is to check if the head node contains the value we want to delete.</li><li>If the head node holds the specified value, we update head to point to the next node. This effectively removes the head node from the list.</li><li>We repeat this check until we either find a node with a different value or the list becomes empty.</li></ul><p><strong>Traverse the List and Remove Matching Nodes (Main part) :</strong></p><pre>Node temp = head;<br><br>while (temp != null &amp;&amp; temp.next != null) {<br>    if (temp.next.data == value) {<br>        temp.next = temp.next.next;<br>    } else {<br>        temp = temp.next;<br>    }<br>}</pre><ul><li>Now we use a temporary pointer (temp) to traverse the rest of the list.</li><li>Whenever a node’s next value matches the value we want to delete, we simply skip it by pointing temp.next to the next node (effectively deleting it).</li><li>If the node doesn’t match, we move temp forward to the next node.</li></ul><p><strong>Update the Tail (if needed):</strong></p><pre>tail = temp;</pre><ul><li>Once the traversal is complete, the tail pointer might need updating if the last node was deleted. We update the tail to point to the last node (temp).</li></ul><blockquote><strong>How it works :</strong></blockquote><blockquote>Let’s say our linked list looks like this:</blockquote><blockquote><strong>Before Deletion (Value = 20):</strong><br>head → [10] → [20] → [30] → [20] → [40] → null<br>tail → [40]</blockquote><blockquote>Now, when we call deleteAllValue(20), the method will:</blockquote><blockquote>Remove both occurrences of 20 in the list.</blockquote><blockquote>Adjust the head and tail if necessary.</blockquote><blockquote><strong>After Deletion:</strong><br>head → [10] → [30] → [40] → null<br>tail → [40]</blockquote><p>As you can see, all instances of 20 have been removed! 🎉</p><p>With the <strong>deleteAllValue(int value)</strong> method, you have the power to remove every instance of a specific value from your linked list in a <strong>single pass.</strong></p><h4>Why It’s Awesome:</h4><ul><li><strong>Efficient and thorough:</strong> It doesn’t just delete one occurrence, it removes <strong>all occurrences</strong> of the specified value.</li><li><strong>No mess left behind:</strong> The list remains perfectly connected and consistent, with the head and tail pointers updated as needed.</li></ul><p>Let’s combine all of them …</p><pre><br>public class LinkedList {<br><br>    public static class Node {<br><br>        int data;<br>        Node next;<br><br>        Node(int data) {<br>            this.data = data;<br>        }<br>    }<br><br>    public static class linkedlist {<br>        Node head = null;<br>        Node tail = null;<br><br>        void insertAtStart(int val) {<br>            Node temp = new Node(val);<br><br>            if (head == null) {<br>                head = temp;<br>                tail = temp;<br>            } else {<br>                temp.next = head;<br>                head = temp;<br>            }<br><br>        }<br><br>        int size() {<br>            Node disp = head;<br>            int count = 0;<br>            while (disp != null) {<br>                count += 1;<br>                disp = disp.next;<br>            }<br><br>            return count;<br>        }<br><br>        void display() {<br><br>            Node disp = head;<br><br>            while (disp != null) {<br>                System.out.print(disp.data + &quot; -&gt; &quot;);<br>                disp = disp.next;<br>            }<br>            System.out.print(&quot;null&quot;);<br>            System.out.println();<br>        }<br><br>        void deleteAtFirst() {<br>            if (head == null) {<br>                System.out.println(&quot;No nodes to delete&quot;);<br>            } else {<br>                head = head.next;<br>            }<br>        }<br><br>        void deleteAtIndex(int index) {<br>            Node ll = head;<br><br>            if (index == 0) {<br>                deleteAtFirst();<br>                return;<br>            }<br>            for (int i = 0; i &lt; index - 1; i++) {<br>                if (ll == null || ll.next == null) {<br>                    System.out.println(&quot;Index out of bounds&quot;);<br>                    return;<br>                }<br>                ll = ll.next;<br>            }<br>            ll.next = ll.next.next;<br>        }<br><br>        void deleteAll() {<br>            head = null;<br>            tail = null;<br>            System.out.println(&quot;All nodes deleted&quot;);<br>        }<br><br>        void deleteLast() {<br>            if (head == null) {<br>                System.out.println(&quot;List is empty&quot;);<br>                return;<br>            }<br>            if (head.next == null) {<br>                head = null;<br>                tail = null;<br>                return;<br>            }<br>            Node temp = head;<br>            while (temp.next != tail) {<br>                temp = temp.next;<br>            }<br>            temp.next = null;<br>            tail = temp;<br>        }<br><br>        void deleteAllValue(int value) {<br>            if (head == null) {<br>                System.out.println(&quot;List is empty&quot;);<br>                return;<br>            }<br>            while (head != null &amp;&amp; head.data == value) {<br>                head = head.next;<br>            }<br><br>            Node temp = head;<br><br>            while (temp != null &amp;&amp; temp.next != null) {<br>                if (temp.next.data == value) {<br>                    temp.next = temp.next.next;<br>                } else {<br>                    temp = temp.next;<br>                }<br>            }<br><br>            tail = temp;<br>        }<br><br>    }<br><br>    public static void main(String[] args) {<br><br>        linkedlist ll = new linkedlist();<br>        ll.insertAtStart(5);<br>        ll.insertAtStart(4);<br>        ll.insertAtStart(4);<br>        ll.insertAtStart(3);<br>        ll.insertAtStart(2);<br>        ll.insertAtStart(1);<br><br>        System.out.println(&quot;Initial list: &quot;);<br>        ll.display();<br>        System.out.println(&quot;After deleting first node&quot;);<br>        ll.deleteAtFirst();<br>        ll.display();<br>        System.out.println(&quot;After deleting last node&quot;);<br>        ll.deleteLast();<br>        ll.display();<br>        System.out.println(&quot;After deleting index 2&quot;);<br>        ll.deleteAtIndex(2);<br>        ll.display();<br>        System.out.println(&quot;After deleting all values that are 4&quot;);<br>        ll.deleteAllValue(4);<br>        ll.display();<br>        System.out.println(&quot;Deleting all nodes&quot;);<br>        ll.deleteAll();<br>        ll.display();<br><br>    }<br>}</pre><p><strong>By running this code it will give output as :</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/351/1*zWpfhuZajHBU3eYzW-Miog.png" /><figcaption>output of above code</figcaption></figure><h3>Updation of an specific node</h3><p>In addition to deleting and inserting nodes, there’s another critical operation in a linked list: <strong>updating the value of a specific node.</strong></p><p>This method allows you to update the value of a node at a given index — perfect for when you need to modify a value without altering the overall structure of the list.</p><pre>        void update(int index, int value) {<br>            // Check if the list is empty<br>            if (head == null) {<br>                System.out.println(&quot;List is empty&quot;);<br>                return;<br>            }<br><br>            Node temp = head;<br>            int currentIndex = 0;<br><br>            while (temp != null &amp;&amp; currentIndex &lt; index) {<br>                temp = temp.next;<br>                currentIndex++;<br>            }<br>            if (temp == null) {<br>                System.out.println(&quot;Index out of bounds&quot;);<br>                return;<br>            }<br><br>            temp.data = value;<br>        }</pre><p>The Logic Behind update(int index, int value)</p><p><strong>Check if the List is Empty:</strong></p><ul><li>We start by checking if the linked list is empty. If the list is empty (head is null), there’s nothing to update, and we inform the user that the list is empty.</li></ul><p><strong>Traverse the List to Find the Desired Node:</strong></p><pre>Node temp = head;<br>int currentIndex = 0;<br><br>while (temp != null &amp;&amp; currentIndex &lt; index) {<br>    temp = temp.next;<br>    currentIndex++;<br>}</pre><ul><li>We then use a temporary pointer (temp) to traverse the list.</li><li>We also track the current index as we move through the nodes.</li><li>We continue traversing until we reach the node at the specified index or until we reach the end of the list.</li></ul><p><strong>Handle Out-of-Bounds Indices:</strong></p><ul><li>If we reach the end of the list (temp == null) before reaching the desired index, it means the index is out of bounds. In this case, we notify the user that the index is invalid.</li></ul><p><strong>Update the Value of the Node:</strong></p><p><em>temp.data = value;</em></p><ul><li>Once we find the node at the specified index, we update its value (temp.data) to the new value passed as a parameter.</li></ul><blockquote>How’s this works :</blockquote><blockquote>Let’s say our linked list looks like this:</blockquote><blockquote><strong>Before Update:</strong><br>head → [10] → [20] → [30] → [40] → null</blockquote><blockquote>Now, if we call update(2, 50):</blockquote><blockquote>The method will traverse the list to the node at index 2 (which is 30).</blockquote><blockquote>It will then update the value of that node to 50.</blockquote><blockquote><strong>After Update:</strong><br>head → [10] → [20] → [50] → [40] → null</blockquote><p>As you can see, the value at index 2 has been successfully updated to 50! 🎉</p><p>The <strong>update(int index, int value)</strong> method gives you the power to change the value of a specific node in your linked list, while keeping the rest of the list intact.</p><p><strong>Great job</strong>! 🎉 You’ve now learned the fundamental operations of <strong>deletion</strong> and <strong>updation</strong> in a linked list, along with detailed explanations to help you understand every step.</p><p>With these concepts under your belt, you’re well on your way to mastering linked lists and their applications.</p><p>And guess what? The journey doesn’t stop here! 🚀 In the next part, we’re going to dive into <strong>searching</strong> nodes in a linked list, <strong>detecting cycles</strong>, and even tackling some <strong>basic DSA problems</strong>. Curious yet? Stay tuned, because we’ve got some exciting content coming your way! 🔍✨</p><p>Keep coding and keep exploring — the best is yet to come! 😎💻</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0aacee924828" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Ultimate Linked List Guide: Become a Hero with All Methods and Theory in Java (Part-2).]]></title>
            <link>https://medium.com/@vinesh.thakkar/the-ultimate-linked-list-guide-become-a-hero-with-all-methods-and-theory-in-java-part-2-3c98d4422ffd?source=rss-c5266b52f4bc------2</link>
            <guid isPermaLink="false">https://medium.com/p/3c98d4422ffd</guid>
            <category><![CDATA[display]]></category>
            <category><![CDATA[linked-lists]]></category>
            <category><![CDATA[insertion]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Vinesh Thakkar]]></dc:creator>
            <pubDate>Tue, 19 Nov 2024 12:59:59 GMT</pubDate>
            <atom:updated>2024-11-20T03:59:15.065Z</atom:updated>
            <content:encoded><![CDATA[<p>In <strong>Part 1</strong>, we covered the basics of linked lists, including what a linked list is, what a node represents, and how to create a linked list. If you’re unfamiliar with linked lists, I highly recommend reviewing <strong>Part 1</strong> for a better understanding. You can find it <a href="https://medium.com/@vinesh.thakkar/the-ultimate-linked-list-guide-become-a-hero-with-all-methods-and-theory-in-java-part-1-4500327ea198">here</a>.</p><h4>In this part, we’ll focus on <strong>insertion</strong> and <strong>display</strong> methods for linked lists.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/298/1*UzA4nZLuPBte7m-KxjMuWQ.png" /><figcaption>Insertion in ll</figcaption></figure><p><strong>Insertion</strong> is one of the most fundamental operations in a linked list. Whether you’re adding a node at the <strong>beginning</strong>, <strong>middle</strong>, or <strong>end</strong>, understanding how insertion works is key to mastering linked lists.</p><p>In this section, we’ll cover the different ways to insert nodes and walk through the implementation step by step.</p><p>We shall adopt a standard structure for all parts of this guide for maintaining uniformity and orderliness of our code. We shall make a LinkedList class and define all these methods within this class.</p><p>This way, our coding is kept organized and simple as well as no repetition occurs.<br>Here’s the sample template of linkedlist class.</p><pre>public class LinkedList {<br>    public static class Node {<br><br>        int data;<br>        Node next;<br><br>        Node(int data) {<br>            this.data = data;<br>        }<br>    }<br><br>    public static class linkedlist {<br>    //Adding head and tail to maintain the ll        <br>        Node head = null;<br>        Node tail = null;<br>    <br>    // All the methods will lay here<br>    <br>    }<br>    public static void main(String[] args) {<br>    <br>        linkedlist ll = new linkedlist();<br><br>    }<br>}</pre><p>By structuring our code this way, we no longer need to explicitly manage node creation and maintenance of the linked list. The <strong>LinkedList</strong> class will handle all operations internally, making it easier and more efficient to work .</p><p>As mentioned earlier we can add node anywhere in the ll start, end , or in the middle of the linked list.We’ll go one by one</p><h3>1.Insert at start</h3><p>Let’s break down the <strong>insertAtStart</strong> method step by step. This method is used to add a new node to the beginning of our linked list.</p><pre>  void insertAtStart(int val) {<br>        Node temp = new Node(val);<br><br>        if (head == null) {<br>            head = temp;<br>            tail = temp;<br>        } else {<br>            temp.next = head;<br>            head = temp;<br>        }<br>    }</pre><ol><li><strong>Creating a new node:</strong></li></ol><p><em>Node temp = new Node(val);</em></p><p>Here, we’re creating a brand-new node called temp and giving it the value val (whatever value we want to insert). Think of temp as a new box that we want to place at the start of our linked list.</p><p>2. <strong>Checking if the list is empty:</strong></p><pre>if (head == null) {<br>            head = temp;<br>            tail = temp;<br>        }</pre><p>Now, we check if our linked list is empty by seeing if head is null. If it is, it means there’s no list yet! So, we make both head and tail point to our new node temp.</p><ul><li>Since there’s only one node, it’s both the start and the end of the list.</li></ul><p>3. <strong>If the list already has nodes</strong></p><pre>else {<br>    temp.next = head;<br>    head = temp;<br>}</pre><p>If the list isn’t empty, things get a bit more <strong>exciting</strong>!</p><ul><li>We make our new node (temp) point to the current first node of the list by setting temp.next = head. This step ensures our new node is connected to the rest of the list.</li><li>Then, we move the head pointer to temp, making it the new first node of the list.</li></ul><blockquote><strong>And that’s it! 🎉 Now, the new node is sitting at the start of our linked list.</strong></blockquote><p>Here’s a quick visualization:</p><ul><li><strong>Before Insertion:</strong><br>head → [10] → [20] → [30] → null</li><li><strong>After inserting </strong><strong>5 at the start:</strong><br>head → [5] → [10] → [20] → [30] → null</li></ul><p>By following these steps, you can easily add nodes at the beginning of a linked list.</p><h3>2.Insert at end.</h3><p>Let’s break down the <strong>insertAtEnd</strong> method step by step. This method is used to add a new node to the end of our linked list.</p><pre>        void insertAtEnd(int val) {<br>            Node temp = new Node(val);<br><br>            if (head == null) {<br>                head = temp;<br>                tail = temp;<br>            } else {<br>                tail.next = temp;<br>                tail = temp;<br>            }<br>        }</pre><p>We have first two common steps creating an temp node and checking if the list is empty or not , tha was covered previously in adding at start.</p><p>Focusing on the main part else one.</p><pre>else {<br>                tail.next = temp;<br>                tail = temp;<br>            }</pre><p>If the list isn’t empty, we do the following:</p><ul><li>Make the current last node (pointed to by tail) connect to the new node temp by setting tail.next = temp.</li><li>Then, update tail to point to the new node, making it the new last node in the list.</li></ul><p><strong>And that’s it! 🎉 The new node is now sitting happily at the end of the list.</strong></p><p>Here’s a quick visualization:</p><p><strong><em>insertAtEnd(40)</em></strong></p><ul><li><strong>Before Insertion:</strong><br>head → [10] → [20] → [30] → tail → null</li><li><strong>After inserting </strong><strong>40 at the end:</strong><br>head → [10] → [20] → [30] → [40] → tail → null</li></ul><h3>3. Insert at index:</h3><p>Alright, now let’s dive into something even cooler — inserting a node at a <strong>specific index</strong> in the linked list!😎 Sounds interesting, right? Let’s break it down step-by-step and see how we can place a node exactly where we want it in the list.</p><pre> void insertAtIndex(int index, int val) {<br>            if (index == 0) {<br>                insertAtStart(val);<br>                return;<br>            }<br>            if (index == size()) {<br>                insertAtEnd(val);<br>                return;<br>            }<br>            Node temp = new Node(val);<br>            Node ll = head;<br><br>            for (int i = 0; i &lt; index - 1; i++) {<br>                if (ll == null || ll.next == null) {<br>                    System.out.println(&quot;Index out of bounds&quot;);<br>                    return;<br>                }<br>                ll = ll.next;<br>            }<br><br>            temp.next = ll.next;<br>            ll.next = temp;<br>        }</pre><ol><li><strong>Handling Edge Cases (First and Last Position):</strong><br>Before we go into the fun part, let’s handle two simple cases:</li></ol><ul><li><strong>Inserting at the beginning:</strong> If the index is 0, we already know what to do — just use the <strong>insertAtStart</strong> method and we’re done! 🚀</li><li><strong>Inserting at the end:</strong> If the index is exactly the size of the list, that means we want to add the node at the very end. We can easily handle this with the <strong>insertAtEnd</strong> method. Simple, right? ✨</li><li>Now , you are wondering what is this size() ,this method just simply calculates the size or length of the linked list.Here’s the function of the size.</li></ul><pre>        int size() {<br>            Node disp = head;<br>            int count = 0;<br>            while (disp != null) {<br>                count += 1;<br>                disp = disp.next;<br>            }<br><br>            return count;<br>        }</pre><p>2.<strong> Creating a New Node:</strong></p><pre>Node temp = new Node(val);</pre><p>Here, we’re creating a brand-new node, temp, with the value val that we want to insert. Think of it as a fresh, shiny new box ready to be added to our linked list!</p><p>3.<strong> Navigating the right spot:</strong></p><p>Now the real fun begins! 🏃‍♂️ We need to find the <strong>exact position</strong> where we. want to insert our new node. To do that, we start from the head of the list and move forward until we reach the node just before the desired position.</p><ul><li>We use a <strong>for loop</strong> to walk through the list. The condition i &lt; index - 1 ensures that we stop right before the node at the desired index.</li><li>If we can’t find the position (for example, the index is out of bounds), we stop and print &quot;Index out of bounds&quot; — no problem, we’ve catch that! 🙅‍♂️</li></ul><p><strong>4. Inserting the Node:</strong><br> Once we’ve reached the right position, we’re almost there! Here’s how we add the new node:</p><pre>temp.next = ll.next;<br>ll.next = temp;</pre><p>Step 1<strong>:</strong> We make temp (our new node) point to the node after ll (the node just before the desired index). This keeps the list connected.</p><p>Step 2<strong>:</strong> We make the previous node (ll) point to temp, inserting it in the desired position! 🎉</p><p><strong><em>And there you have it — a perfectly inserted node at any given index.it’s like a mini adventure through the list. The best part? You’re in control of where each node goes! 🚀</em></strong></p><p>Here’s a quick example to visualize:</p><p><em>insertAtIndex(2,25)</em></p><ul><li><strong>Before Insertion:</strong><br>head → [10] → [20] → [30] → [40] → null</li><li><strong>After inserting </strong><strong>25 at index 2:</strong><br>head → [10] → [20] → [25] → [30] → [40] → null</li></ul><h3>Here’s the full code template of the inserting at all three positions.</h3><pre><br>public class LinkedList {<br><br>    public static class Node {<br><br>        int data;<br>        Node next;<br><br>        Node(int data) {<br>            this.data = data;<br>        }<br>    }<br><br>    public static class linkedlist {<br>        //Adding head and tail to maintain the ll        <br><br>        Node head = null;<br>        Node tail = null;<br><br>        void insertAtStart(int val) {<br>            Node temp = new Node(val);<br><br>            if (head == null) {<br>                head = temp;<br>                tail = temp;<br>            } else {<br>                temp.next = head;<br>                head = temp;<br>            }<br><br>        }<br><br>        void insertAtEnd(int val) {<br>            Node temp = new Node(val);<br><br>            if (head == null) {<br>                head = temp;<br>                tail = temp;<br>            } else {<br>                tail.next = temp;<br>                tail = temp;<br>            }<br>        }<br><br>        void insertAtIndex(int index, int val) {<br>            if (index == 0) {<br>                insertAtStart(val);<br>                return;<br>            }<br>            if (index == size()) {<br>                insertAtEnd(val);<br>                return;<br>            }<br>            Node temp = new Node(val);<br>            Node ll = head;<br><br>            for (int i = 0; i &lt; index - 1; i++) {<br>                if (ll == null || ll.next == null) {<br>                    System.out.println(&quot;Index out of bounds&quot;);<br>                    return;<br>                }<br>                ll = ll.next;<br>            }<br><br>            temp.next = ll.next;<br>            ll.next = temp;<br>        }<br><br>        int size() {<br>            Node disp = head;<br>            int count = 0;<br>            while (disp != null) {<br>                count += 1;<br>                disp = disp.next;<br>            }<br><br>            return count;<br>        }<br>    }<br><br>    public static void main(String[] args) {<br><br>        linkedlist ll = new linkedlist();<br>        ll.insertAtStart(3);<br>        ll.insertAtStart(45);<br>        ll.insertAtStart(456);<br><br>        ll.insertAtEnd(67);<br>        ll.insertAtEnd(65);<br><br>        ll.insertAtIndex(3,77);<br>        ll.insertAtIndex(4,77);<br>        ll.insertAtIndex(5,77);<br><br>    }<br>}</pre><h4>And just like that, <strong>you’ve mastered inserting nodes at any position</strong> in the linked list. Doesn’t that feel awesome? 😎</h4><p>But but but ! you can’t see the linked list right , no problem lets make an function that displays the linked list formed.</p><h3>Displaying the Linked list</h3><p>Showing the contents of the linked list in a readable way is the next step, and we’ll use this <strong>display</strong> method for that.</p><pre>        void display() {<br><br>            Node disp = head;<br><br>            while (disp != null) {<br>                System.out.print(disp.data + &quot; -&gt; &quot;);<br>                disp = disp.next;<br>            }<br>            System.out.print(&quot;null&quot;);<br>            System.out.println();<br>        }</pre><ol><li><strong>Start from the Head:</strong></li></ol><pre>Node disp = head;</pre><p>We start from the head of the linked list, where the list begins. The disp variable will help us move through the list.</p><p>Make sure you use any temporary variable while traversing an list that keep away the use of actual list and actual list remains safe.</p><p>2.<strong> Traverse the List:</strong></p><pre>   while (disp != null) {<br>                System.out.print(disp.data + &quot; -&gt; &quot;);<br>                disp = disp.next;<br>            }</pre><ul><li>The while loop is like a <em>tour guide</em> that walks through each node in the list.</li><li>As long as the current node (disp) is not null (which would mean we’ve reached the end of the list), we’ll keep going.</li><li>For each node, we print the node’s <strong>data</strong> (its value), followed by &quot; -&gt; &quot; to show that the node is connected to the next one.</li><li>After printing the data, we move to the next node by setting disp = disp.next.</li></ul><p>By the end of the list we print null .</p><p>Imagine you have a list of numbers: 10, 20, 30, 40</p><p>After calling <strong>display()</strong>, it prints:<br>10 -&gt; 20 -&gt; 30 -&gt; 40 -&gt; null</p><p><strong><em>And this </em></strong><strong><em>display method is like your personal window into the list, showing you exactly how the nodes are connected. 🎉</em></strong></p><p>Lets make whole insertion and display in one code template.</p><pre><br>public class LinkedList {<br><br>    public static class Node {<br><br>        int data;<br>        Node next;<br><br>        Node(int data) {<br>            this.data = data;<br>        }<br>    }<br><br>    public static class linkedlist {<br>        //Adding head and tail to maintain the ll        <br><br>        Node head = null;<br>        Node tail = null;<br><br>        void insertAtStart(int val) {<br>            Node temp = new Node(val);<br><br>            if (head == null) {<br>                head = temp;<br>                tail = temp;<br>            } else {<br>                temp.next = head;<br>                head = temp;<br>            }<br><br>        }<br><br>        void insertAtEnd(int val) {<br>            Node temp = new Node(val);<br><br>            if (head == null) {<br>                head = temp;<br>                tail = temp;<br>            } else {<br>                tail.next = temp;<br>                tail = temp;<br>            }<br>        }<br><br>        void insertAtIndex(int index, int val) {<br>            if (index == 0) {<br>                insertAtStart(val);<br>                return;<br>            }<br>            if (index == size()) {<br>                insertAtEnd(val);<br>                return;<br>            }<br>            Node temp = new Node(val);<br>            Node ll = head;<br><br>            for (int i = 0; i &lt; index - 1; i++) {<br>                if (ll == null || ll.next == null) {<br>                    System.out.println(&quot;Index out of bounds&quot;);<br>                    return;<br>                }<br>                ll = ll.next;<br>            }<br><br>            temp.next = ll.next;<br>            ll.next = temp;<br>        }<br><br>        int size() {<br>            Node disp = head;<br>            int count = 0;<br>            while (disp != null) {<br>                count += 1;<br>                disp = disp.next;<br>            }<br><br>            return count;<br>        }<br><br>        void display() {<br><br>            Node disp = head;<br><br>            while (disp != null) {<br>                System.out.print(disp.data + &quot; -&gt; &quot;);<br>                disp = disp.next;<br>            }<br>            System.out.print(&quot;null&quot;);<br>            System.out.println();<br>        }<br><br>    }<br><br>    public static void main(String[] args) {<br><br>        linkedlist ll = new linkedlist();<br>        ll.insertAtStart(3);<br>        ll.insertAtStart(45);<br>        ll.insertAtStart(456);<br><br>        ll.insertAtEnd(67);<br>        ll.insertAtEnd(65);<br><br>        ll.insertAtIndex(3, 77);<br>        ll.insertAtIndex(4, 77);<br>        ll.insertAtIndex(5, 77);<br><br>        ll.display();<br>    }<br>}</pre><p>Output will be as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/459/1*9Yt4d6QO_OWyscNKLQvxgg.png" /></figure><p><strong><em>Now, you can insert nodes at any position, and you’ve learned how to display the entire linked list in a clear and structured way. You’ve mastered the basics of working with linked lists — and now you can confidently manage your data in a dynamic, organized way! 💡</em></strong></p><p>In <strong>Part 3</strong>, we’ll take things a step further. Get ready to dive into <strong>deletion</strong> and <strong>updation</strong> of nodes in the linked list!</p><p>Stay tuned for Part 3, where we’ll explore how to remove nodes from specific positions and update their values. It’s going to be exciting — you won’t want to miss it! 😄</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3c98d4422ffd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Ultimate Linked List Guide: Become a Hero with All Methods and Theory in Java (Part-1).]]></title>
            <link>https://medium.com/@vinesh.thakkar/the-ultimate-linked-list-guide-become-a-hero-with-all-methods-and-theory-in-java-part-1-4500327ea198?source=rss-c5266b52f4bc------2</link>
            <guid isPermaLink="false">https://medium.com/p/4500327ea198</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[linked-list-program]]></category>
            <category><![CDATA[linkedlist-in-java]]></category>
            <dc:creator><![CDATA[Vinesh Thakkar]]></dc:creator>
            <pubDate>Fri, 15 Nov 2024 10:01:59 GMT</pubDate>
            <atom:updated>2024-11-15T10:30:03.003Z</atom:updated>
            <content:encoded><![CDATA[<h3>Overview</h3><blockquote>A Linked List is a linear data structure, in which elements are represented as objects and stored in non-contiguous memory locations. Linked List in Java can be implemented using a custom class or using the Collection framework present in java.util package.</blockquote><h3>Introduction to linked list</h3><p>While we dive deep into linked list first let’s understand why we need this data structure, we have an <em>array</em> as an linear data structure which is widely used , but it has some cons too.</p><h4>CONS of using Array Data structure:</h4><h4>1. Fixed size</h4><p><strong>Issue</strong>: Arrays require us to declare their size first. Once the array is created, it’s size cannot be changed dynamically.</p><p><strong>Impact</strong>: If you don’t know how many elements you’ll need in advance, this can lead to either extra space (if the array is too large) or insufficient space (if the array is too small).</p><h4>2. <strong>No Resizing at Runtime</strong></h4><p><strong>Issue</strong>: Since the size of an array is fixed, it cannot be resized during runtime. If you need more space, you must create a new array and copy the elements over, which can be costly in terms of time and space.</p><p><strong>Impact</strong>: Resizing an array is inefficient, especially in scenarios where the number of elements can vary unpredictably.</p><h4>3.Inserting and deleting inefficiency</h4><p><strong>Issue: </strong>Inserting and deleting any elements other than last requires the shifting of the elements.</p><p><strong>Impact: </strong>The operation may be time consuming especially when we are dealing with the large arrays.</p><p><strong><em>“Linked List saves us in all cases” see how !</em></strong></p><p>Let’s go with the <strong><em>formal definition</em></strong> of the Linked list first, linked list is a linear data structure where each element, or “node,” is stored separately in memory, rather than in a contiguous block. Each <strong>node</strong> contains two parts: the <strong>actual data</strong> (or value) and a<strong> reference</strong> (or link) to the memory address of the next node in the sequence, and in some cases, also the previous node.</p><p>As the name suggests, a Linked List is formed by linking multiple nodes together, allowing them to work as a cohesive linear structure.</p><p>First node is called as <strong>head</strong> and similarly last node is called <strong>tail</strong>, and tail always points to null.</p><h4><strong>Representation of an linked list:</strong></h4><figure><img alt="Reprsentation of the linkedlist" src="https://cdn-images-1.medium.com/max/1024/0*yfmikt5fIWtynyQJ.png" /><figcaption>General representation of ll.</figcaption></figure><p>This representation of a linked list shows that each node consists of two fields, data and pointer which points to second node. The last node(tail) always points to null.</p><h3>Linked list is of two types</h3><ol><li><strong>Singly linked list</strong></li></ol><p>We can say that if the nodes in the linked list are connected in the chained sequence and there is only one pointer that points to it’s next node then that linked list is referred as <strong>Singly linked list</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1hnDN2ctH64XLHsc.png" /><figcaption>Representation of singly ll.</figcaption></figure><p><strong>2. Doubly linked list</strong></p><p>In doubly linked list it way similar like singly ll , the difference between them is a new pointer which is added to node named <strong>previous ,</strong> so in doubly linked list there are three fields <strong>previous pointer</strong> — <strong>data</strong> —<strong> next pointer.</strong></p><p>Here the set of linked nodes attached to each other in a sequential manner such that once can traverse both ways from a node, i.e <em>if we are at a node </em><strong><em>X</em></strong><em> we can go to the node previous of </em><strong><em>X</em></strong><em> or we can go to the node that is followed by </em><strong><em>X</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*DOb-q2NbGM1Ni-RsQN1NQA.png" /><figcaption>Representation of doubly ll.</figcaption></figure><p>As we can see that there are two pointers on each node pointing to both previous and next node , by which now we can traverse both sides backward and forward.</p><h4>Curious to know how the linked list is made in java !!</h4><p>let’s go step by step how to make linked list in java</p><p>Step 1 : Make an class Node in main class.</p><p>As mentioned earlier that linked list is an <strong>user defined data type</strong> i.e we as a user has to make it’s own data type , make an class <strong>Node</strong> inside the main class like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*JD6qdhgkYEjV7CDNfMff-w.png" /><figcaption>Node Data type</figcaption></figure><p>This Node class is static because, it simply means you can use it directly without needing an instance of the outer class. It’s like having a tool that can be used on its own, without needing to carry around the entire toolbox.</p><p>There are two fields in Node class , <strong>data</strong> and <strong>next </strong>data to store the value and next to point the next node.Making of the constructer makes us easy to add the data inside the node while creating new one.</p><p>Now by making the objects of the class Node , actual nodes are created like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*xc-sq-ZqQbx9A54l_00afQ.png" /><figcaption>Making nodes</figcaption></figure><p>Here there are three nodes a ,b and c , look these nodes are just made in the memory somewhere they are not still linked with each other , to link them we have to use <strong>next</strong> , <strong>a.next = b</strong>;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/406/1*OTxyUkR1_AMMgmTG-1jXvA.png" /></figure><p>By linking a with b , b with c , you must be wondering that whom does c is pointing , as the last node always points to null , that’s absolutely correct in java by default pointer always points to null , so we don’t have to explicitly point to null. Let’s now see the output</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/676/1*o4XjlcocwUD0qj8e7M8IRA.png" /></figure><p>By printing the node next data we can see that a is pointing to b (2), and c is pointing to null.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/292/1*rLnKkstWvn9Ou9ZX_Id61A.png" /><figcaption>Output</figcaption></figure><p><strong><em>Hooray, you just created a linked list!!</em></strong></p><p>Now in the second part we’ll see how to insert the node into an existing linked list and deletion then updation and many more to come.</p><p><strong>Thank you</strong> for your attention — stay tuned for the<strong> thrilling second part!</strong></p><p><strong><em>“Every great code journey begins with a single node!”</em></strong></p><p>Keep coding, stay curious, and get ready to dive even deeper into the world of linked lists.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4500327ea198" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>