DSA Patterns Flashcards
Pattern used to search or operate on a pair of elements in an array
Two pointers. Ex Two Sum II, 3 Sum, Container with most water.
Pattern to more optimally calculate the sum of a subset of elements in an array
Prefix Sum. Ex Range Sum Query, Contiguous Array, Subarray Sum
Prefix Sum initialization and formula to find sum of subset
Initialization:
new Array(nums.length + 1).fill(0)
This sets up an array with an extra space for the initial sum of 0, and sets all other values to zero until they are summed.
Formula:
Sum(l, r) = prefixSum[r + 1] - prefixSum[l]
Subtracts the total sum just before the left pointer from the sum at the right pointer
Pattern to find or operate on a subset of an array
Sliding Window. Move two pointers to define the subset. Ex Max Avg Subarray, Longest Substring without Repeating Chars, Min Window Substring.
Pattern to find cycles and dupes
Fast and Slow Pointers. Ex Linked List Cycle, Happy Number, Find duplicate number
Properties of a Linked List and Node
LinkedList: head, size
Node: data, next
Linked List Insert First
Create a new node with the data and the current head as it’s next, then set the new node as the head.
Linked List Insert Last
Set a current variable to the head. Then loop through while the current node has a next value and if it does setting next as the new current. When the current.next is null you are at the end of the list and can set current.next to a new node
Linked List Insert at Index
If the index is greater than size exit function. If index is 0 then just invoke insert first method. Initialize variables for the current node, the previous node, and a count. While looping, set previous to current, increment count, and set current to next. Once count == index exit loop. Set new node next to current, set previous.next to new node.
Linked List GetAt
Initialize count variable and loop while count < index then return current
Linked List Remove At
Use current, previous, count and while loop to find node at index and identify its previous and next nodes. Then set previous.next to current.next, effectively removing current from the list
Linked List Reversal
Cur, prev, next variables. While there is a cur:
next = cur.next
cur.next = prev
prev = cur
cur = next
After loop, prev will be the new head so set this.head to prev
Linked List Reverse with Stack
Push all nodes into stack, then while the stack has elements, pop them off and set to the current.next then set current to current.next (the popped off element). Set last next pointer to null
Linked List Clear
this.head = null
Reverse Doubly Linked List
While (current)
temp = current.prev
current.prev = current.next
current.next = temp
current = current.prev
at the end temp will be pointing to new head
this.head = temp.prev