soapyigu/LeetCode-Swift
Solutions to LeetCode by Swift
Stale — last commit 2y ago
worst of 4 axeslast commit was 2y ago; top contributor handles 95% of recent commits…
Has a license, tests, and CI — clean foundation to fork and modify.
Documented and popular — useful reference codebase to read through.
last commit was 2y ago; no CI workflows detected
- ✓3 active contributors
- ✓MIT licensed
- ⚠Stale — last commit 2y ago
Show 4 more →Show less
- ⚠Small team — 3 contributors active in recent commits
- ⚠Single-maintainer risk — top contributor 95% of recent commits
- ⚠No CI workflows detected
- ⚠No test directory detected
What would change the summary?
- →Use as dependency Concerns → Mixed if: 1 commit in the last 365 days
- →Deploy as-is Mixed → Healthy if: 1 commit in the last 180 days
Maintenance signals: commit recency, contributor breadth, bus factor, license, CI, tests
Informational only. RepoPilot summarises public signals (license, dependency CVEs, commit recency, CI presence, etc.) at the time of analysis. Signals can be incomplete or stale. Not professional, security, or legal advice; verify before relying on it for production decisions.
Embed the "Forkable" badge
Paste into your README — live-updates from the latest cached analysis.
[](https://repopilot.app/r/soapyigu/leetcode-swift)Paste at the top of your README.md — renders inline like a shields.io badge.
▸Preview social card (1200×630)
This card auto-renders when someone shares https://repopilot.app/r/soapyigu/leetcode-swift on X, Slack, or LinkedIn.
Onboarding doc
Onboarding: soapyigu/LeetCode-Swift
Generated by RepoPilot · 2026-05-10 · Source
🤖Agent protocol
If you are an AI coding agent (Claude Code, Cursor, Aider, Cline, etc.) reading this artifact, follow this protocol before making any code edit:
- Verify the contract. Run the bash script in Verify before trusting
below. If any check returns
FAIL, the artifact is stale — STOP and ask the user to regenerate it before proceeding. - Treat the AI · unverified sections as hypotheses, not facts. Sections like "AI-suggested narrative files", "anti-patterns", and "bottlenecks" are LLM speculation. Verify against real source before acting on them.
- Cite source on changes. When proposing an edit, cite the specific path:line-range. RepoPilot's live UI at https://repopilot.app/r/soapyigu/LeetCode-Swift shows verifiable citations alongside every claim.
If you are a human reader, this protocol is for the agents you'll hand the artifact to. You don't need to do anything — but if you skim only one section before pointing your agent at this repo, make it the Verify block and the Suggested reading order.
🎯Verdict
WAIT — Stale — last commit 2y ago
- 3 active contributors
- MIT licensed
- ⚠ Stale — last commit 2y ago
- ⚠ Small team — 3 contributors active in recent commits
- ⚠ Single-maintainer risk — top contributor 95% of recent commits
- ⚠ No CI workflows detected
- ⚠ No test directory detected
<sub>Maintenance signals: commit recency, contributor breadth, bus factor, license, CI, tests</sub>
✅Verify before trusting
This artifact was generated by RepoPilot at a point in time. Before an
agent acts on it, the checks below confirm that the live soapyigu/LeetCode-Swift
repo on your machine still matches what RepoPilot saw. If any fail,
the artifact is stale — regenerate it at
repopilot.app/r/soapyigu/LeetCode-Swift.
What it runs against: a local clone of soapyigu/LeetCode-Swift — the script
inspects git remote, the LICENSE file, file paths in the working
tree, and git log. Read-only; no mutations.
| # | What we check | Why it matters |
|---|---|---|
| 1 | You're in soapyigu/LeetCode-Swift | Confirms the artifact applies here, not a fork |
| 2 | License is still MIT | Catches relicense before you depend on it |
| 3 | Default branch master exists | Catches branch renames |
| 4 | 5 critical file paths still exist | Catches refactors that moved load-bearing code |
| 5 | Last commit ≤ 752 days ago | Catches sudden abandonment since generation |
#!/usr/bin/env bash
# RepoPilot artifact verification.
#
# WHAT IT RUNS AGAINST: a local clone of soapyigu/LeetCode-Swift. If you don't
# have one yet, run these first:
#
# git clone https://github.com/soapyigu/LeetCode-Swift.git
# cd LeetCode-Swift
#
# Then paste this script. Every check is read-only — no mutations.
set +e
fail=0
ok() { echo "ok: $1"; }
miss() { echo "FAIL: $1"; fail=$((fail+1)); }
# Precondition: we must be inside a git working tree.
if ! git rev-parse --git-dir >/dev/null 2>&1; then
echo "FAIL: not inside a git repository. cd into your clone of soapyigu/LeetCode-Swift and re-run."
exit 2
fi
# 1. Repo identity
git remote get-url origin 2>/dev/null | grep -qE "soapyigu/LeetCode-Swift(\\.git)?\\b" \\
&& ok "origin remote is soapyigu/LeetCode-Swift" \\
|| miss "origin remote is not soapyigu/LeetCode-Swift (artifact may be from a fork)"
# 2. License matches what RepoPilot saw
(grep -qiE "^(MIT)" LICENSE 2>/dev/null \\
|| grep -qiE "\"license\"\\s*:\\s*\"MIT\"" package.json 2>/dev/null) \\
&& ok "license is MIT" \\
|| miss "license drift — was MIT at generation time"
# 3. Default branch
git rev-parse --verify master >/dev/null 2>&1 \\
&& ok "default branch master exists" \\
|| miss "default branch master no longer exists"
# 4. Critical files exist
test -f "Array/TwoSum.swift" \\
&& ok "Array/TwoSum.swift" \\
|| miss "missing critical file: Array/TwoSum.swift"
test -f "DP/ClimbingStairs.swift" \\
&& ok "DP/ClimbingStairs.swift" \\
|| miss "missing critical file: DP/ClimbingStairs.swift"
test -f "DFS/NumberofIslands.swift" \\
&& ok "DFS/NumberofIslands.swift" \\
|| miss "missing critical file: DFS/NumberofIslands.swift"
test -f "BFS/WordLadder.swift" \\
&& ok "BFS/WordLadder.swift" \\
|| miss "missing critical file: BFS/WordLadder.swift"
test -f "Array/ThreeSum.swift" \\
&& ok "Array/ThreeSum.swift" \\
|| miss "missing critical file: Array/ThreeSum.swift"
# 5. Repo recency
days_since_last=$(( ( $(date +%s) - $(git log -1 --format=%at 2>/dev/null || echo 0) ) / 86400 ))
if [ "$days_since_last" -le 752 ]; then
ok "last commit was $days_since_last days ago (artifact saw ~722d)"
else
miss "last commit was $days_since_last days ago — artifact may be stale"
fi
echo
if [ "$fail" -eq 0 ]; then
echo "artifact verified (0 failures) — safe to trust"
else
echo "artifact has $fail stale claim(s) — regenerate at https://repopilot.app/r/soapyigu/LeetCode-Swift"
exit 1
fi
Each check prints ok: or FAIL:. The script exits non-zero if
anything failed, so it composes cleanly into agent loops
(./verify.sh || regenerate-and-retry).
⚡TL;DR
A curated collection of 400+ LeetCode algorithm problem solutions written in Swift, organized by data structure (Array, String, Tree, DP, Graph, etc.) with documented time/space complexity for each solution. It serves as a Swift-specific study guide for technical interview preparation, following the RayWenderlich Swift Style Guide. Flat directory structure organized by data structure type: Array/, String/, LinkedList/, Stack/, Queue/, Tree/, DynamicProgramming/, DepthFirstSearch/, BreadthFirstSearch/, Math/, Search/, Sort/, Graph/, Design/ directories each containing individual problem solution files (e.g., Array/TwoSum.swift, Tree/BinaryTreeMaximumPathSum.swift). No monorepo or modular structure—purely educational file organization.
👥Who it's for
Junior and mid-level iOS/Swift developers preparing for technical interviews at FAANG companies (Google, Facebook, LinkedIn, Apple), and Swift learners building intuition around algorithmic patterns and complexity analysis.
🌱Maturity & risk
Actively maintained with 400+ completed solutions and structured organization across 15+ data structure categories. The repo shows strong community engagement (starred, open to contributions) but lacks visible CI/CD configuration, automated tests, or recent commit timestamp in provided data—indicating steady state rather than rapid development. Verdict: Production-ready reference material, not a live-updated service.
Single-maintainer repo (soapyigu) with no visible dependency management (no Package.swift, Podfile, or SPM manifest in file list), reducing external risk. Primary risk is content staleness—solutions may not reflect current Swift syntax (5.0+ features, new collection APIs) or latest LeetCode problem changes. No test coverage evident; solutions rely on manual validation against LeetCode's online judge.
Active areas of work
No commit history or open PR data provided, so active development status is unclear. Based on README structure showing 1000+ LeetCode problems with only 400+ solutions, ongoing work likely includes: filling gaps in medium/hard problems, adding missing data structure categories, and maintaining Swift syntax compatibility. The contributor graph suggests collaborative additions but no visible recent activity metadata.
🚀Get running
git clone https://github.com/soapyigu/LeetCode-Swift.git
cd LeetCode-Swift
# No installation needed—Swift files are standalone; open in Xcode or read directly
open . # Opens in Xcode for syntax highlighting and testing
Daily commands:
No traditional 'run' step—this is a reference library. To test individual solutions: open any .swift file (e.g., Array/TwoSum.swift) in Xcode, select the function, and validate logic. For hands-on practice: copy solution into LeetCode's web editor and submit. Alternative: create a Swift playground in Xcode, paste a solution, and execute via cmd+enter.
🗺️Map of the codebase
Array/TwoSum.swift— Foundational hash-map problem that exemplifies the repo's approach to array manipulation and is a gateway problem for most contributors.DP/ClimbingStairs.swift— Core dynamic programming template that establishes the DP memoization pattern used across 40+ DP solutions in this repo.DFS/NumberofIslands.swift— Canonical DFS/BFS graph traversal pattern that serves as a template for 20+ island/graph problems throughout the codebase.BFS/WordLadder.swift— Illustrates the BFS shortest-path pattern used across 6+ BFS problems for finding optimal solutions in unweighted graphs.Array/ThreeSum.swift— Demonstrates the two-pointer sorting technique that appears in 10+ array problems and is essential for understanding the repo's optimization strategies.DFS/Permutations.swift— Shows the backtracking template with state management that is reused across Permutations II, Combinations, and Subsets variants.
🛠️How to make changes
Add a new Array problem solution
- Create new Swift file in Array/ directory following naming: Array/{ProblemNameCamelCase}.swift (
Array/NewArrayProblem.swift) - Follow the solution structure: define a class/struct with a solve method; use comments to explain approach (hash-map, two-pointer, sliding window) (
Array/NewArrayProblem.swift) - Implement time/space complexity comments at function header; test edge cases in comments (
Array/NewArrayProblem.swift) - Reference similar problems (e.g., if TwoSum, reference TwoSumII.swift for context) (
Array/TwoSum.swift)
Add a new Dynamic Programming solution
- Create new file in DP/ directory: DP/{ProblemNameCamelCase}.swift (
DP/NewDPProblem.swift) - Implement memoization approach first (top-down with dictionary/array), then add tabulation alternative (bottom-up) (
DP/NewDPProblem.swift) - Define state representation clearly in comments; explain recurrence relation (
DP/ClimbingStairs.swift) - Include both O(space) optimized version if applicable (e.g., rolling array for 1D instead of 2D) (
DP/NewDPProblem.swift)
Add a new Backtracking/DFS problem solution
- Create file in DFS/ directory: DFS/{ProblemNameCamelCase}.swift (
DFS/NewDFSProblem.swift) - Implement core DFS recursive function with visited state tracking and pruning conditions (
DFS/Permutations.swift) - Use backtracking pattern: recurse → add to result → backtrack (undo state) (
DFS/CombinationSum.swift) - Document time complexity (usually exponential) and space complexity (recursion depth + visited set) (
DFS/NewDFSProblem.swift)
Add a new BFS/Shortest-Path problem solution
- Create file in BFS/ directory: BFS/{ProblemNameCamelCase}.swift (
BFS/NewBFSProblem.swift) - Use Queue data structure (Swift Array with append/removeFirst); implement level-order traversal pattern (
BFS/WordLadder.swift) - Track visited nodes in Set to avoid cycles; handle multi-source BFS if multiple starting points (
BFS/ShortestDistanceAllBuildings.swift) - Document BFS guarantees shortest path in unweighted graphs; compare with Dijkstra if weights involved (
BFS/NewBFSProblem.swift)
🔧Why these technologies
- Swift — Chosen for modern syntax, strong typing, and Apple ecosystem; enables clean algorithm implementations following RayWenderlich style guide
- Dictionary/Set data structures — Core to hash-map solutions (TwoSum, ContainsDuplicate); provides O(1) average lookup critical for algorithm optimization
- Array (Swift native) — Primary sequence type; used with indexing, slicing, and in-place mutations for O(1) random access in sorting/rotation problems
- Recursive DFS with backtracking — Essential pattern for combinatorial problems (Permutations, Subsets, Combinations); enables clean state management with automatic unwind
- Queue (Array-based in Swift) — Required for BFS/level-order traversal; leverages append (O(1) amortized) and removeFirst operations for shortest-path algorithms
⚖️Trade-offs already made
-
Using memoization (top-down DP) vs tabulation (bottom-up DP) across 40+ solutions
- Why: Memoization is more intuitive for recursive problems; tabulation provides better space optimization potential
- Consequence: Repo shows both approaches per problem (e.g., ClimbingStairs); developers must understand trade-off between code clarity and space efficiency
-
In-place array mutations vs creating new arrays
- Why: In-place (e.g., RotateImage) uses O(1) space; new array (e.g., ProductExceptSelf) uses O(n) but avoids complexity
- Consequence: Interview answers demand both techniques; repo documents both with complexity notes, increasing solution size
-
Using Set for O(1) visited tracking in DFS vs boolean 2D matrix
- Why: Set is general-purpose; 2D matrix is cache-friendly for grid problems
- Consequence: Grid DFS (Minesweeper) uses 2D matrix; general graph DFS (NumberofIslands) uses Set; code varies by problem type
-
Sorting-based solutions
- Why: undefined
- Consequence: undefined
🪤Traps & gotchas
No hidden environment variables or service dependencies—solutions are self-contained Swift code. Key gotchas: (1) Solutions assume Swift 4.0+; some use optional chaining and guard statements that differ from older Swift. (2) LeetCode environment uses specific Swift foundation versions—offline testing may fail if local Swift version mismatches online judge (typically Swift 5.x). (3) No type definitions provided for custom classes (e.g., TreeNode, ListNode)—copy LeetCode's class definitions or infer from solution context. (4) README tables are manually maintained; file count (400+ solutions) may drift from actual file count if PRs aren't merged.
🏗️Architecture
💡Concepts to learn
- Two-Pointer Technique — Used in 30+ solutions across TwoSum, ThreeSum, Container With Most Water, Trapping Rain Water; mastering this pattern unlocks O(n) solutions for problems that naively require O(n²)
- Hash Map / Dictionary Optimization — Core pattern in Array solutions (TwoSum, IntersectionTwoArrays, FirstMissingPositive) replacing nested loops; essential for O(n) complexity instead of O(n²)
- Prefix / Suffix Arrays — Reduces complexity from O(n²) to O(n) in ProductExceptSelf, MaxConsecutiveOnes variants; critical DP precomputation technique used across 15+ problems
- In-Place Array Manipulation — FirstMissingPositive, RemoveDuplicatesFromSortedArray use space O(1) by reusing input array; interview trick question pattern separating O(n) space from O(1) space solutions
- Monotonic Stack / Deque — Advanced pattern in problems like Trapping Rain Water, Daily Temperatures (if covered in repo); maintains decreasing/increasing order to solve sliding window max in O(n) instead of O(n²)
- Boyer-Moore Majority Vote Algorithm — MajorityElement solution uses this to find majority in O(n) time, O(1) space—elegant constant-space algorithm interview favorite
- Cycle Detection in Arrays — FirstMissingPositive uses array indices as hash hints; understanding cycle detection with pointers (borrowed from linked list cycle detection) unlocks O(1) space constraint
🔗Related repos
halfrost/LeetCode-Go— Parallel repo with 1000+ LeetCode solutions in Go; same problem organization and complexity documentation—reference for algorithm explanations and alternative implementationsdoocs/leetcode— Multilingual LeetCode solutions (Java, C++, Python, JavaScript) with detailed explanations and diagrams; use for understanding hard problems beyond Swift-only contextkdn251/interviews— Curated interview prep guide aggregating common LeetCode patterns, system design, and company-specific problem lists; complements this repo's solution focus with strategyraywenderlich/swift-style-guide— Official RayWenderlich Swift Style Guide that this repo follows; reference for code formatting and naming conventions across all solutionsTheAlgorithms/Swift— Educational algorithms library in Swift (sorting, searching, data structures) separate from LeetCode; foundational reference for algorithmic concepts underlying problems
🪄PR ideas
To work on one of these in Claude Code or Cursor, paste:
Implement the "<title>" PR idea from CLAUDE.md, working through the checklist as the task list.
Add comprehensive unit tests for Array solutions
The repo contains 50+ Array solutions but no visible test files. Adding unit tests for Array problems (especially foundational ones like TwoSum.swift, ThreeSum.swift, LongestConsecutiveSequence.swift) would catch edge cases (empty arrays, single elements, duplicates, negative numbers) and serve as validation examples for contributors. This is critical since array problems have many edge cases that aren't obvious from problem descriptions alone.
- [ ] Create Array/Tests/ directory with XCTest files
- [ ] Write unit tests for TwoSum.swift covering: empty array, single element, no solution, multiple solutions, negative numbers
- [ ] Write unit tests for ThreeSum.swift covering: no triplets, duplicate handling, all zeros, mixed positive/negative
- [ ] Write unit tests for LongestConsecutiveSequence.swift covering: unsorted sequences, duplicates, single elements
- [ ] Add test execution instructions to README.md
Complete missing Graph/Adjacency List category solutions
The file structure shows DFS and BFS folders but many graph problems require adjacency list representations that aren't explicitly categorized. Several graph problems are missing (CloneGraph, CourseSchedule, NumberOfIslands, SurroundedRegions, GraphValidTree, CourseScheduleII). Adding these 6-8 solutions with proper adjacency list implementations would fill a critical gap in the graph algorithms section.
- [ ] Create Graph/ directory if not present
- [ ] Implement CloneGraph.swift with DFS/BFS solution using adjacency list
- [ ] Implement CourseSchedule.swift with topological sort using adjacency list
- [ ] Implement NumberOfIslands.swift with DFS on grid representation
- [ ] Implement SurroundedRegions.swift with boundary DFS
- [ ] Add these 4 files and update README to reference new Graph section
Add Time & Space Complexity annotations to top 50 solutions
The repo lacks complexity analysis documentation in the actual solution files. Adding standardized complexity comments to high-frequency interview problems (TwoSum.swift, BinarySearch, LongestSubstring, MergeIntervals, etc.) helps contributors understand solution efficiency tradeoffs and teaches best practices. This would be visible during code review and learning.
- [ ] Create a COMPLEXITY_GUIDE.md explaining the annotation format with examples
- [ ] Add // MARK: Complexity - O(n) time, O(1) space comments to Array/TwoSum.swift
- [ ] Add complexity annotations to Array/ThreeSum.swift, Array/LongestConsecutiveSequence.swift, Array/ProductExceptSelf.swift
- [ ] Add complexity annotations to 5-7 String solutions (LongestSubstring, MinimumWindowSubstring, etc.)
- [ ] Document why certain tradeoffs were made (e.g., hash map vs sorting)
🌿Good first issues
- Add unit tests for Array category solutions (TwoSum.swift, ThreeSum.swift, etc.) using XCTest—pick 5-10 core files, write parametrized test cases with provided LeetCode examples, and document test patterns for future contributors.: Repo lacks automated validation; manual testing against LeetCode is slow. Tests would accelerate contribution review and catch Swift syntax regressions.
- Fill missing Easy-level problems in Array category—compare file list against LeetCode's problem set, identify gaps (e.g., 'Trapping Rain Water', 'Largest Number', 'Jump Game'), and add 3-5 solutions with complexity annotations.: README claims 400+ solutions but 1000+ problems exist; easier problems are lower-hanging fruit for beginners to complete and submit.
- Create a 'Solutions by Company' index in README (Google, Facebook, Amazon, etc.) cross-referencing which files solve problems asked by each company—requires mapping current solutions to company-tagged problems on LeetCode.: README lists companies but provides no company-to-problem mapping; users preparing for specific company interviews need targeted problem sets.
⭐Top contributors
Click to expand
Top contributors
- @soapyigu — 95 commits
- [@Yi Gu](https://github.com/Yi Gu) — 4 commits
- @mertlsarac — 1 commits
📝Recent commits
Click to expand
Recent commits
d4aec0f— [Sort] Update solution for the merge intervals (soapyigu)54513f6— Refactor solutions for Valid Parentheses and Insert Interval (soapyigu)26c5865— Refactor solution to the Valid Palindrome II (soapyigu)e9253b8— Graph (#373) (soapyigu)bcbd9ce— Merge pull request #371 from soapyigu/BFS (soapyigu)4bb1804— Merge pull request #370 from soapyigu/Sort (soapyigu)c21f624— Merge pull request #342 from soapyigu/Tree (soapyigu)2d0166c— Merge pull request #357 from mertlsarac/master (soapyigu)89640c0— Merge pull request #365 from soapyigu/Graph (soapyigu)13393c1— Merge pull request #369 from soapyigu/README (soapyigu)
🔒Security observations
This is a LeetCode solutions repository written in Swift. The codebase presents minimal security risks as it is a collection of algorithm implementation examples without external dependencies, backend services, or data handling operations. No hardcoded secrets, injection vulnerabilities, or misconfigurations were detected. The repository is suitable for educational purposes.
LLM-derived; treat as a starting point, not a security audit.
👉Where to read next
- Open issues — current backlog
- Recent PRs — what's actively shipping
- Source on GitHub
Generated by RepoPilot. Verdict based on maintenance signals — see the live page for receipts. Re-run on a new commit to refresh.