<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Garvit Khamesra</title>
    <description>The latest articles on DEV Community by Garvit Khamesra (@garvit_khamesra).</description>
    <link>https://dev.to/garvit_khamesra</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F3264040%2Febc3a639-fe68-4773-9f88-5d0a786e099e.png</url>
      <title>DEV Community: Garvit Khamesra</title>
      <link>https://dev.to/garvit_khamesra</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/garvit_khamesra"/>
    <language>en</language>
    <item>
      <title>Python Cheat Sheet: The Basics</title>
      <dc:creator>Garvit Khamesra</dc:creator>
      <pubDate>Sat, 30 Aug 2025 04:08:16 +0000</pubDate>
      <link>https://dev.to/garvit_khamesra/python-cheat-sheet-the-basics-3211</link>
      <guid>https://dev.to/garvit_khamesra/python-cheat-sheet-the-basics-3211</guid>
      <description>&lt;h1&gt;Python Cheat Sheet: The Basics&lt;/h1&gt;

&lt;p&gt;&lt;em&gt;A quick reference for Python fundamentals, ideal for Data Science, AI, and Development learners.&lt;/em&gt;&lt;/p&gt;

&lt;h2&gt;Python Data Types&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;String&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;A sequence of characters stored as text.&lt;/p&gt;

&lt;pre&gt;my_string = "Hello" &lt;/pre&gt;

&lt;p&gt;Common operations:&lt;/p&gt;

&lt;pre&gt;my_string.upper()      # Convert to uppercase&lt;br&gt;
len(my_string)         # Get length&lt;br&gt;
my_string.find('l')    # Find index of first 'l'&lt;br&gt;
my_string.replace('H', 'C')  # Replace 'H' with 'C'&lt;/pre&gt;

&lt;p&gt;&lt;strong&gt;Integer&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Whole numbers.&lt;/p&gt;

&lt;pre&gt;my_integer = 12321 &lt;/pre&gt;

&lt;p&gt;&lt;strong&gt;Float&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Decimal numbers.&lt;/p&gt;

&lt;pre&gt;my_decimal = 3.14 &lt;/pre&gt;

&lt;p&gt;&lt;strong&gt;Boolean&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;True or False values.&lt;/p&gt;

&lt;pre&gt;a = True b = False &lt;/pre&gt;

&lt;p&gt;&lt;strong&gt;Dictionary&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Changeable collection of key-value pairs.&lt;/p&gt;

&lt;pre&gt;my_dictionary = {'banana': 1, 12: 'laptop', (0,0): 'center'}&lt;br&gt;
my_dictionary['banana']      # Access value&lt;br&gt;
my_dictionary.keys()         # List of keys&lt;br&gt;
my_dictionary.values()       # List of values&lt;/pre&gt;

&lt;p&gt;&lt;strong&gt;Tuple&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Unchangeable collection of objects.&lt;/p&gt;

&lt;pre&gt;tup = (1, 3.12, False, "Hi") &lt;/pre&gt;

&lt;p&gt;&lt;strong&gt;List&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Changeable collection of objects.&lt;/p&gt;

&lt;pre&gt;my_collection = [1, 1, 3.12, False, "Hi"]&lt;br&gt;
len(my_collection)           # Length&lt;br&gt;
my_collection.extend(["More", "Items"])  # Add multiple items&lt;br&gt;
my_collection.append("Single")           # Add single item&lt;br&gt;
del(my_collection[2])        # Delete item at index 2&lt;br&gt;
clone = my_collection[:]     # Clone list&lt;br&gt;
my_collection_3 = my_collection + ["a", "b", "c"]  # Concatenate&lt;br&gt;
sum([1,2,3,4.5])             # Sum numbers&lt;br&gt;
item in my_collection        # Check existence&lt;br&gt;
item not in my_collection    # Check non-existence&lt;/pre&gt;

&lt;p&gt;&lt;strong&gt;Set&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Unordered collection of unique objects.&lt;/p&gt;

&lt;pre&gt;a = {100, 3.12, False, "Bye"}&lt;br&gt;
b = {100, 3.12, "Welcome"}&lt;br&gt;
my_set = set([1,1,2,3])      # Convert list to set&lt;br&gt;
a.add(4)                     # Add item&lt;br&gt;
a.remove("Bye")              # Remove item&lt;br&gt;
a.difference(b)              # Set difference&lt;br&gt;
a.intersection(b)            # Set intersection&lt;br&gt;
a.union(b)                   # Set union&lt;br&gt;
a.issubset(b)                # Subset check&lt;br&gt;
a.issuperset(b)              # Superset check&lt;/pre&gt;

&lt;h2&gt;Indexing and Slicing&lt;/h2&gt;

&lt;p&gt;Access elements by position:&lt;/p&gt;

&lt;pre&gt;my_string[0] my_collection[1] my_tup[2] &lt;/pre&gt;

&lt;p&gt;Access a range of elements:&lt;/p&gt;

&lt;pre&gt;my_string[1:4] my_collection[0:3] my_tup[1:3] &lt;/pre&gt;

&lt;h2&gt;Operators&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Comparison Operators&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;span&gt;a == b&lt;/span&gt; : Equal&lt;/li&gt;
&lt;li&gt;
&lt;span&gt;a &amp;lt; b&lt;/span&gt; : Less Than&lt;/li&gt;
&lt;li&gt;
&lt;span&gt;a &amp;gt; b&lt;/span&gt; : Greater Than&lt;/li&gt;
&lt;li&gt;
&lt;span&gt;a &amp;gt;= b&lt;/span&gt; : Greater Than or Equal&lt;/li&gt;
&lt;li&gt;
&lt;span&gt;a &amp;lt;= b&lt;/span&gt; : Less Than or Equal&lt;/li&gt;
&lt;li&gt;
&lt;span&gt;a != b&lt;/span&gt; : Not Equal&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Arithmetic Operators&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;span&gt;+&lt;/span&gt; : Addition&lt;/li&gt;
&lt;li&gt;
&lt;span&gt;-&lt;/span&gt; : Subtraction&lt;/li&gt;
&lt;li&gt;
&lt;span&gt;*&lt;/span&gt; : Multiplication&lt;/li&gt;
&lt;li&gt;
&lt;span&gt;/&lt;/span&gt; : Division&lt;/li&gt;
&lt;li&gt;
&lt;span&gt;//&lt;/span&gt; : Integer Division&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Conditional Operators&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;span&gt;a and b&lt;/span&gt; : True if both are true&lt;/li&gt;
&lt;li&gt;
&lt;span&gt;a or b&lt;/span&gt; : True if either is true&lt;/li&gt;
&lt;li&gt;
&lt;span&gt;not a&lt;/span&gt; : Opposite of a&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;Control Flow&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Loops&lt;/strong&gt;&lt;/p&gt;

&lt;pre&gt;for x in range(5):           # Loop 5 times&lt;br&gt;
    print(x)

&lt;p&gt;for item in iterable:        # Loop through iterable&lt;br&gt;
    print(item)&lt;/p&gt;

&lt;p&gt;while condition:             # Loop while condition is true&lt;br&gt;
    # code&lt;/p&gt;&lt;/pre&gt;

&lt;p&gt;&lt;strong&gt;Conditional Statements&lt;/strong&gt;&lt;/p&gt;

&lt;pre&gt;if condition1:&lt;br&gt;
    # code&lt;br&gt;
elif condition2:&lt;br&gt;
    # code&lt;br&gt;
else:&lt;br&gt;
    # code&lt;/pre&gt;

&lt;p&gt;&lt;strong&gt;Try/Except&lt;/strong&gt;&lt;/p&gt;

&lt;pre&gt;try:&lt;br&gt;
    # code&lt;br&gt;
except ExceptionType:&lt;br&gt;
    # handle error&lt;br&gt;
else:&lt;br&gt;
    # code if no error&lt;/pre&gt;

&lt;h2&gt;Common Error Types&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;span&gt;IndexError&lt;/span&gt; : Index out of range&lt;/li&gt;
&lt;li&gt;
&lt;span&gt;NameError&lt;/span&gt; : Variable name not found&lt;/li&gt;
&lt;li&gt;
&lt;span&gt;SyntaxError&lt;/span&gt; : Code syntax error&lt;/li&gt;
&lt;li&gt;
&lt;span&gt;ZeroDivisionError&lt;/span&gt; : Division by zero&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;Range&lt;/h2&gt;

&lt;p&gt;Create sequences of numbers:&lt;/p&gt;

&lt;pre&gt;range(5) # 0,1,2,3,4 range(2, 10, 2) # 2,4,6,8 &lt;/pre&gt;

&lt;h2&gt;Webscraping&lt;/h2&gt;

&lt;p&gt;Using BeautifulSoup:&lt;/p&gt;

&lt;pre&gt;from bs4 import BeautifulSoup&lt;br&gt;
soup = BeautifulSoup(html, 'html5lib')&lt;br&gt;
soup.prettify()&lt;br&gt;
soup.find('tag')&lt;br&gt;
soup.find_all('tag')&lt;/pre&gt;

&lt;h2&gt;Requests&lt;/h2&gt;

&lt;p&gt;Using the requests library:&lt;/p&gt;

&lt;pre&gt;import requests&lt;br&gt;
response = requests.get(url, params)&lt;br&gt;
response.status_code&lt;br&gt;
response.text&lt;br&gt;
response.json()&lt;br&gt;
requests.post(url, data)&lt;/pre&gt;

&lt;h2&gt;Functions&lt;/h2&gt;

&lt;p&gt;Define and call functions:&lt;/p&gt;

&lt;pre&gt;def my_function(param1, param2):&lt;br&gt;
    # code&lt;br&gt;
    return result

&lt;p&gt;output = my_function(arg1, arg2)&lt;br&gt;
&lt;/p&gt;&lt;/pre&gt;

&lt;h2&gt;Working with Files&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Reading:&lt;/strong&gt;&lt;/p&gt;

&lt;pre&gt;file = open(file_name, "r")&lt;br&gt;
content = file.read()&lt;br&gt;
file.close()&lt;/pre&gt;

&lt;p&gt;&lt;strong&gt;Writing:&lt;/strong&gt;&lt;/p&gt;

&lt;pre&gt;file = open(file_name, "w")&lt;br&gt;
file.write(content)&lt;br&gt;
file.close()&lt;/pre&gt;

&lt;h2&gt;Objects and Classes&lt;/h2&gt;

&lt;p&gt;Define classes and create objects:&lt;/p&gt;

&lt;pre&gt;class MyClass:&lt;br&gt;
    def &lt;strong&gt;init&lt;/strong&gt;(self, param1, param2):&lt;br&gt;
        self.attr1 = param1&lt;br&gt;
        self.attr2 = param2
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def method(self, param):
    return param
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;obj = MyClass(val1, val2)&lt;br&gt;
obj.method(val3)&lt;/p&gt;&lt;/pre&gt;




&lt;p&gt;&lt;strong&gt;List Comprehensions:&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;squares = [x*x for x in range(10)] &lt;/pre&gt;

