DSA CHEAT SHEET ā Save This Post!
Most Asked Patterns in TCS Infosys Amazon Interviews!
====================================
90% of coding interviews use THESE 10 patterns.
Master these = crack any tech interview!
====================================
PATTERN 1: TWO POINTERS
Use when: Sorted array, find pairs, remove duplicates
Problems: Two Sum, Reverse String, 3Sum
Logic: left=0, right=n-1, move based on condition
Companies: Amazon, Microsoft, TCS
PATTERN 2: SLIDING WINDOW
Use when: Subarray/substring with condition
Problems: Max sum subarray, Longest substring
Logic: Expand right, shrink left when invalid
Companies: Infosys, Wipro, Google
PATTERN 3: BINARY SEARCH
Use when: Sorted array, find position/condition
Problems: Search in rotated array, Find peak
Logic: mid = (lo+hi)//2, eliminate half each time
Companies: Amazon, Flipkart, Accenture
PATTERN 4: LINKED LIST (Fast & Slow Pointer)
Use when: Cycle detection, find middle
Problems: Detect cycle, Find middle, Palindrome
Logic: slow moves 1 step, fast moves 2 steps
Companies: TCS, Infosys, HCL
PATTERN 5: TREE BFS (Level Order)
Use when: Level-by-level traversal, shortest path
Problems: Level order, Zigzag, Right side view
Logic: Use queue, process level by level
Companies: Amazon, Cognizant, Capgemini
====================================
PATTERN 6: TREE DFS
Use when: Path sum, depth, validate BST
Problems: Max depth, Path sum, Inorder traversal
Logic: Recursion ā visit node, left, right
Companies: Microsoft, Wipro, IBM
PATTERN 7: DYNAMIC PROGRAMMING
Use when: Optimization, count ways, max/min
Problems: Fibonacci, Knapsack, LCS, Coin change
Logic: Break into subproblems, store results
Companies: Amazon, Goldman Sachs, Barclays
PATTERN 8: STACK
Use when: Matching brackets, next greater element
Problems: Valid Parentheses, Stock Span, Min Stack
Logic: Push/pop based on LIFO order
Companies: TCS, Accenture, Infosys
PATTERN 9: HASHING (HashMap)
Use when: Count frequency, find duplicates, grouping
Problems: Two Sum, Anagram, Group Anagrams
Logic: key=element, value=count/index
Companies: Google, Amazon, Flipkart
PATTERN 10: GREEDY
Use when: Local optimal = global optimal
Problems: Activity selection, Jump game, Intervals
Logic: Always pick the best option at each step
Companies: Wipro, HCL, Mindtree
====================================
MUST KNOW COMPLEXITY:
Array access -> O(1)
Binary Search -> O(log n)
Linear Search -> O(n)
Bubble Sort -> O(n2)
Merge/Quick Sort-> O(n log n)
HashMap get/put -> O(1) average
BFS/DFS -> O(V + E)
====================================
30-DAY DSA PLAN FOR PLACEMENTS:
Week 1: Arrays + Strings + Hashing
Week 2: Linked List + Stack + Queue
Week 3: Trees + Binary Search
Week 4: DP + Greedy + Mock Tests
Practice on: LeetCode / GeeksForGeeks
Target: 2 problems daily = 60 problems/month
====================================
SAVE this post now!
You will need it before every interview!
Want FREE projects for your resume too?
https://t.me/Projectwithsourcecodes
Share with your placement batch!
#DSA #DataStructures #Algorithms #CodingInterview
#TCS #Infosys #Wipro #Amazon #Microsoft #Google
#LeetCode #PlacementPrep #CampusPlacement
#BTech2026 #MCA2026 #BCA2026 #OffCampus
#DynamicProgramming #BinarySearch #LinkedList
#ProjectWithSourceCodes #StudentsOfIndia #Coding
Most Asked Patterns in TCS Infosys Amazon Interviews!
====================================
90% of coding interviews use THESE 10 patterns.
Master these = crack any tech interview!
====================================
PATTERN 1: TWO POINTERS
Use when: Sorted array, find pairs, remove duplicates
Problems: Two Sum, Reverse String, 3Sum
Logic: left=0, right=n-1, move based on condition
Companies: Amazon, Microsoft, TCS
PATTERN 2: SLIDING WINDOW
Use when: Subarray/substring with condition
Problems: Max sum subarray, Longest substring
Logic: Expand right, shrink left when invalid
Companies: Infosys, Wipro, Google
PATTERN 3: BINARY SEARCH
Use when: Sorted array, find position/condition
Problems: Search in rotated array, Find peak
Logic: mid = (lo+hi)//2, eliminate half each time
Companies: Amazon, Flipkart, Accenture
PATTERN 4: LINKED LIST (Fast & Slow Pointer)
Use when: Cycle detection, find middle
Problems: Detect cycle, Find middle, Palindrome
Logic: slow moves 1 step, fast moves 2 steps
Companies: TCS, Infosys, HCL
PATTERN 5: TREE BFS (Level Order)
Use when: Level-by-level traversal, shortest path
Problems: Level order, Zigzag, Right side view
Logic: Use queue, process level by level
Companies: Amazon, Cognizant, Capgemini
====================================
PATTERN 6: TREE DFS
Use when: Path sum, depth, validate BST
Problems: Max depth, Path sum, Inorder traversal
Logic: Recursion ā visit node, left, right
Companies: Microsoft, Wipro, IBM
PATTERN 7: DYNAMIC PROGRAMMING
Use when: Optimization, count ways, max/min
Problems: Fibonacci, Knapsack, LCS, Coin change
Logic: Break into subproblems, store results
Companies: Amazon, Goldman Sachs, Barclays
PATTERN 8: STACK
Use when: Matching brackets, next greater element
Problems: Valid Parentheses, Stock Span, Min Stack
Logic: Push/pop based on LIFO order
Companies: TCS, Accenture, Infosys
PATTERN 9: HASHING (HashMap)
Use when: Count frequency, find duplicates, grouping
Problems: Two Sum, Anagram, Group Anagrams
Logic: key=element, value=count/index
Companies: Google, Amazon, Flipkart
PATTERN 10: GREEDY
Use when: Local optimal = global optimal
Problems: Activity selection, Jump game, Intervals
Logic: Always pick the best option at each step
Companies: Wipro, HCL, Mindtree
====================================
MUST KNOW COMPLEXITY:
Array access -> O(1)
Binary Search -> O(log n)
Linear Search -> O(n)
Bubble Sort -> O(n2)
Merge/Quick Sort-> O(n log n)
HashMap get/put -> O(1) average
BFS/DFS -> O(V + E)
====================================
30-DAY DSA PLAN FOR PLACEMENTS:
Week 1: Arrays + Strings + Hashing
Week 2: Linked List + Stack + Queue
Week 3: Trees + Binary Search
Week 4: DP + Greedy + Mock Tests
Practice on: LeetCode / GeeksForGeeks
Target: 2 problems daily = 60 problems/month
====================================
SAVE this post now!
You will need it before every interview!
Want FREE projects for your resume too?
https://t.me/Projectwithsourcecodes
Share with your placement batch!
#DSA #DataStructures #Algorithms #CodingInterview
#TCS #Infosys #Wipro #Amazon #Microsoft #Google
#LeetCode #PlacementPrep #CampusPlacement
#BTech2026 #MCA2026 #BCA2026 #OffCampus
#DynamicProgramming #BinarySearch #LinkedList
#ProjectWithSourceCodes #StudentsOfIndia #Coding
Telegram
ProjectWithSourceCodes
Free Source Code Projects for Students š | Python | Java | Android | Web Dev | AI/ML | Final Year Projects | BCA ⢠BTech ⢠MCA | Interview Prep | Job Alerts
Website: https://updategadh.com
Website: https://updategadh.com
ā¤1
DSA CHEAT SHEET - Save This!
Data Structures Asked in Every Tech Interview!
====================================
DSA is tested at Amazon, Google, Microsoft,
Flipkart, Adobe, Uber, Swiggy ā ALL of them!
Master these before your placement rounds!
====================================
ARRAYS - Most Basic, Most Asked!
Two Sum -> HashMap O(n)
Find max/min -> linear scan O(n)
Reverse array -> two pointers O(n)
Find duplicates -> HashSet O(n)
Rotate by k -> reverse technique O(n)
Subarray sum -> sliding window O(n)
Merge sorted arrays -> two pointer O(n+m)
====================================
STRINGS
Palindrome check -> two pointers O(n)
Anagram check -> sort or HashMap O(n)
Longest substring no repeat -> sliding window
String reversal -> s[::-1] in Python
Count char frequency -> HashMap O(n)
====================================
LINKED LIST - Very Frequently Asked!
Reverse linked list -> 3 pointer trick O(n)
Detect cycle -> Floyd's slow/fast O(n)
Find middle -> slow/fast pointers O(n)
Merge 2 sorted lists -> compare & link O(n)
Remove Nth from end -> two pass O(n)
====================================
STACK & QUEUE
Stack (LIFO) - use for:
-> Valid parentheses {[()]}
-> Next Greater Element
-> Undo/Redo operations
Queue (FIFO) - use for:
-> BFS (level order tree traversal)
-> Sliding window maximum
====================================
TREES - 30% of Interview Questions!
Inorder: Left Root Right
Preorder: Root Left Right
Postorder: Left Right Root
Level Order: BFS using Queue
Height of tree -> recursion O(n)
Check BST valid -> inorder sorted check
Lowest Common Ancestor -> recursive O(n)
Path sum root to leaf -> DFS O(n)
====================================
GRAPHS
BFS -> Queue, shortest path unweighted
DFS -> Stack/Recursion, path finding
Detect cycle undirected -> Union Find
Detect cycle directed -> DFS + visited
Topological Sort -> Kahn's algo (BFS)
====================================
DYNAMIC PROGRAMMING
Fibonacci -> memoization O(n)
0/1 Knapsack -> 2D DP O(n*W)
Longest Common Subsequence -> 2D DP
Coin Change -> bottom-up DP O(n*amount)
Climb Stairs -> DP same as Fibonacci
====================================
TIME COMPLEXITY QUICK REFERENCE:
O(1) Constant | Array index
O(logn) Log | Binary search
O(n) Linear | Single loop
O(nlogn) Linearithmic | Merge sort
O(n2) Quadratic | Nested loops
O(2n) Exponential | Recursion tree
====================================
TOP DSA PRACTICE PLATFORMS:
LeetCode -> leetcode.com (must!)
GeeksForGeeks -> geeksforgeeks.org
HackerRank -> hackerrank.com
Codeforces -> codeforces.com
====================================
Save this - revise before every interview!
Get FREE projects with DSA implementations:
https://t.me/Projectwithsourcecodes
Share with your placement batch!
#DSACheatSheet #DSA #DataStructures #Algorithms
#LeetCode #CodingInterview #Placements #FAANG
#BTech2026 #MCA2026 #BCA2026 #CompetitiveCoding
#Java #Python #TechInterview #DynamicProgramming
#ProjectWithSourceCodes #StudentsOfIndia
Data Structures Asked in Every Tech Interview!
====================================
DSA is tested at Amazon, Google, Microsoft,
Flipkart, Adobe, Uber, Swiggy ā ALL of them!
Master these before your placement rounds!
====================================
ARRAYS - Most Basic, Most Asked!
Two Sum -> HashMap O(n)
Find max/min -> linear scan O(n)
Reverse array -> two pointers O(n)
Find duplicates -> HashSet O(n)
Rotate by k -> reverse technique O(n)
Subarray sum -> sliding window O(n)
Merge sorted arrays -> two pointer O(n+m)
====================================
STRINGS
Palindrome check -> two pointers O(n)
Anagram check -> sort or HashMap O(n)
Longest substring no repeat -> sliding window
String reversal -> s[::-1] in Python
Count char frequency -> HashMap O(n)
====================================
LINKED LIST - Very Frequently Asked!
Reverse linked list -> 3 pointer trick O(n)
Detect cycle -> Floyd's slow/fast O(n)
Find middle -> slow/fast pointers O(n)
Merge 2 sorted lists -> compare & link O(n)
Remove Nth from end -> two pass O(n)
====================================
STACK & QUEUE
Stack (LIFO) - use for:
-> Valid parentheses {[()]}
-> Next Greater Element
-> Undo/Redo operations
Queue (FIFO) - use for:
-> BFS (level order tree traversal)
-> Sliding window maximum
====================================
TREES - 30% of Interview Questions!
Inorder: Left Root Right
Preorder: Root Left Right
Postorder: Left Right Root
Level Order: BFS using Queue
Height of tree -> recursion O(n)
Check BST valid -> inorder sorted check
Lowest Common Ancestor -> recursive O(n)
Path sum root to leaf -> DFS O(n)
====================================
GRAPHS
BFS -> Queue, shortest path unweighted
DFS -> Stack/Recursion, path finding
Detect cycle undirected -> Union Find
Detect cycle directed -> DFS + visited
Topological Sort -> Kahn's algo (BFS)
====================================
DYNAMIC PROGRAMMING
Fibonacci -> memoization O(n)
0/1 Knapsack -> 2D DP O(n*W)
Longest Common Subsequence -> 2D DP
Coin Change -> bottom-up DP O(n*amount)
Climb Stairs -> DP same as Fibonacci
====================================
TIME COMPLEXITY QUICK REFERENCE:
O(1) Constant | Array index
O(logn) Log | Binary search
O(n) Linear | Single loop
O(nlogn) Linearithmic | Merge sort
O(n2) Quadratic | Nested loops
O(2n) Exponential | Recursion tree
====================================
TOP DSA PRACTICE PLATFORMS:
LeetCode -> leetcode.com (must!)
GeeksForGeeks -> geeksforgeeks.org
HackerRank -> hackerrank.com
Codeforces -> codeforces.com
====================================
Save this - revise before every interview!
Get FREE projects with DSA implementations:
https://t.me/Projectwithsourcecodes
Share with your placement batch!
#DSACheatSheet #DSA #DataStructures #Algorithms
#LeetCode #CodingInterview #Placements #FAANG
#BTech2026 #MCA2026 #BCA2026 #CompetitiveCoding
#Java #Python #TechInterview #DynamicProgramming
#ProjectWithSourceCodes #StudentsOfIndia
Telegram
ProjectWithSourceCodes
Free Source Code Projects for Students š | Python | Java | Android | Web Dev | AI/ML | Final Year Projects | BCA ⢠BTech ⢠MCA | Interview Prep | Job Alerts
Website: https://updategadh.com
Website: https://updategadh.com
š Advanced Coding Interview Questions with Answers (Part 1)
1ļøā£ Find the Longest Substring Without Repeating Characters
š Given a string, find the length of the longest substring containing no duplicate characters.
š Output:
ā± Time Complexity: O(n)
š¾ Space Complexity: O(n)
---
2ļøā£ Find the Kth Largest Element in an Array
š Find the Kth largest element without completely sorting the array.
š Output:
ā± Time Complexity: O(n log k)
š¾ Space Complexity: O(k)
---
3ļøā£ Detect a Cycle in a Linked List
š Determine whether a linked list contains a cycle using Floyd's Cycle Detection Algorithm.
š” The slow pointer moves one step while the fast pointer moves two steps.
ā± Time Complexity: O(n)
š¾ Space Complexity: O(1)
---
4ļøā£ Find the Maximum Subarray Sum
š Find the contiguous subarray with the largest sum using Kadane's Algorithm.
š Output:
ā± Time Complexity: O(n)
š¾ Space Complexity: O(1)
---
5ļøā£ Merge Overlapping Intervals
š Given a collection of intervals, merge all overlapping intervals.
š Output:
ā± Time Complexity: O(n log n)
š¾ Space Complexity: O(n)
---
š¬ Save this for your advanced coding interview preparation!
š„ Part 2 will cover 5 harder problems on Binary Search, Dynamic Programming, Graphs, Backtracking & Sliding Window.
#Coding #CodingInterview #Python #DSA #AdvancedCoding #Algorithms #DynamicProgramming #Graphs #Programming #TechInterview
1ļøā£ Find the Longest Substring Without Repeating Characters
š Given a string, find the length of the longest substring containing no duplicate characters.
def longest_unique_substring(s):
seen = set()
left = 0
max_length = 0
for right in range(len(s)):
while s[right] in seen:
seen.remove(s[left])
left += 1
seen.add(s[right])
max_length = max(max_length, right - left + 1)
return max_length
print(longest_unique_substring("abcabcbb"))
š Output:
3
ā± Time Complexity: O(n)
š¾ Space Complexity: O(n)
---
2ļøā£ Find the Kth Largest Element in an Array
š Find the Kth largest element without completely sorting the array.
import heapq
def kth_largest(nums, k):
heap = nums[:k]
heapq.heapify(heap)
for num in nums[k:]:
if num > heap[0]:
heapq.heapreplace(heap, num)
return heap[0]
print(kth_largest([3, 2, 1, 5, 6, 4], 2))
š Output:
5
ā± Time Complexity: O(n log k)
š¾ Space Complexity: O(k)
---
3ļøā£ Detect a Cycle in a Linked List
š Determine whether a linked list contains a cycle using Floyd's Cycle Detection Algorithm.
def has_cycle(head):
slow = head
fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast:
return True
return False
š” The slow pointer moves one step while the fast pointer moves two steps.
ā± Time Complexity: O(n)
š¾ Space Complexity: O(1)
---
4ļøā£ Find the Maximum Subarray Sum
š Find the contiguous subarray with the largest sum using Kadane's Algorithm.
def max_subarray_sum(nums):
current = nums[0]
maximum = nums[0]
for num in nums[1:]:
current = max(num, current + num)
maximum = max(maximum, current)
return maximum
print(max_subarray_sum([-2, 1, -3, 4, -1, 2, 1, -5, 4]))
š Output:
6
ā± Time Complexity: O(n)
š¾ Space Complexity: O(1)
---
5ļøā£ Merge Overlapping Intervals
š Given a collection of intervals, merge all overlapping intervals.
def merge_intervals(intervals):
intervals.sort(key=lambda x: x[0])
merged = []
for start, end in intervals:
if not merged or start > merged[-1][1]:
merged.append([start, end])
else:
merged[-1][1] = max(merged[-1][1], end)
return merged
print(merge_intervals([[1, 3], [2, 6], [8, 10], [9, 12]]))
š Output:
[[1, 6], [8, 12]]
ā± Time Complexity: O(n log n)
š¾ Space Complexity: O(n)
---
š¬ Save this for your advanced coding interview preparation!
š„ Part 2 will cover 5 harder problems on Binary Search, Dynamic Programming, Graphs, Backtracking & Sliding Window.
#Coding #CodingInterview #Python #DSA #AdvancedCoding #Algorithms #DynamicProgramming #Graphs #Programming #TechInterview
š Advanced Coding Interview Questions with Answers (Part 3)
1ļøā£1ļøā£ Find the Top K Frequent Elements
š Given an array, return the
š Output:
ā±ļø Time Complexity: O(n log n)
š¾ Space Complexity: O(n)
1ļøā£2ļøā£ Generate All Permutations of a String
š Generate every possible arrangement of the characters in a string using Backtracking.
š Output:
ā±ļø Time Complexity: O(n Ć n!)
š¾ Space Complexity: O(n Ć n!)
1ļøā£3ļøā£ Find the Minimum Coins for a Given Amount
š Given coin denominations, find the minimum number of coins required to make a target amount.
š Output:
š”
ā±ļø Time Complexity: O(amount Ć number of coins)
š¾ Space Complexity: O(amount)
1ļøā£4ļøā£ Find the Maximum Product Subarray
š Find the contiguous subarray whose elements have the largest product.
š Output:
š” The maximum product comes from
ā±ļø Time Complexity: O(n)
š¾ Space Complexity: O(1)
1ļøā£5ļøā£ Implement an LRU Cache
š An LRU (Least Recently Used) Cache removes the item that has not been accessed for the longest time when the cache reaches its capacity.
š Example:
š Output:
ā±ļø Average Time Complexity: O(1) for
š¾ Space Complexity: O(capacity)
š¬ Save this for your advanced coding interview preparation!
š„ Part 4 will cover 5 advanced problems on Dijkstra's Algorithm, Trie, Union-Find, Matrix & Dynamic Programming.
#Coding #CodingInterview #Python #DSA #AdvancedCoding #Algorithms #DynamicProgramming #Graph #DataStructures #Programming
1ļøā£1ļøā£ Find the Top K Frequent Elements
š Given an array, return the
k elements that appear most frequently.from collections import Counter
def top_k_frequent(nums, k):
frequency = Counter(nums)
return [num for num, count in frequency.most_common(k)]
print(top_k_frequent([1, 1, 1, 2, 2, 3], 2))
š Output:
[1, 2]
ā±ļø Time Complexity: O(n log n)
š¾ Space Complexity: O(n)
1ļøā£2ļøā£ Generate All Permutations of a String
š Generate every possible arrangement of the characters in a string using Backtracking.
def permutations(s):
result = []
def backtrack(path, remaining):
if not remaining:
result.append("".join(path))
return
for i in range(len(remaining)):
backtrack(
path + [remaining[i]],
remaining[:i] + remaining[i + 1:]
)
backtrack([], s)
return result
print(permutations("ABC"))
š Output:
['ABC', 'ACB', 'BAC', 'BCA', 'CAB', 'CBA']
ā±ļø Time Complexity: O(n Ć n!)
š¾ Space Complexity: O(n Ć n!)
1ļøā£3ļøā£ Find the Minimum Coins for a Given Amount
š Given coin denominations, find the minimum number of coins required to make a target amount.
def min_coins(coins, amount):
dp = [float("inf")] * (amount + 1)
dp[0] = 0
for current in range(1, amount + 1):
for coin in coins:
if coin <= current:
dp[current] = min(
dp[current],
dp[current - coin] + 1
)
return dp[amount] if dp[amount] != float("inf") else -1
print(min_coins([1, 2, 5], 11))
š Output:
3
š”
5 + 5 + 1 = 11ā±ļø Time Complexity: O(amount Ć number of coins)
š¾ Space Complexity: O(amount)
1ļøā£4ļøā£ Find the Maximum Product Subarray
š Find the contiguous subarray whose elements have the largest product.
def max_product_subarray(nums):
current_max = nums[0]
current_min = nums[0]
result = nums[0]
for num in nums[1:]:
if num < 0:
current_max, current_min = current_min, current_max
current_max = max(num, current_max * num)
current_min = min(num, current_min * num)
result = max(result, current_max)
return result
print(max_product_subarray([2, 3, -2, 4]))
š Output:
6
š” The maximum product comes from
[2, 3].ā±ļø Time Complexity: O(n)
š¾ Space Complexity: O(1)
1ļøā£5ļøā£ Implement an LRU Cache
š An LRU (Least Recently Used) Cache removes the item that has not been accessed for the longest time when the cache reaches its capacity.
from collections import OrderedDict
class LRUCache:
def __init__(self, capacity):
self.capacity = capacity
self.cache = OrderedDict()
def get(self, key):
if key not in self.cache:
return -1
self.cache.move_to_end(key)
return self.cache[key]
def put(self, key, value):
if key in self.cache:
self.cache.move_to_end(key)
self.cache[key] = value
if len(self.cache) > self.capacity:
self.cache.popitem(last=False)
š Example:
cache = LRUCache(2)
cache.put(1, "A")
cache.put(2, "B")
print(cache.get(1))
cache.put(3, "C")
print(cache.get(2))
š Output:
A
-1
ā±ļø Average Time Complexity: O(1) for
get() and put()š¾ Space Complexity: O(capacity)
š¬ Save this for your advanced coding interview preparation!
š„ Part 4 will cover 5 advanced problems on Dijkstra's Algorithm, Trie, Union-Find, Matrix & Dynamic Programming.
#Coding #CodingInterview #Python #DSA #AdvancedCoding #Algorithms #DynamicProgramming #Graph #DataStructures #Programming
š Advanced Coding Interview Questions with Answers (Part 4)
1ļøā£6ļøā£ Find the Shortest Path Using Dijkstra's Algorithm
š Dijkstra's Algorithm finds the shortest path from a source node to other nodes in a graph with non-negative edge weights.
ā±ļø Time Complexity: O((V + E) log V)
1ļøā£7ļøā£ Implement a Trie
š A Trie is a tree-based data structure commonly used for prefix searching and autocomplete.
ā±ļø Time Complexity: O(L) per operation
1ļøā£8ļøā£ Find Connected Components Using Union-Find
š Union-Find, also called Disjoint Set Union (DSU), efficiently manages groups of connected elements.
š” It is commonly used in graph connectivity and Kruskal's algorithm.
ā±ļø Amortized Time: Nearly O(1) per operation with path compression and union by rank/size.
1ļøā£9ļøā£ Rotate a Matrix 90 Degrees Clockwise
š Rotate an
š Output:
ā±ļø Time Complexity: O(n²)
š¾ Space Complexity: O(1)
2ļøā£0ļøā£ Solve the 0/1 Knapsack Problem
š Given items with weights and values, find the maximum value that can be placed in a bag with limited capacity.
š Output:
ā±ļø Time Complexity: O(n Ć capacity)
š¾ Space Complexity: O(capacity)
š¬ Save this for your advanced coding interview preparation!
š„ Next: Generative AI ā Part 9
#Coding #DSA #Python #AdvancedCoding #Algorithms #DynamicProgramming #Graphs #InterviewQuestions
1ļøā£6ļøā£ Find the Shortest Path Using Dijkstra's Algorithm
š Dijkstra's Algorithm finds the shortest path from a source node to other nodes in a graph with non-negative edge weights.
import heapq
def dijkstra(graph, start):
distances = {node: float("inf") for node in graph}
distances[start] = 0
heap = [(0, start)]
while heap:
distance, node = heapq.heappop(heap)
if distance > distances[node]:
continue
for neighbor, weight in graph[node]:
new_distance = distance + weight
if new_distance < distances[neighbor]:
distances[neighbor] = new_distance
heapq.heappush(heap, (new_distance, neighbor))
return distances
ā±ļø Time Complexity: O((V + E) log V)
1ļøā£7ļøā£ Implement a Trie
š A Trie is a tree-based data structure commonly used for prefix searching and autocomplete.
class TrieNode:
def __init__(self):
self.children = {}
self.is_end = False
class Trie:
def __init__(self):
self.root = TrieNode()
def insert(self, word):
node = self.root
for char in word:
if char not in node.children:
node.children[char] = TrieNode()
node = node.children[char]
node.is_end = True
def search(self, word):
node = self.root
for char in word:
if char not in node.children:
return False
node = node.children[char]
return node.is_end
ā±ļø Time Complexity: O(L) per operation
L = length of the word1ļøā£8ļøā£ Find Connected Components Using Union-Find
š Union-Find, also called Disjoint Set Union (DSU), efficiently manages groups of connected elements.
class DSU:
def __init__(self, n):
self.parent = list(range(n))
def find(self, x):
if self.parent[x] != x:
self.parent[x] = self.find(self.parent[x])
return self.parent[x]
def union(self, a, b):
root_a = self.find(a)
root_b = self.find(b)
if root_a != root_b:
self.parent[root_b] = root_a
š” It is commonly used in graph connectivity and Kruskal's algorithm.
ā±ļø Amortized Time: Nearly O(1) per operation with path compression and union by rank/size.
1ļøā£9ļøā£ Rotate a Matrix 90 Degrees Clockwise
š Rotate an
n Ć n matrix 90 degrees clockwise in place.def rotate(matrix):
n = len(matrix)
for i in range(n):
for j in range(i + 1, n):
matrix[i][j], matrix[j][i] = (
matrix[j][i],
matrix[i][j]
)
for row in matrix:
row.reverse()
return matrix
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
print(rotate(matrix))
š Output:
[[7, 4, 1],
[8, 5, 2],
[9, 6, 3]]
ā±ļø Time Complexity: O(n²)
š¾ Space Complexity: O(1)
2ļøā£0ļøā£ Solve the 0/1 Knapsack Problem
š Given items with weights and values, find the maximum value that can be placed in a bag with limited capacity.
def knapsack(weights, values, capacity):
dp = [0] * (capacity + 1)
for i in range(len(weights)):
for w in range(capacity, weights[i] - 1, -1):
dp[w] = max(
dp[w],
dp[w - weights[i]] + values[i]
)
return dp[capacity]
print(knapsack([1, 3, 4], [15, 50, 60], 4))
š Output:
65
ā±ļø Time Complexity: O(n Ć capacity)
š¾ Space Complexity: O(capacity)
š¬ Save this for your advanced coding interview preparation!
š„ Next: Generative AI ā Part 9
#Coding #DSA #Python #AdvancedCoding #Algorithms #DynamicProgramming #Graphs #InterviewQuestions