Writing in the front

As early as in the middle and late July, the recruitment of the 2022 autumn recruitment has been held. Several rounds of written interviews have been held in various major factories, and many students have already received some offers. Due to the serious volume now, leading to the autumn recruitment is earlier and earlier, the technical requirements for this year’s students are also higher and higher, the knowledge is also more and more wide. September and October are the prime time for autumn recruitment, so now is the time to prepare some interview questions, brush up on some algorithm questions. Here is the real interview experience of Bytedance.

One side

A simple introduction

  • To introduce myself
  • The role of entrepreneurial projects
  • Startup results, traffic, that sort of thing

Technical questions and answers

1. Can you talk about some scenarios corresponding to different data results?

1) array

  • Advantages: Fast to query elements according to the index, convenient to traverse the number group according to the index
  • Disadvantages: The size of an array is fixed and cannot be expanded. The array can only store one type of data, and the operation of adding and deleting is slow because other elements need to be moved.
  • Application scenario: This operation is performed frequently, requires little storage space, and is seldom added or deleted

2) stack

  • Application scenario: matching parentheses; Inverse Polish expression evaluation problem; Implement recursive energy scenarios, such as the Fibonacci sequence.

3) queue

  • Application scenario: Because of the characteristics of queue first in first out, it is very suitable for multi-threaded blocking queue management.

4) list

  • Advantages: Linked list is a very common data structure, does not need to initialize the capacity, can arbitrarily add or subtract elements; When adding or deleting an element, you only need to change the pointer field of the node before and after the element to point to the address, so it is quick to add and delete.
  • Disadvantages: Because it contains a large number of pointer fields, it takes up large space; Finding elements requires traversing the linked list to find them, which is time-consuming.
  • Application scenario: A small amount of data needs to be added frequently and deleted. Fast and slow Pointers: finding the middle value problem, one-way list whether there is a ring problem, there is a ring list entry problem; Circular linked lists: The Joseph problem.

5) the tree

  • Application scenario: JDK1.8 HashMap source code used in the array + linked list + red-black tree; Disk files use B-tree as data organization, which greatly improves I/O operation efficiency. Mysql database index structure uses B+ tree

6) Hash table

  • Application scenario: There are many application scenarios of hash table, of course, there are also many problems to consider, such as hash conflict, if not handled properly will waste a lot of time, resulting in application crash. Solve hash conflict problem: you can expand the array; Optimize the hash calculation method.

7) heap

  • Application scenario: Because the characteristics of heap order, generally used to do the array sort, called heap sort.

Figure 8)

  • Application scenario: Road smooth engineering, shortest path

2. Understanding scope

Scope: The area of the program where variables are defined, which determines the access to the variables for the currently executing code.

For the most part in javascript, there are only two scope types:

  • Global scope: A global scope is the outermost scope of a program and always exists.
  • Function scope: A function scope is created only when the function is defined, within the parent function scope/global scope.

Due to scope limitations, each independently executing code block can only access variables in its own scope and in the outer scope, but not in the inner scope.

/* Global scope starts */
var a = 1;

function func () { /* the func function scope starts */
  var a = 2;
  console.log(a);
}                  /* func function scope end */

func(); / / = > 2

console.log(a); / / = > 1

/* End of global scope */
Copy the code

3. Understanding closures

Closure: A function that can access variables inside other functions, called a closure. That is, a closure is a function defined inside a function that is returned and called externally.

function foo() {
  var a = 2;

  function bar() {
    console.log( a );
  }

  return bar;
}

var baz = foo();

baz(); // This forms a closure
Copy the code

Closures can bypass the scope’s regulatory mechanisms and get information about the internal scope from the outside.

Closure application scenarios: Closures are mostly used when internal variables need to be maintained.

Misuse of closures can lead to memory leaks. This inability to release memory due to overuse of closures is called a memory leak.

A memory leak is a condition in which a block of memory is not returned to the operating system or memory pool for some reason when it is no longer being used by an application. A memory leak can cause an application to stall or crash.

Check for memory leaks:

  • Performance
  • Memory

How to avoid memory leaks:

  • Use strict patterns to avoid inadvertent disclosure of global variables
  • Pay attention to the DOM life cycle and remember to unbind related events during the destruction phase
  • Avoid overusing closures

4. Tell the difference between TCP and UDP

