├── Easy ├── Single Number.swift ├── Reverse Words in a String.swift ├── Buy Two Chocolates.swift ├── Running Sum of 1d Array.swift ├── Find the Highest Altitude.swift ├── Maximum Product Difference Between Two Pairs.swift ├── Richest Customer Wealth.swift ├── Hamming Distance.swift ├── Shuffle the Array.swift ├── Calculate Money in Leetcode Bank.swift ├── Count Odd Numbers in an Interval Range.swift ├── Contains Duplicate.swift ├── Remove Palindromic Subsequences.swift ├── Two Sum.swift ├── Average Salary Excluding the Minimum and Maximum Salary.swift ├── Minimum Time Visiting All Points.swift ├── Number of Good Pairs.swift ├── Intersection of Two Arrays.swift ├── Power of Two.swift ├── Check If Two String Arrays are Equivalent.swift ├── Number Complement.swift ├── Sort Array By Parity.swift ├── Complement of Base 10 Integer.swift ├── First Bad Version.swift ├── Binary Tree Paths.swift ├── Design HashMap.swift ├── Design HashSet.swift ├── Minimum Common Value.swift ├── Assign Cookies.swift ├── Count Subarrays of Length Three With a Condition.swift ├── Largest Odd Number in String.swift ├── Ugly Number.swift ├── Max Consecutive Ones.swift ├── Convert Binary Number in a Linked List to Integer.swift ├── Contains Duplicate II.swift ├── Count of Matches in Tournament.swift ├── N-th Tribonacci Number.swift ├── Remove Duplicates from Sorted Array.swift ├── Remove Duplicates from Sorted List.swift ├── Matrix Diagonal Sum.swift ├── Monotonic Array.swift ├── Maximum Value of an Ordered Triplet I.swift ├── Sum of All Subset XOR Totals.swift ├── Can Make Arithmetic Progression From Sequence.swift ├── Minimum Cost to Move Chips to The Same Position.swift ├── Number of Steps to Reduce a Number to Zero.swift ├── Binary Search.swift ├── Ransom Note.swift ├── Transpose Matrix.swift ├── First Unique Character in a String.swift ├── Maximum Average Subarray I.swift ├── Consecutive Characters.swift ├── Flip Game.swift ├── Search in a Binary Search Tree.swift ├── Sign of the Product of an Array.swift ├── Largest Positive Integer That Exists With Its Negative.swift ├── Element Appearing More Than 25% In Sorted Array.swift ├── Meeting Rooms.swift ├── Longest Palindrome.swift ├── Binary Tree Tilt.swift ├── Power of Three.swift ├── Reverse Prefix of Word.swift ├── Single-Row Keyboard.swift ├── Set Mismatch.swift ├── Diameter of Binary Tree.swift ├── Unique Number of Occurrences.swift ├── Generate Parentheses.swift ├── Kids With the Greatest Number of Candies.swift ├── Number of Lines To Write String.swift ├── Maximum Product of Two Elements in an Array.swift ├── Count Elements With Maximum Frequency.swift ├── Add Digits.swift ├── Final Array State After K Multiplication Operations I.swift ├── Sum of Left Leaves.swift ├── Largest 3-Same-Digit Number in String.swift ├── Arranging Coins.swift ├── Redistribute Characters to Make All Strings Equal.swift ├── Reverse Bits.swift ├── Longest Subsequence With Limited Sum.swift ├── Palindrome Permutation.swift ├── Relative Sort Array.swift ├── Sort Integers by The Number of 1 Bits.swift ├── Palindrome Number.swift ├── Closest Binary Search Tree Value.swift ├── Excel Sheet Column Number.swift ├── Find Anagram Mappings.swift ├── Find Smallest Letter Greater Than Target.swift ├── Maximum Odd Binary Number.swift ├── Make The String Great.swift ├── Find the Difference of Two Arrays.swift ├── Find Words That Can Be Formed by Characters.swift ├── Largest Local Values in a Matrix.swift ├── Kth Largest Element in a Stream.swift ├── Find First Palindromic String in the Array.swift ├── Reverse Linked List.swift ├── Reverse Linked List II.swift ├── Check if the Sentence Is Pangram.swift ├── Number of 1 Bits.swift ├── Destination City.swift ├── Read N Characters Given Read4.swift ├── Island Perimeter.swift ├── Maximum Score After Splitting a String.swift ├── Merge Strings Alternately.swift ├── Min Stack.swift ├── Maximum 69 Number.swift ├── Next Greater Element I.swift ├── Average of Levels in Binary Tree.swift ├── Baseball Game.swift ├── Isomorphic Strings.swift ├── Relative Ranks.swift ├── Shift 2D Grid.swift ├── Special Positions in a Binary Matrix.swift ├── Last Stone Weight.swift ├── Path Crossing.swift ├── Guess Number Higher or Lower.swift ├── Maximum Subarray.swift ├── Find the Pivot Integer.swift ├── Image Smoother.swift ├── Check If It Is a Straight Line.swift ├── Middle of the Linked List.swift ├── Reverse Words in a String III.swift ├── Check If a Word Occurs As a Prefix of Any Word in a Sentence.swift ├── Minimum Changes To Make Alternating Binary String.swift ├── Linked List Cycle.swift ├── Unique Email Addresses.swift ├── Minimum Number of Operations to Make Elements in Array Distinct.swift ├── Reverse String.swift ├── Find All Numbers Disappeared in an Array.swift ├── Search Insert Position.swift └── Range Sum Query - Immutable.swift ├── README.md ├── Medium ├── Rectangle Area.swift ├── Largest Number.swift ├── Single Number II.swift ├── Greatest Sum Divisible by Three.swift ├── Partitioning Into Minimum Number Of Deci-Binary Numbers.swift ├── Best Time to Buy and Sell Stock II.swift ├── Determine if a Cell Is Reachable at a Given Time.swift ├── Last Moment Before All Ants Fall Out of a Plank.swift ├── Peak Index in a Mountain Array.swift ├── Perfect Squares.swift ├── Delete Leaves With a Given Value.swift ├── Minimum Moves to Equal Array Elements II.swift ├── Longest Arithmetic Subsequence of Given Difference.swift ├── Minimum Number of Operations to Make Array XOR Equal to K.swift ├── Optimal Partition of String.swift ├── Subarray Sums Divisible by K.swift ├── Binary Subarrays With Sum.swift ├── Broken Calculator.swift ├── Buildings With an Ocean View.swift ├── Linked List Random Node.swift ├── Maximum Ice Cream Bars.swift ├── Number of Subarrays with Bounded Maximum.swift ├── Widest Vertical Area Between Two Points Containing No Points.swift ├── Removing Stars From a String.swift ├── Maximum Element After Decreasing and Rearranging.swift ├── Maximum Size of a Set After Removals.swift ├── Minimize Maximum Pair Sum in Array.swift ├── Online Stock Span.swift ├── Swap Nodes in Pairs.swift ├── Longest Arithmetic Subsequence.swift ├── Maximize Happiness of Selected Children.swift ├── Minimum Number of Operations to Make Array Empty.swift ├── Reduction Operations to Make the Array Elements Equal.swift ├── Distribute Coins in Binary Tree.swift ├── Increasing Triplet Subsequence.swift ├── Adding Spaces to a String.swift ├── Max Number of K-Sum Pairs.swift ├── Find Champion II.swift ├── Arithmetic Slices.swift ├── Count Number of Homogenous Substrings.swift ├── Find Polygon With the Largest Perimeter.swift ├── Find The Original Array of Prefix Xor.swift ├── Sum of Absolute Differences in a Sorted Array.swift ├── Two City Scheduling.swift ├── Trim a Binary Search Tree.swift ├── Encode and Decode TinyURL.swift ├── Array of Doubled Pairs.swift ├── Contiguous Array.swift ├── Frequency of the Most Frequent Element.swift ├── Random Pick Index.swift ├── Unique Paths.swift ├── Maximum Number of Integers to Choose From a Range I.swift ├── Minimum Number of Steps to Make Two Strings Anagram.swift ├── Minimum Operations to Make Array Equal.swift ├── Partition Array for Maximum Sum.swift ├── Sort Colors.swift ├── Convert an Array Into a 2D Array With Conditions.swift ├── Verify Preorder Sequence in Binary Search Tree.swift ├── Continuous Subarray Sum.swift ├── Minimum Number of Vertices to Reach All Nodes.swift ├── Maximum Size Subarray Sum Equals k.swift ├── Group the People Given the Group Size They Belong To.swift ├── Linked List Cycle II.swift ├── Beautiful Arrangement II.swift ├── Sum of Two Integers.swift ├── K-th Symbol in Grammar.swift ├── Check Completeness of a Binary Tree.swift ├── Minimum Time to Complete Trips.swift ├── Gray Code.swift ├── Reordered Power of 2.swift ├── Rotate List.swift ├── Stone Game.swift ├── Longest Valid Parentheses.swift ├── Minimum Index of a Valid Split.swift ├── Minimum Length of String After Deleting Similar Ends.swift ├── Longest Substring Without Repeating Characters.swift ├── Maximum Value of an Ordered Triplet II.swift ├── Minimum Penalty for a Shop.swift ├── Minimum Rounds to Complete All Tasks.swift ├── Single Element in a Sorted Array.swift ├── Solving Questions With Brainpower.swift ├── Least Number of Unique Integers after K Removals.swift ├── K Radius Subarray Averages.swift ├── Maximum Product of Word Lengths.swift ├── Rotate Image.swift ├── Kill Process.swift ├── Remove Nodes From Linked List.swift ├── Remove Zero Sum Consecutive Nodes from Linked List.swift ├── Insertion Sort List.swift ├── Merge In Between Linked Lists.swift ├── Queue Reconstruction by Height.swift ├── Robot Bounded In Circle.swift ├── Diagonal Traverse II.swift ├── Paint Fence.swift ├── Shuffle an Array.swift ├── Combination Sum.swift ├── Remove Colored Pieces if Both Neighbors are the Same Color.swift ├── Arithmetic Subarrays.swift ├── Count Nice Pairs in an Array.swift ├── Binary Tree Right Side View.swift ├── Next Permutation.swift ├── Maximum Number of Coins You Can Get.swift ├── ZigZag Conversion.swift ├── Special Array II.swift ├── Count and Say.swift ├── Find Unique Binary String.swift ├── Max Consecutive Ones II.swift ├── N-ary Tree Preorder Traversal.swift ├── Top K Frequent Words.swift ├── Find the Index of the First Occurrence in a String.swift ├── Stone Game VII.swift ├── Uncrossed Lines.swift ├── Find Duplicate Subtrees.swift ├── Successful Pairs of Spells and Potions.swift ├── Binary Tree Level Order Traversal II.swift ├── Count Primes.swift ├── Minimum Flips to Make a OR b Equal to c.swift ├── Complex Number Multiplication.swift ├── Minimum Domino Rotations For Equal Row.swift ├── Minimum Path Sum.swift ├── Flip Binary Tree To Match Preorder Traversal.swift ├── Redundant Connection.swift ├── Remove Stones to Minimize the Total.swift ├── Single Number III.swift ├── Maximum Average Subtree.swift ├── Partition Array into Disjoint Intervals.swift ├── String Compression.swift ├── Path Sum II.swift ├── Swapping Nodes in a Linked List.swift ├── Construct Binary Search Tree from Preorder Traversal.swift ├── Minimum Limit of Balls in a Bag.swift ├── Remove K Digits.swift ├── Bitwise AND of Numbers Range.swift ├── Delete Node in a BST.swift ├── Find Largest Value in Each Tree Row.swift ├── Equal Tree Partition.swift ├── Path Sum III.swift ├── The Number of Weak Characters in the Game.swift ├── Binary Trees With Factors.swift ├── Rotate Array.swift ├── Wiggle Sort.swift ├── Number of Laser Beams in a Bank.swift ├── Bag of Tokens.swift ├── Intersection of Two Linked Lists.swift ├── Container With Most Water.swift ├── Maximum Bags With Full Capacity of Rocks.swift ├── Find the Duplicate Number.swift ├── Non-decreasing Subsequences.swift ├── Copy List with Random Pointer.swift ├── Delete Node in a Linked List.swift ├── Find Players With Zero or One Losses.swift ├── Keys and Rooms.swift ├── Boats to Save People.swift ├── Number of Zero-Filled Subarrays.swift ├── Beautiful Array.swift ├── Fruit Into Baskets.swift ├── Remove Duplicate Letters.swift ├── Find All Duplicates in an Array.swift ├── Generalized Abbreviation.swift ├── Minimum Moves to Capture The Queen.swift ├── Split Array into Consecutive Subsequences.swift ├── Count Nodes Equal to Average of Subtree.swift ├── Shortest Word Distance III.swift ├── Split Linked List in Parts.swift ├── Maximum Score from Performing Multiplication Operations.swift ├── Permutation in String.swift ├── Check if There is a Valid Partition For The Array.swift ├── Clone N-ary Tree.swift ├── Minimum Speed to Arrive on Time.swift ├── Score of Parentheses.swift └── Maximum Level Sum of a Binary Tree.swift ├── Hard ├── Maximum Gap.swift ├── Best Time to Buy and Sell Stock III.swift ├── Orderly Queue.swift ├── Stone Game IV.swift ├── Count Subarrays With Fixed Bounds.swift ├── Maximum Frequency Stack.swift ├── Reconstruct Itinerary.swift ├── Create Sorted Array through Instructions.swift ├── Find the Kth Smallest Sum of a Matrix With Sorted Rows.swift ├── Longest Happy Prefix.swift ├── Read N Characters Given Read4 II - Call multiple times.swift ├── Data Stream as Disjoint Intervals.swift └── Shortest Subarray with Sum at Least K.swift └── misc └── stack.swift /Easy/Single Number.swift: -------------------------------------------------------------------------------- 1 | //Single Number 2 | //O(n), O(1) 3 | func singleNumber(_ nums: [Int]) -> Int { 4 | var res = 0 5 | for n in nums { 6 | res ^= n 7 | } 8 | return res 9 | } -------------------------------------------------------------------------------- /Easy/Reverse Words in a String.swift: -------------------------------------------------------------------------------- 1 | //Reverse Words in a String 2 | //O(n), O(n) 3 | func reverseWords(_ s: String) -> String { 4 | let list = s.split(separator: " ") 5 | return list.reversed().joined(separator: " ") 6 | } -------------------------------------------------------------------------------- /Easy/Buy Two Chocolates.swift: -------------------------------------------------------------------------------- 1 | // Buy Two Chocolates 2 | // O(n log n), O(n) 3 | func buyChoco(_ prices: [Int], _ money: Int) -> Int { 4 | let arr = prices.sorted() 5 | let p = arr[0] + arr[1] 6 | if p > money {return money} 7 | return money - p 8 | } -------------------------------------------------------------------------------- /Easy/Running Sum of 1d Array.swift: -------------------------------------------------------------------------------- 1 | //Running Sum of 1d Array 2 | //O(n) O(n) 3 | func runningSum(_ nums: [Int]) -> [Int] { 4 | var nums = nums 5 | for i in 1.. Int { 4 | var res = 0, curr = 0 5 | for n in gain { 6 | curr += n 7 | res = max(res, curr) 8 | } 9 | return res 10 | } -------------------------------------------------------------------------------- /Easy/Maximum Product Difference Between Two Pairs.swift: -------------------------------------------------------------------------------- 1 | // Maximum Product Difference Between Two Pairs 2 | // O(n log n), O(n) 3 | func maxProductDifference(_ nums: [Int]) -> Int { 4 | let arr = nums.sorted() 5 | let n = arr.endIndex 6 | return arr[n-1]*arr[n-2]-arr[0]*arr[1] 7 | } -------------------------------------------------------------------------------- /Easy/Richest Customer Wealth.swift: -------------------------------------------------------------------------------- 1 | //Richest Customer Wealth 2 | //O(n), O(1) 3 | func maximumWealth(_ accounts: [[Int]]) -> Int { 4 | var res = 0 5 | for account in accounts { 6 | res = max(res, account.reduce(0,+)) 7 | } 8 | return res 9 | } -------------------------------------------------------------------------------- /Easy/Hamming Distance.swift: -------------------------------------------------------------------------------- 1 | //Hamming Distance 2 | //O(n), O(1) 3 | func hammingDistance(_ x: Int, _ y: Int) -> Int { 4 | var n = x ^ y 5 | var res = 0 6 | while n > 0 { 7 | res += n & 1 8 | n >>= 1 9 | } 10 | return res 11 | } -------------------------------------------------------------------------------- /Easy/Shuffle the Array.swift: -------------------------------------------------------------------------------- 1 | //Shuffle the Array 2 | //O(n), O(n) 3 | func shuffle(_ nums: [Int], _ n: Int) -> [Int] { 4 | var res = [Int]() 5 | for i in 0.. Int { 4 | let lastDays = n % 7 5 | let weeks = n / 7 6 | 7 | let res = 28 * weeks + (0+(weeks-1)*7)*weeks/2 + (1+weeks+lastDays+weeks) * lastDays / 2 8 | return res 9 | } -------------------------------------------------------------------------------- /Easy/Count Odd Numbers in an Interval Range.swift: -------------------------------------------------------------------------------- 1 | //Count Odd Numbers in an Interval Range 2 | //O(1), O(1) 3 | func countOdds(_ low: Int, _ high: Int) -> Int { 4 | var low = low 5 | if low % 2 == 0 { 6 | low += 1 7 | } 8 | return low > high ? 0 : (high-low)/2+1 9 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Leetcode Swift 2 | ### This repository contains various solutions for LeetCode questions in Swift, with Big O notation representing time complexity and space complexity. 3 | 4 | If you like Python, you can also check out the 5 | [LeetCodePython repository](https://github.com/zip520123/leetcodePython) 6 | 7 | 8 | -------------------------------------------------------------------------------- /Easy/Contains Duplicate.swift: -------------------------------------------------------------------------------- 1 | /*Contains Duplicate*/ 2 | //time O(n) space O(n) 3 | func containsDuplicate(_ nums: [Int]) -> Bool { 4 | var set = Set() 5 | for n in nums { 6 | if set.contains(n) { 7 | return true 8 | } 9 | set.insert(n) 10 | } 11 | return false 12 | } -------------------------------------------------------------------------------- /Medium/Rectangle Area.swift: -------------------------------------------------------------------------------- 1 | //Rectangle Area 2 | //O(1) 3 | func computeArea(_ ax1: Int, _ ay1: Int, _ ax2: Int, _ ay2: Int, _ bx1: Int, _ by1: Int, _ bx2: Int, _ by2: Int) -> Int { 4 | return (ax2-ax1)*(ay2-ay1) + (bx2-bx1)*(by2-by1) - max(min(ax2,bx2)-max(ax1,bx1), 0) * max(min(ay2,by2)-max(ay1,by1), 0) 5 | } -------------------------------------------------------------------------------- /Easy/Remove Palindromic Subsequences.swift: -------------------------------------------------------------------------------- 1 | //Remove Palindromic Subsequences 2 | //O(n), O(n) 3 | func removePalindromeSub(_ s: String) -> Int { 4 | if s.count == 0 {return 0} 5 | let arr = Array(s) 6 | if arr == Array(arr.reversed()) { 7 | return 1 8 | } 9 | return 2 10 | } -------------------------------------------------------------------------------- /Easy/Two Sum.swift: -------------------------------------------------------------------------------- 1 | /*Two Sum*/ 2 | func twoSum(_ nums: [Int], _ target: Int) -> [Int] { 3 | var dict = [Int: Int]() 4 | for (i,n) in nums.enumerated() { 5 | let r = target - n 6 | if dict[r] != nil { 7 | return [dict[r]! , i] 8 | } 9 | dict[n] = i 10 | } 11 | 12 | return [] 13 | } -------------------------------------------------------------------------------- /Hard/Maximum Gap.swift: -------------------------------------------------------------------------------- 1 | //Maximum Gap 2 | //O(n log n), O(n) 3 | func maximumGap(_ nums: [Int]) -> Int { 4 | if nums.endIndex < 2 {return 0} 5 | let nums = nums.sorted() 6 | var res = 0 7 | for i in 0.. String { 4 | let nums = nums.sorted { 5 | a, b in 6 | String(a) + String(b) > String(b) + String(a) 7 | } 8 | if nums[0] == 0 {return "0"} 9 | return nums.map{String($0)}.joined() 10 | } -------------------------------------------------------------------------------- /Medium/Single Number II.swift: -------------------------------------------------------------------------------- 1 | // Single Number II 2 | // O(n), O(n) 3 | func singleNumber(_ nums: [Int]) -> Int { 4 | var dict = [Int: Int]() 5 | for n in nums { 6 | dict[n, default: 0] += 1 7 | } 8 | for (key, val) in dict { 9 | if val == 1 { 10 | return key 11 | } 12 | } 13 | return 0 14 | } -------------------------------------------------------------------------------- /Medium/Greatest Sum Divisible by Three.swift: -------------------------------------------------------------------------------- 1 | //Greatest Sum Divisible by Three 2 | //O(n),O(1) 3 | func maxSumDivThree(_ nums: [Int]) -> Int { 4 | var dp = [0,0,0] 5 | for n in nums { 6 | for i in dp { 7 | dp[(i+n) % 3] = max(dp[(i+n)%3], i+n) 8 | } 9 | } 10 | return dp[0] 11 | } -------------------------------------------------------------------------------- /Easy/Average Salary Excluding the Minimum and Maximum Salary.swift: -------------------------------------------------------------------------------- 1 | //Average Salary Excluding the Minimum and Maximum Salary 2 | //O(n log n), O(n) 3 | func average(_ salary: [Int]) -> Double { 4 | var arr = salary.sorted() 5 | arr.removeFirst() 6 | arr.removeLast() 7 | return Double(arr.reduce(0, +)) / Double(arr.endIndex) 8 | } -------------------------------------------------------------------------------- /Easy/Minimum Time Visiting All Points.swift: -------------------------------------------------------------------------------- 1 | // Minimum Time Visiting All Points 2 | // O(n), O(1) 3 | func minTimeToVisitAllPoints(_ points: [[Int]]) -> Int { 4 | var res = 0 5 | for i in 1.. Int { 4 | var res = 0 5 | for i in 0.. Int { 4 | var res = 0 5 | for char in n { 6 | let curr = Int(String(char))! 7 | res = max(res, curr) 8 | } 9 | return res 10 | } -------------------------------------------------------------------------------- /Easy/Intersection of Two Arrays.swift: -------------------------------------------------------------------------------- 1 | // Intersection of Two Arrays 2 | // O(n), O(n) 3 | func intersection(_ nums1: [Int], _ nums2: [Int]) -> [Int] { 4 | var set1 = Set(nums1) 5 | var set2 = Set(nums2) 6 | var res = [Int]() 7 | for n in set2 { 8 | if set1.contains(n) { 9 | res.append(n) 10 | } 11 | } 12 | return res 13 | } -------------------------------------------------------------------------------- /Easy/Power of Two.swift: -------------------------------------------------------------------------------- 1 | //Power of Two 2 | //O(1) 3 | func isPowerOfTwo(_ n: Int) -> Bool { 4 | n > 0 && ((n & (n-1)) == 0) 5 | } 6 | 7 | //O(n) 8 | func isPowerOfTwo(_ n: Int) -> Bool { 9 | if n <= 0 {return false} 10 | var n = n 11 | while n % 2 == 0 { 12 | n /= 2 13 | } 14 | return n == 1 15 | } -------------------------------------------------------------------------------- /Easy/Check If Two String Arrays are Equivalent.swift: -------------------------------------------------------------------------------- 1 | //Check If Two String Arrays are Equivalent 2 | //O(n), O(n) 3 | func arrayStringsAreEqual(_ word1: [String], _ word2: [String]) -> Bool { 4 | return word1.reduce("",+) == word2.reduce("",+) 5 | } 6 | 7 | func arrayStringsAreEqual(_ word1: [String], _ word2: [String]) -> Bool { 8 | word1.joined() == word2.joined() 9 | } -------------------------------------------------------------------------------- /Easy/Number Complement.swift: -------------------------------------------------------------------------------- 1 | //Number Complement O(n) 2 | //the same as Completent of Base 10 interger without `0` test case 3 | func findComplement(_ num: Int) -> Int { 4 | var res = 0 5 | var mask = 1 6 | while mask < num { 7 | res += mask&num == 0 ? mask : 0 8 | mask *= 2 9 | } 10 | return res 11 | } 12 | -------------------------------------------------------------------------------- /Medium/Best Time to Buy and Sell Stock II.swift: -------------------------------------------------------------------------------- 1 | //Best Time to Buy and Sell Stock II 2 | //O(n), O(1) 3 | func maxProfit(_ prices: [Int]) -> Int { 4 | var res = 0 5 | for i in 1.. 0 { 7 | res += prices[i] - prices[i-1] 8 | } 9 | } 10 | return res 11 | } -------------------------------------------------------------------------------- /Medium/Determine if a Cell Is Reachable at a Given Time.swift: -------------------------------------------------------------------------------- 1 | // Determine if a Cell Is Reachable at a Given Time 2 | // O(1), O(1) math 3 | func isReachableAtTime(_ sx: Int, _ sy: Int, _ fx: Int, _ fy: Int, _ t: Int) -> Bool { 4 | let width = abs(sx-fx) 5 | let heigh = abs(sy-fy) 6 | if width == 0 && heigh == 0 && t == 1 {return false} 7 | return t >= max(width, heigh) 8 | } -------------------------------------------------------------------------------- /Easy/Sort Array By Parity.swift: -------------------------------------------------------------------------------- 1 | //Sort Array By Parity 2 | //O(n), O(n) 3 | func sortArrayByParity(_ nums: [Int]) -> [Int] { 4 | var res = [Int]() 5 | for n in nums { 6 | if n % 2 == 1 { 7 | res.append(n) 8 | } else { 9 | res.insert(n, at: 0) 10 | } 11 | } 12 | return res 13 | } -------------------------------------------------------------------------------- /Medium/Last Moment Before All Ants Fall Out of a Plank.swift: -------------------------------------------------------------------------------- 1 | // Last Moment Before All Ants Fall Out of a Plank 2 | // O(n), O(1) 3 | func getLastMoment(_ n: Int, _ left: [Int], _ right: [Int]) -> Int { 4 | var res = 0 5 | for num in left { 6 | res = max(res, num) 7 | } 8 | for num in right { 9 | res = max(res, n-num) 10 | } 11 | return res 12 | } -------------------------------------------------------------------------------- /Easy/Complement of Base 10 Integer.swift: -------------------------------------------------------------------------------- 1 | //Complement of Base 10 Integer 2 | //O(n),O(1) 3 | func bitwiseComplement(_ n: Int) -> Int { 4 | if n == 0 {return 1} 5 | var mask = 1, res = 0 6 | while mask < n { 7 | let curr = n & mask == 0 ? 1 : 0 8 | res += mask * curr 9 | mask *= 2 10 | } 11 | return res 12 | } -------------------------------------------------------------------------------- /Easy/First Bad Version.swift: -------------------------------------------------------------------------------- 1 | /*First Bad Version*/ 2 | //O(log n) space O(1) 3 | func firstBadVersion(_ n: Int) -> Int { 4 | 5 | var l = 1, r = n 6 | while l < r { 7 | let mid = (l + r) >> 1 8 | if isBadVersion(mid) == false { 9 | l = mid + 1 10 | } else { 11 | r = mid 12 | } 13 | 14 | } 15 | return l 16 | } -------------------------------------------------------------------------------- /Easy/Binary Tree Paths.swift: -------------------------------------------------------------------------------- 1 | //Binary Tree Paths 2 | func binaryTreePaths(_ root: TreeNode?) -> [String] { 3 | guard let node = root else {return []} 4 | let left = binaryTreePaths(node.left) 5 | let right = binaryTreePaths(node.right) 6 | if left.isEmpty && right.isEmpty {return ["\(node.val)"]} 7 | return (left + right).map { "\(node.val)->\($0)" } 8 | } -------------------------------------------------------------------------------- /Easy/Design HashMap.swift: -------------------------------------------------------------------------------- 1 | //Design HashMap 2 | //O(1),O(1) 3 | class MyHashMap { 4 | var arr = (0...Int(1E6)).map {_ in -1} 5 | 6 | func put(_ key: Int, _ value: Int) { 7 | arr[key] = value 8 | } 9 | 10 | func get(_ key: Int) -> Int { 11 | arr[key] 12 | } 13 | 14 | func remove(_ key: Int) { 15 | arr[key] = -1 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /Easy/Design HashSet.swift: -------------------------------------------------------------------------------- 1 | //Design HashSet 2 | //O(1),O(n) 3 | class MyHashSet { 4 | var arr = [Bool](repeating: false, count: 1000001) 5 | 6 | func add(_ key: Int) { 7 | arr[key] = true 8 | } 9 | 10 | func remove(_ key: Int) { 11 | arr[key] = false 12 | } 13 | 14 | func contains(_ key: Int) -> Bool { 15 | arr[key] 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /Easy/Minimum Common Value.swift: -------------------------------------------------------------------------------- 1 | // Minimum Common Value 2 | // O(n), O(n) 3 | func getCommon(_ nums1: [Int], _ nums2: [Int]) -> Int { 4 | var set = Set(nums1) 5 | var res = Int.max 6 | for n in nums2 { 7 | if set.contains(n), n < res { 8 | res = n 9 | } 10 | } 11 | if res == Int.max { 12 | return -1 13 | } 14 | return res 15 | } -------------------------------------------------------------------------------- /Easy/Assign Cookies.swift: -------------------------------------------------------------------------------- 1 | // Assign Cookies 2 | // O(n log n), O(g+s) 3 | func findContentChildren(_ g: [Int], _ s: [Int]) -> Int { 4 | let g = g.sorted(), s = s.sorted() 5 | var i = 0, j = 0, res = 0 6 | while i Int { 4 | var l = 0, r = arr.endIndex-1 5 | while l>1) 7 | if arr[mid] < arr[mid+1] { 8 | l = mid+1 9 | } else { 10 | r = mid 11 | } 12 | } 13 | return l 14 | } -------------------------------------------------------------------------------- /Medium/Perfect Squares.swift: -------------------------------------------------------------------------------- 1 | //Perfect Squares 2 | //O(n log n), O(n) 3 | func numSquares(_ n: Int) -> Int { 4 | var dp = [0] 5 | for i in 1...n { 6 | dp.append(i) 7 | var j = 2 8 | while j*j <= i { 9 | dp[i] = min(dp[i], dp[i-j*j] + 1) 10 | j+=1 11 | } 12 | } 13 | return dp[n] 14 | } -------------------------------------------------------------------------------- /Easy/Count Subarrays of Length Three With a Condition.swift: -------------------------------------------------------------------------------- 1 | // Count Subarrays of Length Three With a Condition 2 | // O(n), O(1) 3 | func countSubarrays(_ nums: [Int]) -> Int { 4 | var res = 0 5 | for i in 0..<(nums.endIndex - 2) { 6 | let a = nums[i], b = nums[i+1], c = nums[i+2] 7 | if (a+c) * 2 == b { 8 | res += 1 9 | } 10 | } 11 | return res 12 | } -------------------------------------------------------------------------------- /Easy/Largest Odd Number in String.swift: -------------------------------------------------------------------------------- 1 | // Largest Odd Number in String 2 | // O(n), O(1) 3 | func largestOddNumber(_ num: String) -> String { 4 | var res = "" 5 | let arr = Array(num) 6 | for i in (0.. Bool { 4 | if n == 0 {return false} 5 | var n = n 6 | for p in [2,3,5] { 7 | var curr = 1 8 | while n % (curr * p) == 0 { 9 | curr *= p 10 | } 11 | 12 | n /= curr 13 | } 14 | return n == 1 15 | } -------------------------------------------------------------------------------- /Easy/Max Consecutive Ones.swift: -------------------------------------------------------------------------------- 1 | //Max Consecutive Ones 2 | //O(n), O(1) 3 | func findMaxConsecutiveOnes(_ nums: [Int]) -> Int { 4 | var res = 0 5 | var l = 0, r = 0 6 | while r < nums.endIndex { 7 | if nums[r] == 0 { 8 | l = r+1 9 | } 10 | res = max(r-l+1,res) 11 | r += 1 12 | } 13 | return res 14 | } -------------------------------------------------------------------------------- /Easy/Convert Binary Number in a Linked List to Integer.swift: -------------------------------------------------------------------------------- 1 | //Convert Binary Number in a Linked List to Integer 2 | //O(n), O(1) 3 | func getDecimalValue(_ head: ListNode?) -> Int { 4 | var res = 0 5 | var curr = head 6 | while curr != nil { 7 | res = res << 1 8 | res += curr!.val 9 | curr = curr!.next 10 | } 11 | return res 12 | } -------------------------------------------------------------------------------- /Easy/Contains Duplicate II.swift: -------------------------------------------------------------------------------- 1 | //Contains Duplicate II 2 | //O(n), O(n) 3 | func containsNearbyDuplicate(_ nums: [Int], _ k: Int) -> Bool { 4 | var dict = [Int: Int]() 5 | for (index, n) in nums.enumerated() { 6 | if let i = dict[n] { 7 | if abs(i-index) <= k {return true} 8 | } 9 | dict[n] = index 10 | } 11 | return false 12 | } -------------------------------------------------------------------------------- /Easy/Count of Matches in Tournament.swift: -------------------------------------------------------------------------------- 1 | // Count of Matches in Tournament 2 | // O(log n), O(1) 3 | func numberOfMatches(_ n: Int) -> Int { 4 | var matches = 0, teams = n 5 | while teams > 1 { 6 | var nextTeams = teams / 2 7 | matches += teams / 2 8 | if teams % 2 == 1 { 9 | nextTeams += 1 10 | } 11 | teams = nextTeams 12 | } 13 | return matches 14 | } -------------------------------------------------------------------------------- /Easy/N-th Tribonacci Number.swift: -------------------------------------------------------------------------------- 1 | //N-th Tribonacci Number 2 | //O(n), O(1) 3 | func tribonacci(_ n: Int) -> Int { 4 | if n == 0 {return 0} 5 | if n == 1 {return 1} 6 | if n == 2 {return 1} 7 | var a = 0, b = 1, c = 1 8 | for i in 2.. TreeNode? { 4 | if root == nil { return nil } 5 | root!.left = removeLeafNodes(root!.left, target) 6 | root!.right = removeLeafNodes(root!.right, target) 7 | if root!.left == nil, root!.right == nil, root!.val == target { return nil } 8 | return root 9 | } -------------------------------------------------------------------------------- /Easy/Remove Duplicates from Sorted Array.swift: -------------------------------------------------------------------------------- 1 | //Remove Duplicates from Sorted Array 2 | //O(n), O(1) 3 | func removeDuplicates(_ nums: inout [Int]) -> Int { 4 | var l = 0, r = 0 5 | while r < nums.endIndex { 6 | if nums[l] != nums[r] { 7 | l += 1 8 | nums[l] = nums[r] 9 | } 10 | r += 1 11 | } 12 | 13 | return l+1 14 | } -------------------------------------------------------------------------------- /Easy/Remove Duplicates from Sorted List.swift: -------------------------------------------------------------------------------- 1 | //Remove Duplicates from Sorted List 2 | func deleteDuplicates(_ head: ListNode?) -> ListNode? { 3 | var curr = head 4 | while curr != nil { 5 | while curr!.next != nil && curr!.next!.val == curr!.val{ 6 | curr!.next = curr!.next!.next 7 | } 8 | curr = curr!.next 9 | } 10 | return head 11 | } -------------------------------------------------------------------------------- /Medium/Minimum Moves to Equal Array Elements II.swift: -------------------------------------------------------------------------------- 1 | //Minimum Moves to Equal Array Elements II 2 | //O(n log n), O(1) 3 | func minMoves2(_ nums: [Int]) -> Int { 4 | var res = 0 5 | let arr = nums.sorted() 6 | var l = 0, r = nums.endIndex - 1 7 | while l Int { 4 | var res = 0 5 | var i = 0 6 | let n = mat.endIndex-1 7 | while i Bool { 4 | var increasing = true 5 | for i in 0..= nums[i+1] 11 | } 12 | return increasing || decreasing 13 | } -------------------------------------------------------------------------------- /Medium/Longest Arithmetic Subsequence of Given Difference.swift: -------------------------------------------------------------------------------- 1 | // Longest Arithmetic Subsequence of Given Difference 2 | //O(n), O(n) 3 | func longestSubsequence(_ arr: [Int], _ difference: Int) -> Int { 4 | var dp = [Int: Int]() 5 | var res = 0 6 | for n in arr { 7 | dp[n] = dp[n-difference, default: 0] + 1 8 | res = max(res, dp[n]!) 9 | } 10 | return res 11 | } -------------------------------------------------------------------------------- /Medium/Minimum Number of Operations to Make Array XOR Equal to K.swift: -------------------------------------------------------------------------------- 1 | // Minimum Number of Operations to Make Array XOR Equal to K 2 | // O(n), O(1) 3 | func minOperations(_ nums: [Int], _ k: Int) -> Int { 4 | var curr = 0 5 | for n in nums { 6 | curr ^= n 7 | } 8 | curr ^= k 9 | var res = 0 10 | while curr > 0 { 11 | res += curr & 1 12 | curr >>= 1 13 | } 14 | return res 15 | } -------------------------------------------------------------------------------- /Medium/Optimal Partition of String.swift: -------------------------------------------------------------------------------- 1 | //Optimal Partition of String 2 | //O(n), O(n) 3 | func partitionString(_ s: String) -> Int { 4 | var set = Set() 5 | var res = 1 6 | for char in s { 7 | if set.contains(char) { 8 | res += 1 9 | set.removeAll() 10 | } 11 | set.insert(char) 12 | } 13 | return res 14 | } -------------------------------------------------------------------------------- /Medium/Subarray Sums Divisible by K.swift: -------------------------------------------------------------------------------- 1 | //Subarray Sums Divisible by K 2 | //O(n+k), O(k) 3 | func subarraysDivByK(_ nums: [Int], _ k: Int) -> Int { 4 | var preMod = 0, res = 0 5 | var dict = [0:1] 6 | for n in nums { 7 | preMod = (preMod+n % k + k) % k 8 | res += dict[preMod, default:0] 9 | dict[preMod, default:0] += 1 10 | } 11 | return res 12 | } -------------------------------------------------------------------------------- /Easy/Maximum Value of an Ordered Triplet I.swift: -------------------------------------------------------------------------------- 1 | // Maximum Value of an Ordered Triplet I 2 | // O(n^3), O(1) 3 | func maximumTripletValue(_ nums: [Int]) -> Int { 4 | var res = 0 5 | let n = nums.endIndex 6 | for i in 0.. Int { 4 | var res = 0 5 | func dfs(_ path: Int, _ index: Int) { 6 | if index == nums.endIndex { 7 | res += path 8 | return 9 | } 10 | dfs(path ^ nums[index], index+1) 11 | dfs(path, index+1) 12 | } 13 | dfs(0,0) 14 | return res 15 | } -------------------------------------------------------------------------------- /Medium/Binary Subarrays With Sum.swift: -------------------------------------------------------------------------------- 1 | // Binary Subarrays With Sum 2 | // O(n), O(n) 3 | func numSubarraysWithSum(_ nums: [Int], _ goal: Int) -> Int { 4 | var memo = [Int: Int]() 5 | memo[0] = 1 6 | var res = 0 7 | var prefixSum = 0 8 | for n in nums { 9 | prefixSum += n 10 | res += memo[prefixSum - goal, default: 0] 11 | memo[prefixSum, default: 0] += 1 12 | } 13 | return res 14 | } -------------------------------------------------------------------------------- /Medium/Broken Calculator.swift: -------------------------------------------------------------------------------- 1 | //Broken Calculator 2 | //O(n), O(1) 3 | func brokenCalc(_ startValue: Int, _ target: Int) -> Int { 4 | var res = 0 5 | var t = target 6 | while t > startValue { 7 | res += 1 8 | if t % 2 == 1 { 9 | t += 1 10 | } else { 11 | t /= 2 12 | } 13 | } 14 | return res + startValue - t 15 | } -------------------------------------------------------------------------------- /Medium/Buildings With an Ocean View.swift: -------------------------------------------------------------------------------- 1 | //Buildings With an Ocean View 2 | //O(n) O(n) 3 | func findBuildings(_ heights: [Int]) -> [Int] { 4 | var stack = [Int]() 5 | for i in 0.. Bool { 4 | let arr = arr.sorted() 5 | let d = arr[0]-arr[1] 6 | for i in 0.. Int { 4 | var odd = 0, even = 0 5 | for n in position { 6 | if n % 2 == 0 { 7 | even += 1 8 | } else { 9 | odd += 1 10 | } 11 | } 12 | return min(odd, even) 13 | } -------------------------------------------------------------------------------- /Medium/Linked List Random Node.swift: -------------------------------------------------------------------------------- 1 | //Linked List Random Node 2 | 3 | class Solution { 4 | var arr = [Int]() 5 | init(_ head: ListNode?) { //O(n) 6 | var curr = head 7 | while curr != nil { 8 | arr.append(curr!.val) 9 | curr = curr!.next 10 | } 11 | } 12 | 13 | func getRandom() -> Int { //O(1) 14 | arr[Int.random(in: 0.. Int { 4 | var res = 0 5 | let arr = costs.sorted() 6 | var curr = coins 7 | for i in 0..= arr[i] { 9 | res += 1 10 | curr -= arr[i] 11 | } 12 | } 13 | return res 14 | } -------------------------------------------------------------------------------- /Medium/Number of Subarrays with Bounded Maximum.swift: -------------------------------------------------------------------------------- 1 | //Number of Subarrays with Bounded Maximum 2 | //O(n), O(1) 3 | func numSubarrayBoundedMax(_ nums: [Int], _ left: Int, _ right: Int) -> Int { 4 | var res = 0, l = -1, r = -1 5 | for i in 0.. right {l = i} 7 | if nums[i] >= left {r = i} 8 | 9 | res += r - l 10 | } 11 | return res 12 | } -------------------------------------------------------------------------------- /Easy/Number of Steps to Reduce a Number to Zero.swift: -------------------------------------------------------------------------------- 1 | //Number of Steps to Reduce a Number to Zero 2 | //O(log n) 3 | func numberOfSteps(_ num: Int) -> Int { 4 | var n = num, res = 0 5 | while n > 0 { 6 | res += 1 7 | if n % 2 == 1 { 8 | n -= 1 9 | } else { 10 | n = n >> 1 11 | } 12 | 13 | } 14 | return res 15 | } -------------------------------------------------------------------------------- /Medium/Widest Vertical Area Between Two Points Containing No Points.swift: -------------------------------------------------------------------------------- 1 | // Widest Vertical Area Between Two Points Containing No Points 2 | // O(n log n), O(n) 3 | func maxWidthOfVerticalArea(_ points: [[Int]]) -> Int { 4 | let arr = points.sorted { a, b in 5 | return a[0] < b[0] 6 | } 7 | var res = 0 8 | for i in 1.. Int { 4 | var l = 0, r = nums.endIndex-1 5 | while l>1 7 | if nums[mid] < target { 8 | l = mid + 1 9 | } else { 10 | r = mid 11 | } 12 | 13 | } 14 | return nums[l] == target ? l : -1 15 | } -------------------------------------------------------------------------------- /Medium/Removing Stars From a String.swift: -------------------------------------------------------------------------------- 1 | //Removing Stars From a String 2 | //O(n), O(n) 3 | func removeStars(_ s: String) -> String { 4 | var stack = [Character]() 5 | for char in s { 6 | switch char { 7 | case "*": 8 | stack.removeLast() 9 | default: 10 | stack.append(char) 11 | } 12 | } 13 | return String(stack) 14 | } -------------------------------------------------------------------------------- /Medium/Maximum Element After Decreasing and Rearranging.swift: -------------------------------------------------------------------------------- 1 | // Maximum Element After Decreasing and Rearranging 2 | // O(n log n), O(n) 3 | func maximumElementAfterDecrementingAndRearranging(_ arr: [Int]) -> Int { 4 | var arr = arr.sorted() 5 | if arr[0] != 1 { arr[0]=1 } 6 | for i in 1.. 1 { 8 | arr[i] = arr[i-1]+1 9 | } 10 | } 11 | return arr[arr.endIndex-1] 12 | } -------------------------------------------------------------------------------- /Medium/Maximum Size of a Set After Removals.swift: -------------------------------------------------------------------------------- 1 | // Maximum Size of a Set After Removals 2 | // O(n), O(n) 3 | func maximumSetSize(_ nums1: [Int], _ nums2: [Int]) -> Int { 4 | let n = nums1.endIndex, s1 = Set(nums1), s2 = Set(nums2) 5 | let n1 = s1.count, n2 = s2.count 6 | var c = 0 7 | for num in s1 { 8 | if s2.contains(num){ 9 | c += 1 10 | } 11 | } 12 | return min(n, min(n1-c, n/2)+min(n2-c, n/2)+c) 13 | } -------------------------------------------------------------------------------- /Medium/Minimize Maximum Pair Sum in Array.swift: -------------------------------------------------------------------------------- 1 | // Minimize Maximum Pair Sum in Array 2 | // O(n log n), O(n) 3 | func minPairSum(_ nums: [Int]) -> Int { 4 | let n = nums.endIndex 5 | let arr = nums.sorted() 6 | var res = 0 7 | for i in 0.. res { 10 | res = curr 11 | } 12 | } 13 | return res 14 | } -------------------------------------------------------------------------------- /Medium/Online Stock Span.swift: -------------------------------------------------------------------------------- 1 | //Online Stock Span 2 | //O(1), O(n) 3 | class StockSpanner { 4 | private var stack = [(price: Int, res: Int)]() 5 | 6 | func next(_ price: Int) -> Int { 7 | var res = 1 8 | while !stack.isEmpty && stack.last!.price <= price { 9 | let curr = stack.removeLast() 10 | res += curr.res 11 | } 12 | stack.append((price, res)) 13 | return res 14 | } 15 | } -------------------------------------------------------------------------------- /Medium/Swap Nodes in Pairs.swift: -------------------------------------------------------------------------------- 1 | //Swap Nodes in Pairs 2 | //O(n), O(1) 3 | func swapPairs(_ head: ListNode?) -> ListNode? { 4 | guard let node = head else {return nil} 5 | if let next = node.next { 6 | let nextNext = next.next 7 | node.next = swapPairs(nextNext) 8 | next.next = node 9 | 10 | return next 11 | } else { 12 | return node 13 | } 14 | } -------------------------------------------------------------------------------- /Hard/Best Time to Buy and Sell Stock III.swift: -------------------------------------------------------------------------------- 1 | //Best Time to Buy and Sell Stock III 2 | //O(n), O(1) 3 | func maxProfit(_ prices: [Int]) -> Int { 4 | var hold1 = -Int.max, hold2 = -Int.max 5 | var r1 = 0, r2 = 0 6 | for p in prices { 7 | r2 = max(r2, hold2+p) 8 | hold2 = max(hold2, r1 - p) 9 | r1 = max(r1, hold1+p) 10 | hold1 = max(hold1, -p) 11 | } 12 | return r2 13 | } -------------------------------------------------------------------------------- /Medium/Longest Arithmetic Subsequence.swift: -------------------------------------------------------------------------------- 1 | // Longest Arithmetic Subsequence 2 | // O(n^2),O(n^2) 3 | func longestArithSeqLength(_ nums: [Int]) -> Int { 4 | var dict = [[Int]: Int]() 5 | for i in 0.. Int { 4 | let arr = happiness.sorted(by: >) 5 | var res = 0 6 | var count = 0 7 | for i in 0.. 0 { 10 | res += curr 11 | } 12 | count += 1 13 | } 14 | return res 15 | } -------------------------------------------------------------------------------- /Medium/Minimum Number of Operations to Make Array Empty.swift: -------------------------------------------------------------------------------- 1 | // Minimum Number of Operations to Make Array Empty 2 | // O(n), O(n) 3 | func minOperations(_ nums: [Int]) -> Int { 4 | var memo = [Int: Int]() 5 | for n in nums { 6 | memo[n, default: 0] += 1 7 | } 8 | var res = 0 9 | for (_, val) in memo { 10 | if val == 1 {return -1} 11 | res += Int((Double(val)/3.0).rounded(.up)) 12 | } 13 | return res 14 | } -------------------------------------------------------------------------------- /Medium/Reduction Operations to Make the Array Elements Equal.swift: -------------------------------------------------------------------------------- 1 | // Reduction Operations to Make the Array Elements Equal 2 | // O(n log n), O(n) 3 | func reductionOperations(_ nums: [Int]) -> Int { 4 | let arr = nums.sorted(by: >) 5 | var res = 0 6 | var count = 0 7 | for i in 0.. Bool { 4 | var dict = [Character: Int]() 5 | for char in magazine { 6 | dict[char, default: 0] += 1 7 | } 8 | for char in ransomNote { 9 | dict[char, default:0] -= 1 10 | if dict[char]! < 0 {return false} 11 | } 12 | return true 13 | } -------------------------------------------------------------------------------- /Easy/Transpose Matrix.swift: -------------------------------------------------------------------------------- 1 | //Transpose Matrix 2 | //O(n), O(1) 3 | func transpose(_ matrix: [[Int]]) -> [[Int]] { 4 | let rows = matrix.endIndex, cols = matrix[0].endIndex 5 | let newRows = cols, newCols = rows 6 | var res = [[Int]](repeating: [Int](repeating: 0, count: newCols), count: newRows) 7 | for row in 0.. Int { 4 | var dict = [Character: Int]() 5 | for char in s { 6 | dict[char, default: 0] += 1 7 | } 8 | for (i, char) in Array(s).enumerated() { 9 | if dict[char, default: 0] == 1 { 10 | return i 11 | } 12 | } 13 | return -1 14 | } -------------------------------------------------------------------------------- /Easy/Maximum Average Subarray I.swift: -------------------------------------------------------------------------------- 1 | //Maximum Average Subarray I 2 | //O(n) O(1) 3 | func findMaxAverage(_ nums: [Int], _ k: Int) -> Double { 4 | var res = Int.min, sum = 0 5 | for i in 0..=k-1 { 9 | res = max(res, sum) 10 | sum -= nums[i-k+1] 11 | } 12 | } 13 | return Double(res)/Double(k) 14 | } -------------------------------------------------------------------------------- /Easy/Consecutive Characters.swift: -------------------------------------------------------------------------------- 1 | //Consecutive Characters 2 | //O(n), O(n) 3 | func maxPower(_ s: String) -> Int { 4 | var l = 0, r = 0 5 | let arr = Array(s) 6 | var res = 0 7 | while r [String] { 4 | var res = [String]() 5 | let arr = Array(currentState) 6 | if arr.endIndex == 1 {return []} 7 | for i in 1.. TreeNode? { 5 | guard let node = root else {return nil} 6 | if node.val == val { 7 | return node 8 | }else if node.val > val { 9 | return searchBST(node.left,val) 10 | } else { 11 | return searchBST(node.right,val) 12 | } 13 | } 14 | } -------------------------------------------------------------------------------- /Easy/Sign of the Product of an Array.swift: -------------------------------------------------------------------------------- 1 | //Sign of the Product of an Array 2 | //O(n), O(1) 3 | func arraySign(_ nums: [Int]) -> Int { 4 | var curr = 1 5 | for n in nums { 6 | curr = (curr * n) 7 | if curr > 0 { 8 | curr = 1 9 | } else if curr == 0 { 10 | curr = 0 11 | } else { 12 | curr = -1 13 | } 14 | } 15 | return curr 16 | } -------------------------------------------------------------------------------- /Medium/Distribute Coins in Binary Tree.swift: -------------------------------------------------------------------------------- 1 | // Distribute Coins in Binary Tree 2 | // O(n), O(n) 3 | func distributeCoins(_ root: TreeNode?) -> Int { 4 | var res = 0 5 | func dfs(_ node: TreeNode?) -> Int { 6 | if node == nil { return 0} 7 | let left = dfs(node!.left) 8 | let right = dfs(node!.right) 9 | res += abs(left) + abs(right) 10 | return node!.val - 1 + left + right 11 | } 12 | dfs(root) 13 | return res 14 | } -------------------------------------------------------------------------------- /Medium/Increasing Triplet Subsequence.swift: -------------------------------------------------------------------------------- 1 | /*Increasing Triplet Subsequence*/ 2 | //time O(n) space O(1) 3 | func increasingTriplet(_ nums: [Int]) -> Bool { 4 | var v1 = Int.max, v2 = Int.max 5 | for n in nums { 6 | if n <= v1 { 7 | v1 = n 8 | } else if n <= v2 { 9 | v2 = n 10 | } else { 11 | return true 12 | } 13 | } 14 | return false 15 | } -------------------------------------------------------------------------------- /Easy/Largest Positive Integer That Exists With Its Negative.swift: -------------------------------------------------------------------------------- 1 | // Largest Positive Integer That Exists With Its Negative 2 | // O(n log n), O(n) 3 | func findMaxK(_ nums: [Int]) -> Int { 4 | let arr = nums.sorted() 5 | var set = Set() 6 | for n in nums { 7 | if n > 0 { 8 | set.insert(n) 9 | } 10 | } 11 | for n in arr { 12 | if set.contains(-n) { 13 | return -n 14 | } 15 | } 16 | return -1 17 | } -------------------------------------------------------------------------------- /Medium/Adding Spaces to a String.swift: -------------------------------------------------------------------------------- 1 | // Adding Spaces to a String 2 | // O(n), O(1) 3 | func addSpaces(_ s: String, _ spaces: [Int]) -> String { 4 | var res = "" 5 | let arr_s = Array(s) 6 | var space_index = 0 7 | for i in 0.. Int { 4 | var dict = [Int: Int]() 5 | var res = 0 6 | for n in nums { 7 | if dict[n, default: 0] > 0 { 8 | res += 1 9 | dict[n]! -= 1 10 | } else { 11 | dict[k-n, default:0] += 1 12 | } 13 | } 14 | return res 15 | } -------------------------------------------------------------------------------- /Easy/Element Appearing More Than 25% In Sorted Array.swift: -------------------------------------------------------------------------------- 1 | // Element Appearing More Than 25% In Sorted Array 2 | // O(n), O(1) 3 | func findSpecialInteger(_ arr: [Int]) -> Int { 4 | var curr = 0 5 | for i in 0.. arr.endIndex / 4 { 12 | return arr[i] 13 | } 14 | } 15 | return 0 16 | } -------------------------------------------------------------------------------- /Easy/Meeting Rooms.swift: -------------------------------------------------------------------------------- 1 | //Meeting Rooms 2 | //O(n log n) O(n) 3 | class Solution { 4 | func canAttendMeetings(_ intervals: [[Int]]) -> Bool { 5 | var sorted = intervals.sorted { a, b in 6 | a[0] < b[0] 7 | } 8 | var i = 0 9 | while i < sorted.endIndex - 1 { 10 | let t1 = sorted[i], t2 = sorted[i+1] 11 | if t1[1] > t2[0] {return false} 12 | i += 1 13 | } 14 | return true 15 | } 16 | } -------------------------------------------------------------------------------- /Medium/Find Champion II.swift: -------------------------------------------------------------------------------- 1 | // Find Champion II 2 | // O(n), O(n) 3 | func findChampion(_ n: Int, _ edges: [[Int]]) -> Int { 4 | var memo = [Int: Int]() 5 | for edge in edges { 6 | memo[edge[1], default: 0] += 1 7 | } 8 | var arr = [Int]() 9 | for node in 0.. 1 { 15 | return -1 16 | } 17 | return arr[0] 18 | } -------------------------------------------------------------------------------- /Medium/Arithmetic Slices.swift: -------------------------------------------------------------------------------- 1 | //Arithmetic Slices 2 | //O(n),O(1) 3 | func numberOfArithmeticSlices(_ nums: [Int]) -> Int { 4 | var res = 0, curr = 0 5 | if nums.endIndex < 2 {return 0} 6 | for i in 2.. Int { 4 | var res = 0 5 | var currCount = 0 6 | let arr = Array(s) 7 | for i in 0.. Int { 4 | var res = -1 5 | let arr = nums.sorted() 6 | var curr = arr[0] + arr[1] 7 | for i in 2.. arr[i] { 9 | res = max(res, curr+arr[i]) 10 | } 11 | curr += arr[i] 12 | } 13 | return res 14 | } -------------------------------------------------------------------------------- /Easy/Longest Palindrome.swift: -------------------------------------------------------------------------------- 1 | //Longest Palindrome 2 | func longestPalindrome(_ s: String) -> Int { 3 | var dict = [Character:Int]() 4 | for char in s { 5 | dict[char, default:0]+=1 6 | } 7 | var res = 0 8 | var single = 0 9 | for (_,value) in dict { 10 | res += value / 2 * 2 11 | if res % 2 == 0 && value % 2 == 1 { 12 | res += 1 13 | } 14 | } 15 | return res 16 | } -------------------------------------------------------------------------------- /Medium/Find The Original Array of Prefix Xor.swift: -------------------------------------------------------------------------------- 1 | // Find The Original Array of Prefix Xor 2 | // O(n), O(1) 3 | func findArray(_ pref: [Int]) -> [Int] { 4 | var res = [pref[0]] 5 | for i in 1.. [Int] { 13 | var res = pref 14 | for i in (1.. [Int] { 4 | var res = [Int]() 5 | var rsum = nums.reduce(0, +) 6 | var lsum = 0 7 | let n = nums.endIndex 8 | for i in 0.. Int { 4 | var loses = [Int](), cost = 0 5 | for person in costs { 6 | let a = person[0], b = person[1] 7 | loses.append(b-a) 8 | cost += a 9 | } 10 | loses.sort() 11 | let n = costs.endIndex/2 12 | for i in 0.. Int { 4 | var res = 0 5 | 6 | func dfs(_ node: TreeNode?) -> Int { 7 | guard let node = node else {return 0} 8 | let left = dfs(node.left) 9 | let right = dfs(node.right) 10 | res += abs(left - right) 11 | return node.val + left + right 12 | } 13 | 14 | dfs(root) 15 | return res 16 | } -------------------------------------------------------------------------------- /Medium/Trim a Binary Search Tree.swift: -------------------------------------------------------------------------------- 1 | //Trim a Binary Search Tree 2 | //O(n), O(h) 3 | func trimBST(_ root: TreeNode?, _ low: Int, _ high: Int) -> TreeNode? { 4 | guard let node = root else {return nil} 5 | node.left = trimBST(node.left, low, high) 6 | node.right = trimBST(node.right, low, high) 7 | if node.val < low { 8 | return node.right 9 | } else if node.val > high { 10 | return node.left 11 | } 12 | return node 13 | } -------------------------------------------------------------------------------- /Easy/Power of Three.swift: -------------------------------------------------------------------------------- 1 | //Power of Three 2 | //O(log3 n) 3 | func isPowerOfThree(_ n: Int) -> Bool { 4 | var p = 1 5 | if p == n { 6 | return true 7 | } 8 | while p < n { 9 | p *= 3 10 | if p == n { 11 | return true 12 | } 13 | } 14 | return false 15 | } 16 | 17 | //O(1), O(1) 18 | func isPowerOfThree(_ n: Int) -> Bool { 19 | return n > 0 && Int(pow(Double(3), 19)) % n == 0 20 | } -------------------------------------------------------------------------------- /Easy/Reverse Prefix of Word.swift: -------------------------------------------------------------------------------- 1 | // Reverse Prefix of Word 2 | // O(n), O(n) 3 | func reversePrefix(_ word: String, _ ch: Character) -> String { 4 | var arr = Array(word) 5 | for i in 0.. Int { 4 | var dict = [Character: Int]() 5 | for (i,char) in keyboard.enumerated() { 6 | dict[char] = i 7 | } 8 | var res = 0 9 | var curr = 0 10 | for char in word { 11 | res += abs(curr - dict[char]!) 12 | curr = dict[char]! 13 | } 14 | return res 15 | } -------------------------------------------------------------------------------- /Medium/Encode and Decode TinyURL.swift: -------------------------------------------------------------------------------- 1 | //Encode and Decode TinyURL 2 | //O(1),O(1) 3 | class Codec { 4 | // Encodes a URL to a shortened URL. 5 | var dict = [UUID: String]() 6 | func encode(_ longUrl: String) -> String { 7 | let id = UUID() 8 | dict[id] = longUrl 9 | return id.uuidString 10 | } 11 | 12 | // Decodes a shortened URL to its original URL. 13 | func decode(_ shortUrl: String) -> String { 14 | dict[UUID(uuidString: shortUrl)!]! 15 | } 16 | } -------------------------------------------------------------------------------- /Easy/Set Mismatch.swift: -------------------------------------------------------------------------------- 1 | //Set Mismatch 2 | //O(n), O(n) 3 | func findErrorNums(_ nums: [Int]) -> [Int] { 4 | var set = Set() 5 | var res = [Int]() 6 | for n in nums { 7 | if set.contains(n) { 8 | res.append(n) 9 | } 10 | set.insert(n) 11 | } 12 | for i in 1...nums.endIndex { 13 | if set.contains(i) == false { 14 | res.append(i) 15 | } 16 | } 17 | return res 18 | } -------------------------------------------------------------------------------- /Medium/Array of Doubled Pairs.swift: -------------------------------------------------------------------------------- 1 | //Array of Doubled Pairs 2 | //O(n log n), O(n) 3 | func canReorderDoubled(_ arr: [Int]) -> Bool { 4 | var count = [Int: Int]() 5 | for n in arr { 6 | count[n, default:0]+=1 7 | } 8 | var arr2 = arr.sorted{ a,b in abs(a) Int { 4 | var dict = [Int: Int]() 5 | dict[0] = -1 6 | var count = 0, res = 0 7 | for i in 0.. Int { 4 | let arr = nums.sorted() 5 | var l=0,r=0,res=0,curr=0 6 | while r k { 10 | curr -= arr[l] 11 | l += 1 12 | } 13 | res = max(res, r-l+1) 14 | r += 1 15 | } 16 | return res 17 | } -------------------------------------------------------------------------------- /Medium/Random Pick Index.swift: -------------------------------------------------------------------------------- 1 | //Random Pick Index 2 | //O(n) O(n) 3 | class Solution { 4 | let dict: [Int:[Int]] 5 | init(_ nums: [Int]) { 6 | var dict = [Int:[Int]]() 7 | for (i,n) in nums.enumerated() { 8 | dict[n,default:[]].append(i) 9 | } 10 | self.dict = dict 11 | } 12 | 13 | func pick(_ target: Int) -> Int { 14 | let arr = dict[target]! 15 | let index = Int.random(in: 0.. Int { 4 | var dp = Array<[Int]>(repeating: Array(repeating: 0,count:n), count: m) 5 | 6 | for i in 0.. Int { 3 | var res = 0 4 | 5 | func dfs(_ node: TreeNode?) -> Int { 6 | guard let node = node else {return 0} 7 | let left = dfs(node.left) 8 | let right = dfs(node.right) 9 | res = max(res, left + right) 10 | return max(left,right) + 1 11 | } 12 | 13 | dfs(root) 14 | 15 | return res 16 | } -------------------------------------------------------------------------------- /Easy/Unique Number of Occurrences.swift: -------------------------------------------------------------------------------- 1 | //Unique Number of Occurrences 2 | //O(n), O(n) 3 | func uniqueOccurrences(_ arr: [Int]) -> Bool { 4 | 5 | var dict = [Int: Int]() 6 | for n in arr { 7 | dict[n, default:0] += 1 8 | } 9 | 10 | var set = Set() 11 | for count in dict.values { 12 | if set.contains(count) { 13 | return false 14 | } 15 | set.insert(count) 16 | } 17 | return true 18 | } -------------------------------------------------------------------------------- /Medium/Maximum Number of Integers to Choose From a Range I.swift: -------------------------------------------------------------------------------- 1 | // Maximum Number of Integers to Choose From a Range I 2 | // O(n), O(n) 3 | func maxCount(_ banned: [Int], _ n: Int, _ maxSum: Int) -> Int { 4 | let banned_set = Set(banned) 5 | var curr = 0 6 | var res = 0 7 | for i in 1...n { 8 | if i + curr > maxSum { 9 | break 10 | } 11 | if banned_set.contains(i) == false { 12 | curr += i 13 | res += 1 14 | } 15 | } 16 | return res 17 | } -------------------------------------------------------------------------------- /Medium/Minimum Number of Steps to Make Two Strings Anagram.swift: -------------------------------------------------------------------------------- 1 | // Minimum Number of Steps to Make Two Strings Anagram 2 | // O(n), O(n) 3 | func minSteps(_ s: String, _ t: String) -> Int { 4 | var memo = [Character: Int]() 5 | for char in s { 6 | memo[char, default: 0] += 1 7 | } 8 | 9 | for char in t { 10 | memo[char, default: 0] -= 1 11 | } 12 | 13 | var res = 0 14 | for (key, val) in memo { 15 | res += abs(memo[key, default: 0]) 16 | } 17 | return res / 2 18 | } -------------------------------------------------------------------------------- /Medium/Minimum Operations to Make Array Equal.swift: -------------------------------------------------------------------------------- 1 | //Minimum Operations to Make Array Equal 2 | //O(n) O(1) 3 | func minOperations(_ n: Int) -> Int { 4 | var res = 0 5 | let avg = 1 + (2 * (n - 1)) / 2 6 | for i in 0..>1 { 7 | res += avg - ((2*i)+1) 8 | } 9 | return ress 10 | } 11 | //O(1) 12 | func minOperations(_ n: Int) -> Int { 13 | let avgSum = (1 + (2 * (n - 1) + 1)) * n / 4 - ((1 + (2 * (n - 1)>>1) + 1) * n>>1) / 2 14 | return avgSum 15 | } -------------------------------------------------------------------------------- /Easy/Generate Parentheses.swift: -------------------------------------------------------------------------------- 1 | //Generate Parentheses 2 | func generateParenthesis(_ n: Int) -> [String] { 3 | var res = [String]() 4 | func dfs(_ path:String, _ left: Int, _ right: Int) { 5 | if path.count == n * 2 { 6 | res.append(path) 7 | return 8 | } 9 | if left < n {dfs(path+"(",left+1,right)} 10 | if right < left {dfs(path+")",left,right+1)} 11 | 12 | } 13 | dfs("", 0,0) 14 | return res 15 | } -------------------------------------------------------------------------------- /Easy/Kids With the Greatest Number of Candies.swift: -------------------------------------------------------------------------------- 1 | //Kids With the Greatest Number of Candies 2 | //O(n), O(n) 3 | func kidsWithCandies(_ candies: [Int], _ extraCandies: Int) -> [Bool] { 4 | var res = [Bool]() 5 | let maxCandies = candies.max()! 6 | for i in 0..= maxCandies { 8 | res.append(true) 9 | } else { 10 | res.append(false) 11 | } 12 | } 13 | return res 14 | } -------------------------------------------------------------------------------- /Easy/Number of Lines To Write String.swift: -------------------------------------------------------------------------------- 1 | // Number of Lines To Write String 2 | // O(n), O(n) 3 | func numberOfLines(_ widths: [Int], _ s: String) -> [Int] { 4 | var lines = 1, currWidths = 0 5 | let arr = Array(s) 6 | for char in arr { 7 | let width = widths[Int(char.asciiValue!) - Int(Character("a").asciiValue!)] 8 | if currWidths + width > 100 { 9 | currWidths = 0 10 | lines += 1 11 | } 12 | currWidths += width 13 | } 14 | return [lines, currWidths] 15 | } -------------------------------------------------------------------------------- /Medium/Partition Array for Maximum Sum.swift: -------------------------------------------------------------------------------- 1 | // Partition Array for Maximum Sum 2 | // O(n), O(n) 3 | func maxSumAfterPartitioning(_ arr: [Int], _ k: Int) -> Int { 4 | let n = arr.endIndex 5 | var dp = [Int](repeating: 0, count: n + 1) 6 | for i in 1...n { 7 | var currN = arr[i-1] 8 | for j in 1...k { 9 | if i-j >= 0 { 10 | currN = max(currN, arr[i-j]) 11 | dp[i] = max(dp[i], dp[i-j] + currN*j) 12 | } 13 | } 14 | } 15 | return dp[n] 16 | } -------------------------------------------------------------------------------- /Easy/Maximum Product of Two Elements in an Array.swift: -------------------------------------------------------------------------------- 1 | // Maximum Product of Two Elements in an Array 2 | // O(n), O(1) 3 | func maxProduct(_ nums: [Int]) -> Int { 4 | var a = nums[0] 5 | var aIndex = 0 6 | for i in 1.. a { 8 | a = nums[i] 9 | aIndex = i 10 | } 11 | } 12 | var b = 0 13 | for i in 0.. b && i != aIndex { 15 | b = nums[i] 16 | } 17 | } 18 | return (a-1)*(b-1) 19 | } -------------------------------------------------------------------------------- /Easy/Count Elements With Maximum Frequency.swift: -------------------------------------------------------------------------------- 1 | // Count Elements With Maximum Frequency 2 | // O(n), O(n) 3 | func maxFrequencyElements(_ nums: [Int]) -> Int { 4 | var memo = [Int: Int]() 5 | for n in nums { 6 | memo[n, default: 0] += 1 7 | } 8 | var maxFreq = 0 9 | var res = 0 10 | for val in memo.values { 11 | if val > maxFreq { 12 | maxFreq = val 13 | res = val 14 | } else if val == maxFreq { 15 | res += val 16 | } 17 | } 18 | return res 19 | } -------------------------------------------------------------------------------- /Easy/Add Digits.swift: -------------------------------------------------------------------------------- 1 | //Add Digits 2 | //O(n), O(1) 3 | func addDigits(_ num: Int) -> Int { 4 | var res = num 5 | while res >= 10 { 6 | var temp = 0 7 | while res > 0 { 8 | temp += res%10 9 | res /= 10 10 | } 11 | res = temp 12 | } 13 | return res 14 | } 15 | 16 | //O(1),O(1) 17 | func addDigits(_ num: Int) -> Int { 18 | if num == 0 {return 0} 19 | if num % 9 == 0 {return 9} 20 | return num%9 21 | } -------------------------------------------------------------------------------- /Medium/Sort Colors.swift: -------------------------------------------------------------------------------- 1 | //Sort Colors 2 | //O(n), O(1) 3 | func sortColors(_ nums: inout [Int]) { 4 | var l = 0, r = nums.endIndex-1, i = 0 5 | while i<=r { 6 | if nums[i] == 0 { 7 | (nums[l], nums[i]) = (nums[i],nums[l]) 8 | l += 1 9 | i += 1 10 | } else if nums[i] == 1 { 11 | i += 1 12 | } else { 13 | (nums[i], nums[r]) = (nums[r], nums[i]) 14 | r -= 1 15 | } 16 | } 17 | } -------------------------------------------------------------------------------- /Medium/Convert an Array Into a 2D Array With Conditions.swift: -------------------------------------------------------------------------------- 1 | // Convert an Array Into a 2D Array With Conditions 2 | // O(n), O(n) 3 | func findMatrix(_ nums: [Int]) -> [[Int]] { 4 | var dict = [Int: Int]() 5 | for n in nums { 6 | dict[n, default: 0] += 1 7 | } 8 | var res = [[Int]]() 9 | for (key, val) in dict { 10 | for row in 0.. Bool { 4 | var currMin = Int.min 5 | var stack = [Int]() 6 | for n in preorder { 7 | if n < currMin {return false} 8 | while stack.isEmpty == false && stack.last! < n { 9 | currMin = stack.removeLast() 10 | } 11 | stack.append(n) 12 | 13 | } 14 | return true 15 | } -------------------------------------------------------------------------------- /misc/stack.swift: -------------------------------------------------------------------------------- 1 | public struct Stack{ 2 | private var arr = [T]() 3 | var count: Int { 4 | return arr.count 5 | } 6 | mutating func push(_ item: T) { 7 | arr.append(item) 8 | } 9 | 10 | mutating func pop() -> T? { 11 | return arr.removeLast() 12 | } 13 | 14 | var top: T? { 15 | return arr.last 16 | } 17 | } 18 | var stack = Stack() 19 | print(stack.count) 20 | print(stack.top) 21 | stack.push(10) 22 | stack.push(12) 23 | print(stack.top) 24 | print(stack.pop()) 25 | print(stack.top) -------------------------------------------------------------------------------- /Easy/Final Array State After K Multiplication Operations I.swift: -------------------------------------------------------------------------------- 1 | // Final Array State After K Multiplication Operations I 2 | // O(n*k), O(n) 3 | func getFinalState(_ nums: [Int], _ k: Int, _ multiplier: Int) -> [Int] { 4 | var nums = nums 5 | for _ in 0.. Int { 3 | var res = 0 4 | func dfs(_ node: TreeNode?) { 5 | guard let node = node else {return} 6 | dfs(node.left) 7 | dfs(node.right) 8 | if let left = node.left { 9 | if left.left == nil && left.right == nil { 10 | res += left.val 11 | } 12 | } 13 | } 14 | dfs(root) 15 | 16 | return res 17 | } -------------------------------------------------------------------------------- /Medium/Continuous Subarray Sum.swift: -------------------------------------------------------------------------------- 1 | //Continuous Subarray Sum 2 | //O(n) O(n) 3 | func checkSubarraySum(_ nums: [Int], _ k: Int) -> Bool { 4 | var dict = [0:-1] 5 | 6 | var sum = 0 7 | for (i,n) in nums.enumerated() { 8 | sum += n 9 | if let index = dict[sum % k] { 10 | if i - index > 1 { 11 | return true 12 | } 13 | } else { 14 | dict[sum % k] = i 15 | } 16 | } 17 | return false 18 | } -------------------------------------------------------------------------------- /Medium/Minimum Number of Vertices to Reach All Nodes.swift: -------------------------------------------------------------------------------- 1 | //Minimum Number of Vertices to Reach All Nodes 2 | //O(n+e), O(n) 3 | func findSmallestSetOfVertices(_ n: Int, _ edges: [[Int]]) -> [Int] { 4 | var isIncommingNode = (0.. String { 4 | var res = "" 5 | var curr = -1 6 | let arr = Array(num) 7 | for i in 1.. curr { 11 | curr = n 12 | res = String(arr[(i-1)...(i+1)]) 13 | } 14 | } 15 | } 16 | return res 17 | } -------------------------------------------------------------------------------- /Medium/Maximum Size Subarray Sum Equals k.swift: -------------------------------------------------------------------------------- 1 | //Maximum Size Subarray Sum Equals k 2 | //O(n) O(n) 3 | func maxSubArrayLen(_ nums: [Int], _ k: Int) -> Int { 4 | var dict = [0:-1] 5 | var sum = 0, res = 0 6 | for (i,n) in nums.enumerated() { 7 | sum += n 8 | if dict[sum-k] != nil { 9 | res = max(res, i - dict[sum-k]!) 10 | } 11 | if dict[sum] == nil { 12 | dict[sum] = i 13 | } 14 | 15 | } 16 | return res 17 | } -------------------------------------------------------------------------------- /Easy/Arranging Coins.swift: -------------------------------------------------------------------------------- 1 | //Arranging Coins 2 | //O(log n) 3 | func arrangeCoins(_ n: Int) -> Int { 4 | var l = 0, r = n 5 | while l<=r { 6 | let k = l+(r-l)>>1 7 | let curr = k*(k+1) / 2 8 | if curr == n {return k} 9 | if curr < n { 10 | l = k+1 11 | } else { 12 | r = k-1 13 | } 14 | } 15 | return r 16 | } 17 | 18 | //O(1) 19 | func arrangeCoins(_ n: Int) -> Int { 20 | Int(sqrt(2 * Double(n) + 0.25) - 0.5) 21 | } -------------------------------------------------------------------------------- /Medium/Group the People Given the Group Size They Belong To.swift: -------------------------------------------------------------------------------- 1 | // Group the People Given the Group Size They Belong To 2 | // O(n), O(n) 3 | func groupThePeople(_ groupSizes: [Int]) -> [[Int]] { 4 | var res = [[Int]]() 5 | var dict = [Int: [Int]]() 6 | for (i, n) in groupSizes.enumerated() { 7 | if dict[n] == nil { 8 | dict[n] = [Int]() 9 | } 10 | dict[n]!.append(i) 11 | if dict[n]!.count == n { 12 | res.append(dict[n]!) 13 | dict[n] = [Int]() 14 | } 15 | } 16 | return res 17 | } -------------------------------------------------------------------------------- /Medium/Linked List Cycle II.swift: -------------------------------------------------------------------------------- 1 | /*Linked List Cycle II*/ 2 | func detectCycle(_ head: ListNode?) -> ListNode? { 3 | var slow = head, fast = head 4 | while fast != nil && fast!.next != nil { 5 | slow = slow!.next 6 | fast = fast!.next!.next 7 | if slow === fast {break} 8 | } 9 | if fast == nil || fast!.next == nil {return nil} 10 | fast = head 11 | while slow !== fast { 12 | fast = fast!.next 13 | slow = slow!.next 14 | } 15 | return slow 16 | } -------------------------------------------------------------------------------- /Easy/Redistribute Characters to Make All Strings Equal.swift: -------------------------------------------------------------------------------- 1 | // Redistribute Characters to Make All Strings Equal 2 | // O(n), O(n) 3 | func makeEqual(_ words: [String]) -> Bool { 4 | var memo = [Character: Int]() 5 | for word in words { 6 | for char in word { 7 | memo[char, default: 0] += 1 8 | } 9 | } 10 | let n = words.endIndex 11 | for (key, val) in memo { 12 | if val % n != 0 { 13 | return false 14 | } 15 | } 16 | return true 17 | } -------------------------------------------------------------------------------- /Easy/Reverse Bits.swift: -------------------------------------------------------------------------------- 1 | /*Reverse Bits*/ 2 | //O(1), O(1) 3 | func reverseBits(_ n: Int) -> Int { 4 | var n = n 5 | var result = 0 6 | for _ in 0..<32 { 7 | result <<= 1 8 | result += n & 1 9 | n >>= 1 10 | } 11 | return result 12 | } 13 | 14 | //O(1), O(1) 15 | func reverseBits(_ n: Int) -> Int { 16 | var n = n 17 | var res = [Int]() 18 | for i in 0..<32 { 19 | res.append(n&1) 20 | n >>= 1 21 | } 22 | let curr = res.map{ String($0) }.joined() 23 | 24 | return Int(curr, radix: 2) ?? 0 25 | } -------------------------------------------------------------------------------- /Medium/Beautiful Arrangement II.swift: -------------------------------------------------------------------------------- 1 | //Beautiful Arrangement II 2 | func constructArray(_ n: Int, _ k: Int) -> [Int] { 3 | var res = [Int]() 4 | if n <= k {return []} 5 | var l = 1, r = n 6 | while res.endIndex < n { 7 | if k % 2 != 0 { 8 | res.append(l) 9 | l += 1 10 | } else { 11 | res.append(r) 12 | r -= 1 13 | } 14 | if k > 1 { 15 | k -= 1 16 | } 17 | } 18 | return res 19 | } 20 | -------------------------------------------------------------------------------- /Medium/Sum of Two Integers.swift: -------------------------------------------------------------------------------- 1 | func getSum(_ a: Int, _ b: Int) -> Int { 2 | return a + b 3 | } 4 | 5 | func getSum(_ a: Int, _ b: Int) -> Int { 6 | var a = a 7 | var b = b 8 | while b != 0 { 9 | let carry = a & b 10 | a = a ^ b 11 | b = carry << 1 12 | } 13 | return a 14 | } 15 | 16 | func getSum_Recursive(_ a: Int, _ b: Int) -> Int { 17 | return b == 0 ? a : getSum_Recursive(a ^ b, (a & b) << 1) 18 | } 19 | 20 | func getSum(_ a: Int, _ b: Int) -> Int { 21 | if b == 0 {return a} 22 | return getSum(a^b, (a&b)<<1) 23 | } -------------------------------------------------------------------------------- /Easy/Longest Subsequence With Limited Sum.swift: -------------------------------------------------------------------------------- 1 | //Longest Subsequence With Limited Sum 2 | //O(n log n), O(n) 3 | func answerQueries(_ nums: [Int], _ queries: [Int]) -> [Int] { 4 | var res = [Int]() 5 | let nums = nums.sorted() 6 | for query in queries { 7 | var curr = 0, count = 0 8 | for n in nums { 9 | if curr + n <= query { 10 | count += 1 11 | curr += n 12 | } 13 | } 14 | res.append(count) 15 | } 16 | return res 17 | } -------------------------------------------------------------------------------- /Medium/K-th Symbol in Grammar.swift: -------------------------------------------------------------------------------- 1 | // K-th Symbol in Grammar 2 | // O(n), O(n) 3 | func kthGrammar(_ n: Int, _ k: Int) -> Int { 4 | func dfs(_ n: Int, _ k: Int, _ root: Int) -> Int { 5 | if n == 1 {return root} 6 | let totalNodes = Int(pow(2, Double(n-1))) 7 | if k > totalNodes / 2 { 8 | let nextRoot = root == 0 ? 1 : 0 9 | return dfs(n-1, k-totalNodes/2, nextRoot) 10 | } else { 11 | let nextRoot = root == 0 ? 0 : 1 12 | return dfs(n-1, k, nextRoot) 13 | } 14 | } 15 | return dfs(n,k,0) 16 | } -------------------------------------------------------------------------------- /Easy/Palindrome Permutation.swift: -------------------------------------------------------------------------------- 1 | //Palindrome Permutation 2 | //O(n) O(n) 3 | func canPermutePalindrome(_ s: String) -> Bool { 4 | var dict = [Character:Int]() 5 | for char in s { 6 | dict[char, default:0] += 1 7 | } 8 | var hasOdd = false 9 | for (_,value) in dict { 10 | if value % 2 == 1 { 11 | if hasOdd == false { 12 | hasOdd = true 13 | } else { 14 | return false 15 | } 16 | } 17 | } 18 | return true 19 | } -------------------------------------------------------------------------------- /Medium/Check Completeness of a Binary Tree.swift: -------------------------------------------------------------------------------- 1 | //Check Completeness of a Binary Tree 2 | //O(n), O(h) 3 | func isCompleteTree(_ root: TreeNode?) -> Bool { 4 | guard let node = root else {return true} 5 | var queue = [root] 6 | while !queue.isEmpty && queue.first! != nil { 7 | let node = queue.removeFirst() 8 | queue.append(node!.left) 9 | queue.append(node!.right) 10 | } 11 | while !queue.isEmpty && queue.first! == nil { 12 | queue.removeFirst() 13 | } 14 | return queue.isEmpty 15 | } -------------------------------------------------------------------------------- /Medium/Minimum Time to Complete Trips.swift: -------------------------------------------------------------------------------- 1 | //Minimum Time to Complete Trips 2 | //O(time * log totalTrips), O(1) 3 | func minimumTime(_ time: [Int], _ totalTrips: Int) -> Int { 4 | 5 | var l = 1, r = time.min()! * totalTrips 6 | while l>1 8 | let curr = time.reduce(0, { a, n in 9 | return a + mid/n 10 | }) 11 | if curr < totalTrips { 12 | l = mid+1 13 | } else { 14 | r = mid 15 | } 16 | } 17 | return l 18 | } -------------------------------------------------------------------------------- /Easy/Relative Sort Array.swift: -------------------------------------------------------------------------------- 1 | // Relative Sort Array 2 | // O(n log n), O(n) 3 | func relativeSortArray(_ arr1: [Int], _ arr2: [Int]) -> [Int] { 4 | var memo = [Int: Int]() 5 | for i in 0.. [Int] { 4 | 5 | func count1(_ n: Int) -> Int { 6 | var n = n 7 | var count = 0 8 | while n > 0 { 9 | count += n & 1 10 | n >>= 1 11 | } 12 | return count 13 | } 14 | let sortedArr = arr.sorted { a,b in 15 | let c1 = count1(a) 16 | let c2 = count1(b) 17 | if c1 == c2 {return a < b} 18 | return c1 < c2 19 | } 20 | 21 | return sortedArr 22 | } -------------------------------------------------------------------------------- /Medium/Gray Code.swift: -------------------------------------------------------------------------------- 1 | //Gray Code 2 | //O(2^n), O(n) 3 | func grayCode(_ n: Int) -> [Int] { 4 | 5 | func dfs(_ n: Int) -> [String] { 6 | if n == 0 {return ["0"]} 7 | if n == 1 {return ["0","1"]} 8 | let arr = dfs(n-1) 9 | let addZeroArr = arr.compactMap{ num in "0" + num } 10 | let addOneArr = arr.reversed().compactMap{ num in "1" + num } 11 | let res = addZeroArr + addOneArr 12 | 13 | return res 14 | } 15 | 16 | return dfs(n).compactMap { n in Int(n, radix: 2) } 17 | } -------------------------------------------------------------------------------- /Medium/Reordered Power of 2.swift: -------------------------------------------------------------------------------- 1 | //Reordered Power of 2 2 | //O(log n), O(log n) 3 | class Solution { 4 | func reorderedPowerOf2(_ n: Int) -> Bool { 5 | let arr = count(n) 6 | for p in 0..<32 { 7 | if arr == count(1< [Int] { 15 | var n = n 16 | var arr = (0...9).map{_ in 0} 17 | while n > 0 { 18 | arr[n%10] += 1 19 | n /= 10 20 | } 21 | return arr 22 | } 23 | } -------------------------------------------------------------------------------- /Medium/Rotate List.swift: -------------------------------------------------------------------------------- 1 | //Rotate List 2 | func rotateRight(_ head: ListNode?, _ k: Int) -> ListNode? { 3 | if head == nil || head?.next == nil {return head} 4 | var last = head!, n = 1 5 | while last.next != nil { 6 | last = last.next! 7 | n += 1 8 | } 9 | if k % n == 0 {return head} 10 | var middle = head! 11 | for _ in 0..<(n-(k%n)-1) { 12 | middle = middle.next! 13 | } 14 | let newHead = middle.next 15 | last.next = head 16 | middle.next = nil 17 | return newHead 18 | } -------------------------------------------------------------------------------- /Medium/Stone Game.swift: -------------------------------------------------------------------------------- 1 | //Stone Game 2 | //O(1) 3 | func stoneGame(_ piles: [Int]) -> Bool { 4 | true 5 | } 6 | //O(n^2) 7 | func stoneGame(_ piles: [Int]) -> Bool { 8 | var dp = (0.. 0 18 | } -------------------------------------------------------------------------------- /Medium/Longest Valid Parentheses.swift: -------------------------------------------------------------------------------- 1 | //Longest Valid Parentheses 2 | //O(n) O(n) 3 | func longestValidParentheses(_ s: String) -> Int { 4 | var stack = [-1] 5 | var res = 0 6 | for (i,char) in s.enumerated() { 7 | if char == "(" { 8 | stack.append(i) 9 | } else { 10 | stack.removeLast() 11 | if stack.isEmpty { 12 | stack.append(i) 13 | } else { 14 | res = max(res, i - stack.last!) 15 | } 16 | } 17 | } 18 | return res 19 | } -------------------------------------------------------------------------------- /Medium/Minimum Index of a Valid Split.swift: -------------------------------------------------------------------------------- 1 | // Minimum Index of a Valid Split 2 | // O(n), O(n) 3 | func minimumIndex(_ nums: [Int]) -> Int { 4 | var dict_left = [Int: Int]() 5 | var dict_right = [Int: Int]() 6 | 7 | for n in nums { 8 | dict_right[n, default: 0] += 1 9 | } 10 | 11 | for i in 0.. i+1 && dict_right[curr]! * 2 > nums.endIndex-i-1 { 16 | return i 17 | } 18 | } 19 | return -1 20 | } -------------------------------------------------------------------------------- /Medium/Minimum Length of String After Deleting Similar Ends.swift: -------------------------------------------------------------------------------- 1 | // Minimum Length of String After Deleting Similar Ends 2 | // O(n), O(n) 3 | func minimumLength(_ s: String) -> Int { 4 | let arr = Array(s) 5 | var l = 0, r = arr.endIndex-1 6 | var res = arr.endIndex 7 | while l Bool { 4 | if x < 0 {return false} 5 | let arr = Array(String(x)) 6 | var l = 0, r = arr.endIndex-1 7 | while l Bool { 17 | if x < 0 {return false} 18 | var arr = [Int]() 19 | var n = x 20 | while n > 0 { 21 | arr.append(n % 10) 22 | n /= 10 23 | } 24 | return arr == arr.reversed() 25 | } -------------------------------------------------------------------------------- /Easy/Closest Binary Search Tree Value.swift: -------------------------------------------------------------------------------- 1 | //Closest Binary Search Tree Value 2 | //O(n) 3 | func closestValue(_ root: TreeNode?, _ target: Double) -> Int { 4 | var diff : Double = Double.infinity 5 | var res = Int.max 6 | func dfs(_ node: TreeNode?) { 7 | guard let node = node else {return} 8 | if abs(diff) > abs(target - Double(node.val)) { 9 | diff = target - Double(node.val) 10 | res = node.val 11 | } 12 | dfs(node.left) 13 | dfs(node.right) 14 | } 15 | dfs(root) 16 | return res 17 | } -------------------------------------------------------------------------------- /Easy/Excel Sheet Column Number.swift: -------------------------------------------------------------------------------- 1 | //Excel Sheet Column Number 2 | //O(n), O(n) 3 | func titleToNumber(_ columnTitle: String) -> Int { 4 | var dict = [Character: Int]() 5 | 6 | for (index,char) in "ABCDEFGHIJKLMNOPQRSTUVWXYZ".enumerated() { 7 | dict[char] = index+1 8 | } 9 | 10 | var res = 0 11 | let arr = Array(columnTitle.reversed()) 12 | for i in 0.. Int { 4 | var res = 0 5 | let arr = Array(s) 6 | var l = 0, r = 0 7 | var dict = [Character: Int]() 8 | while r 1 { 12 | let leftChar = arr[l] 13 | dict[leftChar]! -= 1 14 | l += 1 15 | } 16 | res = max(res, r-l+1) 17 | r += 1 18 | } 19 | return res 20 | } -------------------------------------------------------------------------------- /Medium/Maximum Value of an Ordered Triplet II.swift: -------------------------------------------------------------------------------- 1 | // Maximum Value of an Ordered Triplet II 2 | // O(n), O(n) 3 | func maximumTripletValue(_ nums: [Int]) -> Int { 4 | let n = nums.endIndex 5 | var prefix_max = nums.map { $0 } 6 | var suffix_max = nums.map { $0 } 7 | for i in 1.. Int { 4 | let arr = Array(customers) + ["N"] 5 | var index = 0 6 | var p = 0 7 | for char in arr { 8 | if char == "Y" { 9 | p += 1 10 | } 11 | } 12 | var minP = p 13 | for i in 1.. p { 20 | minP = p 21 | index = i 22 | } 23 | } 24 | return index 25 | } -------------------------------------------------------------------------------- /Medium/Minimum Rounds to Complete All Tasks.swift: -------------------------------------------------------------------------------- 1 | //Minimum Rounds to Complete All Tasks 2 | //O(n), O(n) 3 | func minimumRounds(_ tasks: [Int]) -> Int { 4 | var dict = [Int: Int]() 5 | for task in tasks { 6 | dict[task, default:0] += 1 7 | } 8 | 9 | var res = 0 10 | for count in dict.values { 11 | if count == 1 { 12 | return -1 13 | } else if count % 3 == 0 { 14 | res += count / 3 15 | } else { 16 | res += count / 3 + 1 17 | } 18 | } 19 | return res 20 | } -------------------------------------------------------------------------------- /Medium/Single Element in a Sorted Array.swift: -------------------------------------------------------------------------------- 1 | //Single Element in a Sorted Array 2 | //O(n), O(1) 3 | func singleNonDuplicate(_ nums: [Int]) -> Int { 4 | nums.reduce(0, ^) 5 | } 6 | 7 | //O(log n), O(1) 8 | func singleNonDuplicate(_ nums: [Int]) -> Int { 9 | var l = 0, r = nums.endIndex - 1 10 | while l>1 12 | if mid%2==0 && nums[mid] == nums[mid+1] || mid%2==1 && nums[mid] == nums[mid-1] { 13 | l = mid+1 14 | } else { 15 | r = mid 16 | } 17 | } 18 | return nums[l] 19 | } -------------------------------------------------------------------------------- /Medium/Solving Questions With Brainpower.swift: -------------------------------------------------------------------------------- 1 | //Solving Questions With Brainpower 2 | //O(n), O(n) 3 | func mostPoints(_ questions: [[Int]]) -> Int { 4 | var dp = questions.map {_ in 0} 5 | let len = questions.endIndex 6 | dp[len-1] = questions[len-1][0] 7 | for i in (0.. [Int] { 4 | var dict = [Int:Int]() 5 | for (i,n) in B.enumerated() { 6 | dict[n] = i 7 | } 8 | var res = [Int]() 9 | for n in A { 10 | res.append(dict[n]!) 11 | } 12 | return res 13 | } 14 | 15 | func anagramMappings(_ A: [Int], _ B: [Int]) -> [Int] { 16 | var dict = [Int:Int]() 17 | for (i,n) in B.enumerated() { 18 | dict[n] = i 19 | } 20 | return A.compactMap {dict[$0]} 21 | } -------------------------------------------------------------------------------- /Easy/Find Smallest Letter Greater Than Target.swift: -------------------------------------------------------------------------------- 1 | // Find Smallest Letter Greater Than Target 2 | //O(n), O(1) 3 | func nextGreatestLetter(_ letters: [Character], _ target: Character) -> Character { 4 | var res: Character? 5 | for char in letters { 6 | if char > target { 7 | if let curr = res { 8 | if char < curr { 9 | res = char 10 | } 11 | } else { 12 | res = char 13 | } 14 | 15 | } 16 | } 17 | return res ?? letters[0] 18 | } -------------------------------------------------------------------------------- /Easy/Maximum Odd Binary Number.swift: -------------------------------------------------------------------------------- 1 | // Maximum Odd Binary Number 2 | // O(n), O(n) 3 | func maximumOddBinaryNumber(_ s: String) -> String { 4 | var arr = Array(s) 5 | var r = arr.endIndex-1 6 | var l = 0 7 | while l < r { 8 | if arr[l] == "1" { 9 | (arr[l], arr[r]) = (arr[r], arr[l]) 10 | break 11 | } 12 | l += 1 13 | } 14 | l = 0 15 | r = 0 16 | while r < arr.endIndex-1 { 17 | if arr[r] == "1" { 18 | (arr[l], arr[r]) = (arr[r], arr[l]) 19 | l += 1 20 | } 21 | r += 1 22 | } 23 | return String(arr) 24 | } -------------------------------------------------------------------------------- /Medium/Least Number of Unique Integers after K Removals.swift: -------------------------------------------------------------------------------- 1 | // Least Number of Unique Integers after K Removals 2 | // O(n log n), O(n) 3 | func findLeastNumOfUniqueInts(_ arr: [Int], _ k: Int) -> Int { 4 | var memo = [Int: Int]() 5 | for n in arr { 6 | memo[n, default: 0] += 1 7 | } 8 | var arr = [(Int, Int)]() 9 | for (key, val) in memo { 10 | arr.append((key, val)) 11 | } 12 | arr.sort { a, b in a.1 < b.1 } 13 | var i = 0 14 | var k = k 15 | while i < arr.endIndex, arr[i].1 <= k { 16 | k -= arr[i].1 17 | i += 1 18 | } 19 | return arr.endIndex - i 20 | } -------------------------------------------------------------------------------- /Easy/Make The String Great.swift: -------------------------------------------------------------------------------- 1 | //Make The String Great 2 | //O(n), O(n) 3 | func makeGood(_ s: String) -> String { 4 | var stack = [Character]() 5 | next: for char in s { 6 | if !stack.isEmpty { 7 | if (stack.last!.isLowercase && String(char) == stack.last!.uppercased()) || 8 | (stack.last!.isUppercase && String(char) == stack.last!.lowercased()) { 9 | stack.removeLast() 10 | continue next 11 | } 12 | } 13 | stack.append(char) 14 | } 15 | return String(stack) 16 | } -------------------------------------------------------------------------------- /Medium/K Radius Subarray Averages.swift: -------------------------------------------------------------------------------- 1 | // K Radius Subarray Averages 2 | // O(n),O(1) 3 | func getAverages(_ nums: [Int], _ k: Int) -> [Int] { 4 | if k == 0 { 5 | return nums 6 | } 7 | let n = nums.endIndex 8 | var res = (0.. Int { 4 | var res = 0 5 | for i in 0.. [[Int]] { 4 | let set1 = Set(nums1) 5 | var res1 = Set() 6 | for n in nums2 { 7 | if set1.contains(n) == false { 8 | res1.insert(n) 9 | } 10 | } 11 | let set2 = Set(nums2) 12 | var res2 = Set() 13 | for n in nums1 { 14 | if set2.contains(n) == false { 15 | res2.insert(n) 16 | } 17 | } 18 | return [Array(res2),Array(res1)] 19 | } -------------------------------------------------------------------------------- /Medium/Kill Process.swift: -------------------------------------------------------------------------------- 1 | //Kill Process 2 | //O(n) O(n) 3 | func killProcess(_ pid: [Int], _ ppid: [Int], _ kill: Int) -> [Int] { 4 | var graph = [Int:[Int]]() 5 | 6 | for (node, parent) in zip(pid,ppid) { 7 | graph[parent, default:[]].append(node) 8 | } 9 | var res = [Int]() 10 | var queue = [kill] 11 | while queue.isEmpty == false { 12 | let node = queue.removeFirst() 13 | res.append(node) 14 | for child in graph[node, default:[]] { 15 | queue.append(child) 16 | } 17 | } 18 | return res 19 | } -------------------------------------------------------------------------------- /Medium/Remove Nodes From Linked List.swift: -------------------------------------------------------------------------------- 1 | // Remove Nodes From Linked List 2 | // O(n), O(n) 3 | func removeNodes(_ head: ListNode?) -> ListNode? { 4 | var queue = [ListNode]() 5 | let dummy = ListNode(Int.max) 6 | queue.append(dummy) 7 | var curr = head 8 | while curr != nil { 9 | while !queue.isEmpty && queue.last!.val < curr!.val { 10 | queue.removeLast() 11 | } 12 | queue.append(curr!) 13 | curr = curr!.next 14 | } 15 | var prev = queue.removeFirst() 16 | for node in queue { 17 | prev.next = node 18 | prev = node 19 | } 20 | return dummy.next 21 | } -------------------------------------------------------------------------------- /Medium/Remove Zero Sum Consecutive Nodes from Linked List.swift: -------------------------------------------------------------------------------- 1 | // Remove Zero Sum Consecutive Nodes from Linked List 2 | // O(n^2), O(1) 3 | func removeZeroSumSublists(_ head: ListNode?) -> ListNode? { 4 | var root = ListNode(0, head) 5 | var curr: ListNode? = root 6 | while curr != nil { 7 | var end = curr!.next 8 | var prefixSum = 0 9 | while end != nil { 10 | prefixSum += end!.val 11 | if prefixSum == 0 { 12 | curr!.next = end!.next 13 | } 14 | end = end!.next 15 | } 16 | curr = curr!.next 17 | } 18 | return root.next 19 | } -------------------------------------------------------------------------------- /Easy/Find Words That Can Be Formed by Characters.swift: -------------------------------------------------------------------------------- 1 | // Find Words That Can Be Formed by Characters 2 | // O(n), O(n) 3 | func countCharacters(_ words: [String], _ chars: String) -> Int { 4 | var res = 0 5 | var dict = [Character: Int]() 6 | for char in Array(chars) { 7 | dict[char, default: 0] += 1 8 | } 9 | next: for word in words { 10 | var curr = dict 11 | for char in word { 12 | curr[char, default: 0] -= 1 13 | if curr[char, default: 0] == -1 { 14 | continue next 15 | } 16 | } 17 | res += word.count 18 | } 19 | return res 20 | } -------------------------------------------------------------------------------- /Medium/Insertion Sort List.swift: -------------------------------------------------------------------------------- 1 | //Insertion Sort List 2 | //O(n^2), O(1) 3 | func insertionSortList(_ head: ListNode?) -> ListNode? { 4 | let d = ListNode() 5 | var curr = head 6 | while curr != nil { 7 | let temp = curr!.next 8 | curr!.next = nil 9 | var p = d.next 10 | var prev = d 11 | while p != nil && p!.val < curr!.val { 12 | prev = p! 13 | p = p!.next 14 | } 15 | prev.next = curr 16 | curr!.next = p 17 | curr = temp 18 | } 19 | 20 | return d.next 21 | } -------------------------------------------------------------------------------- /Medium/Merge In Between Linked Lists.swift: -------------------------------------------------------------------------------- 1 | // Merge In Between Linked Lists 2 | // O(n), O(1) 3 | func mergeInBetween(_ list1: ListNode?, _ a: Int, _ b: Int, _ list2: ListNode?) -> ListNode? { 4 | var head = ListNode(0, list1) 5 | var curr: ListNode? = head 6 | var start: ListNode? 7 | for i in 0...b { 8 | if i == a { start = curr } 9 | curr = curr!.next 10 | } 11 | let end = curr!.next 12 | start!.next = list2 13 | curr = list2 14 | var prev: ListNode? 15 | while curr != nil { 16 | prev = curr 17 | curr = curr!.next 18 | } 19 | prev!.next = end 20 | return head.next 21 | } -------------------------------------------------------------------------------- /Medium/Queue Reconstruction by Height.swift: -------------------------------------------------------------------------------- 1 | //Queue Reconstruction by Height 2 | //O(n^2), O(n) 3 | func reconstructQueue(_ people: [[Int]]) -> [[Int]] { 4 | let arr = people.sorted { a,b in 5 | if a[0] == b[0] { 6 | return a[1] < b[1] 7 | } 8 | return a[0] > b[0] 9 | } 10 | 11 | var res = [[Int]]() 12 | for item in arr { 13 | if res.count < item[1] { 14 | res.append(item) 15 | } else { 16 | res.insert(item, at: item[1]) 17 | } 18 | 19 | } 20 | return res 21 | } -------------------------------------------------------------------------------- /Medium/Robot Bounded In Circle.swift: -------------------------------------------------------------------------------- 1 | //Robot Bounded In Circle 2 | //O(n), O(1) 3 | func isRobotBounded(_ instructions: String) -> Bool { 4 | var x = 0, y = 0, dx = 0, dy = 1 5 | for char in instructions { 6 | switch char { 7 | case "R": 8 | (dx, dy) = (dy, -dx) 9 | case "L": 10 | (dx, dy) = (-dy, dx) 11 | case "G": 12 | x+=dx 13 | y+=dy 14 | default: 15 | break 16 | } 17 | } 18 | return x==0 && y==0 || !(dx == 0 && dy == 1) 19 | } -------------------------------------------------------------------------------- /Easy/Largest Local Values in a Matrix.swift: -------------------------------------------------------------------------------- 1 | // Largest Local Values in a Matrix 2 | // O(n), O(n) 3 | func largestLocal(_ grid: [[Int]]) -> [[Int]] { 4 | var res = [[Int]]() 5 | let rows = grid.endIndex, cols = grid[0].endIndex 6 | for row in 0.. [Int] { 4 | var res = [Int]() 5 | let rows = nums.endIndex 6 | var groups = [Int:[Int]]() 7 | for row in (0.. Int { 5 | if n == 0 { return 0 } 6 | if n == 1 { return k } 7 | if n == 2 { return k*k } 8 | var dp = [Int](repeating: 0, count: n+1) 9 | dp[1] = k 10 | dp[2] = k*k 11 | for i in 3...n { 12 | dp[i] = (dp[i-1] + dp[i-2]) * (k-1) 13 | } 14 | return dp[n] 15 | } 16 | } 17 | 18 | /* 19 | numWays(i) = diff(i) + same(i) 20 | diff(i) = numWays(i-1) * (k-1) 21 | same(i) = diff(i-1) * 1 22 | 23 | numWays(i) = (numWays(i-1) + numWays(i-2)) * (k-1) 24 | 25 | */ -------------------------------------------------------------------------------- /Medium/Shuffle an Array.swift: -------------------------------------------------------------------------------- 1 | //Shuffle an Array 2 | class Solution { 3 | let arr : [Int] 4 | init(_ nums: [Int]) { 5 | arr = nums 6 | } 7 | 8 | /** Resets the array to its original configuration and return it. */ 9 | func reset() -> [Int] { 10 | return arr 11 | } 12 | 13 | /** Returns a random shuffling of the array. */ 14 | func shuffle() -> [Int] { 15 | var sArr = arr 16 | for i in 0.. Int { 12 | var l = 0, r = arr.endIndex 13 | while l>1 15 | if arr[mid] < val { 16 | l = mid+1 17 | } else { 18 | r = mid 19 | } 20 | } 21 | arr.insert(val, at: l) 22 | return arr[arr.endIndex-k] 23 | } 24 | } -------------------------------------------------------------------------------- /Medium/Combination Sum.swift: -------------------------------------------------------------------------------- 1 | /*Combination Sum*/ 2 | //time O(n!) space O(n) 3 | func combinationSum(_ candidates: [Int], _ target: Int) -> [[Int]] { 4 | var res = [[Int]]() 5 | 6 | func dfs(_ path: [Int], _ rest: Int, _ index: Int) { 7 | if rest < 0 {return} 8 | if rest == 0 { 9 | res.append(path) 10 | return 11 | } 12 | for i in index.. Bool { 4 | var alice = 0, bob = 0 5 | let arr = Array(colors) 6 | if arr.endIndex == 1 {return false} 7 | for i in 1..= 1 17 | } -------------------------------------------------------------------------------- /Easy/Find First Palindromic String in the Array.swift: -------------------------------------------------------------------------------- 1 | // Find First Palindromic String in the Array 2 | // O(n), O(n) 3 | func firstPalindrome(_ words: [String]) -> String { 4 | for word in words { 5 | let arr = Array(word) 6 | var l = 0, r = arr.endIndex-1 7 | var isPalindrome = true 8 | while l [Bool] { 4 | 5 | func isArithmetic(_ arr: [Int]) -> Bool { 6 | let arr = arr.sorted() 7 | let d = arr[0] - arr[1] 8 | for i in 1.. Int { 4 | func rev(_ n: Int) -> Int { 5 | var res = 0 6 | var n = n 7 | while n > 0 { 8 | res = res * 10 + n % 10 9 | n /= 10 10 | } 11 | return res 12 | } 13 | 14 | var arr = [Int]() 15 | for n in nums { 16 | arr.append(n-rev(n)) 17 | } 18 | var dict = [Int: Int]() 19 | var res = 0 20 | for n in arr { 21 | res = (res + dict[n, default: 0]) % Int(1E9+7) 22 | dict[n, default:0] += 1 23 | } 24 | return res 25 | } -------------------------------------------------------------------------------- /Easy/Reverse Linked List.swift: -------------------------------------------------------------------------------- 1 | /*Reverse Linked List*/ 2 | //time O(n) space O(1) 3 | func reverseList(_ head: ListNode?) -> ListNode? { 4 | var prev: ListNode? = nil 5 | var curr = head 6 | while curr != nil { 7 | var temp = curr!.next 8 | curr!.next = prev 9 | prev = curr 10 | curr = temp 11 | } 12 | return prev 13 | } 14 | //recursive time O(n) space O(1) 15 | func reverseList(_ head: ListNode?) -> ListNode? { 16 | if head == nil || head!.next == nil{ 17 | return head 18 | } 19 | var node = reverseList(head!.next) 20 | head!.next!.next = head 21 | head!.next = nil 22 | return node 23 | } -------------------------------------------------------------------------------- /Hard/Orderly Queue.swift: -------------------------------------------------------------------------------- 1 | //Orderly Queue 2 | //O(n^2), O(n) 3 | /* 4 | If k = 1, only rotations of s are possible, and the answer is the lexicographically smallest rotation. 5 | 6 | If k > 1, any permutation of s is possible, and the answer is the letters of s written in lexicographic order. 7 | */ 8 | func orderlyQueue(_ s: String, _ k: Int) -> String { 9 | let arr = Array(s) 10 | 11 | if k == 1 { 12 | var res = s 13 | for i in 0.. [Int] { 4 | guard let node = root else {return []} 5 | 6 | var stack = [node] 7 | var res = [Int]() 8 | while stack.isEmpty == false { 9 | let temp = stack 10 | stack.removeAll() 11 | res.append(temp.last!.val) 12 | for curr in temp { 13 | if curr.left != nil {stack.append(curr.left!)} 14 | if curr.right != nil {stack.append(curr.right!)} 15 | } 16 | 17 | } 18 | return res 19 | } -------------------------------------------------------------------------------- /Easy/Reverse Linked List II.swift: -------------------------------------------------------------------------------- 1 | //Reverse Linked List II 2 | //O(n), O(1) 3 | func reverseBetween(_ head: ListNode?, _ left: Int, _ right: Int) -> ListNode? { 4 | if head == nil {return nil} 5 | let d = ListNode(0) 6 | d.next = head 7 | var prev: ListNode? = d 8 | for i in 0.. Bool { 4 | let set = Set(Array(sentence)) 5 | for char in "abcdefghijklmnopqrstuvwxyz" { 6 | if set.contains(char) == false { 7 | return false 8 | } 9 | } 10 | return true 11 | } 12 | 13 | //O(n), O(1) 14 | func checkIfPangram(_ sentence: String) -> Bool { 15 | for char in "abcdefghijklmnopqrstuvwxyz" { 16 | if sentence.contains(char) == false { 17 | return false 18 | } 19 | } 20 | return true 21 | } -------------------------------------------------------------------------------- /Easy/Number of 1 Bits.swift: -------------------------------------------------------------------------------- 1 | /*Number of 1 Bits*/ 2 | func hammingWeight(_ n: Int) -> Int { 3 | var n = n 4 | var res = 0 5 | while n != 0 { 6 | res += n & 1 7 | n >>= 1 8 | } 9 | return res 10 | } 11 | func hammingWeight(_ n: Int) -> Int { 12 | var res = 0 13 | var n = n 14 | while n != 0 { 15 | res += n%2 16 | n >>= 1 17 | } 18 | return res 19 | } 20 | 21 | func hammingWeight(_ n: Int) -> Int { 22 | var res = 0 23 | for i in 0..<32 { 24 | let mask = Int(NSDecimalNumber(decimal: pow(2,i))) 25 | if n & mask != 0 { 26 | res += 1 27 | } 28 | } 29 | return res 30 | } -------------------------------------------------------------------------------- /Hard/Stone Game IV.swift: -------------------------------------------------------------------------------- 1 | //Stone Game IV 2 | //O(n√n), O(√n) 3 | func winnerSquareGame(_ n: Int) -> Bool { 4 | var dict = [Int: Bool]() 5 | func dfs(_ r: Int) -> Bool { 6 | if r == 0 {return false} 7 | if r == 1 {return true} 8 | if dict[r] != nil {return dict[r]!} 9 | let sqrtRoot = Int(sqrt(Double(r))) 10 | for i in 1...sqrtRoot { 11 | if dfs(r - i*i) == false { 12 | dict[r] = true 13 | return true 14 | } 15 | } 16 | dict[r] = false 17 | return false 18 | } 19 | return dfs(n) 20 | } -------------------------------------------------------------------------------- /Medium/Next Permutation.swift: -------------------------------------------------------------------------------- 1 | //Next Permutation 2 | //O(n) 3 | func nextPermutation(_ nums: inout [Int]) { 4 | var i = nums.endIndex - 2 5 | while i >= 0 && nums[i] >= nums[i+1] { 6 | i -= 1 7 | } 8 | if i >= 0 { 9 | var j = nums.endIndex - 1 10 | 11 | while j >= 0 && nums[i] >= nums[j] { 12 | j -= 1 13 | } 14 | (nums[i],nums[j]) = (nums[j],nums[i]) 15 | } 16 | var l = i + 1, r = nums.endIndex - 1 17 | while l < r { 18 | (nums[l],nums[r]) = (nums[r],nums[l]) 19 | l += 1 20 | r -= 1 21 | } 22 | } -------------------------------------------------------------------------------- /Easy/Destination City.swift: -------------------------------------------------------------------------------- 1 | // Destination City 2 | // O(n), O(n) 3 | func destCity(_ paths: [[String]]) -> String { 4 | var graph = [String: [String]]() 5 | for path in paths { 6 | let a = path[0], b = path[1] 7 | graph[a, default:[]].append(b) 8 | } 9 | var queue = [paths[0][0]] 10 | while !queue.isEmpty { 11 | let temp = queue 12 | queue = [] 13 | for node in temp { 14 | if graph[node, default:[]].count == 0 { 15 | return node 16 | } 17 | for nextNode in graph[node]! { 18 | queue.append(nextNode) 19 | } 20 | } 21 | } 22 | return "" 23 | } -------------------------------------------------------------------------------- /Easy/Read N Characters Given Read4.swift: -------------------------------------------------------------------------------- 1 | //Read N Characters Given Read4 2 | class Solution : Reader4 { 3 | var curr = [Character](repeating:Character(" "), count:4) 4 | var index = 0 5 | var count = 0 6 | func read(_ buf: inout [Character], _ n: Int) -> Int { 7 | var res = 0 8 | for i in 0.. 0 { 14 | buf[i] = curr[index] 15 | index += 1 16 | count -= 1 17 | res += 1 18 | } 19 | 20 | } 21 | return res 22 | } 23 | } -------------------------------------------------------------------------------- /Medium/Maximum Number of Coins You Can Get.swift: -------------------------------------------------------------------------------- 1 | // Maximum Number of Coins You Can Get 2 | // O(n log n), O(n) 3 | func maxCoins(_ piles: [Int]) -> Int { 4 | var res = 0 5 | var arr = piles.sorted() 6 | while !arr.isEmpty { 7 | let alice = arr.removeLast() 8 | let us = arr.removeLast() 9 | res += us 10 | let bob = arr.removeFirst() 11 | } 12 | return res 13 | } 14 | 15 | // O(n log n), O(n) 16 | func maxCoins(_ piles: [Int]) -> Int { 17 | var res = 0 18 | let arr = piles.sorted() 19 | let n = arr.endIndex 20 | var i = n/3 21 | while i < n { 22 | res += arr[i] 23 | i += 2 24 | } 25 | return res 26 | } -------------------------------------------------------------------------------- /Medium/ZigZag Conversion.swift: -------------------------------------------------------------------------------- 1 | //ZigZag Conversion 2 | // 3 | func convert(_ s: String, _ numRows: Int) -> String { 4 | if numRows == 1 {return s} 5 | var rows = [[Character]](repeating: [], count: numRows) 6 | var index = 0 7 | var isDown = false 8 | for char in s { 9 | rows[index].append(char) 10 | if index == 0 || index == numRows-1 { 11 | isDown = !isDown 12 | } 13 | index += isDown ? 1 : -1 14 | } 15 | return String(rows.reduce([], +)) 16 | } 17 | let input = "PAYPALISHIRING" 18 | let input2 = 4 19 | print(convert(input,input2) == "PINALSIGYAHRPI") 20 | -------------------------------------------------------------------------------- /Easy/Island Perimeter.swift: -------------------------------------------------------------------------------- 1 | //Island Perimeter 2 | //O(n), O(1) 3 | func islandPerimeter(_ grid: [[Int]]) -> Int { 4 | let rows = grid.endIndex, cols = grid[0].endIndex 5 | var res = 0 6 | for i in 0..= 0 && grid[i-1][j] == 1 { 11 | res -= 2 12 | } 13 | if j-1 >= 0 && grid[i][j-1] == 1 { 14 | res -= 2 15 | } 16 | } 17 | 18 | } 19 | } 20 | return res 21 | } -------------------------------------------------------------------------------- /Easy/Maximum Score After Splitting a String.swift: -------------------------------------------------------------------------------- 1 | // Maximum Score After Splitting a String 2 | // O(n), O(n) 3 | func maxScore(_ s: String) -> Int { 4 | var ones = 0 5 | for char in s { 6 | if char == "1" { 7 | ones += 1 8 | } 9 | } 10 | var res = 0 11 | var zeros = 0 12 | let arr = Array(s) 13 | 14 | for i in 0.. String { 4 | let arr1 = Array(word1), arr2 = Array(word2) 5 | var res = [Character]() 6 | var i = 0 7 | while i < arr1.endIndex && i= val { 8 | minStack.append(val) 9 | } 10 | } 11 | 12 | func pop() { 13 | let last = arr.removeLast() 14 | if let minArrLast = minArr.last { 15 | if minArrLast == last { 16 | minArr.removeLast() 17 | } 18 | } 19 | } 20 | 21 | func top() -> Int { 22 | arr.last ?? 0 23 | } 24 | 25 | func getMin() -> Int { 26 | minArr.last ?? 0 27 | } 28 | } -------------------------------------------------------------------------------- /Medium/Special Array II.swift: -------------------------------------------------------------------------------- 1 | // Special Array II 2 | // O(n), O(n) 3 | func isArraySpecial(_ nums: [Int], _ queries: [[Int]]) -> [Bool] { 4 | var memo = [Int: Int]() 5 | var l = 0 6 | var interval_index = 0 7 | for i in 1.. String { 3 | var res = "1" 4 | if n == 1 {return res} 5 | for i in 2...n { 6 | let sArr = Array(res) 7 | res = "" 8 | var c = sArr[0] 9 | var count = 0 10 | for char in sArr { 11 | if c == char { 12 | count += 1 13 | } else { 14 | res += String(count) + String(c) 15 | c = char 16 | count = 1 17 | } 18 | } 19 | res += String(count) + String(c) 20 | } 21 | return res 22 | } -------------------------------------------------------------------------------- /Medium/Find Unique Binary String.swift: -------------------------------------------------------------------------------- 1 | // Find Unique Binary String 2 | // O(n), O(n) 3 | func findDifferentBinaryString(_ nums: [String]) -> String { 4 | let n = nums.endIndex 5 | var set = Set(nums) 6 | 7 | func toBinary(_ num: Int) -> String { 8 | var num = num 9 | var res = "" 10 | for i in 0..>= 1 13 | } 14 | return res 15 | } 16 | let maxN: Int = Int(pow(2.0, Double(n))) 17 | for i in 0.. Int { 4 | var res = 0 5 | var l = 0, r = 0 6 | var count = 1 7 | var ones = 0 8 | while r < nums.endIndex { 9 | ones += 1 10 | if nums[r] == 0 { 11 | count -= 1 12 | } 13 | while count < 0 { 14 | ones -= 1 15 | if nums[l] == 0 { 16 | count += 1 17 | } 18 | l += 1 19 | } 20 | res = max(ones,res) 21 | r += 1 22 | } 23 | return res 24 | } -------------------------------------------------------------------------------- /Medium/N-ary Tree Preorder Traversal.swift: -------------------------------------------------------------------------------- 1 | //N-ary Tree Preorder Traversal 2 | //O(n) O(h) 3 | func preorder(_ root: Node?) -> [Int] { 4 | guard let node = root else {return []} 5 | var res = [node.val] 6 | res += node.children.flatMap { preorder($0) } 7 | return res 8 | } 9 | //O(n) O(w) 10 | func preorder(_ root: Node?) -> [Int] { 11 | guard let node = root else {return []} 12 | var res = [Int]() 13 | var stack = [node] 14 | while stack.isEmpty == false { 15 | let curr = stack.removeFirst() 16 | res.append(curr.val) 17 | stack = curr.children + stack 18 | } 19 | return res 20 | } -------------------------------------------------------------------------------- /Medium/Top K Frequent Words.swift: -------------------------------------------------------------------------------- 1 | //Top K Frequent Words 2 | //O(n log n), O(n) 3 | func topKFrequent(_ words: [String], _ k: Int) -> [String] { 4 | var dict = [String: Int]() 5 | for word in words { 6 | dict[word, default: 0] += 1 7 | } 8 | let arr = dict.sorted { a, b in 9 | if a.value != b.value { 10 | return a.value > b.value 11 | } 12 | return a.key < b.key 13 | } 14 | .map { $0.key } 15 | 16 | return Array(arr.prefix(k)) 17 | } -------------------------------------------------------------------------------- /Hard/Count Subarrays With Fixed Bounds.swift: -------------------------------------------------------------------------------- 1 | //Count Subarrays With Fixed Bounds 2 | //O(n), O(1) 3 | func countSubarrays(_ nums: [Int], _ minK: Int, _ maxK: Int) -> Int { 4 | var leftBound = -1, lastMin = -1, lastMax = -1, count = 0 5 | for i in 0..= minK && nums[i] <= maxK { 7 | if nums[i] == minK {lastMin = i} 8 | if nums[i] == maxK {lastMax = i} 9 | count += max(0, min(lastMin, lastMax) - leftBound) 10 | } else { 11 | leftBound = i 12 | lastMin = -1 13 | lastMax = -1 14 | } 15 | } 16 | return count 17 | } -------------------------------------------------------------------------------- /Medium/Find the Index of the First Occurrence in a String.swift: -------------------------------------------------------------------------------- 1 | // Find the Index of the First Occurrence in a String 2 | //O(haystack*needle), O(haystack+needle) 3 | func strStr(_ haystack: String, _ needle: String) -> Int { 4 | let arr1 = Array(haystack), arr2 = Array(needle) 5 | if arr1.endIndex < arr2.endIndex {return -1} 6 | next: for i in 0..= arr1.endIndex || arr1[i+j] != arr2[j] { 10 | continue next 11 | } 12 | j += 1 13 | } 14 | return i 15 | } 16 | return -1 17 | } -------------------------------------------------------------------------------- /Medium/Stone Game VII.swift: -------------------------------------------------------------------------------- 1 | //Stone Game VII 2 | //O(n^2), O(n^2) 3 | func stoneGameVII(_ stones: [Int]) -> Int { 4 | let n = stones.endIndex 5 | var dp = (0.. Int { 11 | if i == j {return 0} 12 | if dp[i][j] == 0 { 13 | let sum = psum[j+1] - psum[i] 14 | dp[i][j] = max(sum-stones[i] - dfs(i+1,j), sum-stones[j]-dfs(i,j-1)) 15 | } 16 | return dp[i][j] 17 | } 18 | 19 | return dfs(0, n-1) 20 | } -------------------------------------------------------------------------------- /Easy/Maximum 69 Number.swift: -------------------------------------------------------------------------------- 1 | //Maximum 69 Number 2 | //O(n), O(n) 3 | func maximum69Number (_ num: Int) -> Int { 4 | var arr = [Int]() 5 | var n = num 6 | while n > 0 { 7 | let curr = n % 10 8 | n /= 10 9 | arr.insert(curr, at: 0) 10 | } 11 | 12 | for i in 0.. [Int] { 4 | var dict = [Int: Int]() 5 | for (i,n) in nums2.enumerated() { 6 | dict[n] = i 7 | } 8 | var res = [Int]() 9 | for n in nums1 { 10 | var i = dict[n]! 11 | var curr = -1 12 | while i < nums2.endIndex { 13 | if nums2[i] > n { 14 | curr = nums2[i] 15 | break 16 | } 17 | i += 1 18 | } 19 | res.append(curr) 20 | } 21 | return res 22 | } -------------------------------------------------------------------------------- /Hard/Maximum Frequency Stack.swift: -------------------------------------------------------------------------------- 1 | //Maximum Frequency Stack 2 | // space O(n) 3 | class FreqStack { 4 | var freq = [Int: Int]() 5 | var freqToStack = [Int: [Int]]() 6 | var maxFreq = 0 7 | 8 | func push(_ val: Int) { 9 | freq[val, default: 0] += 1 10 | let freq = freq[val]! 11 | if freq > maxFreq { 12 | maxFreq = freq 13 | } 14 | freqToStack[freq, default: []].append(val) 15 | } 16 | 17 | func pop() -> Int { 18 | let val = freqToStack[maxFreq]!.removeLast() 19 | freq[val]! -= 1 20 | if freqToStack[maxFreq]!.count == 0 { 21 | maxFreq -= 1 22 | } 23 | return val 24 | } 25 | } -------------------------------------------------------------------------------- /Medium/Uncrossed Lines.swift: -------------------------------------------------------------------------------- 1 | //Uncrossed Lines 2 | //O(n1*n2), O(n1*n2) 3 | func maxUncrossedLines(_ nums1: [Int], _ nums2: [Int]) -> Int { 4 | var dp = [[Int]](repeating: [Int](repeating: 0, count: nums2.endIndex+1), count: nums1.endIndex+1) 5 | for i in 1...nums1.endIndex { 6 | for j in 1...nums2.endIndex { 7 | if nums1[i-1] == nums2[j-1] { 8 | dp[i][j] = max(dp[i-1][j-1]+1, dp[i-1][j], dp[i][j-1]) 9 | } else { 10 | dp[i][j] = max(dp[i-1][j-1], dp[i-1][j], dp[i][j-1]) 11 | } 12 | 13 | } 14 | } 15 | return dp[nums1.endIndex][nums2.endIndex] 16 | } -------------------------------------------------------------------------------- /Easy/Average of Levels in Binary Tree.swift: -------------------------------------------------------------------------------- 1 | //Average of Levels in Binary Tree 2 | //O(n), O(1) 3 | func averageOfLevels(_ root: TreeNode?) -> [Double] { 4 | guard let node = root else {return []} 5 | var queue = [node], res = [Double]() 6 | while !queue.isEmpty { 7 | let temp = queue 8 | queue.removeAll() 9 | var value = 0 10 | for curr in temp { 11 | value += curr.val 12 | if let left = curr.left {queue.append(left)} 13 | if let right = curr.right {queue.append(right)} 14 | } 15 | res.append(Double(value)/Double(temp.count)) 16 | } 17 | return res 18 | } -------------------------------------------------------------------------------- /Easy/Baseball Game.swift: -------------------------------------------------------------------------------- 1 | //Baseball Game 2 | //O(n),O(n) 3 | func calPoints(_ ops: [String]) -> Int { 4 | var arr = [Int]() 5 | for op in ops { 6 | switch op { 7 | case "+": 8 | let n = arr[arr.endIndex-1] + arr[arr.endIndex-2] 9 | arr.append(n) 10 | case "D": 11 | let n = arr[arr.endIndex-1] * 2 12 | arr.append(n) 13 | case "C": 14 | arr.removeLast() 15 | default: 16 | let n = Int(op)! 17 | arr.append(n) 18 | } 19 | } 20 | return arr.reduce(0,+) 21 | } -------------------------------------------------------------------------------- /Hard/Reconstruct Itinerary.swift: -------------------------------------------------------------------------------- 1 | // Reconstruct Itinerary 2 | // O(n log n), O(n) 3 | func findItinerary(_ tickets: [[String]]) -> [String] { 4 | var graph = [String: [String]]() 5 | let arr = tickets.sorted { a,b in 6 | return a[1] > b[1] 7 | } 8 | for item in arr { 9 | let src = item[0] 10 | let dst = item[1] 11 | graph[src, default: []].append(dst) 12 | } 13 | var res = [String]() 14 | func dfs(_ airport: String) { 15 | while graph[airport] != nil && !graph[airport]!.isEmpty { 16 | dfs(graph[airport]!.removeLast()) 17 | } 18 | res.append(airport) 19 | } 20 | dfs("JFK") 21 | 22 | return res.reversed() 23 | } -------------------------------------------------------------------------------- /Easy/Isomorphic Strings.swift: -------------------------------------------------------------------------------- 1 | /*Isomorphic Strings*/ 2 | //time O(s+t) space O(s+t) 3 | func isIsomorphic(_ s: String, _ t: String) -> Bool { 4 | var m1 = [Character:Character](), m2 = [Character:Character]() 5 | let sArr = Array(s), tArr = Array(t) 6 | if sArr.endIndex != tArr.endIndex {return false} 7 | 8 | for (char1, char2) in zip(sArr,tArr) { 9 | if m1[char1] == nil && m2[char2] == nil { 10 | m1[char1] = char2 11 | m2[char2] = char1 12 | } else if m1[char1] == nil || m2[char2] == nil { 13 | return false 14 | } else if m1[char1]! != char2 || m2[char2]! != char1 { 15 | return false 16 | } 17 | } 18 | return true 19 | } -------------------------------------------------------------------------------- /Easy/Relative Ranks.swift: -------------------------------------------------------------------------------- 1 | // Relative Ranks 2 | // O(n log n), O(n) 3 | func findRelativeRanks(_ score: [Int]) -> [String] { 4 | var scoreToIndex = [Int: Int]() 5 | let arr = score.sorted(by: >) 6 | for i in 0.. [[Int]] { 5 | var res = grid 6 | let rows = grid.endIndex, cols = grid[0].endIndex 7 | let n = rows*cols 8 | for row in 0.. (row: Int, col: Int) { 19 | return (index/cols, index%cols) 20 | } 21 | } -------------------------------------------------------------------------------- /Easy/Special Positions in a Binary Matrix.swift: -------------------------------------------------------------------------------- 1 | // Special Positions in a Binary Matrix 2 | // O(n), O(1) 3 | func numSpecial(_ mat: [[Int]]) -> Int { 4 | var res = 0 5 | let rows = mat.endIndex, cols = mat[0].endIndex 6 | for row in 0.. Int { 3 | var arr = [Int]() 4 | var cost = 0 5 | 6 | for insertNum in instructions { 7 | var minCount = 0 8 | var maxCount = 0 9 | for n in arr { 10 | if n < insertNum { 11 | minCount += 1 12 | } else if n > insertNum { 13 | maxCount += 1 14 | } 15 | } 16 | arr.insert(insertNum, at: minCount) 17 | cost += min(minCount, maxCount) 18 | } 19 | 20 | return cost 21 | } -------------------------------------------------------------------------------- /Medium/Find Duplicate Subtrees.swift: -------------------------------------------------------------------------------- 1 | //Find Duplicate Subtrees 2 | //O(h), O(n) 3 | func findDuplicateSubtrees(_ root: TreeNode?) -> [TreeNode?] { 4 | var dict = [String: Int](), res = [TreeNode?]() 5 | func dfs(_ node: TreeNode?) -> String { 6 | guard let node = node else {return ""} 7 | let left = dfs(node.left) 8 | let right = dfs(node.right) 9 | let currStr = String(node.val) + "$" + left + "$" + right 10 | if dict[currStr, default: 0] == 1 { 11 | res.append(node) 12 | } 13 | dict[currStr, default:0] += 1 14 | return currStr 15 | } 16 | dfs(root) 17 | return res 18 | } -------------------------------------------------------------------------------- /Medium/Successful Pairs of Spells and Potions.swift: -------------------------------------------------------------------------------- 1 | //Successful Pairs of Spells and Potions 2 | //O(s * p log p), O(p) 3 | func successfulPairs(_ spells: [Int], _ potions: [Int], _ success: Int) -> [Int] { 4 | var res = [Int]() 5 | let arr = potions.sorted() 6 | for s in spells { 7 | var l = 0, r = arr.endIndex 8 | while l>1 10 | if arr[mid] * s < success { 11 | l = mid+1 12 | } else { 13 | r = mid 14 | } 15 | } 16 | let curr = arr.endIndex-l 17 | res.append(curr) 18 | } 19 | return res 20 | } -------------------------------------------------------------------------------- /Hard/Find the Kth Smallest Sum of a Matrix With Sorted Rows.swift: -------------------------------------------------------------------------------- 1 | //Find the Kth Smallest Sum of a Matrix With Sorted Rows 2 | //O(k* n log n) n is rows 3 | func kthSmallest(_ mat: [[Int]], _ k: Int) -> Int { 4 | var arr = mat[0] 5 | let rows = mat.endIndex, cols = mat[0].endIndex 6 | var i = 1 7 | while i < rows { 8 | var nextRow = [Int]() 9 | for j in 0.. [[Int]] { 4 | guard let node = root else {return []} 5 | var queue = [node] 6 | var res = [[Int]]() 7 | while !queue.isEmpty { 8 | let temp = queue 9 | queue.removeAll() 10 | var curr = [Int]() 11 | for node in temp { 12 | curr.append(node.val) 13 | if let left = node.left {queue.append(left)} 14 | if let right = node.right {queue.append(right)} 15 | } 16 | res.insert(curr, at:0) 17 | } 18 | return res 19 | } -------------------------------------------------------------------------------- /Medium/Count Primes.swift: -------------------------------------------------------------------------------- 1 | //Count Primes 2 | //O(n log log n), O(n) 3 | class Solution { 4 | func countPrimes(_ n: Int) -> Int { 5 | var isPrime = (0.. Int { 4 | var res = 0 5 | var a = a, b = b, c = c 6 | while a > 0 || b > 0 || c > 0 { 7 | res += check(a&1,b&1,c&1) 8 | a = a >> 1 9 | b = b >> 1 10 | c = c >> 1 11 | } 12 | return res 13 | 14 | } 15 | func check(_ l: Int, _ r: Int, _ c: Int) -> Int { 16 | if c == 1 { 17 | if l == 0 && r == 0 { 18 | return 1 19 | } 20 | } 21 | if c == 0 { 22 | return l+r 23 | } 24 | return 0 25 | } -------------------------------------------------------------------------------- /Medium/Complex Number Multiplication.swift: -------------------------------------------------------------------------------- 1 | //Complex Number Multiplication 2 | //O(n1+n2), O(n1+n2) 3 | class Solution { 4 | func complexNumberMultiply(_ num1: String, _ num2: String) -> String { 5 | let (r1, i1) = complexN(num1), (r2, i2) = complexN(num2) 6 | // res = r1*r2 + r1*i2 + i1 * r2 + i1 * i2 7 | let a = r1*r2 8 | let b = r1*i2 + i1*r2 9 | let c = i1*i2*(-1) //i^2 = -1 10 | 11 | return "\(a+c)+\(b)i" 12 | } 13 | 14 | func complexN(_ s: String) -> (Int, Int) { 15 | let sArr = String(Array(s)[0.. Int { 4 | var countA = (0..<7).map {_ in 0}, countB = countA, same = countA 5 | for i in 0.. Int { 4 | let rows = grid.endIndex, cols = grid[0].endIndex 5 | var dp = [[Int]](repeating: [Int](repeating: 0, count: cols), count: rows) 6 | dp[0][0] = grid[0][0] 7 | for i in 1.. [Int] { 3 | var i = 0, res = [Int](), v = voyage 4 | func dfs(_ node: TreeNode?) -> Bool { 5 | guard let node = node else {return true} 6 | if node.val != v[i] {return false} 7 | i+=1 8 | if node.left != nil && node.left!.val != v[i] { 9 | res.append(node.val) 10 | return dfs(node.right) && dfs(node.left) 11 | } else { 12 | return dfs(node.left) && dfs(node.right) 13 | } 14 | } 15 | return dfs(root) ? res : [-1] 16 | } -------------------------------------------------------------------------------- /Medium/Redundant Connection.swift: -------------------------------------------------------------------------------- 1 | //Redundant Connection 2 | //O(v+e), O(n) 3 | func findRedundantConnection(_ edges: [[Int]]) -> [Int] { 4 | var dict = [Int: Int]() 5 | for i in 1...edges.endIndex { 6 | dict[i] = i 7 | } 8 | func find(_ node: Int) -> Int { 9 | if dict[node]! == node {return node} 10 | dict[node] = find(dict[node]!) 11 | return dict[node]! 12 | } 13 | 14 | for edge in edges { 15 | let node1 = edge[0], node2 = edge[1] 16 | let root1 = find(node1), root2 = find(node2) 17 | if root1 == root2 {return edge} 18 | dict[root1] = root2 19 | } 20 | return [] 21 | } -------------------------------------------------------------------------------- /Medium/Remove Stones to Minimize the Total.swift: -------------------------------------------------------------------------------- 1 | //Remove Stones to Minimize the Total 2 | //O(n*k), O(n) TLE 3 | func minStoneSum(_ piles: [Int], _ k: Int) -> Int { 4 | var arr = piles.sorted() //O(n log n) 5 | for _ in 0..>1 11 | if arr[mid] < curr { 12 | l = mid+1 13 | } else { 14 | r = mid 15 | } 16 | } 17 | arr.insert(curr, at: l) //O(n) 18 | } 19 | return arr.reduce(0,+) 20 | } -------------------------------------------------------------------------------- /Medium/Single Number III.swift: -------------------------------------------------------------------------------- 1 | //Single Number III 2 | //O(n), O(n) 3 | func singleNumber(_ nums: [Int]) -> [Int] { 4 | var set = Set() 5 | for n in nums { 6 | if set.contains(n) { 7 | set.remove(n) 8 | } else { 9 | set.insert(n) 10 | } 11 | } 12 | return Array(set) 13 | } 14 | 15 | //O(n),O(1) 16 | func singleNumber(_ nums: [Int]) -> [Int] { 17 | let aXORb = nums.reduce(0, ^) 18 | let rightSetBit = aXORb & -aXORb 19 | var a = 0 20 | for n in nums { 21 | if n & rightSetBit != 0 { 22 | a = a^n 23 | } 24 | } 25 | return [a, a ^ aXORb] 26 | } -------------------------------------------------------------------------------- /Easy/Last Stone Weight.swift: -------------------------------------------------------------------------------- 1 | //Last Stone Weight 2 | //O(n^2), O(n) 3 | func lastStoneWeight(_ stones: [Int]) -> Int { 4 | var arr = stones.sorted() 5 | while arr.endIndex > 1 { 6 | let a = arr.removeLast() 7 | let b = arr.removeLast() 8 | let n = abs(a-b) 9 | var l = 0, r = arr.endIndex 10 | while l>1 12 | if arr[mid] < n { 13 | l = mid + 1 14 | } else { 15 | r = mid 16 | } 17 | } 18 | arr.insert(n, at: l) 19 | } 20 | 21 | if arr.endIndex == 0 {return 0} 22 | return arr[0] 23 | } -------------------------------------------------------------------------------- /Easy/Path Crossing.swift: -------------------------------------------------------------------------------- 1 | // Path Crossing 2 | // O(n), O(n) 3 | func isPathCrossing(_ path: String) -> Bool { 4 | var pointsSet = Set<[Int]>() 5 | var curr = [0,0] 6 | pointsSet.insert(curr) 7 | for char in path { 8 | switch char { 9 | case "N": 10 | curr = [curr[0], curr[1]+1] 11 | case "S": 12 | curr = [curr[0], curr[1]-1] 13 | case "E": 14 | curr = [curr[0]+1, curr[1]] 15 | case "W": 16 | curr = [curr[0]-1, curr[1]] 17 | default: 18 | break 19 | } 20 | if pointsSet.contains(curr) { return true } 21 | pointsSet.insert(curr) 22 | } 23 | return false 24 | } -------------------------------------------------------------------------------- /Medium/Maximum Average Subtree.swift: -------------------------------------------------------------------------------- 1 | //Maximum Average Subtree 2 | //O(n) O(h) 3 | func maximumAverageSubtree(_ root: TreeNode?) -> Double { 4 | var res: Double = 0 5 | func dfs(_ node: TreeNode?) -> (sum: Int, count: Int) { 6 | guard let node = node else {return (0,0)} 7 | let (leftNum, leftCount) = dfs(node.left) 8 | let (rightNum, rightCount) = dfs(node.right) 9 | let currTotalNum = leftNum + rightNum + node.val 10 | let currTotalCount = leftCount + rightCount + 1 11 | res = max(res, Double(currTotalNum) / Double(currTotalCount)) 12 | return (currTotalNum, currTotalCount) 13 | } 14 | dfs(root) 15 | return res 16 | } -------------------------------------------------------------------------------- /Easy/Guess Number Higher or Lower.swift: -------------------------------------------------------------------------------- 1 | /*Guess Number Higher or Lower*/ 2 | //O(log n), O(1) 3 | func guessNumber(_ n: Int) -> Int { 4 | 5 | var l = 1, r = n 6 | while l < r { 7 | let mid = (l+r) >> 1 8 | if guess(mid) == 1 { 9 | l = mid + 1 10 | } else { 11 | r = mid 12 | } 13 | } 14 | return l 15 | } 16 | 17 | func guessNumber(_ n: Int) -> Int { 18 | var l = 1, r = n 19 | while l>1 21 | let curr = guess(mid) 22 | if curr == 1 { 23 | l = mid+1 24 | } else if curr == -1 { 25 | r = mid-1 26 | } else { 27 | return mid 28 | } 29 | } 30 | return l 31 | } -------------------------------------------------------------------------------- /Easy/Maximum Subarray.swift: -------------------------------------------------------------------------------- 1 | /*Maximum Subarray*/ 2 | //time O(n) space O(n) 3 | func maxSubArray(_ nums: [Int]) -> Int { 4 | let ncount = nums.count 5 | var dp = Array(repeating: 0, count: ncount) 6 | dp[0] = nums[0] 7 | var res = nums[0] 8 | for i in 1.. Int { 17 | if nums.endIndex == 0 {return 0} 18 | var prev = nums[0] 19 | var res = nums[0] 20 | for i in 1.. Int { 4 | var leftMax = (0.. Int { 4 | let n = chars.endIndex 5 | if n == 1 {return 1} 6 | var i = 0, j = 0 7 | while i 1 { 16 | let str = String(count) 17 | for char in str { 18 | chars[j] = char 19 | j += 1 20 | } 21 | } 22 | } 23 | return j 24 | } -------------------------------------------------------------------------------- /Hard/Longest Happy Prefix.swift: -------------------------------------------------------------------------------- 1 | //Longest Happy Prefix 2 | //O(n) O(n) 3 | func longestPrefix(_ s: String) -> String { 4 | let sArr = Array(s) 5 | var i = 1, len = 0 6 | 7 | var table = [0] 8 | while i < sArr.endIndex { 9 | if sArr[i] == sArr[len] { 10 | len += 1 11 | table.append(len) 12 | i += 1 13 | } else { 14 | if len == 0 { 15 | table.append(len) 16 | i+=1 17 | } else { 18 | len = table[len - 1] 19 | } 20 | } 21 | } 22 | 23 | len = table.last! 24 | 25 | return String(sArr[i-len.. [[Int]] { 4 | var res = [[Int]]() 5 | 6 | func dfs(_ node: TreeNode?, _ curr: Int, _ list: [Int]) { 7 | guard let node = node else {return} 8 | if node.left == nil && node.right == nil { 9 | let sum = curr + node.val 10 | if sum == targetSum { 11 | res.append(list + [node.val]) 12 | } 13 | } 14 | dfs(node.left, curr+node.val, list + [node.val]) 15 | dfs(node.right, curr+node.val, list + [node.val]) 16 | } 17 | 18 | dfs(root,0,[]) 19 | return res 20 | } -------------------------------------------------------------------------------- /Hard/Read N Characters Given Read4 II - Call multiple times.swift: -------------------------------------------------------------------------------- 1 | //Read N Characters Given Read4 II - Call multiple times 2 | class Solution : Reader4 { 3 | var curr = [Character](repeating: Character(" "), count: 4) 4 | var index = 0 5 | var count = 0 6 | func read(_ buf: inout [Character], _ n: Int) -> Int { 7 | 8 | var res = 0 9 | for i in 0.. 0 { 15 | buf[i] = curr[index] 16 | index += 1 17 | count -= 1 18 | res += 1 19 | } 20 | } 21 | return res 22 | } 23 | 24 | } -------------------------------------------------------------------------------- /Medium/Swapping Nodes in a Linked List.swift: -------------------------------------------------------------------------------- 1 | //Swapping Nodes in a Linked List 2 | //O(n), O(1) 3 | func swapNodes(_ head: ListNode?, _ k: Int) -> ListNode? { 4 | var curr = head, count = 0 5 | var left: ListNode? 6 | while curr != nil { 7 | count += 1 8 | if count == k { 9 | left = curr 10 | } 11 | curr = curr!.next 12 | } 13 | var fromEnd = count - k 14 | var right: ListNode? 15 | curr = head 16 | for _ in 0.. Int { 4 | for i in 1...n { 5 | var curr = 0 6 | for j in 1...i { 7 | curr += j 8 | } 9 | var end = 0 10 | for k in i...n { 11 | end += k 12 | } 13 | if curr == end { 14 | return i 15 | } 16 | } 17 | return -1 18 | } 19 | 20 | // O(n), O(n) 21 | func pivotInteger(_ n: Int) -> Int { 22 | var arr = (0...n).map { num in num } 23 | for i in 1...n { 24 | arr[i] = arr[i-1] + i 25 | } 26 | for i in 1...n { 27 | if arr[n] - arr[i] == arr[i-1] { 28 | return i 29 | } 30 | } 31 | return -1 32 | } -------------------------------------------------------------------------------- /Medium/Construct Binary Search Tree from Preorder Traversal.swift: -------------------------------------------------------------------------------- 1 | //Construct Binary Search Tree from Preorder Traversal 2 | //O(n), O(n) 3 | func bstFromPreorder(_ preorder: [Int]) -> TreeNode? { 4 | var i = 0 5 | func dfs(_ minN: Int, _ maxN: Int) -> TreeNode? { 6 | guard i minN && n < maxN { 9 | let node = TreeNode(n) 10 | i += 1 11 | node.left = dfs(minN, n) 12 | node.right = dfs(n, maxN) 13 | return node 14 | } else { 15 | return nil 16 | } 17 | } 18 | 19 | return dfs(-Int.max, Int.max) 20 | } -------------------------------------------------------------------------------- /Medium/Minimum Limit of Balls in a Bag.swift: -------------------------------------------------------------------------------- 1 | // Minimum Limit of Balls in a Bag 2 | // O(n log n), O(1) 3 | func minimumSize(_ nums: [Int], _ maxOperations: Int) -> Int { 4 | var l = 1, r = 0 5 | for n in nums { 6 | r = max(r, n) 7 | } 8 | while l>1) 10 | var curr_op = 0 11 | for n in nums { 12 | if n > mid { 13 | curr_op += Int(ceil(Double(n)/Double(mid))) - 1 14 | if curr_op > maxOperations { 15 | break 16 | } 17 | } 18 | } 19 | 20 | if curr_op > maxOperations { 21 | l = mid + 1 22 | } else { 23 | r = mid 24 | } 25 | } 26 | return l 27 | } -------------------------------------------------------------------------------- /Medium/Remove K Digits.swift: -------------------------------------------------------------------------------- 1 | //Remove K Digits 2 | //O(n), O(n) 3 | func removeKdigits(_ num: String, _ k: Int) -> String { 4 | var stack = [Int]() 5 | var count = k 6 | for char in num { 7 | let n = Int(String(char))! 8 | while let last = stack.last, last > n, count > 0 { 9 | stack.removeLast() 10 | count -= 1 11 | } 12 | if stack.isEmpty && n == 0 { continue } 13 | stack.append(n) 14 | } 15 | 16 | while count > 0 && !stack.isEmpty { 17 | stack.removeLast() 18 | count -= 1 19 | } 20 | 21 | let res = stack.map { String($0) }.joined() 22 | return res != "" ? res : "0" 23 | } -------------------------------------------------------------------------------- /Easy/Image Smoother.swift: -------------------------------------------------------------------------------- 1 | // Image Smoother 2 | // O(n), O(n) 3 | func imageSmoother(_ img: [[Int]]) -> [[Int]] { 4 | let rows = img.endIndex, cols = img[0].endIndex 5 | var res = [[Int]](repeating: [Int](repeating: 0, count: cols), count: rows) 6 | for row in 0..= 0 && row+y < rows && col+x >= 0 && col+x < cols { 12 | curr += img[row+y][col+x] 13 | count += 1 14 | } 15 | } 16 | } 17 | res[row][col] = curr / count 18 | } 19 | } 20 | return res 21 | } -------------------------------------------------------------------------------- /Medium/Bitwise AND of Numbers Range.swift: -------------------------------------------------------------------------------- 1 | //Bitwise AND of Numbers Range 2 | //O(1), O(1) 3 | func rangeBitwiseAnd(_ left: Int, _ right: Int) -> Int { 4 | var i = 0, l = left, r = right 5 | while l != r { 6 | l >>= 1 7 | r >>= 1 8 | i += 1 9 | } 10 | return l << i 11 | 12 | } 13 | 14 | // O(1), O(1) 15 | func rangeBitwiseAnd(_ left: Int, _ right: Int) -> Int { 16 | var res = 0 17 | for i in 0..<32 { 18 | if right-left < Int(pow(Double(2),Double(i))) && 19 | left & Int(pow(Double(2),Double(i))) != 0 && 20 | right & Int(pow(Double(2),Double(i))) != 0 { 21 | res += Int(pow(Double(2),Double(i))) 22 | } 23 | } 24 | return res 25 | } -------------------------------------------------------------------------------- /Medium/Delete Node in a BST.swift: -------------------------------------------------------------------------------- 1 | //Delete Node in a BST 2 | func deleteNode(_ root: TreeNode?, _ key: Int) -> TreeNode? { 3 | guard let node = root else {return nil} 4 | if node.val > key { 5 | node.left = deleteNode(node.left, key) 6 | } else if node.val < key { 7 | node.right = deleteNode(node.right, key) 8 | } else { 9 | if node.left == nil {return node.right} 10 | if node.right == nil {return node.left} 11 | var right = node.right 12 | while right!.left != nil { 13 | right = right!.left 14 | } 15 | right!.left = node.left 16 | return node.right 17 | } 18 | 19 | return node 20 | } -------------------------------------------------------------------------------- /Medium/Find Largest Value in Each Tree Row.swift: -------------------------------------------------------------------------------- 1 | //Find Largest Value in Each Tree Row 2 | func largestValues(_ root: TreeNode?) -> [Int] { 3 | guard let node = root else {return []} 4 | var res = [Int]() 5 | 6 | var queue = [node] 7 | 8 | while queue.isEmpty == false { 9 | let temp = queue 10 | queue.removeAll() 11 | var localMax = -Int.max 12 | for curr in temp { 13 | localMax = max(localMax,curr.val) 14 | if curr.left != nil {queue.append(curr.left!)} 15 | if curr.right != nil {queue.append(curr.right!)} 16 | } 17 | res.append(localMax) 18 | } 19 | 20 | return res 21 | } -------------------------------------------------------------------------------- /Medium/Equal Tree Partition.swift: -------------------------------------------------------------------------------- 1 | //Equal Tree Partition 2 | //O(n) O(h) 3 | /* 4 | Find a subtree is the sum of entire tree. 5 | RemoveLast one prevented [0,1,-1] 6 | */ 7 | func checkEqualTree(_ root: TreeNode?) -> Bool { 8 | var stack = [Int]() 9 | func sum(_ node: TreeNode?) -> Int { 10 | if node == nil {return 0} 11 | stack.append(sum(node!.left) + sum(node!.right) + node!.val) 12 | return stack.last! 13 | } 14 | let total = sum(root) 15 | stack.removeLast() 16 | if total % 2 == 0 { 17 | for n in stack { 18 | if n == total / 2 { 19 | return true 20 | } 21 | } 22 | } 23 | return false 24 | } -------------------------------------------------------------------------------- /Medium/Path Sum III.swift: -------------------------------------------------------------------------------- 1 | //Path Sum III 2 | //O(n) O(n) 3 | 4 | //sum[i,j] = sum[0,j] - sum[0,i] 5 | //sum[0,i] = sum[0,j] - sum[i,j] 6 | func pathSum(_ root: TreeNode?, _ target: Int) -> Int { 7 | var res = 0 8 | var dict = [0:1] 9 | func dfs(_ node: TreeNode?, _ curr: Int) { 10 | guard let node = node else {return} 11 | let currSum = curr + node.val 12 | if dict[currSum - target] != nil { 13 | res += dict[currSum - target]! 14 | } 15 | dict[currSum, default:0] += 1 16 | dfs(node.left,currSum) 17 | dfs(node.right,currSum) 18 | dict[currSum, default:0] -= 1 19 | } 20 | dfs(root,0) 21 | return res 22 | } 23 | -------------------------------------------------------------------------------- /Medium/The Number of Weak Characters in the Game.swift: -------------------------------------------------------------------------------- 1 | // The Number of Weak Characters in the Game 2 | //O(n log n), O(n) 3 | func numberOfWeakCharacters(_ properties: [[Int]]) -> Int { 4 | let arr = properties.sorted { a, b in 5 | if a[0] == b[0] { 6 | return a[1]>b[1] 7 | } 8 | return a[0] < b[0] 9 | } 10 | var mtn = Int.min, res = 0 11 | for i in (0.. Int { 4 | let mod = Int(1E9+7) 5 | let n = arr.endIndex 6 | let arr = arr.sorted() 7 | var dp = [Int](repeating: 1, count: n) 8 | var dict = [Int: Int]() 9 | for i in 0.. nums[i+1] { 16 | (nums[i],nums[i+1]) = (nums[i+1],nums[i]) 17 | } 18 | } else { 19 | if nums[i] < nums[i+1] { 20 | (nums[i],nums[i+1]) = (nums[i+1],nums[i]) 21 | } 22 | } 23 | } 24 | } -------------------------------------------------------------------------------- /Medium/Number of Laser Beams in a Bank.swift: -------------------------------------------------------------------------------- 1 | // Number of Laser Beams in a Bank 2 | // O(n), O(n) 3 | func numberOfBeams(_ bank: [String]) -> Int { 4 | var res = 0 5 | var rows = [String]() 6 | for row in bank { 7 | var ones = 0 8 | for char in row { 9 | if char == "1" { ones += 1 } 10 | } 11 | if ones > 0 { 12 | rows.append(row) 13 | } 14 | } 15 | var i = 0 16 | while i < rows.endIndex-1 { 17 | var l = 0 18 | for char in rows[i] { 19 | if char == "1" { l += 1 } 20 | } 21 | var r = 0 22 | for char in rows[i+1] { 23 | if char == "1" { r += 1 } 24 | } 25 | res += l*r 26 | i += 1 27 | } 28 | return res 29 | } -------------------------------------------------------------------------------- /Easy/Check If It Is a Straight Line.swift: -------------------------------------------------------------------------------- 1 | //Check If It Is a Straight Line 2 | //O(n), O(1) 3 | func checkStraightLine(_ coordinates: [[Int]]) -> Bool { 4 | let n = coordinates.endIndex 5 | let node1 = coordinates[0], node2 = coordinates[1] 6 | let x1 = node1[0], y1 = node1[1], x2 = node2[0], y2 = node2[1] 7 | let dx1 = Double(x1-x2) 8 | let dy1 = Double(y1-y2) 9 | 10 | for i in 0.. ListNode? { 4 | var curr = head 5 | var count = 0 6 | while curr != nil { 7 | count += 1 8 | curr = curr!.next 9 | } 10 | count /= 2 11 | 12 | 13 | curr = head 14 | for i in 0.. ListNode? { 22 | var slow = head, fast = head 23 | while fast != nil && fast!.next != nil { 24 | slow = slow!.next 25 | fast = fast!.next!.next 26 | } 27 | return slow 28 | } -------------------------------------------------------------------------------- /Easy/Reverse Words in a String III.swift: -------------------------------------------------------------------------------- 1 | //Reverse Words in a String III 2 | func reverseWords(_ s: String) -> String { 3 | let arr = s.split(separator: " ") 4 | return arr.map {String(Array($0).reversed())} .joined(separator: " ") 5 | } 6 | 7 | // O(n), O(n) 8 | class Solution { 9 | func reverseWords(_ s: String) -> String { 10 | let arr = s.split(separator: " ").map { reversed(String($0)) }.joined(separator: " ") 11 | return arr 12 | } 13 | 14 | func reversed(_ w: String) -> String { 15 | var arr = Array(w) 16 | var l = 0, r = arr.endIndex-1 17 | while l Int { 4 | var score = 0, power = power 5 | let arr = tokens.sorted() 6 | var l = 0, r = arr.endIndex-1 7 | var res = 0 8 | while l<=r { 9 | if arr[l] <= power { 10 | score += 1 11 | power -= arr[l] 12 | l += 1 13 | res = max(res, score) 14 | } else { 15 | if score > 0 { 16 | score -= 1 17 | power += arr[r] 18 | r -= 1 19 | } else { 20 | return res 21 | } 22 | } 23 | } 24 | return res 25 | } -------------------------------------------------------------------------------- /Medium/Intersection of Two Linked Lists.swift: -------------------------------------------------------------------------------- 1 | //Intersection of Two Linked Lists 2 | //O(n) O(1) 3 | //Add two node will having the same length, they will meet at the interact eventually or both meet at the tail. 4 | func getIntersectionNode(_ headA: ListNode?, _ headB: ListNode?) -> ListNode? { 5 | var a = headA, b = headB 6 | while a !== b { 7 | a = a == nil ? headB : a!.next 8 | b = b == nil ? headA : b!.next 9 | } 10 | return a 11 | } 12 | 13 | func getIntersectionNode(_ headA: ListNode?, _ headB: ListNode?) -> ListNode? { 14 | var a = headA, b = headB 15 | while a !== b { 16 | a = a != nil ? a!.next : headB 17 | b = b != nil ? b!.next : headA 18 | } 19 | return a 20 | } -------------------------------------------------------------------------------- /Hard/Data Stream as Disjoint Intervals.swift: -------------------------------------------------------------------------------- 1 | //Data Stream as Disjoint Intervals 2 | class SummaryRanges { 3 | var set = Set() 4 | 5 | func addNum(_ value: Int) { //O(1) 6 | set.insert(value) 7 | } 8 | 9 | func getIntervals() -> [[Int]] { //O(n log n) 10 | if set.isEmpty {return [[]]} 11 | var res = [[Int]]() 12 | var l = -1, r = -1 13 | for n in Array(set).sorted() { 14 | if l == -1 { 15 | l = n 16 | r = n 17 | } else if n == r+1 { 18 | r = n 19 | } else { 20 | res.append([l,r]) 21 | l = n 22 | r = n 23 | } 24 | } 25 | res.append([l,r]) 26 | return res 27 | } 28 | } -------------------------------------------------------------------------------- /Medium/Container With Most Water.swift: -------------------------------------------------------------------------------- 1 | /* Container With Most Water*/ 2 | //time O(n^2) space O(1) 3 | func maxArea(_ height: [Int]) -> Int { 4 | var hcount = height.count 5 | var res = 0 6 | for i in 0.. Int { 17 | var l = 0, r = height.endIndex-1, res = 0 18 | while l Int { 4 | var count = 0 5 | 6 | var arr = [Int]() 7 | for (ca, rock) in zip(capacity, rocks) { 8 | let curr = ca-rock 9 | if curr == 0 { 10 | count += 1 11 | } else if curr > 0 { 12 | arr.append(curr) 13 | } 14 | } 15 | 16 | var rocks = additionalRocks 17 | 18 | for n in arr.sorted() { 19 | if n <= rocks { 20 | count += 1 21 | rocks -= n 22 | } 23 | } 24 | return count 25 | } -------------------------------------------------------------------------------- /Easy/Check If a Word Occurs As a Prefix of Any Word in a Sentence.swift: -------------------------------------------------------------------------------- 1 | // Check If a Word Occurs As a Prefix of Any Word in a Sentence 2 | // O(n), O(n) 3 | func isPrefixOfWord(_ sentence: String, _ searchWord: String) -> Int { 4 | let arr = sentence.split(separator: " ") 5 | var res = -1 6 | let search_arr = Array(searchWord) 7 | for i in 0.. Int { 4 | let arr = Array(s) 5 | var mask1 = [Character]() 6 | for i in 0.. Int { 4 | var set = Set() 5 | for n in nums { 6 | if set.contains(n) { 7 | return n 8 | } 9 | set.insert(n) 10 | } 11 | return 0 12 | } 13 | 14 | //O(n), O(1) 15 | func findDuplicate(_ nums: [Int]) -> Int { 16 | var slow = nums[0], fast = nums[0] 17 | while true { 18 | slow = nums[slow] 19 | fast = nums[nums[fast]] 20 | if slow == fast { 21 | break 22 | } 23 | } 24 | slow = nums[0] 25 | while slow != fast { 26 | slow = nums[slow] 27 | fast = nums[fast] 28 | } 29 | return fast 30 | } -------------------------------------------------------------------------------- /Medium/Non-decreasing Subsequences.swift: -------------------------------------------------------------------------------- 1 | //Non-decreasing Subsequences 2 | //O(2^n*n^2), O(2^n*n) 3 | func findSubsequences(_ nums: [Int]) -> [[Int]] { 4 | var path = [Int]() 5 | var res = Set<[Int]>() 6 | 7 | func dfs(_ index: Int) { 8 | if index == nums.endIndex { 9 | if path.endIndex>=2 { 10 | res.insert(path) 11 | } 12 | return 13 | } 14 | 15 | if path.isEmpty || path.last! <= nums[index] { 16 | path.append(nums[index]) 17 | dfs(index+1) 18 | path.removeLast() 19 | } 20 | 21 | dfs(index+1) 22 | } 23 | dfs(0) 24 | return Array(res) 25 | } -------------------------------------------------------------------------------- /Medium/Copy List with Random Pointer.swift: -------------------------------------------------------------------------------- 1 | /*Copy List with Random Pointer*/ 2 | // O(n), O(n) 3 | func copyRandomList(_ head: Node?) -> Node? { 4 | var curr = head 5 | 6 | var dict = [Node:Node]() 7 | while curr != nil { 8 | dict[curr!] = Node(curr!.val) 9 | curr = curr!.next 10 | } 11 | 12 | curr = head 13 | while curr != nil { 14 | let cloneNode = dict[curr!]! 15 | if let next = curr!.next { 16 | cloneNode.next = dict[next] 17 | } 18 | if let random = curr!.random { 19 | cloneNode.random = dict[random] 20 | } 21 | curr = curr!.next 22 | } 23 | 24 | return head == nil ? nil : dict[head!] 25 | } -------------------------------------------------------------------------------- /Hard/Shortest Subarray with Sum at Least K.swift: -------------------------------------------------------------------------------- 1 | //Shortest Subarray with Sum at Least K 2 | //O(n), O(n) 3 | func shortestSubarray(_ nums: [Int], _ k: Int) -> Int { 4 | var N = nums.endIndex, res = N + 1 5 | var prefix = [0]+nums 6 | for i in 1...N { 7 | prefix[i] += prefix[i-1] 8 | } 9 | 10 | var queue = [Int]() 11 | for i in 0...N { 12 | while !queue.isEmpty && prefix[i] - prefix[queue.first!] >= k { 13 | res = min(res, i - queue.first!) 14 | queue.removeFirst() 15 | } 16 | while !queue.isEmpty && prefix[i] <= prefix[queue.last!] { 17 | queue.removeLast() 18 | } 19 | queue.append(i) 20 | } 21 | return res == N+1 ? -1 : res 22 | } -------------------------------------------------------------------------------- /Medium/Delete Node in a Linked List.swift: -------------------------------------------------------------------------------- 1 | //Delete Node in a Linked List 2 | //O(n), O(1) 3 | func deleteNode(_ node: ListNode?) { 4 | guard let node = node else {return} 5 | var curr = node, next = node.next 6 | while next != nil { 7 | curr.val = next!.val 8 | if next?.next == nil { 9 | curr.next = nil 10 | break 11 | } 12 | curr = next! 13 | next = next!.next 14 | } 15 | 16 | } 17 | 18 | // O(n), O(1) 19 | func deleteNode(_ node: ListNode?) { 20 | var curr = node 21 | var prev: ListNode? 22 | while curr != nil, curr!.next != nil { 23 | prev = curr 24 | curr!.val = curr!.next!.val 25 | curr = curr!.next 26 | } 27 | prev!.next = nil 28 | } -------------------------------------------------------------------------------- /Medium/Find Players With Zero or One Losses.swift: -------------------------------------------------------------------------------- 1 | //Find Players With Zero or One Losses 2 | //O(n log n), O(n) 3 | func findWinners(_ matches: [[Int]]) -> [[Int]] { 4 | var set = Set() 5 | var lost = [Int: Int]() 6 | for match in matches { 7 | let l = match[1] 8 | let w = match[0] 9 | set.insert(l) 10 | set.insert(w) 11 | lost[l, default:0] += 1 12 | } 13 | var arr1 = [Int](), arr2 = [Int]() 14 | for player in set.sorted() { 15 | let n = lost[player, default:0] 16 | if n == 0 { 17 | arr1.append(player) 18 | } else if n == 1 { 19 | arr2.append(player) 20 | } 21 | } 22 | 23 | return [arr1, arr2] 24 | } -------------------------------------------------------------------------------- /Easy/Linked List Cycle.swift: -------------------------------------------------------------------------------- 1 | /*Linked List Cycle*/ 2 | //time O(n) space O(1) 3 | func hasCycle(_ head: ListNode?) -> Bool { 4 | if head == nil {return false} 5 | 6 | var fast = head 7 | var slow = head 8 | while fast != nil && slow != nil { 9 | if fast!.next == nil {return false} 10 | slow = slow!.next 11 | fast = fast!.next!.next 12 | if fast === slow {return true} 13 | } 14 | return false 15 | } 16 | 17 | func hasCycle(_ head: ListNode?) -> Bool { 18 | var fast = head 19 | var slow = head 20 | while fast?.next != nil && fast?.next?.next != nil { 21 | fast = fast?.next?.next 22 | slow = slow?.next 23 | 24 | if fast === slow {return true} 25 | } 26 | return false 27 | } -------------------------------------------------------------------------------- /Easy/Unique Email Addresses.swift: -------------------------------------------------------------------------------- 1 | //Unique Email Addresses 2 | //O(n), O(n) 3 | func numUniqueEmails(_ emails: [String]) -> Int { 4 | var set = Set() 5 | 6 | for email in emails { 7 | 8 | let arr = email.split(separator: "@") 9 | let local = arr[0], domain = arr[1] 10 | var s = "" 11 | local: for char in local { 12 | switch char { 13 | case ".": 14 | break 15 | case "+": 16 | break local 17 | default: 18 | s += String(char) 19 | } 20 | } 21 | s += "@\(domain)" 22 | set.insert(s) 23 | } 24 | return set.count 25 | } -------------------------------------------------------------------------------- /Medium/Keys and Rooms.swift: -------------------------------------------------------------------------------- 1 | //Keys and Rooms 2 | //O(n), O(n) 3 | func canVisitAllRooms(_ rooms: [[Int]]) -> Bool { 4 | var seen = Set([0]) 5 | var queue = [0] 6 | while !queue.isEmpty { 7 | let temp = queue 8 | queue.removeAll() 9 | for node in temp { 10 | for next in rooms[node] { 11 | if seen.contains(next) == false { 12 | queue.append(next) 13 | seen.insert(next) 14 | } 15 | } 16 | } 17 | 18 | } 19 | 20 | for i in 0.. Int { 4 | let arr = people.sorted() 5 | var i = 0, j = arr.endIndex-1 6 | var res = 0 7 | while i<=j { 8 | res += 1 9 | if arr[i] + arr[j] <= limit { 10 | i += 1 11 | } 12 | j -= 1 13 | } 14 | return res 15 | } 16 | 17 | // O(n log n), O(n) 18 | func numRescueBoats(_ people: [Int], _ limit: Int) -> Int { 19 | let arr = people.sorted() 20 | var l = 0, r = arr.endIndex-1 21 | var res = 0 22 | while l<=r { 23 | if arr[l] + arr[r] > limit { 24 | r -= 1 25 | } else { 26 | l += 1 27 | r -= 1 28 | } 29 | res += 1 30 | } 31 | return res 32 | } -------------------------------------------------------------------------------- /Medium/Number of Zero-Filled Subarrays.swift: -------------------------------------------------------------------------------- 1 | //Number of Zero-Filled Subarrays 2 | //O(n), O(1) 3 | func zeroFilledSubarray(_ nums: [Int]) -> Int { 4 | var res = 0, count = 0 5 | for n in nums { 6 | if n != 0 { 7 | res += (count+1)*count/2 8 | count = 0 9 | } else { 10 | count += 1 11 | } 12 | } 13 | res += (count+1)*count/2 14 | return res 15 | } 16 | 17 | //O(n), O(1) 18 | func zeroFilledSubarray(_ nums: [Int]) -> Int { 19 | var res = 0, count = 0 20 | for n in nums { 21 | if n == 0 { 22 | count += 1 23 | } else { 24 | count = 0 25 | } 26 | res += count 27 | } 28 | return res 29 | } -------------------------------------------------------------------------------- /Medium/Beautiful Array.swift: -------------------------------------------------------------------------------- 1 | //Beautiful Array 2 | //O(n log n), O(n log n) 3 | func beautifulArray(_ n: Int) -> [Int] { 4 | var dict = [Int: [Int]]() 5 | 6 | func dfs(_ n: Int) -> [Int] { 7 | if dict[n] != nil {return dict[n]!} 8 | 9 | var ans = (0.. Int { 4 | var l = 0, r = 0, res = 0 5 | var typeCount = 0 6 | var dict = [Int: Int]() 7 | while r < fruits.endIndex { 8 | let curr = fruits[r] 9 | dict[curr,default: 0] += 1 10 | if dict[curr]! == 1 { 11 | typeCount += 1 12 | while typeCount > 2 { 13 | let left = fruits[l] 14 | dict[left]! -= 1 15 | if dict[left]! == 0 { 16 | typeCount -= 1 17 | } 18 | l += 1 19 | } 20 | } 21 | res = max(res, r-l+1) 22 | r += 1 23 | } 24 | return res 25 | } -------------------------------------------------------------------------------- /Medium/Remove Duplicate Letters.swift: -------------------------------------------------------------------------------- 1 | //Remove Duplicate Letters 2 | //O(n), O(n) 3 | func removeDuplicateLetters(_ s: String) -> String { 4 | var stack = [Character]() 5 | var count = [Character: Int]() 6 | for char in s { 7 | count[char, default: 0] += 1 8 | } 9 | var visited = [Character: Bool]() 10 | for char in s { 11 | count[char]! -= 1 12 | if visited[char, default: false] { 13 | continue 14 | } 15 | while !stack.isEmpty && stack.last! > char && count[stack.last!]! > 0 { 16 | visited[stack.last!] = false 17 | stack.removeLast() 18 | } 19 | stack.append(char) 20 | visited[char] = true 21 | } 22 | return String(stack) 23 | } -------------------------------------------------------------------------------- /Easy/Minimum Number of Operations to Make Elements in Array Distinct.swift: -------------------------------------------------------------------------------- 1 | // Minimum Number of Operations to Make Elements in Array Distinct 2 | // O(n*max(nums)), O(n) 3 | func minimumOperations(_ nums: [Int]) -> Int { 4 | var dict = [Int: Int]() 5 | for n in nums { 6 | dict[n, default: 0] += 1 7 | } 8 | var i = 0 9 | var count = 0 10 | while Self.haveDuplicate(dict) { 11 | count += 1 12 | for delta in 0..<3 { 13 | if i+delta < nums.endIndex { 14 | dict[nums[i+delta]]! -= 1 15 | } 16 | } 17 | i += 3 18 | } 19 | return count 20 | } 21 | static func haveDuplicate(_ dict: [Int: Int]) -> Bool { 22 | for (key, val) in dict { 23 | if val > 1 { 24 | return true 25 | } 26 | } 27 | return false 28 | } -------------------------------------------------------------------------------- /Easy/Reverse String.swift: -------------------------------------------------------------------------------- 1 | /*Write a function that reverses a string. The input string is given as an array of characters char[]. 2 | 3 | Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. 4 | 5 | You may assume all the characters consist of printable ascii characters. 6 | 7 | 8 | 9 | Example 1: 10 | 11 | Input: ["h","e","l","l","o"] 12 | Output: ["o","l","l","e","h"] 13 | Example 2: 14 | 15 | Input: ["H","a","n","n","a","h"] 16 | Output: ["h","a","n","n","a","H"] 17 | */ 18 | class Solution { 19 | func reverseString(_ s: inout [Character]) { 20 | var left = 0, right = s.count - 1 21 | while(left < right) { 22 | (s[left], s[right]) = (s[right],s[left]) 23 | left+=1 24 | right-=1 25 | } 26 | } 27 | } -------------------------------------------------------------------------------- /Medium/Find All Duplicates in an Array.swift: -------------------------------------------------------------------------------- 1 | //Find All Duplicates in an Array 2 | //O(n),O(n) 3 | func findDuplicates(_ nums: [Int]) -> [Int] { 4 | var dict = [Int:Int]() 5 | for n in nums { 6 | dict[n,default:0]+=1 7 | } 8 | var res = [Int]() 9 | for (key, value) in dict { 10 | if value == 2 { 11 | res.append(key) 12 | } 13 | } 14 | return res 15 | } 16 | //O(n), O(1) or O(n) 17 | func findDuplicates(_ nums: [Int]) -> [Int] { 18 | var nums = nums, res = [Int]() 19 | for i in 0.. [String] { 4 | var res = [String]() 5 | let wArr = Array(word) 6 | func dfs(_ path: String, _ k: Int, _ i: Int) { 7 | if i == wArr.endIndex { 8 | if k != 0 { 9 | res.append(path+String(k)) 10 | } else { 11 | res.append(path) 12 | } 13 | return 14 | } 15 | dfs(path, k+1, i+1) 16 | 17 | if k > 0 { 18 | dfs(path+String(k)+String(wArr[i]), 0, i+1) 19 | } else { 20 | dfs(path+String(wArr[i]), 0, i+1) 21 | } 22 | } 23 | dfs("", 0,0) 24 | return res 25 | } -------------------------------------------------------------------------------- /Medium/Minimum Moves to Capture The Queen.swift: -------------------------------------------------------------------------------- 1 | // Minimum Moves to Capture The Queen 2 | // O(1), O(1) 3 | func minMovesToCaptureTheQueen(_ a: Int, _ b: Int, _ c: Int, _ d: Int, _ e: Int, _ f: Int) -> Int { 4 | if a == e { // rock in same row 5 | if a == c && (d-b) * (d-f) < 0 {return 2} // if bishop in between 6 | return 1 7 | } 8 | if b == f { // rock in same col 9 | if b == d && (c-a) * (c-e) < 0 {return 2} // if bishop in between 10 | return 1 11 | } 12 | if c-e == d-f { // bishop in diagonal \ 13 | if a-e == b-f && (a-c) * (a-e) < 0 {return 2} // if rock in between 14 | return 1 15 | } 16 | if c-e == f-d { // bishop in diagonal / 17 | if a-e == f-b && (a-c) * (a-e) < 0 {return 2} // if rock in between 18 | return 1 19 | } 20 | return 2 21 | } -------------------------------------------------------------------------------- /Medium/Split Array into Consecutive Subsequences.swift: -------------------------------------------------------------------------------- 1 | //Split Array into Consecutive Subsequences 2 | //O(n), O(n) 3 | func isPossible(_ nums: [Int]) -> Bool { 4 | var left = [Int: Int](), end = [Int: Int]() 5 | for n in nums { 6 | left[n, default:0] += 1 7 | } 8 | for i in nums { 9 | if left[i,default: 0] == 0 {continue} 10 | left[i]! -= 1 11 | if end[i-1, default:0] > 0 { 12 | end[i-1]! -= 1 13 | end[i,default:0] += 1 14 | } else if left[i+1, default:0] > 0 && left[i+2,default:0] > 0 { 15 | left[i+1]!-=1 16 | left[i+2]!-=1 17 | end[i+2,default:0]+=1 18 | }else{ 19 | return false 20 | } 21 | } 22 | return true 23 | } -------------------------------------------------------------------------------- /Easy/Find All Numbers Disappeared in an Array.swift: -------------------------------------------------------------------------------- 1 | //Find All Numbers Disappeared in an Array 2 | //O(n) O(n) 3 | func findDisappearedNumbers(_ nums: [Int]) -> [Int] { 4 | var set = Set(nums) 5 | var res = [Int]() 6 | for i in 1...nums.endIndex { 7 | if set.contains(i) == false { 8 | res.append(i) 9 | } 10 | } 11 | return res 12 | } 13 | //O(n) O(1) 14 | func findDisappearedNumbers(_ nums: [Int]) -> [Int] { 15 | 16 | var res = nums 17 | for i in 0.. 0 { 23 | res[i] = i+1 24 | } 25 | } 26 | return res.filter {$0>0} 27 | } -------------------------------------------------------------------------------- /Easy/Search Insert Position.swift: -------------------------------------------------------------------------------- 1 | /*Search Insert Position*/ 2 | func searchInsert(_ nums: [Int], _ target: Int) -> Int { 3 | if target > nums[nums.endIndex - 1] {return nums.endIndex} 4 | var left = 0, right = nums.endIndex - 1 5 | while left < right { 6 | let mid = left + (right - left) >> 1 7 | if nums[mid] < target { 8 | left = mid + 1 9 | } else { 10 | right = mid 11 | } 12 | } 13 | return left 14 | } 15 | 16 | //O(log n) 17 | func searchInsert(_ nums: [Int], _ target: Int) -> Int { 18 | var l = 0, r = nums.endIndex 19 | while l>1 21 | if nums[mid] < target { 22 | l = mid+1 23 | } else{ 24 | r = mid 25 | } 26 | } 27 | return l 28 | } -------------------------------------------------------------------------------- /Medium/Count Nodes Equal to Average of Subtree.swift: -------------------------------------------------------------------------------- 1 | // Count Nodes Equal to Average of Subtree 2 | // O(n), O(n) 3 | func averageOfSubtree(_ root: TreeNode?) -> Int { 4 | 5 | func dfs(_ root: TreeNode?) -> (subNodeCount: Int, sum: Int, resCount: Int) { 6 | guard let node = root else {return (0, 0, 0)} 7 | let left = dfs(node.left) 8 | let right = dfs(node.right) 9 | let currCount = left.subNodeCount + right.subNodeCount + 1 10 | let currSum = left.sum + node.val + right.sum 11 | var currResCount = left.resCount + right.resCount 12 | if currSum / currCount == node.val { 13 | currResCount += 1 14 | } 15 | return (currCount, currSum, currResCount) 16 | } 17 | 18 | return dfs(root).resCount 19 | } -------------------------------------------------------------------------------- /Medium/Shortest Word Distance III.swift: -------------------------------------------------------------------------------- 1 | //Shortest Word Distance III 2 | //O(word1.indices + word2.indices) O(words) 3 | func shortestWordDistance(_ wordsDict: [String], _ word1: String, _ word2: String) -> Int { 4 | var dict = [String:[Int]]() 5 | for (i, w) in wordsDict.enumerated() { 6 | dict[w, default:[]].append(i) 7 | } 8 | let list1 = dict[word1]!, list2 = dict[word2]! 9 | var l = 0, r = 0, res = Int.max 10 | while l < list1.endIndex && r < list2.endIndex { 11 | if list1[l] != list2[r] { 12 | res = min(res, abs(list1[l]-list2[r])) 13 | } 14 | 15 | if list1[l] < list2[r] { 16 | l += 1 17 | } else { 18 | r += 1 19 | } 20 | } 21 | return res 22 | } -------------------------------------------------------------------------------- /Medium/Split Linked List in Parts.swift: -------------------------------------------------------------------------------- 1 | // Split Linked List in Parts 2 | //O(n), O(1) 3 | func splitListToParts(_ head: ListNode?, _ k: Int) -> [ListNode?] { 4 | var allCount = 0 5 | var curr = head 6 | while curr != nil { 7 | allCount += 1 8 | curr = curr!.next 9 | } 10 | var res = [ListNode?]() 11 | let n = allCount/k 12 | curr = head 13 | for i in 0.. Int { 15 | dict[right+1]! - dict[left]! 16 | } 17 | } 18 | 19 | class NumArray { 20 | let prefix : [Int] 21 | init(_ nums: [Int]) { 22 | var arr = [0] + nums 23 | for i in 1.. Int { 30 | return prefix[right+1] - prefix[left] 31 | } 32 | } -------------------------------------------------------------------------------- /Medium/Maximum Score from Performing Multiplication Operations.swift: -------------------------------------------------------------------------------- 1 | //Maximum Score from Performing Multiplication Operations 2 | //O(2^multipliers.len), O(multipliers.len), TLE 3 | func maximumScore(_ nums: [Int], _ multipliers: [Int]) -> Int { 4 | var dict = [[Int]: Int]() 5 | func dfs(_ l: Int, _ r: Int, _ i: Int) -> Int { 6 | if i == multipliers.endIndex else {return 0} 7 | if dict[[l,r,i]] != nil {return dict[[l,r,i]]! } 8 | if l==r {return nums[l]*multipliers[i]} 9 | let left = nums[l] * multipliers[i] + dfs(l+1, r, i+1) 10 | let right = nums[r] * multipliers[i] + dfs(l, r-1, i+1) 11 | let curr = max(left, right) 12 | dict[[l,r,i]] = curr 13 | return curr 14 | } 15 | return dfs(0, nums.endIndex-1, 0) 16 | } 17 | 18 | -------------------------------------------------------------------------------- /Medium/Permutation in String.swift: -------------------------------------------------------------------------------- 1 | //Permutation in String 2 | //O(s1+s2) O(s1) 3 | func checkInclusion(_ s1: String, _ s2: String) -> Bool { 4 | var dict = [Character: Int]() 5 | for char in s1 { 6 | dict[char, default:0] += 1 7 | } 8 | var count = s1.count 9 | var l = 0, r = 0 10 | let sArr = Array(s2) 11 | while r < sArr.endIndex { 12 | dict[sArr[r], default: 0] -= 1 13 | if dict[sArr[r]]! >= 0 { 14 | count -= 1 15 | } 16 | while dict[sArr[r]]! < 0 { 17 | dict[sArr[l]]! += 1 18 | if dict[sArr[l]]! > 0 {count += 1} 19 | l += 1 20 | } 21 | if count == 0 {return true} 22 | r += 1 23 | } 24 | return false 25 | 26 | } -------------------------------------------------------------------------------- /Medium/Check if There is a Valid Partition For The Array.swift: -------------------------------------------------------------------------------- 1 | // Check if There is a Valid Partition For The Array 2 | // O(n), O(n) 3 | func validPartition(_ nums: [Int]) -> Bool { 4 | var dict = [Int: Bool]() 5 | func dfs(_ i: Int) -> Bool { 6 | if dict[i] != nil {return dict[i]!} 7 | if i == nums.endIndex {return true} 8 | var res = false 9 | if i+1 < nums.endIndex && nums[i] == nums[i+1] { 10 | res = res || dfs(i+2) 11 | } 12 | if i+2 < nums.endIndex && nums[i] == nums[i+1] && nums[i+1] == nums[i+2] { 13 | res = res || dfs(i+3) 14 | } 15 | if i+2 < nums.endIndex && nums[i] == nums[i+1]-1 && nums[i+1] == nums[i+2]-1 { 16 | res = res || dfs(i+3) 17 | } 18 | dict[i] = res 19 | return res 20 | } 21 | 22 | return dfs(0) 23 | } -------------------------------------------------------------------------------- /Medium/Clone N-ary Tree.swift: -------------------------------------------------------------------------------- 1 | // Clone N-ary Tree 2 | //O(n), O(n), n = treeNode.len 3 | class Solution { 4 | var dict = [Node: Node]() 5 | func cloneTree(_ root: Node?) -> Node? { 6 | guard let node = root else {return nil} 7 | if let cloneNode = dict[node] { 8 | return cloneNode 9 | } 10 | let cloneNode = Node(node.val) 11 | dict[node] = cloneNode 12 | cloneNode.children = node.children.compactMap { cloneTree($0) } 13 | return cloneNode 14 | } 15 | } 16 | //O(n), O(1), n = treeNode.len 17 | class Solution { 18 | func cloneTree(_ root: Node?) -> Node? { 19 | guard let node = root else {return nil} 20 | let cloneNode = Node(node.val) 21 | 22 | cloneNode.children = node.children.compactMap { cloneTree($0) } 23 | return cloneNode 24 | } 25 | } -------------------------------------------------------------------------------- /Medium/Minimum Speed to Arrive on Time.swift: -------------------------------------------------------------------------------- 1 | // Minimum Speed to Arrive on Time 2 | // O(n log k), O(1) 3 | func minSpeedOnTime(_ dist: [Int], _ hour: Double) -> Int { 4 | var l = 1, r = Int(1E7) 5 | var res = -1 6 | 7 | func timeRequired(_ speed: Int) -> Double { 8 | var time: Double = 0.0 9 | for i in 0..>1) 18 | if timeRequired(mid) <= hour { 19 | res = mid 20 | r = mid-1 21 | } else { 22 | l = mid + 1 23 | } 24 | } 25 | return res 26 | } -------------------------------------------------------------------------------- /Medium/Score of Parentheses.swift: -------------------------------------------------------------------------------- 1 | // Score of Parentheses 2 | //O(n), O(n) 3 | func scoreOfParentheses(_ s: String) -> Int { 4 | var stack = [Int](), res = 0 5 | for char in s { 6 | switch char { 7 | case "(": 8 | stack.append(0) 9 | case ")": 10 | var temp = 0 11 | while !stack.isEmpty && stack.last! != 0 { 12 | let last = stack.removeLast() 13 | temp += last 14 | } 15 | stack.removeLast() 16 | if temp == 0 { 17 | stack.append(1) 18 | } else { 19 | stack.append(temp*2) 20 | } 21 | 22 | default: 23 | break 24 | } 25 | } 26 | return stack.reduce(0,+) 27 | } -------------------------------------------------------------------------------- /Medium/Maximum Level Sum of a Binary Tree.swift: -------------------------------------------------------------------------------- 1 | // Maximum Level Sum of a Binary Tree 2 | // O(n), O(n) 3 | func maxLevelSum(_ root: TreeNode?) -> Int { 4 | guard let node = root else {return 0} 5 | var maxlevel = 0 6 | var maxVal = Int.min 7 | var queue = [node] 8 | var currlevel = 0 9 | while !queue.isEmpty { 10 | let temp = queue 11 | queue = [] 12 | var curr = 0 13 | currlevel += 1 14 | for node in temp { 15 | curr += node.val 16 | node.left.map { queue.append($0) } 17 | node.right.map { queue.append($0) } 18 | } 19 | if curr > maxVal { 20 | maxlevel = currlevel 21 | maxVal = curr 22 | } 23 | } 24 | return maxlevel 25 | } --------------------------------------------------------------------------------