Bea.AI coding blog
  • Tree
    • Tree Traverse
    • Iteration based traverse
    • Typical problems and solutions
      • Max width of binary tree
      • Binary Tree & BST Serialize & Deserialize
      • Lowest common ancestor (LCA) for Binary Tree and BST
      • Subproblem-based Approach for Resolving Max Value on Trees
      • Path sum III
  • Graph
  • Data structure
    • Java data structure
  • Algorithm general templates
    • Tree
    • Trie
    • Graph
  • Java Algorithm Tips and Tricks
    • Java concurrent list
  • Coding patterns & Strategies
  • Coding patterns & template
    • 1. Binary Search
    • 2. Two Pointer
    • 3. Sliding Window
    • 4. Backtracking
    • 5. DFS
    • 6. BFS
    • 7. Stack
    • 8. Heap
    • 9. Prefix Sum
    • 10. Linked List
    • 11. BST
    • 12. Line sweep
    • 14. Tree
    • 15. Graph
    • 16. Bit manipulation
    • 17. Matrix
    • 18. Monotonic Stack
    • 19. Sorting
    • 20. Union Find
    • 21. Trie
    • 22. Dynamic programming
    • 23. Customized Data Structure
  • Code interview steps
  • Leetcode
    • Tree
      • Traversal
      • Construction and Conversion
      • Search and Validation
      • Manipulation and Modification
      • Special Trees
      • Miscellaneous
    • Dynamic programing
      • Classic DP Problems
      • Sequence/Array DP
      • Matrix DP
      • Knapsack Problems
      • String DP
      • Tree/Graph DP
      • Optimization Problems
      • Combinatorial DP
    • DFS
      • Graph Traversal
      • Path Finding
      • Tree Traversal
      • Backtracking
      • Topological Sorting
      • Traversal Order
      • Dynamic Programming with DFS
      • Connected Components
    • BFS
      • Graph
      • Tree
      • Matrix
      • String
      • Others
    • Two points
      • Array
      • String
      • Linked List
      • Sorting
      • Others
    • LinkedList
      • Basic Operations
      • Cycle Detection and Handling
      • Intersection and Union
      • Partitioning and Merging
      • Palindrome
      • Miscellaneous
    • Backtracking
    • Binary Search
    • Union Find
    • Trie
    • Sort
    • Heap
    • Randomness
    • Topological sort
    • Stack
    • HashTable
    • Sliding Window
  • Blind 75
    • Array
    • Binary
    • Dynamic Programming
    • Graph
    • Interval
    • LinkedList
    • Matrix
    • String
    • Tree
    • Heap
  • Companies
    • Apple
Powered by GitBook
On this page
  • 1. Delete Node in a Linked List
  • 2. Reverse Linked List
  • 3. Remove Nth Node From End of List
  • 4. Add Two Numbers
  • 5. Merge Two Sorted Lists
  1. Leetcode
  2. LinkedList

Basic Operations

1. Delete Node in a Linked List

  1. Problem Description and Link: The problem "Delete Node in a Linked List" asks us to delete a node from a singly linked list. The input is the node that needs to be deleted, and we are not given access to the head of the linked list.

    Link: https://leetcode.com/problems/delete-node-in-a-linked-list/

  2. Optimized Java Code with Detailed Comments:

class ListNode {
    int val;
    ListNode next;
    ListNode(int x) { val = x; }
}

public class Solution {
    public void deleteNode(ListNode node) {
        // Instead of actually deleting the node, we can copy the value of the next node to the current node,
        // and then delete the next node.
        // This way, we effectively "delete" the current node by bypassing it.

        // Check if the node to be deleted is the tail of the list, in which case we cannot perform this operation.
        if (node.next == null) {
            throw new IllegalArgumentException("Cannot delete tail node");
        }

        // Copy the value of the next node to the current node
        node.val = node.next.val;

        // Delete the next node by simply skipping it
        node.next = node.next.next;
    }
}
  1. Detailed Description and Approach: In this problem, we are given a node inside a linked list, and we have to delete this node. The tricky aspect of this problem is that we do not have access to the head of the linked list, so we cannot easily remove the node by reconfiguring the pointers.

    The key observation for solving this problem is that instead of actually deleting the specified node, we can copy the value of the next node to the current node, and then delete the next node. This effectively "deletes" the current node by bypassing it.

    To implement this approach, we first check if the given node is the tail of the linked list. If it is, we cannot perform the operation because deleting the tail node requires access to the previous node.

    Next, we copy the value of the next node to the current node, thereby overwriting the value of the current node with the value of the next node. This simulates the effect of deleting the current node while preserving the structure of the linked list.

    Finally, we update the next pointer of the current node to skip the next node, effectively deleting the next node.

    During the interview, it's important to explain the thought process behind this approach. Start by recognizing that we don't have access to the head of the linked list and discuss the limitations it imposes. Then, explain how we can simulate the deletion by copying the value of the next node. Emphasize the importance of updating the pointers correctly to maintain the integrity of the linked list.

    By providing a clear explanation of the approach and walking the interviewer through the code, you can demonstrate strong problem-solving skills and a solid understanding of linked list manipulation.