&lt;p&gt;&lt;strong&gt;Lambda Functions&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;add = lambda x, y: x + y &lt;/pre&gt;

&lt;p&gt;&lt;strong&gt;Importing Modules&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;import math from collections import Counter &lt;/pre&gt;

&lt;p&gt;&lt;strong&gt;Exception Handling: finally&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;try: # code finally: # always runs &lt;/pre&gt;

&lt;p&gt;&lt;strong&gt;With Statement (Context Managers)&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;with open('file.txt', 'r') as f: data = f.read() &lt;/pre&gt;

&lt;p&gt;&lt;strong&gt;Type Conversion&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;int('123')&lt;br&gt;
str(123)&lt;br&gt;
float('3.14')&lt;br&gt;
list('abc')&lt;br&gt;
&lt;/pre&gt;

&lt;p&gt;&lt;strong&gt;Basic Numpy/Pandas Usage&lt;/strong&gt; (for data science focus)&lt;/p&gt;
&lt;pre&gt;import numpy as np&lt;br&gt;
import pandas as pd&lt;br&gt;
arr = np.array([1,2,3])&lt;br&gt;
df = pd.DataFrame({'a':[1,2], 'b':[3,4]})&lt;br&gt;
&lt;/pre&gt;

&lt;p&gt;&lt;strong&gt;Virtual Environments&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;python -m venv myenv source myenv/bin/activate &lt;/pre&gt;

&lt;p&gt;&lt;strong&gt;Package Installation&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;pip install requests &lt;/pre&gt;

&lt;p&gt;&lt;strong&gt;Docstrings&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;def foo(): """This is a docstring.""" pass &lt;/pre&gt;


</description>
      <category>ai</category>
      <category>development</category>
      <category>datascience</category>
      <category>python</category>
    </item>
    <item>
      <title>Java Interview Questions - Part 3</title>
      <dc:creator>Garvit Khamesra</dc:creator>
      <pubDate>Wed, 27 Aug 2025 13:42:06 +0000</pubDate>
      <link>https://dev.to/garvit_khamesra/java-interview-questions-part-3-5hal</link>
      <guid>https://dev.to/garvit_khamesra/java-interview-questions-part-3-5hal</guid>
      <description>&lt;p&gt;&lt;span&gt;Part 3 of the&lt;/span&gt;&lt;strong&gt; Java interview question series&lt;/strong&gt;&lt;span&gt;. In this, we will cover &lt;/span&gt;&lt;/p&gt;


&lt;p&gt;&lt;span&gt;Let's get started&lt;/span&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Q31: What are exceptions? Types of Exceptions?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;&lt;span&gt;A31: Any event/problem that occurs during the execution of the program, due to which the normal flow of code cannot be attained is known as an Exception. It can occur at compile time or runtime.&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;&lt;span&gt;There are 2 types of exceptions&lt;/span&gt;&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Checked Exception &lt;/strong&gt;&lt;span&gt;- The exceptions which occur at compile time and the compiler lets you know of a possible case where your code can fail or give an error. You won't be able to run your code until these are handled. The phenomenon of handling errors is known as &lt;/span&gt;&lt;strong&gt;Exception Handling. &lt;/strong&gt;&lt;span&gt;Eg: &lt;/span&gt;&lt;em&gt;FileNotFoundException.&lt;/em&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Unchecked Exception &lt;/strong&gt;&lt;span&gt;- The exceptions which occur at the runtime, the compilation of the program will be a success. These usually occur because of bad logic or improper use of APIs. Eg: &lt;/span&gt;&lt;em&gt;ArrayIndexOutOfBoundsException.&lt;/em&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;&lt;span&gt;Class hierarchy&lt;/span&gt;&lt;/p&gt;



&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fl5vxqshxungks2ur6pgu.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fl5vxqshxungks2ur6pgu.png" alt="java" width="771" height="441"&gt;&lt;/a&gt;&lt;/p&gt;



&lt;p&gt;&lt;strong&gt;Q32: Can we write a try block without a catch block? &lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;&lt;span&gt;A32: Yes, we can write but then we need to add finally instead. We can have try block alone.&lt;/span&gt;&lt;/p&gt;


&lt;p&gt;&lt;strong&gt;Q33: When finally block will not get executed?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;&lt;span&gt;A33:  Whenever the program exits it can happen either when System.exit() is called or when JVM crashes or any other fatal error.&lt;/span&gt;&lt;/p&gt;


&lt;p&gt;&lt;strong&gt;Q34: When we put a throw statement in Finally block, what will happen?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;&lt;span&gt;A34: As we know that finally blocks execute every time. The throw statement inside finally will take precedence over try and catch block throw statement.&lt;/span&gt;&lt;/p&gt;


&lt;p&gt;&lt;strong&gt;Q35: Throw vs Throws?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;&lt;span&gt;A35: Thow - We can use throw keyword followed by Exception class. This will ask the program to explicitly induce that exception.&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;&lt;span&gt;Throws - We can add throws keyword in the method signature followed by Exception class, it will tell the compiler that the given method might throw that particular exception mentioned.&lt;/span&gt;&lt;/p&gt;


&lt;p&gt;&lt;strong&gt;Q36: How to make custom checked / unchecked exception? &lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;&lt;span&gt;A36: If you want to make a custom unchecked exception class then extend RuntimeException and for creating a custom checked exception class, extend Exception class.&lt;/span&gt;&lt;/p&gt;


&lt;p&gt;&lt;strong&gt;Q37: Try with Resources&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;&lt;span&gt;A 37: Try with Resources automatically closes the resource used within the try catch block. This can be done with Java 7 and above versions.&lt;/span&gt;&lt;/p&gt;

&lt;pre&gt;try (FileReader fr = new FileReader("file.txt")) {

} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}&lt;/pre&gt;
&lt;p&gt;&lt;span&gt;It replaces the below code&lt;/span&gt;&lt;/p&gt;
&lt;pre&gt;FileReader fr = null;      
try {
   File file = new File("file.txt");
   fr = new FileReader(file);
} catch (IOException e) {
   e.printStackTrace();
} finally {
   try {
      fr.close();
   } catch (IOException ex) {
      ex.printStackTrace();
   }
}&lt;/pre&gt;


&lt;p&gt;&lt;strong&gt;Q38: Exception Handling with Method Overriding in Java&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;&lt;span&gt;A38: We would discuss 2 cases&lt;/span&gt;&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;If the parent method does not declare an exception - &lt;/strong&gt;&lt;span&gt;The child overridden method cannot declare the checked exception but it can declare an unchecked exception.&lt;/span&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;If the parent method declares an exception - &lt;/strong&gt;&lt;span&gt;The child overridden method can declare the same, subclass exception, or no exception but cannot declare an exception that has more precedence than the parent class method.&lt;/span&gt;
&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;span&gt;Case 1&lt;/span&gt;&lt;/p&gt;
&lt;pre&gt;import java.io.IOException;

class Parent {
    void method() {

    }
}

class Child extends Parent {
    &lt;a class="mentioned-user" href="https://dev.to/override"&gt;@override&lt;/a&gt;
    void method() {

    }
}

class Child1 extends Parent {
/*
    &lt;a class="mentioned-user" href="https://dev.to/override"&gt;@override&lt;/a&gt;
    void method() throws IOException {
        // 'method()' in 'Child1' clashes with 'method()' in 'Parent'; overridden method does not throw 'java.io.IOException'
    }
*/
}

class Child2 extends Parent {
    &lt;a class="mentioned-user" href="https://dev.to/override"&gt;@override&lt;/a&gt;
    void method() throws ArithmeticException {
        // No error as this is an unchecked exception
    }
}&lt;/pre&gt;

&lt;p&gt;&lt;span&gt;Case 2&lt;/span&gt;&lt;/p&gt;
&lt;pre&gt;import java.io.FileNotFoundException;
import java.io.IOException;

class Parent {
    void method() throws IOException {

    }
}

class Child extends Parent {
    &lt;a class="mentioned-user" href="https://dev.to/override"&gt;@override&lt;/a&gt;
    void method() {

    }
}

class Child1 extends Parent {
    &lt;a class="mentioned-user" href="https://dev.to/override"&gt;@override&lt;/a&gt;
    void method() throws FileNotFoundException {
    }
}

class Child2 extends Parent {
    &lt;a class="mentioned-user" href="https://dev.to/override"&gt;@override&lt;/a&gt;
    void method() throws IOException {
    }
}

class Child3 extends Parent {
/*
    &lt;a class="mentioned-user" href="https://dev.to/override"&gt;@override&lt;/a&gt;
    void method() throws Exception {
        // error as Exception is superclass to IOException
    }
*/
}&lt;/pre&gt;




&lt;p&gt;&lt;strong&gt;#HappyLearning&lt;/strong&gt;&lt;/p&gt;

</description>
    </item>
    <item>
      <title>Code 101: Tower of Hanoi</title>
      <dc:creator>Garvit Khamesra</dc:creator>
      <pubDate>Wed, 27 Aug 2025 13:36:47 +0000</pubDate>
      <link>https://dev.to/garvit_khamesra/code-101-tower-of-hanoi-1l38</link>
      <guid>https://dev.to/garvit_khamesra/code-101-tower-of-hanoi-1l38</guid>
      <description>&lt;h1&gt;&lt;span&gt;Question:&lt;/span&gt;&lt;/h1&gt;
&lt;p&gt;&lt;strong&gt;Towers of Hanoi&lt;/strong&gt;&lt;span&gt;: In the classic problem of the Towers of Hanoi, you have 3 towers and N disks of different sizes which can slide onto any tower. The puzzle starts with disks sorted in ascending order of size from top to bottom (i.e., each disk sits on top of an even larger one).&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;&lt;span&gt;You have the following constraints:&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;&lt;span&gt;(1) Only one disk can be moved at a time.&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;&lt;span&gt;(2) A disk is slid off the top of one tower onto another tower.&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;&lt;span&gt;(3) A disk cannot be placed on top of a smaller disk. Write a program to move the disks from the first tower to the&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;&lt;span&gt;last using Stacks.&lt;/span&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Example 1:&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;Input: 2&lt;br&gt;
Output: Disk 1 moved from A to B&lt;br&gt;
Disk 2 moved from A to C&lt;br&gt;
Disk 1 moved from B to C&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;Example 2:&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;Input: 3&lt;br&gt;
Output: Disk 1 moved from A to C&lt;br&gt;
Disk 2 moved from A to B&lt;br&gt;
Disk 1 moved from C to B&lt;br&gt;
Disk 3 moved from A to C&lt;br&gt;
Disk 1 moved from B to A&lt;br&gt;
Disk 2 moved from B to C&lt;br&gt;
Disk 1 moved from A to C&lt;/pre&gt;

