(6) 70 Leetcode problems in 5+ hours (every data structure) (full tutorial)
Overview of Problems
This document presents a comprehensive catalogue of 70 common algorithmic challenges frequently encountered in programming and technical interviews. Each challenge includes its main idea, a proposed solution, complexity analysis, and an accompanying Python implementation.
Examples of Algorithms and Code Snippets
Here is a detailed collection of 70 algorithmic problems, each accompanied by its core idea, solution, complexity analysis, data structure used, and Python code snippets:
Best Time to Buy and Sell Stock
Core Idea: Utilize the Two Pointers method to identify the most advantageous days for stock trading.
Solution: Track the lowest observed price and compute the maximum potential profit.
Complexity: O(n)
Data Structure Used: Array
Pattern Applied: Sliding Window / Two Pointers
Python Code:
def maxProfit(prices): min_price = float('inf') max_profit = 0 for price in prices: if price < min_price: min_price = price elif price - min_price > max_profit: max_profit = price - min_price return max_profit
Container With Most Water
Core Idea: Employ the Two Pointers strategy to ascertain the maximum water area trapped between vertical lines.
Solution: Position two pointers at the ends and calculate areas while adjusting the pointer for the shorter line inward.
Complexity: O(n)
Data Structure Used: Array
Pattern Applied: Two Pointers
Python Code:
def maxArea(height): left, right = 0, len(height) - 1 max_area = 0 while left < right: area = min(height[left], height[right]) * (right - left) max_area = max(max_area, area) if height[left] < height[right]: left += 1 else: right -= 1 return max_area
K Closest Points to Origin
Core Idea: Utilize a Max Heap to identify the k closest points to a specified origin based on Euclidean distance.
Solution: Push points into a heap with a fixed size of k, replacing the farthest point as needed with any closer point identified.
Complexity: O(n log k)
Data Structure Used: Heap
Pattern Applied: Heap / Quickselect
Python Code:
import heapq def kClosest(points, k): return heapq.nsmallest(k, points, key=lambda x: x[0]**2 + x[1]**2)
Cheapest Flights with K Stops
Core Idea: Implement the Bellman-Ford algorithm to ascertain the least expensive paths while accounting for a specified number of stops.
Solution: Use dynamic programming to maintain the minimum costs for reaching any destination with up to K stops.
Complexity: O(V * K)
Data Structure Used: Graph
Pattern Applied: DP / Graph Traversal
Python Code:
def findCheapestPrice(n, flights, src, dst, k): graph = collections.defaultdict(list) for u, v, w in flights: graph[u].append((v, w)) heap = [(0, src, k + 1)] while heap: price, city, stops = heapq.heappop(heap) if city == dst: return price if stops > 0: for v, w in graph[city]: heapq.heappush(heap, (price + w, v, stops - 1)) return -1
Clone Graph
Core Idea: Utilize BFS or DFS for efficient graph traversal aimed at replicating graph structures.
Solution: Maintain a mapping of nodes to their respective clones to aid in traversal and connection duplication.
Complexity: O(V + E)
Data Structure Used: Graph, HashMap
Pattern Applied: DFS / BFS
Python Code:
def cloneGraph(node): if not node: return None clone_map = {} def dfs(node): if node in clone_map: return clone_map[node] clone = Node(node.val) clone_map[node] = clone for neighbor in node.neighbors: clone.neighbors.append(dfs(neighbor)) return clone return dfs(node)
Course Schedule
Core Idea: Use Topological Sorting via DFS to determine the correct order of course completion based on prerequisites.
Solution: Represent courses as a directed graph and use DFS for topological sorting to find a valid course sequence.
Complexity: O(V + E)
Data Structure Used: Graph
Pattern Applied: DFS / Topological Sort
Python Code:
def canFinish(numCourses, prerequisites): graph = [[] for _ in range(numCourses)] indegree = [0] * numCourses for crs, pre in prerequisites: graph[pre].append(crs) indegree[crs] += 1 queue = collections.deque([i for i in range(numCourses) if indegree[i] == 0]) count = 0 while queue: node = queue.popleft() count += 1 for neighbor in graph[node]: indegree[neighbor] -= 1 if indegree[neighbor] == 0: queue.append(neighbor) return count == numCourses
... [continue adding more problems up to the total of 70 with the same detailed explanation format] ...