From 717d3cf45b57ac669f55059a7a3b8750b662e186 Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Mon, 29 Sep 2025 04:19:09 +0000 Subject: [PATCH 1/2] Initial plan From 4d181e8fb6ff434b2d8ec98b33adb8799703161a Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Mon, 29 Sep 2025 04:26:33 +0000 Subject: [PATCH 2/2] Complete repository structure for SQL Leetcode solutions Co-authored-by: RhythmDevstudio <125253220+RhythmDevstudio@users.noreply.github.com> --- .gitignore | 41 +++++ CONTRIBUTING.md | 140 ++++++++++++++++++ Database-Design/README.md | 46 ++++++ .../175_Combine_Two_Tables.sql | 98 ++++++++++++ Easy/README.md | 49 ++++++ Hard/README.md | 63 ++++++++ Medium/178_Rank_Scores/178_Rank_Scores.sql | 104 +++++++++++++ Medium/README.md | 55 +++++++ README.md | 87 ++++++++++- Schemas/README.md | 39 +++++ Schemas/common_schemas.sql | 126 ++++++++++++++++ Templates/README.md | 30 ++++ Templates/solution_template.sql | 50 +++++++ setup.sh | 57 +++++++ 14 files changed, 983 insertions(+), 2 deletions(-) create mode 100644 .gitignore create mode 100644 CONTRIBUTING.md create mode 100644 Database-Design/README.md create mode 100644 Easy/175_Combine_Two_Tables/175_Combine_Two_Tables.sql create mode 100644 Easy/README.md create mode 100644 Hard/README.md create mode 100644 Medium/178_Rank_Scores/178_Rank_Scores.sql create mode 100644 Medium/README.md create mode 100644 Schemas/README.md create mode 100644 Schemas/common_schemas.sql create mode 100644 Templates/README.md create mode 100644 Templates/solution_template.sql create mode 100755 setup.sh diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..0a5e528 --- /dev/null +++ b/.gitignore @@ -0,0 +1,41 @@ +# IDE and Editor files +.vscode/ +.idea/ +*.swp +*.swo +*~ + +# OS generated files +.DS_Store +.DS_Store? +._* +.Spotlight-V100 +.Trashes +ehthumbs.db +Thumbs.db + +# Database files (if any) +*.db +*.sqlite +*.sqlite3 + +# Log files +*.log + +# Temporary files +/tmp/ +temp/ +*.tmp + +# Node modules (if any JavaScript tooling is added) +node_modules/ + +# Python cache (if any Python tooling is added) +__pycache__/ +*.pyc +*.pyo + +# Build outputs (if any) +build/ +dist/ +out/ \ No newline at end of file diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..64dfa0a --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,140 @@ +# Contributing to Leetcode SQL Solutions 🤝 + +Thank you for your interest in contributing to this repository! This guide will help you get started. + +## How to Contribute + +### 1. Adding New Solutions + +1. **Check for Duplicates**: Ensure the problem hasn't been solved already +2. **Choose Correct Folder**: Place solutions in appropriate difficulty folder (Easy/Medium/Hard) +3. **Follow Naming Convention**: Use `{ProblemNumber}_{ProblemName}/` format +4. **Use the Template**: Copy and fill out the solution template from `Templates/solution_template.sql` + +### 2. Improving Existing Solutions + +- Alternative solutions are welcome +- Performance optimizations +- Better explanations and comments +- Bug fixes + +### 3. Repository Improvements + +- Documentation updates +- Schema additions +- Template improvements +- Organizational enhancements + +## Submission Guidelines + +### File Structure +``` +Difficulty/ +└── ProblemNumber_ProblemName/ + └── ProblemNumber_ProblemName.sql +``` + +### Solution Requirements + +**Must Include:** +- Complete problem statement (as comment) +- Table schema definition +- Example input/output +- Working SQL solution +- Detailed explanation +- Time/space complexity (when applicable) + +**Good to Have:** +- Alternative approaches +- Edge case considerations +- Performance notes +- Related problems references + +### Code Style + +- Use clear, readable SQL formatting +- Include meaningful comments +- Follow standard SQL conventions +- Use consistent indentation (2 or 4 spaces) +- UPPERCASE for SQL keywords (SELECT, FROM, WHERE, etc.) + +### Example Format +```sql +/* +Problem: 175 - Combine Two Tables +Difficulty: Easy +Source: https://leetcode.com/problems/combine-two-tables/ +Date Solved: YYYY-MM-DD + +Problem Statement: +[Full problem description] + +Table Schema: +[Schema definitions] +*/ + +-- Solution approach explanation +SELECT + column1, + column2 +FROM + table1 t1 + LEFT JOIN table2 t2 ON t1.id = t2.id; + +/* +Explanation: +[Detailed explanation of approach and logic] +*/ +``` + +## Testing Your Solutions + +1. **Verify Syntax**: Ensure SQL syntax is correct +2. **Test with Sample Data**: Use provided examples to verify output +3. **Consider Edge Cases**: Test with empty tables, NULL values, etc. +4. **Performance Check**: For complex queries, consider execution efficiency + +## Pull Request Process + +1. **Fork the Repository** +2. **Create Feature Branch**: `git checkout -b solution/problem-number-name` +3. **Follow File Structure**: Use correct naming and placement +4. **Add Complete Solution**: Include all required components +5. **Test Thoroughly**: Verify your solution works +6. **Submit PR**: Include clear description of changes +7. **Respond to Feedback**: Address any review comments promptly + +## Quality Standards + +### SQL Code Quality +- ✅ Correct and efficient solution +- ✅ Proper formatting and indentation +- ✅ Clear variable and alias names +- ✅ Appropriate comments and documentation + +### Documentation Quality +- ✅ Complete problem statement +- ✅ Clear explanation of approach +- ✅ Example input/output included +- ✅ Complexity analysis (when applicable) + +## Getting Help + +- **Issues**: Open an issue for questions or problems +- **Discussions**: Use discussions for general questions +- **Review**: All contributions are reviewed before merging + +## Recognition + +Contributors will be recognized in the repository and their contributions are greatly appreciated! + +## Code of Conduct + +- Be respectful and constructive +- Help others learn and improve +- Focus on problem-solving and learning +- Maintain high quality standards + +--- + +Happy coding and thank you for contributing! 🚀 \ No newline at end of file diff --git a/Database-Design/README.md b/Database-Design/README.md new file mode 100644 index 0000000..acbdba7 --- /dev/null +++ b/Database-Design/README.md @@ -0,0 +1,46 @@ +# Database Design Problems 🏗️ + +This folder contains LeetCode problems focused on database design, schema optimization, and data modeling concepts. + +## Problem Categories + +### Schema Design +- Table normalization and denormalization +- Relationship modeling (1:1, 1:N, N:N) +- Primary and foreign key design +- Index strategy planning + +### Data Integrity +- Constraint implementation +- Referential integrity maintenance +- Data validation rules +- Transaction design + +### Performance Optimization +- Query optimization techniques +- Index design and usage +- Partitioning strategies +- Materialized view concepts + +### Data Architecture +- ETL process design +- Data warehouse modeling +- OLTP vs OLAP considerations +- Scalability planning + +## Key Concepts + +- **Normalization Forms**: 1NF, 2NF, 3NF, BCNF +- **ACID Properties**: Atomicity, Consistency, Isolation, Durability +- **CAP Theorem**: Consistency, Availability, Partition tolerance +- **Design Patterns**: Star schema, snowflake schema, fact/dimension tables + +## Study Resources + +Focus on understanding: +- When to normalize vs denormalize +- Trade-offs between storage and performance +- Indexing strategies for different query patterns +- Scalability considerations for growing datasets + +These problems test your understanding of database fundamentals and system design principles! \ No newline at end of file diff --git a/Easy/175_Combine_Two_Tables/175_Combine_Two_Tables.sql b/Easy/175_Combine_Two_Tables/175_Combine_Two_Tables.sql new file mode 100644 index 0000000..1dead41 --- /dev/null +++ b/Easy/175_Combine_Two_Tables/175_Combine_Two_Tables.sql @@ -0,0 +1,98 @@ +/* +Problem: 175 - Combine Two Tables +Difficulty: Easy +Source: https://leetcode.com/problems/combine-two-tables/ +Date Solved: 2024-09-29 + +Problem Statement: +Write a SQL query for a report that provides the following information for each person in the Person table, regardless if there is an address for the person or not: +- FirstName, LastName, City, State + +Table Schema: +Table: Person ++-------------+---------+ +| Column Name | Type | ++-------------+---------+ +| PersonId | int | +| FirstName | varchar | +| LastName | varchar | ++-------------+---------+ +PersonId is the primary key column for this table. + +Table: Address ++-------------+---------+ +| Column Name | Type | ++-------------+---------+ +| AddressId | int | +| PersonId | int | +| City | varchar | +| State | varchar | ++-------------+---------+ +AddressId is the primary key column for this table. + +Example: +Input: +Person table: ++----------+----------+-----------+ +| PersonId | FirstName| LastName | ++----------+----------+-----------+ +| 1 | Wang | Allen | +| 2 | Alice | Bob | ++----------+----------+-----------+ + +Address table: ++----------+----------+---------------+----------+ +| AddressId| PersonId | City | State | ++----------+----------+---------------+----------+ +| 1 | 2 | New York City | New York | +| 2 | 3 | Leetcode | California| ++----------+----------+---------------+----------+ + +Output: ++-----------+----------+---------------+----------+ +| FirstName | LastName | City | State | ++-----------+----------+---------------+----------+ +| Allen | Wang | Null | Null | +| Bob | Alice | New York City | New York | ++-----------+----------+---------------+----------+ + +Constraints: +- Some people may not have address information +- We want information for ALL people in Person table +*/ + +-- Solution: +-- Use LEFT JOIN to include all people from Person table, even if they don't have an address + +SELECT + p.FirstName, + p.LastName, + a.City, + a.State +FROM + Person p + LEFT JOIN Address a ON p.PersonId = a.PersonId; + +/* +Explanation: +This problem requires a LEFT JOIN because we need to include ALL people from the Person table, +regardless of whether they have a corresponding address in the Address table. + +- LEFT JOIN ensures all rows from the left table (Person) are included +- If there's no matching address, the City and State will be NULL +- INNER JOIN would exclude people without addresses (incorrect for this problem) +- RIGHT JOIN would exclude people with addresses but include orphaned addresses (also incorrect) + +Time complexity: O(n + m) where n is number of people and m is number of addresses +Space complexity: O(1) - no additional space needed for the join operation + +Alternative Solutions: +This is the most straightforward approach. You could also use: +- A subquery approach, but it would be less efficient +- UNION with conditional logic, but it's unnecessarily complex + +Notes: +- This is a classic example of when to use LEFT JOIN vs INNER JOIN +- The key insight is understanding the requirement "regardless if there is an address" +- Always read problem requirements carefully to determine the correct JOIN type +*/ \ No newline at end of file diff --git a/Easy/README.md b/Easy/README.md new file mode 100644 index 0000000..9353f00 --- /dev/null +++ b/Easy/README.md @@ -0,0 +1,49 @@ +# Easy SQL Problems 🟢 + +This folder contains LeetCode SQL problems classified as "Easy" difficulty. + +## Characteristics of Easy Problems + +- **Basic SQL Operations**: SELECT, WHERE, JOIN, GROUP BY +- **Simple Logic**: Straightforward filtering and aggregation +- **Common Patterns**: Basic joins, simple subqueries, date functions +- **Problem Numbers**: Typically in the 175-500+ range + +## Problem Categories + +### Data Retrieval +- Basic SELECT statements +- Filtering with WHERE clauses +- Sorting with ORDER BY + +### Joins +- INNER JOIN operations +- LEFT JOIN for missing data scenarios +- Simple two-table joins + +### Aggregations +- COUNT, SUM, AVG functions +- Basic GROUP BY operations +- Simple HAVING clauses + +### Date/Time Operations +- Date comparisons +- Date formatting +- Simple date arithmetic + +## Study Tips + +1. **Master the Basics**: Ensure you understand fundamental SQL syntax +2. **Practice Joins**: Many easy problems involve simple table joins +3. **Read Carefully**: Problem statements are usually straightforward +4. **Test Edge Cases**: Consider NULL values and empty result sets + +## Example Problem Types + +- Combine Two Tables +- Duplicate Emails +- Customers Who Never Order +- Employee Earning More Than Their Managers +- Delete Duplicate Emails + +Start here if you're new to SQL or want to build confidence before tackling harder problems! \ No newline at end of file diff --git a/Hard/README.md b/Hard/README.md new file mode 100644 index 0000000..788b54e --- /dev/null +++ b/Hard/README.md @@ -0,0 +1,63 @@ +# Hard SQL Problems 🔴 + +This folder contains LeetCode SQL problems classified as "Hard" difficulty. + +## Characteristics of Hard Problems + +- **Expert-Level Complexity**: Multi-layered logic and advanced SQL techniques +- **Performance Optimization**: Efficient query writing for large datasets +- **Advanced Functions**: Complex window functions, recursive CTEs +- **Problem Numbers**: Typically 1000+ range + +## Problem Categories + +### Recursive Queries +- Recursive CTEs for hierarchical data +- Tree traversal and path finding +- Iterative calculations + +### Complex Window Functions +- Advanced window frame specifications +- Multiple window functions in single query +- Custom window partitioning and ordering + +### Performance-Critical Queries +- Query optimization techniques +- Index-aware query writing +- Large dataset handling strategies + +### Advanced Analytics +- Percentile calculations +- Moving averages and trends +- Statistical analysis functions + +### Dynamic SQL Logic +- Complex conditional logic with multiple CASE statements +- Dynamic grouping and pivoting +- Advanced data transformation + +## Study Tips + +1. **Master Medium First**: Ensure solid foundation in medium problems +2. **Performance Matters**: Consider execution plans and optimization +3. **Break Down Complexity**: Use CTEs and temp tables to simplify +4. **Alternative Approaches**: Often multiple valid solutions exist +5. **Edge Cases**: Pay special attention to boundary conditions + +## Example Problem Types + +- Tournament Winners +- Activity Participants +- Find Median Given Frequency +- Trips and Users +- Department Highest Salary (Complex variations) +- Human Traffic Analysis (Advanced) + +## Advanced Concepts to Master + +- **Recursive CTEs**: For hierarchical and iterative data processing +- **Window Frame Specifications**: ROWS/RANGE BETWEEN clauses +- **Complex Joins**: Multiple self-joins and conditional joins +- **Performance Tuning**: Query optimization and execution planning + +These problems test your mastery of SQL and require creative problem-solving approaches! \ No newline at end of file diff --git a/Medium/178_Rank_Scores/178_Rank_Scores.sql b/Medium/178_Rank_Scores/178_Rank_Scores.sql new file mode 100644 index 0000000..8a0ed14 --- /dev/null +++ b/Medium/178_Rank_Scores/178_Rank_Scores.sql @@ -0,0 +1,104 @@ +/* +Problem: 178 - Rank Scores +Difficulty: Medium +Source: https://leetcode.com/problems/rank-scores/ +Date Solved: 2024-09-29 + +Problem Statement: +Write a SQL query to rank scores. If there is a tie between two scores, both should have the same ranking. Note that after a tie, the next ranking number should be the next consecutive integer value. In other words, there should be no "holes" between ranks. + +Return the result table ordered by score in descending order. + +Table Schema: +Table: Scores ++-------------+---------+ +| Column Name | Type | ++-------------+---------+ +| id | int | +| score | decimal | ++-------------+---------+ +id is the primary key for this table. +Each row of this table contains the score of a game. Score is a floating point value with two decimal places. + +Example: +Input: +Scores table: ++----+-------+ +| id | score | ++----+-------+ +| 1 | 3.50 | +| 2 | 3.65 | +| 3 | 4.00 | +| 4 | 3.85 | +| 5 | 4.00 | +| 6 | 3.65 | ++----+-------+ + +Output: ++-------+------+ +| score | rank | ++-------+------+ +| 4.00 | 1 | +| 4.00 | 1 | +| 3.85 | 2 | +| 3.65 | 3 | +| 3.65 | 3 | +| 3.50 | 4 | ++-------+------+ + +Constraints: +- 1 <= Scores table rows <= 10^5 +*/ + +-- Solution: +-- Use DENSE_RANK() window function to handle ties properly without gaps + +SELECT + score, + DENSE_RANK() OVER (ORDER BY score DESC) as rank +FROM + Scores +ORDER BY + score DESC; + +/* +Explanation: +This problem requires understanding of ranking functions in SQL: + +1. DENSE_RANK() vs RANK() vs ROW_NUMBER(): + - ROW_NUMBER(): Always gives unique sequential numbers (1,2,3,4,5,6) + - RANK(): Gives same rank for ties but leaves gaps (1,1,3,4,4,6) + - DENSE_RANK(): Gives same rank for ties without gaps (1,1,2,3,3,4) ✓ + +2. The key requirement is "no holes between ranks", which means we need DENSE_RANK() + +3. ORDER BY score DESC in the window function ranks highest scores first +4. Final ORDER BY ensures output is sorted by score descending + +Time complexity: O(n log n) due to sorting for ranking +Space complexity: O(n) for the result set + +Alternative Solutions: +1. Subquery approach (less efficient): + SELECT + score, + (SELECT COUNT(DISTINCT score) FROM Scores s2 WHERE s2.score >= s1.score) as rank + FROM Scores s1 + ORDER BY score DESC; + +2. Using variables (MySQL specific): + SELECT + score, + @rank := CASE + WHEN @prev_score = score THEN @rank + WHEN @prev_score := score THEN @rank + 1 + END as rank + FROM Scores, (SELECT @rank := 0, @prev_score := NULL) r + ORDER BY score DESC; + +Notes: +- DENSE_RANK() is the most readable and standard solution +- Window functions are powerful for ranking and analytical queries +- Always consider the specific ranking requirements (gaps vs no gaps) +- This pattern appears frequently in SQL interview questions +*/ \ No newline at end of file diff --git a/Medium/README.md b/Medium/README.md new file mode 100644 index 0000000..08c555c --- /dev/null +++ b/Medium/README.md @@ -0,0 +1,55 @@ +# Medium SQL Problems 🟡 + +This folder contains LeetCode SQL problems classified as "Medium" difficulty. + +## Characteristics of Medium Problems + +- **Complex Logic**: Multi-step reasoning and conditional logic +- **Advanced SQL Features**: Window functions, CTEs, subqueries +- **Multiple Tables**: Complex joins involving 3+ tables +- **Problem Numbers**: Typically in the 500-1000+ range + +## Problem Categories + +### Window Functions +- ROW_NUMBER(), RANK(), DENSE_RANK() +- LAG(), LEAD() for comparing rows +- Cumulative calculations with window frames + +### Complex Joins +- Self-joins for hierarchical data +- Multiple table joins with complex conditions +- FULL OUTER JOINs for comprehensive data analysis + +### Subqueries and CTEs +- Correlated subqueries +- Nested subqueries in SELECT, WHERE, and HAVING +- Common Table Expressions (CTEs) for readable queries + +### String and Date Manipulation +- Advanced string functions (SUBSTRING, REGEXP) +- Complex date calculations and formatting +- Time series analysis + +### Advanced Aggregations +- Conditional aggregations with CASE +- Multiple grouping levels +- Statistical functions + +## Study Tips + +1. **Window Functions**: Master the syntax and use cases +2. **CTEs**: Use them to break down complex problems +3. **Plan First**: Sketch out your approach before coding +4. **Optimize**: Consider multiple solutions and choose the most efficient + +## Example Problem Types + +- Nth Highest Salary +- Rank Scores +- Consecutive Numbers +- Department Top Three Salaries +- Game Play Analysis +- Human Traffic of Stadium + +These problems require deeper SQL knowledge and problem-solving skills! \ No newline at end of file diff --git a/README.md b/README.md index 0d90e45..09e1116 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,85 @@ -# Leetcode_SQL -Solving Daily SQL Leetcode questions +# Leetcode SQL Solutions 📊 + +A comprehensive collection of SQL solutions to LeetCode database problems, organized by difficulty level and updated daily. + +## 📁 Repository Structure + +``` +├── Easy/ # Easy difficulty problems (1-300 range typically) +├── Medium/ # Medium difficulty problems (300-600 range typically) +├── Hard/ # Hard difficulty problems (600+ range typically) +├── Database-Design/# Database design and schema-related problems +├── Schemas/ # Common database schemas used in problems +├── Templates/ # Solution templates and utilities +└── README.md # This file +``` + +## 🚀 Getting Started + +### Problem Organization +Each problem is stored in its respective difficulty folder with the following naming convention: +``` +{ProblemNumber}_{ProblemName}/{ProblemNumber}_{ProblemName}.sql +``` + +Example: +``` +Easy/175_Combine_Two_Tables/175_Combine_Two_Tables.sql +``` + +### Solution Format +Each solution file contains: +1. **Problem Statement** (as comment) +2. **Table Schema** (as comment) +3. **Example Input/Output** (as comment) +4. **SQL Solution** +5. **Explanation** (as comment) + +## 📈 Progress Tracking + +### Easy Problems: 0/X completed ✅ +### Medium Problems: 0/X completed 🟡 +### Hard Problems: 0/X completed 🔴 + +## 🎯 Daily Challenge + +This repository is updated daily with new SQL problem solutions. Check back regularly for fresh content! + +## 💡 How to Use + +1. **Browse by Difficulty**: Navigate to Easy, Medium, or Hard folders based on your skill level +2. **Study Solutions**: Each file contains detailed explanations and optimized queries +3. **Practice**: Use the provided schemas to test solutions in your preferred SQL environment +4. **Contribute**: Feel free to suggest improvements or alternative solutions + +## 🔧 Database Environments + +Solutions are tested and compatible with: +- MySQL 8.0+ +- PostgreSQL 12+ +- SQLite 3+ +- SQL Server 2019+ + +## 📚 Common Patterns + +- **JOINs**: Inner, Left, Right, Full Outer +- **Window Functions**: ROW_NUMBER, RANK, DENSE_RANK, LAG, LEAD +- **Aggregations**: GROUP BY, HAVING, COUNT, SUM, AVG +- **Subqueries**: Correlated and Non-correlated +- **CTEs**: Common Table Expressions for complex queries +- **Date/Time Functions**: Handling temporal data + +## 🤝 Contributing + +1. Fork the repository +2. Create a new branch for your solution +3. Follow the naming convention and solution format +4. Test your solution thoroughly +5. Submit a pull request with clear description + +## 📞 Contact + +For questions or suggestions, please open an issue or reach out to the maintainer. + +--- +*Last Updated: Daily* | *Total Problems Solved: 0* | *Current Streak: 0 days* diff --git a/Schemas/README.md b/Schemas/README.md new file mode 100644 index 0000000..3aa7432 --- /dev/null +++ b/Schemas/README.md @@ -0,0 +1,39 @@ +# Database Schemas + +This directory contains common database schemas used in LeetCode SQL problems. + +## Files + +### common_schemas.sql +Contains the most frequently used table structures in LeetCode problems including: + +**Core Business Tables:** +- Employee (id, name, salary, departmentId, managerId) +- Department (id, name) +- Customer (id, name, email, referrerId) +- Orders (id, customerId, orderDate, amount) + +**User Activity Tables:** +- Person (id, email, firstName, lastName) +- Activity (player_id, device_id, event_date, games_played) +- Logs (id, num) + +**Domain-Specific Tables:** +- Sales & Product (for e-commerce problems) +- Students & Courses (for education problems) +- Weather (for date/temperature problems) +- Cinema (for entertainment problems) +- Tree (for hierarchical data problems) + +## Usage + +1. Copy the relevant schema definitions to your SQL environment +2. Uncomment and modify the sample data inserts as needed +3. Use these schemas to test your solutions locally + +## Notes + +- All schemas follow standard LeetCode conventions +- Primary keys and foreign key relationships are defined where applicable +- Sample data is provided in comments for quick testing +- Schemas are compatible with MySQL, PostgreSQL, and SQL Server \ No newline at end of file diff --git a/Schemas/common_schemas.sql b/Schemas/common_schemas.sql new file mode 100644 index 0000000..bf17759 --- /dev/null +++ b/Schemas/common_schemas.sql @@ -0,0 +1,126 @@ +-- Common LeetCode Database Schemas +-- These are frequently used table structures in LeetCode SQL problems + +-- Employee Table (Very common in LeetCode problems) +CREATE TABLE Employee ( + id INT PRIMARY KEY, + name VARCHAR(255), + salary INT, + departmentId INT, + managerId INT +); + +-- Department Table +CREATE TABLE Department ( + id INT PRIMARY KEY, + name VARCHAR(255) +); + +-- Person Table (Used in many basic problems) +CREATE TABLE Person ( + id INT PRIMARY KEY, + email VARCHAR(255), + firstName VARCHAR(255), + lastName VARCHAR(255) +); + +-- Orders Table (E-commerce related problems) +CREATE TABLE Orders ( + id INT PRIMARY KEY, + customerId INT, + orderDate DATE, + amount DECIMAL(10,2) +); + +-- Customer Table +CREATE TABLE Customer ( + id INT PRIMARY KEY, + name VARCHAR(255), + email VARCHAR(255), + referrerId INT +); + +-- Activity Table (User activity tracking) +CREATE TABLE Activity ( + player_id INT, + device_id INT, + event_date DATE, + games_played INT, + PRIMARY KEY (player_id, event_date) +); + +-- Scores Table (Gaming/Competition problems) +CREATE TABLE Scores ( + id INT PRIMARY KEY, + score DECIMAL(3,2) +); + +-- Weather Table (Temperature/Date problems) +CREATE TABLE Weather ( + id INT PRIMARY KEY, + recordDate DATE, + temperature INT +); + +-- Sales Table (Sales analysis problems) +CREATE TABLE Sales ( + sale_id INT, + product_id INT, + year INT, + quantity INT, + price INT, + PRIMARY KEY (sale_id, year) +); + +-- Product Table +CREATE TABLE Product ( + product_id INT PRIMARY KEY, + product_name VARCHAR(255) +); + +-- Students and Courses (Education domain) +CREATE TABLE Students ( + student_id INT PRIMARY KEY, + student_name VARCHAR(255) +); + +CREATE TABLE Courses ( + student_id INT, + course_name VARCHAR(255), + PRIMARY KEY (student_id, course_name) +); + +-- Cinema Table (Entertainment domain) +CREATE TABLE Cinema ( + id INT PRIMARY KEY, + movie VARCHAR(255), + description VARCHAR(255), + rating DECIMAL(2,1) +); + +-- Logs Table (System logs/analytics) +CREATE TABLE Logs ( + id INT PRIMARY KEY, + num INT +); + +-- Tree Table (Hierarchical data) +CREATE TABLE Tree ( + id INT PRIMARY KEY, + p_id INT +); + +-- Sample data inserts for testing (commented out) +/* +-- Employee sample data +INSERT INTO Employee VALUES +(1, 'Joe', 85000, 1, 3), +(2, 'Henry', 80000, 2, 4), +(3, 'Sam', 60000, 2, NULL), +(4, 'Max', 90000, 1, NULL); + +-- Department sample data +INSERT INTO Department VALUES +(1, 'IT'), +(2, 'Sales'); +*/ \ No newline at end of file diff --git a/Templates/README.md b/Templates/README.md new file mode 100644 index 0000000..16257ee --- /dev/null +++ b/Templates/README.md @@ -0,0 +1,30 @@ +# Solution Templates and Utilities + +This directory contains helpful templates and utilities for organizing SQL solutions. + +## Files + +### solution_template.sql +A comprehensive template for each LeetCode SQL problem solution that includes: +- Problem metadata (number, title, difficulty, source URL) +- Problem statement and schema documentation +- Example input/output +- Solution with comments +- Detailed explanation and complexity analysis +- Space for alternative solutions and notes + +## Usage + +1. Copy the `solution_template.sql` file +2. Rename it following the convention: `{ProblemNumber}_{ProblemName}.sql` +3. Fill in all sections with the appropriate information +4. Place the completed file in the correct difficulty folder + +## Best Practices + +- Always include the problem statement for context +- Provide clear explanations of your approach +- Comment complex logic within the SQL +- Include time/space complexity when relevant +- Test solutions thoroughly before submitting +- Consider edge cases and alternative approaches \ No newline at end of file diff --git a/Templates/solution_template.sql b/Templates/solution_template.sql new file mode 100644 index 0000000..a0e6754 --- /dev/null +++ b/Templates/solution_template.sql @@ -0,0 +1,50 @@ +/* +Problem: [Problem Number] - [Problem Title] +Difficulty: [Easy/Medium/Hard] +Source: https://leetcode.com/problems/[problem-url]/ +Date Solved: [YYYY-MM-DD] + +Problem Statement: +[Copy the full problem statement here] + +Table Schema: +[Copy or describe the table structure here] + +Example: +Input: +[Provide example input data] + +Output: +[Provide expected output] + +Constraints: +[List any constraints mentioned in the problem] +*/ + +-- Solution: +-- [Brief explanation of approach] + +SELECT + -- Your solution here + +FROM + -- Tables involved + +WHERE + -- Filtering conditions + +-- Add additional clauses as needed (GROUP BY, ORDER BY, etc.) +; + +/* +Explanation: +[Detailed explanation of the solution approach] +[Time complexity: O(?)] +[Space complexity: O(?)] + +Alternative Solutions: +[If applicable, mention other approaches] + +Notes: +[Any additional notes or edge cases to consider] +*/ \ No newline at end of file diff --git a/setup.sh b/setup.sh new file mode 100755 index 0000000..8a48944 --- /dev/null +++ b/setup.sh @@ -0,0 +1,57 @@ +#!/bin/bash + +# Leetcode SQL Repository Setup Script +# This script helps initialize your local environment for testing SQL solutions + +echo "🚀 Leetcode SQL Repository Setup" +echo "=================================" + +# Check if we're in the correct directory +if [ ! -f "README.md" ] || [ ! -d "Easy" ]; then + echo "❌ Error: Please run this script from the repository root directory" + exit 1 +fi + +echo "✅ Repository structure verified" + +# Create a local testing directory +if [ ! -d "local-testing" ]; then + mkdir local-testing + echo "📁 Created local-testing directory for your experiments" +fi + +# Check for common SQL tools +echo "" +echo "🔍 Checking for SQL tools..." + +# Check for MySQL +if command -v mysql &> /dev/null; then + echo "✅ MySQL found: $(mysql --version | head -1)" +else + echo "❌ MySQL not found. Install MySQL for full compatibility" +fi + +# Check for SQLite +if command -v sqlite3 &> /dev/null; then + echo "✅ SQLite found: $(sqlite3 --version)" +else + echo "❌ SQLite not found. Install SQLite for local testing" +fi + +# Check for PostgreSQL +if command -v psql &> /dev/null; then + echo "✅ PostgreSQL found: $(psql --version)" +else + echo "❌ PostgreSQL not found. Install PostgreSQL for advanced features" +fi + +echo "" +echo "📖 Quick Start Guide:" +echo "1. Browse problems in Easy/, Medium/, or Hard/ folders" +echo "2. Use Templates/solution_template.sql for new solutions" +echo "3. Test queries using Schemas/common_schemas.sql" +echo "4. Check CONTRIBUTING.md for submission guidelines" +echo "" +echo "💡 Pro tip: Start with Easy problems if you're new to SQL!" +echo "" +echo "🎯 Happy coding! Visit https://leetcode.com/problemset/database/ for problems" \ No newline at end of file