&lt;h1&gt;&lt;span&gt;Solution:&lt;/span&gt;&lt;/h1&gt;
&lt;p&gt;&lt;span&gt;By this time we have done several questions on recursion and I believe we can see the similar pattern. Now talking about the problem statement. I feel the best way to solve this question is to first understand how the rings will move and I believe we can understand it better on pen and paper then on code.&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;&lt;span&gt;First try it yourself and if it does not help, take a look at this &lt;/span&gt;&lt;a href="http://towersofhanoi.info/Animate.aspx" rel="noopener noreferrer"&gt;animation&lt;/a&gt;&lt;span&gt; which helped me to understand the problem better.&lt;/span&gt;&lt;/p&gt;

&lt;p&gt;&lt;span&gt;Now coming to solution, As we are considering this as a recursion problem we go back to our approach for recursion.&lt;/span&gt;&lt;/p&gt;

&lt;p&gt;&lt;span&gt;Base Case (when to stop)&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;&lt;span&gt;As we know that when all the disks are moved from source to destination. We are arrived at a solution, also whenever we are left with the last ring we will move it from source to destination. &lt;/span&gt;&lt;/p&gt;
&lt;pre&gt;if (n == 1) &lt;br&gt;
move disk from source to destination&lt;br&gt;
return;&lt;/pre&gt;

&lt;p&gt;&lt;span&gt;Recursive Call (call ourselves)&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;&lt;span&gt;As by question we can only move 1 ring at a time and we have 3 pegs so we will use them to interchangeably. &lt;/span&gt;&lt;/p&gt;
&lt;pre&gt;recursion(n - 1, from, to, inter)&lt;br&gt;
&amp;amp;&lt;br&gt;
recursion(n - 1, inter, from, to)&lt;/pre&gt;

&lt;p&gt;&lt;span&gt;Work needed to move toward Base Case or Solution&lt;/span&gt;&lt;/p&gt;
&lt;pre&gt;public static void towerOfHanoi(int n, char origin, char buffer, char destination) {&lt;br&gt;
    if (n == 1) {&lt;br&gt;
        System.out.println("Move disc 1 from "+origin+" to "+ destination);&lt;br&gt;
        return;&lt;br&gt;
    }
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;towerOfHanoi(n - 1, origin, destination, buffer);
System.out.println("Move disc " + n + " from " + origin + " to " + destination);
towerOfHanoi(n - 1, buffer, origin, destination);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;}&lt;/p&gt;&lt;/pre&gt;

&lt;p&gt;&lt;span&gt;Hope you have a better understanding now, continue with the code101 series, and you'll gain a better understanding.&lt;/span&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;#HappyCoding&lt;/strong&gt;&lt;/p&gt;


</description>
      <category>programming</category>
      <category>competativeprogramming</category>
      <category>coding</category>
      <category>java</category>
    </item>
    <item>
      <title>Code 101: K-th Symbol in Grammar</title>
      <dc:creator>Garvit Khamesra</dc:creator>
      <pubDate>Wed, 27 Aug 2025 13:29:40 +0000</pubDate>
      <link>https://dev.to/garvit_khamesra/code-101-k-th-symbol-in-grammar-5d35</link>
      <guid>https://dev.to/garvit_khamesra/code-101-k-th-symbol-in-grammar-5d35</guid>
      <description>&lt;h1&gt;&lt;span&gt;Question&lt;/span&gt;&lt;/h1&gt;

&lt;p&gt;&lt;span&gt;We build a table of &lt;/span&gt;&lt;span&gt;n&lt;/span&gt;&lt;span&gt; rows (&lt;/span&gt;&lt;strong&gt;1-indexed&lt;/strong&gt;&lt;span&gt;). We start by writing &lt;/span&gt;&lt;span&gt;0&lt;/span&gt;&lt;span&gt; in the &lt;/span&gt;&lt;span&gt;1st &lt;/span&gt;&lt;span&gt;row. Now in every subsequent row, we look at the previous row and replace each occurrence of &lt;/span&gt;&lt;span&gt;0&lt;/span&gt;&lt;span&gt; with &lt;/span&gt;&lt;span&gt;01&lt;/span&gt;&lt;span&gt;, and each occurrence of&lt;/span&gt;&lt;span&gt; 1&lt;/span&gt;&lt;span&gt; with &lt;/span&gt;&lt;span&gt;10&lt;/span&gt;&lt;span&gt;.&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;&lt;span&gt;For example, for&lt;/span&gt;&lt;span&gt; n = 3&lt;/span&gt;&lt;span&gt;, the &lt;/span&gt;&lt;span&gt;1st &lt;/span&gt;&lt;span&gt;row is &lt;/span&gt;&lt;span&gt;0&lt;/span&gt;&lt;span&gt;, the &lt;/span&gt;&lt;span&gt;2nd &lt;/span&gt;&lt;span&gt;row is&lt;/span&gt;&lt;span&gt; 01&lt;/span&gt;&lt;span&gt;, and the&lt;/span&gt;&lt;span&gt; 3rd &lt;/span&gt;&lt;span&gt;row is &lt;/span&gt;&lt;span&gt;0110&lt;/span&gt;&lt;span&gt;.&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;&lt;span&gt;Given two integer &lt;/span&gt;&lt;span&gt;n&lt;/span&gt;&lt;span&gt; and &lt;/span&gt;&lt;span&gt;k&lt;/span&gt;&lt;span&gt;, return the (&lt;/span&gt;&lt;strong&gt;1-indexed&lt;/strong&gt;&lt;span&gt;) symbol in the&lt;/span&gt;&lt;span&gt; nth&lt;/span&gt;&lt;span&gt; row of a table of &lt;/span&gt;&lt;span&gt;n &lt;/span&gt;&lt;span&gt;rows.&lt;/span&gt;&lt;/p&gt;
&lt;p&gt; &lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Example 1:&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;Input: n = 1, k = 1 Output: 0 Explanation: row 1: 0 &lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;Example 2:&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;Input: n = 2, k = 1 Output: 0 Explanation: row 1: 0 row 2: 01 &lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;Example 3:&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;Input: n = 2, k = 2 Output: 1 Explanation: row 1: 0 row 2: 01 &lt;/pre&gt;
&lt;p&gt; &lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Constraints:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;span&gt;1 &amp;lt;= n &amp;lt;= 30&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;&lt;span&gt;1 &amp;lt;= k &amp;lt;= 2n - 1&lt;/span&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;You can find the question &lt;a href="https://leetcode.com/problems/k-th-symbol-in-grammar/" rel="noopener noreferrer"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;h1&gt;&lt;strong&gt;Solution:&lt;/strong&gt;&lt;/h1&gt;
&lt;p&gt;&lt;span&gt;By reading the question we can deduce that there is some kind of structure we need to create based on the question's requirement. Few things to note here:&lt;/span&gt;&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;span&gt;To create the structure we need to rely on previous output. So can we use recursion?&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;&lt;span&gt;The structure is a tree.&lt;/span&gt;&lt;/li&gt;
&lt;/ol&gt;


&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F4wqs2o8nr8pfotbil9lz.jpeg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F4wqs2o8nr8pfotbil9lz.jpeg" alt="Easy Understanding" width="800" height="463"&gt;&lt;/a&gt;&lt;/p&gt;


&lt;p&gt;&lt;span&gt;After creating the structure mentioned we can deduce few more things.&lt;/span&gt;&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;span&gt;The size of each row is double the size of previous row.&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;&lt;span&gt;If we break down the row we can see that the previous row and the first half of the row is exactly same.&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;&lt;span&gt;The second half of the row is the complement of the previous row&lt;/span&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;span&gt;Now we will try to think of a solution keeping all these things in mind. We have previously worked on recursion solutions and we generally break it down to 3 steps.&lt;/span&gt;&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;span&gt;Base Case (when to stop)&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;&lt;span&gt;Work needed to move toward Base Case or Solution&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;&lt;span&gt;Recursive Call (call ourselves)&lt;/span&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;span&gt;Let's start with base case, We know that at n = 1 we have zero, lets consider column as k. So at n == 1 and k == 1 we have 0. This becomes our base case.&lt;/span&gt;&lt;/p&gt;

&lt;pre&gt;if (n == 1 &amp;amp;&amp;amp; k == 1) return 0; &lt;/pre&gt;

&lt;p&gt;&lt;span&gt;We will skip second part and move to the 3rd step the recursion calls.&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;&lt;span&gt;Based on observations we know that the solution depends on the previous output and the complement of previous output.&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;&lt;span&gt;so can we write 2 recursive calls?&lt;/span&gt;&lt;/p&gt;

&lt;pre&gt;recursion( n-1, k ) -&amp;gt; when k is less the middle element
// and for the second call we need the complement of the values i.e. when the k is greator then the middle // element
recursion( n-1, k - mid) -&amp;gt; when k is less the middle element&lt;/pre&gt;

&lt;p&gt;&lt;span&gt;Now coming to the second part. Actually while thinking of the 3rd step we kind off got the second part. I'll explain in the code below.&lt;/span&gt;&lt;/p&gt;

&lt;pre&gt;public static int kthGrammar(int n, int k) {
    if(n==1 &amp;amp;&amp;amp; k==1) {
        return 0;
    }

    int mid = ((int) pow(2, n - 1)) / 2;

    if(k &amp;lt;= mid) {
        return kthGrammar(n-1, k);
    } else {
        return ( kthGrammar(n-1,k-mid)) ^ 1;
    }
}&lt;/pre&gt;

&lt;p&gt;&lt;span&gt;See the code does not have anything else then what we discussed, we found mid, we called the recursion calls based on the conditions we knew.&lt;/span&gt;&lt;/p&gt;

&lt;p&gt;&lt;span&gt;Hope you have a better understanding now, continue with the code101 series, and you'll gain a better understanding.&lt;/span&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;#HappyCoding&lt;/strong&gt;&lt;/p&gt;

