Story happened in a very light in the morning, serious of small firm was sitting in his computer, eyes blurred, because this morning to make a video and bit company side, nervous didn’t sleep well last night, for today’s interview and leadership also please a fake, false body uncomfortable, “god bless”, little heart prayer, After all, I’ve been preparing for this interview for a long time.

Zach stared at the time, breathing more and more tight, because there were only a few seconds left to the appointed interview time, 6,5,4,3,2,1, ding ling ling, the other party dialed the video invitation, zach accepted the invitation, “hello, I am the interviewer today”, “hello, hello” zach hurriedly answered.

Interviewer: Why don’t you introduce yourself first? Zach: Hi, my name is Zach. I graduated from…

Database article

Interviewer: I see your resume says that you are familiar with MySQL. Let me ask you about MySQL first.

Zach: Ok.

Interviewer: Now there is a grade table. The structure of the table is as follows. Please count the names and average grades of the students whose average grade is above 80.Zach :(I go, first directly write SQL…) Having a group by, having a group by, having a group by, having a group by

select name,avg(score) as avgScore from grade having avgScore>80 group by name
Copy the code

The interviewer takes a look at SQL and says, “What engine do you use?” Interviewer: What’s the difference between InndoDB and Myisam? Zach :(as expected, I usually read a lot of eight-part essay.)

  1. InndoDB is transaction supported, Myisam is not
  2. InnoDB supports foreign keys, while Myisam does not
  3. InnoDB’s data is stored in the leaf of the B+ tree, whereas Myisam’s leaf only stores Pointers to data

Interviewer: Wait, I’m going to interrupt. Index, can you explain a little bit more clearly here, like how clustered indexes and non-clustered indexes are stored? Small firm: Here is that for InnoDB, its clustered index leaf node is the entire line of data, rather than a clustered index of the leaf node is the primary key id, so do not check on the non clustered index field needs by id back to the table, and Myisam is not clustered index, said the primary key id index and average index, The leaf node does not store the entire row or the primary key ID, but rather the pointer to the row, so there is no return to the table in Myisam through the normal index. Interviewer: Go ahead. Zach: Ok, InnoDB does not store the exact number of rows in a table, such as a full table scan when performing select count(*) from table. Myisam uses a variable to hold the number of rows in the entire table, which can be read quickly. Interviewer: For Myisam, if I execute a SQL, it does a full table scan?

select count(*) from xx where name=xx
Copy the code

If name does not have an index, then the index of the whole table will be scanned. If name has an index, the index of the whole table will be scanned. Interviewer: Is InnoDB always full table sweep? Zach: Not necessarily. In some cases, MySQL may choose to overwrite an index. Interviewer: So why would MySQL choose to overwrite an index? Zach: When overwriting an index, you only need to store the index field itself and the primary key ID value, so more rows can be stored on the same page, so fewer pages can be scanned and faster. Interviewer: Are there any other differences between the two storage engines? InnoDB supports table and row locking, while MyISAM supports table locking. InnoDB tables must have a primary key. If no primary key is set, InnoDB tables will try to find a unique index in the table as the primary key. If no unique index is set, then a row_ID is used as the primary key by default, while Myisam can have no primary key. Interviewer: Can you tell me why myISam is not available? Zach: As mentioned earlier, for MyISam, the primary key index is not very different from the normal index. The leaf node isa pointer to the whole row of data. This can be seen from the storage file:

  1. Innodb: two files, FRM is a table definition file, IBD is a data file
  2. Myisam: three files, FRM isa table definition file, myd isa data file, myi is an index file.

That’s about all the difference.

Interviewer: Is that all? InnoDB does not support full-text indexing, while Myisam does. Zach :(nim, I don’t know if this is true), this is like this, after version 5.6 InnoDB storage engine started to support full-text index, after version 5.7 InnoDB storage engine started to support Chinese through the use of the ngram plugin, so for the higher version of InnoDB engine MySQL, it supports full-text index. (This is the time, still asking the difference, MyISam is almost eliminated, I XXX)

