Posts

Showing posts from February, 2025

Middle Of LinkedList problem LeetCode

Image
 Given the head of a singly linked list, return the middle node of the linked list. If there are two middle nodes, return the second middle node.   Example 1: Input: head = [1,2,3,4,5] Output: [3,4,5] Explanation: The middle node of the list is node 3. Example 2: Input: head = [1,2,3,4,5,6] Output: [4,5,6] Explanation: Since the list has two middle nodes with values 3 and 4, we return the second one.   Constraints: The number of nodes in the list is in the range [1, 100]. 1 <= Node.val <= 100 Solution : method 1: /**  * Definition for singly-linked list.  * public class ListNode {  *     int val;  *     ListNode next;  *     ListNode() {}  *     ListNode(int val) { this.val = val; }  *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }  * }  */ class Solution {     public ListNode middleNode ( ListNode head ) {       ...

Reverse a Linked List problem LeetCode

Image
 Given the head of a singly linked list, reverse the list, and return the reversed list.   Example 1: Input: head = [1,2,3,4,5] Output: [5,4,3,2,1] Example 2: Solution : /**  * Definition for singly-linked list.  * public class ListNode {  *     int val;  *     ListNode next;  *     ListNode() {}  *     ListNode(int val) { this.val = val; }  *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }  * }  */ class Solution {     public ListNode reverseList ( ListNode head ) {         ListNode previous = null ; ListNode current =head; ListNode next = null ; while (current != null ) {     next= current . next ;     current . next =previous;     previous=current;     current=next; } return previous;     } }

Reverse a Linked List Problem HackerRank

 Given the pointer to the head node of a linked list, change the next pointers of the nodes so that their order is reversed. The head pointer given may be null meaning that the initial list is empty. Example  references the list  Manipulate the  pointers of each node in place and return , now referencing the head of the list . Function Description Complete the reverse function in the editor below. reverse has the following parameter: SinglyLinkedListNode pointer head: a reference to the head of a list Returns SinglyLinkedListNode pointer: a reference to the head of the reversed list Input Format The first line contains an integer , the number of test cases. Each test case has the following format: The first line contains an integer , the number of elements in the linked list. Each of the next  lines contains an integer, the  values of the elements in the linked list. Constraints , where  is the  element in the list. Sample Input 1 5 1 2 3 4 5 Samp...

Insert A Node at Specific position in linkedList Problem HackerRank

 Given the pointer to the head node of a linked list and an integer to insert at a certain position, create a new node with the given integer as its  attribute, insert this node at the desired position and return the head node. A position of 0 indicates head, a position of 1 indicates one node away from the head and so on. The head pointer given may be null meaning that the initial list is empty. Example  refers to the first node in the list  Insert a node at position  with . The new list is  Function Description Complete the function insertNodeAtPosition in the editor below. It must return a reference to the head node of your finished list. insertNodeAtPosition has the following parameters: head: a SinglyLinkedListNode pointer to the head of the list data: an integer value to insert as data in your new node position: an integer position to insert the new node, zero based indexing Returns SinglyLinkedListNode pointer: a reference to the head of the revised ...

Count Linked List Node problem GFG

Given a singly linked list. The task is to find the length of the linked list, where length is defined as the number of nodes in the linked list. Examples : Input: LinkedList : 1->2->3->4->5 Output: 5 Explanation: Count of nodes in the linked list is 5, which is its length. Input: LinkedList : 2->4->6->7->5->1->0   Output: 7 Explanation: Count of nodes in the linked list is 7. Hence, the output is 7. Expected Time Complexity: O(n) Expected Auxilliary Space: O(1) Solution : //{ Driver Code Starts import java.io.*; import java.util.*; class Node {     int data;     Node next;     Node(int a) {         data = a;         next = null;     } } // } Driver Code Ends /*Complete the function below*/ /* class Node{     int data;     Node next;     Node(int a){  data = a; next = null; } }*/ class Solution {     // Function to count nodes of...

Search In Linked List problem GFG

 Given a linked list of n nodes and a key, the task is to check if the key is present in the linked list or not. Example: Input: n = 4, key = 3 1->2->3->4 Output: true Explanation: 3 is present in Linked List, so the function returns true. //{ Driver Code Starts // Initial Template for Java import java.io.*; import java.util.*; class Node {     int data;     Node next;     Node(int x) {         data = x;         next = null;     } } class GFG {     public static void main(String args[]) throws IOException {         Scanner sc = new Scanner(System.in);         int t = sc.nextInt();         while (t > 0) {             int n = sc.nextInt();             Node head = new Node(sc.nextInt());             Node tail = head;      ...

Linked List Insertion At End - GFG Problem

 Given the head of a Singly Linked List and a value x, insert that value x at the end of the LinkedList and return the modified Linked List. Examples : Input: LinkedList: 1->2->3->4->5 , x = 6 Output: 1->2->3->4->5->6 Explanation:  We can see that 6 is inserted at the end of the linkedlist. Input: LinkedList: 5->4 , x = 1 Output: 5->4->1 Explanation:  We can see that 1 is inserted at the end of the linkedlist. Expected Time Complexity: O(n) Expected Auxiliary Space: O(1) Solution : //{ Driver Code Starts // Initial Template for Java import java.io.*; import java.util.*; class Node {     int data;     Node next;     Node(int x) {         data = x;         next = null;     } } // } Driver Code Ends /* class Node{     int data;     Node next;     Node(int x){         data = x;         next = ...

Recursive Digit Sum problem hackerRank

 We define super digit of an integer  using the following rules: Given an integer, we need to find the super digit of the integer. If  has only  digit, then its super digit is . Otherwise, the super digit of  is equal to the super digit of the sum of the digits of . For example, the super digit of  will be calculated as: super_digit(9875)    9+8+7+5 = 29  super_digit(29) 2 + 9 = 11 super_digit(11) 1 + 1 = 2 super_digit(2) = 2   Example The number  is created by concatenating the string   times so the initial .     superDigit(p) = superDigit(9875987598759875)                   9+8+7+5+9+8+7+5+9+8+7+5+9+8+7+5 = 116     superDigit(p) = superDigit(116)                   1+1+6 = 8     superDigit(p) = superDigit(8) All of the digits of  sum to . The digits of  sum to .  is ...

Counter Game problem HackRank

 Louise and Richard have developed a numbers game. They pick a number and check to see if it is a power of . If it is, they divide it by . If not, they reduce it by the next lower number which is a power of . Whoever reduces the number to  wins the game. Louise always starts. Given an initial value, determine who wins the game. Example It's Louise's turn first. She determines that  is not a power of . The next lower power of  is , so she subtracts that from  and passes  to Richard.  is a power of , so Richard divides it by  and passes  to Louise. Likewise,  is a power so she divides it by  and reaches . She wins the game. Update If they initially set counter to , Richard wins. Louise cannot make a move so she loses. Function Description Complete the counterGame function in the editor below. counterGame has the following parameter(s): int n: the initial game counter value Returns string: either Richard or Louise Input Format The firs...

What is Aspect-Oriented Programming (AOP)?

   What is Aspect-Oriented Programming (AOP)? Aspect-Oriented Programming (AOP) is a way to separate common tasks like logging, security, and transaction management from the main code. It works alongside Object-Oriented Programming (OOP) to keep the code clean and organized by handling these tasks separately in "aspects." Problem: Suppose in a class there are  5 methods starting with a, 2 with b, and 3 with c. Let’s say our client wants to send a notification after executing all methods that start with ‘a’. Solution: a) Without AOP: To send a notification after each method we need to write a logic inside each method or a separate method and then invoke that method at the end. But this seems so hectic as we’ll have to modify the code which is not feasible in every case. What if tomorrow our client says not to send the notification then, in that case, we need to remove the code. b) With AOP: We can create advice that sends the notification after each method execution. And t...

