Pages

Thursday, October 30, 2025

Connect n ropes with minimum cost in Java ( solved )

 import java.util.*;


public class Main {

    

    public static int minRopeCost(int[] arr, int n) {

        PriorityQueue<Integer> pq = new PriorityQueue<Integer>();

        

        

        // add all elements to the min-heap

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

            pq.add(arr[i]);

        }

        

        int res = 0;

        

        // keep combining two smallest el.

        while(pq.size() > 1) 

        {

            int first = pq.poll(); // 1st smallest elements 

            int second = pq.poll(); // 2nd smallest elements

            

            res += first+second; // add their combined cost;

            

            int new_rope = first + second; // store the new rope

            

            pq.add(new_rope); // push the new rope back into the heap

        }

        

        // return total cost

        return res;

        

    }

    

    

    

    

public static void main(String[] args) {

int[] rope = {3, 2, 4, 6};

int n = rope.length;

System.out.println("Total cost for connecting ropes is " + minRopeCost(rope, n));

}

}


problems i faced:

1. Main.java:43: error: reached end of file while parsing } ^ 1 error

FIX: 
Make sure main , class and function braces are closed properly.

Wednesday, October 29, 2025

Self-practice-01: Check if arrays are matching or not in Java

 import java.util.*;


public class Main

{

    

    

    public static void ifMatch(int[] arr) {

        

        // Combine array with a predefined array

        int[] pattern = {4, 3, 2, 6};

        

        // Check if arrays have same length

        if(Arrays.equals(arr, pattern)) {

            System.out.println("Yes, Array is matching.");

        } else {

            System.out.println("No, Array isn't matching.");

        }

    }

    

    

    

public static void main(String[] args) {

int[] testArr = {4, 3, 2, 6};

System.out.print("Array 1: ");

ifMatch(testArr);

int[] testArr2 = {4, 3, 2, 9};

System.out.print("Array 2: ");

ifMatch(testArr2);

}

}

Friday, October 24, 2025

What is System.in and nextInt() ?

 Let’s break it down simply 👇

🧩 1. System.in

  • System is a built-in Java class that gives access to system-level input and output.

  • in is a static field inside the System class.

  • System.in represents standard input stream — usually the keyboard.

💡 In short:
System.in = the stream that takes input from the keyboard.


🧮 2. nextInt() (from Scanner class)

  • nextInt() is a method of the Scanner class.

  • It reads the next integer value from the input stream connected to the scanner.

Example:

import java.util.Scanner;

public class Example {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in); // connect scanner to keyboard input
        System.out.print("Enter a number: ");
        int num = sc.nextInt();              // reads an integer from user
        System.out.println("You entered: " + num);
        sc.close();
    }
}

🔍 Step-by-step of what happens:

  1. new Scanner(System.in) → connects the scanner to keyboard input.

  2. sc.nextInt() → waits for the user to type an integer and press Enter.

  3. It reads that integer and stores it in a variable (like num).


🧠 Summary Table

Expression Type Meaning
System.in Input Stream Takes input from keyboard
new Scanner(System.in) Scanner Object Reads input from user
nextInt() Method Reads the next integer value entered

Would you like me to also explain what happens internally (how Java converts the typed number to an integer)?

Saturday, October 18, 2025

Stack using Deque in java

 import java.util.*;


// Deque: Double-ended queue, allows insertion & removal from both ends , rear and front end.

// Dequeue(verb, action, method): To remove an element from the front of a queue.


public class Main

{

    static class Stack {

        Deque<Integer> deque = new LinkedList<>();

        

        

        public void push(int data) {

            deque.addLast(data);

        }

        

        

        public int pop() {

            return deque.removeLast();

        }

        

        public int peek() {

            return deque.getLast();

        }

    

    }

    

public static void main(String[] args) {

Stack s = new Stack();

s.push(1);

s.push(2);

s.push(3);

System.out.println("peek = " + s.peek());

    System.out.println(s.pop()); // 3 2 1 -> 3

    System.out.println(s.pop()); // 2 1 -> 2

    System.out.println(s.pop()); // 1 -> 1

}

}

Deque explaination with Java + (Difference between Deque v/s Dequeue!)

import java.util.*;


// Deque: Double-ended queue, allows insertion & removal from both ends , rear and front end.

// Dequeue(verb, action, method): To remove an element from the front of a queue.


public class Main