TCP is connection-oriented and requires a three-way handshake to establish a connection and a four-way handshake to disconnect a connection. Therefore, TCP is reliable and does not operate on packets. TCP supports unicast transmission only, is byte stream oriented, and can provide congestion control.

UDP is connectionless and provides unicast, multicast, and broadcast functions without the need for three-way handshake. It is message-oriented, with low header overhead and high efficiency in transmitting data packets.

In short:

  • TCP provides connection-oriented reliable services to the upper layer, while UDP provides connectionless unreliable services to the upper layer.
  • Although UDP is not as accurate as TCP transmission, it can also be used in many places where real-time requirements are high
  • TCP can be used if the data accuracy is high and the speed is relatively slow

5. Why does HTTP3.0 use UDP

HTTP/3 chose UDP primarily to solve the problem of head blocking. Its underlying protocol, known as QUIC, runs at the transport (or application) layer. Unlike TCP, QUIC code is not hard-coded into the operating system kernel, but runs entirely in user space, with TLS integrated by default.

  • QUIC can realize all the functional requirements of TCP protocol and integrate TLS, surpassing TCP in function
  • One connection, multiple stream concurrent transmission, real multiplexing, effectively solve the queue head blocking phenomenon, performance beyond TCP
  • Reduced number of handshakes, especially with TSL transport, with lower handshake latency
  • Because it is easy to upgrade, it provides a huge imagination space for the renewal and development of the protocol

6. How to implement a V-Model

The V-model is essentially a syntax-sugar of $emit(‘input’) and props: Value, and you can use a V-model in a component if both conditions are met.

The parent component

new Vue({
 components: {
   CompOne,
 },
 data () {
   return {
     value: 'vue'}},template: '
      
// Using v-model satisfies the syntax sugar rules: the attribute must be value and the method name must be input
'
, }).$mount(root) Copy the code

Child components:

// Modify child components
const CompOne = {
  props: ['value1'].model: {
      prop: "value1".// Received data value => value1
      event: "change" $emit input => change
  },
  template: ` 
      
`
.methods: { handleInput (e) { this.$emit('change', e.target.value) } } } Copy the code

7. Talk about the nextTick principle

The callback in nextTick is the callback that is executed after the next DOM update cycle. Use this method immediately after modifying the data to get the updated DOM.

The main idea is to call asynchronous methods to execute nextTick methods in a microtask-first manner. It’s an event loop.

8. Event loops

During the execution of JavaScript code, not only the function call stack is used to determine the execution order of functions, but also the task queue is used to determine the execution of other codes. The entire execution process is called the event loop. Event loops are unique within a thread, but task queues can have multiple. Task queues are divided into macro-tasks and micro-tasks. In the latest standard, they are called Tasks and Jobs respectively.

Macro-task includes:

  • Script (whole code)
  • setTimeout
  • setInterval
  • setImmediate
  • I/O
  • UI render

Micro-task includes:

  • process.nextTick
  • Promise
  • Async/Await(actually promise)
  • MutationObserver(new html5 feature)

The main thread reads asynchronous task execution from the “task queue”. This process is cyclic, so we also call this process an Event Loop or Event Loop.

When executing the JavaScript code, the main thread will execute the code step by step from top to bottom. Synchronous tasks will be added to the execution stack and executed first, and asynchronous tasks will put the registered callback function into the task queue when they get the result. When there is no task executing in the execution stack, The engine reads tasks from the task queue and pushes them onto the Call Stack to process execution.

Complete event loop mechanism:

  • First, when the overall script(as the first macro task) starts executing, all the code is divided into synchronous tasks and asynchronous tasks.

  • Synchronous tasks are directly executed in the main thread, and asynchronous tasks are divided into macro tasks and micro tasks.

  • The macro task enters the Event Table and registers the callback function in the Event Table, which will be moved to the Event Queue whenever the specified Event completes. The microtask will also go to another Event Table and register a callback function in it, which will be moved to the Event Queue whenever the specified Event completes.

  • When tasks in the main thread are completed and the main thread is empty, the Event Queue of microtasks will be checked. If there are tasks, they will all be executed. If there are no tasks, the next macro task will be executed

  • This process is repeated over and over again. This is called an Event Loop, a relatively complete Event Loop

9. Perform nextTick first and then modify the value. Is the nextTick value before or after modification?

NextTick takes the value before it was modified, because every time you update the data, you have to update the DOM the next time you can re-render the data.