2. Reverse Linked List

  1. Problem Description:

The problem "Reverse Linked List" is a fundamental problem in data structures and algorithms. Given a singly linked list, reverse the list in-place and return the head of the reversed list.

  1. Java Code:

Here is the optimized Java code solution for the problem "Reverse Linked List" with detailed comments:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode reverseList(ListNode head) {
        ListNode prev = null; // Initialize a pointer to keep track of the previous node
        ListNode curr = head; // Initialize a pointer to the current node
        
        while (curr != null) {
            ListNode nextTemp = curr.next; // Store the next node in a temporary variable
            curr.next = prev; // Reverse the link of the current node to the previous node
            prev = curr; // Move the previous node pointer to the current node
            curr = nextTemp; // Move the current node pointer to the original next node
        }
        
        return prev; // Return the head of the reversed linked list
    }
}
  1. Algorithm Description:

To reverse a linked list, we need to iterate through the original list and reverse the links of each node. We can use three pointers - prev, curr, and nextTemp - to keep track of the previous, current, and next nodes, respectively.

Initially, prev is set to null, and curr is set to the head of the original linked list. We iterate through the list until curr becomes null. In each iteration, we store the next pointer of the current node in the nextTemp variable to avoid losing the next node's reference. Then, we reverse the link of the current node by pointing its next pointer to the previous node (prev). After that, we move the prev pointer to the current node and the curr pointer to the original next node (nextTemp). This process continues until we reach the end of the original list, at which point prev will be the new head of the reversed list.

During an interview, it is important to explain the algorithm step-by-step, mentioning the purpose of each pointer and variable. Emphasize the iterative approach and demonstrate your understanding of linked list traversal and pointer manipulation.

3. Remove Nth Node From End of List

  1. Here is the optimized Java code with detailed comments for the problem:

class ListNode {
    int val;
    ListNode next;
    ListNode(int val) {
        this.val = val;
    }
}

public class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        // Create a dummy node to handle the case when the head needs to be removed
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        
        ListNode slow = dummy;
        ListNode fast = dummy;
        
        // Move the fast pointer n+1 steps ahead
        for (int i = 0; i <= n; i++) {
            fast = fast.next;
        }
        
        // Move both slow and fast pointers at the same time until the fast pointer reaches the end of the list
        while (fast != null) {
            slow = slow.next;
            fast = fast.next;
        }
        
        // Remove the node by updating the next pointer of the slow pointer
        slow.next = slow.next.next;
        
        // Return the modified list
        return dummy.next;
    }
}
  1. Detailed description of the algorithm and tips for the interview process:

  • To solve this problem, we can use the two-pointer technique, also known as the "slow and fast pointers" approach.

  • We create a dummy node to handle the special case where the head needs to be removed.

  • We initialize two pointers, slow and fast, to point to the dummy node initially.

  • We move the fast pointer n+1 steps ahead. This is done because we need to locate the node that is n steps behind the node to be removed.

  • Then, we move both slow and fast pointers at the same time until the fast pointer reaches the end of the list.

  • The slow pointer will be pointing to the node that is n steps behind the node to be removed.

  • Finally, we remove the node by updating the next pointer of the slow pointer to skip the node to be removed.

  • We return the modified list by returning dummy.next.

During the interview process, it is important to understand the problem thoroughly and come up with the most efficient solution. Explaining the algorithm with proper comments and writing clean code will leave a good impression on the interviewer. It is also crucial to test the solution with different test cases to ensure its correctness.

4. Add Two Numbers

  1. The problem: You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contains a single digit. Add the two numbers and return it as a linked list.

LeetCode link: https://leetcode.com/problems/add-two-numbers/

  1. Optimized Java code for "Add Two Numbers" with detailed comments:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
