Sitemap

Competitive Programming CheatSheet in Swift

7 min readJun 3, 2025

--

covering essential concepts, data structures, and snippets you’ll frequently need in coding contests:

Press enter or click to view image in full size
Leetcode

1. Loops & Ranges swift

// LoopsAndRanges.swift
import Foundation

struct LoopUtils {
// MARK: - Basic Loops

// Loop from 0 to n-1
static func loopZeroToNMinusOne(n: Int, action: (Int) -> Void) {
for i in 0..<n {
action(i)
}
}

// Loop from 1 to n
static func loopOneToN(n: Int, action: (Int) -> Void) {
for i in 1...n {
action(i)
}
}

// Reverse loop from n-1 to 0
static func reverseLoop(n: Int, action: (Int) -> Void) {
for i in stride(from: n - 1, through: 0, by: -1) {
action(i)
}
}

// Loop with custom step
static func loopWithStep(start: Int, end: Int, step: Int, action: (Int) -> Void) {
for i in stride(from: start, through: end, by: step) {
action(i)
}
}

// Nested loop example
static func nestedLoop(rows: Int, cols: Int, action: (Int, Int) -> Void) {
for i in 0..<rows {
for j in 0..<cols {
action(i, j)
}
}
}
}

// Example usage:
// LoopUtils.loopZeroToNMinusOne(n: 5) { print($0) }

2. String & Character Utilities in Swift

// StringUtilities.swift
import Foundation

struct StringUtils {
// MARK: - Vowel Check
static func isVowel(_ c: Character) -> Bool {
return "aeiouAEIOU".contains(c)
}

// MARK: - Case Check
static func isLowercase(_ c: Character) -> Bool {
return c >= "a" && c <= "z"
}

static func isUppercase(_ c: Character) -> Bool {
return c >= "A" && c <= "Z"
}

// MARK: - Digit & Alphanumeric
static func isDigit(_ c: Character) -> Bool {
return c >= "0" && c <= "9"
}

static func isAlphanumeric(_ c: Character) -> Bool {
return c.isLetter || c.isNumber
}

static func isAscii(_ c: Character) -> Bool {
return c.unicodeScalars.allSatisfy { $0.isASCII }
}

// MARK: - Case Conversion
static func toLower(_ c: Character) -> Character {
return Character(String(c).lowercased())
}

static func toUpper(_ c: Character) -> Character {
return Character(String(c).uppercased())
}

// MARK: - String Reversal
static func reverse(_ s: String) -> String {
return String(s.reversed())
}

// MARK: - Palindrome Check
static func isPalindrome(_ s: String) -> Bool {
let filtered = s.lowercased().filter { $0.isLetter || $0.isNumber }
return filtered == filtered.reversed()
}

// MARK: - Clean String
static func cleanString(_ s: String) -> String {
return s.filter { $0.isLetter || $0.isNumber }
}

// MARK: - Frequency Counter
static func charFrequency(_ s: String) -> [Character: Int] {
var freq = [Character: Int]()
for c in s {
freq[c, default: 0] += 1
}
return freq
}
}

// Example usage
// let result = StringUtils.isVowel("e") // true

3. Arrays

// ArrayUtilities.swift
import Foundation

