Pages

Wednesday, August 20, 2025

Container with Most Water (2-pointer approach)

 import java.util.*;



public class Main

{

    

    // 2pointer approach

    public static int storeWater(ArrayList<Integer> height) {

        int maxWater = 0;

        int lp = 0;

        int rp = height.size()-1;

        

        while(lp < rp) {

            // calculate water

            int ht = Math.min(height.get(lp), height.get(rp));

            int width = rp- lp;

            int currWater = ht*width;

            maxWater = Math.max(maxWater, currWater);

            

            // update 2pointer

            if(height.get(lp) < height.get(rp)) {

                lp++;

            } else {

                rp--;

            }

        }

        

      return maxWater;  

    }

    

public static void main(String[] args) {

ArrayList<Integer> height = new ArrayList<>();

// 1, 8, 6, 2, 5, 4, 8, 3, 7

height.add(1);

height.add(8);

height.add(6);

height.add(2);

height.add(5);

height.add(4);

height.add(8);

height.add(3);

height.add(7);

System.out.println(storeWater(height));

}

}

Container with Most Water (Brute Force method) in Java

 import java.util.*;



public class Main

{

    

    

    public static int storeWater(ArrayList<Integer> height) {

        int maxWater = 0;

        // brute force - O(n^2)

        for(int i=0; i<height.size(); i++) {

            for(int j=i+1; j<height.size(); j++) {

                int ht = Math.min(height.get(i), height.get(j)); // L1 and L2

                int width = j-1;

                int currWater = ht * width;

                maxWater = Math.max(maxWater, currWater);

            }

        }

        

        

        return maxWater;

        

    }

public static void main(String[] args) {

ArrayList<Integer> height = new ArrayList<>();

// 1, 8, 6, 2, 5, 4, 8, 3, 7

height.add(1);

height.add(8);

height.add(6);

height.add(2);

height.add(5);

height.add(4);

height.add(8);

height.add(3);

height.add(7);

System.out.println(storeWater(height));

}

}

Tuesday, August 19, 2025

Multi-dimensional ArrayList in Java

 // import java.util.ArrayList;

import java.util.*;
// import java.util.Collections;
public class Classroom {


    public static void main(String args[]) {
        ArrayList<ArrayList<Integer>> mainList = new ArrayList<>();
        ArrayList<Integer> list1 = new ArrayList<>();
        ArrayList<Integer> list2 = new ArrayList<>();
        ArrayList<Integer> list3 = new ArrayList<>();

        for(int i=1; i<=5; i++) {
            list1.add(i*1); // 1 2 3 4 5
            list2.add(i*2); // 2 4 6 8 10
            list3.add(i*3); // 3 6 9 12 15

           
        }

            mainList.add(list1);
            mainList.add(list2);
            mainList.add(list3);
            list2.remove(3);
            list2.remove(2);

            System.out.println(mainList);

            // Nested loops
            for(int i=0; i<mainList.size(); i++) {
                ArrayList<Integer> currList = mainList.get(i);
                for(int j=0; j<currList.size(); j++) {
                    System.out.print(currList.get(j)+" ");
                }
                System.out.println();

            }
       
    }


}

Monday, August 18, 2025

Sorting an ArrayList in Java - optimized version of sort(use if not asked in question)

 // import java.util.ArrayList;

import java.util.*;
// import java.util.Collections;
public class Classroom {

    public static void main(String[] args) {
       ArrayList<Integer> list = new ArrayList<>();
       list.add(2);
       list.add(5);
       list.add(9);
       list.add(6);
       list.add(8);

   
       System.out.println("List before sorted: " + list );
       Collections.sort(list);
       System.out.println("List after sorted: " + list);

       // desc order
       Collections.sort(list, Collections.reverseOrder());
       
       // Comparator - fnx logic
       System.out.println("in Desc Order: " + list);
    }

}

Swap 2 Numbers in ArrayList in Java

 import java.util.ArrayList;

import java.util.*;

public class Classroom {

    public static void swap(ArrayList<Integer> list, int idx1, int idx2) {
        int temp = list.get(idx1);
        list.set(idx1, list.get(idx2));// sets the value of idx1 to idx2
        list.set(idx2, temp);
    }

    public static void main(String[] args) {
       ArrayList<Integer> list = new ArrayList<>();
       list.add(2);
       list.add(5);
       list.add(9);
       list.add(6);
       list.add(8);

    int idx1 = 1, idx2 = 3;
        System.out.println(list);

      swap(list, idx1, idx2);
        System.out.println(list);
    }
}

