Loading...
Loading...
Compare original and translation side by side
Pattern: Use two pointers to scan array
Use when: Need to find pairs, triplets, or subarrays
Example: "Find Instagram users who like each other"
Complexity: O(n) time, O(1) spacePattern: Maintain a window that slides through array
Use when: Need to find subarray with certain property
Example: "Find trending topics in last N tweets"
Complexity: O(n) time, O(k) spacePattern: Two pointers moving at different speeds
Use when: Detect cycles, find middle element
Example: "Detect circular dependency in package manager"
Complexity: O(n) time, O(1) spacePattern: Use two pointers to scan array
Use when: Need to find pairs, triplets, or subarrays
Example: "Find Instagram users who like each other"
Complexity: O(n) time, O(1) spacePattern: Maintain a window that slides through array
Use when: Need to find subarray with certain property
Example: "Find trending topics in last N tweets"
Complexity: O(n) time, O(k) spacePattern: Two pointers moving at different speeds
Use when: Detect cycles, find middle element
Example: "Detect circular dependency in package manager"
Complexity: O(n) time, O(1) spacePattern: Level-order traversal using queue
Use when: Need level-by-level processing
Example: "Show friends by degree of connection"
Complexity: O(n) time, O(w) space (w = max width)Pattern: Preorder, inorder, or postorder traversal
Use when: Need to explore all paths
Example: "Find all paths in file system"
Complexity: O(n) time, O(h) space (h = height)Pattern: Explore neighbors level by level
Use when: Shortest path, level-based exploration
Example: "Find shortest connection path on LinkedIn"
Complexity: O(V + E) time, O(V) spacePattern: Explore as far as possible before backtracking
Use when: Path finding, cycle detection
Example: "Detect circular references in social graph"
Complexity: O(V + E) time, O(V) spacePattern: Order nodes by dependencies
Use when: Task scheduling, build systems
Example: "Order courses based on prerequisites"
Complexity: O(V + E) time, O(V) spacePattern: Level-order traversal using queue
Use when: Need level-by-level processing
Example: "Show friends by degree of connection"
Complexity: O(n) time, O(w) space (w = max width)Pattern: Preorder, inorder, or postorder traversal
Use when: Need to explore all paths
Example: "Find all paths in file system"
Complexity: O(n) time, O(h) space (h = height)Pattern: Explore neighbors level by level
Use when: Shortest path, level-based exploration
Example: "Find shortest connection path on LinkedIn"
Complexity: O(V + E) time, O(V) spacePattern: Explore as far as possible before backtracking
Use when: Path finding, cycle detection
Example: "Detect circular references in social graph"
Complexity: O(V + E) time, O(V) spacePattern: Order nodes by dependencies
Use when: Task scheduling, build systems
Example: "Order courses based on prerequisites"
Complexity: O(V + E) time, O(V) spacePattern: Include or exclude each item
Use when: Optimization with constraints
Example: "Select best ads within budget"
Complexity: O(n * capacity) time and spacePattern: Can use item unlimited times
Use when: Coin change, combinations
Example: "Minimum transactions to reach balance"
Complexity: O(n * target) time and spacePattern: Current state depends on previous states
Use when: Climbing stairs, tiling problems
Example: "Ways to navigate through app screens"
Complexity: O(n) time, O(1) space optimizedPattern: Compare two sequences
Use when: Diff tools, edit distance
Example: "Find similar code snippets"
Complexity: O(m * n) time and spacePattern: Include or exclude each item
Use when: Optimization with constraints
Example: "Select best ads within budget"
Complexity: O(n * capacity) time and spacePattern: Can use item unlimited times
Use when: Coin change, combinations
Example: "Minimum transactions to reach balance"
Complexity: O(n * target) time and spacePattern: Current state depends on previous states
Use when: Climbing stairs, tiling problems
Example: "Ways to navigate through app screens"
Complexity: O(n) time, O(1) space optimizedPattern: Compare two sequences
Use when: Diff tools, edit distance
Example: "Find similar code snippets"
Complexity: O(m * n) time and spacePattern: Binary search on sorted or rotated array
Use when: Search in O(log n)
Example: "Find version when bug was introduced"
Complexity: O(log n) time, O(1) spacePattern: Use heap to track K largest/smallest
Use when: Finding top items
Example: "Get top K trending hashtags"
Complexity: O(n log k) time, O(k) spacePattern: Merge K sorted arrays/lists
Use when: Combining sorted data
Example: "Merge activity feeds from K users"
Complexity: O(n log k) time, O(k) spacePattern: Try all possibilities with pruning
Use when: Generate permutations, combinations
Example: "Generate all valid parentheses combinations"
Complexity: Varies, often exponentialPattern: Track connected components
Use when: Network connectivity, grouping
Example: "Find connected friend groups"
Complexity: O(α(n)) amortized per operationPattern: Merge, insert, or find overlapping intervals
Use when: Calendar scheduling, time ranges
Example: "Find free meeting slots"
Complexity: O(n log n) time, O(n) spacePattern: Maintain increasing/decreasing stack
Use when: Next greater/smaller element
Example: "Stock price span calculation"
Complexity: O(n) time, O(n) spacePattern: Prefix tree for string operations
Use when: Autocomplete, prefix matching
Example: "Implement search autocomplete"
Complexity: O(m) time per operation (m = word length)Pattern: Binary search on sorted or rotated array
Use when: Search in O(log n)
Example: "Find version when bug was introduced"
Complexity: O(log n) time, O(1) spacePattern: Use heap to track K largest/smallest
Use when: Finding top items
Example: "Get top K trending hashtags"
Complexity: O(n log k) time, O(k) spacePattern: Merge K sorted arrays/lists
Use when: Combining sorted data
Example: "Merge activity feeds from K users"
Complexity: O(n log k) time, O(k) spacePattern: Try all possibilities with pruning
Use when: Generate permutations, combinations
Example: "Generate all valid parentheses combinations"
Complexity: Varies, often exponentialPattern: Track connected components
Use when: Network connectivity, grouping
Example: "Find connected friend groups"
Complexity: O(α(n)) amortized per operationPattern: Merge, insert, or find overlapping intervals
Use when: Calendar scheduling, time ranges
Example: "Find free meeting slots"
Complexity: O(n log n) time, O(n) spacePattern: Maintain increasing/decreasing stack
Use when: Next greater/smaller element
Example: "Stock price span calculation"
Complexity: O(n) time, O(n) spacePattern: Prefix tree for string operations
Use when: Autocomplete, prefix matching
Example: "Implement search autocomplete"
Complexity: O(m) time per operation (m = word length)Real Scenario: Count how many times user's posts were liked today
Pattern: Hash Map
Data Structure: Dictionary/HashMap
Languages: Python, TypeScript, Kotlin, SwiftReal Scenario: Find first unread message in channel
Pattern: Linear Search with Flag
Data Structure: Array
Teaches: Early terminationReal Scenario: Compute trip cost based on distance and time
Pattern: Simple Calculation
Data Structure: Numbers
Teaches: Math operations, roundingReal Scenario: Count how many times user's posts were liked today
Pattern: Hash Map
Data Structure: Dictionary/HashMap
Languages: Python, TypeScript, Kotlin, SwiftReal Scenario: Find first unread message in channel
Pattern: Linear Search with Flag
Data Structure: Array
Teaches: Early terminationReal Scenario: Compute trip cost based on distance and time
Pattern: Simple Calculation
Data Structure: Numbers
Teaches: Math operations, roundingReal Scenario: Find top N movies by rating
Pattern: Top K Elements (Heap)
Data Structure: Priority Queue
Teaches: Heap operations, partial sortingReal Scenario: Find products running low in stock
Pattern: Filtering with Threshold
Data Structure: Array + HashMap
Teaches: Multi-criteria filteringReal Scenario: Find most used hashtags in time window
Pattern: Sliding Window + Frequency Count
Data Structure: Queue + HashMap
Teaches: Time-based window managementReal Scenario: Find connection path between two users
Pattern: BFS
Data Structure: Graph (Adjacency List)
Teaches: Shortest path, level trackingReal Scenario: Find top N movies by rating
Pattern: Top K Elements (Heap)
Data Structure: Priority Queue
Teaches: Heap operations, partial sortingReal Scenario: Find products running low in stock
Pattern: Filtering with Threshold
Data Structure: Array + HashMap
Teaches: Multi-criteria filteringReal Scenario: Find most used hashtags in time window
Pattern: Sliding Window + Frequency Count
Data Structure: Queue + HashMap
Teaches: Time-based window managementReal Scenario: Find connection path between two users
Pattern: BFS
Data Structure: Graph (Adjacency List)
Teaches: Shortest path, level trackingReal Scenario: Find free time slots for all attendees
Pattern: Interval Merging
Data Structure: Array of Intervals
Teaches: Sorting, merging overlapping intervalsReal Scenario: True random shuffle avoiding artist repetition
Pattern: Modified Fisher-Yates
Data Structure: Array
Teaches: Randomization with constraintsReal Scenario: Find longest common subsequence in files
Pattern: Dynamic Programming (LCS)
Data Structure: 2D Array
Teaches: DP state definition, optimizationReal Scenario: Rank listings by multiple weighted criteria
Pattern: Custom Sorting + Heap
Data Structure: Priority Queue with Comparator
Teaches: Complex comparisons, tie-breakingReal Scenario: Find free time slots for all attendees
Pattern: Interval Merging
Data Structure: Array of Intervals
Teaches: Sorting, merging overlapping intervalsReal Scenario: True random shuffle avoiding artist repetition
Pattern: Modified Fisher-Yates
Data Structure: Array
Teaches: Randomization with constraintsReal Scenario: Find longest common subsequence in files
Pattern: Dynamic Programming (LCS)
Data Structure: 2D Array
Teaches: DP state definition, optimizationReal Scenario: Rank listings by multiple weighted criteria
Pattern: Custom Sorting + Heap
Data Structure: Priority Queue with Comparator
Teaches: Complex comparisons, tie-breaking<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>🚀 LeetCode Teacher - Two Sum (Instagram Likes)</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body {
font-family: 'SF Mono', 'Monaco', 'Courier New', monospace;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
min-height: 100vh;
padding: 20px;
color: white;
}
.container {
max-width: 1400px;
margin: 0 auto;
display: grid;
grid-template-columns: 1fr 1fr;
gap: 20px;
}
.panel {
background: rgba(255, 255, 255, 0.1);
backdrop-filter: blur(10px);
border-radius: 15px;
padding: 30px;
box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
}
h1 {
font-size: 2.5em;
margin-bottom: 10px;
text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.3);
}
.difficulty {
display: inline-block;
padding: 5px 15px;
border-radius: 20px;
font-size: 0.9em;
font-weight: bold;
margin-bottom: 20px;
}
.easy { background: #4CAF50; }
.medium { background: #FF9800; }
.hard { background: #F44336; }
.problem {
background: rgba(255, 255, 255, 0.1);
padding: 20px;
border-radius: 10px;
margin: 20px 0;
line-height: 1.6;
}
.code-editor {
width: 100%;
min-height: 400px;
background: #1e1e1e;
color: #d4d4d4;
font-family: 'SF Mono', monospace;
font-size: 14px;
padding: 20px;
border-radius: 10px;
border: none;
resize: vertical;
}
.controls {
display: flex;
gap: 10px;
margin: 20px 0;
}
.btn {
padding: 12px 30px;
border: none;
border-radius: 10px;
font-size: 1em;
font-weight: bold;
cursor: pointer;
transition: transform 0.2s;
}
.btn-run {
background: linear-gradient(135deg, #4CAF50, #45a049);
color: white;
}
.btn-hint {
background: linear-gradient(135deg, #FF9800, #F57C00);
color: white;
}
.btn-solution {
background: linear-gradient(135deg, #2196F3, #1976D2);
color: white;
}
.btn:hover { transform: translateY(-2px); }
.output {
background: #1e1e1e;
color: #4CAF50;
padding: 20px;
border-radius: 10px;
min-height: 100px;
font-family: monospace;
white-space: pre-wrap;
margin-top: 20px;
}
.test-case {
background: rgba(255, 255, 255, 0.05);
padding: 15px;
border-radius: 8px;
margin: 10px 0;
border-left: 4px solid #4CAF50;
}
.test-failed {
border-left-color: #F44336;
}
.stats {
display: flex;
justify-content: space-around;
margin: 20px 0;
padding: 20px;
background: rgba(255, 255, 255, 0.1);
border-radius: 10px;
}
.stat {
text-align: center;
}
.stat-value {
font-size: 2em;
font-weight: bold;
color: #FFD700;
}
.pattern-badge {
display: inline-block;
background: rgba(255, 215, 0, 0.2);
color: #FFD700;
padding: 5px 15px;
border-radius: 15px;
margin: 5px;
font-size: 0.9em;
}
</style>
</head>
<body>
<div class="container">
<!-- Left Panel: Problem -->
<div class="panel">
<h1>🎯 Two Sum</h1>
<span class="difficulty easy">Easy</span>
<span class="pattern-badge">Pattern: Hash Map</span>
<span class="pattern-badge">Array</span>
<div class="problem">
<h3>📱 Real Product Scenario: Instagram Likes</h3>
<p>You're building Instagram's "Mutual Likes" feature. Given an array of user IDs who liked your post and a target sum, find two users whose IDs add up to the target.</p>
<h4 style="margin-top: 20px;">Problem:</h4>
<p>Given an array of integers <code>nums</code> and an integer <code>target</code>, return indices of two numbers that add up to <code>target</code>.</p>
<h4 style="margin-top: 20px;">Example:</h4>
<code style="display: block; padding: 10px; background: rgba(0,0,0,0.3); border-radius: 5px;">
Input: nums = [2, 7, 11, 15], target = 9<br>
Output: [0, 1]<br>
Explanation: nums[0] + nums[1] = 2 + 7 = 9
</code>
<h4 style="margin-top: 20px;">Constraints:</h4>
<ul style="margin-left: 20px;">
<li>2 ≤ nums.length ≤ 10⁴</li>
<li>Only one valid answer exists</li>
<li>Can't use the same element twice</li>
</ul>
</div>
<div class="stats">
<div class="stat">
<div class="stat-value" id="testsRun">0</div>
<div>Tests Run</div>
</div>
<div class="stat">
<div class="stat-value" id="testsPassed">0</div>
<div>Passed</div>
</div>
<div class="stat">
<div class="stat-value" id="attempts">0</div>
<div>Attempts</div>
</div>
</div>
<div id="hints" style="margin-top: 20px;"></div>
</div>
<!-- Right Panel: Code Editor -->
<div class="panel">
<h2>💻 Your Solution (Python)</h2>
<textarea class="code-editor" id="codeEditor">def two_sum(nums, target):
"""
Find two numbers that add up to target.
Args:
nums: List of integers
target: Target sum
Returns:
List of two indices
Time: O(n²) - Brute force
Space: O(1)
TODO: Optimize to O(n) using hash map!
"""
# Your code here
pass<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>🚀 LeetCode Teacher - Two Sum (Instagram Likes)</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body {
font-family: 'SF Mono', 'Monaco', 'Courier New', monospace;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
min-height: 100vh;
padding: 20px;
color: white;
}
.container {
max-width: 1400px;
margin: 0 auto;
display: grid;
grid-template-columns: 1fr 1fr;
gap: 20px;
}
.panel {
background: rgba(255, 255, 255, 0.1);
backdrop-filter: blur(10px);
border-radius: 15px;
padding: 30px;
box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
}
h1 {
font-size: 2.5em;
margin-bottom: 10px;
text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.3);
}
.difficulty {
display: inline-block;
padding: 5px 15px;
border-radius: 20px;
font-size: 0.9em;
font-weight: bold;
margin-bottom: 20px;
}
.easy { background: #4CAF50; }
.medium { background: #FF9800; }
.hard { background: #F44336; }
.problem {
background: rgba(255, 255, 255, 0.1);
padding: 20px;
border-radius: 10px;
margin: 20px 0;
line-height: 1.6;
}
.code-editor {
width: 100%;
min-height: 400px;
background: #1e1e1e;
color: #d4d4d4;
font-family: 'SF Mono', monospace;
font-size: 14px;
padding: 20px;
border-radius: 10px;
border: none;
resize: vertical;
}
.controls {
display: flex;
gap: 10px;
margin: 20px 0;
}
.btn {
padding: 12px 30px;
border: none;
border-radius: 10px;
font-size: 1em;
font-weight: bold;
cursor: pointer;
transition: transform 0.2s;
}
.btn-run {
background: linear-gradient(135deg, #4CAF50, #45a049);
color: white;
}
.btn-hint {
background: linear-gradient(135deg, #FF9800, #F57C00);
color: white;
}
.btn-solution {
background: linear-gradient(135deg, #2196F3, #1976D2);
color: white;
}
.btn:hover { transform: translateY(-2px); }
.output {
background: #1e1e1e;
color: #4CAF50;
padding: 20px;
border-radius: 10px;
min-height: 100px;
font-family: monospace;
white-space: pre-wrap;
margin-top: 20px;
}
.test-case {
background: rgba(255, 255, 255, 0.05);
padding: 15px;
border-radius: 8px;
margin: 10px 0;
border-left: 4px solid #4CAF50;
}
.test-failed {
border-left-color: #F44336;
}
.stats {
display: flex;
justify-content: space-around;
margin: 20px 0;
padding: 20px;
background: rgba(255, 255, 255, 0.1);
border-radius: 10px;
}
.stat {
text-align: center;
}
.stat-value {
font-size: 2em;
font-weight: bold;
color: #FFD700;
}
.pattern-badge {
display: inline-block;
background: rgba(255, 215, 0, 0.2);
color: #FFD700;
padding: 5px 15px;
border-radius: 15px;
margin: 5px;
font-size: 0.9em;
}
</style>
</head>
<body>
<div class="container">
<!-- Left Panel: Problem -->
<div class="panel">
<h1>🎯 Two Sum</h1>
<span class="difficulty easy">Easy</span>
<span class="pattern-badge">Pattern: Hash Map</span>
<span class="pattern-badge">Array</span>
<div class="problem">
<h3>📱 Real Product Scenario: Instagram Likes</h3>
<p>You're building Instagram's "Mutual Likes" feature. Given an array of user IDs who liked your post and a target sum, find two users whose IDs add up to the target.</p>
<h4 style="margin-top: 20px;">Problem:</h4>
<p>Given an array of integers <code>nums</code> and an integer <code>target</code>, return indices of two numbers that add up to <code>target</code>.</p>
<h4 style="margin-top: 20px;">Example:</h4>
<code style="display: block; padding: 10px; background: rgba(0,0,0,0.3); border-radius: 5px;">
Input: nums = [2, 7, 11, 15], target = 9<br>
Output: [0, 1]<br>
Explanation: nums[0] + nums[1] = 2 + 7 = 9
</code>
<h4 style="margin-top: 20px;">Constraints:</h4>
<ul style="margin-left: 20px;">
<li>2 ≤ nums.length ≤ 10⁴</li>
<li>Only one valid answer exists</li>
<li>Can't use the same element twice</li>
</ul>
</div>
<div class="stats">
<div class="stat">
<div class="stat-value" id="testsRun">0</div>
<div>Tests Run</div>
</div>
<div class="stat">
<div class="stat-value" id="testsPassed">0</div>
<div>Passed</div>
</div>
<div class="stat">
<div class="stat-value" id="attempts">0</div>
<div>Attempts</div>
</div>
</div>
<div id="hints" style="margin-top: 20px;"></div>
</div>
<!-- Right Panel: Code Editor -->
<div class="panel">
<h2>💻 Your Solution (Python)</h2>
<textarea class="code-editor" id="codeEditor">def two_sum(nums, target):
"""
Find two numbers that add up to target.
Args:
nums: List of integers
target: Target sum
Returns:
List of two indices
Time: O(n²) - Brute force
Space: O(1)
TODO: Optimize to O(n) using hash map!
"""
# Your code here
pass <div class="controls">
<button class="btn btn-run" onclick="runCode()">▶️ Run Tests</button>
<button class="btn btn-hint" onclick="getHint()">💡 Get Hint</button>
<button class="btn btn-solution" onclick="showSolution()">✨ Show Solution</button>
</div>
<div class="output" id="output">Click "Run Tests" to test your solution...</div>
</div> <div class="controls">
<button class="btn btn-run" onclick="runCode()">▶️ Run Tests</button>
<button class="btn btn-hint" onclick="getHint()">💡 Get Hint</button>
<button class="btn btn-solution" onclick="showSolution()">✨ Show Solution</button>
</div>
<div class="output" id="output">Click "Run Tests" to test your solution...</div>
</div> document.getElementById('codeEditor').value = solution;
alert('✨ Solution revealed! Study the pattern and try to implement it yourself next time.');
} document.getElementById('codeEditor').value = solution;
alert('✨ Solution revealed! Study the pattern and try to implement it yourself next time.');
}undefinedundefinedundefinedundefined// Hash Map pattern
function twoSum(nums: number[], target: number): number[] {
const seen = new Map<number, number>();
for (let i = 0; i < nums.length; i++) {
const complement = target - nums[i];
if (seen.has(complement)) {
return [seen.get(complement)!, i];
}
seen.set(nums[i], i);
}
return [];
}// Hash Map pattern
function twoSum(nums: number[], target: number): number[] {
const seen = new Map<number, number>();
for (let i = 0; i < nums.length; i++) {
const complement = target - nums[i];
if (seen.has(complement)) {
return [seen.get(complement)!, i];
}
seen.set(nums[i], i);
}
return [];
}// Hash Map pattern
fun twoSum(nums: IntArray, target: Int): IntArray {
val seen = mutableMapOf<Int, Int>()
nums.forEachIndexed { i, num ->
val complement = target - num
if (seen.containsKey(complement)) {
return intArrayOf(seen[complement]!!, i)
}
seen[num] = i
}
return intArrayOf()
}// Hash Map pattern
fun twoSum(nums: IntArray, target: Int): IntArray {
val seen = mutableMapOf<Int, Int>()
nums.forEachIndexed { i, num ->
val complement = target - num
if (seen.containsKey(complement)) {
return intArrayOf(seen[complement]!!, i)
}
seen[num] = i
}
return intArrayOf()
}// Hash Map pattern
func twoSum(_ nums: [Int], _ target: Int) -> [Int] {
var seen = [Int: Int]()
for (i, num) in nums.enumerated() {
let complement = target - num
if let j = seen[complement] {
return [j, i]
}
seen[num] = i
}
return []
}// Hash Map pattern
func twoSum(_ nums: [Int], _ target: Int) -> [Int] {
var seen = [Int: Int]()
for (i, num) in nums.enumerated() {
let complement = target - num
if let j = seen[complement] {
return [j, i]
}
seen[num] = i
}
return []
}See problem → Identify pattern → Apply template → Optimize看问题 → 识别模式 → 应用模板 → 优化Always analyze:
- Time complexity: O(?)
- Space complexity: O(?)
- Can we do better?始终分析:
- 时间复杂度:O(?)
- 空间复杂度:O(?)
- 能否进一步优化?1. Read problem
2. Write test cases
3. Think of edge cases
4. Code solution
5. Run tests
6. Optimize1. 阅读问题
2. 编写测试用例
3. 考虑边界情况
4. 编写解决方案代码
5. 运行测试
6. 优化Brute Force → Identify bottleneck → Apply pattern → Optimize space暴力解法 → 识别瓶颈 → 应用模式 → 空间优化- State assumptions
- Ask clarifying questions
- Think out loud
- Explain trade-offs
- Discuss alternatives- 说明假设条件
- 提出澄清问题
- 边思考边表达
- 解释权衡取舍
- 讨论替代方案/references/references/scripts/scripts