struct ArrayUtils {
// MARK: - Initialize Arrays
static func zeroArray(of size: Int) -> [Int] {
return [Int](repeating: 0, count: size)
}

static func arrayWithValue(_ value: Int, size: Int) -> [Int] {
return [Int](repeating: value, count: size)
}

// MARK: - Sorting
static func sortedAscending(_ array: [Int]) -> [Int] {
return array.sorted()
}

static func sortedDescending(_ array: [Int]) -> [Int] {
return array.sorted(by: >)
}

// MARK: - Reversing
static func reversedArray(_ array: [Int]) -> [Int] {
return array.reversed()
}

// MARK: - Sum
static func sum(_ array: [Int]) -> Int {
return array.reduce(0, +)
}

// MARK: - Max/Min
static func maxElement(_ array: [Int]) -> Int? {
return array.max()
}

static func minElement(_ array: [Int]) -> Int? {
return array.min()
}

// MARK: - array from 1 to n
func createArray(fromOneTo n: Int) -> [Int] {
return Array(1...n)
}

// MARK: - Prefix Sum
static func prefixSum(_ array: [Int]) -> [Int] {
var result = [Int](repeating: 0, count: array.count + 1)
for i in 0..<array.count {
result[i + 1] = result[i] + array[i]
}
return result
}

// MARK: - Frequencies
static func frequencyMap(_ array: [Int]) -> [Int: Int] {
var freq = [Int: Int]()
for num in array {
freq[num, default: 0] += 1
}
return freq
}

// MARK: - In-place Modify
static func incrementAll(_ array: inout [Int]) {
for i in 0..<array.count {
array[i] += 1
}
}
}

// Example usage:
// let arr = ArrayUtils.zeroArray(of: 5) // [0, 0, 0, 0, 0]

4. Bitwise Operator:

// BitwiseUtilities.swift
import Foundation

struct BitwiseUtils {
// MARK: - Basic Bitwise Operations
static func and(_ a: Int, _ b: Int) -> Int {
return a & b
}

static func or(_ a: Int, _ b: Int) -> Int {
return a | b
}

static func xor(_ a: Int, _ b: Int) -> Int {
return a ^ b
}

static func not(_ a: Int) -> Int {
return ~a
}

static func leftShift(_ a: Int, _ by: Int) -> Int {
return a << by
}

static func rightShift(_ a: Int, _ by: Int) -> Int {
return a >> by
}

// MARK: - Bit Checking
static func isBitSet(_ num: Int, _ position: Int) -> Bool {
return (num & (1 << position)) != 0
}

// MARK: - Set/Clear/Toggle Bit
static func setBit(_ num: Int, _ position: Int) -> Int {
return num | (1 << position)
}

static func clearBit(_ num: Int, _ position: Int) -> Int {
return num & ~(1 << position)
}

static func toggleBit(_ num: Int, _ position: Int) -> Int {
return num ^ (1 << position)
}

// MARK: - Count Set Bits
static func countSetBits(_ num: Int) -> Int {
var count = 0
var n = num
while n > 0 {
count += n & 1
n >>= 1
}
return count
}

// MARK: - Check Power of Two
static func isPowerOfTwo(_ num: Int) -> Bool {
return num > 0 && (num & (num - 1)) == 0
}
}

// Example usage:
// let result = BitwiseUtils.isBitSet(5, 0) // true (5 = 101, LSB is 1)

5. Binary Trees:

// TreeUtilities.swift
import Foundation

// MARK: - Tree Node Definition
class TreeNode {
var val: Int
var left: TreeNode?
var right: TreeNode?

init(_ val: Int) {
self.val = val
self.left = nil
self.right = nil
}
}