Find the Max in an ArrayList

 import java.util.ArrayList;


public class Classroom {

    public static void main(String[] args) {
       ArrayList<Integer> list = new ArrayList<>();
       list.add(2);
       list.add(5);
       list.add(9);
       list.add(6);
       list.add(8);

      // Find Maximum in an ArrayList - O(1)
        int max = Integer.MIN_VALUE;
        for(int i=0; i<list.size(); i++) {
            // if(max < list.get(i)) {
            //     max = list.get(i);
            // }
            max = Math.max(max, list.get(i));

            System.out.println("Max element = " + max);
        }


    }
}

Reverse of ArrayList in Java

import java.util.ArrayList;

public class Classroom {

    public static void main(String[] args) {
       ArrayList<Integer> list = new ArrayList<>();
       list.add(1);
       list.add(2);
       list.add(3);
       list.add(4);
       list.add(5);

       // Reverse Print - O(n)
       for(int i=list.size()-1; i>= 0; i--) {
        System.out.println(list.get(i));
       }
    }
}

Size of ArrayList in Java

import java.util.ArrayList;

public class Classroom {

    public static void main(String[] args) {
       ArrayList<Integer> list = new ArrayList<>();
       list.add(1);
       list.add(2);
       list.add(3);
       list.add(4);
       list.add(5);

       System.out.println(list.size());

       // print the arraylist
       for(int i=0; i<list.size(); i++) {
        System.out.print(list.get(i) + " ");
       }
    }
}

Operations on ArrayList in Java

 import java.util.ArrayList;


public class Classroom {



    public static void main(String[] args) {
       
        ArrayList<Integer> list = new ArrayList<>();
        ArrayList<String> list2 = new ArrayList<>();
        ArrayList<Boolean> list3 = new ArrayList<>();

        // Add Element - O(1)
        list.add(1); // O(1)
        list.add(2);
        list.add(3);
        list.add(4);
        list.add(5);


        list.add(1, 9); // O(n)
        System.out.println(list);


        // Get Operation - O(1)
        // int element = list.get(2);
        // System.out.println("Get Operation: " + element);

        // Delete
        // list.remove(2);
        // System.out.println("Delete Operation: " + list);

        // Set - o(n)
        // list.set(2, 10);
        // System.out.println(list);

        // // Contains - O(n)
        // System.out.println(list.contains(1));
        // System.out.println(list.contains(2));
        // System.out.println(list.contains(11));

       
    }
}

Saturday, August 16, 2025

Find Subsets in Java (backtracking problem)

 

Problem:

Generate all subsets of {1,2,3}
👉 Subsets are like: [], [1], [2], [3], [1,2], [1,3], [2,3], [1,2,3].


Key points you need:

  1. List<Integer> → Just a resizable array.
    Example: List<Integer> a = new ArrayList<>();
    You can:

    • a.add(5); → adds 5

    • a.remove(0); → removes first element

    • a.size(); → gives length

    Think of it like Python’s list or C++ vector.

  2. List<List<Integer>> → means a list of lists.
    Why? Because we want to store all subsets (each subset itself is a list).
    Example:

    [ [], [1], [2], [1,2], [3], [1,3], [2,3], [1,2,3] ]

Now your function step-by-step:

