Friday, August 30, 2013

find four elements in array whose sum equal to a given number X

This can be solved efficiently via using HashTables. We can have a hashtable sums sums will store all possible sums of two different elements. For each sum S it returns pair of indexes i and j such that a[i] + a[j] == S and i != j. But initially it's empty, we'll populate it on the way. So, this can be done in O(n^2) time. Pseudocode for (int i = 0; i < n; ++i) { // 'sums' hastable holds all possible sums a[k] + a[l] // where k and l are both less than i for (int j = i + 1; j < n; ++j) { int current = a[i] + a[j]; ...

Sunday, August 25, 2013

Balanced Binary Search Tree Index

Introduction to Balanced Binary Search Tree Red Black Tree Red Black Tree Red Black Tree - Insertions Red Black Tree - Deletions AVL Tree Introduction Insertion of element AVL Tree - Rotations Deletion of element Splay Trees Treap...

AVL Tree Index

Introduction Insertion of element AVL Tree - Rotations Deletion of elemen...

DFS (Depth first search) for graph

What is dfs?  This algorithm explores aggressively and backtracks only when necessary. This is similar to how we play a maze game. To code DFS iteratively, we can mimic BFS , but use a Stack instead of a Queue. Another way to code this would be to do it recursively. DFS is very naturally phased as recursive example. We will see both of implementation later. DFS(graph G, vertex s) mark s as explored for every edge (s, v): ...

Dijkstra's algorithm for equal weight edges using BFS

This is the application of BFS (breadth first search) dist(v) = fewest number of edges on path s to v. Here is the pseudocode: Initialize dist(v) = {0 if v=s, infinity if v != s} foreach vertex v in all vertices { if(v==s) dist(v) = 0; else dist(v) = infinity; } Now apply BFS, and hen considering edge (v, w), if w is unexplored, then set dist(w) = dist(v)+1, keeping rest of the BFS same. Note - BFS computes the shortest path,...

BFS (Breadth first search) on Graph

Algorithm Starting at some arbitrarily chosen vertex s (s stands for start vertex) , we mark v so that we know we've visited it, process v, and  then visit i.e. mark the vertex as visited and process all of v's neighbors.  Now that we've visited and processed all of v's neighbors,  we need to visit and process all of v's neighbors neighbors Pseudocode BFS(graph G, vertex s) [all nodes initially unexplored] -mark s as explored let...

Saturday, August 24, 2013

Deleting the element from the heap

Here we will discuss deletion of element from min heap. Pseudocode for deletion from heap Find the index of the element to be deleted from the heap. This takes O(n) time.(If you already have the index, please skip this step) Remove the element from the heap Move the root element to the element to be deleted location Move the last element to the first position Decrease array size by 1 Now bubble down on the array(like we did in extract min). Bubbling...

Application of heap (in computer science)

Following are applications of heap: Heap Sort - fast way to get minimum computationSelectionSort() with time complexity - Θ(n2) when uses heap data-structure is used as Heapsort, with time compexity nlogn. Heapsort has 2 steps1) Insert all n array elements in the heap O(n)2) Extract min to place elements in sorted order n * O(lg n)So, it is now close to quicksort. Priority QueueA heap can also be called a priority queue. It can be used to schedule events and to check which event is going to occur next, using the timestamp as key. This makes...

Building of heap

To be done soo...

Array Implementation of Heap

We have discussed a heap as binary tree. Normal implementation of tree is via pointer, but in heap it is much more efficient to use arrays. So, suppose we have following heap (having 9 elements) : Now, we need array of 9 elements. Now, we see the heap having 3 levels, level 0 as root, and level 3 which is partially filled. Now, we start putting the elements one by one. So, level 0 goes at first position, level 2 goes next and so on. You,...

Find Nth largest element in the rotated sorted array

