Posts

Showing posts with the label Algorithms

Intro to Hashing problems made easy

/*--- Below are 3 problems i have used hasing technique, After seeing below problems you'll be 100% clear on the basic hasing needed for competative programming First Repeating Element  Given an array arr[] of size N. The task is to find the first repeating element in an array of integers, i.e., an element that occurs more than once and whose index of first occurrence is smallest. Input : The first line contains an integer T denoting the total number of test cases. In each test cases, First line is number of elements in array N and second its values. Output: In each separate line print the index of first repeating element, if there is not any repeating element then print “-1” (without quotes). Use 1 Based Indexing. Constraints: 1 <= T <= 500 1 <= N <= 106 0 <= Ai <= 106 Example: Input: 1 7 1 5 3 4 3 5 6 Output: 2 Explanation: Testcase 1: 5 is appearing twice and its first appearence is at index 2 which is less than 3 whose first occur...

Never Two consecutive , Include Exclude technique

/* Stickler the thief wants to loot money from a society having n houses in a single line.  He is a weird person and follows a certain rule when looting the houses.  According to the rule, he will never loot two consecutive houses. At the same time,   he wants to maximize the amount he loots. The thief knows which house has what amount of money   but is unable to come up with an optimal looting strategy. He asks for your help to find the maximum money   he can get if he strictly follows the rule. Each house has a[i] amount of money present in it. */ #include<bits/stdc++.h> // this is clearly an consec include exclude problem using namespace std; int maxsumnotconsec(int a[], int n) {     int incl=a[0];     int exec=0;     for(int i=1;i<n;i++)     {         int inc_new=exec+a[i];         // we can incude the new element(latest ele) if and only if we have ex...

Queue Delete at middle in constant time (Only possible way is using doubly linked list)

#include<bits/stdc++.h> using namespace std; struct doublyqueue { int d; doublyqueue* next=NULL; doublyqueue* prev=NULL; }; doublyqueue *front=NULL; doublyqueue *rear=NULL; doublyqueue *mid=NULL; //  f->null r->null mid =null // f->1<-r mid=1 i.e when changed from even to odd by push mid updated // f->1>2><r mid =1 odd to ev no ch //f->1>2>3<r mid=2 i.e mid=mid->next when changed to odd and n!=1 // f->1>2>3<r  deque 1 i.e,( changed from odd to even) then no change in mid // f->2->3<r mid =2 deque again => only 1 ele and mid is 3 i.e mid=m->next if changed from even to odd  // deque => mid= 2 i.e mid= mid->prev i.e // now check for delete mid ex only  1 then mid=null //if 1 2 mid=1 and delmid=> mid=m->next; // if 1 2 3 mid= 2 del mid => mid=m->prev; // 1 2 3 4 m=2 del 2 => 1 3 4 mid = 3 i.e m->next; // i.e size reduced and if new size is odd =>...