</description>
      <category>programming</category>
      <category>java</category>
      <category>coding</category>
      <category>competativeprogramming</category>
    </item>
    <item>
      <title>Code 101: Number of Islands</title>
      <dc:creator>Garvit Khamesra</dc:creator>
      <pubDate>Wed, 27 Aug 2025 13:24:35 +0000</pubDate>
      <link>https://dev.to/garvit_khamesra/code-101-number-of-islands-5ebm</link>
      <guid>https://dev.to/garvit_khamesra/code-101-number-of-islands-5ebm</guid>
      <description>&lt;p&gt;&lt;strong&gt;Question:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;&lt;span&gt;Given an &lt;/span&gt;&lt;span&gt;m x n&lt;/span&gt;&lt;span&gt; 2D binary grid which represents a map of &lt;/span&gt;&lt;span&gt;'1'&lt;/span&gt;&lt;span&gt;s (land) and &lt;/span&gt;&lt;span&gt;'0'&lt;/span&gt;&lt;span&gt;s (water), return &lt;/span&gt;&lt;em&gt;the number of islands&lt;/em&gt;&lt;span&gt;.&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;&lt;span&gt;An &lt;/span&gt;&lt;strong&gt;island&lt;/strong&gt;&lt;span&gt; is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are surrounded by water.&lt;/span&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Example 1:&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;Input: grid = [
  ["1","1","1","1","0"],
  ["1","1","0","1","0"],
  ["1","1","0","0","0"],
  ["0","0","0","0","0"]
]
Output: 1&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;Example 2:&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;Input: grid = [
  ["1","1","0","0","0"],
  ["1","1","0","0","0"],
  ["0","0","1","0","0"],
  ["0","0","0","1","1"]
]
Output: 3&lt;/pre&gt;
&lt;p&gt;&lt;span&gt; &lt;/span&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Constraints:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;span&gt;m == grid.length&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;&lt;span&gt;n == grid[i].length&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;&lt;span&gt;1 &amp;lt;= m, n &amp;lt;= 300&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;
&lt;span&gt;grid[i][j]&lt;/span&gt;&lt;span&gt; is &lt;/span&gt;&lt;span&gt;'0'&lt;/span&gt;&lt;span&gt; or &lt;/span&gt;&lt;span&gt;'1'&lt;/span&gt;&lt;span&gt;.&lt;/span&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;You can find the question &lt;a href="https://leetcode.com/problems/number-of-islands/" rel="noopener noreferrer"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Solution:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;&lt;span&gt;We have given an 2d array, and asked to find number of islands.&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;&lt;span&gt;What all things can we deduce from the question&lt;/span&gt;&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;span&gt;To count the island we need to check where the land end.&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;&lt;span&gt;All the grid boundaries are considered water.&lt;/span&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;span&gt;With this information can we say that we need to traverse the whole array to check where the land is and where the water is?&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;&lt;span&gt;Also, can we say that whenever we see 1 can we consider it as an Island? &lt;/span&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Note: &lt;/strong&gt;&lt;span&gt;This assumption will count all the '1' as islands.&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;&lt;span&gt;Will break the answer into smaller parts.&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;&lt;span&gt;Based on the understanding till now. &lt;/span&gt;&lt;/p&gt;

&lt;pre&gt;public int numIslands(char[][] grid) {
        if (grid == null || grid.length == 0) return 0;
        int noOfIslands = 0;
        for (int i = 0; i &amp;lt; grid.length; i++) {
            for (int j = 0; j &amp;lt; grid[0].length; j++) {
                if (grid[i][j] == '1') {
                    noOfIslands++;
                }
            }
        }
        return noOfIslands;
}&lt;/pre&gt;

&lt;p&gt;&lt;span&gt;With this, we have reached half of the solution but we know that we are counting all the 1 as islands and that is wrong.&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;&lt;span&gt;So let's say we are standing on a square in a grid and we count that as an island and now wherever you see land attached to the 1 you are standing, consider it as water.&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;&lt;span&gt;Will doing this solve your duplicate counting problem? Because anyway we are iterating the whole grid, so every time while iterating through the grid we encounter a 1, count it as an island, and mark all the connected land as the water we are good.&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;&lt;span&gt;Also, we don't want to do anything when we see water.&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;&lt;span&gt;Now to code our understanding.&lt;/span&gt;&lt;/p&gt;

&lt;pre&gt;public int numIslands(char[][] grid) {
        if (grid == null || grid.length == 0) return 0;
        int noOfIslands = 0;
        for (int i = 0; i &amp;lt; grid.length; i++) {
            for (int j = 0; j &amp;lt; grid[0].length; j++) {
                if (grid[i][j] == '1') {
                    noOfIslands++;
                    flippingTheContIslands(grid, i, j);
                }
            }
        }
        return noOfIslands;
}
    
public void flippingTheContIslands(char[][] grid, int i, int j) {
        if (i &amp;lt; 0 || i &amp;gt;= grid.length || j &amp;lt; 0 || j &amp;gt;= grid[0].length || grid[i][j] == '0' ) {
            return;
        }
        grid[i][j] = '0';
        flippingTheContIslands(grid, i+1, j);
        flippingTheContIslands(grid, i, j+1);
        flippingTheContIslands(grid, i-1, j);
        flippingTheContIslands(grid, i, j-1);
}
&lt;/pre&gt;

&lt;p&gt;&lt;span&gt;Hope you understood the solution.&lt;/span&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;#HappyCoding&lt;/strong&gt;&lt;/p&gt;

</description>
      <category>programming</category>
      <category>competativeprogramming</category>
      <category>java</category>
      <category>coding</category>
    </item>
    <item>
      <title>Code 101: Swap Nodes in Pairs</title>
      <dc:creator>Garvit Khamesra</dc:creator>
      <pubDate>Wed, 27 Aug 2025 13:01:44 +0000</pubDate>
      <link>https://dev.to/garvit_khamesra/code-101-swap-nodes-in-pairs-4jjh</link>
      <guid>https://dev.to/garvit_khamesra/code-101-swap-nodes-in-pairs-4jjh</guid>
      <description>&lt;p&gt;&lt;strong&gt;Question:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;&lt;span&gt;Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.)&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;&lt;span&gt; &lt;/span&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Example 1:&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;Input: head = [1,2,3,4] &lt;/pre&gt;

&lt;pre&gt;Output: [2,1,4,3] &lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;Example 2:&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;Input: head = [] Output: [] &lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;Example 3:&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;Input: head = [1] Output: [1] &lt;/pre&gt;
&lt;p&gt;&lt;span&gt; &lt;/span&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Constraints:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;span&gt;The number of nodes in the list is in the range [0, 100].&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;&lt;span&gt;0 &amp;lt;= Node.val &amp;lt;= 100&lt;/span&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;You can find the question &lt;a href="https://leetcode.com/explore/learn/card/recursion-i/250/principle-of-recursion/1681/" rel="noopener noreferrer"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Solution:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;&lt;span&gt;This question can be solved with both iterative and recursive approaches, But As I'm covering recursion so will start with the recursive approach and then will explain the iterative approach.&lt;/span&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Recursive approach&lt;/strong&gt;&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;span&gt;The Base Condition&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;&lt;span&gt;What to do, to get a solution?&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;&lt;span&gt;Recursive call&lt;/span&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;&lt;span&gt;I broke down the solution in these steps.&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;&lt;span&gt;Now the 1&lt;/span&gt;&lt;sup&gt;st&lt;/sup&gt;&lt;span&gt; step is pretty straightforward. As we know, to swap 2 nodes we need 2 nodes, so let's say we have 2 null checks for that. And for step 3, Can we consider moving to the next node by skipping 1 node? So that we cover every node.&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;&lt;span&gt;Now coming to 2&lt;/span&gt;&lt;sup&gt;nd&lt;/sup&gt;&lt;span&gt; point.&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;&lt;span&gt;We know that to swap we need to have 2 nodes, and for swapping we make changes to the next pointer in the list.&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;&lt;span&gt;Because we are trying to solve it through recursion, for me the problem is to visualize the solution, so I have tried to show using some diagrams.&lt;/span&gt;&lt;/p&gt;

&lt;p&gt;&lt;span&gt;Let's take an example of list&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;&lt;span&gt;1-&amp;gt; 2 -&amp;gt; 3-&amp;gt; 4&lt;/span&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fl7ig2m0rpsd1tx22x615.jpeg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fl7ig2m0rpsd1tx22x615.jpeg" alt="Recursive Approach" width="800" height="516"&gt;&lt;/a&gt;&lt;/p&gt;


&lt;p&gt;&lt;span&gt;Now with this example, you should a rough idea of the algorithm. We will use the same logic to code.&lt;/span&gt;&lt;/p&gt;
&lt;pre&gt;    public ListNode swapPairs(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode next = head.next;
        head.next = swapPairs(next.next);
        next.next = head;
        return next;
    }&lt;/pre&gt;


&lt;p&gt;&lt;strong&gt;Iterative Approach&lt;/strong&gt;&lt;/p&gt;


&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F3f8le3sep1259etjsyrx.jpeg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F3f8le3sep1259etjsyrx.jpeg" alt="Iterative approach" width="800" height="290"&gt;&lt;/a&gt;&lt;/p&gt;


&lt;p&gt;&lt;span&gt;So if you view the above image it follows a similar approach just we need an additional node.&lt;/span&gt;&lt;/p&gt;

&lt;pre&gt;public ListNode swapPairs(ListNode head) {
    ListNode dummy = new ListNode(0);
    dummy.next = head;
    ListNode current = dummy;
    while (current.next != null &amp;amp;&amp;amp; current.next.next != null) {
        ListNode first = current.next;
        ListNode second = current.next.next;
        first.next = second.next;
        current.next = second;
        current.next.next = first;
        current = current.next.next;
    }
    return dummy.next;
}&lt;/pre&gt;


&lt;p&gt;&lt;strong&gt;#HappyCoding&lt;/strong&gt;&lt;/p&gt;

</description>
    </item>
    <item>
      <title>Code 101: Rat in a Maze</title>
      <dc:creator>Garvit Khamesra</dc:creator>
      <pubDate>Wed, 27 Aug 2025 03:26:25 +0000</pubDate>
      <link>https://dev.to/garvit_khamesra/code-101-rat-in-a-maze-9j</link>
      <guid>https://dev.to/garvit_khamesra/code-101-rat-in-a-maze-9j</guid>
      <description>&lt;p&gt;&lt;strong&gt;Question:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;span&gt;Consider a rat placed at (0, 0) in a square matrix of order N * N. It has to reach the destination at (N – 1, N – 1). Find all possible paths that the rat can take to reach from source to destination. The directions in which the rat can move are ‘U'(up), ‘D'(down), ‘L’ (left), ‘R’ (right). Value 0 at a cell in the matrix represents that it is blocked and the rat cannot move to it while value 1 at a cell in the matrix represents that rat can travel through it.&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;&lt;span&gt;Note: In a path, no cell can be visited more than one time.&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;&lt;span&gt;Print the answer in lexicographical(sorted) order&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Examples:&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;Example 1:
Input:
N = 4
m[][] = `{{1, 0, 0, 0},
        {1, 1, 0, 1}, 
        {1, 1, 0, 0},
        {0, 1, 1, 1}}`

Output: DDRDRR DRDDRR
Explanation:
The rat can reach the destination at (3, 3) from (0, 0) by two paths - DRDDRR and DDRDRR, when printed in sorted order we get DDRDRR DRDDRR.
&lt;/pre&gt;

&lt;pre&gt;Example 2:
Input: N = 2
       m[][] = `{{1, 0},
                {1, 0}}`

Output:
 No path exists and the destination cell is blocked.&lt;/pre&gt;


&lt;p&gt;&lt;strong&gt;Solution:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;&lt;span&gt;After reading the question, the solution approach is straightforward:&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;&lt;span&gt;We need to find a path in the maze so that the rat reaches the exit, to do that we just need to start from the initial point and see if we can move to the next block in any of the 4 directions. &lt;/span&gt;&lt;/p&gt;
&lt;p&gt;&lt;span&gt;Now comes the tricky part how we can code this solution:&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;&lt;span&gt;By looking at the pattern of our solution we can say this will be a backtracking problem, and also we can see that we can use recursion for our solution.&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;&lt;span&gt;My idea is to break down the code into smaller pieces so that we don't get confused. That's how I like to approach it.&lt;/span&gt;&lt;/p&gt;

