The 10 most common algorithms in the programming interview process

Source: Internet
Author: User
Tags array sort bitwise operators

Here are the concepts related to the top 10 algorithms in the programming interview, and I'll use some simple examples to illustrate these concepts. Since the full mastery of these concepts requires more effort, this list is just as an introduction. This article looks at the problem from a Java perspective and includes the following concepts:

1. String

If the IDE does not have the code auto-completion feature, you should keep these methods in mind.

// gets the char array corresponding to the string Arrays.sort ()  //  array sort arrays.tostring (char//  array turns into string charAt (  int//  get the character //  string length //  array size at an index
2. Linked list

In Java, the implementation of a linked list is very simple, with each node having a value Val and a link to the next node next.

class Node {    int  val;    Node Next;    Node (int  x) {        = x;         NULL ;    }}

List of two notable applications are stack stacks and queue queues.

Stack:

classstack{Node top;  PublicNode Peek () {if(Top! =NULL){            returntop; }        return NULL; }     PublicNode Pop () {if(top = =NULL){            return NULL; }Else{Node temp=NewNode (Top.val); Top=Top.next; returntemp; }    }     Public voidpush (Node N) {if(n! =NULL) {N.next=top; Top=N; }    }}

Queue:

classqueue{Node First, last;  Public voidEnqueue (Node N) {if(First = =NULL) { First=N; Last=First ; }Else{Last.next=N; Last=N; }    }     PublicNode dequeue () {if(First = =NULL){            return NULL; }Else{Node temp=NewNode (First.val); First=First.next; returntemp; }        }}
3. Tree

The tree here usually refers to a two-fork tree, each of which contains a left child node and a right child node, as follows:

class treenode{    int  value;    TreeNode left;    TreeNode right;}

Here are some of the concepts related to trees:

    1. Balance vs. unbalanced: In a balanced binary tree, the depth difference between the left and right subtrees of each node is at most 1 (1 or 0).
    2. Full binary tree with two forks: each node except the leaf node has two children.
    3. Perfect binary tree (Perfect binary trees): is a full two-tree with the following properties: All leaf nodes have the same depth or level, and each parent node must have two children.
    4. Complete binary tree: Two in a tree, each layer is fully filled, except for the last one, and all nodes must be left-leaning as far as they can.

Translator Note: The perfect binary tree is also vaguely called a complete binary tree. An example of a perfect binary tree is an ancestor diagram of a person at a given depth, because everyone must have two birth parents. A complete binary tree can be seen as a perfect binary tree that can have several additional left-leaning leaf nodes. Question: What is the difference between a perfect binary tree and a full two-fork tree? (Reference: http://xlinux.nist.gov/dads/HTML/perfectBinaryTree.html)

4. Figure

Graph-related issues are mainly focused on depth-first search and breadth-depth (breath first search).

The following is an implementation of a simple graph breadth-first search.

1) Define Graphnode

class graphnode{     int  val;    Graphnode Next;    Graphnode[] neighbors;     Boolean visited;    Graphnode (int  x) {        = x;    }    Graphnode (int  x, graphnode[] n) {        = x;         = n;    }      Public String toString () {        returnthis. val;     }}

2) define a queue

classqueue{Graphnode First, last;  Public voidEnqueue (graphnode N) {if(First = =NULL) { First=N; Last=First ; }Else{Last.next=N; Last=N; }    }     PublicGraphnode dequeue () {if(First = =NULL){            return NULL; }Else{Graphnode temp=NewGraphnode (First.val, first.neighbors); First=First.next; returntemp; }        }}

3) to achieve breadth-first search by queuing queue

 Public classGraphtest { Public Static voidMain (string[] args) {Graphnode N1=NewGraphnode (1); Graphnode N2=NewGraphnode (2); Graphnode N3=NewGraphnode (3); Graphnode N4=NewGraphnode (4); Graphnode N5=NewGraphnode (5); N1.neighbors=NewGraphnode[]{n2,n3,n5}; N2.neighbors=NewGRAPHNODE[]{N1,N4}; N3.neighbors=NewGraphnode[]{n1,n4,n5}; N4.neighbors=NewGraphnode[]{n2,n3,n5}; N5.neighbors=NewGRAPHNODE[]{N1,N3,N4}; Breathfirstsearch (N1,5); }     Public Static voidBreathfirstsearch (Graphnode root,intx) {        if(Root.val = =x) System.out.println ("Find in Root"); Queue Queue=NewQueue (); Root.visited=true;        Queue.enqueue (root);  while(Queue.first! =NULL) {Graphnode C=(Graphnode) queue.dequeue ();  for(Graphnode n:c.neighbors) {if(!n.visited) {System.out.print (n+ " "); N.visited=true; if(N.val = =x) System.out.println ("Find" +N);                Queue.enqueue (n); }            }        }    }}
