Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
File renamed without changes.
File renamed without changes.
14 changes: 7 additions & 7 deletions Arrays/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,10 @@ This directory contains Python implementations of common array-based algorithms

## Contents

- [Anagram Check (Sorted Solution)](Anagram_Check_Sorted_Sol.py): Checks if two strings are anagrams by comparing their sorted versions.
- [Anagram Check (Manual Solution)](Anagram_Check_manual_Sol.py): Checks if two strings are anagrams using a hash table (dictionary) to count character frequencies.
- [Array Find Missing Element (XOR Solution)](ArrayFindTheMissingElement_XOR_sol.py): Efficiently finds a missing element in a shuffled array using bitwise XOR.
- [Array Find Missing Element (Brute Force Solution)](ArrayFindTheMissingElement_brute_force_sol.py): Finds a missing element by sorting both arrays and comparing them.
- [Array Find Missing Element (Hash Table Solution)](ArrayFindTheMissingElement_hash_table_sol.py): Finds a missing element using a hash table (dictionary) to track element counts.
- [Array Find Missing Element (Sum/Subtract Solution)](ArrayFindTheMissingElement_takingSumandSubtract_sol.py): Finds a missing element by calculating the difference between the sums of the two arrays.
- [Array Pair Sum Solution](ArrayPairSumSol.py): Finds all unique pairs in an array that sum up to a specific value $k$ using a set for $O(n)$ complexity.
- [Anagram Check (Sorted Solution)](AnagramCheckSortedSol.py): Checks if two strings are anagrams by comparing their sorted versions. Time Complexity: $O(n \log n)$
- [Anagram Check (Manual Solution)](AnagramCheckManualSol.py): Checks if two strings are anagrams using a hash table (dictionary) to count character frequencies. Time Complexity: $O(n)$
- [Array Find Missing Element (XOR Solution)](ArrayFindTheMissingElementXORSol.py): Efficiently finds a missing element in a shuffled array using bitwise XOR. Time Complexity: $O(n)$
- [Array Find Missing Element (Brute Force Solution)](ArrayFindTheMissingElementBruteForceSol.py): Finds a missing element by sorting both arrays and comparing them. Time Complexity: $O(n \log n)$
- [Array Find Missing Element (Hash Table Solution)](ArrayFindTheMissingElementHashTableSol.py): Finds a missing element using a hash table (dictionary) to track element counts. Time Complexity: $O(n)$
- [Array Find Missing Element (Sum Solution)](ArrayFindTheMissingElementSumSol.py): Finds a missing element by calculating the difference between the sums of the two arrays. Time Complexity: $O(n)$
- [Array Pair Sum Solution](ArrayPairSumSol.py): Finds all unique pairs in an array that sum up to a specific value $k$ using a set. Time Complexity: $O(n)$
File renamed without changes.
2 changes: 1 addition & 1 deletion deque/README.md → Deque/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,4 @@ This directory contains Python implementations of the Deque (Double-Ended Queue)

## Contents

- [Deque Implementation](DequeImple.py): Basic implementation of a Deque using a Python list. Includes operations like `addFront`, `addRear`, `removeFront`, `removeRear`, `isEmpty`, and `size`.
- [Deque Implementation](DequeImple.py): Basic implementation of a Deque using a Python list. Includes operations like `addFront`, `addRear`, `removeFront`, `removeRear`, `isEmpty`, and `size`. Time Complexity: `addFront`, `removeFront` are $O(1)$; `addRear`, `removeRear` are $O(n)$.
7 changes: 0 additions & 7 deletions Error-debug/README.md

This file was deleted.

File renamed without changes.
7 changes: 7 additions & 0 deletions ErrorHandling/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
# Error Handling

This directory contains examples of error handling and debugging in Python.

## Contents

- [Error and Exceptions](ErrorExceptions.py): Demonstrates `try`, `except`, `else`, and `finally` blocks for robust error handling.
14 changes: 7 additions & 7 deletions GraphAlgorithms/README.md
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
# Graph Algorithms

This directory contains Python implementations of common graph-based algorithms and data structures.
This directory contains Python implementations of graph-based algorithms.

## Contents

