Type something to search...

Leetcode: LinkedList in Python

create a dummy node

Merge two linked lists.

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
        pre = ListNode(0)
        ans = pre
        while(l1 != None or l2 != None):
            if l1 == None or (l2 != None and l2.val <= l1.val):
                pre.next = l2
                l2 = l2.next
                pre = pre.next
            else:
                pre.next = l1
                l1 = l1.next
                pre = pre.next
        return ans.next

delete a node

delete a node

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def deleteNode(self, node):
        """
        :type node: ListNode
        :rtype: void Do not return anything, modify node in-place instead.
        """
        node.val = node.next.val
        node.next = node.next.next

quick and slow node.

Check if it is palindrome. Example 1: Input: 1->2 Output: false Example 2: Input: 1->2->2->1 Output: true

class Solution:
    def isPalindrome(self, head: ListNode) -> bool:
        if head is None:
            return True
        hare = turtle = curr = head
        while hare and hare.next:
            hare = hare.next.next
            turtle = turtle.next
        stack = []
        while turtle:
            stack.append(turtle.val)
            turtle = turtle.next
        while stack:
            if curr.val != stack.pop():
                return False
            curr = curr.next
        return True

Detect cycle. Example1: Input: head = [3,2,0,-4], pos = 1 Output: tail connects to node index 1 Explanation: There is a cycle in the linked list, where tail connects to the second node.

class Solution(object):
    def detectCycle(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        meet = None
        fast = head
        slow = head
        # must check all 3 here
        while slow and  fast and fast.next:
            slow = slow.next
            fast = fast.next.next
            if slow is fast:
                meet = slow
                break

        if meet:
            p = head
            q = meet
            while p and q:
                if p is q:
                    return p
                p= p.next
                q = q.next
        return None

Related Posts

Leetcode: Array questions with Python

134.Gas StationThere are N gas stations along a circular route, where the amount of gas at station i is gas[i]. You have a car with an unlimited gas tank and it costs cost[i] of gas to trave

read more

leetcode questions: Backtracking

Template def backtrack(candidate): if find_solution(candidate): output(candidate) return # iterate all possible candidates. for next_candidate in list_of_candid

read more

leetcode questions: BFS

BFS Template /** * Return the length of the shortest path between root and target node. */ int BFS(Node root, Node target) { Queue<Node> queue; // store all nodes which are waiting

read more

leetcode questions: Binary Search

bisect.bisect_left(a, x) https://dynalist.io/d/RWIGNj7DLlzkBed-3ZqhuBg_#z=cbr2Mkrig9KhE6Lxfwhm31IS O(log n) greater than or equal to the targeted value. If all elements are less than x, return `

read more

leetcode questions: Bit

common tricks x & (-x) to isolate/get the rightmost 1-bit This operation reverts all bits of x except the rightmost 1-bit. Hence, x and -x have just one bit in common - the rightmost 1-bit

read more

leetcode questions: DFS

DFS Templates Template 1: /* * Return true if there is a path from cur to target. */ boolean DFS(Node cur, Node target, Set<Node> visited) { return true if cur is target; for (

read more

leetcode questions: dynamic programming

Intro Good video: Dynamic Programming - Learn to Solve Algorithmic Problems & Coding Challenges - YouTube DP is a style of coding where you store t

read more

leetcode: mini spanning tree, single src shortest path, topological

Minimum spanning tree A minimum spanning tree is a spanning tree with the minimum possible total edge weight in a “weighted undirected graph”. [Min Cost to Connect All Points - LeetCode](https://

read more

Java frequently used data structures and methods for leetcode

Array Common declarations: int[] a = new int[100]; int[] b = {4, 1, 5}; int[] c = new int[] {1, 2, 3};Two-dimensional arrays: int[][] grid = {{1, 2}, {3, 4}};int[][] jag

read more

Python list/dict functions for leetcode

Listlen(array) : length of array list.index(obj)enumerate(array) : adds counter at the beginning. for count, item in enumerate(['x','y','z']) # 0x 1y 2z`range(0,len(mylis

read more

Python String functions for leetcode

print(f'best RF score: {grid.best_score_:.3f}') str.index(sub[,start[,end]]) str.strip() remove spaces at the beginning and the end strip(str-not-want)lower() `print(str.upp

read more

leetcode: Trie

Basic A Trie is a special form of a Nary tree. Typically, a trie is used to store strings. Each Trie node represents a string (a prefix). Each node might have several children nodes while the pat

read more