&lt;p&gt;&lt;span&gt;So I'll start by writing wrappers and the main method, basically all the pre-requisite.&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;&lt;span&gt;1 more point, we need to find all the paths and also we should not end up visiting the nodes again and again. To handle these 2 conditions we will be using visited nodes array.&lt;/span&gt;&lt;/p&gt;

&lt;pre&gt;package medium.recursion.backtracking;
import java.util.ArrayList;
public class RatInAMaze {
    // Main method to test our code.
    public static void main(String[] args) {
        int n = 4;
        int[][] a = `{{1,0,0,0},{1,1,0,1},{1,1,0,0},{0,1,1,1}}`;
        ArrayList&amp;lt; String &amp;gt; res = findPath(a, n);
        if (res.size() &amp;gt; 0) {
            for (int i = 0; i &amp;lt; res.size(); i++)
                System.out.print(res.get(i) + " ");
            System.out.println();
        } else {
            System.out.println(-1);
        }
    }
    // Based on our solution we have added a new array to maintain visited nodes
    private static ArrayList findPath(int[][] arr, int n) {
        int visited[][] = new int[n][n];
        for (int i = 0; i &amp;lt; n; i++) {
            for (int j = 0; j &amp;lt; n; j++) {
                visited[i][j] = 0;
            }
        }
        ArrayList &amp;lt; String &amp;gt; ans = new ArrayList &amp;lt; &amp;gt; ();
        if (arr[0][0] == 1) {
            findPathHelper(arr, n, 0, 0, ans, "", visited);
        }
        return ans;
    }
}&lt;/pre&gt;

&lt;p&gt;&lt;span&gt;Now we are ready with the test code and the method for our solution. We have defined our helper method as:&lt;/span&gt;&lt;/p&gt;
&lt;blockquote&gt;&lt;span&gt; findPathHelper(int[][] arr, int n, int i, int j, ArrayList&amp;lt;String&amp;gt; allDiffPaths, String path, int[][] visited)&lt;/span&gt;&lt;/blockquote&gt;
&lt;p&gt;&lt;span&gt;We are starting from 0,0 and we will be maintaining the current path and all the paths which leads to the solution.&lt;/span&gt;&lt;/p&gt;

&lt;p&gt;&lt;span&gt;﻿If you haven't gone through &lt;/span&gt;&lt;a href="https://thetechnote.web.app/article/Code-101-Sort-an-Array-using-Recursion/X3QplctWbcTlneYRk2Da" rel="noopener noreferrer"&gt;&lt;strong&gt;Code 101: Sort an Array using Recursion&lt;/strong&gt;&lt;/a&gt;,&lt;span&gt; please have a look at the &lt;/span&gt;&lt;strong&gt;Recursive Algorithm &lt;/strong&gt;&lt;span&gt;explained here.&lt;/span&gt;&lt;/p&gt;

&lt;p&gt;&lt;span&gt;Now as we know we can solve this with recursion, we will try to think of a base condition.&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;&lt;span&gt;Base Condition:&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;&lt;span&gt;We know that once the rat reaches the end of the maze it's a success and we add it to our solution.&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;&lt;span&gt;Now skipping the second point &lt;/span&gt;&lt;strong&gt;Work needed to move toward Base Case or Solution &lt;/strong&gt;&lt;span&gt;and moving towards 3rd point the &lt;/span&gt;&lt;strong&gt;Recursive Call (call ourselves)&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;&lt;span&gt;As we know the rat can move in 4 directions, so the recursive call corresponding will be&lt;/span&gt;&lt;/p&gt;

&lt;pre&gt;  findPathHelper(arr, n, i+1, j, ans, path + "D", visited);
  findPathHelper(arr, n, i-1, j, ans, path + "U", visited);
  findPathHelper(arr, n, i, j+1, ans, path + "R", visited);
  findPathHelper(arr, n, i, j-1, ans, path + "L", visited);
// Each call is based on each direction and that will be added in path.&lt;/pre&gt;

&lt;p&gt;&lt;span&gt;Now coming to 2nd point &lt;/span&gt;&lt;strong&gt;Work needed to move toward Base Case or Solution.&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;&lt;span&gt;We know that the calls we specified above will be called and the solution will arrive, but there are a few constraints we need to put.&lt;/span&gt;&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;span&gt;the indices should not be out of bounds&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;&lt;span&gt;do not visit already visited node&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;&lt;span&gt;skip the node if it have 0&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;&lt;span&gt;mark the node visited once the rat is at that node&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;&lt;span&gt;once you have a path make the visited node as 0 so for the next path you will have the node as not visited&lt;/span&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;&lt;span&gt;We will write our helper function now:&lt;/span&gt;&lt;/p&gt;

&lt;pre&gt;private static void findPathHelper(int[][] arr, int n, int i, int j, ArrayList ans, String path, int[][] visited) {
        if (i == n-1 &amp;amp;&amp;amp; j == n-1) {
            ans.add(path);
            return;
        }

        if (visited[i][j] == 1 || arr[i][j] != 1) {
            return;
        }

        visited[i][j] = 1;

        if (i &amp;gt;= 0 &amp;amp;&amp;amp; i + 1 &amp;lt; n &amp;amp;&amp;amp; arr[i+1][j] == 1 &amp;amp;&amp;amp; visited[i+1][j] != 1) {
            findPathHelper(arr, n, i+1, j, ans, path + "D", visited);
        }

        if (i - 1 &amp;gt;= 0 &amp;amp;&amp;amp; i &amp;lt; n &amp;amp;&amp;amp; arr[i-1][j] == 1 &amp;amp;&amp;amp; visited[i-1][j] != 1) {
            findPathHelper(arr, n, i-1, j, ans, path + "U", visited);
        }

        if (j &amp;gt;= 0 &amp;amp;&amp;amp; j+1 &amp;lt; n &amp;amp;&amp;amp; arr[i][j+1] == 1 &amp;amp;&amp;amp; visited[i][j+1] != 1) {
            findPathHelper(arr, n, i, j+1, ans, path + "R", visited);
        }

        if (j-1 &amp;gt;= 0 &amp;amp;&amp;amp; j &amp;lt; n &amp;amp;&amp;amp; arr[i][j-1] == 1 &amp;amp;&amp;amp; visited[i][j-1] != 1) {
            findPathHelper(arr, n, i, j-1, ans, path + "L", visited);
        }

        visited[i][j] = 0;
    }
}&lt;/pre&gt;

&lt;p&gt;&lt;span&gt;This will take care of all the scenarios discussed and now consolidate everything into 1 place.&lt;/span&gt;&lt;/p&gt;

&lt;pre&gt;package medium.recursion.backtracking;

import java.util.ArrayList;

public class RatInAMaze {

    public static void main(String[] args) {
        int n = 4;
        int[][] a = `{{1,0,0,0},{1,1,0,1},{1,1,0,0},{0,1,1,1}}`;

        ArrayList&amp;lt; String &amp;gt; res = findPath(a, n);
        if (res.size() &amp;gt; 0) {
            for (int i = 0; i &amp;lt; res.size(); i++)
                System.out.print(res.get(i) + " ");
            System.out.println();
        } else {
            System.out.println(-1);
        }
    }

    private static ArrayList findPath(int[][] arr, int n) {
        int visited[][] = new int[n][n];
        for (int i = 0; i &amp;lt; n; i++) {
            for (int j = 0; j &amp;lt; n; j++) {
                visited[i][j] = 0;
            }
        }
        ArrayList &amp;lt; String &amp;gt; ans = new ArrayList &amp;lt; &amp;gt; ();

        if (arr[0][0] == 1) {
            findPathHelper(arr, n, 0, 0, ans, "", visited);
        }
        return ans;
    }

    private static void findPathHelper(int[][] arr, int n, int i, int j, ArrayList ans, String path, int[][] visited) {
        if (i == n-1 &amp;amp;&amp;amp; j == n-1) {
            ans.add(path);
            return;
        }

        if (visited[i][j] == 1 || arr[i][j] != 1) {
            return;
        }

        visited[i][j] = 1;

        if (i &amp;gt;= 0 &amp;amp;&amp;amp; i + 1 &amp;lt; n &amp;amp;&amp;amp; arr[i+1][j] == 1 &amp;amp;&amp;amp; visited[i+1][j] != 1) {
            findPathHelper(arr, n, i+1, j, ans, path + "D", visited);
        }

        if (i - 1 &amp;gt;= 0 &amp;amp;&amp;amp; i &amp;lt; n &amp;amp;&amp;amp; arr[i-1][j] == 1 &amp;amp;&amp;amp; visited[i-1][j] != 1) {
            findPathHelper(arr, n, i-1, j, ans, path + "U", visited);
        }

        if (j &amp;gt;= 0 &amp;amp;&amp;amp; j+1 &amp;lt; n &amp;amp;&amp;amp; arr[i][j+1] == 1 &amp;amp;&amp;amp; visited[i][j+1] != 1) {
            findPathHelper(arr, n, i, j+1, ans, path + "R", visited);
        }

        if (j-1 &amp;gt;= 0 &amp;amp;&amp;amp; j &amp;lt; n &amp;amp;&amp;amp; arr[i][j-1] == 1 &amp;amp;&amp;amp; visited[i][j-1] != 1) {
            findPathHelper(arr, n, i, j-1, ans, path + "L", visited);
        }

        visited[i][j] = 0;
    }
}&lt;/pre&gt;

&lt;p&gt;&lt;span&gt;Now that we have completed the code, I wanted to organize it better and removed pieces that we can remove.&lt;/span&gt;&lt;/p&gt;
&lt;pre&gt;private static void findPathHelper(int[][] arr, int n, int i, int j, ArrayList ans, String path) {
    if (i &amp;lt; 0 || j &amp;lt; 0 || i &amp;gt;= arr.length || j &amp;gt;= arr[0].length || arr[i][j] == 0 || arr[i][j] ==  -1) {
        return;
    }

    if (i == n-1 &amp;amp;&amp;amp; j == n-1) {
        ans.add(path);
        return;
    }

    arr[i][j] = -1;
    findPathHelper(arr, n, i+1, j, ans, path + "D");
    findPathHelper(arr, n, i-1, j, ans, path + "U");
    findPathHelper(arr, n, i, j+1, ans, path + "R");
    findPathHelper(arr, n, i, j-1, ans, path + "L");
    arr[i][j] = 1;
}
&lt;/pre&gt;

&lt;p&gt;&lt;strong&gt;#HappyCoding&lt;/strong&gt;&lt;/p&gt;

