Core Problem Patterns with Code Templates Flashcards

(26 cards)

1
Q

What is the key insight for the Two Sum (HashMap) pattern?

A

For each number, check if (target - number) exists

This approach uses a hashmap to track seen numbers and their indices.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What is the template for the Two Sum (HashMap) pattern?

A

def twoSum(nums, target):
seen = {}
for i, num in enumerate(nums):
complement = target - num
if complement in seen:
return [seen[complement], i]
seen[num] = i

This function returns the indices of the two numbers that add up to the target.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What is the key insight for the Sliding Window (Set) pattern?

A

Expand window with right pointer, shrink when duplicate found

This technique is useful for finding the longest substring without repeating characters.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What is the template for the Sliding Window (Set) pattern?

A

def lengthOfLongestSubstring(s):
seen = set()
left = 0
max_len = 0
for right in range(len(s)):
while s[right] in seen:
seen.remove(s[left])
left += 1
seen.add(s[right])
max_len = max(max_len, right - left + 1)
return max_len

This function returns the length of the longest substring without repeating characters.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What is the key insight for the Valid Parentheses (Stack) pattern?

A

Push opening brackets, pop and match closing brackets

This method ensures that all brackets are balanced.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What is the template for the Valid Parentheses (Stack) pattern?

A

def isValid(s):
stack = []
mapping = {‘)’: ‘(‘, ‘}’: ‘{‘, ‘]’: ‘[’}
for char in s:
if char in mapping:
top = stack.pop() if stack else ‘#’
if mapping[char] != top:
return False
else:
stack.append(char)
return not stack

This function checks if the input string of brackets is valid.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What is the key insight for the Two Pointers (Sorted Array) pattern?

A

Move left pointer up if sum too small, right pointer down if too large

This approach is efficient for finding pairs in a sorted array.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What is the template for the Two Pointers (Sorted Array) pattern when 1 indexed (as seen in two sum II)?

A

def twoSum(numbers, target):
left, right = 0, len(numbers) - 1
while left < right:
curr_sum = numbers[left] + numbers[right]
if curr_sum == target:
return [left + 1, right + 1]
elif curr_sum < target:
left += 1
else:
right -= 1

This function returns the indices of the two numbers that add up to the target in a sorted array.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What is the key insight for the BFS (Tree Level Order) pattern?

A

Use queue, process all nodes at current level before next

This method is used for level order traversal of a tree.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What is the template for the BFS (Tree Level Order) pattern?

A

from collections import deque

def levelOrder(root):
if not root:
return []
result = []
queue = deque([root])
while queue:
level_size = len(queue)
current_level = []
for _ in range(level_size):
node = queue.popleft()
current_level.append(node.val)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
result.append(current_level)
return result

This function returns the values of the tree nodes level by level.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What is the key insight for the DFS (Tree Recursion) pattern?

A

Recursive function that processes current node then children

This method is useful for traversing trees and validating properties.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What is the template for the DFS (Tree Recursion) pattern?

A

def dfs(node):
if not node:
return
result = node.val
left_result = dfs(node.left)
right_result = dfs(node.right)
return result

This function processes each node in a tree recursively.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What is the key insight for Kadane’s Algorithm?

A

Track current sum, reset to 0 when negative

This algorithm is used to find the maximum sum subarray.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What is the template for Kadane’s Algorithm?

A

def maxSubArray(nums):
max_sum = nums[0]
current_sum = nums[0]
for i in range(1, len(nums)):
current_sum = max(nums[i], current_sum + nums[i])
max_sum = max(max_sum, current_sum)
return max_sum

This function returns the maximum sum of a contiguous subarray.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

What is the key insight for the Merge Intervals pattern?

A

Sort by start time, merge if current overlaps with last

This approach is effective for merging overlapping intervals.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What is the template for the Merge Intervals pattern?

A

def merge(intervals):
intervals.sort(key=lambda x: x[0])
merged = [intervals[0]]
for current in intervals[1:]:
last = merged[-1]
if current[0] <= last[1]:
last[1] = max(last[1], current[1])
else:
merged.append(current)
return merged

This function returns a list of merged intervals.

17
Q

What is the key insight for the Backtracking pattern?

A

Build solution incrementally, backtrack when needed

This technique is useful for generating combinations, permutations, and subsets.

18
Q

What is the template for the Backtracking pattern?

A

def backtrack(result, temp, nums, start):
result.append(temp[:]) # Make a copy
for i in range(start, len(nums)):
temp.append(nums[i])
backtrack(result, temp, nums, i + 1)
temp.pop() # Backtrack

This function generates all combinations of the input list.

19
Q

What is the key insight for the Binary Search pattern?

A

Divide search space in half each iteration

This method is efficient for finding a target in a sorted array.

20
Q

What is the template for the Binary Search pattern?

A

def binarySearch(nums, target):
left, right = 0, len(nums) - 1
while left <= right:
mid = (left + right) // 2
if nums[mid] == target:
return mid
elif nums[mid] < target:
left = mid + 1
else:
right = mid - 1
return -1

This function returns the index of the target in the sorted array or -1 if not found.

21
Q

What is the common import for using a deque in Python?

A

from collections import deque

Deques are useful for implementing queues and stacks.

22
Q

How do you convert a string to a list in Python?

A

chars = list(s)

This operation splits the string into its constituent characters.

23
Q

How do you join a list to a string in Python?

A

s = ‘‘.join(chars)

This operation combines the list elements into a single string.

24
Q

What is the syntax for integer division in Python?

A

a // b

This operation rounds down the result of the division.

25
What is the syntax for **regular division** in Python?
a / b ## Footnote This operation returns a float result.
26
What does **range(n)** do in Python?
Gives 0 to n-1 ## Footnote This function generates a sequence of numbers from 0 to n-1.