static void findSubsets(int index, int[] nums, List<Integer> current, List<List<Integer>> result) {
  • index → where we are in the array.

  • nums → original input {1,2,3}.

  • current → current subset we are building.

  • result → stores all subsets.


Base case:

if(index == nums.length) { result.add(new ArrayList<>(current)); return; }

👉 If we reached the end of array → save the current subset.
new ArrayList<>(current) = copy of current (otherwise all subsets would change together).


Choices:

// Choice 1: Exclude nums[index] findSubsets(index+1, nums, current, result);

Skip the element.

// Choice 2: Include nums[index] current.add(nums[index]); findSubsets(index+1, nums, current, result); current.remove(current.size() -1); // backtrack

Take the element, explore, then remove it (to undo choice for next branch).


Dry run with {1,2,3}:

  • Start [] at index=0

  • Exclude 1 → go next

    • Exclude 2 → go next

      • Exclude 3 → add []

      • Include 3 → add [3]

    • Include 2 →

      • Exclude 3 → add [2]

      • Include 3 → add [2,3]

  • Include 1 →

    • Exclude 2 →

      • Exclude 3 → add [1]

      • Include 3 → add [1,3]

    • Include 2 →

      • Exclude 3 → add [1,2]

      • Include 3 → add [1,2,3]

Result = [[], [3], [2], [2,3], [1], [1,3], [1,2], [1,2,3]]


✅ That’s why we need List<List<Integer>> → to store all subsets.



CODE: 

import java.util.*; // (My Mistake) -> forgot to add this which had 'List' errors atleast 8




public class Main

{

static void findSubsets(int index, int[] nums, List<Integer> current, List<List<Integer>> result) {

    // Base case: if index == nums.length, add the subset

    if(index == nums.length) {

        result.add(new ArrayList<>(current)); // dynamic size of ArrayList no worry of size

        return;

    }

    

    

    // Choice 1: Exclude nums[index]

    findSubsets(index+1, nums, current, result);

    

    // Choice 2: Include nums[index]

    current.add(nums[index]);

    findSubsets(index+1, nums, current, result);

    

    // Backtrack (Remove last added element)

    current.remove(current.size() -1);

    

}

public static void main(String[] args) {

    int[] nums = {1, 2, 3};

    List<List<Integer>> result = new ArrayList<>();

    

    findSubsets(0, nums, new ArrayList<>(), result);

    System.out.println(result);

}

}

Transition from C++ to Java (Sheet) helps you switch language faster!

Perfect 😎 I’ll make a visual translation map that you can memorize quickly while coding. I’ll organize it by common operations so you just “see C++ → Java” at a glance.


C++ STL → Java Collections Quick Map

1. Dynamic Arrays

C++ Java Notes
vector<int> v; ArrayList<Integer> list = new ArrayList<>(); Dynamic size
v.push_back(x); list.add(x); Add element at end
v.pop_back(); list.remove(list.size()-1); Remove last element
v[i] list.get(i) Access element
v.size() list.size() Size of array
v[i] = x; list.set(i, x); Modify element

2. 2D Arrays / Lists

C++ Java Notes
vector<vector<int>> mat; List<List<Integer>> mat = new ArrayList<>(); Nested dynamic arrays
mat[i][j] mat.get(i).get(j) Access element
mat[i].push_back(x) mat.get(i).add(x) Append to inner list

3. Stack

C++ Java Notes
stack<int> st; Stack<Integer> st = new Stack<>(); LIFO stack
st.push(x); st.push(x); Add element
st.pop(); st.pop(); Remove top
st.top(); st.peek(); Access top element

4. Queue

C++ Java Notes
queue<int> q; Queue<Integer> q = new LinkedList<>(); FIFO queue
q.push(x); q.offer(x); Add element
q.pop(); q.poll(); Remove front
q.front(); q.peek(); Access front

5. Priority Queue

C++ Java Notes
priority_queue<int> pq; PriorityQueue<Integer> pq = new PriorityQueue<>(Collections.reverseOrder()); Max-heap
pq.push(x); pq.add(x); Add element
pq.top(); pq.peek(); Max element
pq.pop(); pq.poll(); Remove top

6. Hash Map / Hash Set

C++ Java Notes
unordered_map<int,int> mp; HashMap<Integer,Integer> map = new HashMap<>(); Key-value store
mp[key] = val; map.put(key,val); Insert / update
mp.count(key) map.containsKey(key) Check existence
unordered_set<int> st; HashSet<Integer> set = new HashSet<>(); Unique elements
st.insert(x) set.add(x); Add element
st.erase(x) set.remove(x); Remove element

7. Sorting & Utility

C++ Java Notes
sort(v.begin(), v.end()); Collections.sort(list); Sort ascending
reverse(v.begin(), v.end()); Collections.reverse(list); Reverse order
*min_element(v.begin(), v.end()) Collections.min(list) Minimum
*max_element(v.begin(), v.end()) Collections.max(list) Maximum

8. Other Useful

C++ Java Notes
pair<int,int> p; Map.Entry<Integer,Integer> p; or custom Pair class No native pair in Java
string s; String s; or StringBuilder sb; Strings immutable in Java
bool flag; boolean flag; true / false
for(int x : v) for(int x : list) Enhanced for-loop
v.empty() list.isEmpty() Check empty
const int x = 5; final int x = 5; Immutable variable

💡 Tips to remember:

  • Think push_back → add, pop_back → remove(last), top/front → peek.

  • Vectors → ArrayLists, Sets/Maps mostly same but Java needs class wrappers.

  • Most STL algorithms (sort, reverse, min/max) → Collections methods in Java.


If you want, I can also make a compact “1-page visual map with arrows” showing C++ → Java in a diagram.
It’ll be like cheat-sheet wallpaper for your brain 😎.

Do you want me to do that next?

Factorial in Java

 public class Main

{

    public static int fact(int n) { // void -> int (My Mistake)-01

        if(n == 0 || n == 1) {

            return 1;

        }

        

        

        // recursion

        return n * fact(n-1);

    }

    

    

    

public static void main(String[] args) {

System.out.println(fact(5));

}

}

My Most Important Mistake (realize before it's too late) ! - in DSA

 

I AM STRONG AT ->  1. Conceptual Thinking(Logic/ Pseudocode)
but Weak at 2. Pattern and Technique Thinking (DSA Concepts)


🔹 Levels of Thinking in DSA

When solving problems (for interviews, contests, or your mastery dream), there are 3 levels of thinking you need:

1. Conceptual Thinking (Logic / Pseudocode)

  • Being able to break a problem into steps without worrying about syntax.

  • Example: For "letter combinations", you already thought → “pick one letter from 2, combine with letters from 3, repeat until done.”

  • ✅ You’re good at this already.


2. Pattern & Technique Thinking (DSA Concepts)

This is where you need to choose the right tool/approach:

  • Recursion / Backtracking → when you need to try all possibilities.

  • BFS / DFS → when exploring trees/graphs or generating levels of combinations.

  • Hashing → for fast lookups.

  • Sorting + Two pointers / Binary Search → for optimization.

  • Dynamic Programming → when problems overlap & repeat.

👉 This is your current weak point.
You didn’t know BFS yet, which means you don’t fully know when to apply which technique. Without this toolbox, you’ll struggle in harder problems.


3. Implementation Thinking (Code)

  • Turning logic into working Java code.

  • Debugging syntax errors.

  • Writing clean, efficient code in limited time.

👉 Here, you’re still developing. Right now, you can explain logic but not always translate into runnable code without help. That’s fine — practice fixes this.


🔹 So what do you actually lack?

Here’s your strength vs weak points right now:

SkillYour StatusWhat to Work On
Problem Understanding👍 Good – you can explain logic in words/pseudocodeKeep practicing step-by-step breakdown
Patterns / DSA Concepts⚠️ Weak – don’t know BFS, DFS, backtracking fully, also need sorting, binary search, DPLearn and practice each category one by one
Coding Skills (Java)⚠️ Medium – you mix pseudocode with C++/Java, struggle with syntaxPractice writing clean Java code, debug by yourself first
Optimization Thinking❌ Not started yet – like improving time/space complexityWill come after you master basics

🔹 Roadmap for You (DSA Mastery Dream)

  1. Strengthen Core Java Implementation

    • Arrays, Strings, Loops, Recursion.

    • Write small programs daily (don’t copy, type yourself).

  2. Master Core Patterns (must-know for interviews):

    • Recursion + Backtracking → (Maze, Subsets, N-Queens, Letter Combinations).

    • BFS & DFS → (Graphs, Trees, Shortest Path).

    • Binary Search & Variants.

    • Hashing (HashMap/Set).

    • Sliding Window / Two pointers.

    • Dynamic Programming basics.

  3. Daily Practice Plan (90–120 mins)

    • Step 1 (20 mins): Read a new concept (e.g., BFS).

    • Step 2 (40 mins): Solve 1–2 easy/medium problems on it.

    • Step 3 (30–40 mins): Try to write code without help. If stuck, then check solutions.

  4. Weekly Reflection:

    • Can I explain this problem in English + pseudocode?

    • Can I code it alone in 20 mins?


💡 In short:

  • You already think like a problem solver (pseudocode).

  • What you lack is:

    1. Knowledge of DSA techniques (patterns like BFS, recursion, backtracking, etc.)

    2. Coding fluency in Java (turning logic into syntax fast).

Rat in a Maze using Backtracking in Java (Assignment sigma 7.0)

 public class Main {


    public static void printSolution(int sol[][]) {

        for (int i = 0; i < sol.length; i++) {

            for (int j = 0; j < sol.length; j++) {

                System.out.print(" " + sol[i][j] + " ");

            }

            System.out.println(); // prints new line

        }

    }


    public static boolean isSafe(int maze[][], int x, int y) {

        return (x >= 0 && x < maze.length &&

                y >= 0 && y < maze.length &&

                maze[x][y] == 1);

    }


    public static boolean solveMaze(int maze[][]) {

        int N = maze.length;

        int sol[][] = new int[N][N];


        if (!solveMazeUtil(maze, 0, 0, sol)) {

            System.out.println("Solution doesn't exist");

            return false;

        }


        printSolution(sol);

        return true;

    }


    public static boolean solveMazeUtil(int maze[][], int x, int y, int sol[][]) {

        int N = maze.length;


        // if destination is reached

        if (x == N - 1 && y == N - 1 && maze[x][y] == 1) {

            sol[x][y] = 1;

            return true;

        }


        if (isSafe(maze, x, y)) {

            if (sol[x][y] == 1) // already visited

                return false;


            sol[x][y] = 1;


            // move Down

            if (solveMazeUtil(maze, x + 1, y, sol))

                return true;


            // move Right

            if (solveMazeUtil(maze, x, y + 1, sol))

                return true;


            // backtrack

            sol[x][y] = 0;

            return false;

        }


        return false;

    }


    public static void main(String args[]) {

        int maze[][] = {

            {1, 0, 0, 0},

            {1, 1, 0, 1},

            {0, 1, 0, 0},

            {1, 1, 1, 1}

        };

        solveMaze(maze);

    }

}





OUTPUT:
 1  0  0  0 
 1  1  0  0 
 0  1  0  0 
 0  1  1  1 

Thursday, August 14, 2025

GridWays in Java (backtracking)

 class Main {

    public static int gridWays(int i, int j, int n, int m) {

        

        //base case

        if(i == n-1 && j == m-1) { // condition for last cell

            return 1;

        } else if(i == n || j == n) { // boundary cross

            return 0;

        }

        

        

        

        

        

        int w1 = gridWays(i+1, j, n, m);

        int w2 = gridWays(i, j+1, n, m);

        return w1+w2;

    }

    

    

    public static void main(String[] args) {

        int n = 3, m = 3;

        System.out.println(gridWays(0, 0, n, m));

    }

}


OUTPUT:
6

Sudoku Solver in Java

class Main {

    public static boolean isSafe(int sudoku[][], int row, int col, int digit) {

        // column

        for (int i = 0; i < 9; i++) {

            if (sudoku[i][col] == digit) return false;

        }

        // row

        for (int j = 0; j < 9; j++) {

            if (sudoku[row][j] == digit) return false;

        }

        // grid

        int sr = (row / 3) * 3;

        int sc = (col / 3) * 3;

        for (int i = sr; i < sr + 3; i++) {

            for (int j = sc; j < sc + 3; j++) {

                if (sudoku[i][j] == digit) return false;

            }

        }

        return true;

    }


    public static boolean sudokuSolver(int sudoku[][], int row, int col) {

        if (row == 9) return true;


        int nextRow = row, nextCol = col + 1;

        if (nextCol == 9) {

            nextRow = row + 1;

            nextCol = 0;

        }


        if (sudoku[row][col] != 0) {

            return sudokuSolver(sudoku, nextRow, nextCol);

        }


        for (int digit = 1; digit <= 9; digit++) {

            if (isSafe(sudoku, row, col, digit)) {

                sudoku[row][col] = digit;

                if (sudokuSolver(sudoku, nextRow, nextCol)) return true;

                sudoku[row][col] = 0;

            }

        }

        return false;

    }


    public static void printSudoku(int sudoku[][]) {

        for (int i = 0; i < 9; i++) {

            for (int j = 0; j < 9; j++) {

                System.out.print(sudoku[i][j] + " ");

            }

            System.out.println();

        }

    }


    public static void main(String[] args) {

        // Valid unsolved puzzle

        int sudoku[][] = { 

    {0,0,0,2,6,0,7,0,1},

    {6,8,0,0,7,0,0,9,0},

    {1,9,0,0,0,4,5,0,0},

    {8,2,0,1,0,0,0,4,0},

    {0,0,4,6,0,2,9,0,0},

    {0,5,0,0,0,3,0,2,8},

    {0,0,9,3,0,0,0,7,4},

    {0,4,0,0,5,0,0,3,6},

    {7,0,3,0,1,8,0,0,0}

};




        if (sudokuSolver(sudoku, 0, 0)) {

            System.out.println("Solution exists");

            printSudoku(sudoku);

        } else {

            System.out.println("Solution doesn't exist");

        }

    }

}



OUTPUT: 
Solution exists
4 3 5 2 6 9 7 8 1 
6 8 2 5 7 1 4 9 3 
1 9 7 8 3 4 5 6 2 
8 2 6 1 9 5 3 4 7 
3 7 4 6 8 2 9 1 5 
9 5 1 7 4 3 6 2 8 
5 1 9 3 2 6 8 7 4 
2 4 8 9 5 7 1 3 6 
7 6 3 4 1 8 2 5 9 



-> My Mistakes:
 https://chatgpt.com/share/689ddc41-c054-8013-bd32-d87240924565

Wednesday, August 13, 2025

N Queen - all ways - Java - 02nd example

 import java.util.*;


public class Classroom {



    public static boolean isSafe(char board[][], int row, int col) {
        // vertical up
        for(int i=row-1; i>=0; i--) {
            if(board[i][col] == 'Q') {
                return false;
            }
        }



        // diag left up
        for(int i=row-1, j=col-1; i>=0 && j>=0; i--, j--) {
            if(board[i][j] == 'Q') {
                return false;
            }
        }

        // diag right up
        for(int i=row-1, j=col+1; i>=0 && j<board.length; i--, j++) {
            if(board[i][j] == 'Q') {
                return false;
            }
        }

        return true;
    }



    // function to place queens
    public static void nQueens(char board[][], int row) {
        // base case
        if (row == board.length) {
            printBoard(board);
            return;
        }

        // column loop
        for(int j = 0; j < board.length; j++) {
            if(isSafe(board, row, j)) {
                board[row][j] = 'Q'; // queen placed here
                nQueens(board, row + 1); // recursive call
                board[row][j] = 'x'; // backtracking step


            }
        }
    }

    // print board
    public static void printBoard(char board[][]) {
        System.out.println("--------- chess board ---------");
        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j < board.length; j++) {
                System.out.print(board[i][j] + " ");
            }
            System.out.println();
        }
    }

    public static void main(String[] args) {
        int n = 4;
        char board[][] = new char[n][n];
       
        // initialize board with 'x'
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                board[i][j] = 'x';
            }
        }

        nQueens(board, 0);
    }
}