Question : Find Nth largest element in the rotated sorted array So for example we have sorted array as  - 2,3,6,12, 15, 18. Now suppose the array is rotated k times ( we don't know k), such that array becomes 15, 18,2,3,6,12 Solution So, to find the Nth largest element in normal sorted array is a[N]. But in this case it is rotated k, which we don't know. But seeing the above array we cans see that k = 2, which is also the index of minimum element i.e. 2 here. So, 3rd largest element is counting 3rd from 2 i.e....

Find the rotation count in rotated sorted array

Question : Find the minimum element in the rotated sorted array. So for example we have sorted array as  - 2,3,6,12, 15, 18. Now suppose the array is rotated k times ( we don't know k), such that array becomes 15, 18,2,3,6,12 Solution This can be solved in linear time and logarithmic time. If we notice the above array, we see the array has been rotated 2 times, which is also the index of smallest element in the array. So, we need to find the point of inflection where we find a point such that a[i]>a[i+1]. So, finding...

Random Contraction Algorithm

This algorithm was designed by Karger in 1990, as phd student at stanford. This algorithm is used to solve the min cut problem, which is : Input - An undirected graph G = (V,E) ,  (note that parallel edges are allowed) Goal - Tom compute a cut with fewest number of crossing edges (a min cut) Karger's Algorithm We will have just one mail loop, and algorithm terminates when only 2 vertices are remaining. This algorithm showed that random...

Graph Representations

We have already discussed what are graphs here. Now graph can be represented in 2ways: Adjacency matrix  Adjacency list Adjacency Matrix Undirected graph Represent G by a nXn, n being number of vertices 0-1 matrix A, where Aij = 1 for every edge between 2 nodes. Undirected graph with parallel edges Aij = b*1 where b is number of parallel edges between i and j. Weighted Undirected graph Aij = w for every edge between 2 nodes with weight w Directed graph Aij = +1 if edge goes from node i to j, similarly for edge from j to i, it is -1. Space...

Thursday, August 22, 2013

Cuts of Graphs

A cut of a graph (V, E) is a partition of a graph into two non-empty sets A and B. Each set contains only the vertices that connect one vertex in the set to another in the set. Meanwhile, there are also edges connecting the vertices from set A to set B and vice versa. For eg. Similarly we have directed graph. Edges, that cross from A, to B are called are crossing edges. In a graph with n nodes, you can either put them in set A, or set B....

Wednesday, August 14, 2013

Integer Multiplication using Karatsuba algorithm

Normal Integer method If we consider the integer multiplication, we need 2 integers and output is also integer. Suppose we have to multiply 5678*1234. In the normal way, we will realize following: 5678 X 1234 ------------ 22712 //first number multiply as is i.e. 4*5678 17034- //2nd time, shift (left) and then multiply the number as 3*5678 11356-- //shift twice 5678--- //shift thrice ------------ 7006652 So, each time we multiply, depending on the digit of the 2nd number, we shift and then multiply. Now, lets compute its...

Tuesday, August 13, 2013

Red Black Tree Index

Red Black Tree Red Black Tree - Insertions Red Black Tree - Deletio...

Sunday, August 11, 2013

Data Type in Data Structure

               Before discussing data type in data structure, i am going to describe data, basis of categorization of these data, and advanced categories of data.  DATA :- Data can be defined as a value or set of values. These values may represent some observations from an experiment, some figures collected during some surveys, marks obtained by a student in an examination,...

Pathological Data Sets and Universal Hashing Motivation

We will go deep inside hash function, where we will find every hash table has its Kryptonite, i.e some pathological data set, which will make it vulnerable. Note:To continue on this article, please first read the article - Hash Tables. The Load factor or Load of a hash table It tells us how populated the hash table is.It is denoted by alpha (α) α = (number of objects in the hash table) / (number of buckets in the hash table) The load of a hash table is the total number of elements in the hash table divided by total amount of space in the table....

Saturday, August 10, 2013

Hash Tables

A hash table is primarily used to keep track of an evolving set of stuff by using a key. It is good for inserting, deleting, and lookups. It is also sometimes referred to as a "dictionary." They are similar to array in a way, that array gives information at the index very fast, if you know the index. Suppose, your friend names are integer, and you save the number in the array. If you need phone number of your friend 173, you can get it as array[173]....

Given a dictionary of word - Group all words into set of anagrams of each other

Given a set of words in a dictionary, write a program to group all words which are anagrams of each other in to sets. input: “bat”, “tar”, “xyz” , “tab”, “tar”      output:[["bat", tab"], ["tar", rat"],”xyz” ] Anagrams Two words are anagrams if one of them has exactly same characters as that of the another word. Example : Anagram & Nagaram are anagrams (case-insensitive). Approach The simpler logic would be to : Use some sort of a hash structure - key being string, and value may be list of words Sort all words...

Friday, August 9, 2013

Splay trees

http://en.wikipedia.org/wiki/Splay_tree http://www.youtube.com/watch?v=G5QIXywcJl...

Boyer Moore Algorithm

http://dev-faqs.blogspot.in/2010/05/boyer-moore-algorithm.htm...

Sorting

What is a sorting algorithm ? A sorting algorithm is an algorithm that sorts the data into some order, say from ascending to descending. The sorting problem Input: Array of numbers , unsorted. Eg. Output : Same numbers sorted in some order, say increasing order. Eg. Classification of sorting algorithms Sorting algorithm can be classified in various ways. Comparison sorts vs non comparison sorts Various sorts Bubble sorting Selection...

Tower of Hanoi Problem

There are 3 pegs source ,auxillary and target. n disks of different sizes are given which can slide onto any peg . In the beginning all of the disks are in the source peg in the order of size with largest disk at the bottom and smallest disk at the top. We have to move all the disks from source peg to target peg such that in the end the target peg will have all the disks in the same order of size. Rules: Only one disk can be moved from one...

Thursday, August 8, 2013

Implementing doubly linked list using single pointer

http://chanduthedev.blogspot.in/2012/10/implementing-doubly-linked-list-using-single-pointer.html http://chanduthedev.blogspot.in/2012/10/double-linked-list-using-single-pointer.ht...

Rearranging linked list first odd next even numbers

Here is the implemenation in cpp http://chanduthedev.blogspot.in/2012/11/c-program-rearrange-linkedlist-first-odd-next-even-elements.ht...

Wednesday, August 7, 2013

GetMin and GetMax in BST

...

Binary tree - Types and Properties

Tree is sometimes binary tree (BT) and sometimes binary search tree(BST). BT has maximum of 2 child nodes. Binary Search Tree or Ordered tree(sometimes) is BT such that left child has value less than the parent and right child has value greater than parent. Strictly binary tree - If every non-leaf node in BT has non empty left and right subtrees.     A    / \   B   C      /   \     D    E    / \   F    G Complete...

Linear Search on Array

References http://www.durofy.com/computing/linear-search-in-...

Tuesday, August 6, 2013

Randomized Algorithm

...

Bellman ford algorithm - One source shortest path

http://compprog.wordpress.com/2007/11/29/one-source-shortest-path-the-bellman-ford-algorithm/ http://shriphani.com/blog/2010/07/02/bellman-ford-algorithms-applications-triangular-arbitrage...

Sunday, August 4, 2013

Strongly Connected Graph

A strongly connected graph is a graph such that there is a path connecting each vertex in the graph to another vertex in the graph. The strongly connected components (SCCs) of a directed graph G are the equivalence classes of the relation: u~v <-> path u->v AND path v->u.  The ~ relation is an equivalence class, that is, ~ is reflexive, symmetric, and transitive. (Reflexive => everybody is related to itself, symmetric =>...