Interviewer :(ok, then blast him to see), know query cache?

Zach: Yes, some executed statements and their results may be cached directly in memory as key-value pairs. Key is the query statement, value is the query result, so that when the same SQL query, if there is a cache, can be obtained from the cache.

Interviewer: Did you know that MySQL8.0 deprecated this module? Isn’t the query cache good? Why scrap it?

Zach: This is a good point to understand, because for some tables that update frequently, the query cache is too easy to invalidate. For example, if you have just cached a data, the cache may be kicked out because of the next query, and then a cache operation is wasted.

Interviewer: Can you tell me when you need a vertical scale and when you need a horizontal scale?

Small firm: If a table field a lot, and there are some types of text fields, for example, suggest to be spun off, some fields are often queries not parsing overhead, bandwidth overhead, which is perpendicular to the table, the table for level a list that is more and more data, suggest points a few tables, it won’t because a table is more and more big result in slow query.

Network article

Interview :(ok, database first don’t ask), next I test your network related knowledge. Zach :(come on! Who’s afraid of who) Ok, ok.

Interviewer: What is the difference between GET and HEAD in AN HTTP request?

Zach :(I don’t follow the rules, usually GET and POST, treacherous! A HEAD request only needs to respond to the header, and its HTTP header contains the same information as a GET request. With this approach, rather than transferring the entire content of the resource, the HEAD method is typically used to test whether the hyperlink is valid, accessible, recently updated, and so on.Interviewer: Tell me the difference between a cookie and a session.

Small firm: Session is stored on the server, while cookie is stored on the client browser. By default, session is stored in a file on the server, not in memory. Of course, session can also be stored in a file, database, or memory. The session depends on the session ID, and the session ID is stored in the cookie. That is, if the browser disables the cookie, the session will also be invalid, but it can be implemented in other ways. For example, passing session_id in the URL.

Interviewer: tell me, what are the HTTP status codes 401,301,302,201,304?

Zach: what do you mean, who can remember all this? ) really want to ask you, I think ha, 401 is the request to authentication, the need to log in to the web page, the server may return this response, 301 is a permanent redirect, 302 is a temporary redirect, 304 is the client cache, such as a static resource hasn’t changed, may return 304, (201, what the heck is a muddle through first). That’s about it.

Interviewer: HMM, 201 didn’t say.

Zach :(did not expect this bald three, still quite serious), 201 ~. I have to confess, I will ask him to see if he is pretending to be X.

Interviewer: HTTP status 201, as the result of an HTTP POST request, indicates that one or more new resources have been successfully created on the server, okay?

Zach: Oh, oh, I get it. Big ass.

Interviewer: Ok, moving on, do you know what HTTP keep-alive stands for?

Small firm: In the early days of HTTP, every HTTP request required a TCP connection to be opened and then disconnected after being used once. With keep-alive, a TCP connection generated by HTTP was opened after the last response. You also need to wait a certain timeout seconds before starting to close the connection.

Interviewer: What’s the difference between TCP and UDP?

Zach: A TCP connection requires three handshakes and a disconnection requires four waves. Udp does not. TCP guarantees data correctness, udp packet loss.

Interviewer: So udp is so unreliable that there are no application scenarios?

Zach: No, no, like QQ chat, online video, voice over Internet (VOIP) and so on, it requires high efficiency, but it can tolerate data loss occasionally. It should be able to use UDP protocol.

Interviewer: You mentioned TCP four waves. Can you specify which four waves?

Zach: Ok, let me draw a picture

