
Hi! My name is Nhut Nguyen. I am a software engineer and a writer in Copenhagen, Denmark.
Learn more about me at nhutnguyen.com
Search for a command to run...

Hi! My name is Nhut Nguyen. I am a software engineer and a writer in Copenhagen, Denmark.
Learn more about me at nhutnguyen.com
No comments yet. Be the first to comment.
A simple example of using C++ switch

Two dynamic programming techniques to solve Leetcode 120. Triangle. One has space complexity O(n^2). The other is O(n).

An example of using a sliding window approach and an unordered map to track character positions

A simple C++ solution to Leetcode 1695. Maximum Erasure Value using a sliding window approach and prefix sums.

Strategies to avoid them will help you excel in your following technical interview

Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.)

Input: head = [1,2,3,4]
Output: [2,1,4,3]
Input: head = []
Output: []
Input: head = [1]
Output: [1]
The number of nodes in the list is in the range [0, 100].
0 <= Node.val <= 100.
Draw a picture of the swapping to identify the correct order of the update.

Denote (cur, next) the pair of nodes you want to swap and prev be the previous node that links to cur. Here are the steps you need to perform for the swapping.
Update the links between nodes.
Go to the next pair.
#include <iostream>
struct ListNode {
int val;
ListNode *next;
ListNode() : val(0), next(nullptr) {}
ListNode(int x) : val(x), next(nullptr) {}
ListNode(int x, ListNode *next) : val(x), next(next) {}
};
ListNode* swapPairs(ListNode* head) {
if (head == nullptr || head->next == nullptr) {
return head;
}
ListNode* preNode = nullptr;
ListNode* curNode = head;
ListNode* nextNode = head->next;
head = nextNode;
while (curNode != nullptr && nextNode != nullptr) {
curNode->next = nextNode->next;
nextNode->next = curNode;
if (preNode) {
preNode->next = nextNode;
}
preNode = curNode;
curNode = curNode->next;
if (curNode) {
nextNode = curNode->next;
}
}
return head;
}
void print(ListNode* head) {
ListNode* node = head;
std::cout << "[";
while (node != nullptr) {
std::cout << node->val << ",";
node = node->next;
}
std::cout << "]" << std::endl;
}
int main() {
ListNode four(4);
ListNode three(3, &four);
ListNode two(2, &three);
ListNode one(1, &two);
print(swapPairs(&one));
ListNode five(5);
print(swapPairs(nullptr));
print(swapPairs(&five));
}
Output:
[2,1,4,3,]
[]
[5,]
Runtime: O(N), where N is the number of nodes.
Extra space: O(1).
Thanks for reading. Feel free to share your thought about my content and check out my FREE book “10 Classic Coding Challenges”.