The Wayback Machine - https://web.archive.org/web/20140914080635/http://www.geeksforgeeks.org:80/fundamentals-of-algorithms/

GeeksforGeeks

A computer science portal for geeks

GeeksQuiz

Login

Algorithms

Analysis of Algorithms: Asymptotic AnalysisWorst, Average and Best CasesAsymptotic Notations,  Analysis of LoopsSolving Recurrences, What does ‘Space Complexity’ mean?,   NP-Completeness IntroductionA Time Complexity QuestionTime Complexity of building a heap, Quiz on Analysis of Algorithms, Quiz on Recurrences

Searching and Sorting: Binary Search, Selection Sort,  Bubble Sort, Insertion SortMerge SortHeap SortQuickSort, Bucket Sort, ShellSort, Interpolation search vs Binary search,  Stability in sorting algorithmsWhen does the worst case of Quicksort occur?Lower bound for comparison based sorting algorithmsWhich sorting algorithm makes minimum number of memory writes?,  Find the Minimum length Unsorted Subarray, sorting which makes the complete array sorted,  Merge Sort for Linked Lists, Sort a nearly sorted (or K sorted) array,  Iterative Quick Sort, QuickSort on Singly Linked List, QuickSort on Doubly Linked List, Find k closest elements to a given value, Sort n numbers in range from 0 to n^2 – 1 in linear timeA Problem in Many Binary Search Implementations, Search in an almost sorted array, Quiz on Sorting, Quiz on Searching

Greedy Algorithms: Activity Selection Problem, Kruskal’s Minimum Spanning Tree Algorithm, Huffman Coding, Efficient Huffman Coding for Sorted Input, Prim’s Minimum Spanning Tree Algorithm, Prim’s MST for Adjacency List Representation, Dijkstra’s Shortest Path Algorithm, Dijkstra’s Algorithm for Adjacency List Representation, Quiz on Greedy Algorithms

Dynamic Programming: Overlapping Subproblems Property, Optimal Substructure Property, Longest Increasing Subsequence, Longest Common Subsequence, Edit Distance, Min Cost Path, Coin Change, Matrix Chain Multiplication, Binomial Coefficient, 0-1 Knapsack Problem, Egg Dropping Puzzle, Longest Palindromic Subsequence, Cutting a Rod, Maximum Sum Increasing Subsequence, Longest Bitonic Subsequence, Floyd Warshall Algorithm, Palindrome Partitioning, Partition problem, Word Wrap Problem, Maximum Length Chain of Pairs, Variations of LIS, Box Stacking Problem, Program for Fibonacci numbers, Minimum number of jumps to reach end, Maximum size square sub-matrix with all 1s, Ugly Numbers, Largest Sum Contiguous Subarray, Longest Palindromic Substring, Bellman–Ford Algorithm for Shortest Paths, Optimal Binary Search Tree, Largest Independent Set Problem, Subset Sum Problem, Maximum sum rectangle in a 2D matrix, Count number of binary strings without consecutive 1?sBoolean Parenthesization Problem,  Count ways to reach the n’th stair.  See Dynamic Programming Tag for more problems, Quiz on Dynamic Programming

Pattern Searching: Naive Pattern Searching, KMP Algorithm, Rabin-Karp Algorithm, A Naive Pattern Searching Question, Finite Automata, Efficient Construction of Finite Automata, Boyer Moore Algorithm – Bad Character Heuristic, Suffix Array, Anagram Substring Search (Or Search for all permutations)

BacktrackingPrint all permutations of a given string, The Knight’s tour problem, Rat in a Maze, N Queen Problem, Subset Sum, m Coloring Problem, Hamiltonian Cycle, SudokuTug of War,  Solving Cryptarithmetic Puzzles

Divide and ConquerIntroduction, Write your own pow(x, n) to calculate x*n, Median of two sorted arrays, Count Inversions , Closest Pair of Points, Strassen’s Matrix Multiplication, See this for more, Quiz on Divide and Conquer

Geometric Algorithms:Closest Pair of Points | O(nlogn) ImplementationHow to check if two given line segments intersect?How to check if a given point lies inside or outside a polygon?Convex Hull | Set 1 (Jarvis’s Algorithm or Wrapping)Convex Hull | Set 2 (Graham Scan)Given n line segments, find if any two segments intersect, Check whether a given point lies inside a triangle or not

Mathematical Algorithms: Write an Efficient Method to Check if a Number is Multiple of 3,   Efficient way to multiply with 7,   Write a C program to print all permutations of a given string,   Lucky Numbers,   Write a program to add two numbers in base 14,   Babylonian method for square root,   Multiply two integers without using multiplication, division and bitwise operators, and no loops,   Print all combinations of points that can compose a given number,   Write you own Power without using multiplication(*) and division(/) operators,   Program for Fibonacci numbers,   Average of a stream of numbers,   Count numbers that don’t contain 3,   Magic Square,   Sieve of Eratosthenes,   Find day of the week for a given date,   DFA based division,   Generate integer from 1 to 7 with equal probability,   Given a number, find the next smallest palindrome,   Make a fair coin from a biased coin,   Check divisibility by 7,   Find the largest multiple of 3,   Lexicographic rank of a string,   Print all permutations in sorted (lexicographic) order,   Shuffle a given array,   Space and time efficient Binomial Coefficient,   Reservoir Sampling,   Pascal’s Triangle,   Select a random number from stream, with O(1) space,   Find the largest multiple of 2, 3 and 5,   Efficient program to calculate e^x,   Measure one litre using two vessels and infinite water supply,   Efficient program to print all prime factors of a given number,   Print all possible combinations of r elements in a given array of size n,   Random number generator in arbitrary probability distribution fashion,   How to check if a given number is Fibonacci number?,   Russian Peasant Multiplication  Count all possible groups of size 2 or 3 that have sum as multiple of 3, Tower of Hanoi, Horner’s Method for Polynomial Evaluation, Count trailing zeroes in factorial of a number, Program for nth Catalan NumberGenerate one of 3 numbers according to given probabilities, Find Excel column name from a given column number,Find next greater number with same set of digits,Count Possible Decodings of a given Digit Sequence, Calculate the angle between hour hand and minute handCount number of binary strings without consecutive 1?s, Find the smallest number whose digits multiply to a given number n, Draw a circle without floating point arithmetic,

Bit Algorithms: Find the element that appears once, Detect opposite signs, Set bits in all numbers from 1 to n, Swap bits, Add two numbers, Smallest of three, A Boolean Array Puzzle, Set bits in an (big) array, Next higher number with same number of set bits, Optimization Technique (Modulus), Add 1 to a number, Multiply with 3.5, Turn off the rightmost set bit, Check for Power of 4, Absolute value (abs) without branching, Modulus division by a power-of-2-number, Minimum or Maximum of two integers , Rotate bits, Find the two non-repeating elements in an array, Number Occurring Odd Number of Times, Check for Integer Overflow, Little and Big Endian , Reverse Bits of a Number, Count set bits in an integer, Number of bits to be flipped to convert A to B, Next Power of 2, Check if a Number is Multiple of 3, Find parity, Multiply with 7, Find whether a no is power of two, Position of rightmost set bit, Binary representation of a given number, Swap all odd and even bits, Find position of the only set bit, Karatsuba algorithm for fast multiplication, How to swap two numbers without using a temporary variable?, Check if a number is multiple of 9 using bitwise operators, Swap two nibbles in a byte, How to turn off a particular bit in a number?, Check if binary representation of a number is palindrome

Quiz on Bit Algorithms.