{

    

    

public static void main(String[] args) {

Deque<Integer> deque = new LinkedList<>();

deque.addFirst(1); // 1

deque.addFirst(2); // 2 1

deque.addLast(3); // 2 1 3

deque.addLast(4); // 2 1 3 4

System.out.println(deque); 

deque.removeFirst();

System.out.println(deque); // 1 3 4

System.out.println("first el = " + deque.getFirst());

System.out.println("last el = " + deque.getLast());

}

}

Thursday, October 16, 2025

Interleave two halves of a Queue(even Length) in Java

 import java.util.*;


public class Main

{

    public static void interLeave(Queue<Integer> q) {

        Queue<Integer> firstHalf = new LinkedList<>();

        int size = q.size(); // size must be constant, or there will be anomaly.

        

        

        for(int i=0; i<size/2;i++) {

            

            firstHalf.add(q.remove());

            

        }

        

        

        while(!firstHalf.isEmpty()) {

            q.add(firstHalf.remove());

            q.add(q.remove());

        }

    }

    

public static void main(String[] args) {

        Queue<Integer> q = new LinkedList<>();

        q.add(1);

        q.add(2);

        q.add(3);

        q.add(4);

        q.add(5);

        q.add(6);

        q.add(7);

        q.add(8);

        q.add(9);

        q.add(10);

        

        interLeave(q);

        // print Q

        while(!q.isEmpty()) {

            System.out.print(q.remove() + " ");

        }

}

}

Wednesday, October 15, 2025

first-non repeating letters in java

 import java.util.*;


public class Main

{

    public static void printNonRepeating(String str) {

        int freq[] = new int[26]; // 'a' - 'z'

        Queue<Character> q = new LinkedList<>();

        

        

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

            char ch = str.charAt(i);

            q.add(ch);

            freq[ch-'a']++;

            

            while(!q.isEmpty() && freq[q.peek()-'a'] > 1) {

                q.remove();

            }

            

            if(q.isEmpty()) {

                System.out.println(-1); }

                else {

                System.out.println(q.peek()+" ");

            }

        }

        

        System.out.println();

    }

    

    

public static void main(String[] args) {

        String str = "aabccxb";

        printNonRepeating(str);

}

}

Monday, October 13, 2025

Queue using 2 Stacks

 import java.util.*;


class Main {

    

    static class Stack {

        static Queue<Integer> q1 = new LinkedList<>();

        static Queue<Integer> q2 = new LinkedList<>();

        

        public boolean isEmpty() {

            return q1.isEmpty() && q2.isEmpty();

        }

        

        public void push(int data) {

            if(!q1.isEmpty()) {

                q1.add(data);

            } else if(!q2.isEmpty()) {

                q2.add(data);

            } else {

                q1.add(data);

            }

        }

        

        public int pop() {

            if(isEmpty()) {

                System.out.println("empty stack");

                return -1;

            }

            int top = -1;

            

            

            // case-1

            if(!q1.isEmpty()) {

                while(!q1.isEmpty()) {

                    top = q1.remove();

                    if(!q1.isEmpty()) {

                        break;

                    }

                    q2. add(top);

                } 

            } else {

                // case 2

                while(!q2.isEmpty()) {

                    top = q2.remove();

                    if(q2.isEmpty()) {

                        break;

                    }

                    q1.add(top);

                }

            }

            return top;

        }

        

        public int peek() {

            if(isEmpty()) {

                System.out.println("empty stack");

                return -1;

            }

            int top = -1;

            

            

            // case-1

            if(!q1.isEmpty()) {

                while(!q1.isEmpty()) {

                    top = q1.remove();

                    q2. add(top);

                } 

            } else {

                // case 2

                while(!q2.isEmpty()) {

                    top = q2.remove();

                    q1.add(top);

                }

            }

            return top;

        }

    }

    

    

    public static void main(String[] args) {

    Stack s = new Stack();

    s.push(1);

    s.push(2);

    s.push(3);

    

    while(!s.isEmpty()) {

        System.out.println(s.peek());

        s.pop();

    }

        

    }

}


OUTPUT:

3

2

1


=== Code Execution Successful ===

Sunday, October 12, 2025

Queue JCF

 import java.util.*;