5. Sorting

Here is the time complexity of the different sorting algorithms, you can go to the wiki to see the basic idea of these algorithms.

Algorithm Average time Worst time Space
Bubble sort N^2 N^2 1
Select sort N^2 N^2 1
Counting Sort N+k N+k N+k
Insertion Sort N^2 N^2
Quick sort n Log (N) N^2
Merge sort n Log (N) n Log (N) Depends

In addition, here are some implementations/demos:: Counting Sort, mergesort, Quicksort, Insertionsort.

    • 7 commonly used sorting algorithms for visually intuitive perception
    • Video: 6-minute demo of 15 sorting algorithms
6. Recursion vs. Iteration

For programmers, recursion should be an innate thought (a built-in thought), which can be explained by a simple example.

Problem: There are n steps, only 1 or 2 steps at a time, the total number of ways to go.

Step 1: Find the relationship between the top n steps and the front n-1 step steps.

In order to finish the n steps, there are only two methods: Climb 1 steps from the n-1 step steps or climb 2 steps from the n-2 steps. If f (n) is the number of methods that crawl to the nth step, then f (n) = f (n-1) + f (n-2).

Step 2: Make sure that the starting condition is correct.

F (0) = 0;
F (1) = 1;

 Public Static int f (int  n) {    ifreturn  N;     int x = f (n-1) + f (n-2);     return x;}

The time complexity of the recursive method is the number of N, because there are many redundant computations, as follows:

F (5)
F (4) + F (3)
F (3) + F (2) + F (2) + F (1)
F (2) + f (1) + f (1) + f (0) + F (1) + f (0) + F (1)
F (1) + f (0) + F (1) + f (1) + f (0) + F (1) + f (0) + F (1)

The direct idea is to translate recursion into iterations:

 Public Static intFintN) {if(N <= 2){        returnN; }    intFirst = 1, second = 2; intThird = 0;  for(inti = 3; I <= N; i++) {Third= First +second; First=second; Second=third; }    returnthird;}

For this example, iterations take less time, and you might want to see recursion vs iteration.

7. Dynamic Planning

Dynamic planning is a technique for solving the following nature-class problems:

    1. A problem can be solved by the solution of the problem (translator Note: The optimal solution of the problem contains the optimal solution of its sub-problem, that is, the optimal sub-structure properties).
    2. The solution of some sub-problems may need to be calculated several times (translator note: That is, sub-problem overlapping properties).
    3. The solution to the sub-problem is stored in a table so that each sub-problem is calculated only once.
    4. Additional space is required to save time.

The stair climbing problem is completely in line with the above four properties, so it can be solved by dynamic programming method.

 Public Static int[] A =New int[100]; Public Static intF3 (intN) {if(N <= 2) A[n]=N; if(A[n] > 0)        returnA[n]; ElseA[n]= F3 (n-1) + F3 (n-2);//Store results so only calculate once!    returna[n];}
8. Bit operation

Bitwise operators:

OR (|) and (&) XOR (^) Left Shift (<<) Right Shift (>>) Not (~)
1|0=1 1&0=0 1^0=1 0010<<2=1000 1100>>2=0011 ~1=0

Gets the first bit of the given number n: (I count from 0 and start from the right)

 Public Static boolean getbit (intint  i) {    int result = num & (1<<i);     if(result = = 0)        {returnfalse;    } Else {        returntrue;    }

For example, get the 2nd digit of the Number 10:

I=1, n=10
1<<1= 10
1010&10=10
0, so return true;

9. Probability problems

Solving probability-related problems usually requires a good plan to understand the problem (formatting the problem), where there is just one simple example of this type of problem:

There are 50 people in a room, so what is the probability that at least two people have the same birthday? (ignoring the fact that leap years, that is, 365 days a year)

The probability of calculating certain things can often be converted to calculate their relative faces first. In this example, we can calculate the probability that everyone's birthdays are different, that is: 365/365 * 364/365 * 363/365 * ... * (365-49)/365, so that at least two people birthday the same probability is the value of this.

 Public Static double caculateprobability (int  n) {    double x = 1;       for (int i=0; i<n; i++) {        *=  (365.0-i)/365.0;    }     double pro = Math.Round ((1-x) * +);     return pro/100;

Calculateprobability (50) = 0.97

10. Permutations and combinations

The difference between composition and arrangement is whether the order is critical.

10 most common algorithms (RPM) in the programming interview process

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.