Interview 10 Big algorithm summary

Source: Internet
Author: User
Tags add numbers array sort array to string rotate image

English version


The following explains the common algorithms and data structures of interviews from a Java perspective: string, List, tree, graph, sort, recursive vs. iteration, dynamic planning, bit manipulation, probability problems, permutation combinations, and some questions that need to be searched for.


1. Strings and Arrays


strings and arrays are the most common types of interview topics and should be assigned the maximum time. With regard to strings, the first thing to note is that unlike C + +, Java strings are not char arrays. Without the automatic completion of IDE code, you should keep in mind the following common methods.


ToCharArray ()//get string corresponding to char array arrays.sort ()  //Array sort arrays.tostring (char[] a)//array to string charat (int x)// Gets the character at an index length ()//String length long//array size substring (int beginindex) substring (int beginindex, int endIndex) Integer.valueof ()//string to Integerstring.valueof ()/integer to String


The strings and arrays themselves are simple, but the related topics require more complex algorithms to solve. such as dynamic planning, search, and so on.


Classic topics:

1) Evaluate Reverse Polish Notation

2) Longest palindromic Substring

3) Word Break

4) Word Ladder

5) Median of Sorted Arrays

6) Regular Expression Matching

7) Merge intervals

8) Insert Interval

9) The Sum of the

9) 3Sum

9) 4Sum

3Sum Closest

One) String to Integer

) Merge Sorted Array

) Valid parentheses

) Implement StrStr ()

) Set Matrix Zeroes

Search Insert Position

) Longest consecutive Sequence

) Valid palindrome

Spiral Matrix

Search a 2D Matrix

) Rotate Image

Triangle)

Distinct subsequences Total

) Maximum Subarray

Remove Duplicates from Sorted Array

Remove duplicates from Sorted Array II

Longest Substring without repeating characters

Longest Substring that contains 2 unique characters

) Palindrome Partitioning

() Reverse Words in a String

) Find Minimum in rotated Sorted Array

Find Peak Element

) Min Stack

Majority Element

Combination Sum (DFS)

best time to Buy and Sell Stock

best time to Buy and Sell Stock II

Time to Buy and Sell Stock III (DP)


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) {        val = x;        next = null;}    }


List of two notable applications are stack stacks and queue queues. There are implementations in the Java standard Library, one is the stack and the other is LinkedList (the queue is the interface it implements).


Classic topics:

1) Add Numbers

2) Reorder List

3) Linked List Cycle

4) Copy List with Random Pointer

5) Merge Sorted Lists

6) Merge k Sorted Lists *

7) Remove duplicates from Sorted List

8) Partition List


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:

Binary search Tree: <= node <= right node in left node

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).

Full binary tree with two forks: each node except the leaf node has two children.

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.

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.


Classic topics:

1) Binary Tree Preorder Traversal

2) Binary Tree inorder traversal

3) Binary Tree postorder Traversal

4) Word Ladder

5) Validate Binary Search Tree

6) Flatten Binary Tree to Linked List

7) Path Sum

8) Construct Binary Tree from inorder and Postorder traversal

9) Convert Sorted Array to Binary Search Tree

Convert Sorted List to Binary Search Tree

One) Minimum Depth of Binary Tree

Binary Tree Maximum Path Sum *

Balanced Binary Tree


4. Figure


Graph-related issues are mainly focused on depth-first search and breadth-depth (breath first search). Depth-First search is simple, and breadth first takes care to use queue. The following is a simple use queue to achieve breadth-first search.

public class Graphtest {public    static void Breathfirstsearch (Graphnode root, int x) {        if (Root.val = = x)            syste M.out.println ("Find in Root");        Queue queue = new Queue ();        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);}}}}    


Classic topics:

Copy graph (clone graph)


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 (Bubble sort) N^2 N^2 1
Select sort (Selection sort) N^2 N^2 1
Insert sort (Insertion sort) N^2 N^2
Quick sorting (Quick sort) n Log (N) N^2
Merge sort n Log (N) n Log (N) Depends

* There are also Binsort, Radixsort and countsort three kinds of more special sort.

Classic title: MergeSort, Quicksort, Insertionsort.


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 steps 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) {    if (n <= 2) return n;    int x = f (n-1) + f (n-2);    return x;}


The time complexity of a recursive method is a number of levels, because there are many redundant computations:

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 int F (int n) {    if (n <= 2) {        return n;    }    int first = 1, second = 2;    int third = 0;    for (int i = 3; I <= n; i++) {        third = first + second;        first = second;        second = third;    }    return third;}


This example iterations takes less time and you may review a difference between the two 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, or the optimal solution of the problem contains the optimal solution of its sub-problem.
    2. Solutions for some sub-problems may need to be calculated multiple times
    3. The solution to the sub-problem is stored in a table so that each sub-problem is calculated only once
    4. Extra space is needed 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];p ublic static int f3 (int n) {    if (n <= 2)        a[n]= N;    if (A[n] > 0)        return a[n];    else        A[n] = F3 (n-1) + F3 (n-2);//store results so only calculate once!    return a[n];}


Classic topics:

1) Edit Distance

2) Longest palindromic Substring

3) Word Break

4) Maximum Subarray

5) Palindrome Partitioning


8. Bit operation


Common bit 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

Use a topic to understand these operations-

gets the first bit of the given number n: (I count from 0 and start from the right)
public static Boolean getbit (int num, int i) {    int result = num & (1<<i);    if (result = = 0) {        return false;    } else{        return true;}
For example, get the 2nd bit of the Number 10: I=1, n=101<<1= 101010&10=1010 is not 0 and so return true;

9. Probability problems


Solving probability-related problems usually requires a first analysis of the problem, and here is a simple example of such a 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++) {        x *=  (365.0-i)/365.0;    }    Double Pro = Math.Round ((1-x) * +);    return pro/100;}
Calculateprobability (50) = 0.97

Classic title: Taking the ball in a bucket


10. Permutations and combinations


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

1, 2, 3, 4, 5 of these 5 numbers, write a method in Java, print out all the different permutations, such as: 51234, 41235, and so on. Requirements: "4" can not be in the third place, "3" and "5" can not be connected.
Example 2:
5 Bananas, 4 pears, 3 apples. The same kind of fruit is the same, how many of these fruits are arranged in different combinations?


11. Other types of topics


The main is not to the above 10 categories. Need to look for patterns and then solve problems. Classic title: Reverse Integer

Interview 10 Big algorithm summary

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.