diff --git a/README.md b/README.md index acfbf7f..547a91b 100644 --- a/README.md +++ b/README.md @@ -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. diff --git a/Sources/swift-ds-algorithms/Arrays/ArrayFirstDuplicate.swift b/Sources/swift-ds-algorithms/Arrays/ArrayFirstDuplicate.swift index 3406538..0828162 100644 --- a/Sources/swift-ds-algorithms/Arrays/ArrayFirstDuplicate.swift +++ b/Sources/swift-ds-algorithms/Arrays/ArrayFirstDuplicate.swift @@ -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() diff --git a/Sources/swift-ds-algorithms/Arrays/ArrayRemoveDuplicates.swift b/Sources/swift-ds-algorithms/Arrays/ArrayRemoveDuplicates.swift index 002438e..319858c 100644 --- a/Sources/swift-ds-algorithms/Arrays/ArrayRemoveDuplicates.swift +++ b/Sources/swift-ds-algorithms/Arrays/ArrayRemoveDuplicates.swift @@ -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(_ array: [T]) -> [T] { let set = NSOrderedSet(array: array) guard let newArray = set.array as? [T] else { @@ -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(_ array: [T]) -> [T] { var uniqueValues: [T] = [] var seen = Set() @@ -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(_ array: [T]) -> [T] { return array.reduce(into: []) { (results, value) in let elementPresent = results.contains { (element) -> Bool in diff --git a/Sources/swift-ds-algorithms/Arrays/LongestWord.swift b/Sources/swift-ds-algorithms/Arrays/LongestWord.swift index efaacaa..68c6ba5 100644 --- a/Sources/swift-ds-algorithms/Arrays/LongestWord.swift +++ b/Sources/swift-ds-algorithms/Arrays/LongestWord.swift @@ -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 @@ -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 diff --git a/Sources/swift-ds-algorithms/Arrays/MaxValue.swift b/Sources/swift-ds-algorithms/Arrays/MaxValue.swift index 562ec0e..de27a5d 100644 --- a/Sources/swift-ds-algorithms/Arrays/MaxValue.swift +++ b/Sources/swift-ds-algorithms/Arrays/MaxValue.swift @@ -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 @@ -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 diff --git a/Sources/swift-ds-algorithms/Arrays/Pairs.swift b/Sources/swift-ds-algorithms/Arrays/Pairs.swift index 2abd8e4..c9d18d4 100644 --- a/Sources/swift-ds-algorithms/Arrays/Pairs.swift +++ b/Sources/swift-ds-algorithms/Arrays/Pairs.swift @@ -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]]() diff --git a/Sources/swift-ds-algorithms/Arrays/README.md b/Sources/swift-ds-algorithms/Arrays/README.md deleted file mode 100644 index b308c3b..0000000 --- a/Sources/swift-ds-algorithms/Arrays/README.md +++ /dev/null @@ -1,117 +0,0 @@ -# Arrays - -- [First Duplicate](#first-duplicate) -- [Remove Duplicates](#remove-duplicates) -- [Remove Duplicates From Sorted Array](#remove-duplicates-from-sorted-array) - -## First Duplicate - -Given an array a that contains only numbers find the first duplicate number - -```swift -static func firstDuplicate(_ array: Array) -> Int? { - var uniqueNums = Set() - - for (index, number) in array.enumerated() { - if uniqueNums.contains(number) { - return index - } - uniqueNums.insert(number) - } - return nil -} -``` - -## Remove Duplicates - -Find and remove duplicate elements from an Array - -Approach 1 - Use an NSOrderedSet to maintain order and return unique elements - -```swift -static func removeDuplicatesWithNSOrderedSet(_ array: [T]) -> [T] { - let set = NSOrderedSet(array: array) - guard let newArray = set.array as? [T] else { - return array - } - return newArray -} -``` - -Approach 2 - Use `reduce(into:_)` to iterate through array. This approach is less efficient due to the time complexity of the inner `contains` - -```swift -static func removeDuplicatesWithReduce(_ array: [T]) -> [T] { - return array.reduce(into: []) { (results, value) in - let elementPresent = results.contains() { (element) -> Bool in - element == value - } - if !elementPresent { - results.append(value) - } - } -} -``` - -Approach 3 - Use a `Set` to track duplicates as we build a new array in-order - -```swift -static func removeDuplicatesWithSet(_ array: [T]) -> [T] { - var uniqueValues: [T] = [] - var seen = Set() - for value in array { - if seen.contains(value) { - continue - } else { - uniqueValues.append(value) - seen.insert(value) - } - } - return uniqueValues -} -``` - -## Remove Duplicates From Sorted Array - -Remove duplicate values in-place from a sorted array. - -```swift -static func removeDuplicates(array: inout [Int]) { - var count = 0 - while count < array.count - 1 { - if array[count] == array[count + 1] { - array.remove(at: count + 1) - } else { - count += 1 - } - } -} -``` - -## Remove Element - -You are given an integer array and an integer. Remove all occurrences of the integer from the array in-place. - -```swift -class 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 - var p2 = 0 - var length = arr.count - - while p1 < arr.count, p2 < arr.count { - if arr[p2] == value { - length -= 1 - } else { - arr[p1] = arr[p2] - p1 += 1 - } - p2 += 1 - } - - return length - } -} - -``` diff --git a/Sources/swift-ds-algorithms/Arrays/RemoveDuplicatesFromSortedArray.swift b/Sources/swift-ds-algorithms/Arrays/RemoveDuplicatesFromSortedArray.swift index 58c1d35..999f43c 100644 --- a/Sources/swift-ds-algorithms/Arrays/RemoveDuplicatesFromSortedArray.swift +++ b/Sources/swift-ds-algorithms/Arrays/RemoveDuplicatesFromSortedArray.swift @@ -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 { diff --git a/Sources/swift-ds-algorithms/Arrays/RemoveElement.swift b/Sources/swift-ds-algorithms/Arrays/RemoveElement.swift index 97a0e2d..484ae1b 100644 --- a/Sources/swift-ds-algorithms/Arrays/RemoveElement.swift +++ b/Sources/swift-ds-algorithms/Arrays/RemoveElement.swift @@ -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 diff --git a/Sources/swift-ds-algorithms/BinaryTree/BreadthFirstSearchValues.swift b/Sources/swift-ds-algorithms/BinaryTree/BreadthFirstSearchValues.swift index 47dcc68..eeccbb3 100644 --- a/Sources/swift-ds-algorithms/BinaryTree/BreadthFirstSearchValues.swift +++ b/Sources/swift-ds-algorithms/BinaryTree/BreadthFirstSearchValues.swift @@ -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] { var values = [Int]() diff --git a/Sources/swift-ds-algorithms/BinaryTree/DepthFirstSearch.swift b/Sources/swift-ds-algorithms/BinaryTree/DepthFirstSearch.swift index 1b89653..ea01ac8 100644 --- a/Sources/swift-ds-algorithms/BinaryTree/DepthFirstSearch.swift +++ b/Sources/swift-ds-algorithms/BinaryTree/DepthFirstSearch.swift @@ -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] { guard let root else { return [] @@ -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] { var values = [Int]() diff --git a/Sources/swift-ds-algorithms/BinaryTree/TreeSum.swift b/Sources/swift-ds-algorithms/BinaryTree/TreeSum.swift index 72c90c4..62d8db4 100644 --- a/Sources/swift-ds-algorithms/BinaryTree/TreeSum.swift +++ b/Sources/swift-ds-algorithms/BinaryTree/TreeSum.swift @@ -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 { var total = 0 @@ -30,6 +32,7 @@ public enum TreeSum { return total } + /// Sums the tree's values recursively. public static func treeSumRecursive(root: BinaryTreeNode?) -> Int { guard let root else { return 0 diff --git a/Sources/swift-ds-algorithms/BinaryTree/ValidateBinaryTree.swift b/Sources/swift-ds-algorithms/BinaryTree/ValidateBinaryTree.swift index 99a8242..f9547b5 100644 --- a/Sources/swift-ds-algorithms/BinaryTree/ValidateBinaryTree.swift +++ b/Sources/swift-ds-algorithms/BinaryTree/ValidateBinaryTree.swift @@ -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?) -> Bool { guard let root else { return false diff --git a/Sources/swift-ds-algorithms/DataStructures/CircularQueue.swift b/Sources/swift-ds-algorithms/DataStructures/CircularQueue.swift index 3284f1d..5d49012 100644 --- a/Sources/swift-ds-algorithms/DataStructures/CircularQueue.swift +++ b/Sources/swift-ds-algorithms/DataStructures/CircularQueue.swift @@ -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 { private var storage: [T?] @@ -18,6 +20,7 @@ public class CircularQueue { 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 @@ -34,10 +37,12 @@ public class CircularQueue { } } + /// 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 @@ -51,6 +56,7 @@ public class CircularQueue { return value } + /// Grow the underlying storage to the given capacity. public func resize(capacity: Int) { if capacity < self.capacity { return diff --git a/Sources/swift-ds-algorithms/DataStructures/DoublyLinkedList.swift b/Sources/swift-ds-algorithms/DataStructures/DoublyLinkedList.swift index 7478007..59914b2 100644 --- a/Sources/swift-ds-algorithms/DataStructures/DoublyLinkedList.swift +++ b/Sources/swift-ds-algorithms/DataStructures/DoublyLinkedList.swift @@ -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 { private var dummyHead: DoublyLinkedListNode private var dummyTail: DoublyLinkedListNode @@ -26,6 +27,7 @@ public class DoublyLinkedList { self.dummyTail.previous = dummyHead } + /// Add a value to the end of the list. public func append(_ value: T) { let node = DoublyLinkedListNode(value: value) count += 1 @@ -36,6 +38,7 @@ public class DoublyLinkedList { node.next = dummyTail } + /// Add a value to the front of the list. public func appendLeft(_ value: T) { let node = DoublyLinkedListNode(value: value) count += 1 @@ -46,10 +49,12 @@ public class DoublyLinkedList { 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 @@ -64,6 +69,7 @@ public class DoublyLinkedList { 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 diff --git a/Sources/swift-ds-algorithms/DataStructures/NodeTypes/BinaryTreeNode.swift b/Sources/swift-ds-algorithms/DataStructures/NodeTypes/BinaryTreeNode.swift index 67c5e6e..0e0b153 100644 --- a/Sources/swift-ds-algorithms/DataStructures/NodeTypes/BinaryTreeNode.swift +++ b/Sources/swift-ds-algorithms/DataStructures/NodeTypes/BinaryTreeNode.swift @@ -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 { public var value: T public var left: BinaryTreeNode? diff --git a/Sources/swift-ds-algorithms/DataStructures/NodeTypes/DoublyLinkedListNode.swift b/Sources/swift-ds-algorithms/DataStructures/NodeTypes/DoublyLinkedListNode.swift index d7042b1..0abacff 100644 --- a/Sources/swift-ds-algorithms/DataStructures/NodeTypes/DoublyLinkedListNode.swift +++ b/Sources/swift-ds-algorithms/DataStructures/NodeTypes/DoublyLinkedListNode.swift @@ -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 { public var value: T? public var previous: DoublyLinkedListNode? diff --git a/Sources/swift-ds-algorithms/DataStructures/NodeTypes/SinglyLinkedListNode.swift b/Sources/swift-ds-algorithms/DataStructures/NodeTypes/SinglyLinkedListNode.swift index 36aa9bc..670df6e 100644 --- a/Sources/swift-ds-algorithms/DataStructures/NodeTypes/SinglyLinkedListNode.swift +++ b/Sources/swift-ds-algorithms/DataStructures/NodeTypes/SinglyLinkedListNode.swift @@ -7,6 +7,7 @@ import Foundation +/// Node used by `SinglyLinkedList`, holding a value and a reference to the next node. public class SinglyLinkedListNode { public var next: SinglyLinkedListNode? public var value: T diff --git a/Sources/swift-ds-algorithms/DataStructures/NodeTypes/TrieNode.swift b/Sources/swift-ds-algorithms/DataStructures/NodeTypes/TrieNode.swift index 165de9f..7f153db 100644 --- a/Sources/swift-ds-algorithms/DataStructures/NodeTypes/TrieNode.swift +++ b/Sources/swift-ds-algorithms/DataStructures/NodeTypes/TrieNode.swift @@ -5,6 +5,7 @@ // Created by Aaron on 4/22/26. // +/// Node used to build a trie, holding a value and its child nodes. public class TrieNode { public var value: T public var children: [TrieNode] diff --git a/Sources/swift-ds-algorithms/DataStructures/Queue.swift b/Sources/swift-ds-algorithms/DataStructures/Queue.swift index 92b8026..af2e418 100644 --- a/Sources/swift-ds-algorithms/DataStructures/Queue.swift +++ b/Sources/swift-ds-algorithms/DataStructures/Queue.swift @@ -5,6 +5,7 @@ // Created by Aaron on 4/20/26. // +/// Queue data structure backed by a `DoublyLinkedList`. Queue is a FIFO data structure. public class Queue { public private(set) var count: Int = 0 @@ -13,11 +14,13 @@ public class Queue { private var list: DoublyLinkedList = DoublyLinkedList() + /// Add a value to the back of the queue. public func enqueue(_ value: T) { count += 1 list.appendLeft(value) } + /// Remove and return the value at the front of the queue. @discardableResult public func deque() -> T? { if let value = list.pop() { @@ -27,10 +30,12 @@ public class Queue { return nil } + /// Returns true if the queue contains no elements. public func empty() -> Bool { return count == 0 } + /// Returns the value at the front of the queue without removing it. public func peek() -> T? { return list.last } diff --git a/Sources/swift-ds-algorithms/DataStructures/README.md b/Sources/swift-ds-algorithms/DataStructures/README.md deleted file mode 100644 index f037420..0000000 --- a/Sources/swift-ds-algorithms/DataStructures/README.md +++ /dev/null @@ -1,174 +0,0 @@ -# Data Structures - -- [Singly Linked List](#singly-linked-list) -- [Stack](#stack) - -## Singly Linked List - - -`SinglyLinkedListNode` - -```swift -class SinglyLinkedListNode { - var next: SinglyLinkedListNode? - var value: T - - init(value: T) { - self.value = value - } -} -``` - -`SinglyLinkedList` - -```swift -class SinglyLinkedList { - var head: SinglyLinkedListNode? - var length: Int { - get { - var count = 0 - var currentNode = self.head - - while let node = currentNode { - currentNode = node.next - count += 1 - } - return count - } - } - - init() { } - - init(node: SinglyLinkedListNode) { - self.head = node - } - - func append(_ node: SinglyLinkedListNode) { - guard var currentNode = self.head else { - self.head = node - return - } - while let nextNode = currentNode.next { - currentNode = nextNode - } - currentNode.next = node - } - - func appendLeft(_ node: SinglyLinkedListNode) { - if let head = self.head { - node.next = head - } - self.head = node - } - - func node(atIndex index: Int) -> SinglyLinkedListNode? { - var currentNode = self.head - var count = 0 - - while let node = currentNode { - if count == index { - return currentNode - } - currentNode = node.next - count += 1 - } - return nil - } - - func pop() -> SinglyLinkedListNode? { - guard var currentNode = self.head else { - return nil - } - - guard var nextNode = currentNode.next else { - self.head = nil - return currentNode - } - - while let nextNextNode = nextNode.next { - currentNode = nextNode - nextNode = nextNextNode - } - - currentNode.next = nil - return nextNode - } - - func popLeft() -> SinglyLinkedListNode? { - guard let head = self.head else { - return nil - } - - self.head = head.next - head.next = nil - return head - } - - func remove(atIndex index: Int) -> SinglyLinkedListNode? { - guard var currentNode = self.head else { - return nil - } - - if index == 0 { - self.head = currentNode.next - currentNode.next = nil - return currentNode - } - - var count = 1 - - while count <= index, let indexNode = currentNode.next { - if count == index { - currentNode.next = indexNode.next - indexNode.next = nil - return indexNode - } - - currentNode = indexNode - count += 1 - } - return nil - } - - func values() -> [T] { - var values: [T] = [] - var currentNode = self.head - - while let node = currentNode { - values.append(node.value) - currentNode = node.next - } - - return values - } -} - -``` - -## Stack - -Basic stack implementation. Stack is a LIFO data structure - -```swift -class Stack { - private var stack: [T] = [] - - init() {} - - func empty() -> Bool { - return self.size() == 0 - } - - func pop() -> T? { - return self.stack.popLast() - } - - func push(value: T) { - self.stack.append(value) - } - - func size() -> Int { - return self.stack.count - } -} -``` diff --git a/Sources/swift-ds-algorithms/DataStructures/SinglyLinkedList.swift b/Sources/swift-ds-algorithms/DataStructures/SinglyLinkedList.swift index ba2e674..2bb8753 100644 --- a/Sources/swift-ds-algorithms/DataStructures/SinglyLinkedList.swift +++ b/Sources/swift-ds-algorithms/DataStructures/SinglyLinkedList.swift @@ -7,6 +7,7 @@ import Foundation +/// Singly linked list data structure. public class SinglyLinkedList { public var head: SinglyLinkedListNode? public var length: Int { diff --git a/Sources/swift-ds-algorithms/DataStructures/Stack.swift b/Sources/swift-ds-algorithms/DataStructures/Stack.swift index db40734..b6d1f69 100644 --- a/Sources/swift-ds-algorithms/DataStructures/Stack.swift +++ b/Sources/swift-ds-algorithms/DataStructures/Stack.swift @@ -5,6 +5,7 @@ // Created by Aaron on 3/14/21. // +/// Basic stack implementation. Stack is a LIFO data structure. public class Stack { private var stack: [T] = [] diff --git a/Sources/swift-ds-algorithms/Integers/CenturyFromYear.swift b/Sources/swift-ds-algorithms/Integers/CenturyFromYear.swift index 355a917..56a88c7 100644 --- a/Sources/swift-ds-algorithms/Integers/CenturyFromYear.swift +++ b/Sources/swift-ds-algorithms/Integers/CenturyFromYear.swift @@ -8,6 +8,16 @@ import Foundation public class CenturyFromYear { + /// Given a year, return the century it is in. The first century spans from the year + /// 1 up to and including the year 100, the second - from the year 101 up to and + /// including the year 200, etc. + /// + /// Example: + /// * For `year = 1905`, the output should be `centuryFromYear(year) = 20` + /// * For `year = 1700`, the output should be `centuryFromYear(year) = 17` + /// + /// - Parameter year: A positive integer, designating the year. + /// - Returns: The number of the century the year is in. public static func centuryFromYear(year: Int) -> Int { let hundreths = Double(year) / 100 return Int(hundreths.rounded(.up)) diff --git a/Sources/swift-ds-algorithms/Integers/README.md b/Sources/swift-ds-algorithms/Integers/README.md deleted file mode 100644 index b08cabb..0000000 --- a/Sources/swift-ds-algorithms/Integers/README.md +++ /dev/null @@ -1,23 +0,0 @@ -# Integers - -- [Century From Year](#century-from-year) - -## Century From Year - -Given a year, return the century it is in. The first century spans from the year -1 up to and including the year 100, the second - from the year 101 up to and -including the year 200, etc. - -Example: - -* For `year = 1905`, the output should be `centuryFromYear(year) = 20` -* For `year = 1700`, the output should be `centuryFromYear(year) = 17` -* [input] integer year - A positive integer, designating the year. -* [output] integer - The number of the century the year is in. - -```swift -static func centuryFromYear(year: Int) -> Int { - let hundreths = Double(year) / 100 - return Int(hundreths.rounded(.up)) -} -``` diff --git a/Sources/swift-ds-algorithms/LinkedList/MergeLists.swift b/Sources/swift-ds-algorithms/LinkedList/MergeLists.swift index 118ba48..f5259b7 100644 --- a/Sources/swift-ds-algorithms/LinkedList/MergeLists.swift +++ b/Sources/swift-ds-algorithms/LinkedList/MergeLists.swift @@ -5,7 +5,9 @@ // Copyright © 2026. All rights reserved. // +/// Merge two sorted singly linked lists into a single sorted list. public enum MergeLists { + /// Merges `head1` and `head2`, both assumed to already be sorted in ascending order. public static func merge( head1: SinglyLinkedListNode?, head2: SinglyLinkedListNode? diff --git a/Sources/swift-ds-algorithms/LinkedList/ReverseLinkedList.swift b/Sources/swift-ds-algorithms/LinkedList/ReverseLinkedList.swift index c197bcc..b8b5687 100644 --- a/Sources/swift-ds-algorithms/LinkedList/ReverseLinkedList.swift +++ b/Sources/swift-ds-algorithms/LinkedList/ReverseLinkedList.swift @@ -5,7 +5,9 @@ // Copyright © 2026. All rights reserved. // +/// Reverse a singly linked list. public enum ReverseLinkedList { + /// Reverses the list iteratively and returns the new head. public static func reverse(head: SinglyLinkedListNode?) -> SinglyLinkedListNode? { var prev: SinglyLinkedListNode? var current: SinglyLinkedListNode? = head @@ -20,6 +22,7 @@ public enum ReverseLinkedList { return prev } + /// Reverses the list recursively and returns the new head. public static func reverseRecursive( head: SinglyLinkedListNode?, prev: SinglyLinkedListNode? = nil diff --git a/Sources/swift-ds-algorithms/LinkedList/ZipperLists.swift b/Sources/swift-ds-algorithms/LinkedList/ZipperLists.swift index 7f3bd45..7ba2cfd 100644 --- a/Sources/swift-ds-algorithms/LinkedList/ZipperLists.swift +++ b/Sources/swift-ds-algorithms/LinkedList/ZipperLists.swift @@ -5,7 +5,10 @@ // Copyright © 2026. All rights reserved. // +/// Interleave (zipper) two singly linked lists node by node. public enum ZipperLists { + /// Merges `head1` and `head2` by alternating nodes from each list. Any remaining nodes + /// from the longer list are appended at the end. public static func zipper( head1: SinglyLinkedListNode?, head2: SinglyLinkedListNode? diff --git a/Sources/swift-ds-algorithms/Stack/Brackets.swift b/Sources/swift-ds-algorithms/Stack/Brackets.swift index 81a1590..517b44b 100644 --- a/Sources/swift-ds-algorithms/Stack/Brackets.swift +++ b/Sources/swift-ds-algorithms/Stack/Brackets.swift @@ -5,7 +5,10 @@ // Created by Aaron on 6/10/26. // +/// Check that a string's brackets are balanced and properly nested. public enum Brackets { + /// Returns true if every `(`, `[`, and `{` in the input is closed by the matching + /// bracket in the correct order. public static func validBrackets(_ input: String) -> Bool { let stack = Stack() let brackets: [Character: Character] = [ diff --git a/Sources/swift-ds-algorithms/Strings/Anagrams.swift b/Sources/swift-ds-algorithms/Strings/Anagrams.swift index 3979f58..bb1b3dc 100644 --- a/Sources/swift-ds-algorithms/Strings/Anagrams.swift +++ b/Sources/swift-ds-algorithms/Strings/Anagrams.swift @@ -5,7 +5,9 @@ // Copyright © 2026. All rights reserved. // +/// Check if two strings are anagrams of each other. public enum Anagrams { + /// Returns true if `a` and `b` contain the same characters with the same frequency. public static func isAnagram(_ a: String, _ b: String) -> Bool { var dictA = [Character: Int]() var dictB = [Character: Int]() diff --git a/Sources/swift-ds-algorithms/Strings/CondenseWhitespace.swift b/Sources/swift-ds-algorithms/Strings/CondenseWhitespace.swift index 26338d8..89426da 100644 --- a/Sources/swift-ds-algorithms/Strings/CondenseWhitespace.swift +++ b/Sources/swift-ds-algorithms/Strings/CondenseWhitespace.swift @@ -7,8 +7,11 @@ import Foundation -/// Remove extra white space from String +/// Remove the whitespace from a String. +/// +/// Example: "Hello World" -> "HelloWorld" public class CondenseWhitespace { + /// Approach 1: Remove whitespace using a for loop and a character array. public static func condenseWhitespaceWithLoop(_ text: String) -> String { var charArray = [Character]() var lastCharWasSpace = false @@ -30,10 +33,13 @@ public class CondenseWhitespace { return String(charArray) } + /// Approach 2: Utilize a regular expression to remove whitespace. public static func condenseWhitespaceWithRegex(_ text: String) -> String { return text.replacingOccurrences(of: " +", with: " ", options: .regularExpression) } + /// Approach 3: Utilize the `split(separator:_)` String function to remove whitespace + /// and then `joined(separator:_)` to concatenate the result. public static func condenseWhitespaceWithSplit(_ text: String) -> String { var result = text.split(separator: " ").joined(separator: " ") if text.first == " " { diff --git a/Sources/swift-ds-algorithms/Strings/Contains.swift b/Sources/swift-ds-algorithms/Strings/Contains.swift index f195994..305aea1 100644 --- a/Sources/swift-ds-algorithms/Strings/Contains.swift +++ b/Sources/swift-ds-algorithms/Strings/Contains.swift @@ -10,6 +10,7 @@ import Foundation /// Check if one string contains another public class Contains { + /// Approach 1: Use the `range(of:_)` String API function to check for presence of a substring. public static func containsIgnoreCaseWithRange(_ string1: String, contains string2: String) -> Bool { if string1.count < string2.count || string1.isEmpty && string2.isEmpty { return false @@ -17,6 +18,7 @@ public class Contains { return string1.range(of: string2) != nil } + /// Approach 2: Use a for loop to iterate across strings. public static func containsIgnoreCaseWithLoop(_ string1: String, contains string2: String) -> Bool { if string1.count < string2.count || string1.isEmpty && string2.isEmpty { return false @@ -44,6 +46,7 @@ public class Contains { return false } + /// Approach 3: Use the native String API `contains(:_)`. public static func containsWithStringAPI(_ string1: String, contains string2: String) -> Bool { return string1.contains(string2) } diff --git a/Sources/swift-ds-algorithms/Strings/FirstNotRepeatingCharacter.swift b/Sources/swift-ds-algorithms/Strings/FirstNotRepeatingCharacter.swift index 2312f46..3f59468 100644 --- a/Sources/swift-ds-algorithms/Strings/FirstNotRepeatingCharacter.swift +++ b/Sources/swift-ds-algorithms/Strings/FirstNotRepeatingCharacter.swift @@ -7,6 +7,8 @@ import Foundation +/// Given a string, find and return the first instance of a non-repeating character in it. +/// If there is no such character, return '_'. public class FirstNotRepeatingCharacter { public static func firstWithDictionary(_ string: String) -> Character? { diff --git a/Sources/swift-ds-algorithms/Strings/OccurrencesOfCharacter.swift b/Sources/swift-ds-algorithms/Strings/OccurrencesOfCharacter.swift index 7e266d3..f4a0076 100644 --- a/Sources/swift-ds-algorithms/Strings/OccurrencesOfCharacter.swift +++ b/Sources/swift-ds-algorithms/Strings/OccurrencesOfCharacter.swift @@ -9,12 +9,14 @@ import Foundation /// Count the number of times a character occurs in a String public class OccurrencesOfCharacter { + /// Approach 1: Use filter to isolate occurrences. public static func countOccurancesWithFilter(_ char: Character, in input: String) -> Int { return input.filter { (inputChar) -> Bool in return inputChar == char }.count } + /// Approach 2: Use a for loop to iterate over the input string. public static func countOccurrencesWithLoop(_ input: Character, in text: String) -> Int { var count = 0 @@ -26,6 +28,7 @@ public class OccurrencesOfCharacter { return count } + /// Approach 3: Use the reduce function to iterate over the string and count occurrences. public static func countOccurrencesWithReduce(_ input: Character, in text: String) -> Int { return text.reduce(0) { (result, char) -> Int in return char == input ? result + 1 : result diff --git a/Sources/swift-ds-algorithms/Strings/Palindrome.swift b/Sources/swift-ds-algorithms/Strings/Palindrome.swift index 0b49df8..49a79a6 100644 --- a/Sources/swift-ds-algorithms/Strings/Palindrome.swift +++ b/Sources/swift-ds-algorithms/Strings/Palindrome.swift @@ -9,7 +9,7 @@ import Foundation /// Check that a string is the same forwards and backwards, Ex: mom, dad, etc. public class Palindrome { - /// String.reversed() - O(1) + /// Approach 1 - `String.reversed()` - O(1) public static func isPalindromeWithReverse(_ input: String) -> Bool { if input.count < 2 { return true @@ -18,6 +18,7 @@ public class Palindrome { return lowercasedInput == String(lowercasedInput.reversed()) } + /// Approach 2 - Array public static func isPalindromeWithArray(_ input: String) -> Bool { var charArray = Array(input.lowercased()) diff --git a/Sources/swift-ds-algorithms/Strings/Pangram.swift b/Sources/swift-ds-algorithms/Strings/Pangram.swift index eeace55..63ffe22 100644 --- a/Sources/swift-ds-algorithms/Strings/Pangram.swift +++ b/Sources/swift-ds-algorithms/Strings/Pangram.swift @@ -11,11 +11,13 @@ import Foundation public class Pangram { private static let alphabet = "abcdefghijklmnopqrstuvwxyz" + /// Approach 1 - Set public static func isPangramWithSet(_ string1: String) -> Bool { let string1Set = Set(string1.lowercased()) return string1Set.count == string1.count } + /// Approach 2 - Loop/Contains public static func isPangramWithLoop(_ string1: String) -> Bool { let lowercased = string1.lowercased() diff --git a/Sources/swift-ds-algorithms/Strings/README.md b/Sources/swift-ds-algorithms/Strings/README.md deleted file mode 100644 index 9fd14b7..0000000 --- a/Sources/swift-ds-algorithms/Strings/README.md +++ /dev/null @@ -1,557 +0,0 @@ -# Strings - -- [Condense Whitespace](#condense-whitespace) -- [Contains](#contains) -- [Find Longest Prefix](#find-longest-prefix) -- [First Not Repeating Character](#first-not-repeating-character) -- [Occurrences of Character](#occurences-of-character) -- [Palindrome](#palindrome) -- [Panagram](#panagram) -- [Remove Duplicates](#remove-duplicates) -- [Reverse Words In Sentence](#reverse-words-in-sentence) -- [Rotated String](#rotated-string) -- [Run Length Encoding](#run-length-encoding) -- [Same Characters](#same-characters) -- [Three Different Letters](#three-different-letters) -- [Unique Characters](#unique-characters) -- [Vowels and Consonants](#vowels-and-consonants) - -## Condense Whitespace - -Remove the whitespace from a String. - -* Example: "Hello World" -> "HelloWorld" - -Approach 1: Remove Whitespace using a for loop and a character array - -```swift -static func condenseWhitespaceWithLoop(_ text: String) -> String { - var charArray = [Character]() - var lastCharWasSpace = false - - for char in text { - if lastCharWasSpace == false { - charArray.append(char) - if char == " " { lastCharWasSpace = true } - } else { - if char == " " { continue } - charArray.append(char) - lastCharWasSpace = false - } - } - return String(charArray) -} -``` - -Approach 2: Utilize a regular expression to remove whitespace. - -```swift -static func condenseWhitespaceWithRegex(_ text: String) -> String { - return text.replacingOccurrences(of: " +", with: " ", options: .regularExpression) -} -``` - -Approach 3: Utilize the `split(separator:_)` String function remove whitespace -and then `joined(separator:_)` to concatenate the result - -```swift -static func condenseWhitespaceWithSplit(_ text: String) -> String { - var result = text.split(separator: " ").joined(separator: " ") - - if text.first == " " { result.insert(" ", at: result.startIndex) } - if text.last == " " { result.append(" ") } - return result -} -``` - -## Contains - -Check if one string contains another string - -Approach 1: Use `range(of:_)` String API function to check for presence of substring - -```swift -static func containsWithRange(_ string1: String, contains string2: String) -> Bool { - if string1.count < string2.count || string1.isEmpty && string2.isEmpty { return false } - return string1.range(of: string2) != nil -} -``` - -Approach 2: Use for loop to iterate across strings - -```swift -static func containsWithLoop(_ string1: String, contains string2: String) -> Bool { - if string1.count < string2.count || string1.isEmpty && string2.isEmpty { return false } - - let input1 = Array(string1) - let input2 = Array(string2) - - var currentIndex = 0 - - while currentIndex < input1.count - input2.count { - var match = true - for i in 0.. Bool { - return string1.contains(string2) -} -``` - -## Find Longest Prefix - -Write a function that accepts a string of words with a similar prefix, separated by spaces, -and returns the longest substring that prefixes all words. - -Example: "test tesx texx" -> "te" - -```swift -static func findLongestPrefix(_ string1: String) -> String { - let words = string1.components(separatedBy: " ") - - guard words.count > 1 else { return string1 } - - var prefixEndIndex = words[0].endIndex - - for index in 1.. prefixEndIndex { break } - - // Check if characters match - if words[0][position] == words[index][position] { continue } - - // Set the max end index to the position of our invalid match - if prefixEndIndex > position { - prefixEndIndex = position - break - } - } - } - return String(words[0].prefix(upTo: prefixEndIndex)) -} -``` - -## First Not Repeating Character - -Given a string s, find and return the first instance of a non-repeating character in it. If there is no such character, return '_'. - -```swift -class FirstNotRepeatingCharacter { - - static func firstWithDictionary(_ string: String) -> Character? { - var charCount = Dictionary(minimumCapacity: 26) - - for char in string { - charCount[char] = (charCount[char] ?? 0) + 1 - } - - for char in string { - if charCount[char] == 1 { - return char - } - } - - return nil - } -} -``` - -## Occurrences of Character - -Count the number of times a character occurs in a String - -Approach 1 - Use filter to isolate occurrences - -```swift -static func countOccurancesWithFilter(_ char: Character, in input: String) -> Int { - return input.filter { (inputChar) -> Bool in return inputChar == char }.count -} -``` - -Approach 2 - Use a for loop to iterate over the input string - -```swift -static func countOccurrencesWithLoop(_ input: Character, in text: String) -> Int { - var count = 0 - - for char in text { - if char == input { count += 1 } - } - return count -} -``` - -Approach 3 - Use the reduce function to iterate over the string and count occurrences - -```swift -static func countOccurrencesWithReduce(_ input: Character, in text: String) -> Int { - return text.reduce(0) { (result, char) -> Int in - return char == input ? result + 1 : result - } -} -``` - -## Palindrome - -Check that a string is the same forwards and backwards, Ex: mom, dad, etc. - -Approach 1 - `String.reversed()`: - -```swift -/// String.reversed() - O(1) -static func isPalindromeWithReverse(_ input: String) -> Bool { - if input.count < 2 { - return true - } - let lowercasedInput = input.lowercased() - return lowercasedInput == String(lowercasedInput.reversed()) -} -``` - -Approach 2 - Array: - -```swift -static func isPalindromeWithArray(_ input: String) -> Bool { - var charArray = Array(input.lowercased()) - - while charArray.count > 1, let last = charArray.popLast() { - if last != charArray.remove(at: 0) { - return false - } - } - return true -} -``` - -## Panagram - -Check if a String is a Pangram (Contains every letter of the alphabet) - -Approach 1 - Set: - -```swift -static func isPangramWithSet(_ string1: String) -> Bool { - let string1Set = Set(string1.lowercased()) - return string1Set.count == string1.count -} -``` - -Approach 2 - Loop/Contains: - -```swift -private static let alphabet = "abcdefghijklmnopqrstuvwxyz" - -static func isPangramWithLoop(_ string1: String) -> Bool { - let lowercased = string1.lowercased() - - for letter in alphabet { - if lowercased.contains(letter) { - continue - } - return false - } - return true -} -``` - -## Remove Duplicates - -Remove duplicate characters from a String - -Approach 1 - `NSOrderedSet`: - -```swift -static func removeDuplicatesWithNSOrderedSet(from input: String) -> String { - let set = NSOrderedSet(array: Array(input)) - if let array = set.array as? [Character] { - return String(array) - } - return input -} -``` - -Approach 2 - Set / Filter: - -```swift -static func removeDuplicatesWithSetAndFilter(from input: String) -> String { - var duplicateSet = Set() - var inputArray = Array(input) - inputArray = inputArray.filter { (char) -> Bool in - if duplicateSet.contains(char) { - return false - } - duplicateSet.insert(char) - return true - } - return String(inputArray) -} -``` - -Approach 3 - Filter: - -```swift -static func removeDuplicatesWithFilter(from input: String) -> String { - var used = [Character]() - let uniqueChars = input.filter { (char) -> Bool in - if !used.contains(char) { - used.append(char) - return true - } - return false - } - return String(uniqueChars) -} -``` - -Approach 4 - Dictionary / Filter: - -```swift -static func removeDuplicatesWithDictionaryAndFilter(from input: String) -> String { - var uniqueDictionary = Dictionary() - let output = input.filter { (char) -> Bool in - return uniqueDictionary.updateValue(true, forKey: char) == nil - } - return String(output) -} -``` - -## Reverse Words In Sentence - -Reverse the words in a sentence - -Example: "foo bar baz" -> "oof rab zab" - -```swift -class ReverseWordsInSentence { - static func reverse(_ sentence: String) -> String { - let words = sentence.split(separator: " ") - let reversedWords = words.map { $0.reversed() } - return String(reversedWords.joined(separator: " ")) - } -} -``` - -## Rotated String - -Checks that a string is "Rotated" A string rotation is when you take a string, -remove some letters from its end, then append them to the front. For example, -“swift” rotated by two characters would be “ftswi”. - -Approach 1 - Concatenate the original string to itself: -"swiftswift" contains "ftswi" -> true - -```swift -static func isRotatedStringWithAddition(_ original: String, rotated: String) -> Bool { - guard original.count == rotated.count else { return false } - - return (original + original).contains(rotated) -} -``` - -Approach 2 - Rotate through string until a match is found: - -```swift -static func isRotatedStringWithLoop(_ original: String, rotated: String) -> Bool { - guard original.count == rotated.count else { return false } - - var tempString = original - for _ in 0.. `a3b2cd3` - -```swift -static func runLengthEncoding(_ input: String) -> String { - if input.isEmpty { - return "" - } - var currentCharacter: Character? - var count = 0 - var compressedString = "" - - for index in input.indices { - if input[index] == currentCharacter { - count += 1 - } else { - if let current = currentCharacter { - let normalizedCount = count == 1 ? "": "\(count)" - compressedString += "\(current)\(normalizedCount)" - } - count = 1 - currentCharacter = input[index] - } - } - - if let character = currentCharacter { - let normalizedCount = count == 1 ? "": "\(count)" - compressedString += "\(character)\(normalizedCount)" - } - - return compressedString -} -``` - -## Same Characters - -Check that two strings have the same characters (including matching casing) - -Approach 1 - Loop: - -```swift -static func hasSameCharactersWithLoop(_ string1: String, in string2: String) -> Bool { - if string1.count != string2.count { return false } - - var input = Substring(string1) - var input2 = Substring(string2) - - while input.count != 0 { - if let char = input2.popFirst(), let index = input.index(of: char) { - input.remove(at: index) - continue - } - return false - } - return true -} -``` - -Approach 2 - Sort: - -```swift -static func hasSameCharactersWithSort(_ string1: String, in string2: String) -> Bool { - if string1.count != string2.count { return false } - - return string1.sorted() == string2.sorted() -} -``` - -Approach 3 - Dictionary: - -```swift -static func hasSameCharactersWithDictionary(_ string1: String, in string2: String) -> Bool { - if string1.count != string2.count { return false } - - var input1Dictionary = [Character: Int]() - var input2Dictionary = [Character: Int]() - - string1.forEach { (char) in - if var value = input1Dictionary[char] { - value += 1 - } else { - input1Dictionary[char] = 1 - } - } - - string2.forEach { (char) in - if var value = input2Dictionary[char] { - value += 1 - } else { - input2Dictionary[char] = 1 - } - } - - for pair in input1Dictionary.enumerated() { - if input2Dictionary[pair.element.key] != pair.element.value { return false } - } - return true -} -``` - -## Three Different Letters - -Write a function that accepts two strings, and returns true if they are identical in length -but have no more than three different letters, taking case and string order into account. - -```swift -static func threeDifferentLetters(string1: String, string2: String) -> Bool { - guard string1.count == string2.count else { return false } - var count = 0 - - for index in string1.indices { - if string1[index] == string2[index] { continue } - if count < 3 { - count += 1 - continue - } - return false - } - return true -} -``` - -## Unique Characters - -Check if a string only consists of unique characters - -Approach 1 - Set: - -```swift -static func uniqueCharactersWithSet(_ input: String) -> Bool { - if input.count < 2 { return true } - - return input.count == Set(input).count -} -``` - -Approach 2 - Loop: - -```swift -static func uniqueCharactersWithLoop(_ input: String) -> Bool { - if input.count < 2 { return true } - - var inputSet = Set() - - for char in input { - if inputSet.contains(char) { return false } - inputSet.insert(char) - } - return true -} -``` - -## Vowels and Consonants - -Count the number of vowels and consonants in a String - -```swift -static let vowels = "aeiou" -static let consonants = "bcdfghjklmnpqrstvwxyz" - -static func vowelsAndConsonantsForEach(_ string1: String) -> (vowels: Int, consonants: Int) { - let normalizedString = string1.lowercased() - var count: (vowels: Int, consonants: Int) = (vowels: 0, consonants: 0) - normalizedString.forEach { - if vowels.contains($0) { - count.vowels += 1 - } else if consonants.contains($0) { - count.consonants += 1 - } - } - return count -} -``` diff --git a/Sources/swift-ds-algorithms/Strings/RemoveDuplicates.swift b/Sources/swift-ds-algorithms/Strings/RemoveDuplicates.swift index baf19d7..dec3181 100644 --- a/Sources/swift-ds-algorithms/Strings/RemoveDuplicates.swift +++ b/Sources/swift-ds-algorithms/Strings/RemoveDuplicates.swift @@ -9,6 +9,7 @@ import Foundation /// Remove duplicate characters from a String public class RemoveDuplicates { + /// Approach 1 - `NSOrderedSet` public static func removeDuplicatesWithNSOrderedSet(from input: String) -> String { let set = NSOrderedSet(array: Array(input)) if let array = set.array as? [Character] { @@ -17,6 +18,7 @@ public class RemoveDuplicates { return input } + /// Approach 2 - Set / Filter public static func removeDuplicatesWithSetAndFilter(from input: String) -> String { var duplicateSet = Set() var inputArray = Array(input) @@ -30,6 +32,7 @@ public class RemoveDuplicates { return String(inputArray) } + /// Approach 3 - Filter public static func removeDuplicatesWithFilter(from input: String) -> String { var used = [Character]() let uniqueChars = input.filter { (char) -> Bool in @@ -42,6 +45,7 @@ public class RemoveDuplicates { return String(uniqueChars) } + /// Approach 4 - Dictionary / Filter public static func removeDuplicatesWithDictionaryAndFilter(from input: String) -> String { var uniqueDictionary = [Character: Bool]() let output = input.filter { (char) -> Bool in diff --git a/Sources/swift-ds-algorithms/Strings/ReverseWordsInSentence.swift b/Sources/swift-ds-algorithms/Strings/ReverseWordsInSentence.swift index 59a6f4a..1d44499 100644 --- a/Sources/swift-ds-algorithms/Strings/ReverseWordsInSentence.swift +++ b/Sources/swift-ds-algorithms/Strings/ReverseWordsInSentence.swift @@ -7,6 +7,9 @@ import Foundation +/// Reverse the words in a sentence. +/// +/// Example: "foo bar baz" -> "oof rab zab" public class ReverseWordsInSentence { public static func reverse(_ sentence: String) -> String { let words = sentence.split(separator: " ") diff --git a/Sources/swift-ds-algorithms/Strings/RotatedString.swift b/Sources/swift-ds-algorithms/Strings/RotatedString.swift index 8659958..706912d 100644 --- a/Sources/swift-ds-algorithms/Strings/RotatedString.swift +++ b/Sources/swift-ds-algorithms/Strings/RotatedString.swift @@ -11,12 +11,14 @@ import Foundation /// from its end, then append them to the front. /// For example, “swift” rotated by two characters would be “ftswi”. public class RotatedString { + /// Approach 1 - Concatenate the original string to itself: "swiftswift" contains "ftswi" -> true public static func isRotatedStringWithAddition(_ original: String, rotated: String) -> Bool { guard original.count == rotated.count else { return false } return (original + original).contains(rotated) } + /// Approach 2 - Rotate through the string until a match is found. public static func isRotatedStringWithLoop(_ original: String, rotated: String) -> Bool { guard original.count == rotated.count else { return false } diff --git a/Sources/swift-ds-algorithms/Strings/RunLengthEncoding.swift b/Sources/swift-ds-algorithms/Strings/RunLengthEncoding.swift index 0f5399f..6150a9e 100644 --- a/Sources/swift-ds-algorithms/Strings/RunLengthEncoding.swift +++ b/Sources/swift-ds-algorithms/Strings/RunLengthEncoding.swift @@ -7,6 +7,9 @@ import Foundation +/// Perform basic run length encoding on an input string. +/// +/// Example: `"aaabbcddd"` -> `a3b2cd3` public class RunLengthEncoding { public static func runLengthEncoding(_ input: String) -> String { if input.isEmpty { diff --git a/Sources/swift-ds-algorithms/Strings/SameCharacters.swift b/Sources/swift-ds-algorithms/Strings/SameCharacters.swift index 974b45a..3701c22 100644 --- a/Sources/swift-ds-algorithms/Strings/SameCharacters.swift +++ b/Sources/swift-ds-algorithms/Strings/SameCharacters.swift @@ -10,6 +10,7 @@ import Foundation /// Check that two strings have the same characters (including matching casing) public class SameCharacters { + /// Approach 1 - Loop public static func hasSameCharactersWithLoop(_ string1: String, in string2: String) -> Bool { if string1.count != string2.count { return false } @@ -26,12 +27,14 @@ public class SameCharacters { return true } + /// Approach 2 - Sort public static func hasSameCharactersWithSort(_ string1: String, in string2: String) -> Bool { if string1.count != string2.count { return false } return string1.sorted() == string2.sorted() } + /// Approach 3 - Dictionary public static func hasSameCharactersWithDictionary(_ string1: String, in string2: String) -> Bool { if string1.count != string2.count { return false } diff --git a/Sources/swift-ds-algorithms/TestData/BinaryTreeData.swift b/Sources/swift-ds-algorithms/TestData/BinaryTreeData.swift index a137755..d0eb5c6 100644 --- a/Sources/swift-ds-algorithms/TestData/BinaryTreeData.swift +++ b/Sources/swift-ds-algorithms/TestData/BinaryTreeData.swift @@ -5,7 +5,9 @@ // Copyright © 2026. All rights reserved. // +/// Test fixtures for building binary trees. public enum BinaryTreeData { + /// Builds a complete binary tree of the given depth with sequentially numbered values. public static func balanced(depth: Int) -> BinaryTreeNode? { guard depth >= 0 else { return nil } @@ -36,6 +38,7 @@ public enum BinaryTreeData { return root } + /// Returns the tree's values in in-order (left, node, right) traversal order. public static func inOrderValues(root: BinaryTreeNode?) -> [T] { return inOrder(node: root) } @@ -53,6 +56,7 @@ public enum BinaryTreeData { return values } + /// Returns the tree's values in level-order (breadth-first) traversal order. public static func levelOrderValues(root: BinaryTreeNode?) -> [T] { var result = [T]() @@ -76,6 +80,7 @@ public enum BinaryTreeData { return result } + /// Builds a small, unbalanced binary tree fixture for testing. public static func unbalanced() -> BinaryTreeNode { let c = BinaryTreeNode(value: 3) let d = BinaryTreeNode(value: 4) diff --git a/Sources/swift-ds-algorithms/TestData/Helpers.swift b/Sources/swift-ds-algorithms/TestData/Helpers.swift index 923023a..5466de5 100644 --- a/Sources/swift-ds-algorithms/TestData/Helpers.swift +++ b/Sources/swift-ds-algorithms/TestData/Helpers.swift @@ -8,6 +8,7 @@ import Foundation import GameKit +/// Miscellaneous test helpers. public enum Helpers { public enum HelperError: Error, CustomStringConvertible { case invalidInput(message: String) @@ -20,6 +21,7 @@ public enum Helpers { } } + /// Generates a random string of the given length using letters, digits, and spaces. public static func generateRandomString(ofLength length: Int = 1000000) -> String { let characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890 " let charCount = characters.count diff --git a/Sources/swift-ds-algorithms/TestData/IntegerCounter.swift b/Sources/swift-ds-algorithms/TestData/IntegerCounter.swift index 12dbc18..11decd9 100644 --- a/Sources/swift-ds-algorithms/TestData/IntegerCounter.swift +++ b/Sources/swift-ds-algorithms/TestData/IntegerCounter.swift @@ -5,6 +5,7 @@ // Copyright © 2026. All rights reserved. // +/// Generates a sequence of incrementing integers, useful for assigning unique test values. public class IntegerCounter { private var current: Int @@ -12,6 +13,7 @@ public class IntegerCounter { self.current = start } + /// Returns the current value and increments the counter. public func next() -> Int { defer { current += 1 } return current diff --git a/Sources/swift-ds-algorithms/TestData/SinglyLinkedListData.swift b/Sources/swift-ds-algorithms/TestData/SinglyLinkedListData.swift index bb0c99b..81d0057 100644 --- a/Sources/swift-ds-algorithms/TestData/SinglyLinkedListData.swift +++ b/Sources/swift-ds-algorithms/TestData/SinglyLinkedListData.swift @@ -5,8 +5,10 @@ // Copyright © 2026. All rights reserved. // +/// Test fixtures for building singly linked lists. public enum SinglyLinkedListData { + /// Builds a linked list of the given length with sequential integer values starting at 0. public static func linkedList(ofLength length: Int) -> SinglyLinkedListNode? { guard length >= 0 else { return nil @@ -24,6 +26,7 @@ public enum SinglyLinkedListData { return dummyHead.next } + /// Builds a linked list containing the given array's elements in order. public static func linkedList(from array: [T]) -> SinglyLinkedListNode? { var head: SinglyLinkedListNode? var last: SinglyLinkedListNode? @@ -43,6 +46,7 @@ public enum SinglyLinkedListData { return head } + /// Returns the values of a linked list as an array, in order from head to tail. public static func linkedListToArray(head: SinglyLinkedListNode?) -> [T] { var result: [T] = [] var current = head