Read more about the company's interview materials before the interview, which will be very helpful for subsequent interviews. Today I will share with you 15 real Shopee server interview questions (with answer analysis). Come and see what your level is. I hope it can help you!
1. Sort the linked list
Given you the head node of the linked list, please sort it in ascending order and return the sorted linked list.
Example 1:
输入:head = [4,2,1,3]
输出:[1,2,3,4]
Copy after login
Example 2:
输入:head = [-1,5,3,4,0]
输出:[-1,0,3,4,5]
Copy after login
This question can use double The pointer merge sorting algorithm is solved by the following four steps
1. Fast and slow pointer method, traverse the linked list to find the intermediate node
2. The intermediate node cuts off the linked list
3. Use respectively Merge sort left and right sub-linked lists
4. Merge sub-linked lists
The complete code is as follows:
class Solution {
public ListNode sortList(ListNode head) {
//如果链表为空,或者只有一个节点,直接返回即可,不用排序
if (head == null || head.next == null)
return head;
//快慢指针移动,以寻找到中间节点
ListNode slow = head;
ListNode fast = head;
while(fast.next!=null && fast.next.next !=null){
fast = fast.next.next;
slow = slow.next;
}
//找到中间节点,slow节点的next指针,指向mid
ListNode mid = slow.next;
//切断链表
slow.next = null;
//排序左子链表
ListNode left = sortList(head);
//排序左子链表
ListNode right = sortList(mid);
//合并链表
return merge(left,right);
}
public ListNode merge(ListNode left, ListNode right) {
ListNode head = new ListNode(0);
ListNode temp = head;
while (left != null && right != null) {
if (left.val <= right.val) {
temp.next = left;
left = left.next;
} else {
temp.next = right;
right = right.next;
}
temp = temp.next;
}
if (left != null) {
temp.next = left;
} else if (right != null) {
temp.next = right;
}
return head.next;
}
}
Copy after login
2. The difference between symmetric and asymmetric encryption algorithms
Let’s review the relevant concepts first:
Clear text: refers to information/data that has not been encrypted.
Ciphertext: After the plaintext is encrypted by the encryption algorithm, it will become ciphertext to ensure data security.
Key: is a parameter that is entered in the algorithm that converts plaintext to ciphertext or ciphertext to plaintext. Keys are divided into symmetric keys and asymmetric keys.
Encryption: The process of turning plaintext into ciphertext.
Decryption: The process of restoring ciphertext to plaintext.
Symmetric encryption algorithm: An encryption algorithm that uses the same key for encryption and decryption. Common symmetric encryption algorithms include AES, 3DES, DES, RC5, RC6, etc.
Asymmetric encryption algorithm: Asymmetric encryption algorithm requires two keys (public key and private key). Public keys and private keys exist in pairs. If the public key is used to encrypt data, only the corresponding private key can decrypt it. The main asymmetric encryption algorithms are: RSA, Elgamal, DSA, D-H, ECC.
3. How does TCP ensure reliability
First of all, TCP connection is based on three-way handshake. And disconnection is four waves. Ensure reliable connection and disconnection.
Secondly, the reliability of TCP is also reflected in the state; TCP will record which data is sent, which data is accepted, and which is not accepted, and ensures that the data packets are in order Arrival to ensure that there are no errors in data transmission.
Thirdly, the reliability of TCP is also reflected in its controllability. It has mechanisms such as message verification, ACK response, timeout retransmission (sender), out-of-sequence data retransmission (receiver), discarding duplicate data, flow control (sliding window) and congestion control.
4. Let’s talk about the five IO models
##4.1 Blocking IO model
Assume that the application process initiates an IO call, but if the kernel data is not ready yet, the application process will be blocked and waiting until the kernel data is ready and copied from the kernel to the user space. Returning a successful prompt, this IO operation is called blocking IO.
4.2 Non-blocking IO model
If the kernel data is not ready yet, you can return an error first The information is given to the user process so that it does not need to wait, but requests again through polling. This is non-blocking IO. The flow chart is as follows:
##4.3 IO multiplexing model
IO multiplexing select
The application process can monitor multiple fds at the same time by calling the select function. In the fd monitored by the select function, as long as any data status is ready , the select function will return to the readable state, and then the application process will initiate a recvfrom request to read the data.
select has several disadvantages:
The maximum number of connections is limited, generally 1024 on Linux systems.
After the select function returns, the ready descriptor fd is found by traversing fdset.
IO multiplexing epoll
In order to solve the problems of select, the multiplexing model epoll was born, which is event-driven To implement, the flow chart is as follows:
epoll first registers an fd (file descriptor) through epoll_ctl(). Once a certain fd is ready, the kernel will use a callback mechanism to quickly activate the fd. When the process calls epoll_wait(), it will be notified. The tricky operation of traversing file descriptors is removed here, and a mechanism of listening for event callbacks is used. This is the highlight of epoll.
4.4 Signal-driven model of IO model
Signal-driven IO no longer uses active inquiry to confirm whether the data is ready, but to The kernel sends a signal (a SIGIO signal is established when calling sigaction), and then the application user process can do other things without blocking. When the kernel data is ready, the application process is notified through the SIGIO signal that the data is ready for readability. After the application user process receives the signal, it immediately calls recvfrom to read the data.
4.5 IO model of asynchronous IO (AIO)
AIO realizes the non-linearization of the entire IO process Blocking means that after the application process issues a system call, it returns immediately, but what is returned immediately is not the processing result, but something like a successful submission. When the kernel data is ready, copy the data to the user process buffer, and send a signal to notify the user process that the IO operation is completed.
The process is as follows:
5. Hystrix working principle
Hystrix workflow chart is as follows:
1. Build command
Hystrix provides two command objects: HystrixCommand and HystrixObservableCommand, which will represent one of your dependency request tasks and pass it into the constructor Parameters required to request dependencies.
2. Execute commands
There are four ways to execute Hystrix commands. They are:
R execute(): synchronous blocking execution, receiving a single response from the dependent request.
Future queue(): Asynchronous execution, returns a Future object containing a single response.
Observable observe(): After creating an Observable, it will subscribe to the Observable and return the Observable object representing the response from the dependent request
Observable toObservable() : cold observable, returns an Observable, Hystrix commands will only be executed when subscribing, and multiple results can be returned
3. Check whether the response is cached
If enabled Hystrix cache, before task execution, it will first determine whether there is a cache for executing the same command. If there is, the Observable containing the cached response will be returned directly; if there is no cached result but caching is enabled, the execution result will be cached for subsequent use.
4. Check whether the circuit breaker is open. The circuit breaker (circuit-breaker) is similar to a fuse. The fuse will burn out to protect the circuit when danger occurs, while the circuit breaker can open the circuit when it reaches the threshold we set. Trigger a short circuit (for example, the request failure rate reaches 50%) and refuse to execute any request.
If the looper is opened, Hystrix will not execute the command and directly enter the Fallback processing logic.
5. Check the thread pool/semaphore/queue situation. Hystrix isolation methods include thread pool isolation and semaphore isolation. When using the Hystrix thread pool, Hystrix allocates 10 threads to each dependent service by default. When all 10 threads are busy, the execution of the command will be refused, and instead it will immediately jump to the execution of fallback logic.
6. Perform specific tasks. Use HystrixObservableCommand.construct() or HystrixCommand.run() to run the user's real tasks.
7. Calculate the loop health. Every time a command starts to be executed, ends to execute a command, or an exception occurs, the execution status will be recorded, such as: success, failure, rejection, timeout and other indicators, and these will be processed regularly. data, and then determine whether to open the looper according to the set conditions.
8. Execute Fallback logic when the command fails. Execute the user-specified Fallback logic when the command fails. In the above figure, circuit breaking, thread pool rejection, semaphore rejection, execution execution, and execution timeout will all enter Fallback processing.
9. Return the execution result. The original object result will be returned in the form of Observable. Before being returned to the user, some processing will be done depending on the calling method.
6. Delay scenario processing
In daily development, we often encounter this kind of business scenario, such as: if a takeout order is not paid for more than 30 minutes, it will be automatically canceled. Order; 15 minutes after the user successfully registers, a text message will be sent to notify the user, etc. This is the delayed task processing scenario. We mainly have the following solutions for such scenarios:
JDK's DelayQueue delay queue
Time wheel algorithm
Database scheduled tasks (such as Quartz)
Redis ZSet implementation
MQ delay queue implementation
7.https request process
HTTPS = HTTP SSL/TLS, that is, using SSL/TLS to encrypt and decrypt data , HTTP for transmission.
SSL, or Secure Sockets Layer, is a security protocol that provides security and data integrity for network communications.
TLS, Transport Layer Security (Secure Transport Layer Protocol), is a subsequent version of SSL 3.0.
http request process
1. The user enters an https URL in the browser, and then connects to the 443 port of the server.
2. The server must have a set of digital certificates. It can be made by itself or applied to the organization. The difference is that the certificate issued by itself needs to be verified by the client. This set of certificates is actually a pair of public and private keys.
3. The server sends its own digital certificate (containing public key) to the client.
4. After the client receives the digital certificate from the server, it will check it. If it fails, a warning box will pop up. If the certificate is OK, a key is generated (symmetric encryption) and encrypted with the certificate's public key.
5. The client will initiate a second HTTP request in HTTPS and send the encrypted client key to the server.
6. After the server receives the ciphertext from the client, it will use its own private key to asymmetrically decrypt it. After decryption, it will obtain the client key, and then use the client key pair to return the data. Perform symmetric encryption so that the data becomes ciphertext.
7. The server returns the encrypted ciphertext to the client.
8. The client receives the ciphertext returned by the server, uses its own key (client key) to symmetrically decrypt it, and obtains the data returned by the server.
8. Let’s talk about the transaction isolation level and the implementation principle of repeatable read
##8.1 The four major isolation levels of the database
In order to solve the problems of
dirty reading, non-repeatable reading, and phantom reading in concurrent transactions, the database uncle designed four isolation levels. They are Read uncommitted, Read committed, Repeatable read, Serializable.
Read uncommitted isolation level: It only limits that two data cannot be modified at the same time. However, when the data is modified, even if the transaction is not committed, it can be read by other transactions. , this level of transaction isolation has problems with dirty reads, repeated reads, and phantom reads;
Read committed isolation level: The current transaction can only read data submitted by other transactions, so This transaction isolation level solves the problem of dirty reads, but there will still be problems of repeated reads and phantom reads;
Repeatable reads: When reading data is restricted, it cannot be performed Modification, so the problem of repeated reading is solved, but when reading range data, data can be inserted, so there will still be a phantom reading problem;
Serialization: the highest transaction Isolation level, at which all transactions are executed serially. It can avoid all concurrency problems of dirty reads, non-repeatable reads and phantom reads. However, under this transaction isolation level, transaction execution is very performance-intensive.
What are the concurrency problems among the four isolation levels?
Isolation level
Dirty read
Non-repeatable read
Phantom read
Read Uncommitted
√
√
√
Read Submitted
×
√
√
Repeatable read
×
×
√
##Serialization
×
×
×
8.2 Read View Visibility Rules
##Variables
Description
m_ids
The active (uncommitted) read and write transaction IDs in the current system, its data structure is a List.
max_limit_id
Indicates the id value that should be assigned to the next transaction in the system when a Read View is generated.
min_limit_id
Indicates the smallest transaction id among the active read and write transactions in the current system when the Read View is generated, that is, the minimum value in m_ids.
creator_trx_id
Create the transaction ID of the current Read View
The visibility rules of Read View are as follows:
If the data transaction ID trx_id < min_limit_id, it indicates that the transaction that generated this version is generating Read Before View, it has been submitted (because the transaction ID is incremented), so this version can be accessed by the current transaction.
If trx_id>= max_limit_id, it indicates that the transaction that generated this version was generated after Read View was generated, so this version cannot be Current transaction access.
Ifmin_limit_id =<trx_id< max_limit_id, it needs to be discussed in 3 situations
1) If m_ids contains trx_id, it represents the time when Read View is generated. This transaction has not yet been submitted, but if the trx_id of the data is equal to creator_trx_id indicates that the data is generated by itself, so it is visible.
2) If m_ids contains trx_id, and trx_id is not equal to creator_trx_id, then Read ViewWhen generated, the transaction is not submitted and is not produced by itself, so the current transaction is also invisible;
3) If m_ids does not contain trx_id, then It means that your transaction has been submitted before Read View is generated, and the result of the modification can be seen by the current transaction.
8.3 Principle of Repeatable Read Implementation
The database achieves isolation level through locking. For example, if you want to be alone, To be quiet and not be disturbed by others, you can lock yourself in the house and add a lock on the door! The serialization isolation level is implemented by locking. But if you lock frequently, performance will decrease. So the uncle who designed the database thought of MVCC.
The implementation principle of repeatable reading is MVCC multi-version concurrency control. Within the scope of a transaction, two identical queries read the same record, but return different data. This is non-repeatable reading. The repeatable read isolation level is to solve the non-repeatable read problem.
Querying a record based on MVCC, what is the process?
Get the version number of the transaction, that is, the transaction ID
Get Read View
Query The obtained data is then compared with the transaction version number in Read View.
If the visibility rules of Read View are not met, the historical snapshot in Undo log is needed;
Finally return the data that meets the rules
InnoDB implements MVCC, which is implemented through Read View Undo Log, Undo Log saves historical snapshots,Read ViewVisibility rules help determine whether the current version of data is visible.
Repeatable Read (RR) isolation level, how to solve the problem of non-repeatable read?
Assuming that there are transactions A and B, the SQL execution process is as follows
Under the repeatable read (RR) isolation level, a transaction will only be obtained once read view are shared by the replicas, ensuring that the data in each query is the same.
Assume that there is currently a core_user table and insert an initialization data as follows:
##Based on MVCC, let’s take a look at the execution process 1. A opens a transaction and first gets a transaction ID of 1002. B opens a transaction and gets a transaction ID of 1013. Transaction A generates a Read View and the value corresponding to the read view as follows
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn