Front end interview classic: common algorithms

Time:2021-9-2

preface:

If you want to systematically learn the front-end interview questions, it is highly recommended to browseOnline ebook(mobile version is supported and updated continuously).

Features of this book: comprehensive system (covering front-end core technology points), concise and targeted (designed for interview scenes).

Welcome togithubComment feedback on

algorithm

Fibonacci series?

Golden section sequence

From the third digit, each number is the sum of the first two digits

[3, 5, 8, 13, 21]

//Generating Fibonacci sequence by iterative method
    function fib(n) {
        var fib_n = function(curr, next, n) {
            if (n == 0) {
                return curr;
            }
            else {
                return fib_n(next, curr+next, n-1);
            }
        }
        return fib_n(0, 1, n);
    }
    alert(fib(40));

What are the common algorithms?

  • Sorting algorithm: quick sort, merge sort and count sort (8 sorting algorithms)
  • search algorithm : backtracking, recursion, pruning techniques
  • graph theory: shortest tree, minimum spanning tree, network flow modeling
  • dynamic programming: knapsack problem, longest subsequence, counting problem
  • Basic skills: divide and conquer, multiplication, dichotomy, greed

reference material:

What are the most common interview algorithm questions for Internet companies?

Divide and conquer algorithm?

Applicable:

  1. The scale can be reduced to a certain extentEasily solved
  2. It can be decomposed into several smaller same problems withOptimal substructure properties
  3. Solution of subproblemCan mergeIs the solution of the problem
  4. Subproblems are independent of each other, subproblems do not contain common subproblems

Implementation process:

Similar to mathematical induction, find the equation formula to solve the problem, and then design the recursive program according to the equation formula

  1. [decomposition] the original problem is decomposed into several small-scale, independent subproblems with the same form as the original problem
  2. [solution] if the scale is small and easy, solve it directly, otherwise solve the subproblem recursively (consider the solution method as the problem scale increases)
  3. [merge] merge the solutions of subproblems into the solutions of the original problem, find the recursive functions (various scales and factors) to solve, and design the recursive program

Use case:

  • Binary search
  • Quick sort

reference material:

One of the five commonly used algorithms: divide and conquer algorithm

Introduction to recursive algorithm?

There is a call to the function itself in the function. This phenomenon is called recursion

Lenovo (tower of Hanoi):

Convert the pyramid stacked with wood blocks (5 in total) to another column. You can use an intermediate column. You can only move one wood block at a time. Large wood blocks cannot be pressed on small wood blocks. The minimum path is

General solution (steps):

  • [implement the same function] decompose a problem into sub problems with the same solution ideas, and can call a function to implement
  • [termination condition] determine the termination condition before calling the function

Front end interview classic: common algorithms

reference material:

Dynamic programming algorithm?

reference material:

Cow force, the original God is learning dynamic planning like this

Greedy algorithm?

Greedy algorithm (greedy method) only considers the current optimal solution, not the whole situation. Hope from: local optimal solution – > global optimal solution, and often not

Steps:

  1. [split]: divide the problem into several steps
  2. [optimal solution in each step] select the best / best choice in the current state (local most favorable choice) in each step
  3. [loop] the stacked result is also the best / optimal solution

Lenovo (change, minimum quantity): Change: 31 yuan

Core idea: only consider the current optimal solution, not the overall situation

  • Among the conditions (x ≤ 31), the best choice is 20 yuan
  • Among the conditions (x ≤ 11), the best choice is 10 yuan
  • Among the conditions (x ≤ 1), the best choice is 1 yuan

Disadvantage case: change 41 yuan

If there is (25 yuan, 20 yuan, 10 yuan, 5 yuan, 1 yuan) in the face value of the currency at this time

  • Strategy of greedy algorithm: 25 + 10 + 5 + 1
  • Actual optimal solution strategy: 20 + 20 + 1

advantage:

  • It is simple, efficient and eliminates the exhaustive operation that may be required to find the optimal solution. It is usually used as an auxiliary algorithm of other algorithms

Disadvantages:

  • Regardless of the population, the local optimal solution is selected every time, and the backtracking processing is no longer carried out, so the optimal solution is obtained in few cases

reference material:

Little white belt you learn — greedy algorithm

Introduction to backtracking algorithm (belonging to depth first search)?

Backtracking method (heuristic method): it is an optimization search method, which searches forward according to the optimization conditions to achieve the goal. However, when a certain step is explored and it is found that the original step is not excellent or the goal cannot be achieved, it will be returned to the first step again. This technology is called backtracking method, and a state point that meets the backtracking conditions is called “backtracking point”

