diff --git a/.gitignore b/.gitignore index 5d947ca..2478979 100644 --- a/.gitignore +++ b/.gitignore @@ -16,3 +16,45 @@ bin-release/ # Project files, i.e. `.project`, `.actionScriptProperties` and `.flexProperties` # should NOT be excluded as they contain compiler settings and other important # information for Eclipse / Flash Builder. + +# Competitive Programming specific +# Compiled binaries +*.exe +*.o +*.out +a.out + +# IDE files +.vscode/ +.idea/ +*.iml + +# Language specific +# Python +__pycache__/ +*.pyc +*.pyo +*.pyd +.Python +*.so + +# Java +*.class +*.jar + +# C++ +*.gch +*.pch + +# System files +.DS_Store +Thumbs.db + +# Temporary files +*.tmp +*.temp +*~ + +# Test files (optional - remove if you want to commit test outputs) +test_output.txt +debug.txt diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..48c9421 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,108 @@ +# Contributing to Competitive Programming and Algorithms + +Thank you for your interest in contributing to this repository! This guide will help you understand the project structure and contribution guidelines. + +## Repository Structure + +``` +├── algorithms/ # Algorithm implementations +│ ├── graph/ # Graph algorithms +│ ├── dynamic-programming/ # DP solutions +│ ├── greedy/ # Greedy algorithms +│ ├── string/ # String algorithms +│ ├── sorting/ # Sorting algorithms +│ ├── searching/ # Search algorithms +│ └── math/ # Mathematical algorithms +├── data-structures/ # Data structure implementations +│ ├── linear/ # Arrays, lists, stacks, queues +│ ├── trees/ # Trees and tree-based structures +│ ├── graphs/ # Graph representations +│ ├── heaps/ # Heap implementations +│ └── hash-tables/ # Hash-based structures +├── problems/ # Problem solutions by platform +│ ├── leetcode/ # LeetCode solutions +│ ├── codeforces/ # Codeforces solutions +│ ├── atcoder/ # AtCoder solutions +│ ├── hackerrank/ # HackerRank solutions +│ ├── codechef/ # CodeChef solutions +│ └── spoj/ # SPOJ solutions +└── templates/ # Code templates and boilerplate +``` + +## Contribution Guidelines + +### Adding Algorithm Implementations + +1. Place the algorithm in the appropriate subdirectory under `algorithms/` +2. Include comprehensive documentation: + - Brief description of the algorithm + - Time and space complexity analysis + - When to use this algorithm + - Example usage + +### Adding Data Structure Implementations + +1. Place implementations in the appropriate subdirectory under `data-structures/` +2. Include: + - Clear interface documentation + - Complexity analysis for all operations + - Example usage + - Test cases demonstrating functionality + +### Adding Problem Solutions + +1. Choose the appropriate platform directory under `problems/` +2. Use descriptive file names: `problem_id_brief_description.ext` +3. Include at the top of each solution: + ``` + Problem: [Problem Title] + Link: [URL to problem] + Difficulty: [Easy/Medium/Hard] + + Approach: [Brief explanation of your approach] + Time Complexity: O(...) + Space Complexity: O(...) + ``` + +### Code Quality Standards + +- **Readability**: Write clean, well-commented code +- **Efficiency**: Focus on optimal time and space complexity +- **Testing**: Include test cases when applicable +- **Documentation**: Explain complex logic and edge cases + +### File Naming Conventions + +- Use lowercase with underscores: `binary_search.cpp` +- Include relevant keywords: `dijkstra_shortest_path.py` +- For problems, include platform identifier: `lc_1480_two_sum.cpp` + +### Language Support + +We accept solutions in: +- C++ (preferred for competitive programming) +- Python +- Java +- Other languages are welcome + +### Submitting Changes + +1. Fork the repository +2. Create a feature branch for your changes +3. Follow the structure and naming conventions +4. Add appropriate documentation +5. Test your implementations +6. Submit a pull request with a clear description + +## Getting Started + +1. Use the templates in `templates/` for consistent code structure +2. Check existing implementations for reference +3. Read the README files in each directory for specific guidelines +4. Start with simpler algorithms or problems if you're new to the repository + +## Questions? + +If you have questions about contributing, feel free to open an issue or reach out to the maintainers. + +Happy coding! 🚀 \ No newline at end of file diff --git a/README.md b/README.md index 87ea201..746e475 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,72 @@ -# competitive-programming-and-algorithms -Solutions to world renowed problems and explanations of legacy algorithms. This is not a research, but my personal findings and understanding +# Competitive Programming and Algorithms + +A comprehensive collection of algorithm implementations, data structures, and solutions to competitive programming problems. This repository serves as a learning resource and reference for competitive programmers and algorithm enthusiasts. + +## Repository Structure + +### 📚 **Algorithms** +Fundamental algorithms organized by category: +- **Graph Algorithms**: DFS, BFS, Dijkstra, Floyd-Warshall, MST +- **Dynamic Programming**: Classic DP patterns and optimizations +- **Greedy Algorithms**: Optimization and scheduling problems +- **String Algorithms**: Pattern matching, string processing +- **Sorting & Searching**: Various implementations and applications +- **Mathematical Algorithms**: Number theory, combinatorics + +### 🏗️ **Data Structures** +Essential data structures for competitive programming: +- **Linear**: Arrays, linked lists, stacks, queues +- **Trees**: Binary trees, segment trees, Fenwick trees, tries +- **Graphs**: Adjacency lists, matrices, specialized structures +- **Heaps**: Priority queues, min/max heaps +- **Hash Tables**: Efficient lookup structures + +### 💻 **Problems** +Solutions from popular competitive programming platforms: +- **LeetCode**: Interview preparation problems +- **Codeforces**: Contest problems and solutions +- **AtCoder**: Japanese competitive programming platform +- **HackerRank**: Coding challenges and algorithms +- **CodeChef**: Monthly contests and practice problems +- **SPOJ**: Classical programming problems + +### 🛠️ **Templates** +Ready-to-use code templates for: +- C++ competitive programming setup +- Python algorithm implementations +- Java contest templates +- Fast I/O and common utilities + +## Getting Started + +1. **Browse** the directory structure to find relevant algorithms or problems +2. **Use** the templates for quick contest setup +3. **Refer** to individual README files in each directory for specific guidance +4. **Contribute** by adding new solutions or improving existing ones + +## Contributing + +We welcome contributions! Please read [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines on: +- Code quality standards +- File naming conventions +- Documentation requirements +- Submission process + +## Languages + +Solutions are primarily in: +- **C++** (preferred for competitive programming) +- **Python** (for readability and quick prototyping) +- **Java** (for specific contest requirements) + +## Philosophy + +This repository focuses on: +- **Clarity**: Well-documented, readable code +- **Efficiency**: Optimal time and space complexity +- **Learning**: Comprehensive explanations and examples +- **Practice**: Real problem solutions from contests + +--- + +*Happy coding and may your solutions be bug-free! 🚀* diff --git a/algorithms/README.md b/algorithms/README.md new file mode 100644 index 0000000..3b80e08 --- /dev/null +++ b/algorithms/README.md @@ -0,0 +1,20 @@ +# Algorithms + +This directory contains implementations of fundamental algorithms commonly used in competitive programming and software development. + +## Directory Structure + +- **graph/**: Graph algorithms (DFS, BFS, Dijkstra, Floyd-Warshall, MST, etc.) +- **dynamic-programming/**: Dynamic programming solutions and patterns +- **greedy/**: Greedy algorithms and optimization problems +- **string/**: String processing algorithms (KMP, Z-algorithm, suffix arrays, etc.) +- **sorting/**: Various sorting algorithms implementations +- **searching/**: Binary search and other searching techniques +- **math/**: Mathematical algorithms (number theory, combinatorics, etc.) + +## Implementation Guidelines + +- Each algorithm should be well-documented with complexity analysis +- Include example usage and test cases +- Prefer clear, readable code over micro-optimizations +- Add comments explaining the algorithm's key concepts \ No newline at end of file diff --git a/algorithms/searching/binary_search.cpp b/algorithms/searching/binary_search.cpp new file mode 100644 index 0000000..535bdeb --- /dev/null +++ b/algorithms/searching/binary_search.cpp @@ -0,0 +1,109 @@ +/** + * Binary Search Algorithm + * + * Description: Efficiently searches for a target value in a sorted array + * Time Complexity: O(log n) + * Space Complexity: O(1) + * + * Use Cases: + * - Finding element in sorted array + * - Lower/upper bound queries + * - Search space optimization problems + */ + +#include +#include +using namespace std; + +/** + * Standard binary search - finds exact match + * @param arr: sorted array to search in + * @param target: value to find + * @return: index of target if found, -1 otherwise + */ +int binarySearch(const vector& arr, int target) { + int left = 0, right = arr.size() - 1; + + while (left <= right) { + int mid = left + (right - left) / 2; // Avoid overflow + + if (arr[mid] == target) { + return mid; + } else if (arr[mid] < target) { + left = mid + 1; + } else { + right = mid - 1; + } + } + + return -1; // Not found +} + +/** + * Lower bound - finds first position where element >= target + * @param arr: sorted array + * @param target: target value + * @return: index of first element >= target + */ +int lowerBound(const vector& arr, int target) { + int left = 0, right = arr.size(); + + while (left < right) { + int mid = left + (right - left) / 2; + + if (arr[mid] < target) { + left = mid + 1; + } else { + right = mid; + } + } + + return left; +} + +/** + * Upper bound - finds first position where element > target + * @param arr: sorted array + * @param target: target value + * @return: index of first element > target + */ +int upperBound(const vector& arr, int target) { + int left = 0, right = arr.size(); + + while (left < right) { + int mid = left + (right - left) / 2; + + if (arr[mid] <= target) { + left = mid + 1; + } else { + right = mid; + } + } + + return left; +} + +// Example usage and test cases +int main() { + vector arr = {1, 3, 5, 7, 9, 11, 13, 15}; + + cout << "Array: "; + for (int x : arr) cout << x << " "; + cout << "\n\n"; + + // Test binary search + cout << "Binary Search Tests:\n"; + cout << "Search for 7: " << binarySearch(arr, 7) << " (expected: 3)\n"; + cout << "Search for 4: " << binarySearch(arr, 4) << " (expected: -1)\n"; + cout << "Search for 1: " << binarySearch(arr, 1) << " (expected: 0)\n"; + cout << "Search for 15: " << binarySearch(arr, 15) << " (expected: 7)\n\n"; + + // Test bounds + cout << "Bounds Tests:\n"; + cout << "Lower bound of 7: " << lowerBound(arr, 7) << " (expected: 3)\n"; + cout << "Lower bound of 6: " << lowerBound(arr, 6) << " (expected: 3)\n"; + cout << "Upper bound of 7: " << upperBound(arr, 7) << " (expected: 4)\n"; + cout << "Upper bound of 6: " << upperBound(arr, 6) << " (expected: 3)\n"; + + return 0; +} \ No newline at end of file diff --git a/data-structures/README.md b/data-structures/README.md new file mode 100644 index 0000000..bca91b8 --- /dev/null +++ b/data-structures/README.md @@ -0,0 +1,18 @@ +# Data Structures + +This directory contains implementations of various data structures used in competitive programming. + +## Directory Structure + +- **linear/**: Arrays, linked lists, stacks, queues, deques +- **trees/**: Binary trees, BSTs, segment trees, Fenwick trees, tries +- **graphs/**: Graph representations and specialized graph data structures +- **heaps/**: Min/max heaps, priority queues +- **hash-tables/**: Hash map implementations and related structures + +## Implementation Guidelines + +- Focus on functionality needed for competitive programming +- Include common operations with time complexity analysis +- Provide clear examples of usage +- Test implementations thoroughly \ No newline at end of file diff --git a/data-structures/linear/stack.py b/data-structures/linear/stack.py new file mode 100644 index 0000000..ce7da27 --- /dev/null +++ b/data-structures/linear/stack.py @@ -0,0 +1,127 @@ +""" +Stack Implementation using Dynamic Array + +A Last-In-First-Out (LIFO) data structure implementation. + +Operations: +- push(item): Add item to top - O(1) amortized +- pop(): Remove and return top item - O(1) +- peek()/top(): Return top item without removing - O(1) +- is_empty(): Check if stack is empty - O(1) +- size(): Get number of elements - O(1) + +Use Cases: +- Function call management +- Expression evaluation +- Undo operations +- DFS traversal +- Balanced parentheses checking +""" + +class Stack: + def __init__(self): + """Initialize an empty stack.""" + self._items = [] + + def push(self, item): + """ + Add an item to the top of the stack. + + Args: + item: The item to add + """ + self._items.append(item) + + def pop(self): + """ + Remove and return the top item from the stack. + + Returns: + The top item from the stack + + Raises: + IndexError: If the stack is empty + """ + if self.is_empty(): + raise IndexError("pop from empty stack") + return self._items.pop() + + def peek(self): + """ + Return the top item without removing it. + + Returns: + The top item from the stack + + Raises: + IndexError: If the stack is empty + """ + if self.is_empty(): + raise IndexError("peek from empty stack") + return self._items[-1] + + def is_empty(self): + """ + Check if the stack is empty. + + Returns: + True if stack is empty, False otherwise + """ + return len(self._items) == 0 + + def size(self): + """ + Get the number of items in the stack. + + Returns: + Number of items in the stack + """ + return len(self._items) + + def __str__(self): + """String representation of the stack.""" + return f"Stack({self._items})" + +# Example usage and test cases +def test_stack(): + print("Testing Stack Implementation:") + print("=" * 30) + + # Create a new stack + stack = Stack() + print(f"Created empty stack: {stack}") + print(f"Is empty: {stack.is_empty()}") + print(f"Size: {stack.size()}\n") + + # Push elements + print("Pushing elements: 1, 2, 3") + for i in [1, 2, 3]: + stack.push(i) + print(f"Pushed {i}, stack: {stack}") + print() + + # Peek at top element + print(f"Peek: {stack.peek()}") + print(f"Stack after peek: {stack}\n") + + # Pop elements + print("Popping elements:") + while not stack.is_empty(): + popped = stack.pop() + print(f"Popped: {popped}, remaining: {stack}") + print() + + # Test error handling + print("Testing error handling:") + try: + stack.pop() + except IndexError as e: + print(f"Expected error: {e}") + + try: + stack.peek() + except IndexError as e: + print(f"Expected error: {e}") + +if __name__ == "__main__": + test_stack() \ No newline at end of file diff --git a/problems/README.md b/problems/README.md new file mode 100644 index 0000000..fe248ba --- /dev/null +++ b/problems/README.md @@ -0,0 +1,28 @@ +# Problems + +This directory contains solutions to problems from various competitive programming platforms. + +## Directory Structure + +- **leetcode/**: LeetCode problem solutions +- **codeforces/**: Codeforces contest problems +- **atcoder/**: AtCoder contest problems +- **hackerrank/**: HackerRank challenges +- **codechef/**: CodeChef problems +- **spoj/**: SPOJ classical problems + +## Solution Format + +Each solution should include: +- Problem statement or link to the problem +- Approach explanation +- Time and space complexity analysis +- Clean, well-commented code +- Test cases (when applicable) + +## File Naming Convention + +Use descriptive names that include: +- Problem ID (if available) +- Brief problem description +- Example: `1480_two_sum.cpp`, `cf_round_800_a.py` \ No newline at end of file diff --git a/problems/leetcode/lc_1_two_sum.py b/problems/leetcode/lc_1_two_sum.py new file mode 100644 index 0000000..6720054 --- /dev/null +++ b/problems/leetcode/lc_1_two_sum.py @@ -0,0 +1,68 @@ +""" +Problem: Two Sum +Link: https://leetcode.com/problems/two-sum/ +Difficulty: Easy + +Problem Statement: +Given an array of integers nums and an integer target, return indices of the +two numbers such that they add up to target. + +Approach: +Use a hash map to store each number and its index as we iterate through the array. +For each number, check if (target - current_number) exists in the hash map. + +Time Complexity: O(n) +Space Complexity: O(n) +""" + +def two_sum(nums, target): + """ + Find two numbers in the array that sum to target. + + Args: + nums: List of integers + target: Target sum + + Returns: + List of two indices whose values sum to target + """ + num_to_index = {} + + for i, num in enumerate(nums): + complement = target - num + + if complement in num_to_index: + return [num_to_index[complement], i] + + num_to_index[num] = i + + return [] # No solution found + +# Test cases +def test_two_sum(): + # Test case 1: Basic case + nums1 = [2, 7, 11, 15] + target1 = 9 + result1 = two_sum(nums1, target1) + print(f"Input: nums = {nums1}, target = {target1}") + print(f"Output: {result1}") + print(f"Expected: [0, 1]\n") + + # Test case 2: Different positions + nums2 = [3, 2, 4] + target2 = 6 + result2 = two_sum(nums2, target2) + print(f"Input: nums = {nums2}, target = {target2}") + print(f"Output: {result2}") + print(f"Expected: [1, 2]\n") + + # Test case 3: Same number twice + nums3 = [3, 3] + target3 = 6 + result3 = two_sum(nums3, target3) + print(f"Input: nums = {nums3}, target = {target3}") + print(f"Output: {result3}") + print(f"Expected: [0, 1]\n") + +if __name__ == "__main__": + test_two_sum() \ No newline at end of file diff --git a/templates/README.md b/templates/README.md new file mode 100644 index 0000000..683f046 --- /dev/null +++ b/templates/README.md @@ -0,0 +1,14 @@ +# Templates + +This directory contains code templates and boilerplate code for competitive programming. + +## Available Templates + +- Language-specific templates for quick contest setup +- Common algorithm implementations ready to copy-paste +- Input/output handling templates +- Debugging utilities + +## Usage + +These templates are designed to speed up coding during contests and provide consistent structure across solutions. \ No newline at end of file diff --git a/templates/cpp_template.cpp b/templates/cpp_template.cpp new file mode 100644 index 0000000..427232d --- /dev/null +++ b/templates/cpp_template.cpp @@ -0,0 +1,49 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace std; + +// Fast I/O +#define fast_io ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); + +// Common macros +#define ll long long +#define vi vector +#define vll vector +#define pii pair +#define pll pair +#define mp make_pair +#define pb push_back +#define all(x) (x).begin(), (x).end() +#define sz(x) (int)(x).size() + +// Constants +const int MOD = 1e9 + 7; +const int INF = 1e9; +const ll LINF = 1e18; + +void solve() { + // Your solution here + +} + +int main() { + fast_io; + + int t = 1; + // cin >> t; // Uncomment for multiple test cases + + while (t--) { + solve(); + } + + return 0; +} \ No newline at end of file diff --git a/templates/java_template.java b/templates/java_template.java new file mode 100644 index 0000000..c94bb48 --- /dev/null +++ b/templates/java_template.java @@ -0,0 +1,49 @@ +import java.util.*; +import java.io.*; + +public class Main { + static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + static StringTokenizer st; + static PrintWriter out = new PrintWriter(System.out); + + // Fast input methods + static String next() throws IOException { + while (st == null || !st.hasMoreTokens()) { + st = new StringTokenizer(br.readLine()); + } + return st.nextToken(); + } + + static int nextInt() throws IOException { + return Integer.parseInt(next()); + } + + static long nextLong() throws IOException { + return Long.parseLong(next()); + } + + static double nextDouble() throws IOException { + return Double.parseDouble(next()); + } + + // Constants + static final int MOD = 1000000007; + static final int INF = Integer.MAX_VALUE; + static final long LINF = Long.MAX_VALUE; + + static void solve() throws IOException { + // Your solution here + + } + + public static void main(String[] args) throws IOException { + int t = 1; + // t = nextInt(); // Uncomment for multiple test cases + + while (t-- > 0) { + solve(); + } + + out.close(); + } +} \ No newline at end of file diff --git a/templates/python_template.py b/templates/python_template.py new file mode 100644 index 0000000..4c1c3cb --- /dev/null +++ b/templates/python_template.py @@ -0,0 +1,37 @@ +import sys +from collections import defaultdict, deque, Counter +from heapq import heappush, heappop +import bisect +import math + +# Fast input +def fast_input(): + return sys.stdin.readline().strip() + +# Input helpers +def get_int(): + return int(fast_input()) + +def get_ints(): + return list(map(int, fast_input().split())) + +def get_string(): + return fast_input() + +# Constants +MOD = 10**9 + 7 +INF = float('inf') + +def solve(): + # Your solution here + pass + +def main(): + t = 1 + # t = get_int() # Uncomment for multiple test cases + + for _ in range(t): + solve() + +if __name__ == "__main__": + main() \ No newline at end of file