Skip to content
Merged
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
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# Swift Algorithms ![](https://github.com/ahcode0919/swift-ds-algorithms/actions/workflows/ci.yml/badge.svg?branch=main)
# Swift Algorithms ![](https://github.com/ahcode0919/swift-ds-algorithms/actions/workflows/swift.yml/badge.svg?branch=main)

Repository of solutions to various problems and algorithms in Swift.

Expand Down
3 changes: 2 additions & 1 deletion Sources/swift-ds-algorithms/Arrays/ArrayFirstDuplicate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,9 @@

import Foundation

public class ArrayFirstDuplicate {
public enum ArrayFirstDuplicate {

/// Given an array that contains only numbers, find the first duplicate number.
public static func firstDuplicate(_ array: [Int]) -> Int? {
var uniqueNums = Set<Int>()

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,9 @@

import Foundation

public class ArrayRemoveDuplicates {
/// Find and remove duplicate elements from an Array.
public enum ArrayRemoveDuplicates {
/// Uses an `NSOrderedSet` to maintain order and return unique elements.
public static func removeDuplicatesWithNSOrderedSet<T>(_ array: [T]) -> [T] {
let set = NSOrderedSet(array: array)
guard let newArray = set.array as? [T] else {
Expand All @@ -16,6 +18,7 @@ public class ArrayRemoveDuplicates {
return newArray
}

/// Uses a `Set` to track duplicates as it builds a new array in-order.
public static func removeDuplicatesWithSet<T: Hashable & Equatable>(_ array: [T]) -> [T] {
var uniqueValues: [T] = []
var seen = Set<T>()
Expand All @@ -30,6 +33,8 @@ public class ArrayRemoveDuplicates {
return uniqueValues
}

/// Uses `reduce(into:_)` to iterate through the array. This approach is less efficient
/// due to the time complexity of the inner `contains`.
public static func removeDuplicatesWithReduce<T: Equatable>(_ array: [T]) -> [T] {
return array.reduce(into: []) { (results, value) in
let elementPresent = results.contains { (element) -> Bool in
Expand Down
4 changes: 4 additions & 0 deletions Sources/swift-ds-algorithms/Arrays/LongestWord.swift
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@
// Copyright © 2026. All rights reserved.
//

/// Find the longest word in a sentence.
public enum LongestWord {
/// Returns the longest word in the sentence by splitting on spaces and comparing lengths.
public static func longestWord(in sentence: String) -> String? {
guard sentence.count > 0 else {
return nil
Expand All @@ -26,6 +28,8 @@ public enum LongestWord {
return nil
}

/// Returns the longest word in the sentence in a single pass by tracking the start and
/// end indices of the current word as it scans for spaces.
public static func longestWordOnePass(in sentence: String) -> String? {
guard sentence.count > 0 else {
return nil
Expand Down
3 changes: 3 additions & 0 deletions Sources/swift-ds-algorithms/Arrays/MaxValue.swift
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@
// Copyright © 2026. All rights reserved.
//

/// Find the maximum value in an array of integers.
public enum MaxValue {
/// Returns the maximum value using the built-in `max()` function.
public static func max_value_builtin(nums: [Int]) -> Int? {
guard !nums.isEmpty else {
return nil
Expand All @@ -14,6 +16,7 @@ public enum MaxValue {
return nums.max()
}

/// Returns the maximum value by iterating and tracking the running maximum.
public static func max_value(nums: [Int]) -> Int? {
guard nums.count > 0 else {
return nil
Expand Down
3 changes: 3 additions & 0 deletions Sources/swift-ds-algorithms/Arrays/Pairs.swift
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,10 @@
// Copyright © 2026. All rights reserved.
//

/// Generate pairs of elements from an array.
public enum Pairs {
/// Returns every unique pair of elements from the array, without repeating a pair in
/// reverse order.
public static func pairs(for elements: [String]) -> [[String]] {
var pairs = [[String]]()

Expand Down
117 changes: 0 additions & 117 deletions Sources/swift-ds-algorithms/Arrays/README.md

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@
// Created by Aaron on 3/14/21.
//

public class RemoveDuplicatesFromSortedArray {
public enum RemoveDuplicatesFromSortedArray {
/// Remove duplicate values in-place from a sorted array.
public static func removeDuplicates(array: inout [Int]) {
var count = 0
while count < array.count - 1 {
Expand Down
4 changes: 3 additions & 1 deletion Sources/swift-ds-algorithms/Arrays/RemoveElement.swift
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@
// Created by Aaron on 3/19/26.
//

public class RemoveElement {
/// You are given an integer array and an integer. Remove all occurrences of the integer
/// from the array in-place.
public enum RemoveElement {
/// Remove the element from the array in-place and return the new length of the array
public static func removeElement(from arr: inout [Int], value: Int) -> Int {
var p1 = 0
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@
// Copyright © 2026. All rights reserved.
//

/// Traverse a binary tree breadth-first (level by level).
public enum BreadthFirstSearch {
/// Returns the tree's values in breadth-first (level) order using a queue.
public static func bfsValues(root: BinaryTreeNode<Int>?) -> [Int] {
var values = [Int]()

Expand Down
3 changes: 3 additions & 0 deletions Sources/swift-ds-algorithms/BinaryTree/DepthFirstSearch.swift
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@
// Copyright © 2026. All rights reserved.
//

/// Traverse a binary tree depth-first in pre-order (node, left, right).
public enum DepthFirstSearch {
/// Returns the tree's values in pre-order using recursion.
public static func dfsRecursive(root: BinaryTreeNode<Int>?) -> [Int] {
guard let root else {
return []
Expand All @@ -24,6 +26,7 @@ public enum DepthFirstSearch {
return values
}

/// Returns the tree's values in pre-order using an explicit stack.
public static func dfs(root: BinaryTreeNode<Int>?) -> [Int] {
var values = [Int]()

Expand Down
3 changes: 3 additions & 0 deletions Sources/swift-ds-algorithms/BinaryTree/TreeSum.swift
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@
// Copyright © 2026. All rights reserved.
//

/// Sum all the values in a binary tree.
public enum TreeSum {
/// Sums the tree's values iteratively using an explicit stack.
public static func treeSumIterative(root: BinaryTreeNode<Int>?) -> Int {
var total = 0

Expand All @@ -30,6 +32,7 @@ public enum TreeSum {
return total
}

/// Sums the tree's values recursively.
public static func treeSumRecursive(root: BinaryTreeNode<Int>?) -> Int {
guard let root else {
return 0
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,11 @@
// Created by Aaron on 4/14/26.
//

/// Validate whether a binary tree is a valid binary search tree.
public enum ValidateBinaryTree {

/// Returns true if every node's value falls strictly between the lower and upper
/// bounds established by its ancestors, verified iteratively with an explicit stack.
public static func isValidBST(_ root: BinaryTreeNode<Int>?) -> Bool {
guard let root else {
return false
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
// Created by Aaron on 4/21/26.
//

/// Queue backed by a fixed-size array that wraps around on itself, doubling its capacity
/// and reindexing when full.
public class CircularQueue<T> {
private var storage: [T?]

Expand All @@ -18,6 +20,7 @@ public class CircularQueue<T> {
self.storage = [T?](repeating: nil, count: capacity)
}

/// Add a value to the queue, doubling and resizing the underlying storage if it's at capacity.
public func enqueue(_ value: T) {
if count == capacity {
self.capacity *= 2
Expand All @@ -34,10 +37,12 @@ public class CircularQueue<T> {
}
}

/// Returns true if the queue contains no elements.
public func empty() -> Bool {
return count == 0
}

/// Remove and return the value at the front of the queue.
public func deque() -> T? {
guard count > 0 else {
return nil
Expand All @@ -51,6 +56,7 @@ public class CircularQueue<T> {
return value
}

/// Grow the underlying storage to the given capacity.
public func resize(capacity: Int) {
if capacity < self.capacity {
return
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
// Created by Aaron on 4/20/26.
//

/// Doubly linked list backed by dummy head and tail sentinel nodes.
public class DoublyLinkedList<T> {
private var dummyHead: DoublyLinkedListNode<T>
private var dummyTail: DoublyLinkedListNode<T>
Expand All @@ -26,6 +27,7 @@ public class DoublyLinkedList<T> {
self.dummyTail.previous = dummyHead
}

/// Add a value to the end of the list.
public func append(_ value: T) {
let node = DoublyLinkedListNode<T>(value: value)
count += 1
Expand All @@ -36,6 +38,7 @@ public class DoublyLinkedList<T> {
node.next = dummyTail
}

/// Add a value to the front of the list.
public func appendLeft(_ value: T) {
let node = DoublyLinkedListNode<T>(value: value)
count += 1
Expand All @@ -46,10 +49,12 @@ public class DoublyLinkedList<T> {
dummyHead.next? = node
}

/// Returns true if the list contains no elements.
public func empty() -> Bool {
return count == 0
}

/// Remove and return the value at the end of the list.
public func pop() -> T? {
guard let previous = dummyTail.previous, previous !== dummyHead else {
return nil
Expand All @@ -64,6 +69,7 @@ public class DoublyLinkedList<T> {
return previous.value
}

/// Remove and return the value at the front of the list.
public func popLeft() -> T? {
guard let next = dummyHead.next, next !== dummyTail else {
return nil
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
// Created by Aaron on 4/14/26.
//

/// Node used by binary tree algorithms, holding a value and optional left/right children.
public class BinaryTreeNode<T> {
public var value: T
public var left: BinaryTreeNode?
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
// Created by Aaron on 4/20/26.
//

/// Node used by `DoublyLinkedList`, holding a value and references to the previous and next nodes.
public class DoublyLinkedListNode<T> {
public var value: T?
public var previous: DoublyLinkedListNode?
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@

import Foundation

/// Node used by `SinglyLinkedList`, holding a value and a reference to the next node.
public class SinglyLinkedListNode<T> {
public var next: SinglyLinkedListNode<T>?
public var value: T
Expand Down
Loading