The callback in nextTick is the callback that is executed after the next DOM update cycle. Use this method immediately after modifying the data to get the updated DOM.

10. Why use mutationObserver?

Mutation Observer is an API used to replace Mutation Events to observe changes in DOM tree structure and perform corresponding processing.

11. To realize the Promise. All

Promise.all is characterized by:

  • Receives an array of Promise instances or an object with an Iterator interface
  • Resolve becomes a Promise object if the element is not a Promise object
  • If everything succeeds, the state becomes Resolved and the returned values are passed as an array to the callback
  • Once there is a failure, the state becomes Rejected and the return value is passed directly to the callback
  • The return value of promise.all () is also a new Promise object
Promise.all = function(arr){
    return new Promise((resolve,reject) = > {
        if(!Array.isArray(arr)){
            return reject(new TypeError('arguments must be an array'));
        }
        let length = arr.length;
        let resolveNum = 0;
        let resolveResult = [];
        for(let i = 0; i < length; i++){
            arr[i].then(data= > {
                resolveNum++;
                resolveResult.push(data)
                if(resolveNum == length){
                    return resolve(resolveResult)
                }
            }).catch(data= > {
                return reject(data)
            })
        }
    })
}

Copy the code

Second interview

A simple introduction

  • To introduce myself
  • What did you learn in your startup program?
  • Can you tell me something about your internship program? (Project background, project function, project structure, what did you do and what benefits did you bring?)

Technology is introduced

1. Tell me about the print result

function ClassA(){
  this.x = "hello";
}

ClassA.prototype.x = "world";

const a = new ClassA();
a.x = "what";
console.log(a.x);
delete a.x;
console.log(a.x);
a.x = undefined;
console.log(a.x)
Copy the code

2. Tell me about the print result

function someFunction(){
  let a = 0;
  return function(){
    returna++; }}const f1 = someFunction();
const f2 = someFunction();

console.log(f1())
console.log(f2())

const f = someFunction();
console.log(f())
console.log(f())
Copy the code

3. Talk about scopes and closures

meet

4. How does webSocket do message confirmation? There are no Ajax callbacks.

Websocket is a fairly thin layer of abstraction on top of a traditional TCP socket, and a remote client will send a TCP ACK packet for every packet you will send it, only if the peer explicitly acknowledges it via an application-level protocol. But this fact is nicely hidden in the application, and just receiving the ACK packet means that the remote TCP stack has processed it, but it says nothing about how (and if) the client application processes it.

5. Can you tell me what optimization you have made in your internship program?

6. Can you tell me about the pitfalls you stepped in during your internship program?

7. What is BFC and what are the trigger conditions? What problems does the BFC solve? How to solve the margin overlap?

BFC: Block Formatting Context, which is an independent rendering area, isolates the elements inside the BFC from the elements outside, so that the positioning of the elements inside and outside does not affect each other.

