DSA Notes
HubAlgorithm vs Data Structure — Key Differences, Definitions, and How They Work TogetherApplications of DSA — How Data Structures and Algorithms Power Real-World SoftwareTime and Space Complexity — A Complete BeginnerWhat is DSA? — A Complete BeginnerWhy Learn DSA? — Career Benefits, Real-World Impact, and Long-Term ValueAsymptotic Analysis — Complete Framework with Recurrence Relations and Master TheoremBest, Average, and Worst Case Analysis — A Practical Guide for Every AlgorithmBig O Notation — Complete Guide with Formal Definition, Rules, and ExamplesBig Omega Notation — Lower Bounds, Best Case, and Formal DefinitionBig Theta (Θ) Notation — Tight Bounds and Exact Growth RatesSpace Complexity — Memory Analysis, Auxiliary Space, and Time-Space TradeoffsTime Complexity Examples — 25 Worked Problems from Basic to AdvancedArray Interview Problems — 15 Classic Problems with Complete SolutionsArray Operations — Every Operation Explained with Code, Complexity, and Edge CasesArray Rotation — Algorithms, Techniques, and Interview ProblemsArray Searching — Linear Search, Binary Search, and Advanced TechniquesArrays — The Complete Introduction to the Most Fundamental Data StructureDynamic Arrays — How Python Lists and ArrayLists Work InternallyMultidimensional Arrays — 2D Arrays, Matrices, and Memory LayoutSliding Window Technique — Complete Guide with 10 Classic ProblemsAnagram Problems — Detection, Grouping, and Sliding Window VariationsPalindrome Problems — Check, Longest, Count, and Expand Around CenterPattern Searching — KMP, Rabin-Karp, and Boyer-Moore AlgorithmsString Interview Problems — 10 Classic Problems with Complete SolutionsString Matching — Longest Common Subsequence, Edit Distance, and Z-AlgorithmString Operations — Complete Reference with Complexity and ImplementationStrings — Complete Introduction to String Data Structure and OperationsCircular Linked List — Structure, Operations, and ApplicationsDoubly Linked List — Complete Implementation with Bidirectional OperationsLinked List Interview Problems — 12 Classic Problems with Complete SolutionsLinked Lists — A Complete Introduction with Memory Model and TypesLinked List Operations — Every Technique with Code and ComplexityReverse Linked List — All Approaches from Basic to AdvancedSingly Linked List — Complete Implementation with All OperationsBalanced Parentheses — Stack-Based Validation with All VariantsInfix, Prefix, and Postfix Expressions — Stack-Based Conversion and EvaluationStack Implementation — Three Complete Implementations with Edge CasesStack Interview Problems — 10 Classic Problems with Complete SolutionsStack — Complete Introduction to LIFO Data StructureStack Using Arrays — Memory Layout, Capacity Management, and PerformanceStack Using Linked List — Implementation, Analysis, and When to Use ItCircular Queue — The Ring Buffer Explained with ImplementationDeque — Double-Ended Queue with Complete Implementation and ApplicationsPriority Queue — Complete Guide from Concept to ImplementationQueue Applications — BFS, Level-Order Traversal, 01-BFS, and MoreQueue Implementation — Array, Linked List, and Two-Stack ApproachesQueue Interview Problems — 10 Classic Problems with Complete SolutionsQueue — Complete Introduction to the FIFO Data StructureAVL Tree - Self-Balancing Binary Search TreeBinary Search Tree (BST)Binary Tree - Structure and OperationsFenwick Tree (Binary Indexed Tree)Red-Black Tree - Another Balanced BSTSegment Tree - Range Query Data StructureTree Interview Problems CollectionTree Data Structure FundamentalsTree Traversals - Inorder, Preorder, Postorder, Level OrderHeap — Complete Introduction to the Priority-Based Tree Data StructureHeap Operations — Complete Reference with Complexity AnalysisHeap Problems — 8 Classic Interview Problems with Complete SolutionsMax Heap — Complete Implementation and ApplicationsMin Heap — Complete Implementation with All OperationsPriority Queue Using Heap — Implementation, Applications, and PatternsBellman-Ford Algorithm — Shortest Path with Negative Weights and Cycle DetectionBFS Algorithm — Breadth-First Search with All Applications and VariantsDFS Algorithm — Depth-First Search with Cycle Detection and All ApplicationsDijkstraFloyd-Warshall Algorithm — All-Pairs Shortest Paths with Complete AnalysisGraph Interview Problems — 12 Classic Problems with Complete SolutionsGraph — Complete Introduction to the Most Powerful Data StructureGraph Representation — Adjacency List, Matrix, Edge List with Complete AnalysisKruskalMinimum Spanning Tree — Definition, Properties, and ApplicationsPrimShortest Path Algorithms — Complete Comparison and Selection GuideTopological Sorting — DFS and BFS (KahnUnion-Find (DSU) in Graphs — Connected Components and Dynamic ConnectivitySeparate Chaining — Complete Implementation and AnalysisCollision Handling — Chaining vs Open Addressing Complete ComparisonHash Functions — Design, Properties, and Common ImplementationsHashing — Complete Introduction to Hash Tables and Hash FunctionsHashing Problems — 10 Classic Interview Problems with Complete SolutionsOpen Addressing — Linear Probing, Quadratic Probing, and Double HashingBubble Sort — Complete Analysis with Optimizations and When to Use ItCounting Sort — O(n+k) Sorting That Breaks the Comparison Lower BoundHeap Sort — Guaranteed O(n log n) with O(1) SpaceInsertion Sort — The O(n) Best Case Sort That Powers PythonMerge Sort — Complete Guide to the Guaranteed O(n log n) Stable SortQuick Sort — The Fastest Practical Sorting Algorithm with Complete AnalysisRadix Sort — O(nk) Digit-by-Digit Sorting for Large Integer RangesSelection Sort — Complete Analysis with Swaps Minimization PropertySorting Algorithm Comparison — The Complete Decision GuideSorting — Complete Introduction to Sorting AlgorithmsBinary Search — Complete Guide with All Variants and Proof of CorrectnessInterpolation Search — O(log log n) Search for Uniformly Distributed DataLinear Search — Complete Guide with All Variants and ApplicationsSearch Algorithm Comparison — Choosing the Right Search for Every SituationSearching Interview Problems — 10 Classic Problems with Complete SolutionsTernary Search — Finding Maximum/Minimum of Unimodal FunctionsBacktracking Introduction — The Recursive Exploration with UndoRecursion Basics — The Complete BeginnerRecursion Problems — 12 Classic Problems from Basic to AdvancedRecursion Tree — Visualizing Recursion for Complexity AnalysisRecursion vs Iteration — When to Use Each and How to ConvertTail Recursion — Definition, Optimization, and Converting to IterationDP Interview Problems — 12 Classic Problems with Pattern Recognition GuideDynamic Programming — Complete Introduction with Properties and Problem IdentificationFibonacci DP — From Exponential to Linear with Memoization and Matrix ExponentiationKnapsack Problem — 0/1, Unbounded, and Fractional with Complete AnalysisLongest Common Subsequence — Complete Guide with DP Table and String VariantsLongest Increasing Subsequence — O(n log n) with Patience SortingMatrix Chain Multiplication — Interval DP with Complete AnalysisMemoization — Top-Down Dynamic Programming with CachingTabulation — Bottom-Up Dynamic Programming with Complete Table BuildingActivity Selection Problem — Greedy Scheduling with Proof of CorrectnessFractional Knapsack — Greedy by Value Density with ProofGreedy Interview Problems — 10 Classic Problems with Complete SolutionsGreedy Algorithms — Complete Introduction with Proof TechniquesHuffman Coding — Optimal Prefix-Free Data CompressionJob Sequencing Problem — Greedy Scheduling with DeadlinesBacktracking — The Complete Guide to Recursive Exploration with UndoBacktracking Problems — 12 Classic Interview Problems with Complete SolutionsN-Queens Problem — Complete Solution with Backtracking and OptimizationRat in a Maze — Backtracking Path Finding with All SolutionsSubset Generation — All Subsets, Combinations, and Partitions with BacktrackingSudoku Solver — Backtracking with Constraint PropagationCodeforces Guide — Complete Strategy to Reach 1800+ RatingCommon CP Techniques — Essential Algorithms Every Competitive Programmer Must KnowContest Strategies — How to Perform Your Best in Competitive Programming ContestsCompetitive Programming — Complete Introduction for BeginnersFast Input/Output — Why I/O Speed Matters and Complete Templates for C++ and PythonLeetCode Guide — Complete Strategy to Crack FAANG InterviewsBit Manipulation — Complete Guide with All Tricks and Interview ProblemsBloom Filter — Space-Efficient Probabilistic Membership TestingComputational Geometry — Points, Lines, Convex Hull, and Geometric AlgorithmsDisjoint Set Union (DSU) — Union-Find with Path Compression and Union by RankRandomized Algorithms — Las Vegas, Monte Carlo, and Probabilistic TechniquesSkip List — The Probabilistic Data Structure that Competes with Balanced BSTsSuffix Array — Construction, LCP Array, and String Search ApplicationsTrie Data Structure — Complete Guide with Implementation and ApplicationsAutocomplete System Using TrieLibrary Management System Using DSARoute Finder Using GraphsMini Search Engine ProjectSocial Network Analysis Using GraphsEssential Coding Patterns for InterviewsDSA Cheatsheet: Quick ReferenceEssential DSA Interview QuestionsFAANG DSA Sheet: Company-Specific Patterns and ProblemsProblem Solving Strategies for Coding InterviewsComplexity CheatsheetImportant Algorithms SummaryBest Practice Platforms for DSARecommended Books for DSA
Complete reference for all string operations — reversal, rotation, compression, checking palindrome, counting characters, removing duplicates, replacing characters, converting case, splitting and joining — each with implementation, time and space complexity, and edge cases.
1. Reversal
Example
def reverse_string(s):
# Method 1: Slicing — O(n), creates new string
return s[::-1]
def reverse_string_inplace(s):
# Method 2: Two-pointer on char array — O(n), O(n) for array conversion
chars = list(s)
left, right = 0, len(chars) - 1
while left < right:
chars[left], chars[right] = chars[right], chars[left]
left += 1
right -= 1
return ''.join(chars)
print(reverse_string("hello")) # "olleh"
print(reverse_string("abcde")) # "edcba"
Reverse Words in a String
Example
def reverse_words(s):
"""Reverse order of words, not characters."""
return ' '.join(s.split()[::-1])
print(reverse_words(" Hello World ")) # "World Hello"
def reverse_words_inplace(s):
"""Reverse words without extra space (interview version)."""
chars = list(s.strip())
# Step 1: Reverse entire string
chars.reverse()
# Step 2: Reverse each word
start = 0
for i in range(len(chars) + 1):
if i == len(chars) or chars[i] == ' ':
chars[start:i] = chars[start:i][::-1]
start = i + 1
return ''.join(chars)
3. String Compression
Example
def compress_string(s):
"""
Compress by replacing repeated characters: "aaabbc" → "a3b2c1"
Return original if compressed is longer.
"""
if not s:
return s
result = []
count = 1
for i in range(1, len(s)):
if s[i] == s[i-1]:
count += 1
else:
result.append(s[i-1] + (str(count) if count > 1 else ''))
count = 1
result.append(s[-1] + (str(count) if count > 1 else ''))
compressed = ''.join(result)
return compressed if len(compressed) < len(s) else s
print(compress_string("aaabbc")) # "a3b2c"
print(compress_string("abc")) # "abc" (no benefit)
4. Remove Duplicates
python example
def remove_duplicates_keep_order(s):
"""Remove duplicate characters, keep first occurrence. O(n)."""
seen = set()
result = []
for char in s:
if char not in seen:
seen.add(char)
result.append(char)
return ''.join(result)
print(remove_duplicates_keep_order("programming")) # "progamin"5. Character Frequency Count
Example
from collections import Counter
def char_frequency(s):
"""Count frequency of each character. O(n)."""
return dict(Counter(s))
print(char_frequency("hello")) # {'h':1, 'e':1, 'l':2, 'o':1}
def most_frequent_char(s):
freq = Counter(s)
return freq.most_common(1)[0] # ('l', 2) for "hello"
6. Case Conversion
python example
s = "Hello World"
print(s.upper()) # "HELLO WORLD"
print(s.lower()) # "hello world"
print(s.title()) # "Hello World"
print(s.swapcase()) # "hELLO wORLD"
print(s.capitalize()) # "Hello world"
def toggle_case(s):
"""Toggle case of each character."""
return ''.join(c.lower() if c.isupper() else c.upper() for c in s)
print(toggle_case("HeLLo")) # "hEllO"7. Check Permutation / Anagram
Example
def is_anagram(s1, s2):
"""Check if s1 and s2 are anagrams. O(n)."""
if len(s1) != len(s2):
return False
return Counter(s1) == Counter(s2)
# O(1) space version for lowercase letters
def is_anagram_array(s1, s2):
if len(s1) != len(s2): return False
count = [0] * 26
for c in s1: count[ord(c) - ord('a')] += 1
for c in s2: count[ord(c) - ord('a')] -= 1
return all(x == 0 for x in count)
print(is_anagram("listen", "silent")) # True
print(is_anagram("hello", "world")) # False
8. String Formatting
python example
name, age, score = "Alice", 25, 98.5
# f-strings (Python 3.6+) — recommended
print(f"Name: {name}, Age: {age}, Score: {score:.1f}")
# "Name: Alice, Age: 25, Score: 98.5"
# Padding and alignment
print(f"{'left':<10}|{'center':^10}|{'right':>10}")
# "left | center | right"
# Number formatting
print(f"{1234567:,}") # "1,234,567"
print(f"{0.1234:.2%}") # "12.34%"
print(f"{255:#010b}") # "0b11111111"9. Splitting and Joining
Example
# Split by delimiter
s = "a,b,c,d"
print(s.split(',')) # ['a', 'b', 'c', 'd']
print(s.split(',', 2)) # ['a', 'b', 'c,d'] — max 2 splits
# Split by whitespace (handles multiple spaces, tabs, newlines)
s = " hello world "
print(s.split()) # ['hello', 'world']
# Join
words = ['hello', 'world']
print(' '.join(words)) # "hello world"
print('-'.join(words)) # "hello-world"
print(''.join(words)) # "helloworld"
# Join efficiently
chars = ['a', 'b', 'c']
result = ''.join(chars) # O(n) — best way to build strings
10. Find and Replace
python example
s = "Hello World Hello"
# Find
print(s.find("Hello")) # 0 (first occurrence)
print(s.rfind("Hello")) # 12 (last occurrence)
print(s.find("xyz")) # -1 (not found)
# Count occurrences
print(s.count("Hello")) # 2
# Replace
print(s.replace("Hello", "Hi")) # "Hi World Hi"
print(s.replace("Hello", "Hi", 1)) # "Hi World Hello" — replace only first
# Strip characters
s = "***hello***"
print(s.strip('*')) # "hello"
print(s.lstrip('*')) # "hello***"Complexity Summary
| Operation | Time | Space | Notes |
|---|---|---|---|
| Access s[i] | O(1) | O(1) | |
| Length len(s) | O(1) | O(1) | Stored |
| Slice s[i:j] | O(j-i) | O(j-i) | Creates new string |
| Concatenate s1+s2 | O(n+m) | O(n+m) | Creates new string |
| Find/search | O(n) | O(1) | Linear scan |
| Replace | O(n) | O(n) | Creates new string |
| Split | O(n) | O(n) | Returns list |
| Join n strings | O(total_length) | O(total_length) | One allocation |
| Upper/lower | O(n) | O(n) | New string |
| Reverse | O(n) | O(n) | New string |
| Count char | O(n) | O(1) |
*Next Lesson: Pattern Searching*
Continue the lesson path
Study next in this module
01StringsString Matching — Longest Common Subsequence, Edit Distance, and Z-AlgorithmMaster string matching and similarity algorithms — Longest Common Subsequence (LCS) with DP, Edit Distance (Levenshtein), Longest Common Substring, Z-algorithm for pattern matching, and their applications in spell checking, DNA analysis, and diff utilities.02StringsStrings — Complete Introduction to String Data Structure and OperationsA thorough introduction to strings — what strings are, how they are stored in memory, immutability in Python and Java, all fundamental string operations with complexity, string comparison, slicing, building strings efficiently, and the most important string patterns for interviews.03StringsString Interview Problems — 10 Classic Problems with Complete SolutionsSolve 10 classic string interview problems — reverse words in a string, longest substring without repeating characters, minimum window substring, Roman to integer, integer to string, decode ways, word break, wildcard matching, longest common prefix, and string to integer.04StringsPattern Searching — KMP, Rabin-Karp, and Boyer-Moore AlgorithmsMaster string pattern searching algorithms — naive O(nm) approach, KMP algorithm with failure function in O(n+m), Rabin-Karp rolling hash approach, Boyer-Moore bad character rule, and when to use each algorithm. Complete implementations with detailed traces.