0% found this document useful (0 votes)
28 views2 pages

DSA Cheatsheet Python With Code

This document is a DSA cheat sheet for Python, providing code snippets for various algorithms and techniques. It covers the Two Pointer Technique, Sliding Window, Hashing, Binary Search, Recursion, Stack, Queue, Linked List Reverse, Tree DFS, and Dynamic Programming for Fibonacci. Each section includes a brief explanation and corresponding code examples.

Uploaded by

ritamcind
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views2 pages

DSA Cheatsheet Python With Code

This document is a DSA cheat sheet for Python, providing code snippets for various algorithms and techniques. It covers the Two Pointer Technique, Sliding Window, Hashing, Binary Search, Recursion, Stack, Queue, Linked List Reverse, Tree DFS, and Dynamic Programming for Fibonacci. Each section includes a brief explanation and corresponding code examples.

Uploaded by

ritamcind
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

DSA Cheat Sheet (Python) – With Code Snippets

Two Pointer Technique


Used for sorted arrays, pair sum problems
l, r = 0, len(arr)-1
while l < r:
if arr[l] + arr[r] == target:
return True
elif arr[l] + arr[r] < target:
l += 1
else:
r -= 1

Sliding Window
Used for subarray max/min or sum problems
window_sum = sum(arr[:k])
max_sum = window_sum

for i in range(k, len(arr)):


window_sum += arr[i] - arr[i-k]
max_sum = max(max_sum, window_sum)

Hashing / Frequency Count


Used for fast lookup, anagrams, duplicates
from collections import Counter
freq = Counter(arr)

Binary Search
Used when data is sorted, O(log n)
l, r = 0, len(arr)-1
while l <= r:
mid = (l+r)//2
if arr[mid] == target:
return mid
elif arr[mid] < target:
l = mid + 1
else:
r = mid - 1

Recursion
Break problem into smaller subproblems
def factorial(n):
if n == 1:
return 1
return n * factorial(n-1)

Stack
LIFO – used in parenthesis check
stack = []
for ch in s:
if ch == '(':
[Link](ch)
else:
[Link]()

Queue (BFS)
FIFO – used in BFS and scheduling
from collections import deque
q = deque([root])
while q:
node = [Link]()

Linked List Reverse


Pointer manipulation logic
prev = None
curr = head
while curr:
nxt = [Link]
[Link] = prev
prev = curr
curr = nxt

Tree DFS
Depth First Search using recursion
def dfs(root):
if not root:
return
dfs([Link])
dfs([Link])

Dynamic Programming – Fibonacci


Optimized recursion using tabulation
dp = [0, 1]
for i in range(2, n+1):
[Link](dp[i-1] + dp[i-2])

You might also like