DEV Community

Andrew
Andrew

Posted on

2nd Week - Algorithms

5. Merge Two Sorted Lists (Easy)

πŸ”— Problem Link

🧱 Context:

  • Written in C++.
  • Merges two sorted singly linked lists into a new sorted list.
  • A singly linked list is a structure where each node holds a value (val) and a pointer to the next node (next).

🧩 ListNode Structure

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) {}
};
Enter fullscreen mode Exit fullscreen mode
  • val: value of the node
  • next: pointer to the next node

Three constructors:

  1. Default: val = 0, next = nullptr
  2. With value only
  3. With value and next node pointer

🧠 Solution Class

class Solution {
public:
Enter fullscreen mode Exit fullscreen mode
  • Class for our solution
  • public: means the method is accessible externally

πŸ”§ mergeTwoLists Method

ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {
Enter fullscreen mode Exit fullscreen mode
  • Takes two pointers to sorted lists
  • Returns pointer to a new merged sorted list

🧱 Step 1: Create dummy starting node

ListNode* dummyHead = new ListNode();
Enter fullscreen mode Exit fullscreen mode

Used as a fake starting point to simplify appending new nodes.


πŸ“ Step 2: Create traversal pointer

ListNode* current = dummyHead;
Enter fullscreen mode Exit fullscreen mode

current moves along the new list.


πŸ”„ Step 3: While both lists aren't finished

while (list1 && list2) {
Enter fullscreen mode Exit fullscreen mode

Continue while both lists have nodes.


πŸ” Step 4: Compare values

if (list1->val <= list2->val) {
Enter fullscreen mode Exit fullscreen mode

Choose the smaller value.


➑️ Step 5: Append from list1

current->next = list1;
list1 = list1->next;
Enter fullscreen mode Exit fullscreen mode

πŸ” Otherwise, take from list2

} else {
    current->next = list2;
    list2 = list2->next;
}
Enter fullscreen mode Exit fullscreen mode

🧭 Step 6: Move forward in the new list

current = current->next;
Enter fullscreen mode Exit fullscreen mode

πŸ”š Step 7: Attach remaining nodes

current->next = list1 ? list1 : list2;
Enter fullscreen mode Exit fullscreen mode

🏁 Step 8: Return the merged list

return dummyHead->next;
Enter fullscreen mode Exit fullscreen mode

Return the first real node (skip dummy).


βœ… Summary:

  1. Create a dummy node
  2. Traverse both lists
  3. Choose the smaller node each time
  4. Attach the rest when one list ends
  5. Return merged result

6. Reverse Linked List (Easy)

πŸ”— Problem Link


πŸ”Ή ListNode Structure

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) {}
};
Enter fullscreen mode Exit fullscreen mode

πŸŒ€ reverseList Function

ListNode* reverseList(ListNode* head) {
Enter fullscreen mode Exit fullscreen mode
  • Input: pointer to start of the list
  • Output: pointer to start of reversed list

Steps:

  1. Create dummy head
ListNode* dummy = new ListNode();
Enter fullscreen mode Exit fullscreen mode
  1. Pointer for traversal
ListNode* current = head;
Enter fullscreen mode Exit fullscreen mode
  1. Loop through list
while (current != nullptr) {
Enter fullscreen mode Exit fullscreen mode
  1. Save the next node
ListNode* nextNode = current->next;
Enter fullscreen mode Exit fullscreen mode
  1. Reverse pointer
current->next = dummy->next;
Enter fullscreen mode Exit fullscreen mode
  1. Insert at start of new list
dummy->next = current;
Enter fullscreen mode Exit fullscreen mode
  1. Move to next
current = nextNode;
Enter fullscreen mode Exit fullscreen mode
  1. Return reversed list
return dummy->next;
Enter fullscreen mode Exit fullscreen mode

🧩 Visual Walkthrough

Original:

head β†’ 1 β†’ 2 β†’ 3 β†’ 4 β†’ nullptr
Enter fullscreen mode Exit fullscreen mode

After iterations:

dummy β†’ 1
dummy β†’ 2 β†’ 1
dummy β†’ 3 β†’ 2 β†’ 1
dummy β†’ 4 β†’ 3 β†’ 2 β†’ 1
Enter fullscreen mode Exit fullscreen mode

🟑 Recap:

  1. Create empty list
  2. Take nodes one by one from original
  3. Insert at beginning of new list
  4. Return result

7. Linked List Cycle (Easy)

πŸ”— Problem Link


πŸ“¦ Node Structure

struct ListNode {
    int value;
    ListNode *next;
    ListNode(int x) : value(x), next(nullptr) {}
};
Enter fullscreen mode Exit fullscreen mode

🧠 Cycle Detection (hasCycle)

bool hasCycle(ListNode *head) {
Enter fullscreen mode Exit fullscreen mode

πŸ’πŸ‡ Use two pointers:

ListNode *slowPointer = head;
ListNode *fastPointer = head;
Enter fullscreen mode Exit fullscreen mode
  • slowPointer moves 1 step
  • fastPointer moves 2 steps

πŸ” Traverse the list

while (fastPointer && fastPointer->next) {
    slowPointer = slowPointer->next;
    fastPointer = fastPointer->next->next;
Enter fullscreen mode Exit fullscreen mode

If they meet:

if (slowPointer == fastPointer)
    return true;
Enter fullscreen mode Exit fullscreen mode

No cycle?

return false;
Enter fullscreen mode Exit fullscreen mode

πŸ“Š Visual

Without cycle:

1 β†’ 2 β†’ 3 β†’ 4 β†’ nullptr
Enter fullscreen mode Exit fullscreen mode

With cycle:

1 β†’ 2 β†’ 3 β†’ 4
          ↑
          ↓
          2 (loop)
Enter fullscreen mode Exit fullscreen mode

🧩 Summary:

  • Two pointers moving at different speeds
  • If cycle exists β†’ they'll meet
  • If not β†’ fast pointer hits end

8. Maximum Subarray (Medium)

πŸ”— Problem Link


πŸ“¦ The Problem:

Given an array, find the maximum sum of any continuous subarray.

Example:
Input: [-2, 1, -3, 4, -1, 2, 1, -5, 4]
Output: 6 β†’ from [4, -1, 2, 1]


🧠 Kadane’s Algorithm

int maxSubArray(vector<int>& nums) {
Enter fullscreen mode Exit fullscreen mode

πŸ”Ή Step 1: Initialize max values

int currentMax = nums[0];
int globalMax = nums[0];
Enter fullscreen mode Exit fullscreen mode

πŸ” Step 2: Iterate

for (int i = 1; i < nums.size(); ++i) {
    currentMax = std::max(currentMax, 0) + nums[i];
    globalMax = std::max(globalMax, currentMax);
}
Enter fullscreen mode Exit fullscreen mode

βœ… Step 3: Return result

return globalMax;
Enter fullscreen mode Exit fullscreen mode

🧩 Example Breakdown

i nums[i] currentMax globalMax
0 -2 -2 -2
1 1 1 1
2 -3 -2 1
3 4 4 4
4 -1 3 4
5 2 5 5
6 1 6 βœ… 6
7 -5 1 6
8 4 5 6

🟑 Summary:

  • currentMax: sum of current subarray
  • Reset to 0 if it turns negative
  • globalMax: max seen so far
  • One pass: O(n) complexity

βœ… Follow-up

If you liked this breakdown, let me know β€” I plan to continue this series with more Leetcode problems, especially in C++ with deep explanations for beginners.


Top comments (0)