public class Main {
    public static void main(String[] args) {
        // Queue q = new Queue();
        Queue<Integer> q = new LinkedList<>(); // or ArrayDeque, because we can't make a object using Queue, queue is an interface
        q.add(1);
        q.add(2);
        q.add(3);

        while(!q.isEmpty()) {
            System.out.println(q.peek());
            q.remove();
        }
    }
}

Friday, October 10, 2025

Queue using LinkedList -most optimized implementation)

 public class QueueB {


    static class Node {
        int data;
        Node next;

        Node(int data) {
            this.data = data;
            this.next = null;
        }
    }



    static class Queue {
       static Node head = null;
       static Node tail = null;




        public boolean isEmpty() {
            return head == null && tail == null;
        }


        // add
        public void add(int data) {
            Node newNode = new Node(data);
            if(head == null) {
                head = tail = newNode;
                return;
            }
            tail.next = newNode;
            tail = newNode;
        }

        // remove
        public int remove() {
            if (isEmpty()) {
                System.out.println("Queue is empty");
                return -1;
            }

            int front = head.data;
            // last element deleted
            if (tail == head) {
               tail = head = null;
            } else {
                head = head.next;
            }
            return front;
        }

        // peek
        public int peek() {
            if (isEmpty()) {
                System.out.println("Queue is empty");
                return -1;
            }

            return head.data;
        }
    }

    public static void main(String args[]) {
        Queue q = new Queue();
        q.add(1);
        q.add(2);
        q.add(3);
        // adding condition that works like a circular queue
        System.out.println(q.remove()); // prints 1
        q.add(4);
        System.out.println(q.remove()); // prints 2
        q.add(5);
        // queue now contains 3,4,5 in order

        while (!q.isEmpty()) {
            System.out.println(q.peek());
            q.remove();
        }
    }
}
output: 1
2
3
4
5

Circular Queue using Arrays

 public class QueueB {

    static class Queue {
        static int arr[];
        static int size;
        static int rear;
        static int front;

        Queue(int n) {
            arr = new int[n];
            size = n;
            rear = -1;
            front = -1;
        }

        public boolean isEmpty() {
            return rear == -1 && front == -1;
        }

        public boolean isFull() {
            return (rear + 1) % size == front;
        }

        // add
        public void add(int data) {
            if (isFull()) {
                System.out.println("Queue is full");
                return;
            }

            // add 1st element
            if (front == -1) {
                front = 0;
            }
            rear = (rear + 1) % size;
            arr[rear] = data;
        }

        // remove
        public int remove() {
            if (isEmpty()) {
                System.out.println("Queue is empty");
                return -1;
            }

            int result = arr[front];
            // last element deleted
            if (rear == front) {
                rear = front = -1;
            } else {
                front = (front + 1) % size;
            }
            return result;
        }

        // peek
        public int peek() {
            if (isEmpty()) {
                System.out.println("Queue is empty");
                return -1;
            }
            return arr[front];
        }
    }

    public static void main(String args[]) {
        Queue q = new Queue(3);
        q.add(1);
        q.add(2);
        q.add(3);
        // adding condition that works like a circular queue
        System.out.println(q.remove()); // prints 1
        q.add(4);
        System.out.println(q.remove()); // prints 2
        q.add(5);
        // queue now contains 3,4,5 in order

        while (!q.isEmpty()) {
            System.out.println(q.peek());
            q.remove();
        }
    }
} OUTPUT: 1 2
3
4
5

Queue using Arrays

 public class QueueB {

    static class Queue {
        static int arr[];
        static int size;
        static int rear;

        Queue(int n) {
            arr = new int[n];
            size = n;
            rear = -1;
        }


        public static boolean isEmpty() {
            return rear == -1;
        }



        // add
        public static void add(int data) {
            if(rear == size-1) {
                System.out.println("Queue is full");
                return;
            }

            rear = rear + 1;
            arr[rear] = data;
        }


        // remove
        public static int remove() {
            if(isEmpty()) {
                System.out.println("Quene is empty");
                return -1;
            }


            int front = arr[0];
            for(int i=0; i<rear ;i++) {
                arr[i] = arr[i+1];
            }

            rear = rear - 1;

            return front;
        }


        // peek
        public static int peek() {
            if(isEmpty()) {
                System.out.println("Queue is Empty");
                return -1;
            }

            return arr[0];
        }
    }

    public static void main(String args[]) {
        Queue q = new Queue(5);
        q.add(1);
        q.add(2);
        q.add(3);
        // 1 2 3
       
        while(!q.isEmpty()) {
            System.out.println(q.peek());
            q.remove();
        }
    }
} OUTPUT: 1 2
3