Graph Algorithms:
Introduction, DFS and BFS:Graph and its representations, Breadth First Traversal for a Graph, Depth First Traversal for a Graph, Applications of Depth First Search, Detect Cycle in a Directed Graph, Detect Cycle in a an Undirected Graph, Detect cycle in an undirected graph, Longest Path in a Directed Acyclic Graph, Topological Sorting, Check whether a given graph is Bipartite or not
Minimum Spanning Tree:Prim’s Minimum Spanning Tree (MST)), Applications of Minimum Spanning Tree Problem, Prim’s MST for Adjacency List Representation, Kruskal’s Minimum Spanning Tree Algorithm
Shortest Paths:Dijkstra’s shortest path algorithm, Dijkstra’s Algorithm for Adjacency List Representation, Bellman–Ford Algorithm, Floyd Warshall Algorithm, Johnson’s algorithm for All-pairs shortest paths, Shortest Path in Directed Acyclic Graph, Some interesting shortest path questions
Connectivity:Find if there is a path between two vertices in a directed graph, Connectivity in a directed graph, Articulation Points (or Cut Vertices) in a Graph, Biconnected graph, Bridges in a graph, Eulerian path and circuit, Fleury’s Algorithm for printing Eulerian Path or Circuit, Strongly Connected Components, Transitive closure of a graph, Find the number of islands, Count all possible walks from a source to a destination with exactly k edgesEuler Circuit in a Directed Graph
Hard Problems:Graph Coloring (Introduction and Applications),Greedy Algorithm for Graph Coloring, Travelling Salesman Problem (Naive and Dynamic Programming), Travelling Salesman Problem (Approximate using MST), Hamiltonian Cycle
Maximum Flow:Ford-Fulkerson Algorithm for Maximum Flow Problem,Find maximum number of edge disjoint paths between two vertices, Find minimum s-t cut in a flow network, Maximum Bipartite MatchingChannel Assignment Problem
Misc:  Find if the strings can be chained to form a circle, Given a sorted dictionary of an alien language, find order of characters
Quiz on Graph
Quiz on Graph Traversals
Quiz on Graph Shortest Paths
Quiz on Graph Minimum Spanning Tree

Quizzes on Algorithms:Analysis of Algorithms,   Sorting,   Divide and Conquer,   Greedy Algorithms,   Dynamic Programming,   Backtracking,   Misc,   NP Complete,   Searching,   Analysis of Algorithms (Recurrences),   Recursion,   Bit Algorithms,   Graph Traversals,   Graph Shortest Paths,   Graph Minimum Spanning Tree,

Commonly Asked Algorithm Interview Questions | Set 1

Please see Data Structures and Advanced Data Structures for Graph, Binary Tree, BST and Linked List based algorithms.

We will be adding more categories and posts to this page soon.