struct TreeUtils {
// MARK: - Preorder Traversal (Root, Left, Right)
static func preorder(_ root: TreeNode?) -> [Int] {
var result = [Int]()
func dfs(_ node: TreeNode?) {
guard let node = node else { return }
result.append(node.val)
dfs(node.left)
dfs(node.right)
}
dfs(root)
return result
}

// MARK: - Inorder Traversal (Left, Root, Right)
static func inorder(_ root: TreeNode?) -> [Int] {
var result = [Int]()
func dfs(_ node: TreeNode?) {
guard let node = node else { return }
dfs(node.left)
result.append(node.val)
dfs(node.right)
}
dfs(root)
return result
}

// MARK: - Postorder Traversal (Left, Right, Root)
static func postorder(_ root: TreeNode?) -> [Int] {
var result = [Int]()
func dfs(_ node: TreeNode?) {
guard let node = node else { return }
dfs(node.left)
dfs(node.right)
result.append(node.val)
}
dfs(root)
return result
}

// MARK: - Level Order Traversal (BFS)
static func levelOrder(_ root: TreeNode?) -> [[Int]] {
var result = [[Int]]()
guard let root = root else { return result }

var queue = [TreeNode]()
queue.append(root)

while !queue.isEmpty {
var level = [Int]()
for _ in 0..<queue.count {
let node = queue.removeFirst()
level.append(node.val)
if let left = node.left { queue.append(left) }
if let right = node.right { queue.append(right) }
}
result.append(level)
}

return result
}

// MARK: - Tree Height
static func height(_ root: TreeNode?) -> Int {
guard let root = root else { return 0 }
return 1 + max(height(root.left), height(root.right))
}

// MARK: - Count Nodes
static func countNodes(_ root: TreeNode?) -> Int {
guard let root = root else { return 0 }
return 1 + countNodes(root.left) + countNodes(root.right)
}

// MARK: - Check if Balanced
static func isBalanced(_ root: TreeNode?) -> Bool {
func check(_ node: TreeNode?) -> (Bool, Int) {
guard let node = node else { return (true, 0) }
let (leftBalanced, leftHeight) = check(node.left)
let (rightBalanced, rightHeight) = check(node.right)
let balanced = leftBalanced && rightBalanced && abs(leftHeight - rightHeight) <= 1
return (balanced, 1 + max(leftHeight, rightHeight))
}
return check(root).0
}
}

// Example usage:
// let root = TreeNode(1); root.left = TreeNode(2); root.right = TreeNode(3)
// let preorderList = TreeUtils.preorder(root)

6. Graph Traversal:

// GraphTraversalUtilities.swift
import Foundation

struct GraphTraversal {
// MARK: - DFS (Recursive)
static func dfsRecursive(_ node: Int, _ adj: [[Int]], _ visited: inout [Bool], _ result: inout [Int]) {
visited[node] = true
result.append(node)
for neighbor in adj[node] {
if !visited[neighbor] {
dfsRecursive(neighbor, adj, &visited, &result)
}
}
}

// MARK: - DFS (Iterative)
static func dfsIterative(start: Int, adj: [[Int]]) -> [Int] {
var visited = [Bool](repeating: false, count: adj.count)
var stack = [start]
var result = [Int]()

while !stack.isEmpty {
let node = stack.removeLast()
if !visited[node] {
visited[node] = true
result.append(node)
for neighbor in adj[node].reversed() {
if !visited[neighbor] {
stack.append(neighbor)
}
}
}
}
return result
}

// MARK: - BFS
static func bfs(start: Int, adj: [[Int]]) -> [Int] {
var visited = [Bool](repeating: false, count: adj.count)
var queue = [start]
var result = [Int]()
visited[start] = true

while !queue.isEmpty {
let node = queue.removeFirst()
result.append(node)
for neighbor in adj[node] {
if !visited[neighbor] {
visited[neighbor] = true
queue.append(neighbor)
}
}
}
return result
}

// MARK: - Adjacency List Builder
static func buildAdjacencyList(_ edges: [(Int, Int)], _ n: Int) -> [[Int]] {
var adj = [[Int]](repeating: [], count: n)
for (u, v) in edges {
adj[u].append(v)
adj[v].append(u) // remove this line for directed graphs
}
return adj
}
}

// Example usage:
// let adj = GraphTraversal.buildAdjacencyList([(0,1),(1,2),(1,3)], 4)
// let dfsResult = GraphTraversal.dfsIterative(start: 0, adj: adj)
// let bfsResult = GraphTraversal.bfs(start: 0, adj: adj)

Follow me

for more updates.

--

--

Rahul Goel
Rahul Goel

Written by Rahul Goel

EM- SonyLiv | Scaled iOS apps to 100M+ users (Shorts, Streaming, Payments, E-com) | Sharechat, Groupon, Paytm, Myntra https://www.linkedin.com/in/therahulgoel/