</description>
      <category>programming</category>
      <category>java</category>
      <category>competativeprogramming</category>
    </item>
    <item>
      <title>Code 101: Sort a Stack using Recursion</title>
      <dc:creator>Garvit Khamesra</dc:creator>
      <pubDate>Wed, 27 Aug 2025 03:12:35 +0000</pubDate>
      <link>https://dev.to/garvit_khamesra/code-101-sort-a-stack-using-recursion-157p</link>
      <guid>https://dev.to/garvit_khamesra/code-101-sort-a-stack-using-recursion-157p</guid>
      <description>&lt;p&gt;&lt;strong&gt;Question:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;&lt;span&gt;Given a stack, sort it using recursion. Use of any loop constructs like while, for..etc is not allowed.&lt;/span&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Solution:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;&lt;span&gt;This question follows the same algorithm as &lt;/span&gt;&lt;a href="https://thetechnote.web.app/article/code-101-sort-an-array-using-recursion/X3QplctWbcTlneYRk2Da" rel="noopener noreferrer"&gt;&lt;strong&gt;Sort an Array using recursion&lt;/strong&gt;&lt;/a&gt;&lt;span&gt;. So I would suggest you go through the post and try it once.&lt;/span&gt;&lt;/p&gt;

&lt;p&gt;&lt;span&gt;I have added the code and the call order because once go through it you'll see the code is similar.&lt;/span&gt;&lt;/p&gt;

&lt;pre&gt;package stack.queue;
import java.util.Stack;
public class SortStackWithRecursion {
    static Stack stack;
    public static void sort() {
        if (!stack.isEmpty()) {
            int temp = stack.pop();
            sort();
            insert(temp);
        }
    }
    private static void insert(int value) {
        if (stack.isEmpty() || stack.peek() &amp;lt; value) {
            stack.push(value);
        } else {
            int temp = stack.pop();
            insert(value);
            stack.push(temp);
        }
    }
    public static void main(String[] args) {
        stack = new Stack&amp;lt;&amp;gt;();
        stack.add(12112);
        stack.add(21);
        stack.add(300);
        stack.add(41);
        stack.add(52);
        for (int i : stack) {
            System.out.print(i + " ,");
        }
        System.out.println("\n&amp;gt;&amp;gt;&amp;gt;");
        sort();
        System.out.println("&amp;lt;&amp;lt;&amp;lt;");
        for (int i : stack) {
            System.out.print(i + " ,");
        }
    }
}&lt;/pre&gt;


&lt;pre&gt;Sort [12112, 21, 300, 41, 52] Stack Size: 5
Sort [12112, 21, 300, 41] Stack Size: 4
Sort [12112, 21, 300] Stack Size: 3
Sort [12112, 21] Stack Size: 2
Sort [12112] Stack Size: 1
Insert [] Stack Size: 0
Inserting Value: 12112
Insert [12112] Stack Size: 1
Insert [] Stack Size: 0
Inserting Value: 21
Inserting Value: 12112
Insert [21, 12112] Stack Size: 2
Insert [21] Stack Size: 1
Inserting Value: 300
Inserting Value: 12112
Insert [21, 300, 12112] Stack Size: 3
Insert [21, 300] Stack Size: 2
Insert [21] Stack Size: 1
Inserting Value: 41
Inserting Value: 300
Inserting Value: 12112
Insert [21, 41, 300, 12112] Stack Size: 4
Insert [21, 41, 300] Stack Size: 3
Insert [21, 41] Stack Size: 2
Inserting Value: 52
Inserting Value: 300
Inserting Value: 12112&lt;/pre&gt;

&lt;p&gt;&lt;strong&gt;#HappyCoding&lt;/strong&gt;&lt;/p&gt;

</description>
      <category>programming</category>
      <category>java</category>
      <category>competativeprogramming</category>
    </item>
    <item>
      <title>Code 101: Sort an Array using Recursion</title>
      <dc:creator>Garvit Khamesra</dc:creator>
      <pubDate>Wed, 27 Aug 2025 03:08:01 +0000</pubDate>
      <link>https://dev.to/garvit_khamesra/code-101-sort-an-array-using-recursion-3i79</link>
      <guid>https://dev.to/garvit_khamesra/code-101-sort-an-array-using-recursion-3i79</guid>
      <description>&lt;p&gt;&lt;strong&gt;Question:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;&lt;span&gt;Given an array of integers &lt;/span&gt;&lt;span&gt;nums&lt;/span&gt;&lt;span&gt;, sort the array in ascending order.&lt;/span&gt;&lt;/p&gt;
&lt;p&gt; &lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Example 1:&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;Input: nums = [5,2,3,1] Output: [1,2,3,5] &lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;Example 2:&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;Input: nums = [5,1,1,2,0,0] Output: [0,0,1,1,2,5] &lt;/pre&gt;
&lt;p&gt; &lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Constraints:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;span&gt;1 &amp;lt;= nums.length &amp;lt;= 5 * 104&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;&lt;span&gt;-5 * 104 &amp;lt;= nums[i] &amp;lt;= 5 * 104&lt;/span&gt;&lt;/li&gt;
&lt;/ul&gt;


&lt;p&gt;&lt;strong&gt;Solution:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;&lt;span&gt;Let's start with Recursion.&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;&lt;span&gt;I found this definition while starting with recursion and found it useful.&lt;/span&gt;&lt;/p&gt;

&lt;blockquote&gt;&lt;span&gt;Recursion is the process of defining a problem (or the solution to a problem) in terms of (a simpler version of) itself.&lt;/span&gt;&lt;/blockquote&gt;

&lt;p&gt;&lt;strong&gt;Recursive Algorithm&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;&lt;span&gt;All recursive algorithms must have the following:&lt;/span&gt;&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;span&gt;Base Case (when to stop)&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;&lt;span&gt;Work needed to move toward Base Case or Solution&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;&lt;span&gt;Recursive Call (call ourselves)&lt;/span&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;span&gt;Now coming back to the problem, we know that we need to breakdown our solution in above 3 points&lt;/span&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;span&gt;Think when do you tell an array to be sorted.&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;&lt;span&gt;if the size is zero? &lt;/span&gt;&lt;/li&gt;
&lt;li&gt;&lt;span&gt;if the size is 1?&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;&lt;span&gt;if the array is in ascending order :)?&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;&lt;span&gt;Now can we make a recursive call to attain 1.a?&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;&lt;span&gt;yes, if we make a recursive call by decreasing the size of the array&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;&lt;span&gt;Now we will try to code what we just thought.&lt;/span&gt;&lt;/li&gt;
&lt;/ol&gt;


&lt;pre&gt;public class SortArray {
    public static void sort(int[] arr, int n) {
        if (n == 0) return;
        sort(arr, n-1);
    }
    public static void main(String[] args) {
        int[] arr = new int[] {3, 4, 2, 6, 1, 1, 9, 1};
        for (int i : arr) {
            System.out.print(i + " ,");
        }
        System.out.println("\n&amp;gt;&amp;gt;&amp;gt;");
        sort(arr, arr.length - 1);
        System.out.println("&amp;lt;&amp;lt;&amp;lt;");
        for (int i : arr) {
            System.out.print(i + " ,");
        }
    }
}&lt;/pre&gt;



&lt;ol&gt;
&lt;li&gt;&lt;span&gt;Now we will think how we can achieve 1. c&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;&lt;span&gt;Let's say we have an empty array. Now if we want to add an element to it and the resultant should be a sorted array.&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;&lt;span&gt;so we can add the element directly in this case, correct?&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;&lt;span&gt;Let's say we have a sorted array. Now if we want to add an element to it and the resultant should be a sorted array.&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;&lt;span&gt;so if the element is greater than the last element then we can add the element directly at the end in this case, correct?&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;&lt;span&gt;if the element is shorter than the last element then we need to put it in between the array, at its correct place. Now, don't you think this is again pointing to recursion, because we need to go to a place where we can insert the element in the array and it will be sorted.&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;&lt;span&gt;Now we know that we need 2 recursive functions&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;&lt;span&gt;sort&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;&lt;span&gt;insert&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;&lt;span&gt;With this, we will again try to write a code&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;&lt;span&gt;Now adding to the last piece of code we have written. It was reducing or array by 1 in each call so we need to add those back at the correct place.&lt;/span&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;pre&gt;public static void sort(int[] arr, int n) {
    if (n == 0) return;
    int val = arr[n];
    sort(arr, n-1);
    insert(arr, val, n);
}
// So we just took the last element and put it at it's correct position&lt;/pre&gt;

&lt;p&gt;&lt;span&gt;Now to insert elements back we will write the insert method.&lt;/span&gt;&lt;/p&gt;

&lt;pre&gt;private static void insert(int[] arr, int value, int n) {
    if (n == 0 || arr[n-1] &amp;lt;= value) {
        arr[n] = value;
    } else {
        int val = arr[n-1];
        insert(arr, value, n - 1);
        arr[n] = val;
    }
}&lt;/pre&gt;

&lt;p&gt;&lt;strong&gt;Code and The order of the calls&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;import java.util.Arrays;

public class SortArray {
    public static void sort(int[] arr, int n) {
        if (n == 0) return;
        int val = arr[n];
        sort(arr, n-1);
        insert(arr, val, n);
    }
    private static void insert(int[] arr, int value, int n) {
        if (n == 0 || arr[n-1] &amp;lt;= value) {
            arr[n] = value;
        } else {
            int val = arr[n-1];
            insert(arr, value, n - 1);
            arr[n] = val;
        }
    }
    public static void main(String[] args) {
        int[] arr = new int[] {9, 4, 2, 9, 1};
        for (int i : arr) {
            System.out.print(i + " ,");
        }
        System.out.println("\n&amp;gt;&amp;gt;&amp;gt;");
        sort(arr, arr.length - 1);
        System.out.println("&amp;lt;&amp;lt;&amp;lt;");
        for (int i : arr) {
            System.out.print(i + " ,");
        }
    }
}&lt;/pre&gt;

&lt;pre&gt;Sort [9, 4, 2, 9, 1] Arr Size: 4
Sort [9, 4, 2, 9, 1] Arr Size: 3
Sort [9, 4, 2, 9, 1] Arr Size: 2
Sort [9, 4, 2, 9, 1] Arr Size: 1
Sort [9, 4, 2, 9, 1] Arr Size: 0
Insert [9, 4, 2, 9, 1] Arr Size: 1
Insert [9, 4, 2, 9, 1] Arr Size: 0
Inserting Value: 4 at 0
Inserting Value: 9 at 1
Insert [4, 9, 2, 9, 1] Arr Size: 2
Insert [4, 9, 2, 9, 1] Arr Size: 1
Insert [4, 9, 2, 9, 1] Arr Size: 0
Inserting Value: 2 at 0
Inserting Value: 4 at 1
Inserting Value: 9 at 2
Insert [2, 4, 9, 9, 1] Arr Size: 3
Inserting Value: 9 at 3
Insert [2, 4, 9, 9, 1] Arr Size: 4
Insert [2, 4, 9, 9, 1] Arr Size: 3
Insert [2, 4, 9, 9, 1] Arr Size: 2
Insert [2, 4, 9, 9, 1] Arr Size: 1
Insert [2, 4, 9, 9, 1] Arr Size: 0
Inserting Value: 1 at 0
Inserting Value: 2 at 1
Inserting Value: 4 at 2
Inserting Value: 9 at 3
Inserting Value: 9 at 4&lt;/pre&gt;