You can create a new Algortihm topic and discuss it with other geeks usingask a question page. See already discussed Algorithm questions on forum.





 
  • swarnim

    There are 8 cubicles in a room. In each cubicle, there are 8 computers. There are a total of 60 members. Constraint#1 – A team can contain a minimum of 2 members and a maximum of 6 members. Constraint#2 – In every cubicle, not more than 1 computer can be unallocated. Constraint#3 – All team members of a team must be in the same cubicle..anyone plz answer how to write algo on this??

  • swarnim

    Return the longest possible word from the English dictionary by combining symbols of the Periodic Table. Constraint – Symbols containing 2 characters cannot be broken & used independently. E.g. – Sodium’s symbol Na cannot be broken into N & a, you have to use Na together,how to write algo on this??

  • v kumar

    i need fast reply

  • v kumar

    i want step wise algorithm for pascal triangle using nested for loops in the form of
    1
    1 2 1
    1 3 3 1
    1 4 6 4 1

  • v kumar

    i want step wise algorithm for pascal triangle using nested for loops in the form of
    1
    1 2 1
    1 3 3 1
    1 4 6 4 1

  • sukoon sharma

    i want some new problems on transfer and conquer algorithm not the ones used in textbooks

  • Yo


    #include

    using namsespace std;

    int geeksforgeeks(int n){

    if(n==1) cout<<"GEEKS FOREVER"<<endl;

    else geeksforgeeks(n-1);

    }

    int main(){#include

    using namespace std;

    int geeksforgeeks(int n){

    if(n==1) return 0;

    geeksforgeeks(n-1);

    cout<<"GEEKS FOREVER"<<endl;

    return 0;

    }

    int main(){

    geeksforgeeks(5);

    }

    geeksforgeeks(20);

    }

  • gwpark

    So incredible job, guy. I’m so impressed. I’ve just read about dynamic programming, and I think the code you inserted is very helpful for me to understand more deeply about dynamic programming. Actually, I was finding some tutorial about algorithm in my native language, but I just decided to get around here to study algorithms (also study English). Thank you.

  • Haad Ali

    Hello….Can any one write an algorithm like find Fibonacci no from 1-20??
    I need dat…plx reply me as soon as possible……..

    • piyush bansal

      a = 0
      b = 1
      c=a+b
      a = b
      b = c
      again loop from start

      play with this algo as per your requirement

    • Chaithanya Kanumolu

      We have a D.P solution for fibonacci series.

      it looks like:
      a[0]=1;
      a[1]=1;
      int i=2;
      for(;a[i]<=20;i++)
      a[i]=a[i-1]+a[i-2];
      for(int j=1;j<=i;j++)
      sop(a[j]);
      Intentionally I have avoided a[0] in sop since 1 gets repeated twice.
      I hope this helps.

    • ARUN

      don’t ask for homework questions here , this platform is for quality discussion .

  • mysticPrince

    Nice List of Algorithms! Good Work geeks!

  • samg

    Hello,

    Thank you for helping me with this. I need to design an algorithm for the following.

    From the table below, I want to find out a set of 7 names that gives the largest sum of marks possible with keeping the total fees less than 4000.

    Just to be clear, here is the problem in different words.

    Desired output:
    Set of 7 names (Name1,Name2,Name3,Name4,Name5,Name6,Name7)that gives the largest sum of Marks
    (Marks1+Marks2+Marks3+Marks4+Marks5+Marks6+Marks7) should be the largest, satisfying the given condition.

    Conditions:
    Sum of Fees of 7 names is less than 4000.
    Fees1+Fees2+Fees3+Fees4+Fees5+Fees6+Fees7 < 4000

    Name Marks Fees
    A 87 345
    B 4 897
    C 87 432
    D 34 435
    E 6 345
    F 3 789
    G 9 78
    H 8 345
    I 7 879
    J 8 324
    K 87 789
    L 43 4536
    M 65 234
    N 87 897
    O 65 978
    P 23 324
    Q 89 342
    R 9 789
    S 87 34
    T 76 234
    U 654 897
    V 76 23
    W 879 435
    X 0 897
    Y 435 54
    Z 56 23

    I really appreciate your response.

    Regards!

    • Chaithanya Kanumolu

      I think this is similar to Knapsack problem. DP should help you, I guess.

    • Desmond

      Knapsack has very less runtime efficiency. . .this takes O(n^2). . .Or better if u replace selection sort with merge sort. . .

      #include

      #include

      main()

      {

      FILE *fp;

      char buff[255];

      int i;

      struct xxx

      {

      char name;

      float marks;

      float fees;

      float avg;

      };

      struct xxx a[26] = {{‘A’, 87 ,345 },

      {‘B’, 4 ,897 },

      {‘C’, 87 ,432 },

      {‘D’, 34 ,435 },

      {‘E’, 6 ,345 },

      {‘F’, 3 ,789 },

      {‘G’, 9 ,78 },

      {‘H’, 8 ,345 },

      {‘I’, 7 ,879 },

      {‘J’, 8 ,324 },

      {‘K’, 87 ,789 },

      {‘L’, 43 ,4536},

      {‘M’, 65 ,234 },

      {‘N’, 87 ,897 },

      {‘O’, 65 ,978 },

      {‘P’, 23 ,324 },

      {‘Q’, 89 ,342 },

      {‘R’, 9 ,789 },

      {‘S’, 87 ,34 },

      {‘T’, 76 ,234 },

      {‘U’, 654 ,897 },

      {‘V’, 76 ,23 },

      {‘W’, 879 ,435 },

      {‘X’, 0 ,897 },

      {‘Y’, 435 ,54 },

      {‘Z’, 56 ,23 }};

      for (i=0;i<26;i++)

      {

      a[i].avg = (4000/a[i].fees) * a[i].marks;

      printf("%c:%fn",a[i].name,a[i].avg);

      }

      printf("nnn");

      for(i=0;i<25;i++)

      {

      int pos=i;

      int j;

      for(j=i+1;ja[pos].avg)

      {

      pos = j;

      }

      }

      if(pos!=i)

      {

      float temp = a[i].avg;

      a[i].avg = a[pos].avg;

      a[pos].avg =temp;

      temp = a[i].fees;

      a[i].fees = a[pos].fees;

      a[pos].fees =temp;

      temp = a[i].marks;

      a[i].marks = a[pos].marks;

      a[pos].marks =temp;

      char c =a[i].name;

      a[i].name=a[pos].name;

      a[pos].name=c;

      }

      }

      for (i=0;i<26;i++)

      {

      printf("%c:t%ft%.0ft%.0fn",a[i].name,a[i].avg,a[i].marks,a[i].fees);

      }

      for(i=6;i<26;i++)

      {

      if((a[i].fees + a[i-1].fees + a[i-2].fees+a[i-3].fees+a[i-4].fees+a[i-5].fees+a[i-6].fees)<=4000 )

      {

      break;

      }

      }

      int j;

      printf("Optimal solution is : n");

      for(j=0;j<7;j++)

      {

      printf ("%c ",a[i--]);

      }

      }

  • mano

    hi! i just want to know some problems that could be solved using graph data structure based on vertex or edge coloring…

    • manu

      kunju paiya. sootha moodu

  • Anoop S S

    Excellent work

  • Hari priya

    It’s really helpful!! thank u GeekfforGeeks

  • anoop shukla

    i got a new way to learn………..i like your data that are being provided

  • Chetan

    Wow loving it all ..Happy studying.. Good work geeksforgeeks :)

  • Ganesh

    Very helpful…. Few more Datastructure and algorithms resources shared here http://www.indiageeks.in/top-5-online-resources-to-learn-data-structures-algorithms/

  • vsethuooo

    This is great! I can find more algos in the misc page! Why don’t you transfer them here, for easier access!!

  • savan

    thank you guys

  • harish.pendela

    Excellent work geeksforgeeks team…!!

  • ultimate_coder

    excellent

  • ultimate_coder

    excellent

  • Procastinator

    Respect!!

  • mahesh

    You guys are awesome … respect !!!

  • Akshay

    Whenever I am confused about what to do…I come to geeksforgeeks…its a boon for passionate individuals who loves coding and dreams of bagging a job at software giants like google,microsoft..

  • Naaz
     Great work....thank u guys !!!!!!!!!! 
  • subho

    Fantastic job being done by geeksforgeeks guys. Keep it up. really useful…..

  • http://www.shashank11sharma.blogspot.com shashank sharma

    Loving it….

  • Nauman

    Guys u rock!! 1 of d best website ever!!

  • azee

    Awesome work guys. Best place to understand code level implementation of different algorithms. Very Very helpful. :)

  • George

    Thanks

  • Chandana

    This is till now the best website for all the knowledge on programming till now, I have come across. Awesome work people. Bless All

  • PG

    Excellent work guys..keep it up!!

     /* Paste your code here (You may delete these lines if not writing code) */ 
  • Ashish

    Exactly the kind of website I was looking for. Alive, informative and to the point. Applause for your efforts.

  • gosi
     indeed , worth a web Portal ... 
  • Shailesh

    Great Work,thank you so much…

  • Sharat

    Thank you for this great work… I love this site!

     /* Paste your code here (You may delete these lines if not writing code) */ 
 
close