First: Initiates the disconnection. The other party sends a FIN packet, as if to say, “Hello, I’m ready to disconnect.” Second: After receiving the FIN, the receiver replies with an ACK packet, as if to say, “OK, got it”, and sends the processed data to the peer end. Third: the receiving party after finish data processing, also send a FIN bag to take the initiative to disconnect the side, as if said: “the opposite, my side has finished processing, you break it, I don’t receive you send to the data of the” fourth: active fault prescribing received on the FIN bag, ACK, at the same time wait for TIME_WAIT time. Interviewer: What is TIME_WAIT for? How long is TIME_WAIT? Zach: TIME_WAIT is the last state to enter after the active breaker is closed. TIME_WAIT is 2MSL, where one MSL is the maximum lifetime of a packet. Interviewer: Then why are there two MSLS here? Small firm: After the active breaker sends the last ACK, if the ACK has not reached the peer and the connection has not been properly disconnected, the peer will retry, that is, the peer will send another FIN packet. Therefore, 2MSL is the time for the active breaker to send the last ACK packet + the time for the peer end to resend the FIN packet, ensuring the shortest time for a return trip.

redis

Interviewer: Do you usually use a lot of cache? Zach: Not bad. I can use some. Interviewer: What do you use for caching? Interviewer: So, what types of redis do you support? Interviewer: What data structure is underneath a string? Zach: SDS dynamic string, like when we do set key value, key corresponds to an SDS structure, value corresponds to an SDS structure. Its structure is roughly as follows:

struct sdshdr {
    int len;
    int free;
    char buf[];
};
Copy the code

Free represents how much space SDS has left, len represents the length of the string, and BUf is the actual stored value. Interviewer: What are the advantages of such a design? Zach: In order to avoid the overhead of memory application caused by the constant modification of the key, SDS will apply for more space every time when the space is insufficient, usually twice as much. In this way, when the next change is made, there is no need to apply for memory from the system if there is still space left. Interviewer: Do you usually use Redis as message queue? Zach: Not much. Some scenarios with less stringent requirements on data security will use some, because the Redis list cannot guarantee data loss. Interviewer: What else should I consider when using a list for message queues, if not for loss? Zach: It is best not to share a cluster with business Redis, because if there is a problem with the message queue, such as a consumer hanging, then in the case of a high volume of messages, the memory will go straight online, which may affect other businesses. Zach: There are two main redis persistence schemes: RDB and AOF. RDB stores binary format and recovery is fast, while AOF stores executed statements. Interviewer: Since AOF stores executed statements, will that cause aOF to get bigger and bigger? For example, if I execute incr num 100 times, is it really the same as set num 100? Zach: AOF will get bigger and bigger. The number of changes to the same key will be recorded as many times as possible. To solve this problem, AOF will be rewritten when the file size reaches a certain level. Interviewer: How was this rewritten? Do you analyze existing AOF files directly? Small firm: No, in fact, there is no need to analyze the existing AOF, but directly read the library scan, for example, we will start from library 0, and write the data into a new AOF file. For example, for string data, we can directly record a set key value, regardless of how many times the key changes during the process. Of course, not all data can be replaced by a single command, such as sadd, which can add up to 64 data at a time. If more than 64 data can be added in batches.

sadd key 1 2.64
sadd key 65 66. .Copy the code

Interviewer: What about the new commands during the rewrite process? Student: Just write the new Aof? Small firm: no, it takes time to rewrite, so still use the old aof before rewriting to complete, so the new command will write old aof, will also write a rewrite buffer, after finished rewriting, then rewrite the buffer data to new aof files, or rename new aof, atomic aof covering the old. Interviewer: Wait, wait, wait, wait, wait, wait, wait, wait, wait, wait, wait, wait, wait, wait, wait, wait, wait, wait, wait, wait, wait, wait, wait, wait. Zach: Let me be more specific, here’s what happens. First, the override is handled by the child process. After the override is complete, the child process tells the main process that the main process will block when it receives a notification, and no new commands will be written.

linux

Interviewer: So what is orphan progress and what is zombie progress? Well, an orphan process is one of the parent processes that exits while one or more of its children are still running. Those children become orphan processes, which are adopted by init (process number 1) and collected from them. A zombie process is a process that forks its child. If the child exits and the parent does not call wait or waitPID to retrieve the child’s status, the child’s process descriptor remains in the system. This process is called rigor mortis. Interviewer: How do I check the usage of a port? Interviewer: How do I check the CPU load? Interviewer: How do I check the current disk load? Interviewer: What is the difference between a signal and a semaphore? Small firm: Signals and the quantity is two things, the signal is sent to the target by the user, system, or process information, to notify the target process is a state change or a system exception, common is the KILL signal, a semaphore is to deal with the mechanism of synchronous mutex inter-process communication, it is the nature of the counter, semaphore recorded the number of critical resources inside, how many number, The value of the semaphore is whatever the process accesses atomic operations.