BFC trigger conditions, that is, the following schemes can be used to create BFC:

  • Float element, float is not None
  • Absolute position element, position attribute absolute, fixed
  • Block-level containers for non-block-level boxes (display values are inline-blocks, table-cells, table-captions, etc.)
  • Overflow is not visible (unavailable is the default value. Content is not pruned and is rendered outside the element box.
  • In addition, the root element, the HTML element itself, is the BFC (the largest BFC)

Landing the role:

  • Adaptive two-column layout: Prevents elements from being overwritten by floating elements and ADAPTS to a two-column layout
  • Clear internal float: Fixed floating elements not being too high (floating elements not wrapped in parent container)
  • Solve margin overlap: In order to prevent margin overlap, multiple boxes can be divided into different BFC
  • Prevents elements from being overwritten by floating elements

How BFC resolves margin overlap:

  • The inner boxes will be placed vertically, one on top of the other;
  • The vertical distance of boxes is determined by margin. The upper and lower margins of two adjacent boxes belonging to the same BFC will overlap.
  • The left side of each element touches the left side of the contained box, even if there is a float;
  • The region of the BFC does not overlap with float;
  • A BFC is a separate container on a page, where child elements do not affect outside elements and vice versa;
  • When calculating the height of the BFC, floating elements are also involved.

8. Does Vue encounter data changes without updating views?

Yes, you can use Nexttick to solve the problem of data not being updated in time.

9. What is the difference between UDP and TCP? Why is TCP reliable? Other than connection-oriented, reliable, byte stream, what else does TCP have?

meet

10. How to achieve vertical horizontal center?

Method one:

div.box{
  weight:200px;
  height:400px; <! Change element to position element -->position:absolute; <! -- Sets the position of the element, both up and left50%-->
  left:50%;
  top:50%; <! Set the left margin and upper margin of the element to negative of the width and height1/2-->
  margin-left: -100px;
  margin-top: -200px; } * Good compatibility; Disadvantages: Must know the width and height of the elementCopy the code

Method 2:

div.box{
  weight:200px;
  height:400px; <! Change element to position element -->position:absolute; <! -- Sets the position of the element, both up and left50%-->
  left:50%;
  top:50%; <! -- Sets the offset of the element to negative relative to itself50%(that is, half the size of the element itself)-->transform:translate(-50%, -50%); } * This is the style in CSS3; Disadvantages: Poor compatibility, only supports IE9+ browsersCopy the code

Method 3:

div.box{
  width:200px;
  height:400px; <! Change element to position element -->position:absolute; <! -- Sets the position of the element, up, down, left, and right0-->
  left:0;
  right:0;
  top:0;
  bottom:0; <! -- sets the element'smarginStyle value forauto-->
  margin:auto; } * Good compatibility, disadvantages: does not support browsers below IE7Copy the code

11. What is your understanding of CDN? What is the CDN back source? Is the source negotiated cache or strong cache?

A Content Delivery Network (CDN) is a group of servers distributed in various regions. These servers store copies of the data, so the server can fulfill requests for data based on which servers are closest to the user. CDN provides fast service and is less affected by high traffic.

“Back source” is the process in which the CDN finds that it does not have the resource (usually the cached data has expired) and turns to the root server (or its upper layer server) for the resource.

12. What about load balancing?

Load balancing is a key component of the high availability architecture. Load balancing is used to improve performance and availability. Traffic is distributed to multiple servers through load balancing, and multiple servers can eliminate single points of failure.

Load balancers are single point of failure hazards. You can consider load balancing dual-system hot backup or other solutions to eliminate single point of failure and improve availability.

13. Algorithm

Given an array of non-empty integers, each element appears an even number of times except for one element. Find the element that occurs only once and implement it programmatically.

14. Algorithm: tree hierarchy traversal

15. Why is HTTPS secure? Asymmetric encryption and decryption process?

  • HTTP is a hypertext transfer protocol. Information is transmitted in plain text. HTTPS is a secure SSL transmission protocol that encrypts the communication between the browser and server to ensure data transmission security. HTTP is usually carried on top of TCP, and a security layer (SSL or TSL) is added between HTTP and TCP, which is often referred to as HTTPS.

  • HTTPS chooses to exchange keys during handshake.

  • In general, during the handshake, the server issues a certificate (with a public key) with which the client encrypts a short piece of data S and returns it to the server. Unlock the server with the private key and get S. At this point, the handshake step is complete, and S becomes a symmetric encryption key that is securely transmitted to the other party. After that, the server and my request response only need to use S as the key for a symmetric encryption.

16. Do you know about man-in-the-middle attacks? How can XSS be prevented? If you were asked to implement XSS prevention with JS, what would you do?

Cross-site scripting (XSS) : A malicious attacker inserts malicious HTML code into a Web page. When a user browses the page, the HTML code embedded in the Web page will be executed to attack the user.

How XSS can prevent:

  • Input filtering: Prevents HTML from being injected and JavaScript from executing malicious code.
  • Prevent stored and reflective XSS attacks: Switch to pure front-end rendering, separate code from data, and fully escape HTML.
  • Prevention of DOM XSS attacks: DOM XSS attacks actually mean that the front-end JavaScript code of a website is not strict enough and untrusted data is executed as code. If untrusted data is concatenated into strings and passed to these apis, it is easy to create a security risk that must be avoided.

Hr side

  • Introduce yourself
  • Are you dating someone? Will you be in the same city or different places in the future?
  • Can you handle working till ten o ‘clock at night? How late do you study and work?
  • What are your career plans for the future?
  • Do you have any other offers?
  • .

Refer to the article

  • Why IS HTTP/3 Based on UDP reliable?

  • Front-end Security Series 1: How to Prevent XSS Attacks?

Write in the last

Thank you for reading. I will continue to share more excellent articles with you. If there are any mistakes or omissions, I hope you can correct them.