N Queens - all ways in Java

 

1. Missing curly braces after class declaration

java
public class Classroom

should be:

java
public class Classroom {

2. Wrong way of representing '.' in char

You are using:

java
board[row][j] = ".";
  • This is a String, not a char.

  • Since your board is char[][], use single quotes:

java
board[row][j] = '.';

3. Strings[] args should be String[] args

java
public static void main(Strings[] args)

must be:

java
public static void main(String[] args)

4. board.length() is wrong

length() is for methods (like String).
For arrays, use .length without parentheses:

java
for(int i=0; i<board.length; i++) { for(int j=0; j<board.length; j++) {

5. Your main method is misplaced

You placed main inside { } outside any method, which is invalid.
It should be inside the Classroom class, not after random { }.


6. Initialization of board

Same issue as point 2 — you need to use '.' instead of ".".


Here’s the corrected code:

java



import java.util.*;


public class Classroom {

    // function to place queens
    public static void nQueens(char board[][], int row) {
        // base case
        if (row == board.length) {
            printBoard(board);
            return;
        }

        // column loop
        for (int j = 0; j < board.length; j++) {
            board[row][j] = 'Q'; // queen placed here
            nQueens(board, row + 1); // recursive call
            board[row][j] = '.'; // backtracking step
        }
    }

    // print board
    public static void printBoard(char board[][]) {
        System.out.println("--------- chess board ---------");
        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j < board.length; j++) {
                System.out.print(board[i][j] + " ");
            }
            System.out.println();
        }
    }

    public static void main(String[] args) {
        int n = 2;
        char board[][] = new char[n][n];
       
        // initialize board with '.'
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                board[i][j] = '.';
            }
        }

        nQueens(board, 0);
    }
}




OUTPUT: --------- chess board --------- Q . Q . --------- chess board --------- Q . . Q --------- chess board --------- . Q Q . --------- chess board --------- . Q . Q



Container with Most Water (2-pointer approach)

 import java.util.*; public class Main {          // 2pointer approach     public static int storeWater(ArrayList<Integer> height) {  ...