Triplet Sum in Array Problem GFG

 Given an array arr[] and an integer target, determine if there exists a triplet in the array whose sum equals the given target. Return true if such a triplet exists, otherwise, return false. Examples Input: arr[] = [1, 4, 45, 6, 10, 8], target = 13  Output: true  Explanation: The triplet {1, 4, 8} sums up to 13 Input: arr[] = [1, 2, 4, 3, 6, 7], target = 10  Output: true  Explanation: The triplets {1, 3, 6} and {1, 2, 7} both sum to 10.  Input: arr[] = [40, 20, 10, 3, 6, 7], target = 24  Output: false  Explanation: No triplet in the array sums to 24 Constraints: 3 ≤ arr.size() ≤ 103 1 ≤ arr[i] ≤ 105 Approach 1 //{ Driver Code Starts import java.io.*; import java.util.*; class Main {     public static void main(String args[]) throws IOException {         BufferedReader read = new BufferedReader(new InputStreamReader(System.in));         int t = Integer.parseInt(read.readLine().trim()); // Read numb...

3 Sum Problem LeetCode

 Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0. Notice that the solution set must not contain duplicate triplets.   Example 1: Input: nums = [-1,0,1,2,-1,-4] Output: [[-1,-1,2],[-1,0,1]] Explanation:  nums[0] + nums[1] + nums[2] = (-1) + 0 + 1 = 0. nums[1] + nums[2] + nums[4] = 0 + 1 + (-1) = 0. nums[0] + nums[3] + nums[4] = (-1) + 2 + (-1) = 0. The distinct triplets are [-1,0,1] and [-1,-1,2]. Notice that the order of the output and the order of the triplets does not matter. Example 2: Input: nums = [0,1,1] Output: [] Explanation: The only possible triplet does not sum up to 0. Example 3: Input: nums = [0,0,0] Output: [[0,0,0]] Explanation: The only possible triplet sums up to 0. Good Approach class Solution {     public List < List < Integer >> threeSum ( int [] nums ) {           List < List < Integer >...

Trapping rain Water problem leetCode

Image
 Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining. Example 1: Input: height = [0,1,0,2,1,0,1,3,2,1,2,1] Output: 6 Explanation: The above elevation map (black section) is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. Example 2: Input: height = [4,2,0,3,2,5] Output: 9 class Solution {     public int trap ( int [] height ) {         if (height == null || height . length == 0 ) return 0 ;         int n = height . length ;         int [] leftMax = new int [n];         int [] rightMax = new int [n];         int water = 0 ;         // Fill leftMax array         leftMax[ 0 ] = height[ 0 ];         for ( int i = 1 ; i < n; i++) {   ...

Permutation Of Array problem leetCode

 Given an array nums of distinct integers, return all the possible  permutations . You can return the answer in any order. Example 1: Input: nums = [1,2,3] Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]] Example 2: Input: nums = [0,1] Output: [[0,1],[1,0]] Example 3: Input: nums = [1] Output: [[1]]   class Solution {     public List < List < Integer >> permute ( int [] nums ) {         List < List < Integer >> result = new ArrayList <>();         generatePermutations (nums, 0 , result);         return result;     }     private void generatePermutations ( int [] nums , int start , List < List < Integer >> result ) {         if (start == nums . length ) {             result . add ( convertToList (nums)); // Convert array to list and add to result         ...