DSA Patterns Flashcards
Two Pointers
Definition
Use two indices (pointers) that move through a data structure (often an array) at different speeds or directions to solve problems involving pair-sums, sorting, or partitioning.
Common Use Cases
• Finding pairs/triplets in a sorted array that sum to a specific value (e.g., 2-sum, 3-sum).
• Removing duplicates or elements in-place (e.g., “Remove Duplicates from Sorted Array”).
• Partitioning arrays (e.g., “Dutch National Flag”).
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. Takes only one pass to create the array, then 0(1) retrieval of sums
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
Sliding Window
Definition
Maintain a window (subarray or substring) that moves (slides) through the data, expanding or shrinking to satisfy conditions like sum, distinct characters, or maximum average.
Common Use Cases
• Subarray sums (e.g., “Subarray Sum Equals K” when all positives).
• Longest substring with certain constraints (e.g., “Longest Substring Without Repeating Characters”).
• Maximum average subarray, minimum window substring, etc.
Fast and Slow Pointers
Definition
Use two pointers that move at different speeds (commonly in linked lists) to detect cycles or find middle points.
Common Use Cases
• Detecting cycles in a linked list.
• Finding the cycle start or the middle node of a linked list.
• Checking if a linked list is palindrome by splitting and reversing second half.
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
Pattern to find the k smallest or k largest
Heaps. Min heap for k largest, max heap for k smallest.
Formula to calculate the distance between two points on a plot
Math.sqrt((x1 - x2)^2 + (y1 - y2)^2) = distance
Get parent, right child, left child in a heap or binary tree
Parent idx = Math.floor((i- 1) / 2)
Left child idx = 2 * i + 1
Right child idx = 2 * i + 2
Adding to a heap
Push to heap (add lead) and heapify up
Set idx to last idx. While idx > 0
Get parent idx. Compare heap[idx] to heap[parentIdx] and switch them if needed. If not needed, break the loop
Replacing an element in a heap (heap already has k elements and new element is larger/smaller than max/min)
Set root (heap[0]) to new element then heapify down
Set idx to 0. While true
Set largest/smallest idx for min/max heap respectively to idx. Get idx for left and right children. Compare left child the right child to largest/smallest and reassign largest/smallest as necessary. If largest/smallest still equals idx then break. If not switch element at idx with element at largest/smallest and set idx to largest/smallest idx
Binary tree pre order
DFS - root, left, right
Binary tree in order
DFS - left, root, right
Binary tree post order
DFS - left, right, root
Binary tree level order
BFS