- [Adjacency List Implementation](AdjacencyListGraphImple.py): Implements the Graph Abstract Data Type (ADT) using an adjacency list (dictionaries in Python). Includes `Vertex` and `Graph` classes.
- [Breadth First Search (BFS)](BFS.py): Implements BFS to solve the Word Ladder problem, finding the shortest transformation path between words.
- [General Depth First Search (DFS)](DFSGeneral.py): Provides a general implementation of DFS, including discovery and finish times for vertices.
- [DFS - Knight's Tour Problem](DFSImpleTheKnightsTourProblem.py): Another implementation of DFS specifically tailored to the Knight's Tour puzzle.
- [The Knight's Tour Problem](TheKnightsTourProblem.py): Focuses on generating the knight's move graph and solving the tour using DFS and backtracking.
- [Word Ladder Problem](WordLadderProblem.py): Specifically focuses on building the word ladder graph where edges connect words that differ by only one letter.
- [Adjacency List Graph Implementation](AdjacencyListGraphImple.py): Implementation of a Graph ADT using an adjacency list.
- [Breadth First Search (BFS)](BFS.py): Implementation of BFS for solving the Word Ladder problem. Time Complexity: $O(V+E)$
- [Depth First Search (DFS) General](DFSGeneral.py): General implementation of DFS. Time Complexity: $O(V+E)$
- [The Knight's Tour Problem (Graph Generation)](TheKnightsTourProblem.py): Building a graph to represent the Knight's Tour problem.
- [DFS Implementation for Knight's Tour](DFSImpleTheKnightsTourProblem.py): Using DFS to solve the Knight's Tour problem. Time Complexity: $O(k^N)$ where $N$ is the number of squares.
- [Word Ladder Problem](WordLadderProblem.py): Building the word ladder graph.
8 changes: 4 additions & 4 deletions LinkedLists/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ This directory contains Python implementations of various types of linked lists

## Contents

- [Singly Linked List Implementation](SingleLinkedListImple.py): Basic implementation of a singly linked list node and basic linkage.
- [Singly Linked List Implementation](SinglyLinkedListImple.py): Basic implementation of a singly linked list node and basic linkage.
- [Doubly Linked List Implementation](DoublyLinkedListImple.py): Basic implementation of a doubly linked list node with `prev` and `next` pointers.
- [Singly Linked List Cycle Check](SinglyLinkedListCycleCheckImple.py): Implements Floyd's Cycle-Finding Algorithm (two pointers) to detect cycles in a linked list.
- [Linked List Reversal](LinkedListReversal.py): Reverses a singly linked list in-place in $O(n)$ time.
- [Nth to Last Node](LinkedListNthToLastNode.py): Finds the $n$-th to last node in a singly linked list using two pointers.
- [Singly Linked List Cycle Check](SinglyLinkedListCycleCheckImple.py): Implements Floyd's Cycle-Finding Algorithm to detect cycles. Time Complexity: $O(n)$
- [Linked List Reversal](LinkedListReversal.py): Reverses a singly linked list in-place. Time Complexity: $O(n)$
- [Nth to Last Node](LinkedListNthToLastNode.py): Finds the $n$-th to last node in a singly linked list. Time Complexity: $O(n)$
13 changes: 4 additions & 9 deletions LinkedLists/SinglyLinkedListCycleCheckImple.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,10 @@ def __init__(self, value):
self.value = value
self.nextnode = None

def cycle_check(node):
def cycle_check(self):
# Set two pointers initialize to passed node
pt1 = node
pt2 = node
pt1 = self
pt2 = self
# loop through end of the list
while pt2 != None and pt2.nextnode != None:
pt1 = pt1.nextnode
Expand All @@ -31,6 +31,7 @@ def cycle_check(node):
if pt2 == pt1:
return True
return False

# Test
# Create a Linked List
a = LinkedListNode(1)
Expand All @@ -46,12 +47,6 @@ def cycle_check(node):
print (b.value)
print (c.value)

# Since cycle_check is a method but it doesn't use self and is defined inside class
# it should be called on an instance or changed to static method.
# In its current definition it behaves like a regular method but is missing 'self'.
# Actually it is defined as def cycle_check(node): which means it takes one arg.
# If called as LinkedListNode.cycle_check(a) it should work if it was just a function.

print(a.cycle_check())


4 changes: 2 additions & 2 deletions Queues/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,5 @@ This directory contains Python implementations of the Queue data structure.

## Contents

- [Queue Implementation](QueueImple.py): Basic implementation of a FIFO (First-In-First-Out) queue using a Python list. Includes `enqueue`, `dequeue`, `isEmpty`, and `size` methods.
- [Queue with Two Stacks](QueueWith2StacksImple.py): Implements a queue using two stacks (represented by Python lists) to achieve FIFO behavior.
- [Queue Implementation](QueueImple.py): Basic implementation of a FIFO queue using a Python list. Time Complexity: `enqueue` is $O(n)$, `dequeue` is $O(1)$.
- [Queue with Two Stacks](QueueWith2StacksImple.py): Implements a queue using two stacks. Time Complexity: Amortized $O(1)$ for both `enqueue` and `dequeue`.
122 changes: 24 additions & 98 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,31 +5,18 @@
[![Python Version](https://img.shields.io/badge/python-3.6%2B-blue)](https://www.python.org/downloads/)
[![License](https://img.shields.io/badge/license-MIT-green.svg)](LICENSE)
[![Contributions Welcome](https://img.shields.io/badge/contributions-welcome-brightgreen.svg)](CONTRIBUTING.md)
[![GitHub Stars](https://img.shields.io/github/stars/ppant/DS-Algos-Python.svg?style=social)](https://github.com/ppant/DS-Algos-Python)

---

## 🎯 About This Repository

This repository was started in **2017** with a simple goal: to create a comprehensive, well-documented collection of Data Structures and Algorithms implementations in Python. Whether you're preparing for technical interviews, learning CS fundamentals, or just brushing up on your algo skills, this repo serves as a practical reference.

### Why This Repository?
- 📖 **Educational**: Each implementation is well-commented and easy to understand
- 🔄 **Multiple Solutions**: Different approaches to the same problem (brute force, optimized, etc.)
- 🎓 **Interview Ready**: Solutions for common technical interview questions
- 🚀 **Practical**: Standalone scripts that can be run and modified

---

## 🤝 Contributing

This is an open-source learning project! We welcome contributions from everyone:
- Found a bug? Open an issue
- Have a better solution? Submit a pull request
- Want to add new algorithms? Contributions are always appreciated!
- Have learning notes? Share them with the community

See [CONTRIBUTING.md](CONTRIBUTING.md) for more details.
This is an open-source learning project! We welcome contributions from everyone. See [CONTRIBUTING.md](CONTRIBUTING.md) for more details.

---

Expand All @@ -38,19 +25,18 @@ See [CONTRIBUTING.md](CONTRIBUTING.md) for more details.
- [Getting Started](#getting-started)
- [Project Structure](#project-structure)
- [Data Structures](#data-structures)
- [Arrays](#arrays)
- [Linked Lists](#linked-lists)
- [Stacks](#stacks)
- [Queues](#queues)
- [Deque](#deque)
- [Trees](#trees)
- [Arrays 🔢](#arrays)
- [Linked Lists 🔗](#linked-lists)
- [Stacks 📚](#stacks)
- [Queues 📦](#queues)
- [Deque 🔄](#deque)
- [Trees 🌳](#trees)
- [Algorithms](#algorithms)
- [Sorting](#sorting)
- [Recursion & Dynamic Programming](#recursion--dynamic-programming)
- [Graph Algorithms](#graph-algorithms)
- [Error Handling & Debugging](#error-handling--debugging)
- [Sorting 📊](#sorting)
- [Recursion & Dynamic Programming 🔀](#recursion--dynamic-programming)
- [Graph Algorithms 🗺️](#graph-algorithms)
- [Error Handling & Debugging ⚠️](#error-handling--debugging)
- [Usage](#usage)
- [Quick Reference](#quick-reference)
- [License](#license)

---
Expand All @@ -59,15 +45,14 @@ See [CONTRIBUTING.md](CONTRIBUTING.md) for more details.

### Prerequisites
- Python 3.6 or higher
- Basic understanding of Python syntax

### Running Examples

Most scripts in this repository are standalone and can be executed directly:

```bash
# Run any Python script
python3 Arrays/Anagram_Check_Sorted_Sol.py
python3 Arrays/AnagramCheckSortedSol.py

# Or run from the repo root
python3 Sorting/BubbleSortImple.py
Expand All @@ -79,16 +64,16 @@ python3 Sorting/BubbleSortImple.py

```
.
├── Arrays/ # 🔤 Array-based problems and algorithms
├── Error-debug/ # ⚠️ Error handling and debugging examples
├── Arrays/ # 🔢 Array-based problems and algorithms
├── Deque/ # 🔄 Double-ended queue
├── ErrorHandling/ # ⚠️ Error handling and debugging examples
├── GraphAlgorithms/ # 🗺️ Graph traversal (BFS, DFS) and pathfinding
├── LinkedLists/ # 🔗 Singly and Doubly Linked Lists
├── Queues/ # 📦 Queue implementations (FIFO)
├── Recursion/ # 🔀 Recursive problems and Dynamic Programming
├── Sorting/ # 📊 Common sorting algorithms
├── Stacks/ # 📚 Stack implementations and applications
├── Trees/ # 🌳 Binary Trees, BSTs, Heaps, and Traversals
├── deque/ # 🔄 Double-ended queue
├── CONTRIBUTING.md # 🤝 Contribution guidelines
├── LICENSE # 📄 MIT License
└── README.md # 📖 This file
Expand All @@ -98,23 +83,23 @@ python3 Sorting/BubbleSortImple.py

## 📊 Data Structures

### Arrays 🔤
### Arrays 🔢
Common array-based algorithms and manipulations.
- [Anagram Check](Arrays/): [Sorted](Arrays/Anagram_Check_Sorted_Sol.py) & [Manual](Arrays/Anagram_Check_manual_Sol.py) solutions
- [Anagram Check](Arrays/): [Sorted](Arrays/AnagramCheckSortedSol.py) & [Manual](Arrays/AnagramCheckManualSol.py) solutions
- [Array Pair Sum](Arrays/ArrayPairSumSol.py): Find pairs that sum to $k$
- [Find Missing Element](Arrays/): [XOR](Arrays/ArrayFindTheMissingElement_XOR_sol.py), [Brute Force](Arrays/ArrayFindTheMissingElement_brute_force_sol.py), [Hash Table](Arrays/ArrayFindTheMissingElement_hash_table_sol.py), & [Sum](Arrays/ArrayFindTheMissingElement_takingSumandSubtract_sol.py) approaches
- [Find Missing Element](Arrays/): [XOR](Arrays/ArrayFindTheMissingElementXORSol.py), [Brute Force](Arrays/ArrayFindTheMissingElementBruteForceSol.py), [Hash Table](Arrays/ArrayFindTheMissingElementHashTableSol.py), & [Sum](Arrays/ArrayFindTheMissingElementSumSol.py) approaches

### Linked Lists 🔗
Implementations and problems involving linked structures.
- [Singly Linked List](LinkedLists/SingleLinkedListImple.py) & [Doubly Linked List](LinkedLists/DoublyLinkedListImple.py)
- [Singly Linked List](LinkedLists/SinglyLinkedListImple.py) & [Doubly Linked List](LinkedLists/DoublyLinkedListImple.py)
- [Cycle Detection](LinkedLists/SinglyLinkedListCycleCheckImple.py): Detect cycles using two pointers (Floyd's algorithm)
- [Reverse Linked List](LinkedLists/LinkedListReversal.py): In-place reversal
- [Nth to Last Node](LinkedLists/LinkedListNthToLastNode.py): Find the $n$-th node from the end

### Stacks 📚
LIFO (Last-In-First-Out) data structures.
- [Stack Implementation](Stacks/StackImple.py): Basic operations (push, pop, peek)
- [Balanced Parentheses](Stacks/BalanceParenthlessCheckImple.py): Check for balanced brackets using a stack
- [Balanced Parentheses](Stacks/BalanceParenthesesCheckImple.py): Check for balanced brackets using a stack

### Queues 📦
FIFO (First-In-First-Out) data structures.
Expand All @@ -123,7 +108,7 @@ FIFO (First-In-First-Out) data structures.

### Deque 🔄
Double-ended queue operations.
- [Deque Implementation](deque/DequeImple.py): Operations at both ends
- [Deque Implementation](Deque/DequeImple.py): Operations at both ends

### Trees 🌳
Hierarchical data structures.
Expand All @@ -133,7 +118,7 @@ Hierarchical data structures.
- [Binary Heap](Trees/BinaryHeapImple.py): Min-heap implementation
- [Tree Traversals](Trees/TreeLevelOrderPrintImple.py): Level order (BFS) printing
- [Trim BST](Trees/TrimBinarySearchTreeImple.py): Keep nodes within a range
- [Tree Representations](Trees/): [Nodes & References](Trees/TreeRepresentationWithNodesReferences.py) & [List of Lists](Trees/buildTreeTest.py)
- [Tree Representations](Trees/): [Nodes & References](Trees/TreeRepresentationWithNodesReferences.py) & [List of Lists](Trees/BuildTreeTest.py)

---

Expand All @@ -144,7 +129,7 @@ Algorithms for arranging elements in order.
- [Bubble Sort](Sorting/BubbleSortImple.py) - $O(n^2)$
- [Selection Sort](Sorting/SelectionSortImple.py) - $O(n^2)$
- [Insertion Sort](Sorting/InsertionSortImple.py) - $O(n^2)$
- [Shell Sort](Sorting/ShellSortImple.py) - $O(n \log n)$
- [Shell Sort](Sorting/ShellSortImple.py) - $O(n^2)$
- [Merge Sort](Sorting/MergeSortImple.py) - $O(n \log n)$
- [Quick Sort](Sorting/QuickSortImple.py) - $O(n \log n)$ average

Expand All @@ -168,7 +153,7 @@ Algorithms for graph traversal and pathfinding.

## ⚠️ Error Handling & Debugging

- [Error and Exceptions](Error-debug/ErrorExceptions.py): Demonstrates `try`, `except`, `else`, and `finally` blocks for robust error handling.
- [Error and Exceptions](ErrorHandling/ErrorExceptions.py): Demonstrates `try`, `except`, `else`, and `finally` blocks for robust error handling.

---

Expand All @@ -180,47 +165,6 @@ Most scripts in this repository are standalone. You can run them using the Pytho
python3 path/to/script.py
```

Example:
```bash
python3 Sorting/BubbleSortImple.py
```

---

## 📊 Quick Reference

| Topic | Easy | Medium | Hard |
|-------|------|--------|------|
| Arrays | Anagram Check | Array Pair Sum | Find Missing Element |
| Linked Lists | Singly LL | Cycle Detection | Reverse LL |
| Trees | Binary Search | BST Validation | Trim BST |
| Sorting | Bubble Sort | Merge Sort | Quick Sort |
| DP | Fibonacci | Coin Change | Word Split |

---

## 🎓 Learning Path

New to DSA? Follow this recommended order:
1. Start with **Arrays** - Fundamental data structure
2. Learn **Sorting** - Essential for interviews
3. Study **Linked Lists** - Understanding pointers/references
4. Master **Stacks & Queues** - Core data structures
5. Explore **Trees** - Most interview questions
6. Dive into **Recursion & DP** - Advanced problem solving
7. Finish with **Graphs** - Complex algorithms

---

## 🔮 Roadmap

- [ ] Add more graph algorithms (Dijkstra, Bellman-Ford)
- [ ] Include complexity analysis for each solution
- [ ] Add interactive examples/visualizations
- [ ] Create a difficulty level classification
- [ ] Add more test cases
- [ ] Create beginner-friendly guides

---

## 📄 License
Expand All @@ -233,22 +177,4 @@ Copyright (c) 2017 - 2026 Pradeep K. Pant

---

## 👨‍💻 Author

**Pradeep K. Pant**
- Started: 2017
- Python enthusiast | Algorithm lover | Open source advocate

---

## ⭐ Show Your Support

If this repository helped you learn or prepare for interviews, please consider:
- ⭐ Starring the repository
- 🤝 Contributing improvements
- 📢 Sharing with others learning DSA
- 💬 Giving feedback

---

*Happy Learning! 🚀*
11 changes: 5 additions & 6 deletions Recursion/FibonacciSeqDynamic.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,11 @@
# memoization + recursion = dynamic programming
# Author: Pradeep K. Pant, ppant@cpan.org

# Instantiate Cache information
n = 10
cache = [None] * (n + 1)

# Implement fibonacci_dynamic
def fibonacci_dynamic(n):
def fibonacci_dynamic(n, cache=None):
if cache is None:
cache = [None] * (n + 1)

# Base Case
if n == 0 or n == 1:
return n
Expand All @@ -17,7 +16,7 @@ def fibonacci_dynamic(n):
return cache[n]

# Recursive call to and keep setting cache
cache[n] = fibonacci_dynamic(n - 1) + fibonacci_dynamic(n - 2)
cache[n] = fibonacci_dynamic(n - 1, cache) + fibonacci_dynamic(n - 2, cache)
return cache[n]

# Test
Expand Down
Loading