Tuesday, October 7, 2025

Trapping rainwater (stack problem) solved with Gemini Pro 2.5

 LINK TO CHAT:
https://g.co/gemini/share/320262b94bda

import java.util.Stack;


class Main {


    public static int trappingRainStack(int[] height) {

        if (height == null || height.length == 0) {

            return 0;

        }


        Stack<Integer> stack = new Stack<>();

        int ans = 0;

        int n = height.length;


        // Main loop to iterate through each bar

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

            

            // 1. Finding a container: This loop runs when the current bar is a "right wall"

            while (!stack.isEmpty() && height[stack.peek()] < height[i]) {


                // 2. Identifying parts of the container

                // i. The popped bar is the bottom of the container.

                int topIndex = stack.pop();

                int pop_height = height[topIndex];


                // If stack is empty, there is no left wall, so break.

                if (stack.isEmpty()) {

                    break;

                }

                

                // iii. The new top of the stack is the left wall.

                int left_wall_index = stack.peek();

                // ii. The current bar 'i' is the right wall.


                // 3. Calculating the Trapped Water 💧

                int width = i - left_wall_index - 1;

                int min_height = Math.min(height[left_wall_index], height[i]) - pop_height;


                ans += width * min_height;

            }

            

            // Push the current bar's index. It might be a future left wall.

            stack.push(i);

        }

        return ans;

    }


    public static void main(String[] args) {

        int[] arr = {0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1};

        int result = trappingRainStack(arr);

        System.out.println("The total trapped water is: " + result); // Output: 6

    }

}

Wednesday, October 1, 2025

For enhanced loop in Java .. explaination

 Ah! You want a clear explanation of the enhanced for-loop (for-each loop) in your code. Let’s go step by step.


Syntax:

for(Type variable : collection) {
    // use variable here
}
  • Type → data type of the elements in the collection/array

  • variable → temporary variable that holds the current element in each iteration

  • collection → array, List, or any iterable


Example in your code:

for(String comp : components) {
    // comp is the current string element from components array
}
  • components is a String[] array like {"home", ".", "user"}

  • The loop does:

Iteration comp
1 "home"
2 "."
3 "user"
  • On each iteration, comp takes the value of the next element in the array.


Another example:

String[] arr = {"a", "b", "c"};
for(String s : arr) {
    System.out.println(s);
}

Output:

a
b
c

Key points:

  1. You cannot modify the array structure (like adding/removing elements) inside an enhanced for-loop.

  2. It is simpler than the traditional for(int i=0; i<array.length; i++) loop.

  3. Great for iterating over arrays or collections when you just need the elements.


In your simplifyPath code:

for(String str1 : st) {
    sb.append("/").append(str1);
}
  • st is a stack of strings.

  • str1 takes each element of the stack in order (bottom → top).

  • You append / + str1 to the StringBuilder.


If you want, I can draw a small diagram showing how comp and str1 change in your simplifyPath example, which makes the enhanced for-loop super visual.

Do you want me to do that?

leetcode. 71: Simplify Path (Stacks question)

 class Solution {

    public String simplifyPath(String path) {
        String[] components = path.split("/");
        Stack<String> st = new Stack<>();

        for(String comp : components) {
            if(comp.equals(".") || comp.equals("")) {
                continue;
            }
            if(comp.equals("..")) {
                if(!st.isEmpty()) {
                    st.pop();
                }
            } else {
                st.push(comp);
            }
            }
            StringBuilder sb = new StringBuilder();
            for(String str1 : st) {// st will have stored everything
                sb.append("/").append(str1);
        }
        return sb.length() == 0 ? "/" : sb.toString();
        }
    }

What is a StringBuilder?

 - Mutable sequence of characters.

Unlike, String which is immutable (cannot be changed).

Benefits:

1. Allows you to append, insert or delete characters efficiently without creating a new object each time.

CODE:

public class Main {
    public static void main(String str[]) {
        StringBuilder sb = new StringBuilder();
        sb.append("Hello");
        sb.append(" World");

        System.out.println(sb.toString()); // Output: Hello World
    }
}

Contains duplicate - using HashSet (optimized code)

  class Solution {     public boolean containsDuplicate ( int [] nums) {         HashSet< Integer > seen = new HashSet<>()...