Struggling with LeetCode? The secret is to master core algorithmic patterns instead of memorizing code. We will deep-dive into two classic beginner-friendly problems with complete Python implementations, concrete examples, and step-by-step variable dry runs.
Problem 1: Two Sum (Hash Map Pattern)
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
Python Implementation
def two_sum(nums, target):
seen = {} # val -> index
for i, num in enumerate(nums):
complement = target - num
if complement in seen:
return [seen[complement], i]
seen[num] = i
return []
Step-by-Step Example Explanation
Let's trace this code with the following input: nums = [2, 7, 11, 15] and target = 9.
| Index (i) | Num | Complement (9 - Num) | In Seen Map? | Seen Map State |
|---|---|---|---|---|
| 0 | 2 | 7 | No (seen is empty) | {2: 0} |
| 1 | 7 | 2 | Yes! (2 is at index 0) | Return [0, 1] |
Problem 2: Valid Palindrome (Two-Pointer Pattern)
Given a string, check if it reads the same forward and backward, ignoring non-alphanumeric characters and casing.
Python Implementation
def is_palindrome(s):
# Filter string to only contain lowercase alphanumeric characters
cleaned = [char.lower() for char in s if char.isalnum()]
left, right = 0, len(cleaned) - 1
while left < right:
if cleaned[left] != cleaned[right]:
return False
left += 1
right -= 1
return True
Step-by-Step Example Explanation
Let's trace this code with the input: s = "A man, a plan, a canal: Panama"
First, the list comprehension cleans and filters the string into:
cleaned = ['a', 'm', 'a', 'n', 'a', 'p', 'l', 'a', 'n', 'a', 'c', 'a', 'n', 'a', 'l', 'p', 'a', 'n', 'a', 'm', 'a'] (Length = 21)
Now, let's trace our pointers left and right:
- Iteration 1:
left = 0('a'),right = 20('a'). They match! Pointers move:left = 1,right = 19. - Iteration 2:
left = 1('m'),right = 19('m'). They match! Pointers move:left = 2,right = 18. - Iteration 3:
left = 2('a'),right = 18('a'). They match! ... This loop continues untilleft >= right, verifying that the entire word is perfectly symmetrical.