&lt;p&gt;&lt;span&gt;Hope you have a better understanding now, continue with the code101 series, and you'll gain a better understanding.&lt;/span&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;#HappyCoding&lt;/strong&gt;&lt;/p&gt;

</description>
      <category>java</category>
      <category>competativeprogramming</category>
      <category>programming</category>
    </item>
    <item>
      <title>Java Interview Questions - Part 2</title>
      <dc:creator>Garvit Khamesra</dc:creator>
      <pubDate>Tue, 26 Aug 2025 03:17:54 +0000</pubDate>
      <link>https://dev.to/garvit_khamesra/java-interview-questions-part-2-4bln</link>
      <guid>https://dev.to/garvit_khamesra/java-interview-questions-part-2-4bln</guid>
      <description>&lt;p&gt;&lt;span&gt;Part 2 of the&lt;/span&gt;&lt;strong&gt; [Java interview question series](https://dev.to/garvit_khamesra/java-interview-questions-part-1-3ba7)&lt;/strong&gt;&lt;span&gt;. In this, we will cover static, abstract classes and methods, and interfaces.&lt;/span&gt;&lt;/p&gt;

&lt;p&gt;&lt;span&gt;Before we start with the questions I would recommend going through these 3 articles.&lt;/span&gt;&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;a href="https://thetechnote.web.app/article/y3b7IVTcK8aSYKl6HxL2" rel="noopener noreferrer"&gt;Static Keyword in Java&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://thetechnote.web.app/article/iTNFvvhVRYZ8lrQlFr6z" rel="noopener noreferrer"&gt;Final Keyword in Java&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://thetechnote.web.app/article/CINvNGUU3QfEtGIxTXid" rel="noopener noreferrer"&gt;How To Create An Immutable Class In Java?&lt;/a&gt;&lt;/li&gt;
&lt;/ol&gt;


&lt;p&gt;&lt;span&gt;Let's get started&lt;/span&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Q21: Why is main a static method?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;&lt;span&gt;A21: Main method is an entry point of execution in java. JVM has been following this signature to locate the entry point. If we change the signature of the method, the program compiles but does not execute. The main() method in Java must be declared public, static, and void. If any of these are missing, the Java program will compile but a runtime error will be thrown.&lt;/span&gt;&lt;/p&gt;


&lt;p&gt;&lt;strong&gt;Q22: Can we override static methods?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;&lt;span&gt;A22: No, We cannot override static methods because the binding is done at compile time. Even if we create an overridden method, it will not have any effect because runtime polymorphism is not possible.&lt;/span&gt;&lt;/p&gt;

&lt;p&gt;&lt;span&gt;Example:&lt;/span&gt;&lt;/p&gt;

&lt;pre&gt;class Parent {
    static void staticMethod() {
        System.out.println("Parent Method");
    }
}
class Child extends Parent {
    static void staticMethod() {
        System.out.println("Child Method");
    }
    public static void main(String[] args) {
        Parent parent = new Parent();
        Parent child = new Child();
        Child child1 = new Child();
        parent.staticMethod();
        child.staticMethod();
        child1.staticMethod();
    }
} &lt;/pre&gt;


&lt;h3&gt;&lt;strong&gt;Q23: Can we make constructors static?&lt;/strong&gt;&lt;/h3&gt;
&lt;p&gt;&lt;span&gt;A23: No, Contrustors are called when the object is created and static refers to class level properties and not the object level. Even if we try to put static keyword in front of the constructor it will give us an error.&lt;/span&gt;&lt;/p&gt;


&lt;p&gt;&lt;strong&gt;Q24: Can we make the abstract methods static?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;&lt;span&gt;A24: We write abstract methods so that we can override them. So now this question is similar to Can we override static methods. For both, the answer is no with same reasoning.&lt;/span&gt;&lt;/p&gt;


&lt;p&gt;&lt;strong&gt;Q25: What is covariant return type?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;&lt;span&gt;A25: &lt;/span&gt;&lt;span&gt;Before Java5, it was not possible to override methods by changing the return type. But now, we can change the return type to the sub-class type.&lt;/span&gt;&lt;/p&gt;

&lt;p&gt;&lt;span&gt;Example:&lt;/span&gt;&lt;/p&gt;
&lt;pre&gt;class Parent {
     Parent parentMethod() {
        System.out.println("Parent Method");
        return new Parent();
    }
}
class Child extends Parent {
     Child parentMethod() {
        System.out.println("Child Method");
        return new Child();
    }
    public static void main(String[] args) {
        Parent parent = new Parent();
        Parent child = new Child();
        Child child1 = new Child();
        parent.parentMethod();
        child.parentMethod();
        child1.parentMethod();
    }
} &lt;/pre&gt;



&lt;p&gt;&lt;strong&gt;Q26: Can we declare main method as final?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;&lt;span&gt;A26: Yes, we cab have main method as final. The compiler will not give any error and it will work also. But the final keyword is used such that the method cannot be overridden. But as main method already have static which makes it not supported for override.&lt;/span&gt;&lt;/p&gt;



&lt;p&gt;&lt;strong&gt;Q27: Can we declare a constructor as final?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;&lt;span&gt;A27: We cannot declare constructor as final, the compiler will throw an error. &lt;/span&gt;&lt;/p&gt;
&lt;blockquote&gt;&lt;span&gt;"Constructor declarations are not members. They are never inherited and therefore are not subject to hiding or overriding."&lt;/span&gt;&lt;/blockquote&gt;
&lt;p&gt;&lt;span&gt;And final keyword is used to prevent overriding, so adding final will not make sense.&lt;/span&gt;&lt;/p&gt;



&lt;p&gt;&lt;strong&gt;Q28: Can we declare an interface as final?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;&lt;span&gt;A28: No, we cannot declare an interface as final because the interface must be implemented by some class to provide its definition, and the use of final is to prevent that behavior. Therefore, there is no sense to make an interface final. If we try to do so, the compiler will show an error.&lt;/span&gt;&lt;/p&gt;



&lt;p&gt;&lt;strong&gt;Q29: Can we declare an abstract method as final?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;&lt;span&gt;A29: We cannot declare an abstract method as final, because final is used to prevent overriding and abstract methods must be overridden by a subclass. If we try to do so, the compiler will show an error.&lt;/span&gt;&lt;/p&gt;



&lt;p&gt;&lt;strong&gt;Q30: Can we declare an abstract method as private?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;&lt;span&gt;A30: We cannot use a private modifier with an abstract method, because a private modifier restricts access to the given class and the abstract methods must be overridden by a subclass. If we try to do so, the compiler will show an error.&lt;/span&gt;&lt;/p&gt;


&lt;p&gt;&lt;strong&gt;#HappyLearning&lt;/strong&gt;&lt;/p&gt;


</description>
      <category>beginners</category>
      <category>programming</category>
      <category>java</category>
      <category>learning</category>
    </item>
    <item>
      <title>Static Keyword in Java</title>
      <dc:creator>Garvit Khamesra</dc:creator>
      <pubDate>Tue, 26 Aug 2025 03:11:57 +0000</pubDate>
      <link>https://dev.to/garvit_khamesra/static-keyword-in-java-4jak</link>
      <guid>https://dev.to/garvit_khamesra/static-keyword-in-java-4jak</guid>
      <description>&lt;p&gt;&lt;strong&gt;Static Keyword&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;span&gt;We can use the Static keyword in 5 places.&lt;/span&gt;&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;span&gt;Import Statement&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;&lt;span&gt;Block&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;&lt;span&gt;Class&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;&lt;span&gt;Method&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;&lt;span&gt;Variable&lt;/span&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Static Import Statement&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;span&gt;We use import statements to import classes from different packages, adding static to those import statements will only import the static members of the class.&lt;/span&gt;&lt;/p&gt;

&lt;p&gt;&lt;span&gt;Example:&lt;/span&gt;&lt;/p&gt;



&lt;pre&gt;import static {package name}.{static member name};&lt;br&gt;
import static java.lang.System.out; &lt;/pre&gt;




&lt;p&gt;&lt;strong&gt;Static Block&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;span&gt;We create a static block by adding a static keyword before a pair of curly braces.&lt;/span&gt;&lt;/p&gt;

&lt;p&gt;&lt;span&gt;Example:&lt;/span&gt;&lt;/p&gt;



&lt;pre&gt;static {&lt;br&gt;
    staticVariable = 24; // initializing static variable&lt;br&gt;
 }&lt;br&gt;
&lt;/pre&gt;

&lt;p&gt;&lt;span&gt;Few points to remember about the static block.&lt;/span&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;span&gt;It is used to initialize the static variables.&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;&lt;span&gt;It is executed before the main method, It is executed when the class is loaded in the memory. &lt;/span&gt;&lt;/li&gt;
&lt;li&gt;&lt;span&gt;We can have multiple static blocks in a class and these are executed in the same sequence in which they appear in the class definition.&lt;/span&gt;&lt;/li&gt;
&lt;/ul&gt;


&lt;p&gt;&lt;strong&gt;Static Class&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;span&gt;There are a few constraints while dealing with static class.&lt;/span&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;span&gt;A class can be made static only if it is a nested class. We cannot declare a top-level class with a static modifier. &lt;/span&gt;&lt;/li&gt;
&lt;li&gt;&lt;span&gt;Nested static class doesn’t need a reference of Outer class. &lt;/span&gt;&lt;/li&gt;
&lt;li&gt;&lt;span&gt;A static class cannot access non-static members of the Outer class. &lt;/span&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;span&gt;Below is an example of a static nested class.&lt;/span&gt;&lt;/p&gt;

&lt;p&gt;&lt;span&gt;Example:&lt;/span&gt;&lt;/p&gt;

&lt;br&gt;
&lt;pre&gt;public class StaticClassExample {&lt;br&gt;
    public static void main(String[] args) {&lt;br&gt;
        //Static inner class example&lt;br&gt;
        DataObject.StaticInnerClass.accessOuterClass();&lt;br&gt;
    }&lt;br&gt;
}&lt;br&gt;
class DataObject {&lt;br&gt;
    public int nonStaticVariable;&lt;br&gt;
    public static int staticVariable;  //static variable
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;static {
    staticVariable = 40;
    //nonStaticVariable = 20;  //Not possible to access non-static members
}
public static int getStaticVariable(){
    return staticVariable;
}
static class StaticInnerClass {
    public static void accessOuterClass() {
        System.out.println(DataObject.staticVariable);   //static variable of outer class
        System.out.println(DataObject.getStaticVariable());  //static method of outer class
        System.out.println(staticVariable);   //static variable of outer class
        System.out.println(getStaticVariable()); // static method of outer class
        // System.out.println(DataObject.nonStaticVariable); // Not Possible
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;}&lt;br&gt;
&lt;/p&gt;&lt;/pre&gt;


&lt;p&gt;&lt;strong&gt;Static Methods&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;span&gt;Few points to remember about the static methods.&lt;/span&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;span&gt;Static methods can be accessed via its class reference. &lt;/span&gt;&lt;/li&gt;
&lt;li&gt;&lt;span&gt;Static methods can call other static methods.&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;&lt;span&gt;Static methods also belong to the class-level scope.&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;&lt;span&gt;Static methods can access static data members and can change their value.&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;
&lt;span&gt;They cannot refer to &lt;/span&gt;&lt;span&gt;this&lt;/span&gt;&lt;span&gt; or &lt;/span&gt;&lt;span&gt;super&lt;/span&gt;&lt;span&gt; in any way.&lt;/span&gt;
&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;span&gt;Example:&lt;/span&gt;&lt;/p&gt;

&lt;br&gt;
&lt;pre&gt;public static int getStaticVariable(){&lt;br&gt;
      return staticVariable;&lt;br&gt;
}&lt;br&gt;
&lt;/pre&gt;


&lt;p&gt;&lt;strong&gt;Static Variables&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;span&gt;Static variables are Class level properties. They do not vary based on the objects of the class.&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;&lt;span&gt;We can demonstrate this by the below code example, where we have a counter which is static and non-static.&lt;/span&gt;&lt;/p&gt;

&lt;p&gt;&lt;span&gt;Example:&lt;/span&gt;&lt;/p&gt;

&lt;br&gt;
&lt;pre&gt;public class StaticClassExample {&lt;br&gt;
    public static void main(String[] args) {&lt;br&gt;
        DataObject object1 = new DataObject();&lt;br&gt;
        DataObject object2 = new DataObject();&lt;br&gt;
        DataObject object3 = new DataObject();&lt;br&gt;
        DataObject object4 = new DataObject();&lt;br&gt;
    }&lt;br&gt;
}&lt;br&gt;
class DataObject {&lt;br&gt;
    public int nonStaticVariable;&lt;br&gt;
    public static int staticVariable;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public DataObject() {
    nonStaticVariable++;
    staticVariable++;
    System.out.println(staticVariable);
    System.out.println(nonStaticVariable);
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;}&lt;br&gt;
&lt;/p&gt;&lt;/pre&gt;


&lt;p&gt;&lt;strong&gt;#HappyCoding&lt;/strong&gt;&lt;/p&gt;



</description>
      <category>java</category>
      <category>beginners</category>
      <category>programming</category>
    </item>
    <item>
      <title>Code 101: Longest Valid Parentheses ( LeetCode Hard Problem )</title>
      <dc:creator>Garvit Khamesra</dc:creator>
      <pubDate>Tue, 26 Aug 2025 02:57:19 +0000</pubDate>
      <link>https://dev.to/garvit_khamesra/code-101-longest-valid-parentheses-leetcode-hard-problem--3b98</link>
      <guid>https://dev.to/garvit_khamesra/code-101-longest-valid-parentheses-leetcode-hard-problem--3b98</guid>
      <description>&lt;p&gt;&lt;strong&gt;Question:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;&lt;span&gt;Given a string containing just the characters &lt;/span&gt;&lt;span&gt;'('&lt;/span&gt;&lt;span&gt; and &lt;/span&gt;&lt;span&gt;')'&lt;/span&gt;&lt;span&gt;, find the length of the longest valid (well-formed) parentheses substring.&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;&lt;span&gt; &lt;/span&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Example 1:&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;Input: s = "(()" Output: 2 Explanation: The longest valid parentheses substring is "()". &lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;Example 2:&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;Input: s = ")()())" Output: 4 Explanation: The longest valid parentheses substring is "()()". &lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;Example 3:&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;Input: s = "" Output: 0 &lt;/pre&gt;
&lt;p&gt; &lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Constraints:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;span&gt;0 &amp;lt;= s.length &amp;lt;= 3 * 104&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;
&lt;span&gt;s[i]&lt;/span&gt; is &lt;span&gt;'('&lt;/span&gt;, or &lt;span&gt;')'&lt;/span&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;You can find the question &lt;a href="https://leetcode.com/problems/longest-valid-parentheses/" rel="noopener noreferrer"&gt;here&lt;/a&gt;.&lt;/p&gt;



&lt;p&gt;&lt;strong&gt;Solution:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Stack Approach&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;&lt;span&gt;First thing whenever I see questions that have something to balance, validate, or format, I think in terms of the stack. The first thought is to check can we solve this with the stack.&lt;/span&gt;&lt;/p&gt;

&lt;p&gt;&lt;span&gt;Coming to the problem, How do we say a parenthesis is valid? Whenever we see 1 closing and corresponding opening parenthesis.&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;&lt;span&gt;How do we say a parenthesis is invalid? Whenever we see a closing parenthesis without an opening parenthesis. We cannot say the same for the opening parenthesis because we can say that in the future a closing parenthesis might come.&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;&lt;span&gt;Also, we need to find the longest valid string length, so we need to maintain the size some place.&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;&lt;span&gt;Now with this information, we can derive an algorithm to solve this.&lt;/span&gt;&lt;/p&gt;

&lt;p&gt;&lt;span&gt;Let's say we iterate the string and &lt;/span&gt;&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;span&gt;Whenever we encounter '(' we add it's index to the stack.&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;&lt;span&gt;Whenever we encounter ')' now we need to check if there is any valid combination to add to out result or not.&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;&lt;span&gt;To calculate max length we need to check the index with the index of the '(' which will be present in the stack top.&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;&lt;span&gt;There are a few scenarios that are missed above.&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;&lt;span&gt;What happens when there is String "()" -&amp;gt; result would be 1 instead of 2&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;&lt;span&gt;What if we have more ')', That means we have an invalid string starting. So now we need to restart our calculation. We will do that by adding the index of the invalid string start&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;&lt;span&gt;Edge case: only ')'&lt;/span&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;span&gt;I have added inline comments in the code for a better understanding of the algorithm.&lt;/span&gt;&lt;/p&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import java.util.Stack;

public class LongestValidParenthesis {
    public static int longestValidParentheses(String s) {
        int res = 0; // Initial length
        Stack&amp;lt;Integer&amp;gt; st = new Stack&amp;lt;&amp;gt;(); // Initialize the stack
        st.push(-1); // Added to handle edge case
        for (int i = 0; i &amp;lt; s.length(); i++) {
            if (s.charAt(i) == '(') {
                st.push(i);
            } else {
                if (st.size() &amp;gt; 1 &amp;amp;&amp;amp; s.charAt(st.peek()) == '(') {
                    st.pop();
                    res = Math.max(res,i - st.peek()); // calc the length of valid string
                } else {
                    st.push(i); // To handle invalid scenarios 
                }
            }
        }
        return res;
    }

    public static void main(String[] args) {
        System.out.println(longestValidParentheses(")()())))"));
    }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;span&gt;Above is 1 approach to solve this question. Once I understood this, I wanted to check what all other solutions could be possible for this question.&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;&lt;span&gt;I found there are 2 more ways to solve this.&lt;/span&gt;&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;span&gt;Dynamic Programing &lt;/span&gt;&lt;/li&gt;
&lt;li&gt;&lt;span&gt;Without extra space&lt;/span&gt;&lt;/li&gt;
&lt;/ol&gt;


&lt;p&gt;&lt;strong&gt;Dynamic Programming Approach&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;span&gt;Dp problems consist of 2 parts, 1st subproblem, and 2nd memoization.&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;&lt;span&gt;The condition for valid and invalid remains the same for every approach. So now the subproblem will be something when we have ) do we have corresponding ( and we will maintain the length of each valid substring.&lt;/span&gt;&lt;/p&gt;

&lt;p&gt;&lt;span&gt;The below code demonstrates the same algo, I have added inline comments for better understanding.&lt;/span&gt;&lt;/p&gt;




&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class LongestValidParenthesis {

    public static int longestValidParenthesesDP(String str) {
        int res = 0;
        int dp[] = new int[str.length()];
        for (int i = 1; i &amp;lt; str.length(); i++) {
            if (str.charAt(i) == ')') { // Whenever we encounter ')'
                if (str.charAt(i - 1) == '(') { // We need to check if the character before is '(' or not
                    dp[i] = (i &amp;gt;= 2 ? dp[i - 2] : 0) + 2; // if true we just add 2 to the previously calculated length of valid substring
                } else if (i - dp[i - 1] &amp;gt; 0 &amp;amp;&amp;amp; str.charAt(i - dp[i - 1] - 1) == '(') {
                    // i - dp[i-1] -1 means we are pointing to the index just before we had a valid string,
                    // because the dp[i-1] has the valid substring length
                    // once we at that index we need to check that the index is having '('
                    // this means we have addition to our valid substring
                    dp[i] = dp[i - 1] + ((i - dp[i - 1]) &amp;gt;= 2 ? dp[i - dp[i - 1] - 2] : 0) + 2;
                }
                res = Math.max(res, dp[i]);
            }
        }
        return res;
    }

    public static void main(String[] args) {
        System.out.println(longestValidParenthesesDP(")()())))"));
    }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;




&lt;p&gt;&lt;strong&gt;Without Extra Space&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;&lt;span&gt;This solution I did not think, I just read it from the solution and find it interesting so thought to add it.&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;&lt;span&gt;Here the idea remains the same, only now we use 2 pointers and we traverse 2 times, 1 left to right &amp;amp; 1 right to left.&lt;/span&gt;&lt;/p&gt;

&lt;p&gt;&lt;span&gt;The below code demonstrates the same algo, I have added inline comments for better understanding.&lt;/span&gt;&lt;/p&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public int longestValidParenthesesWithoutExtraSpace(String s) {
    int left = 0, right = 0, maxlength = 0;
    for (int i = 0; i &amp;lt; s.length(); i++) {
        if (s.charAt(i) == '(') {
            left++;
        } else {
            right++;
        }
        if (left == right) { // string is valid
            maxlength = Math.max(maxlength, 2 * right);
        } else if (right &amp;gt;= left) { // string becomes invalid
            left = right = 0;
        }
    }

    // Second iteration is to make sure if we had left more from left -&amp;gt; right which when traverse from right -&amp;gt; left
    // can contribute to max length 
    left = right = 0;
    for (int i = s.length() - 1; i &amp;gt;= 0; i--) {
        if (s.charAt(i) == '(') {
            left++;
        } else {
            right++;
        }
        if (left == right) { // string is valid
            maxlength = Math.max(maxlength, 2 * left);
        } else if (left &amp;gt;= right) { // String becomes invalid
            left = right = 0;
        }
    }
    return maxlength;
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;#HappyCoding&lt;/strong&gt;&lt;/p&gt;

</description>
      <category>programming</category>
      <category>java</category>
      <category>competativeprogramming</category>
    </item>
  </channel>
</rss>
