As your “Professor” for this Algorithms 101 module, I’ve translated and refined Level 1 of our roadmap into English. This is designed to be clear, visually structured, and ready for a professional technical post.
1. Arrays & Strings: The Building Blocks
In the world of LeetCode, almost everything begins with how you store and access data. In Python, lists and strings are your primary tools.
- How to Recognize: Look for problems asking to reverse, rotate, or find frequencies within a list of items or characters.
- The Mindset: Focus on Index Manipulation. Understand that accessing an element by its index is lightning fast ($O(1)$).
Python
# Example: Valid Palindrome
# Goal: Check if a string reads the same forward and backward
def is_palindrome(s: str) -> bool:
# Clean the string: remove non-alphanumeric and lowercase
filtered_chars = [char.lower() for char in s if char.isalnum()]
return filtered_chars == filtered_chars[::-1]
print(is_palindrome("A man, a plan, a canal: Panama")) # Output: True
2. Big O Notation: The Measure of Excellence
Before you optimize code, you must know how to measure it. Big O defines how your code’s runtime scales as the input size grows.
- The “Cheat Sheet”:
- $O(1)$: Instant (e.g., accessing a list index).
- $O(n)$: Linear (e.g., a single for-loop through a list).
- $O(n^2)$: Quadratic (e.g., nested loops). This is often the “brute force” trap that leads to “Time Limit Exceeded.”
- The Goal: Always ask yourself: “Can I solve this without nesting loops?”
3. Two Pointers: Efficiency in Motion
This technique is a “golden rule” for optimizing $O(n^2)$ brute force solutions down to $O(n)$ linear time.
- How to Recognize: The input is usually a sorted array, and you need to find a pair of elements that meet a specific condition.
- The Strategy: Use two indices—one starting at the beginning (
left) and one at the end (right)—and move them toward each other.
Python
# Example: Two Sum (Sorted Input)
# Goal: Find indices of two numbers that add up to a target
def two_sum_sorted(nums, target):
left, right = 0, len(nums) - 1
while left < right:
current_sum = nums[left] + nums[right]
if current_sum == target:
return [left, right]
if current_sum < target:
left += 1 # We need a larger sum
else:
right -= 1 # We need a smaller sum
return []
print(two_sum_sorted([2, 7, 11, 15], 9)) # Output: [0, 1]
4. Sliding Window: The Converging Lens
Instead of recalculating results from scratch, “slide” a window across the data to reuse previous computations.
- How to Recognize: Problems involving contiguous subarrays or substrings (e.g., “Find the longest substring without repeating characters”).
- The Strategy: Maintain a “window” of elements. As you add one element to the right, you remove one from the left.
Python
# Example: Maximum Sum Subarray of size K
def max_subarray_sum(nums, k):
if not nums or k > len(nums): return 0
# Calculate sum of the first window
window_sum = sum(nums[:k])
max_sum = window_sum
for i in range(len(nums) - k):
# Slide: Subtract the element leaving, add the element entering
window_sum = window_sum - nums[i] + nums[i + k]
max_sum = max(max_sum, window_sum)
return max_sum
print(max_subarray_sum([2, 1, 5, 1, 3, 2], 3)) # Output: 9
5. Basic Sorting & Binary Search
Order brings efficiency. Many complex problems become trivial once the data is sorted.
- Sorting: Use Python’s built-in
.sort()(Timsort), which runs in $O(n \log n)$. - Binary Search: If an array is already sorted, don’t search linearly. “Cut the search area in half” to find your target in $O(\log n)$ time.
Python
# Example: Classic Binary Search
def binary_search(nums, target):
low, high = 0, len(nums) - 1
while low <= high:
mid = (low + high) // 2
if nums[mid] == target:
return mid
elif nums[mid] < target:
low = mid + 1
else:
high = mid - 1
return -1
print(binary_search([1, 3, 5, 7, 9], 7)) # Output: 3
🎓 Professor’s Final Note:
“Algorithm study is not about memorizing code; it’s about pattern recognition. Master these Level 1 patterns, and you will have the foundation to tackle Medium and Hard problems with confidence.”
Which of these patterns do you find most intuitive? Let me know in the comments!
Leave a Reply