public class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        // Create a dummy head and a current node to store the sum of digits
        ListNode dummyHead = new ListNode(0);
        ListNode current = dummyHead;
        
        int carry = 0;
        
        // Iterate until both lists are exhausted or the carry is zero
        while (l1 != null || l2 != null || carry != 0) {
            int sum = carry;
            
            // Add the respective values of l1 and l2 to the sum
            if (l1 != null) {
                sum += l1.val;
                l1 = l1.next;
            }
            
            if (l2 != null) {
                sum += l2.val;
                l2 = l2.next;
            }
            
            // Store the current digit and update the carry
            current.next = new ListNode(sum % 10);
            carry = sum / 10;
            
            // Move to the next digit
            current = current.next;
        }
        
        // Return the head of the resulting linked list
        return dummyHead.next;
    }
}
  1. Algorithm and thinking process:

  • We are given two linked lists that represent two non-negative integers, with each digit stored in reverse order. Our task is to add the two numbers and return the result as a linked list.

  • To solve this problem, we can use a simple iterative approach where we iterate through both linked lists simultaneously, starting from the head.

  • We initialize a carry variable to keep track of any carry that occurs during addition. We start with a dummy head and a current node to store the sum of digits.

  • While iterating, for each node, we add the respective values from both lists and the carry. We update the carry and the current digit accordingly.

  • If either of the lists has more digits than the other, we continue adding the remaining digits and the carry.

  • Finally, if there is any remaining carry, we add it as a new digit to the resulting linked list.

  • We return the head of the resulting linked list.

  • This approach has an overall time complexity of O(max(m, n)), where m and n are the lengths of the two input lists.

5. Merge Two Sorted Lists

  1. Problem Description: The problem "Merge Two Sorted Lists" on LeetCode can be found at the following link: https://leetcode.com/problems/merge-two-sorted-lists/

  2. Optimized Java Code:

// Definition for singly-linked list.
class ListNode {
  int val;
  ListNode next;
  ListNode(int x) {
      val = x;
      next = null;
  }
}

class Solution {
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        // Create a dummy head to start the merged list
        ListNode dummy = new ListNode(0);
        // Create a pointer to keep track of the current node
        ListNode current = dummy;
        
        // While both lists are not empty, compare the values of the current nodes
        // and append the smaller one to the merged list
        while (l1 != null && l2 != null) {
            if (l1.val <= l2.val) {
                current.next = l1;
                l1 = l1.next;
            } else {
                current.next = l2;
                l2 = l2.next;
            }
            current = current.next;
        }
        
        // Append the remaining nodes of the non-empty list directly to the merged list
        if (l1 != null)
            current.next = l1;
        if (l2 != null)
            current.next = l2;
        
        // Return the head of the merged list
        return dummy.next;
    }
}
  1. Algorithm and Approach:

  • The given problem asks us to merge two sorted linked lists and return the resulting merged list.

  • The algorithm I provided uses a simple iterative approach to merge the two given lists.

  • I will explain the algorithm and provide some tips on how to think through it during an interview:

    • We initialize a dummy head and a current pointer to start building the merged list.

    • We use a while loop to compare the values of the current nodes of the two lists.

    • We append the smaller value node to the merged list and move the corresponding pointer to the next node.

    • We repeat this process until one of the lists becomes empty.

    • If one list becomes empty before the other, we append the remaining nodes from the non-empty list directly to the merged list.

    • Finally, we return the head of the merged list.

    Tips for thinking through the problem:

    • Understand the problem thoroughly and identify the constraints and requirements.

    • Start by visualizing some examples of merging two sorted lists manually to understand how the process works.

    • Compare the first nodes of both lists and determine which one should come first in the merged list.

    • Continue comparing and merging the nodes until one of the lists becomes empty.

    • Handle the case when one list becomes empty before the other.

    • Think about the time complexity and try to optimize the solution.

    • Discuss the solution and algorithm with the interviewer, explaining your thought process and any optimizations you made.

    • Test the solution with different test cases to ensure its correctness.

    • Ask clarifying questions to confirm any assumptions or edge cases related to the problem.

    By understanding the problem, breaking it down into simpler steps, and discussing the solution with the interviewer, you can approach and solve the problem effectively during an interview.

PreviousLinkedListNextCycle Detection and Handling

Last updated 1 year ago

LeetCode problem link:

The problem is called "Remove Nth Node From End of List" on LeetCode. The problem description and the link to the problem can be found here: .

Reverse Linked List
Remove Nth Node From End of List