algorithm

The interviewer looked at the time tactfully and thought, “Let’s do an algorithm.” Zach :(here comes the big one, calm down, I take a deep breath) okay. Now, given an array of prices, the ith element prices[I] represents the price of a given stock on the ith day. You can only choose to buy the stock on a certain day and sell it on a different day in the future. Design an algorithm to calculate the maximum profit you can make. If prices=[7,1,5,3,6,4], then buy on day 2 (prices= 1) and sell on day 5 (prices= 6), the maximum profit = 6-1 = 5: (pretended to calm ~), good, understand the (this nima yesterday I not just brush to you, lucky ~) interviewer: remind, you don’t use brute force method, two traverse is too simple, see if there are any other ideas. Zach: Ok, I get it.

Memories in your mind at the moment of small firm hard “to find the solution to this problem in is to find a rule, what is this?”, however at this time the tension make small unable to concentrate, and the interviewer seems very anxious appearance make the atmosphere more nervous, “one ~ ~” beverage cooled guru ~, quiet atmosphere let little he heard the voice of the interviewer feel hungry, “the nima, This interviewer must be in a hurry to eat ah, I guess I don’t have much time, I have to think quickly. The minutes tick by, and suddenly, two minutes later, the interviewer says, “Is this shit over? It’s only been a few minutes, Ash.” “To give you a hint, if maximum profit equals maximum minus minimum, think of it that way,” the interviewer said. After hearing the interviewer’s hint, Zach suddenly thought ~.

The core idea is to buy at the lowest price and sell at the highest price to get the maximum profit, but after finding the lowest price, it also depends on the day after the lowest price to sell, is bigger than the previous profit. For example, in step 4 above, although 1 is the lowest, it is clear that 3-1 is less than 5-2, so in step 4, the maximum profit is still 3.

So the first step to solve the problem is to need a variable to save the lowest purchase price and a variable to save the current maximum profit, and then run through successively. As long as there is a situation where the difference between the current selling price and the lowest purchase price is greater than the current maximum profit, the profit obtained by selling at this time must be the maximum.

Just find the lowest purchase price and run through it

func maxProfit(prices []int) int {
	minPrice := prices[0]
	for i := 1; i < len(prices); i++ {
		if prices[i] < minPrice {
			minPrice = prices[i]
		}
	}
}
Copy the code

So the next step is to calculate the profit, which is found to maximize profit selling price, if the current selling price is lower than the lowest price, then skip and don’t have to calculate profit (because in front of the minimum value minus any value affirmation is a negative number), if the current selling price is the lowest price is high, then the lowest price to buy and cut once, And then compare that with the current profit to see who has the most profit, so the code should end up like this:

func maxProfit(prices []int) int {
	minPrice := prices[0] // Assume that the minimum purchase price is the first element
	maxProfit := 0        // Maximum profit
	for i := 1; i < len(prices); i++ {
		if prices[i] < minPrice {
			minPrice = prices[i] // Minimum purchase price
		} else if prices[i]-minPrice > maxProfit {
			maxProfit = prices[i] - minPrice// Maximum profit}}return maxProfit
}
Copy the code

“Big guy, I wrote it,” confident Zach said to the interviewer, at this time zach was very proud, he felt like a star.

The interviewer looks at Zach’s code and says, “Call it a day. Hr will get back to you.”

The last

And we reveal in advance, The small side has passed the wechat search [pretend to understand programming], please look forward to the small students beat the second side (more brutal)

  • Internal work greatly increased! Look at IO from the structure of mechanical hard drives and solid-state drives
  • Have you ever stumbled on MySQL order by
  • Memory management: programs load those things