Posts

Showing posts with the label DS

TWO SUM

Given an array of integers   nums  and an integer   target , return   indices of the two numbers such that they add up to  target . You may assume that each input would have  exactly  one solution , and you may not use the  same  element twice. You can return the answer in any order. Example 1: Input: nums = [2,7,11,15], target = 9 Output: [0,1] Explanation: Because nums[0] + nums[1] == 9, we return [0, 1]. Example 2: Input: nums = [3,2,4], target = 6 Output: [1,2] Example 3: Input: nums = [3,3], target = 6 Output: [0,1]   Constraints: 2 <= nums.length <= 10 4 -10 9  <= nums[i] <= 10 9 -10 9  <= target <= 10 9 Only one valid answer exists. Solution 1: HashMap We need to find 2 numbers  a ,  b  so that  a + b = target . We need a HashMap datastructure to store elements in the past, let name it  seen . The idea is that we iterate  b  as each element in  nums , we ch...

Sliding Window Algorithm

Image
The main idea behind the sliding window technique is to convert two nested loops into a single loop. Usually, the technique helps us to reduce the time complexity from O(n^2) to O(n). The condition to use the sliding window technique is that the problem asks to find the maximum (or minimum) value for a function that calculates the answer repeatedly for a set of ranges from the array. Namely, if these ranges can be sorted based on their start, and their end becomes sorted as well, then we can use the sliding window technique. Let’s start with a problem for illustration where we can apply this technique –  Given an array of integers of size ‘n’. Our aim is to calculate the maximum sum of ‘k’  consecutive elements in the array. Input  : arr[] = {100, 200, 300, 400}          k = 2  Output : 700 Input  : arr[] = {1, 4, 2, 10, 23, 3, 1, 0, 20}          k = 4 Output : 39 We get maximum sum by adding subarray {4, 2, 10, ...

Largest Pair Sum

Iterate the list and store the max element in J and add with the elements in the list to check if it greater than SUM. public class LargestPairSum { public static void main(String args[]) { int arr[] = {- 1 , 3 , 5 , - 6 , 8 , - 9 , 10 , 4 , - 2 , 7 }; largestPairSum (arr, arr. length ); } private static int largestPairSum( int [] arr, int n) { int j = 0 ; int max = n == 1 ? arr[ 0 ] + arr[ 1 ] : arr[ 0 ]; for ( int i = 0 ; i < n; i++) { int sum = arr[j] + arr[i]; if (sum > max) { max = sum; if (arr[j] < arr[i]) { j = i; } } } System. out .println( "Max--" + max); return max; } }

Find second largest pair

 First find 3 largest numbers and the sum of first and third integer is the 2nd largest number. The size of Array should be greater than 3. public class FindSecondLargestPair {     public static void main(String args[]) {         int[] nums = {-1, 3, 5, -6, 8, -9, 10, 4, -2, 7};         secondLargestPair(nums, nums.length);     }     public static void secondLargestPair (int[] arr, int arr_size) {         int i, first, second, third;         /* There should be atleast three elements */         if (arr_size < 3)         {             System.out.print(" Invalid Input ");             return;         }         third = first = second = Integer.MIN_VALUE;         for (i = 0; i < arr_size ; i ++)       ...

Find Permutations of a string

Image
 Example ABC -> [ABC, ACB, BAC, BCA, CBA, CAB] public class FindPermutations {     // COmplexity     // O(TIme to find one permutation * Number of permutations)     // O(n*n!)     public static void main(String args[]) {         permutate("abc", 0, 2);     }     public static void permutate(String s, int low, int high) {         if (low == high) {             System.out.println(s);             return;         }         for (int i = low; i <= high; i++) {             s = swap(s, low, i);             permutate(s, low + 1, high);             s = swap(s, low, i); //Back track to the previous string to get other permutations.Just similar of first step         }     }...

Array Containing Duplicates

public class ArrayContainsDuplicate {     public static void main(String args[])     {         int[] nums = {1,2,3,1};         boolean returnValue = containsDuplicate(nums);         System.out.println("returnValue-->"+returnValue);     }     public static boolean containsDuplicate(int[] nums) {         if(nums.length==1) return false;         HashSet<Integer> hashSet = new HashSet<>();         for(int i =0; i<nums.length;i++)         {             if(!hashSet.add(nums[i]))return true;         }         return false;     } }

Find Loop in a Linked List

Image
 Problem Statement In this problem, we are given a linked list with a loop. We have to find the first node of the loop in the linked list. Problem Statement Understanding Let’s try to understand the problem statement with the help of examples. Suppose the given list is: According to the problem statement, we need to find the starting node of the loop. From the linked list, we can see that there is a loop in the linked list starting at node with value 3 and containing 3 nodes 3, 5, and 7. The last node of the loop points back to the first node of the loop. As node with value 3 is the first node of the loop, so we will return 3 as output. Approach and Algorithm (Floyd’s Cycle Detection) Our approach will be simple: 1) Firstly, we have to detect the loop in the given linked list. For detecting a loop in any linked list, we know the most efficient algorithm is the  Floyd Cycle detection Algorithm . 2) In Floyd's cycle detection algorithm, we initialize 2 pointers,  slow ...

Implement Stack using 2 Queues

Costly Push Operation  public class StackUsingTwoQueues { Queue<Integer> queue1 = new LinkedList<>(); Queue<Integer> queue2 = new LinkedList<>(); public void push(Integer element) { if (element== null ) { return ; } while (! queue1 .isEmpty()) { queue2 .add( queue1 .poll()); } queue1 .add(element); while (! queue2 .isEmpty()) { queue1 .add( queue2 .poll()); } } public int pop() { return queue1 .poll(); } public static void main(String args[]) { StackUsingTwoQueues stackUsingTwoQueus = new StackUsingTwoQueues(); stackUsingTwoQueus.push( 1 ); stackUsingTwoQueus.push( 2 ); stackUsingTwoQueus.push( 3 ); stackUsingTwoQueus.push( 4 ); stackUsingTwoQueus.push( 5 ); System. out .println(stackUsingTwoQueus.pop()); System. out .println(stackUsi...

Implement Stack using LinkedList

 Logic - Have a top node in the starting. Insert element in Linked List at the start so latest element will be present at the top. When we have to remove, remove the element from the top LIFO (Last In First Out). public class StackUsingLinkedList { private class Node { Integer data ; Node next ; } Node top ; public StackUsingLinkedList() { top = null ; } public void push(Integer element) { Node temp = new Node(); temp. data = element; temp. next = top ; top = temp; } public void pop() { if ( top == null ) { System. out .println( "Stack Underflow" ); } if ( top != null ) { top = top . next ; } } public int peek() { // check for empty stack if ( top != null ) { return top . data ; } else { System. out .println( "Stack is empty" ); return - 1 ; } } ...

Knapsack Problem

The Knapsack Problem is a famous Dynamic Programming Problem that falls in the optimization category. It derives its name from a scenario where, given a set of items with specific weights and assigned values, the goal is to maximize the value in a knapsack while remaining within the weight constraint. Each item can only be selected once, as we don’t have multiple quantities of any item. In the below example, the weights of different honeycombs and the values associated with them are provided. The goal is to maximize the value of honey that can be fit in the bear’s knapsack. Example Let’s take the example of Mary, who wants to carry some fruits in her knapsack and maximize the profit she makes. She should pick them such that she minimizes weight ( <= bag's capacity) and maximizes value. Here are the weights and profits associated with the different fruits: Items: { Apple, Orange, Banana, Melon } Weights: { 2, 3, 1, 4 } Profits: { 4, 5, 3, 7 } Knapsack Capacity: 5 Fruits Picked by...