Backtracking attribute depth first search, because it is a global search, the complexity is relatively high.

Lenovo:

Go through the maze,

  • [tentative execution] first choose a path and start walking
  • [find it impassable, prepare to return] if the road is impassable, go back to the last fork
  • [take another road at the node] take the next road until the destination is found;

reference material:

Little white belt you learn — back tracking algorithm

Array sort?

  1. Sort method of array
  2. Bubble sorting

What are the common sorting algorithms?

  1. Bubble sorting: the size of adjacent pairs is exchanged, and the circular comparison is completed in two layers
  2. Select sort: select sort is the most intuitive sort. Confirm the maximum or minimum value of a key, and then exchange it with the maximum / minimum value found in other numbers to the matching position
  3. Insert sort:
  4. Shell Sort
  5. Merge sort
  6. Quick sort: the records to be sorted are separated into two independent parts by one-time sorting. If the data of one part of the records are smaller than that of the other part, the records of the two parts can be sorted separately to achieve the order of the whole sequence;
  7. Heap sort
  8. Count sort:
  9. Bucket sorting
  10. Cardinality sort

Reference materials (including algorithm visualization diagram):https://github.com/damonare/S…

Bubble sorting

Definition: the size of adjacent pairs is interchanged, and the circular comparison is completed in two layers

Bubble sort:

Front end interview classic: common algorithms

Select sort

Definition: selection sorting is the most intuitive sorting. Confirm the maximum or minimum value of a key, and then exchange it with the maximum / minimum value found in other numbers to the matching position

Algorithm implementation:

  • Confirm comparison value: default first
  • Find the minimum number: find the number smaller than the comparison value in the remaining number
  • Position replacement: replace the minimum value found with the position of the comparison value
  • Repeat step: two layer circulation

Front end interview classic: common algorithms

Quick sort

Definition: the records to be sorted are separated into two independent parts by one-time sorting. If the data of one part of the records are smaller than the data of the other part, the records of the two parts can be sorted separately to achieve the order of the whole sequence;

Algorithm implementation:

  • Confirmation benchmark: select an element from the sequence, which is called ‘pivot’
  • Partition operation: less than the datum before placement, greater than the datum after placement. After completion, the datum is in the middle position
  • Recursive operation (confirm benchmark – > partition operation): repeat the above steps

Front end interview classic: common algorithms

Insert sort

Definition: by constructing an ordered sequence, for unordered data, scan from back to front in the sorted sequence, find the corresponding position and insert it (Association: the process of playing cards and touching cards)

realization:

  • start: take the first element first, and the default is ordered sequence
  • Touch cards and compare: find the data on the sorted sequence, look it up from the back to the front, and insert the data smaller than it

Shell Sort

It is an improved version of simple insertion sort. The difference between it and insertion sort is that it will preferentially compare elements far away, reduce aliases and incremental sort

Definition: the core of Hill sort is the setting of interval sequence (which can be set in advance or dynamically defined)

Common search algorithms?

Binary search method

  • Scope of use: the search object is an ordered data structure
  • Introduction: in an ordered data, compromise the data. Each compromised data should be compared with the searched data, and then continue to narrow the search range until it is found or the interval is 0;
  • Case:

    • Judge the index of a letter and data in the array;
    • Figure guessing game

Linear search

  • Scope of use: Unlimited
  • Features: simple traversal to judge whether it exists
  • Case: judge the index of a target object in the data

Binary tree introduction?

Binary tree is a very basic and important data structure

application:

  • Preamble: display directory
  • Middle order: implement expressions, which are very useful at the bottom of the compiler
  • Post order: calculate the files and their information in the directory

characteristic:

  • The length of each node is no more than 2
  • The child node order of each node cannot be reversed arbitrarily

Binary node traversal method classification: (to be used to stack, queue, recursion, etc.)

  • Depth first traversal
  • breadth-first search

What is the difference between depth first traversal and breadth first traversal?

Traversal concept of binary tree.

Depth first traversal (DFS)

Definition: start from the root node and traverse vertically along the left subtree until the leaf node is found. Then the right subtree node is traversed until all reachable nodes are traversed.

Classification:

  • Preamble:
  • Middle order:
  • Post order:

Breadth first traversal (BFS)

Definition: starting from the root node, traverse the hierarchy of the binary tree vertically on the basis of traversing the binary tree horizontally;

Traversal idea: recursion

Illustration:

Front end interview classic: common algorithms

Above search order

DFS:ABDECFG

BFS:ABCDEFG

The expression is represented by a binary tree:

(a+b*c)-d/e

Front end interview classic: common algorithms

reference material:https://juejin.im/entry/68449…