├── .github └── FUNDING.yml ├── .gitignore ├── LICENSE ├── README.md └── Solutions ├── 000-099 ├── 01 Two Sum.swift ├── 02 Add Two Numbers.swift ├── 03 Longest Substring Without Repeating Characters.swift ├── 05 Longest Palindromic Substring.swift ├── 06 ZigZag Conversion.swift ├── 07 Reverse Integer.swift ├── 09 Palindrome Number.swift ├── 11 Container With Most Water.swift ├── 12 Integer to Roman.swift ├── 13 Roman to Integer.swift ├── 14 Longest Common Prefix.swift ├── 15 3Sum.swift ├── 16 3Sum Closest.swift ├── 17 Letter Combinations of a Phone Number.swift ├── 19 Remove Nth Node From End of List.swift ├── 20 Valid Parentheses.swift ├── 21 Merge Two Sorted Lists.swift ├── 22 Generate Parentheses.swift ├── 23 Merge k Sorted Lists.swift ├── 24 Swap Nodes in Pairs.swift ├── 26 Remove Duplicates from Sorted Array.swift ├── 27 Remove Element.swift ├── 31 Next Permutation.swift ├── 33 Search in Rotated Sorted Array.swift ├── 35 Search Insert Position.swift ├── 39 Combination Sum.swift ├── 41 First Missing Positive.swift ├── 47 Permutations II.swift ├── 50 Pow(x, n).swift ├── 55 Jump Game.swift ├── 56 Merge Intervals.swift ├── 57 Insert Interval.swift ├── 58 Length of Last Word.swift ├── 59 Spiral Matrix II.swift ├── 61 Rotate List.swift ├── 62 Unique Paths.swift ├── 64 Minimum Path Sum.swift ├── 66 Plus One.swift ├── 67 Add Binary.swift ├── 70 Climbing Stairs.swift ├── 71 Simplify Path.swift ├── 74 Search a 2D Matrix.swift ├── 75 Sort Colors.swift ├── 79 Word Search.swift ├── 80 Remove Duplicates from Sorted Array II.swift ├── 81 Search in Rotated Sorted Array II.swift ├── 82 Remove Duplicates from Sorted List II.swift ├── 83 Remove Duplicates from Sorted List.swift ├── 84 Largest Rectangle in Histogram.swift ├── 88 Merge Sorted Array.swift ├── 91 Decode Ways.swift ├── 94 Binary Tree Inorder Traversal.swift ├── 98 Validate Binary Search Tree.swift └── 99 Recover Binary Search Tree.swift ├── 100-199 ├── 100 Same Tree.swift ├── 101 Symmetric Tree.swift ├── 103 Binary Tree Zigzag Level Order Traversal.swift ├── 104 Maximum Depth of Binary Tree.swift ├── 107 Binary Tree Level Order Traversal II.swift ├── 108 Convert Sorted Array to Binary Search Tree.swift ├── 110 Balanced Binary Tree.swift ├── 111 Minimum Depth of Binary Tree.swift ├── 116 Populating Next Right Pointers in Each Node.swift ├── 117 Populating Next Right Pointers in Each Node II.swift ├── 118 Pascal's Triangle.swift ├── 119 Pascal's Triangle II.swift ├── 121 Best Time to Buy and Sell Stock.swift ├── 122 Best Time to Buy and Sell Stock II.swift ├── 123 Best Time to Buy and Sell Stock III.swift ├── 124 Binary Tree Maximum Path Sum.swift ├── 125 Valid Palindrome.swift ├── 129 Sum Root to Leaf Numbers.swift ├── 131 Palindrome Partitioning.swift ├── 133 Clone Graph.swift ├── 134 Gas Station.swift ├── 136 Single Number.swift ├── 138 Copy List with Random Pointer.swift ├── 139 Word Break.swift ├── 140 Word Break II.swift ├── 141 Linked List Cycle.swift ├── 142 Linked List Cycle II.swift ├── 143 Reorder List.swift ├── 147 Insertion Sort List.swift ├── 148 Sort List.swift ├── 150 Evaluate Reverse Polish Notation.swift ├── 151 Reverse Words in a String.swift ├── 152 Maximum Product Subarray.swift ├── 154 Find Minimum in Rotated Sorted Array II.swift ├── 155 Min Stack.swift ├── 156 Binary Tree Upside Down.swift ├── 157 Read N Characters Given Read4.swift ├── 159 Longest Substring with At Most Two Distinct Characters.swift ├── 160 Intersection of Two Linked Lists.swift ├── 161 One Edit Distance.swift ├── 163 Missing Ranges.swift ├── 165 Compare Version Numbers.swift ├── 167 Two Sum II - Input array is sorted.swift ├── 169 Majority Element.swift ├── 170 Two Sum III - Data structure design.swift ├── 171 Excel Sheet Column Number.swift ├── 173 Binary Search Tree Iterator.swift ├── 174 Dungeon Game.swift ├── 179 Largest Number.swift ├── 186 Reverse Words in a String II.swift ├── 187 Repeated DNA Sequences.swift ├── 188 Best Time to Buy and Sell Stock IV.swift ├── 189 Rotate Array.swift ├── 191 Number of 1 Bits.swift ├── 198 House Robber.swift └── 199 Binary Tree Right Side View.swift ├── 1000-1099 ├── 1007 Minimum Domino Rotations For Equal Row.swift ├── 1009 Complement of Base 10 Integer.swift ├── 1010 Pairs of Songs With Total Durations Divisible by 60.swift ├── 1015 Smallest Integer Divisible by K.swift ├── 1022 Sum of Root To Leaf Binary Numbers.swift ├── 1026 Maximum Difference Between Node and Ancestor.swift ├── 1032 Stream of Characters.swift ├── 1035 Uncrossed Lines.swift ├── 1038 Binary Search Tree to Greater Sum Tree.swift ├── 1041 Robot Bounded In Circle.swift ├── 1056 Confusing Number.swift ├── 1064 Fixed Point.swift ├── 1065 Index Pairs of a String.swift ├── 1081 Smallest Subsequence of Distinct Characters.swift ├── 1091 Shortest Path in Binary Matrix.swift ├── 1094 Car Pooling.swift └── 1099 Two Sum Less Than K.swift ├── 1100-1199 ├── 1103 Distribute Candies to People.swift ├── 1123 Lowest Common Ancestor of Deepest Leaves.swift └── 1165 Single-Row Keyboard.swift ├── 1200-1299 ├── 1213 Intersection of Three Sorted Arrays.swift ├── 1217 Minimum Cost to Move Chips to The Same Position.swift ├── 1249 Minimum Remove to Make Valid Parentheses.swift ├── 1272 Remove Interval.swift ├── 1283 Find the Smallest Divisor Given a Threshold.swift ├── 1286 Iterator for Combination.swift ├── 1288 Remove Covered Intervals.swift ├── 1290 Convert Binary Number in a Linked List to Integer.swift ├── 1291 Sequential Digits.swift └── 1295 Find Numbers with Even Number of Digits.swift ├── 1300-1399 ├── 1306 Jump Game III.swift ├── 1329 Sort the Matrix Diagonally.swift ├── 1332 Remove Palindromic Subsequences.swift ├── 1337 The K Weakest Rows in a Matrix.swift ├── 1342 Number of Steps to Reduce a Number to Zero.swift ├── 1344 Angle Between Hands of a Clock.swift ├── 1345 Jump Game IV.swift ├── 1365 How Many Numbers Are Smaller Than the Current Number.swift └── 1396 Design Underground System.swift ├── 1400-1499 ├── 1426 Counting Elements.swift ├── 1437 Check If All 1's Are at Least Length K Places Away.swift ├── 1446 Consecutive Characters.swift ├── 1457 Pseudo-Palindromic Paths in a Binary Tree.swift ├── 1463 Cherry Pickup II.swift └── 1492 The kth Factor of n.swift ├── 1500-1599 ├── 1506 Find Root of N-Ary Tree.swift ├── 1510 Stone Game IV.swift └── 1539 Kth Missing Positive Number.swift ├── 1600-1699 ├── 1602 Find Nearest Right Node in Binary Tree.swift ├── 1631 Path With Minimum Effort.swift ├── 1640 Check Array Formation Through Concatenation.swift ├── 1641 Count Sorted Vowel Strings.swift ├── 1646 Get Maximum in Generated Array.swift ├── 1657 Determine if Two Strings Are Close.swift ├── 1658 Minimum Operations to Reduce X to Zero.swift ├── 1662 Check If Two String Arrays are Equivalent.swift ├── 1663 Smallest String With A Given Numeric Value.swift ├── 1673 Find the Most Competitive Subsequence.swift ├── 1679 Max Number of K-Sum Pairs.swift └── 1680 Concatenation of Consecutive Binary Numbers.swift ├── 1700-1799 └── 1721 Swapping Nodes in a Linked List.swift ├── 200-299 ├── 202 Happy Number.swift ├── 203 Remove Linked List Elements.swift ├── 208 Implement Trie (Prefix Tree).swift ├── 209 Minimum Size Subarray Sum.swift ├── 210 Course Schedule II.swift ├── 211 Add and Search Word - Data structure design.swift ├── 213 House Robber II.swift ├── 215 Kth Largest Element in an Array.swift ├── 216 Combination Sum III.swift ├── 217 Contains Duplicate.swift ├── 219 Contains Duplicate II.swift ├── 220 Contains Duplicate III.swift ├── 222 Count Complete Tree Nodes.swift ├── 225 Implement Stack using Queues.swift ├── 226 Invert Binary Tree.swift ├── 227 Basic Calculator II.swift ├── 228 Summary Ranges.swift ├── 229 Majority Element II.swift ├── 231 Power of Two.swift ├── 232 Implement Queue using Stacks.swift ├── 237 Delete Node in a Linked List.swift ├── 239 Sliding Window Maximum.swift ├── 242 Valid Anagram.swift ├── 243 Shortest Word Distance.swift ├── 246 Strobogrammatic Number.swift ├── 252 Meeting Rooms.swift ├── 253 Meeting Rooms II.swift ├── 257 Binary Tree Paths.swift ├── 258 Add Digits.swift ├── 260 Single Number III.swift ├── 264 Ugly Number II.swift ├── 266 Palindrome Permutation.swift ├── 268 Missing Number.swift ├── 270 Closest Binary Search Tree Value.swift ├── 274 H-Index.swift ├── 276 Paint Fence.swift ├── 278 First Bad Version.swift ├── 283 Move Zeroes.swift ├── 284 Peeking Iterator.swift ├── 287 Find the Duplicate Number.swift ├── 289 Game of Life.swift ├── 290 Word Pattern.swift ├── 292 Nim Game.swift ├── 293 Flip Game.swift └── 299 Bulls and Cows.swift ├── 300-399 ├── 309 Best Time to Buy and Sell Stock with Cooldown.swift ├── 310 Minimum Height Trees.swift ├── 312 Burst Balloons.swift ├── 316 Remove Duplicate Letters.swift ├── 322 Coin Change.swift ├── 334 Increasing Triplet Subsequence.swift ├── 337 House Robber III.swift ├── 339 Nested List Weight Sum.swift ├── 340 Longest Substring with At Most K Distinct Characters.swift ├── 342 Power of Four.swift ├── 344 Reverse String.swift ├── 346 Moving Average from Data Stream.swift ├── 348 Design Tic-Tac-Toe.swift ├── 349 Intersection of Two Arrays.swift ├── 350 Intersection of Two Arrays II.swift ├── 359 Logger Rate Limiter.swift ├── 367 Valid Perfect Square.swift ├── 369 Plus One Linked List.swift ├── 376 Wiggle Subsequence.swift ├── 380 Insert Delete GetRandom O(1).swift ├── 382 Linked List Random Node.swift ├── 383 Ransom Note.swift ├── 387 First Unique Character in a String.swift ├── 389 Find the Difference.swift ├── 392 Is Subsequence.swift ├── 394 Decode String.swift ├── 395 Longest Substring with At Least K Repeating Characters.swift └── 399 Evaluate Division.swift ├── 400-499 ├── 404 Sum of Left Leaves.swift ├── 408 Valid Word Abbreviation.swift ├── 409 Longest Palindrome.swift ├── 412 Fizz Buzz.swift ├── 413 Arithmetic Slices.swift ├── 414 Third Maximum Number.swift ├── 416 Partition Equal Subset Sum.swift ├── 417 Pacific Atlantic Water Flow.swift ├── 421 Maximum XOR of Two Numbers in an Array.swift ├── 422 Valid Word Square.swift ├── 430 Flatten a Multilevel Doubly Linked List.swift ├── 435 Non-overlapping Intervals.swift ├── 436 Find Right Interval.swift ├── 437 Path Sum III.swift ├── 441 Arranging Coins.swift ├── 442 Find All Duplicates in an Array.swift ├── 445 Add Two Numbers II.swift ├── 449 Serialize and Deserialize BST.swift ├── 450 Delete Node in a BST.swift ├── 452 Minimum Number of Arrows to Burst Balloons.swift ├── 454 4Sum II.swift ├── 456 132 Pattern.swift ├── 458 Poor Pigs.swift ├── 459 Repeated Substring Pattern.swift ├── 461 Hamming Distance.swift ├── 463 Island Perimeter.swift ├── 470 Implement Rand10() Using Rand7().swift ├── 476 Number Complement.swift ├── 478 Generate Random Point in a Circle.swift ├── 484 Find Permutation.swift ├── 485 Max Consecutive Ones.swift ├── 487 Max Consecutive Ones II.swift ├── 489 Robot Room Cleaner.swift ├── 490 The Maze.swift ├── 495 Teemo Attacking.swift ├── 497 Random Point in Non-overlapping Rectangles.swift └── 498 Diagonal Traverse.swift ├── 500-599 ├── 510 Inorder Successor in BST II.swift ├── 518 Coin Change 2.swift ├── 520 Detect Capital.swift ├── 526 Beautiful Arrangement.swift ├── 532 K-diff Pairs in an Array.swift ├── 535 Encode and Decode TinyURL.swift ├── 538 Convert BST to Greater Tree.swift ├── 551 Student Attendance Record I.swift ├── 556 Next Greater Element III.swift ├── 563 Binary Tree Tilt.swift ├── 573 Squirrel Simulation.swift ├── 582 Kill Process.swift ├── 593 Valid Square.swift └── 594 Longest Harmonious Subsequence.swift ├── 600-699 ├── 604 Design Compressed String Iterator.swift ├── 605 Can Place Flowers.swift ├── 616 Add Bold Tag in String.swift ├── 621 Task Scheduler.swift ├── 623 Add One Row to Tree.swift ├── 624 Maximum Distance in Arrays.swift ├── 637 Average of Levels in Binary Tree.swift ├── 662 Maximum Width of Binary Tree.swift ├── 669 Trim a Binary Search Tree.swift ├── 673 Number of Longest Increasing Subsequence.swift ├── 678 Valid Parenthesis String.swift └── 694 Number of Distinct Islands.swift ├── 700-799 ├── 700 Search in a Binary Search Tree.swift ├── 701 Insert into a Binary Search Tree.swift ├── 702 Search in a Sorted Array of Unknown Size.swift ├── 704 Binary Search.swift ├── 708 Insert into a Sorted Circular Linked List.swift ├── 713 Subarray Product Less Than K.swift ├── 714 Best Time to Buy and Sell Stock with Transaction Fee.swift ├── 716 Max Stack.swift ├── 733 Flood Fill.swift ├── 734 Sentence Similarity.swift ├── 735 Asteroid Collision.swift ├── 744 Find Smallest Letter Greater Than Target.swift ├── 750 Number Of Corner Rectangles.swift ├── 754 Reach a Number.swift ├── 758 Bold Words in String.swift ├── 760 Find Anagram Mappings.swift ├── 763 Partition Labels.swift ├── 771 Jewels and Stones.swift ├── 784 Letter Case Permutation.swift ├── 785 Is Graph Bipartite?.swift ├── 797 All Paths From Source to Target.swift └── 799 Champagne Tower.swift ├── 800-899 ├── 800 Similar RGB Color.swift ├── 804 Unique Morse Code Words.swift ├── 821 Shortest Distance to a Character.swift ├── 824 Goat Latin.swift ├── 832 Flipping an Image.swift ├── 845 Longest Mountain in Array.swift ├── 849 Maximize Distance to Closest Person.swift ├── 858 Mirror Reflection.swift ├── 859 Buddy Strings.swift ├── 865 Smallest Subtree with all the Deepest Nodes.swift ├── 869 Reordered Power of 2.swift ├── 870 Advantage Shuffle.swift ├── 876 Middle of the Linked List.swift ├── 880 Decoded String at Index.swift ├── 881 Boats to Save People.swift └── 897 Increasing Order Search Tree.swift └── 900-999 ├── 901 Online Stock Span.swift ├── 902 Numbers At Most N Given Digit Set.swift ├── 905 Sort Array By Parity.swift ├── 910 Smallest Range II.swift ├── 933 Number of Recent Calls.swift ├── 938 Range Sum of BST.swift ├── 941 Valid Mountain Array.swift ├── 948 Bag of Tokens.swift ├── 949 Largest Time for Given Digits.swift ├── 952 Largest Component Size by Common Factor.swift ├── 957 Prison Cells After N Days.swift ├── 966 Vowel Spellchecker.swift ├── 967 Numbers With Same Consecutive Differences.swift ├── 969 Pancake Sorting.swift ├── 977 Squares of a Sorted Array.swift ├── 980 Unique Paths III.swift ├── 983 Minimum Cost For Tickets.swift ├── 987 Vertical Order Traversal of a Binary Tree.swift ├── 994 Rotting Oranges.swift └── 997 Find the Town Judge.swift /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | 3 | github: [AleksandarDinic] 4 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store -------------------------------------------------------------------------------- /Solutions/000-099/01 Two Sum.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 01 Two Sum.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 01/04/2020. 6 | // Copyright © 2020 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/two-sum 12 | class Solution { 13 | 14 | /// Given an array of integers, return indices of the two numbers 15 | /// such that they add up to a specific target. 16 | /// 17 | /// - Parameters: 18 | /// - nums: Array of integers 19 | /// - target: Specific target 20 | /// 21 | /// - Returns: Indices of the two numbers 22 | /// 23 | /// - Complexity: 24 | /// - time: O(n), where n is the length of the nums. 25 | /// - space: O(n), where n is the length of the nums. 26 | func twoSum(_ nums: [Int], _ target: Int) -> [Int] { 27 | var dict = [Int: Int]() 28 | 29 | for (i, num) in nums.enumerated() { 30 | if let j = dict[target - num] { 31 | return [j, i] 32 | } 33 | 34 | dict[num] = i 35 | } 36 | 37 | return [] 38 | } 39 | 40 | } 41 | -------------------------------------------------------------------------------- /Solutions/000-099/03 Longest Substring Without Repeating Characters.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 03 Longest Substring Without Repeating Characters.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 08/04/2020. 6 | // Copyright © 2020 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/longest-substring-without-repeating-characters 12 | class Solution { 13 | 14 | /// Find the length of the longest substring without repeating characters. 15 | /// 16 | /// - Parameter s: String 17 | /// 18 | /// - Returns: Length of the longest substring. 19 | /// 20 | /// - Complexity: 21 | /// - time: O(n), where n is the length of the s. 22 | /// - space: O(m), where m is the size of the charset. 23 | func lengthOfLongestSubstring(_ s: String) -> Int { 24 | var dict = [Character: Int]() 25 | var ans = 0 26 | var j = 0 27 | 28 | for (i, c) in s.enumerated() { 29 | j = max(j, dict[c] ?? -1) 30 | 31 | ans = max(ans, i - j + 1) 32 | dict[c] = i + 1 33 | } 34 | 35 | return ans 36 | } 37 | 38 | } 39 | -------------------------------------------------------------------------------- /Solutions/000-099/06 ZigZag Conversion.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 06 ZigZag Conversion.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 20/02/2021. 6 | // Copyright © 2021 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/zigzag-conversion/ 12 | class Solution { 13 | 14 | /// Makes ZigZag conversion of string. 15 | /// 16 | /// - Parameters: 17 | /// - s: The string. 18 | /// - numRows: The number of rows. 19 | /// - Returns: ZigZag conversion of the string. 20 | /// 21 | /// - Complexity: 22 | /// - time: O(n), where n is the length of `s`. 23 | /// - space: O(n), where n is the length of `s`. 24 | func convert(_ s: String, _ numRows: Int) -> String { 25 | guard s.count > 1, numRows > 1 else { return s } 26 | 27 | var ans = [String](repeating: "", count: numRows) 28 | let tmp = (numRows - 1) * 2 29 | 30 | for (i, ch) in s.enumerated() { 31 | let location = i % tmp 32 | if location < numRows { 33 | ans[location].append(ch) 34 | } else { 35 | let upLocation = location - numRows 36 | ans[numRows - 1 - upLocation - 1].append(ch) 37 | } 38 | } 39 | 40 | return ans.joined() 41 | } 42 | 43 | } 44 | -------------------------------------------------------------------------------- /Solutions/000-099/07 Reverse Integer.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 07 Reverse Integer.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 21/02/2021. 6 | // Copyright © 2021 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/reverse-integer/ 12 | class Solution { 13 | 14 | /// Reverse digits in `x`. 15 | /// 16 | /// - Parameter x: An integer. 17 | /// - Returns: Reversed `x`. 18 | /// 19 | /// - Complexity: 20 | /// - time: O(log n), where n is the given `x`. 21 | /// - space: O(1), only constant space is used. 22 | func reverse(_ x: Int) -> Int { 23 | var x = x 24 | var ans = 0 25 | 26 | while x != 0 { 27 | let tmp = (x % 10) 28 | x /= 10 29 | 30 | if ans > Int32.max / 10 || (ans == Int32.max / 10 && tmp > 7) { return 0 } 31 | if ans < Int32.min / 10 || (ans == Int32.max / 10 && tmp < -8) { return 0 } 32 | 33 | ans = (ans * 10) + tmp 34 | } 35 | 36 | return ans 37 | } 38 | 39 | } 40 | -------------------------------------------------------------------------------- /Solutions/000-099/09 Palindrome Number.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 09 Palindrome Number.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 14/06/2020. 6 | // Copyright © 2020 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/palindrome-number/ 12 | class Solution { 13 | 14 | /// Determines whether an integer is a palindrome. 15 | /// 16 | /// - Parameter x: The integer. 17 | /// - Returns: True if the integer is a palindrome, otherwise returns false. 18 | /// 19 | /// - Complexity: 20 | /// - time: O(log n), where n is the number of digits in x. 21 | /// - space: O(1), only constant space is used. 22 | func isPalindrome(_ x: Int) -> Bool { 23 | guard x >= 0, (x % 10 != 0 || x == 0) else { return false } 24 | 25 | var revertedNumber = 0 26 | var x = x 27 | 28 | while x > revertedNumber { 29 | revertedNumber = revertedNumber * 10 + x % 10 30 | x /= 10 31 | } 32 | 33 | return x == revertedNumber || x == revertedNumber/10 34 | } 35 | 36 | } 37 | -------------------------------------------------------------------------------- /Solutions/000-099/11 Container With Most Water.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 11 Container With Most Water.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 14/06/2020. 6 | // Copyright © 2020 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/container-with-most-water/ 12 | class Solution { 13 | 14 | /// Forms a container which contains the most water. 15 | /// 16 | /// - Parameter height: Non-negative integers. 17 | /// - Returns: The max area of water. 18 | /// 19 | /// - Complexity: 20 | /// - time: O(n), where n is the number of heights. 21 | /// - space: O(1), only constant space is used. 22 | func maxArea(_ height: [Int]) -> Int { 23 | var start = 0 24 | var end = height.count - 1 25 | 26 | var ans = 0 27 | 28 | while start < end { 29 | ans = max(ans, min(height[start], height[end]) * (end - start)) 30 | 31 | if height[start] < height[end] { 32 | start += 1 33 | } else { 34 | end -= 1 35 | } 36 | } 37 | 38 | return ans 39 | } 40 | 41 | } 42 | -------------------------------------------------------------------------------- /Solutions/000-099/12 Integer to Roman.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 12 Integer to Roman.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 24/06/2020. 6 | // Copyright © 2020 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/integer-to-roman/ 12 | class Solution { 13 | 14 | /// Converts an integer to a roman numeral. 15 | /// 16 | /// - Parameter num: The integer. 17 | /// - Returns: Roman numeral. 18 | /// 19 | /// - Complexity: 20 | /// - time: O(n), where n is the number of digits in num. 21 | /// - space: O(1), only constant space is used. 22 | func intToRoman(_ num: Int) -> String { 23 | let roman = [ 24 | ["", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"], 25 | ["", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"], 26 | ["", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"], 27 | ["", "M", "MM", "MMM"] 28 | ] 29 | 30 | var ans = "" 31 | var digit = 0 32 | var num = num 33 | 34 | while num > 0 { 35 | let remain = num % 10 36 | ans = "\(roman[digit][remain])\(ans)" 37 | digit += 1 38 | num /= 10 39 | } 40 | 41 | return ans 42 | } 43 | 44 | } 45 | -------------------------------------------------------------------------------- /Solutions/000-099/26 Remove Duplicates from Sorted Array.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 26 Remove Duplicates from Sorted Array.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 06/04/2020. 6 | // Copyright © 2020 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/remove-duplicates-from-sorted-array 12 | class Solution { 13 | 14 | /// Remove duplicates in-place such that each element appear only once. 15 | /// 16 | /// - Parameter nums: Sorted array 17 | /// 18 | /// - Returns: New length of array 19 | /// 20 | /// - Complexity: 21 | /// - time: O(n), where n is the length of the nums. 22 | /// - space: O(1), only constant space is used. 23 | func removeDuplicates(_ nums: inout [Int]) -> Int { 24 | guard !nums.isEmpty else { return 0 } 25 | var i = 0 26 | 27 | for j in 1.. Int { 26 | guard !nums.isEmpty else { return 0 } 27 | 28 | var i = 0 29 | 30 | for num in nums { 31 | guard num != val else { continue } 32 | 33 | nums[i] = num 34 | i += 1 35 | } 36 | 37 | return i 38 | } 39 | 40 | } 41 | -------------------------------------------------------------------------------- /Solutions/000-099/35 Search Insert Position.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 35 Search Insert Position.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 10/06/2020. 6 | // Copyright © 2020 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/search-insert-position/ 12 | class Solution { 13 | 14 | /// Search insert position. 15 | /// 16 | /// - Parameters: 17 | /// - nums: A sorted array. 18 | /// - target: A target value. 19 | /// - Returns: The index of the target if exists, or the index where it would be if it 20 | /// were inserted in order. 21 | /// 22 | /// - Complexity: 23 | /// - time: O(log n), where n is the length of the nums. 24 | /// - space: O(1), only constant space is used. 25 | func searchInsert(_ nums: [Int], _ target: Int) -> Int { 26 | var start = 0 27 | var end = nums.count 28 | 29 | while start < end { 30 | let mid = start + (end - start) / 2 31 | 32 | if nums[mid] < target { 33 | start = mid + 1 34 | } else { 35 | end = mid 36 | } 37 | } 38 | 39 | return start 40 | } 41 | 42 | } 43 | -------------------------------------------------------------------------------- /Solutions/000-099/50 Pow(x, n).swift: -------------------------------------------------------------------------------- 1 | // 2 | // 50 Pow(x, n).swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 16/07/2020. 6 | // Copyright © 2020 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/powx-n/ 12 | class Solution { 13 | 14 | /// Calculates x raised to the power n (x^n). 15 | /// 16 | /// - Parameters: 17 | /// - x: The base value. 18 | /// - n: The power value. 19 | /// - Returns: A decimal number raised to a given power. 20 | /// 21 | /// - Complexity: 22 | /// - time: O(log n), where n is the power value. 23 | /// - space: O(log n), where n is the power value. 24 | func myPow(_ x: Double, _ n: Int) -> Double { 25 | guard n != 0 else { return 1 } 26 | 27 | var x = x 28 | var n = n 29 | 30 | if n < 0 { 31 | n = -n 32 | x = 1 / x 33 | } 34 | 35 | return n % 2 == 0 ? myPow(x * x, n / 2) : x * myPow(x * x, n / 2) 36 | } 37 | 38 | } 39 | -------------------------------------------------------------------------------- /Solutions/000-099/55 Jump Game.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 55 Jump Game.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 30/04/2020. 6 | // Copyright © 2020 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/jump-game/ 12 | class Solution { 13 | 14 | /// Determines if it is able to reach the last index. 15 | /// 16 | /// - Parameter nums: Array of non-negative integers. 17 | /// 18 | /// - Returns: True if it is able to reach the last index, otherwise returns false. 19 | /// 20 | /// - Complexity: 21 | /// - time: O(n), where n is the length of the nums. 22 | /// - space: O(1), only constant space is used. 23 | func canJump(_ nums: [Int]) -> Bool { 24 | var reach = 0 25 | var i = 0 26 | while i <= reach { 27 | reach = max(reach, i + nums[i]) 28 | i += 1 29 | if reach >= nums.count - 1 { 30 | return true 31 | } 32 | } 33 | 34 | return false 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /Solutions/000-099/56 Merge Intervals.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 56 Merge Intervals.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 18/11/2020. 6 | // Copyright © 2020 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/merge-intervals/ 12 | class Solution { 13 | 14 | /// Merge all overlapping intervals. 15 | /// 16 | /// - Parameter intervals: An array of `intervals`. 17 | /// - Returns: An array of the non-overlapping intervals. 18 | /// 19 | /// - Complexity: 20 | /// - time: O(n log(n)), where n is the number of intervals. 21 | /// - space: O(n), where n is the number of intervals. 22 | func merge(_ intervals: [[Int]]) -> [[Int]] { 23 | guard !intervals.isEmpty else { return [] } 24 | var intervals = intervals.sorted(by: { $0[0] < $1[0] }) 25 | 26 | var ans = [[Int]]() 27 | var start = intervals[0][0] 28 | var end = intervals[0][1] 29 | 30 | for interval in intervals { 31 | guard end < interval[0] else { 32 | end = max(end, interval[1]) 33 | continue 34 | } 35 | ans.append([start, end]) 36 | start = interval[0] 37 | end = interval[1] 38 | } 39 | 40 | ans.append([start, end]) 41 | 42 | return ans 43 | } 44 | 45 | } 46 | -------------------------------------------------------------------------------- /Solutions/000-099/58 Length of Last Word.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 58 Length of Last Word.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 15/09/2020. 6 | // Copyright © 2020 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/length-of-last-word/ 12 | class Solution { 13 | 14 | /// Finds the length of the last word in a given string. 15 | /// 16 | /// - Parameter s: A string consists of upper/lower-case alphabets and empty space 17 | /// characters ' '. 18 | /// - Returns: The length of the last word, if the last word does not exist returns 0. 19 | /// 20 | /// - Complexity: 21 | /// - time: O(n), where n is the length of `s`. 22 | /// - space: O(1), only constant space is used. 23 | func lengthOfLastWord(_ s: String) -> Int { 24 | var ans = 0 25 | 26 | for ch in s.reversed() { 27 | if ch != " " { 28 | ans += 1 29 | } else if ans > 0 { 30 | return ans 31 | } 32 | } 33 | 34 | return ans 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /Solutions/000-099/59 Spiral Matrix II.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 59 Spiral Matrix II.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 07/12/2020. 6 | // Copyright © 2020 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/spiral-matrix-ii/ 12 | class Solution { 13 | 14 | /// Generates an n x n matrix filled with elements from 1 to n*n in spiral order. 15 | /// 16 | /// - Parameter n: A positive integer. 17 | /// - Returns: Spiral matrix. 18 | /// 19 | /// - Complexity: 20 | /// - time: O(n * n), where n is the given `n`. 21 | /// - space: O(n * n), where n is the given `n`. 22 | func generateMatrix(_ n: Int) -> [[Int]] { 23 | var ans = [[Int]](repeating: [Int](repeating: 0, count: n), count: n) 24 | let dir: [(row: Int, col: Int)] = [(0, 1), (1, 0), (0, -1), (-1, 0)] 25 | var d = 0 26 | var row = 0 27 | var col = 0 28 | 29 | for num in 1...n*n { 30 | ans[row][col] = num 31 | 32 | let r = abs((row + dir[d].row) % n) 33 | let c = abs((col + dir[d].col) % n) 34 | 35 | if ans[r][c] != 0 { 36 | d = (d + 1) % 4 37 | } 38 | 39 | row += dir[d].row 40 | col += dir[d].col 41 | } 42 | 43 | return ans 44 | } 45 | 46 | } 47 | -------------------------------------------------------------------------------- /Solutions/000-099/62 Unique Paths.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 62 Unique Paths.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 29/06/2020. 6 | // Copyright © 2020 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/unique-paths/ 12 | class Solution { 13 | 14 | /// Finds how many unique paths exist. 15 | /// 16 | /// - Parameters: 17 | /// - m: Number of rows. 18 | /// - n: Number of columns. 19 | /// - Returns: Number of unique paths. 20 | /// 21 | /// - Complexity: 22 | /// - time: O(n * m), where n is the number of rows, and m is the number of columns. 23 | /// - space: O(min(n, m)), where n is the number of rows, and m is the number of 24 | /// columns. 25 | func uniquePaths(_ m: Int, _ n: Int) -> Int { 26 | guard m <= n else { return uniquePaths(n, m) } 27 | 28 | var dp = [Int](repeating: 1, count: m) 29 | 30 | for _ in 1.. [Int] { 23 | var digits = digits 24 | 25 | for i in (0.. Int { 23 | if n == 0 || n == 1 { 24 | return 1 25 | } 26 | 27 | var first = 1 28 | var second = 1 29 | var third = 0 30 | for _ in 2...n { 31 | third = first + second 32 | first = second 33 | second = third 34 | } 35 | 36 | return second 37 | } 38 | 39 | } 40 | -------------------------------------------------------------------------------- /Solutions/000-099/71 Simplify Path.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 71 Simplify Path.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 05/02/2021. 6 | // Copyright © 2021 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/simplify-path/ 12 | class Solution { 13 | 14 | /// Finds the simplified canonical path. 15 | /// 16 | /// - Parameter path: An absolute path. 17 | /// - Returns: The simplified canonical path. 18 | /// 19 | /// - Complexity: 20 | /// - time: O(n), where n is the length of `path`. 21 | /// - space: O(n), where n is the length of `path`. 22 | func simplifyPath(_ path: String) -> String { 23 | let paths = path.split(separator: "/") 24 | 25 | var stack = [String]() 26 | for path in paths { 27 | guard path != ".", !path.isEmpty else { continue } 28 | 29 | if path == ".." { 30 | if !stack.isEmpty { 31 | stack.removeLast() 32 | } 33 | } else { 34 | stack.append(String(path)) 35 | } 36 | } 37 | 38 | return "/\(stack.joined(separator: "/"))" 39 | } 40 | 41 | } 42 | -------------------------------------------------------------------------------- /Solutions/000-099/75 Sort Colors.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 75 Sort Colors.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 11/06/2020. 6 | // Copyright © 2020 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/sort-colors/ 12 | class Solution { 13 | 14 | /// Sorts colors in-place. 15 | /// 16 | /// - Parameter nums: An array with red, white or blue color. The integers 0, 1, and 2 17 | /// represent the color red, white, and blue respectively. 18 | /// 19 | /// - Complexity: 20 | /// - time: O(n), where n is the length of the `nums`. 21 | /// - space: O(1), only constant space is used. 22 | func sortColors(_ nums: inout [Int]) { 23 | var zeroIndex = 0 24 | var twoIndex = nums.count - 1 25 | var i = 0 26 | 27 | while i <= twoIndex { 28 | if nums[i] == 0, i > zeroIndex { 29 | nums.swapAt(i, zeroIndex) 30 | zeroIndex += 1 31 | 32 | } else if nums[i] == 2, i < twoIndex { 33 | nums.swapAt(i, twoIndex) 34 | twoIndex -= 1 35 | 36 | } else { 37 | i += 1 38 | } 39 | } 40 | } 41 | 42 | } 43 | -------------------------------------------------------------------------------- /Solutions/000-099/80 Remove Duplicates from Sorted Array II.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 80 Remove Duplicates from Sorted Array II.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 11/12/2020. 6 | // Copyright © 2020 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/ 12 | class Solution { 13 | 14 | /// Removes the duplicates in-place such that duplicates appeared at most twice. 15 | /// 16 | /// - Parameter nums: A sorted array. 17 | /// - Returns: The new length. 18 | /// 19 | /// - Complexity: 20 | /// - time: O(n), where n is the length of `nums`. 21 | /// - space: O(1), only constant space is used. 22 | func removeDuplicates(_ nums: inout [Int]) -> Int { 23 | let n = nums.count 24 | guard n > 2 else { return n } 25 | var j = 1 26 | var count = 1 27 | 28 | for i in 1.. Int { 23 | let message = Array(s).compactMap { Int(String($0)) } 24 | let n = message.count 25 | 26 | guard n > 0, message[0] != 0 else { return 0 } 27 | guard n > 1 else { return 1 } 28 | 29 | var pre1 = 1 30 | var pre2 = 1 31 | var cur = 0 32 | 33 | for i in 1..= 1, message[i] <= 9 { 36 | cur += pre1 37 | } 38 | let tmp = message[i-1] * 10 + message[i] 39 | if tmp >= 10, tmp <= 26 { 40 | cur += pre2 41 | } 42 | pre2 = pre1 43 | pre1 = cur 44 | } 45 | 46 | return cur 47 | } 48 | 49 | } 50 | -------------------------------------------------------------------------------- /Solutions/100-199/104 Maximum Depth of Binary Tree.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 104 Maximum Depth of Binary Tree.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 19/11/2020. 6 | // Copyright © 2020 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/maximum-depth-of-binary-tree/ 12 | class Solution { 13 | 14 | /// Finds the maximum depth in a binary tree. 15 | /// 16 | /// - Parameter root: The binary tree. 17 | /// - Returns: The maximum depth. 18 | /// 19 | /// - Complexity: 20 | /// - time: O(n), where n is the number of nodes. 21 | /// - space: O(n), where n is the number of nodes. 22 | func maxDepth(_ root: TreeNode?) -> Int { 23 | root == nil ? 0 : max(maxDepth(root?.left), maxDepth(root?.right)) + 1 24 | } 25 | 26 | } 27 | 28 | /// Provided Code 29 | public class TreeNode { 30 | 31 | public var val: Int 32 | public var left: TreeNode? 33 | public var right: TreeNode? 34 | 35 | public init() { 36 | self.val = 0 37 | self.left = nil 38 | self.right = nil 39 | } 40 | 41 | public init(_ val: Int) { 42 | self.val = val 43 | self.left = nil 44 | self.right = nil 45 | } 46 | 47 | public init(_ val: Int, _ left: TreeNode?, _ right: TreeNode?) { 48 | self.val = val 49 | self.left = left 50 | self.right = right 51 | } 52 | 53 | } 54 | -------------------------------------------------------------------------------- /Solutions/100-199/118 Pascal's Triangle.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 118 Pascal's Triangle.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 15/04/2020. 6 | // Copyright © 2020 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/pascals-triangle/ 12 | class Solution { 13 | 14 | /// Generates the first *numRows* of Pascal's triangle. 15 | /// 16 | /// - Parameter numRows: Number of rows. 17 | /// 18 | /// - Returns: Pascal's triangle. 19 | /// 20 | /// - Complexity: 21 | /// - time: O(n * n), where n is the numRows. 22 | /// - space: O(n * n), where n is the numRows. 23 | func generate(_ numRows: Int) -> [[Int]] { 24 | var ans = [[Int]](repeating: [Int](), count: numRows) 25 | 26 | for i in 0.. [Int] { 24 | guard rowIndex > 0 else { return [1] } 25 | 26 | var ans = [Int]() 27 | ans.append(1) 28 | 29 | var tmp = 1 30 | for i in 1...rowIndex { 31 | tmp = tmp * (rowIndex + 1 - i) / i 32 | ans.append(tmp) 33 | } 34 | 35 | return ans 36 | } 37 | 38 | } 39 | -------------------------------------------------------------------------------- /Solutions/100-199/121 Best Time to Buy and Sell Stock.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 121 Best Time to Buy and Sell Stock.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 18/09/2020. 6 | // Copyright © 2020 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/best-time-to-buy-and-sell-stock/ 12 | class Solution { 13 | 14 | /// Finds the maximum profit. 15 | /// 16 | /// - Parameter prices: An array where the i-th element is the price of 17 | /// a given stock on day i. 18 | /// - Returns: Maximum profit. 19 | /// 20 | /// - Complexity: 21 | /// - time: O(n), where n is the number of prices. 22 | /// - space: O(1), only constant space is used. 23 | func maxProfit(_ prices: [Int]) -> Int { 24 | var minPrice = Int.max 25 | var ans = 0 26 | 27 | for price in prices { 28 | minPrice = min(minPrice, price) 29 | ans = max(ans, price - minPrice) 30 | } 31 | 32 | return ans 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /Solutions/100-199/122 Best Time to Buy and Sell Stock II.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 122 Best Time to Buy and Sell Stock II.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 28/04/2020. 6 | // Copyright © 2020 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/ 12 | class Solution { 13 | 14 | /// Finds the maximum profit. 15 | /// 16 | /// - Parameter prices: An array where the i-th element is the price of 17 | /// a given stock on day i. 18 | /// 19 | /// - Returns: Maximum profit. 20 | /// 21 | /// - Complexity: 22 | /// - time: O(n), where n is the length of the prices. 23 | /// - space: O(1), only constant space is used. 24 | func maxProfit(_ prices: [Int]) -> Int { 25 | guard !prices.isEmpty else { return 0 } 26 | 27 | var ans = 0 28 | for i in 1.. prices[i - 1] else { continue } 30 | ans += prices[i] - prices[i - 1] 31 | } 32 | 33 | return ans 34 | } 35 | 36 | } 37 | -------------------------------------------------------------------------------- /Solutions/100-199/123 Best Time to Buy and Sell Stock III.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 123 Best Time to Buy and Sell Stock III.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 16/08/2020. 6 | // Copyright © 2020 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/ 12 | class Solution { 13 | 14 | /// Finds the maximum profit. 15 | /// 16 | /// - Parameter prices: An array where the i-th element is the price of 17 | /// a given stock on day i. 18 | /// - Returns: Maximum profit. 19 | /// 20 | /// - Complexity: 21 | /// - time: O(n), where n is the length of the prices. 22 | /// - space: O(1), only constant space is used. 23 | func maxProfit(_ prices: [Int]) -> Int { 24 | var buy1 = Int.max 25 | var buy2 = Int.max 26 | var sell1 = 0 27 | var sell2 = 0 28 | 29 | for price in prices { 30 | buy1 = min(buy1, price) 31 | sell1 = max(sell1, price - buy1) 32 | 33 | buy2 = min(buy2, price - sell1) 34 | sell2 = max(sell2, price - buy2) 35 | } 36 | 37 | return sell2 38 | } 39 | 40 | } 41 | -------------------------------------------------------------------------------- /Solutions/100-199/125 Valid Palindrome.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 125 Valid Palindrome.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 03/08/2020. 6 | // Copyright © 2020 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/valid-palindrome/ 12 | class Solution { 13 | 14 | /// Determines if a string is a palindrome. 15 | /// 16 | /// - Parameter s: The string. 17 | /// - Returns: True if the string is a palindrome, otherwise returns false. 18 | /// 19 | /// - Complexity: 20 | /// - time: O(n), where n is the length of the *s*. 21 | /// - space: O(1), only constant space is used. 22 | func isPalindrome(_ s: String) -> Bool { 23 | guard !s.isEmpty else { return true } 24 | 25 | let s = Array(s) 26 | var i = 0 27 | var j = s.count - 1 28 | 29 | while i < j { 30 | if !s[i].isLetter, !s[i].isNumber { 31 | i += 1 32 | continue 33 | } 34 | 35 | if !s[j].isLetter, !s[j].isNumber { 36 | j -= 1 37 | continue 38 | } 39 | 40 | guard s[i].lowercased() == s[j].lowercased() else { return false } 41 | i += 1 42 | j -= 1 43 | } 44 | 45 | return true 46 | } 47 | 48 | } 49 | -------------------------------------------------------------------------------- /Solutions/100-199/134 Gas Station.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 134 Gas Station.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 23/09/2020. 6 | // Copyright © 2020 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/gas-station/ 12 | class Solution { 13 | 14 | /// Finds out if you can once travel around the circle in a clockwise direction. 15 | /// 16 | /// - Parameters: 17 | /// - gas: The gas stations. 18 | /// - cost: Gas costs for travel from station `i` to the next station (i + 1). 19 | /// - Returns: The starting gas station's index if you can travel, otherwise returns -1. 20 | /// 21 | /// - Complexity: 22 | /// - time: O(n), where n is the number of gas stations. 23 | /// - space: O(1), only constant space is used. 24 | func canCompleteCircuit(_ gas: [Int], _ cost: [Int]) -> Int { 25 | var totalTank = 0 26 | var currTank = 0 27 | var startingStation = 0 28 | 29 | for i in 0..= 0 ? startingStation : -1 39 | } 40 | 41 | } 42 | -------------------------------------------------------------------------------- /Solutions/100-199/136 Single Number.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 136 Single Number.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 18/04/2020. 6 | // Copyright © 2020 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/single-number/ 12 | class Solution { 13 | 14 | /// Except for one, every other element appears twice in given array of integers. 15 | /// Finds that single one. 16 | /// 17 | /// - Parameter nums: Array of integers. 18 | /// - Returns: A number that appears only once. 19 | /// 20 | /// - Complexity: 21 | /// - time: O(n), where n is the length of the nums. 22 | /// - space: O(1), only constant space is used. 23 | func singleNumber(_ nums: [Int]) -> Int { 24 | var ans = 0 25 | 26 | for num in nums { 27 | ans ^= num 28 | } 29 | 30 | return ans 31 | } 32 | 33 | } 34 | -------------------------------------------------------------------------------- /Solutions/100-199/139 Word Break.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 139 Word Break.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 29/09/2020. 6 | // Copyright © 2020 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/word-break/ 12 | class Solution { 13 | 14 | /// Determines if `s` can be segmented into a space-separated sequence of one or more 15 | /// dictionary words. 16 | /// 17 | /// - Parameters: 18 | /// - s: A non-empty string. 19 | /// - wordDict: A dictionary containing a list of non-empty words. 20 | /// - Returns: True if `s` can be segmented, otherwise returns false. 21 | /// 22 | /// - Complexity: 23 | /// - time: O(n^2), where n is the length of `s`. 24 | /// - space: O(n), where n is the length of `s`. 25 | func wordBreak(_ s: String, _ wordDict: [String]) -> Bool { 26 | var dp = [Bool](repeating: false, count: s.count+1) 27 | dp[0] = true 28 | 29 | let chars = Array(s) 30 | let wordSet = Set(wordDict) 31 | 32 | for i in 1...s.count { 33 | for j in 0.. Bool { 23 | var slow = head 24 | var fast = head?.next 25 | 26 | while slow != nil, fast != nil { 27 | guard slow !== fast else { return true } 28 | 29 | slow = slow?.next 30 | fast = fast?.next?.next 31 | } 32 | 33 | return false 34 | } 35 | 36 | } 37 | 38 | /// Provided code 39 | public class ListNode { 40 | 41 | public var val: Int 42 | public var next: ListNode? 43 | 44 | public init(_ val: Int) { 45 | self.val = val 46 | self.next = nil 47 | } 48 | 49 | } 50 | -------------------------------------------------------------------------------- /Solutions/100-199/151 Reverse Words in a String.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 151 Reverse Words in a String.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 09/06/2020. 6 | // Copyright © 2020 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/reverse-words-in-a-string/ 12 | class Solution { 13 | 14 | /// Reverses the string word by word. 15 | /// 16 | /// - Parameter s: An input string. 17 | /// - Returns: Reversed string. 18 | /// 19 | /// - Complexity: 20 | /// - time: O(n), where n is the number of words in the input string. 21 | /// - space: O(m), where m is the length of the input string. 22 | func reverseWords(_ s: String) -> String { 23 | var ans = s.split(separator: " ") 24 | 25 | var start = 0 26 | var end = ans.count - 1 27 | 28 | while start < end { 29 | ans.swapAt(start, end) 30 | start += 1 31 | end -= 1 32 | } 33 | 34 | return ans.joined(separator: " ") 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /Solutions/100-199/152 Maximum Product Subarray.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 152 Maximum Product Subarray.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 11/09/2020. 6 | // Copyright © 2020 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/maximum-product-subarray/ 12 | class Solution { 13 | 14 | /// Finds the contiguous subarray within an array that has the largest product. 15 | /// 16 | /// - Parameter nums: The array of integers. 17 | /// - Returns: The largest product. 18 | /// 19 | /// - Complexity: 20 | /// - time: O(n), where n is the length of `nums`. 21 | /// - space: O(1), only constant space is used. 22 | func maxProduct(_ nums: [Int]) -> Int { 23 | guard !nums.isEmpty else { return 0 } 24 | 25 | var ans = nums[0] 26 | var maxSoFar = nums[0] 27 | var minSoFar = nums[0] 28 | 29 | for i in 1.. Int { 23 | var left = 0 24 | var right = nums.count-1 25 | var mid = 0 26 | 27 | while left < right { 28 | mid = left + (right - left) / 2 29 | 30 | if nums[mid] > nums[right] { 31 | left = mid + 1 32 | } else if nums[mid] < nums[right] { 33 | right = mid 34 | } else { 35 | right -= 1 36 | } 37 | } 38 | 39 | return nums[left] 40 | } 41 | 42 | } 43 | -------------------------------------------------------------------------------- /Solutions/100-199/167 Two Sum II - Input array is sorted.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 167 Two Sum II - Input array is sorted.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 13/06/2020. 6 | // Copyright © 2020 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/ 12 | class Solution { 13 | 14 | /// Finds two numbers such that they add up to a specific target number. 15 | /// 16 | /// - Parameters: 17 | /// - numbers: An array of integers sorted in ascending order. 18 | /// - target: Specific target number. 19 | /// - Returns: Indices of the two numbers such that they add up to the target, where 20 | /// index1 must be less than index2. 21 | /// 22 | /// - Complexity: 23 | /// - time: O(n), where n is the length of the numbers. 24 | /// - space: O(1), only constant space is used. 25 | func twoSum(_ numbers: [Int], _ target: Int) -> [Int] { 26 | guard !numbers.isEmpty else { return [] } 27 | var i = 0 28 | var j = numbers.count - 1 29 | 30 | while i < j { 31 | guard numbers[i] + numbers[j] != target else { break } 32 | 33 | if numbers[i] + numbers[j] > target { 34 | j -= 1 35 | } else { 36 | i += 1 37 | } 38 | } 39 | 40 | return [i + 1, j + 1] 41 | } 42 | 43 | } 44 | -------------------------------------------------------------------------------- /Solutions/100-199/169 Majority Element.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 169 Majority Element.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 06/05/2020. 6 | // Copyright © 2020 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/majority-element/ 12 | class Solution { 13 | 14 | /// Finds the majority element. 15 | /// 16 | /// - Parameter nums: Array of numbers. 17 | /// - Returns: Majority element. 18 | /// 19 | /// - Complexity: 20 | /// - time: O(n), where n is the length of the nums. 21 | /// - space: O(1), only constant space is used. 22 | func majorityElement(_ nums: [Int]) -> Int { 23 | var ans = -1 24 | var count = 0 25 | 26 | for num in nums { 27 | if count == 0 { 28 | ans = num 29 | } 30 | 31 | count += num == ans ? 1 : -1 32 | } 33 | 34 | return ans 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /Solutions/100-199/171 Excel Sheet Column Number.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 171 Excel Sheet Column Number.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 10/08/2020. 6 | // Copyright © 2020 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/excel-sheet-column-number/ 12 | class Solution { 13 | 14 | /// Finds the corresponding column number for a column title. 15 | /// 16 | /// - Parameter s: The column title. 17 | /// - Returns: The column title corresponding column number. 18 | /// 19 | /// - Complexity: 20 | /// - time: O(n), where n is the length of the column title. 21 | /// - space: O(1), only constant space is used. 22 | func titleToNumber(_ s: String) -> Int { 23 | let A = Int(("A" as Character).asciiValue ?? 0) 24 | var ans = 0 25 | 26 | for ch in s { 27 | ans *= 26 28 | ans += Int(ch.asciiValue ?? 0) - A + 1 29 | } 30 | 31 | return ans 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /Solutions/100-199/179 Largest Number.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 179 Largest Number.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 25/09/2020. 6 | // Copyright © 2020 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/largest-number/ 12 | class Solution { 13 | 14 | /// Arranges the list of non-negative integers to make the largest number. 15 | /// 16 | /// - Parameter nums: The list of non-negative integers. 17 | /// - Returns: The largest number. 18 | /// 19 | /// - Complexity: 20 | /// - time: O(n log(n)), where n is the length of `nums`. 21 | /// - space: O(n), where n is the length of `nums`. 22 | func largestNumber(_ nums: [Int]) -> String { 23 | guard !nums.isEmpty else { return "" } 24 | 25 | var strs = [String]() 26 | for num in nums { 27 | strs.append(String(num)) 28 | } 29 | 30 | strs.sort(by: { "\($0)\($1)" > "\($1)\($0)" }) 31 | 32 | guard let first = strs.first, first != "0" else { return "0" } 33 | 34 | var ans = "" 35 | for str in strs { 36 | ans = "\(ans)\(str)" 37 | } 38 | 39 | return ans 40 | } 41 | 42 | } 43 | -------------------------------------------------------------------------------- /Solutions/100-199/186 Reverse Words in a String II.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 186 Reverse Words in a String II.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 12/08/2020. 6 | // Copyright © 2020 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/reverse-words-in-a-string-ii/ 12 | class Solution { 13 | 14 | /// Reverses the string word by word. 15 | /// 16 | /// - Parameter s: The string. 17 | /// 18 | /// - Complexity: 19 | /// - time: O(n), where n is the length of the string. 20 | /// - space: O(1), only constant space is used. 21 | func reverseWords(_ s: inout [Character]) { 22 | reverse(&s, start: 0, end: s.count - 1) 23 | 24 | var start = 0 25 | for end in 0.. Int { 23 | var ans = 0 24 | 25 | var n = n 26 | while n != 0 { 27 | n &= n - 1 28 | ans += 1 29 | } 30 | 31 | return ans 32 | } 33 | 34 | // OR 35 | 36 | /// Finds the number of '1' bits in the given integer. 37 | /// 38 | /// - Parameter n: An integer. 39 | /// - Returns: The number of '1' bits in the given integer. 40 | /// 41 | /// - Complexity: 42 | /// - time: O(1), only constant time is used. 43 | /// - space: O(1), only constant space is used. 44 | func hammingWeight(_ n: Int) -> Int { 45 | n.nonzeroBitCount 46 | } 47 | 48 | } 49 | -------------------------------------------------------------------------------- /Solutions/100-199/198 House Robber.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 198 House Robber.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 14/09/2020. 6 | // Copyright © 2020 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/house-robber/ 12 | class Solution { 13 | 14 | /// Determines the maximum amount of money you can rob tonight without alerting the 15 | /// police. 16 | /// 17 | /// - Parameter nums: A list of non-negative integers representing the amount of money 18 | /// of each house. 19 | /// - Returns: The maximum amount of money you can rob. 20 | /// 21 | /// - Complexity: 22 | /// - time: O(n), where n is the length of the `nums`. 23 | /// - space: O(1), only constant space is used. 24 | func rob(_ nums: [Int]) -> Int { 25 | var prev = 0 26 | var ans = 0 27 | 28 | for num in nums { 29 | let tmp = ans 30 | ans = max(prev + num, ans) 31 | prev = tmp 32 | } 33 | 34 | return ans 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /Solutions/1000-1099/1009 Complement of Base 10 Integer.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 1009 Complement of Base 10 Integer.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 04/05/2020. 6 | // Copyright © 2020 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/complement-of-base-10-integer/ 12 | class Solution { 13 | 14 | /// Flips the bits of num. 15 | /// 16 | /// - Parameter num: Non-negative integer. 17 | /// - Returns: Complement of num. 18 | /// 19 | /// - Complexity: 20 | /// - time: O(n), where n is the number of digits in num. 21 | /// - space: O(1), only constant space is used. 22 | func bitwiseComplement(_ N: Int) -> Int { 23 | guard N != 0 else { return 1 } 24 | var i = 1 25 | 26 | while i <= N { 27 | i <<= 1 28 | } 29 | 30 | return (i - 1) ^ N 31 | } 32 | 33 | } 34 | -------------------------------------------------------------------------------- /Solutions/1000-1099/1010 Pairs of Songs With Total Durations Divisible by 60.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 1010 Pairs of Songs With Total Durations Divisible by 60.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 08/12/2020. 6 | // Copyright © 2020 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/pairs-of-songs-with-total-durations-divisible-by-60/ 12 | class Solution { 13 | 14 | /// Finds the number of pairs of songs for which their total duration in seconds 15 | /// is divisible by 60. 16 | /// 17 | /// - Parameter time: A list of song duration. 18 | /// - Returns: The number of pairs of songs. 19 | /// 20 | /// - Complexity: 21 | /// - time: O(n), where n is the length of `time`. 22 | /// - space: O(n), where n is the length of `time`. 23 | func numPairsDivisibleBy60(_ time: [Int]) -> Int { 24 | var ans = 0 25 | var dict = [Int: Int]() 26 | 27 | for t in time { 28 | if t % 60 == 0 { 29 | ans += dict[0] ?? 0 30 | } else if let val = dict[60 - t % 60] { 31 | ans += val 32 | } 33 | 34 | dict[t % 60, default: 0] += 1 35 | } 36 | 37 | return ans 38 | } 39 | 40 | } 41 | -------------------------------------------------------------------------------- /Solutions/1000-1099/1015 Smallest Integer Divisible by K.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 1015 Smallest Integer Divisible by K.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 25/11/2020. 6 | // Copyright © 2020 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/smallest-integer-divisible-by-k/ 12 | class Solution { 13 | 14 | /// Finds the length of the smallest positive integer `N` such that `N` is 15 | /// divisible by `K`, and `N` only contains the digit `1`. 16 | /// 17 | /// - Parameter K: A positive integer. 18 | /// - Returns: The length of `N` if such exists, otherwise returns -1. 19 | /// 20 | /// - Complexity: 21 | /// - time: O(K), where K is the given number `K`. 22 | /// - space: O(1), only constant space is used. 23 | func smallestRepunitDivByK(_ K: Int) -> Int { 24 | var ans = 0 25 | 26 | for i in 1...K { 27 | ans = (ans * 10 + 1) % K 28 | guard ans == 0 else { continue } 29 | return i 30 | } 31 | 32 | return -1 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /Solutions/1000-1099/1035 Uncrossed Lines.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 1035 Uncrossed Lines.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 25/05/2020. 6 | // Copyright © 2020 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/uncrossed-lines/ 12 | class Solution { 13 | 14 | /// Calculates the maximum number of uncrossed Lines. 15 | /// 16 | /// - Parameters: 17 | /// - A: An array A. 18 | /// - B: An array B. 19 | /// - Returns: The maximum number of connecting lines. 20 | /// 21 | /// - Complexity: 22 | /// - time: O(n * m), where n is the length of A and m is the length of B. 23 | /// - space: O(m), where m is the length of *B*. 24 | func maxUncrossedLines(_ A: [Int], _ B: [Int]) -> Int { 25 | var dp = [Int](repeating: 0, count: B.count+1) 26 | 27 | for i in 1...A.count { 28 | var prev = 0 29 | for j in 1...B.count { 30 | let cur = dp[j] 31 | if A[i-1] == B[j-1] { 32 | dp[j] = prev + 1 33 | } else { 34 | dp[j] = max(dp[j-1], dp[j]) 35 | } 36 | prev = cur 37 | } 38 | } 39 | 40 | return dp[B.count] 41 | } 42 | 43 | } 44 | -------------------------------------------------------------------------------- /Solutions/1000-1099/1041 Robot Bounded In Circle.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 1041 Robot Bounded In Circle.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 17/09/2020. 6 | // Copyright © 2020 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/robot-bounded-in-circle/ 12 | class Solution { 13 | 14 | /// Finds if the robot is bounded in a circle. 15 | /// 16 | /// - Parameter instructions: Movement instructions. 17 | /// - Returns: True if there is a circle that the robot never leaves, otherwise returns 18 | /// false. 19 | /// 20 | /// - Complexity: 21 | /// - time: O(n), where n is the number of `instructions`. 22 | /// - space: O(1), only constant space is used. 23 | func isRobotBounded(_ instructions: String) -> Bool { 24 | var directions: [(x: Int, y: Int)] = [(0, 1), (1, 0), (0, -1), (-1, 0)] 25 | var x = 0 26 | var y = 0 27 | var idx = 0 28 | 29 | for instruction in instructions { 30 | if instruction == "L" { 31 | idx = (idx + 3) % 4 32 | } else if instruction == "R" { 33 | idx = (idx + 1) % 4 34 | } else { 35 | x += directions[idx].x 36 | y += directions[idx].y 37 | } 38 | } 39 | 40 | return (x == 0 && y == 0) || idx != 0 41 | } 42 | 43 | } 44 | -------------------------------------------------------------------------------- /Solutions/1000-1099/1056 Confusing Number.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 1056 Confusing Number.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 07/03/2021. 6 | // Copyright © 2021 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/confusing-number/ 12 | class Solution { 13 | 14 | private let dict = [0: 0, 1: 1, 6: 9, 8: 8, 9: 6] 15 | 16 | /// Finds if `N` is a confusing number. 17 | /// 18 | /// - Parameter N: The number. 19 | /// - Returns: True if `N` is a confusing number, otherwise return false. 20 | /// 21 | /// - Complexity: 22 | /// - time: O(log n), where n is the length of `N`. 23 | /// - space: O(1), only constant space is used. 24 | func confusingNumber(_ N: Int) -> Bool { 25 | var n = N 26 | var ans = 0 27 | 28 | while n > 0 { 29 | guard let num = dict[n % 10] else { return false } 30 | ans = ans * 10 + num 31 | n /= 10 32 | } 33 | return ans != N 34 | } 35 | 36 | } 37 | -------------------------------------------------------------------------------- /Solutions/1000-1099/1064 Fixed Point.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 1064 Fixed Point.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 10/03/2021. 6 | // Copyright © 2021 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/fixed-point/ 12 | class Solution { 13 | 14 | /// Finds the smallest index `i` that satisfies `arr[i] == i`. 15 | /// 16 | /// - Parameter arr: An array of distinct integers. 17 | /// - Returns: The smallest index. 18 | /// 19 | /// - Complexity: 20 | /// - time: O(log n), where n is the length of `arr`. 21 | /// - space: O(1), only constant space is used. 22 | func fixedPoint(_ arr: [Int]) -> Int { 23 | var lo = 0 24 | var hi = arr.count - 1 25 | 26 | while lo < hi { 27 | let mid = lo + (hi - lo) / 2 28 | 29 | if arr[mid] < mid { 30 | lo = mid + 1 31 | } else { 32 | hi = mid 33 | } 34 | } 35 | 36 | return arr[lo] == lo ? lo : -1 37 | } 38 | 39 | } 40 | -------------------------------------------------------------------------------- /Solutions/1000-1099/1094 Car Pooling.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 1094 Car Pooling.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 21/09/2020. 6 | // Copyright © 2020 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/car-pooling/ 12 | class Solution { 13 | 14 | /// Finds if it is possible to pick up and drop off all passengers for all the given 15 | /// trips. 16 | /// 17 | /// - Parameters: 18 | /// - trips: A list of trips. 19 | /// - capacity: A number of empty seats. 20 | /// - Returns: True if it is possible, otherwise returns false. 21 | /// 22 | /// - Complexity: 23 | /// - time: O(max(n, 1_001)), where n is the number of `trips`. 24 | /// - space: O(1), only constant space is used. 25 | func carPooling(_ trips: [[Int]], _ capacity: Int) -> Bool { 26 | var timestamp = [Int](repeating: 0, count: 1_001) 27 | 28 | for trip in trips { 29 | timestamp[trip[1]] += trip[0] 30 | timestamp[trip[2]] -= trip[0] 31 | } 32 | 33 | var used = 0 34 | for time in timestamp { 35 | used += time 36 | guard used > capacity else { continue } 37 | return false 38 | } 39 | 40 | return true 41 | } 42 | 43 | } 44 | -------------------------------------------------------------------------------- /Solutions/1000-1099/1099 Two Sum Less Than K.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 1099 Two Sum Less Than K.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 08/11/2020. 6 | // Copyright © 2020 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/two-sum-less-than-k/ 12 | class Solution { 13 | 14 | /// Finds the maximum sum less than `K` between two numbers in a given array. If 15 | /// this sum does not exist, it returns -1. 16 | /// 17 | /// - Parameters: 18 | /// - A: An array of integers. 19 | /// - K: An integer. 20 | /// - Returns: The maximum sum if exists, otherwise returns -1. 21 | /// 22 | /// - Complexity: 23 | /// - time: O(n log(n)), where n is the length of `A`. 24 | /// - space: O(n), where n is the length of `A`. 25 | func twoSumLessThanK(_ A: [Int], _ K: Int) -> Int { 26 | var arr = A.sorted(by: <) 27 | 28 | var ans = -1 29 | var i = 0 30 | var j = arr.count - 1 31 | 32 | while i < j { 33 | let sum = arr[i] + arr[j] 34 | 35 | if sum < K { 36 | ans = max(ans, sum) 37 | i += 1 38 | } else { 39 | j -= 1 40 | } 41 | } 42 | 43 | return ans 44 | } 45 | 46 | } 47 | -------------------------------------------------------------------------------- /Solutions/1100-1199/1103 Distribute Candies to People.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 1103 Distribute Candies to People.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 17/08/2020. 6 | // Copyright © 2020 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/distribute-candies-to-people/ 12 | class Solution { 13 | 14 | /// Calculates the distribution of the candies. 15 | /// 16 | /// - Parameters: 17 | /// - candies: The number of candies. 18 | /// - num_people: The number of people. 19 | /// - Returns: The final distribution of candies. 20 | /// 21 | /// - Complexity: 22 | /// - time: O(sqrt(n)), where n is the number of candies. 23 | /// - space: O(m), where m is the number of people. 24 | func distributeCandies(_ candies: Int, _ num_people: Int) -> [Int] { 25 | var ans = [Int](repeating: 0, count: num_people) 26 | 27 | var candies = candies 28 | var curr = 0 29 | 30 | while candies > 0 { 31 | ans[curr % num_people] += min(candies, curr + 1) 32 | curr += 1 33 | candies -= curr 34 | } 35 | 36 | return ans 37 | } 38 | 39 | } 40 | -------------------------------------------------------------------------------- /Solutions/1100-1199/1165 Single-Row Keyboard.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 1165 Single-Row Keyboard.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 12/03/2021. 6 | // Copyright © 2021 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/single-row-keyboard/ 12 | class Solution { 13 | 14 | /// Finds how much time it takes to type `word` with one finger. 15 | /// 16 | /// - Parameters: 17 | /// - keyboard: The string. 18 | /// - word: The word. 19 | /// - Returns: How much time it takes to type `word` with one finger. 20 | /// 21 | /// - Complexity: 22 | /// - time: O(max(n, m)), where n is the length of `keyboard`, and m is 23 | /// the length of `word`. 24 | /// - space: O(n), where n is the length of `keyboard`. 25 | func calculateTime(_ keyboard: String, _ word: String) -> Int { 26 | var dict = [Character: Int]() 27 | 28 | for (i, key) in keyboard.enumerated() { 29 | dict[key] = i 30 | } 31 | 32 | var prev = 0 33 | var ans = 0 34 | 35 | for ch in word { 36 | ans += abs(prev - (dict[ch] ?? 0)) 37 | 38 | prev = dict[ch] ?? 0 39 | } 40 | 41 | return ans 42 | } 43 | 44 | } 45 | -------------------------------------------------------------------------------- /Solutions/1200-1299/1217 Minimum Cost to Move Chips to The Same Position.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 1217 Minimum Cost to Move Chips to The Same Position.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 05/11/2020. 6 | // Copyright © 2020 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/minimum-cost-to-move-chips-to-the-same-position/ 12 | class Solution { 13 | 14 | /// Finds the minimum cost needed to move all the chips to the same position. 15 | /// 16 | /// - Parameter position: The positions of chips. 17 | /// - Returns: The minimum cost needed to move all the chips. 18 | /// 19 | /// - Complexity: 20 | /// - time: O(n), where n is the number of chips. 21 | /// - space: O(1), only constant space is used. 22 | func minCostToMoveChips(_ position: [Int]) -> Int { 23 | var even = 0 24 | var odd = 0 25 | 26 | for pos in position { 27 | if pos % 2 == 0 { 28 | even += 1 29 | } else { 30 | odd += 1 31 | } 32 | } 33 | 34 | return min(odd, even) 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /Solutions/1200-1299/1288 Remove Covered Intervals.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 1288 Remove Covered Intervals.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 04/10/2020. 6 | // Copyright © 2020 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/remove-covered-intervals/ 12 | class Solution { 13 | 14 | /// Calculates the number of intervals that are covered by another interval in the list. 15 | /// 16 | /// - Parameter intervals: A list of intervals. 17 | /// - Returns: The number of remaining intervals. 18 | /// 19 | /// - Complexity: 20 | /// - time: O(n log(n)), where n is the number of intervals. 21 | /// - space: O(n), where n is the number of intervals. 22 | func removeCoveredIntervals(_ intervals: [[Int]]) -> Int { 23 | let intervals = intervals.sorted(by: { $0[0] != $1[0] ? $0[0] < $1[0] : $0[1] > $1[1] }) 24 | 25 | var ans = 0 26 | var prevEnd = 0 27 | 28 | for interval in intervals { 29 | guard prevEnd < interval[1] else { continue } 30 | ans += 1 31 | prevEnd = interval[1] 32 | } 33 | 34 | return ans 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /Solutions/1200-1299/1295 Find Numbers with Even Number of Digits.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 1295 Find Numbers with Even Number of Digits.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 05/09/2020. 6 | // Copyright © 2020 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/find-numbers-with-even-number-of-digits/ 12 | class Solution { 13 | 14 | /// Finds how many numbers in a given array contain an even number of digits. 15 | /// 16 | /// - Parameter nums: The array of integers. 17 | /// - Returns: How many numbers contain an even number of digits. 18 | /// 19 | /// - Complexity: 20 | /// - time: O(n), where n is the length of nums. 21 | /// - space: O(1), only constant space is used. 22 | func findNumbers(_ nums: [Int]) -> Int { 23 | var ans = 0 24 | 25 | for num in nums { 26 | ans += String(num).count % 2 == 0 ? 1 : 0 27 | } 28 | 29 | return ans 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /Solutions/1300-1399/1306 Jump Game III.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 1306 Jump Game III.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 29/11/2020. 6 | // Copyright © 2020 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/jump-game-iii/ 12 | class Solution { 13 | 14 | /// Checks if you can reach any index with value 0. 15 | /// 16 | /// - Parameters: 17 | /// - arr: An array of non-negative integers. 18 | /// - start: Start index. 19 | /// - Returns: True if index with value 0 can be reached, otherwise returns false. 20 | /// 21 | /// - Complexity: 22 | /// - time: O(n), where n is the length of the `arr`. 23 | /// - space: O(n), where n is the length of the `arr`. 24 | func canReach(_ arr: [Int], _ start: Int) -> Bool { 25 | var arr = arr 26 | return dfs(&arr, arr.count, start) 27 | } 28 | 29 | private func dfs(_ arr: inout [Int], _ n: Int, _ start: Int) -> Bool { 30 | guard start >= 0, start < n, arr[start] >= 0 else { return false } 31 | guard arr[start] != 0 else { return true } 32 | 33 | arr[start] = -arr[start] 34 | return dfs(&arr, n, start + arr[start]) || dfs(&arr, n, start - arr[start]) 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /Solutions/1300-1399/1332 Remove Palindromic Subsequences.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 1332 Remove Palindromic Subsequences.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 08/03/2021. 6 | // Copyright © 2021 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/remove-palindromic-subsequences/ 12 | class Solution { 13 | 14 | /// Finds the minimum number of steps to make the given string empty. 15 | /// 16 | /// - Parameter s: The string. 17 | /// - Returns: The minimum number of steps. 18 | /// 19 | /// - Complexity: 20 | /// - time: O(n), where n is the length of `s`. 21 | /// - space: O(1), only constant space is used. 22 | func removePalindromeSub(_ s: String) -> Int { 23 | guard !s.isEmpty else { return 0 } 24 | 25 | return isPalindrome(Array(s)) ? 1 : 2 26 | } 27 | 28 | private func isPalindrome(_ s: [Character]) -> Bool { 29 | var start = 0 30 | var end = s.count - 1 31 | 32 | while start < end { 33 | guard s[start] == s[end] else { return false } 34 | start += 1 35 | end -= 1 36 | } 37 | 38 | return true 39 | } 40 | 41 | } 42 | -------------------------------------------------------------------------------- /Solutions/1300-1399/1342 Number of Steps to Reduce a Number to Zero.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 1342 Number of Steps to Reduce a Number to Zero.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 12/02/2021. 6 | // Copyright © 2021 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/number-of-steps-to-reduce-a-number-to-zero/ 12 | class Solution { 13 | 14 | /// Finds the number of steps to reduce the given integer to zero. 15 | /// 16 | /// - Parameter num: A non-negative integer. 17 | /// - Returns: The number of steps. 18 | /// 19 | /// - Complexity: 20 | /// - time: O(log n), where n is the given integer. 21 | /// - space: O(1), only constant space is used. 22 | func numberOfSteps(_ num: Int) -> Int { 23 | var num = num 24 | var ans = 0 25 | 26 | while num > 0 { 27 | if num % 2 == 0 { 28 | num /= 2 29 | } else { 30 | num -= 1 31 | } 32 | ans += 1 33 | } 34 | 35 | return ans 36 | } 37 | 38 | } 39 | -------------------------------------------------------------------------------- /Solutions/1300-1399/1344 Angle Between Hands of a Clock.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 1344 Angle Between Hands of a Clock.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 14/07/2020. 6 | // Copyright © 2020 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/angle-between-hands-of-a-clock/ 12 | class Solution { 13 | 14 | /// Calculates the smaller angle formed between the hour and the minute hand. 15 | /// 16 | /// - Parameters: 17 | /// - hour: Hour hand. 18 | /// - minutes: Minute hand. 19 | /// - Returns: The smaller angle between the hour and the minute hand. 20 | /// 21 | /// - Complexity: 22 | /// - time: O(1), only constant time is used. 23 | /// - space: O(1), only constant space is used. 24 | func angleClock(_ hour: Int, _ minutes: Int) -> Double { 25 | let hour = (Double(hour%12) * 30.0) + (Double(minutes) * 0.5) 26 | let minutes = Double(minutes) * 6.0 27 | let ans = Double(abs(minutes - hour)) 28 | 29 | return ans <= 180 ? ans : 360 - ans 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /Solutions/1400-1499/1426 Counting Elements.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 1426 Counting Elements.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 05/03/2021. 6 | // Copyright © 2021 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/counting-elements/ 12 | class Solution { 13 | 14 | /// Finds how many elements x is in `arr`, such that x + 1 is also in `arr`. 15 | /// 16 | /// - Parameter arr: An array. 17 | /// - Returns: The number of elements. 18 | /// 19 | /// - Complexity: 20 | /// - time: O(n), where n is the length of `arr`. 21 | /// - space: O(n), where n is the length of `arr`. 22 | func countElements(_ arr: [Int]) -> Int { 23 | var tmp = Set() 24 | 25 | for a in arr { 26 | tmp.insert(a) 27 | } 28 | 29 | var ans = 0 30 | 31 | for a in arr { 32 | guard tmp.contains(a+1) else { continue } 33 | ans += 1 34 | } 35 | 36 | return ans 37 | } 38 | 39 | } 40 | -------------------------------------------------------------------------------- /Solutions/1400-1499/1437 Check If All 1's Are at Least Length K Places Away.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 1437 Check If All 1's Are at Least Length K Places Away.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 25/01/2021. 6 | // Copyright © 2021 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/check-if-all-1s-are-at-least-length-k-places-away/ 12 | class Solution { 13 | 14 | /// Checks if all 1's are at least length `k` places away. 15 | /// 16 | /// - Parameters: 17 | /// - nums: An array of 0s and 1s. 18 | /// - k: An integer. 19 | /// - Returns: True if all 1's are at least k places away from each other, 20 | /// otherwise returns false. 21 | /// 22 | /// - Complexity: 23 | /// - time: O(n), where n is the length of `nums`. 24 | /// - space: O(1), only constant space is used. 25 | func kLengthApart(_ nums: [Int], _ k: Int) -> Bool { 26 | guard k > 0 else { return true } 27 | 28 | var i: Int? 29 | 30 | for (j, num) in nums.enumerated() { 31 | guard num == 1 else { continue } 32 | 33 | if let prev = i, j - prev <= k { 34 | return false 35 | } 36 | 37 | i = j 38 | } 39 | 40 | return true 41 | } 42 | 43 | } 44 | -------------------------------------------------------------------------------- /Solutions/1400-1499/1446 Consecutive Characters.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 1446 Consecutive Characters.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 03/11/2020. 6 | // Copyright © 2020 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/consecutive-characters/ 12 | class Solution { 13 | 14 | /// Finds the power of the string. 15 | /// 16 | /// - Parameter s: The string. 17 | /// - Returns: The power of the string. 18 | /// 19 | /// - Complexity: 20 | /// - time: O(n), where n is the length of `s`. 21 | /// - space: O(1), only constant space is used. 22 | func maxPower(_ s: String) -> Int { 23 | var ans = 0 24 | var cur = 0 25 | 26 | var prev: Character = "-" 27 | 28 | for ch in s { 29 | if prev == ch { 30 | cur += 1 31 | } else { 32 | cur = 1 33 | prev = ch 34 | } 35 | 36 | ans = max(ans, cur) 37 | } 38 | 39 | return ans 40 | } 41 | 42 | } 43 | -------------------------------------------------------------------------------- /Solutions/1400-1499/1492 The kth Factor of n.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 1492 The kth Factor of n.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 04/12/2020. 6 | // Copyright © 2020 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/the-kth-factor-of-n/ 12 | class Solution { 13 | 14 | /// Finds the kth factor or returns -1 if `n` has less than `k` factors. 15 | /// 16 | /// - Parameters: 17 | /// - n: Positive integer. 18 | /// - k: Positive integer. 19 | /// - Returns: The kth factor if exist, otherwise returns -1. 20 | /// 21 | /// - Complexity: 22 | /// - time: O(n), where n is given `n`. 23 | /// - space: O(1), only constant space is used. 24 | func kthFactor(_ n: Int, _ k: Int) -> Int { 25 | var k = k 26 | 27 | for i in 1...(n / 2 + 1) { 28 | guard n % i == 0 else { continue } 29 | k -= 1 30 | guard k == 0 else { continue } 31 | return i 32 | } 33 | 34 | return k == 1 ? n : -1 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /Solutions/1500-1599/1506 Find Root of N-Ary Tree.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 1506 Find Root of N-Ary Tree.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 08/01/2021. 6 | // Copyright © 2021 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/find-root-of-n-ary-tree/ 12 | class Solution { 13 | 14 | /// Finds the root of the N-ary tree. 15 | /// 16 | /// - Parameter tree: An array of nodes. 17 | /// - Returns: The root of the N-ary tree. 18 | /// 19 | /// - Complexity: 20 | /// - time: O(n), where n is the number of nodes. 21 | /// - space: O(1), only constant space is used. 22 | func findRoot(_ tree: [Node]) -> Node? { 23 | var sum = 0 24 | 25 | for node in tree { 26 | sum += node.val 27 | for child in node.children { 28 | sum -= child.val 29 | } 30 | } 31 | 32 | for node in tree { 33 | guard node.val == sum else { continue } 34 | return node 35 | } 36 | 37 | return nil 38 | } 39 | 40 | } 41 | 42 | /// Provided code 43 | public class Node { 44 | 45 | public var val: Int 46 | public var children: [Node] 47 | 48 | public init(_ val: Int) { 49 | self.val = val 50 | self.children = [] 51 | } 52 | 53 | } 54 | -------------------------------------------------------------------------------- /Solutions/1500-1599/1510 Stone Game IV.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 1510 Stone Game IV.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 25/10/2020. 6 | // Copyright © 2020 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/stone-game-iv/ 12 | class Solution { 13 | 14 | /// Finds if Alice can win a game. 15 | /// 16 | /// - Parameter n: Number of stones. 17 | /// - Returns: True if Alice wins the game, otherwise returns false. 18 | /// 19 | /// - Complexity: 20 | /// - time: O(n sqrt(n)), where n is the given number of stones. 21 | /// - space: O(n), where n is the given number of stones. 22 | func winnerSquareGame(_ n: Int) -> Bool { 23 | var dp = [Bool](repeating: false, count: n+1) 24 | 25 | for i in 0...n { 26 | guard !dp[i] else { continue } 27 | var j = 1 28 | while i + j * j <= n { 29 | dp[i + j * j] = true 30 | j += 1 31 | } 32 | } 33 | 34 | return dp[n] 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /Solutions/1500-1599/1539 Kth Missing Positive Number.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 1539 Kth Missing Positive Number.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 06/01/2021. 6 | // Copyright © 2021 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/kth-missing-positive-number/ 12 | class Solution { 13 | 14 | /// Finds the `k`-th positive integer that is missing from the given array. 15 | /// 16 | /// - Parameters: 17 | /// - arr: An array arr sorted in a strictly increasing order. 18 | /// - k: An integer. 19 | /// - Returns: The `k`-th missing integer. 20 | /// 21 | /// - Complexity: 22 | /// - time: O(log(n)), where n is the length of `arr`. 23 | /// - space: O(1), only constant space is used. 24 | func findKthPositive(_ arr: [Int], _ k: Int) -> Int { 25 | var left = 0 26 | var right = arr.count - 1 27 | 28 | while left <= right { 29 | let mid = left + (right - left) / 2 30 | 31 | if arr[mid] - mid - 1 < k { 32 | left = mid + 1 33 | } else { 34 | right = mid - 1 35 | } 36 | } 37 | 38 | return left + k 39 | } 40 | 41 | } 42 | -------------------------------------------------------------------------------- /Solutions/1600-1699/1641 Count Sorted Vowel Strings.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 1641 Count Sorted Vowel Strings.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 17/01/2021. 6 | // Copyright © 2021 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/count-sorted-vowel-strings/ 12 | class Solution { 13 | 14 | /// Finds the number of strings of length `n` that consist only of vowels 15 | /// (a, e, i, o, u) and are lexicographically sorted. 16 | /// 17 | /// - Parameter n: An integer. 18 | /// - Returns: The number of strings. 19 | /// 20 | /// - Complexity: 21 | /// - time: O(n), where n is given `n`. 22 | /// - space: O(n), where n is given `n`. 23 | func countVowelStrings(_ n: Int) -> Int { 24 | guard n > 1 else { return 5 } 25 | var dp = [[Int]](repeating: [Int](repeating: 0, count: 6), count: n + 1) 26 | 27 | for i in 1...5 { 28 | dp[1][i] = i 29 | } 30 | 31 | for i in 2...n { 32 | dp[i][1] = 1 33 | for j in 2...5 { 34 | dp[i][j] = dp[i][j - 1] + dp[i - 1][j] 35 | } 36 | } 37 | 38 | return dp[n][5] 39 | } 40 | 41 | } 42 | -------------------------------------------------------------------------------- /Solutions/1600-1699/1646 Get Maximum in Generated Array.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 1646 Get Maximum in Generated Array.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 15/01/2021. 6 | // Copyright © 2021 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/get-maximum-in-generated-array/ 12 | class Solution { 13 | 14 | /// Finds the maximum integer in the array. 15 | /// 16 | /// - Parameter n: An integer. 17 | /// - Returns: The maximum integer in the array. 18 | /// 19 | /// - Complexity: 20 | /// - time: O(n), where n is given `n`. 21 | /// - space: O(n), where n is given `n`. 22 | func getMaximumGenerated(_ n: Int) -> Int { 23 | guard n > 1 else { return n } 24 | 25 | var arr = [Int](repeating: 0, count: n+1) 26 | arr[1] = 1 27 | 28 | var ans = 1 29 | for i in 2...n { 30 | if i % 2 == 0 { 31 | arr[i] = arr[i / 2] 32 | } else { 33 | arr[i] = arr[i / 2] + arr[i / 2 + 1] 34 | } 35 | ans = max(ans, arr[i]) 36 | } 37 | 38 | return ans 39 | } 40 | 41 | } 42 | -------------------------------------------------------------------------------- /Solutions/1600-1699/1657 Determine if Two Strings Are Close.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 1657 Determine if Two Strings Are Close.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 22/01/2021. 6 | // Copyright © 2021 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/determine-if-two-strings-are-close/ 12 | class Solution { 13 | 14 | /// Finds if two strings are close. 15 | /// 16 | /// - Parameters: 17 | /// - word1: First word. 18 | /// - word2: Second word. 19 | /// - Returns: True if `word1` and `word2` are close, otherwise returns false. 20 | /// 21 | /// - Complexity: 22 | /// - time: O(n), where n is the max length of `word1` and `word2`. 23 | /// - space: O(n), where n is the max length of `word1` and `word2`. 24 | func closeStrings(_ word1: String, _ word2: String) -> Bool { 25 | guard word1.count == word2.count else { return false } 26 | 27 | var dict1 = [Character: Int]() 28 | for ch in word1 { 29 | dict1[ch, default: 0] += 1 30 | } 31 | 32 | var dict2 = [Character: Int]() 33 | for ch in word2 { 34 | dict2[ch, default: 0] += 1 35 | } 36 | 37 | return Set(dict1.keys) == Set(dict2.keys) && 38 | Set(dict1.values) == Set(dict2.values) 39 | } 40 | 41 | } 42 | -------------------------------------------------------------------------------- /Solutions/1600-1699/1662 Check If Two String Arrays are Equivalent.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 1662 Check If Two String Arrays are Equivalent.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 08/01/2021. 6 | // Copyright © 2021 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/check-if-two-string-arrays-are-equivalent/ 12 | class Solution { 13 | 14 | /// Finds if two string arrays are equivalent. 15 | /// 16 | /// - Parameters: 17 | /// - word1: An array of string. 18 | /// - word2: An array of string. 19 | /// - Returns: True if the two arrays represent the same string, otherwise 20 | /// returns false. 21 | /// 22 | /// - Complexity: 23 | /// - time: O(n), where n is the number of characters in `word1` and `word2`. 24 | /// - space: O(n), where n is the number of characters in `word1` and `word2`. 25 | func arrayStringsAreEqual(_ word1: [String], _ word2: [String]) -> Bool { 26 | word1.joined(separator: "") == word2.joined(separator: "") 27 | } 28 | 29 | } 30 | -------------------------------------------------------------------------------- /Solutions/1600-1699/1663 Smallest String With A Given Numeric Value.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 1663 Smallest String With A Given Numeric Value.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 28/01/2021. 6 | // Copyright © 2021 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/smallest-string-with-a-given-numeric-value/ 12 | class Solution { 13 | 14 | /// Finds the lexicographically smallest string with length equal to `n` and 15 | /// numeric value equal to `k`. 16 | /// 17 | /// - Parameters: 18 | /// - n: An integer. 19 | /// - k: An integer. 20 | /// - Returns: The lexicographically smallest string. 21 | /// 22 | /// - Complexity: 23 | /// - time: O(n), where n is the given `n`. 24 | /// - space: O(n), where n is the given `n`. 25 | func getSmallestString(_ n: Int, _ k: Int) -> String { 26 | let a = Character("a").asciiValue ?? 0 27 | var ans = [String](repeating: "", count: n) 28 | 29 | var k = k 30 | for i in (0.. [Int] { 25 | var tmp = [Int]() 26 | var count = nums.count - k 27 | 28 | for num in nums { 29 | while !tmp.isEmpty, let last = tmp.last, last > num, count > 0 { 30 | tmp.removeLast() 31 | count -= 1 32 | } 33 | tmp.append(num) 34 | } 35 | 36 | return Array(tmp[0.. Int { 25 | var dict = [Int: Int]() 26 | 27 | var ans = 0 28 | for num in nums { 29 | if let val = dict[k - num] { 30 | dict[k - num] = val > 1 ? val - 1 : nil 31 | ans += 1 32 | } else { 33 | dict[num, default: 0] += 1 34 | } 35 | } 36 | 37 | return ans 38 | } 39 | 40 | } 41 | -------------------------------------------------------------------------------- /Solutions/1600-1699/1680 Concatenation of Consecutive Binary Numbers.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 1680 Concatenation of Consecutive Binary Numbers.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 27/01/2021. 6 | // Copyright © 2021 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/concatenation-of-consecutive-binary-numbers/ 12 | class Solution { 13 | 14 | /// Finds the decimal value of the binary string formed by concatenating the 15 | /// binary representations of 1 to `n` in order, modulo 10^9 + 7. 16 | /// 17 | /// - Parameter n: An integer. 18 | /// - Returns: The decimal value of the binary string. 19 | /// 20 | /// - Complexity: 21 | /// - time: O(n), where n is the given `n`. 22 | /// - space: O(1), only constant space is used. 23 | func concatenatedBinary(_ n: Int) -> Int { 24 | let mod = 1_000_000_007 25 | var length = 0 26 | var ans = 0 27 | 28 | for i in 1...n { 29 | if i & (i - 1) == 0 { 30 | length += 1 31 | } 32 | ans = ((ans << length) | i) % mod 33 | } 34 | 35 | return ans 36 | } 37 | 38 | } 39 | -------------------------------------------------------------------------------- /Solutions/200-299/202 Happy Number.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 202 Happy Number.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 26/02/2021. 6 | // Copyright © 2021 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/happy-number/ 12 | class Solution { 13 | 14 | /// Finds if a given number is happy humber. 15 | /// 16 | /// - Parameter n: The number. 17 | /// - Returns: True if `n` is a happy number, otherwise returns false. 18 | /// 19 | /// - Complexity: 20 | /// - time: O(log n), where n is the given `n`. 21 | /// - space: O(log n), where n is the given `n`. 22 | func isHappy(_ n: Int) -> Bool { 23 | var n = n 24 | var seen = Set() 25 | 26 | while n != 1, !seen.contains(n) { 27 | seen.insert(n) 28 | n = getNext(n) 29 | } 30 | 31 | return n == 1 32 | } 33 | 34 | private func getNext(_ n: Int) -> Int { 35 | var n = n 36 | var ans = 0 37 | while n > 0 { 38 | let d = n % 10 39 | n /= 10 40 | ans += d * d 41 | } 42 | return ans 43 | } 44 | 45 | } 46 | -------------------------------------------------------------------------------- /Solutions/200-299/209 Minimum Size Subarray Sum.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 209 Minimum Size Subarray Sum.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 27/02/2021. 6 | // Copyright © 2021 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/minimum-size-subarray-sum/ 12 | class Solution { 13 | 14 | /// Finds the minimum length of a contiguous subarray of which the sum is 15 | /// greater than or equal to given target. 16 | /// 17 | /// - Parameters: 18 | /// - target: The target. 19 | /// - nums: An array of positive integers. 20 | /// - Returns: The minimum length of a contiguous subarray. 21 | /// 22 | /// - Complexity: 23 | /// - time: O(n), where n is the length of `nums`. 24 | /// - space: O(1), only constant space is used. 25 | func minSubArrayLen(_ target: Int, _ nums: [Int]) -> Int { 26 | var ans = Int.max 27 | var sum = 0 28 | var j = 0 29 | 30 | for i in 0..= target { 34 | ans = min(ans, i + 1 - j) 35 | sum -= nums[j] 36 | j += 1 37 | } 38 | } 39 | 40 | return ans == Int.max ? 0 : ans 41 | } 42 | 43 | } 44 | -------------------------------------------------------------------------------- /Solutions/200-299/217 Contains Duplicate.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 217 Contains Duplicate.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 09/04/2020. 6 | // Copyright © 2020 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/contains-duplicate 12 | class Solution { 13 | 14 | /// Given an array of integers, find if the array contains any duplicates. 15 | /// 16 | /// - Parameter nums: Array of integers. 17 | /// 18 | /// - Returns: true if any value appears at least twice in the array, 19 | /// or false if every element is distinct. 20 | /// 21 | /// - Complexity: 22 | /// - time: O(n), where n is the length of the nums. 23 | /// - space: O(n), where n is the length of the nums. 24 | func containsDuplicate(_ nums: [Int]) -> Bool { 25 | var set = Set() 26 | 27 | for num in nums { 28 | guard !set.contains(num) else { return true } 29 | set.insert(num) 30 | } 31 | 32 | return false 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /Solutions/200-299/219 Contains Duplicate II.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 219 Contains Duplicate II.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 27/06/2020. 6 | // Copyright © 2020 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/contains-duplicate-ii/ 12 | class Solution { 13 | 14 | /// Finds out if an array contains nearby duplicate. 15 | /// 16 | /// - Parameters: 17 | /// - nums: The array of integers. 18 | /// - k: The difference. 19 | /// - Returns: True if nearby duplicate exists, otherwise returns false. 20 | /// 21 | /// - Complexity: 22 | /// - time: O(n), where n is the length of the nums. 23 | /// - space: O(n), where n is the length of the nums. 24 | func containsNearbyDuplicate(_ nums: [Int], _ k: Int) -> Bool { 25 | var dic = [Int: Int]() 26 | 27 | for (i, num) in nums.enumerated() { 28 | if let val = dic[num], i - val <= k { 29 | return true 30 | } else { 31 | dic[num] = i 32 | } 33 | } 34 | 35 | return false 36 | } 37 | 38 | } 39 | -------------------------------------------------------------------------------- /Solutions/200-299/228 Summary Ranges.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 228 Summary Ranges.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 28/10/2020. 6 | // Copyright © 2020 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/summary-ranges/ 12 | class Solution { 13 | 14 | /// Finds the smallest sorted list of ranges that cover all the numbers in the 15 | /// array exactly. 16 | /// 17 | /// - Parameter nums: A sorted unique integer array. 18 | /// - Returns: The smallest sorted list of ranges. 19 | /// 20 | /// - Complexity: 21 | /// - time: O(n), where n is the length of nums. 22 | /// - space: O(n), where n is the length of nums. 23 | func summaryRanges(_ nums: [Int]) -> [String] { 24 | guard !nums.isEmpty else { return [] } 25 | 26 | var ans = [String]() 27 | 28 | var i = 0 29 | for j in 0..\(nums[j])") 35 | i = j + 1 36 | } 37 | 38 | return ans 39 | } 40 | 41 | } 42 | -------------------------------------------------------------------------------- /Solutions/200-299/231 Power of Two.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 231 Power of Two.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 08/06/2020. 6 | // Copyright © 2020 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/power-of-two/ 12 | class Solution { 13 | 14 | /// Determines if the given integer is a power of two. 15 | /// 16 | /// - Parameter n: The integer. 17 | /// - Returns: True if the given integer is a power of two, otherwise returns false. 18 | /// 19 | /// - Complexity: 20 | /// - time: O(1), only constant time is used. 21 | /// - space: O(1), only constant space is used. 22 | func isPowerOfTwo(_ n: Int) -> Bool { 23 | return n > 0 && (n & (n - 1)) == 0 24 | } 25 | 26 | } 27 | -------------------------------------------------------------------------------- /Solutions/200-299/237 Delete Node in a Linked List.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 237 Delete Node in a Linked List.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 03/06/2020. 6 | // Copyright © 2020 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/delete-node-in-a-linked-list/ 12 | class Solution { 13 | 14 | /// Deletes a node (except the tail) in a singly linked list. 15 | /// 16 | /// - Parameter node: Node for deletion. 17 | /// 18 | /// - Complexity: 19 | /// - time: O(1), only constant time is used. 20 | /// - space: O(1), only constant space is used. 21 | func deleteNode(_ node: ListNode?) { 22 | guard let node = node, let next = node.next else { return } 23 | node.val = next.val 24 | node.next = next.next 25 | } 26 | 27 | } 28 | 29 | /// Provided Code 30 | public class ListNode { 31 | 32 | public var val: Int 33 | public var next: ListNode? 34 | 35 | public init(_ val: Int) { 36 | self.val = val 37 | self.next = nil 38 | } 39 | 40 | } 41 | -------------------------------------------------------------------------------- /Solutions/200-299/242 Valid Anagram.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 242 Valid Anagram.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 11/02/2021. 6 | // Copyright © 2021 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/valid-anagram/ 12 | class Solution { 13 | 14 | /// Finds if `t` is an anagram of `s`. 15 | /// 16 | /// - Parameters: 17 | /// - s: A string. 18 | /// - t: A string. 19 | /// - Returns: True if `t` is an anagram of `s`, otherwise returns false. 20 | /// 21 | /// - Complexity: 22 | /// - time: O(n), where n is the length of `s`. 23 | /// - space: O(n), where n is the length of `s`. 24 | func isAnagram(_ s: String, _ t: String) -> Bool { 25 | var dict = [Character: Int]() 26 | for ch in s { 27 | dict[ch, default: 0] += 1 28 | } 29 | 30 | for ch in t { 31 | guard let val = dict[ch] else { return false } 32 | dict[ch] = val > 1 ? val - 1 : nil 33 | } 34 | 35 | return dict.isEmpty 36 | } 37 | 38 | } 39 | -------------------------------------------------------------------------------- /Solutions/200-299/243 Shortest Word Distance.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 243 Shortest Word Distance.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 05/10/2020. 6 | // Copyright © 2020 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/shortest-word-distance/ 12 | class Solution { 13 | 14 | /// Finds the shortest distance between two given words in the list. 15 | /// 16 | /// - Parameters: 17 | /// - words: A list of words. 18 | /// - word1: First word. 19 | /// - word2: Second word. 20 | /// - Returns: The shortest distance between two words. 21 | /// 22 | /// - Complexity: 23 | /// - time: O(n), where n is the number of words. 24 | /// - space: O(1), only constant space is used. 25 | func shortestDistance(_ words: [String], _ word1: String, _ word2: String) -> Int { 26 | var ans = Int.max 27 | var i1: Int? 28 | var i2: Int? 29 | 30 | for (i, word) in words.enumerated() { 31 | if word == word1 { 32 | i1 = i 33 | } else if word == word2 { 34 | i2 = i 35 | } 36 | 37 | guard let i1 = i1, let i2 = i2 else { continue } 38 | ans = min(ans, abs(i1 - i2)) 39 | } 40 | 41 | return ans 42 | } 43 | 44 | } 45 | -------------------------------------------------------------------------------- /Solutions/200-299/246 Strobogrammatic Number.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 246 Strobogrammatic Number.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 13/08/2020. 6 | // Copyright © 2020 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/strobogrammatic-number/ 12 | class Solution { 13 | 14 | /// Determines if a number is strobogrammatic. 15 | /// 16 | /// - Parameter num: The number, represented as a string. 17 | /// - Returns: True if the number is strobogrammatic, otherwise returns false. 18 | /// 19 | /// - Complexity: 20 | /// - time: O(n), where n is the length of the number. 21 | /// - space: O(1), only constant space is used. 22 | func isStrobogrammatic(_ num: String) -> Bool { 23 | let dict: [Character: Character] = [ 24 | "0": "0", 25 | "1": "1", 26 | "6": "9", 27 | "8": "8", 28 | "9": "6" 29 | ] 30 | let num = Array(num) 31 | 32 | var i = 0 33 | var j = num.count - 1 34 | 35 | while i <= j { 36 | guard dict[num[i]] == num[j] else { return false } 37 | i += 1 38 | j -= 1 39 | } 40 | 41 | return true 42 | } 43 | 44 | } 45 | -------------------------------------------------------------------------------- /Solutions/200-299/252 Meeting Rooms.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 252 Meeting Rooms.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 01/11/2020. 6 | // Copyright © 2020 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/meeting-rooms/ 12 | class Solution { 13 | 14 | /// Determines if a person can attend all meetings. 15 | /// 16 | /// - Parameter intervals: An array of meeting time intervals. 17 | /// - Returns: True if a person can attend all meetings, otherwise returns false. 18 | /// 19 | /// - Complexity: 20 | /// - time: O(n log(n)), where n is the number of `intervals`. 21 | /// - space: O(n), where n is the number of `intervals`. 22 | func canAttendMeetings(_ intervals: [[Int]]) -> Bool { 23 | guard !intervals.isEmpty else { return true } 24 | 25 | var intervals = intervals.sorted(by: { $0[0] < $1[0] }) 26 | 27 | for i in 1.. intervals[i][0] else { continue } 29 | return false 30 | } 31 | 32 | return true 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /Solutions/200-299/253 Meeting Rooms II.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 253 Meeting Rooms II.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 15/10/2020. 6 | // Copyright © 2020 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/meeting-rooms-ii/ 12 | class Solution { 13 | 14 | /// Finds the minimum number of conference rooms needed for meetings. 15 | /// 16 | /// - Parameter intervals: An array of meeting time intervals. 17 | /// - Returns: The minimum number of conference rooms. 18 | /// 19 | /// - Complexity: 20 | /// - time: O(n log(n)), where n is the number of intervals. 21 | /// - space: O(n), where n is the number of intervals. 22 | func minMeetingRooms(_ intervals: [[Int]]) -> Int { 23 | guard !intervals.isEmpty else { return 0 } 24 | 25 | let start = intervals.map { $0[0] }.sorted() 26 | let end = intervals.map { $0[1] }.sorted() 27 | 28 | var ans = 0 29 | var j = 0 30 | 31 | for i in 0.. Int { 23 | return num == 0 ? 0 : 1 + (num - 1) % 9 24 | } 25 | 26 | } 27 | -------------------------------------------------------------------------------- /Solutions/200-299/260 Single Number III.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 260 Single Number III.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 23/07/2020. 6 | // Copyright © 2020 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/single-number-iii/ 12 | class Solution { 13 | 14 | /// Finds the two elements that appear only once in an array of numbers. 15 | /// 16 | /// - Parameter nums: The array of numbers. 17 | /// - Returns: The two elements that appear only once. 18 | /// 19 | /// - Complexity: 20 | /// - time: O(n), where n is the length of the nums. 21 | /// - space: O(1), only constant space is used. 22 | func singleNumber(_ nums: [Int]) -> [Int] { 23 | var diff = 0 24 | for num in nums { 25 | diff ^= num 26 | } 27 | 28 | diff &= -diff 29 | 30 | var ans = [Int](repeating: 0, count: 2) 31 | 32 | for num in nums { 33 | if num & diff == 0 { 34 | ans[0] ^= num 35 | } else { 36 | ans[1] ^= num 37 | } 38 | } 39 | 40 | return ans 41 | } 42 | 43 | } 44 | -------------------------------------------------------------------------------- /Solutions/200-299/264 Ugly Number II.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 264 Ugly Number II.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 04/07/2020. 6 | // Copyright © 2020 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/ugly-number-ii/ 12 | class Solution { 13 | 14 | /// Finds the n-th ugly number. 15 | /// 16 | /// - Parameter n: The integer. 17 | /// - Returns: N-th ugly number. 18 | /// 19 | /// - Complexity: 20 | /// - time: O(n), where n is given n. 21 | /// - space: O(n), where n is given n. 22 | func nthUglyNumber(_ n: Int) -> Int { 23 | guard n > 0 else { return -1 } 24 | var ans = [Int](repeating: 0, count: n) 25 | ans[0] = 1 26 | 27 | var i2 = 0 28 | var i3 = 0 29 | var i5 = 0 30 | 31 | for i in 1.. Bool { 23 | var set = Set() 24 | 25 | for ch in s { 26 | guard !set.insert(ch).inserted else { continue } 27 | set.remove(ch) 28 | } 29 | 30 | return set.count <= 1 31 | } 32 | 33 | } 34 | -------------------------------------------------------------------------------- /Solutions/200-299/268 Missing Number.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 268 Missing Number.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 10/12/2020. 6 | // Copyright © 2020 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/missing-number/ 12 | class Solution { 13 | 14 | /// Finds the only number in the range that is missing from the array. 15 | /// 16 | /// - Parameter nums: An array of numbers. 17 | /// - Returns: The missing number. 18 | /// 19 | /// - Complexity: 20 | /// - time: O(n), where n is the length of `nums`. 21 | /// - space: O(1), only constant space is used. 22 | func missingNumber(_ nums: [Int]) -> Int { 23 | let n = nums.count 24 | var ans = n 25 | 26 | for i in 0.. Int { 23 | guard !citations.isEmpty else { return 0 } 24 | let n = citations.count 25 | 26 | var papers = [Int](repeating: 0, count: n+1) 27 | for citation in citations { 28 | papers[min(n, citation)] += 1 29 | } 30 | 31 | var ans = 0 32 | 33 | for i in (0...n).reversed() { 34 | ans += papers[i] 35 | guard ans >= i else { continue } 36 | return i 37 | } 38 | 39 | return 0 40 | } 41 | 42 | } 43 | -------------------------------------------------------------------------------- /Solutions/200-299/276 Paint Fence.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 276 Paint Fence.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 02/01/2021. 6 | // Copyright © 2021 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/paint-fence/ 12 | class Solution { 13 | 14 | /// Finds the total number of ways you can paint the fence. 15 | /// 16 | /// - Parameters: 17 | /// - n: The number of posts. 18 | /// - k: The number of colors. 19 | /// - Returns: The total number of ways. 20 | /// 21 | /// - Complexity: 22 | /// - time: O(n), where n is the number of posts. 23 | /// - space: O(1), only constant space is used. 24 | func numWays(_ n: Int, _ k: Int) -> Int { 25 | guard n > 0 else { return 0 } 26 | guard n > 1 else { return k } 27 | 28 | var same = 0 29 | var diff = k 30 | 31 | for i in 2...n { 32 | let tmp = same 33 | same = diff 34 | diff = (tmp + diff) * (k - 1) 35 | } 36 | 37 | return same + diff 38 | } 39 | 40 | } 41 | -------------------------------------------------------------------------------- /Solutions/200-299/278 First Bad Version.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 278 First Bad Version.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 30/01/2021. 6 | // Copyright © 2021 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/first-bad-version/ 12 | class Solution { 13 | 14 | /// Finds the first bad version. 15 | /// 16 | /// - Parameter n: The number of versions. 17 | /// - Returns: First bad version. 18 | /// 19 | /// - Complexity: 20 | /// - time: O(log n), where n is the given `n`. 21 | /// - space: O(1), only constant space is used. 22 | func firstBadVersion(_ n: Int) -> Int { 23 | var start = 1 24 | var end = n 25 | 26 | while start < end { 27 | let mid = start + (end - start) / 2 28 | if isBadVersion(mid) { 29 | end = mid 30 | } else { 31 | start = mid + 1 32 | } 33 | } 34 | 35 | return start 36 | } 37 | 38 | } 39 | 40 | /// Provided code 41 | class VersionControl { 42 | 43 | func isBadVersion(_ version: Int) -> Bool 44 | 45 | } 46 | -------------------------------------------------------------------------------- /Solutions/200-299/283 Move Zeroes.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 283 Move Zeroes.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 03/04/2020. 6 | // Copyright © 2020 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/move-zeroes 12 | class Solution { 13 | 14 | /// Move all 0's to the end while maintaining the 15 | /// relative order of the non-zero elements. 16 | /// 17 | /// - Parameter nums: Array of integers 18 | /// 19 | /// - Complexity: 20 | /// - time: O(n), where n is the length of the nums. 21 | /// - space: O(1), only constant space is used. 22 | func moveZeroes(_ nums: inout [Int]) { 23 | guard !nums.isEmpty else { return } 24 | 25 | var j = 0 26 | for (i, num) in nums.enumerated() { 27 | guard num != 0 else { continue } 28 | nums.swapAt(i, j) 29 | j += 1 30 | } 31 | } 32 | 33 | } 34 | -------------------------------------------------------------------------------- /Solutions/200-299/287 Find the Duplicate Number.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 287 Find the Duplicate Number.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 25/06/2020. 6 | // Copyright © 2020 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/find-the-duplicate-number/ 12 | class Solution { 13 | 14 | /// Finds the duplicate number. 15 | /// 16 | /// - Parameter nums: An array containing n + 1 integers where each integer is between 17 | /// 1 and n (inclusive). 18 | /// - Returns: The duplicate number. 19 | /// 20 | /// - Complexity: 21 | /// - time: O(n), where n is the length of the nums. 22 | /// - space: O(1), only constant space is used. 23 | func findDuplicate(_ nums: [Int]) -> Int { 24 | var slow = nums[0] 25 | var fast = nums[nums[0]] 26 | 27 | while slow != fast { 28 | slow = nums[slow] 29 | fast = nums[nums[fast]] 30 | } 31 | 32 | slow = 0 33 | while slow != fast { 34 | slow = nums[slow] 35 | fast = nums[fast] 36 | } 37 | 38 | return slow 39 | } 40 | 41 | } 42 | -------------------------------------------------------------------------------- /Solutions/200-299/292 Nim Game.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 292 Nim Game.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 01/05/2020. 6 | // Copyright © 2020 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/nim-game/ 12 | class Solution { 13 | 14 | /// Determines whether you can win the Nim Game. 15 | /// 16 | /// - Parameter n: The number of stones. 17 | /// - Returns: True if you can win, otherwise returns false. 18 | /// 19 | /// - Complexity: 20 | /// - time: O(1), only constant time is used. 21 | /// - space: O(1), only constant space is used. 22 | func canWinNim(_ n: Int) -> Bool { 23 | return n % 4 != 0 24 | } 25 | 26 | } 27 | -------------------------------------------------------------------------------- /Solutions/200-299/293 Flip Game.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 293 Flip Game.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 04/01/2021. 6 | // Copyright © 2021 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/flip-game/ 12 | class Solution { 13 | 14 | /// Finds all possible states of the string after one valid move. 15 | /// 16 | /// - Parameter s: The string. 17 | /// - Returns: All possible states of the string after one valid move. 18 | /// 19 | /// - Complexity: 20 | /// - time: O(n), where n is the length of `s`. 21 | /// - space: O(m), where m is the number of all possible states. 22 | func generatePossibleNextMoves(_ s: String) -> [String] { 23 | guard !s.isEmpty else { return [] } 24 | 25 | var s = Array(s) 26 | var ans = [String]() 27 | 28 | for i in 1.. Int { 23 | var sold = 0 24 | var hold = Int.min 25 | var rest = 0 26 | var prevSold = 0 27 | 28 | for price in prices { 29 | prevSold = sold 30 | sold = hold + price 31 | hold = max(hold, rest - price) 32 | rest = max(rest, prevSold) 33 | } 34 | 35 | return max(sold, rest) 36 | } 37 | 38 | } 39 | -------------------------------------------------------------------------------- /Solutions/300-399/322 Coin Change.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 322 Coin Change.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 11/03/2021. 6 | // Copyright © 2021 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/coin-change/ 12 | class Solution { 13 | 14 | /// Finds the fewest number of coins that you need to make up to the amount. 15 | /// 16 | /// - Parameters: 17 | /// - coins: The coins. 18 | /// - amount: The total amount of money. 19 | /// - Returns: The fewest number of coins, if the amount of money cannot be 20 | /// made up returns -1. 21 | /// 22 | /// - Complexity: 23 | /// - time: O(s * n), where s is the `amount`, and n is the length of `coins`. 24 | /// - space: O(s), where s is the `amount`. 25 | func coinChange(_ coins: [Int], _ amount: Int) -> Int { 26 | guard amount > 0 else { return 0 } 27 | var dp = [Int](repeating: amount + 1, count: amount + 1) 28 | dp[0] = 0 29 | for i in 1...amount { 30 | for coin in coins { 31 | guard coin <= i else { continue } 32 | dp[i] = min(dp[i], dp[i - coin] + 1) 33 | } 34 | } 35 | return dp[amount] > amount ? -1 : dp[amount] 36 | } 37 | 38 | } 39 | -------------------------------------------------------------------------------- /Solutions/300-399/334 Increasing Triplet Subsequence.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 334 Increasing Triplet Subsequence.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 18/12/2020. 6 | // Copyright © 2020 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/increasing-triplet-subsequence/ 12 | class Solution { 13 | 14 | /// Finds if there exists a triple of indices `(i, j, k)` such that `i < j < k` 15 | /// and `nums[i] < nums[j] < nums[k]` 16 | /// 17 | /// - Parameter nums: An integer array. 18 | /// - Returns: True if indices exist, otherwise returns false. 19 | /// 20 | /// - Complexity: 21 | /// - time: O(n), where n is the length of the `nums`. 22 | /// - space: O(1), only constant space is used. 23 | func increasingTriplet(_ nums: [Int]) -> Bool { 24 | var first = Int.max 25 | var second = Int.max 26 | 27 | for num in nums { 28 | if num <= first { 29 | first = num 30 | } else if num <= second { 31 | second = num 32 | } else { 33 | return true 34 | } 35 | } 36 | 37 | return false 38 | } 39 | 40 | } 41 | -------------------------------------------------------------------------------- /Solutions/300-399/342 Power of Four.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 342 Power of Four.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 04/08/2020. 6 | // Copyright © 2020 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/power-of-four/ 12 | class Solution { 13 | 14 | /// Checks whether an integer is a power of 4. 15 | /// 16 | /// - Parameter num: The integer. 17 | /// - Returns: True if the integer is a power of 4, otherwise returns false. 18 | /// 19 | /// - Complexity: 20 | /// - time: O(1), only constant time is used. 21 | /// - space: O(1), only constant space is used. 22 | func isPowerOfFour(_ num: Int) -> Bool { 23 | return num > 0 && (log(Double(num)) / log(2.0)).truncatingRemainder(dividingBy: 2) == 0 24 | } 25 | 26 | } 27 | -------------------------------------------------------------------------------- /Solutions/300-399/344 Reverse String.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 344 Reverse String.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 04/06/2020. 6 | // Copyright © 2020 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/reverse-string/ 12 | class Solution { 13 | 14 | /// Reverses a string in-place. 15 | /// 16 | /// - Parameter s: An array of characters. 17 | /// 18 | /// - Complexity: 19 | /// - time: O(n), where n is the length of the *s*. 20 | /// - space: O(1), only constant space is used. 21 | func reverseString(_ s: inout [Character]) { 22 | var i = 0 23 | var j = s.count-1 24 | 25 | while i < j { 26 | s.swapAt(i, j) 27 | 28 | i += 1 29 | j -= 1 30 | } 31 | } 32 | 33 | } 34 | -------------------------------------------------------------------------------- /Solutions/300-399/349 Intersection of Two Arrays.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 349 Intersection of Two Arrays.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 28/06/2020. 6 | // Copyright © 2020 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/intersection-of-two-arrays/ 12 | class Solution { 13 | 14 | /// Computes the intersection of two arrays. 15 | /// 16 | /// - Parameters: 17 | /// - nums1: An array of integers. 18 | /// - nums2: An array of integers. 19 | /// - Returns: Intersection of two arrays. 20 | /// 21 | /// - Complexity: 22 | /// - time: O(max(n, m)), where n is the length of the nums1, and m is the length of 23 | /// the nums2. 24 | /// - space: O(max(n, m)), where n is the length of the nums1, and m is the length of 25 | /// the nums2. 26 | func intersection(_ nums1: [Int], _ nums2: [Int]) -> [Int] { 27 | var buf = Set() 28 | 29 | for num in nums1 { 30 | buf.insert(num) 31 | } 32 | 33 | var ans = Set() 34 | 35 | for num in nums2 { 36 | guard buf.contains(num), !ans.contains(num) else { continue } 37 | ans.insert(num) 38 | } 39 | 40 | return Array(ans) 41 | } 42 | 43 | } 44 | -------------------------------------------------------------------------------- /Solutions/300-399/350 Intersection of Two Arrays II.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 350 Intersection of Two Arrays II.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 03/03/2021. 6 | // Copyright © 2021 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/intersection-of-two-arrays-ii/ 12 | class Solution { 13 | 14 | /// Computes intersections of two arrays. 15 | /// 16 | /// - Parameters: 17 | /// - nums1: An array. 18 | /// - nums2: An array. 19 | /// - Returns: Intersection of two arrays. 20 | /// 21 | /// - Complexity: 22 | /// - time: O(max(n, m)), where n is length of `nums1`, and m is the length 23 | /// of `nums2`. 24 | /// - space: O(n), where n is length of `nums1`. 25 | func intersect(_ nums1: [Int], _ nums2: [Int]) -> [Int] { 26 | var dic = [Int: Int]() 27 | 28 | for num in nums1 { 29 | dic[num, default: 0] += 1 30 | } 31 | 32 | var ans = [Int]() 33 | 34 | for num in nums2 { 35 | guard let val = dic[num], val > 0 else { continue } 36 | ans.append(num) 37 | dic[num] = val - 1 38 | } 39 | 40 | return ans 41 | } 42 | 43 | } 44 | -------------------------------------------------------------------------------- /Solutions/300-399/367 Valid Perfect Square.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 367 Valid Perfect Square.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 09/05/2020. 6 | // Copyright © 2020 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/valid-perfect-square/ 12 | class Solution { 13 | 14 | /// **Newton's Algorithm** for checking if the number is a perfect square. 15 | /// 16 | /// - Parameter num: Positive integer. 17 | /// - Returns: True if num is a perfect square, otherwise returns false. 18 | /// 19 | /// - Complexity: 20 | /// - time: O(log n), where n is the num. 21 | /// - space: O(1), only constant space is used. 22 | func isPerfectSquare(_ num: Int) -> Bool { 23 | guard num > 0 else { return false } 24 | 25 | var n = num 26 | 27 | while n * n > num { 28 | n = (n + num/n) / 2 29 | } 30 | 31 | return n * n == num 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /Solutions/300-399/376 Wiggle Subsequence.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 376 Wiggle Subsequence.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 18/03/2021. 6 | // Copyright © 2021 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/wiggle-subsequence/ 12 | class Solution { 13 | 14 | /// Finds the length of the longest wiggle sequence. 15 | /// 16 | /// - Parameter nums: An integer array. 17 | /// - Returns: The length of the longest wiggle sequence. 18 | /// 19 | /// - Complexity: 20 | /// - time: O(n), where n is the length of `nums`. 21 | /// - space: O(1), only constant space is used. 22 | func wiggleMaxLength(_ nums: [Int]) -> Int { 23 | let n = nums.count 24 | guard n > 1 else { return n } 25 | 26 | var diff = nums[1] - nums[0] 27 | var ans = diff != 0 ? 2 : 1 28 | 29 | for i in 2.. 0 && diff <= 0) || (tmp < 0 && diff >= 0) else { continue } 32 | ans += 1 33 | diff = tmp 34 | } 35 | 36 | return ans 37 | } 38 | 39 | } 40 | -------------------------------------------------------------------------------- /Solutions/300-399/383 Ransom Note.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 383 Ransom Note.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 03/05/2020. 6 | // Copyright © 2020 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/ransom-note/ 12 | class Solution { 13 | 14 | /// Findes if ransom note can be constructed from the magazines. 15 | /// 16 | /// - Parameters: 17 | /// - ransomNote: Ransom note string 18 | /// - magazine: Magazine string 19 | /// 20 | /// - Returns: True if the ransom note can be constructed, otherwise returns false. 21 | /// 22 | /// - Complexity: 23 | /// - time: O(m), where m is the number of letters in magazine. 24 | /// - space: O(m), where m is the number of letters in magazine. 25 | func canConstruct(_ ransomNote: String, _ magazine: String) -> Bool { 26 | guard magazine.count >= ransomNote.count else { return false } 27 | 28 | var dict = [Character: Int]() 29 | 30 | for mag in magazine { 31 | dict[mag, default: 0] += 1 32 | } 33 | 34 | for ran in ransomNote { 35 | guard let val = dict[ran] else { return false } 36 | dict[ran] = val == 1 ? nil : val - 1 37 | } 38 | 39 | return true 40 | } 41 | 42 | } 43 | -------------------------------------------------------------------------------- /Solutions/300-399/387 First Unique Character in a String.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 387 First Unique Character in a String.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 05/05/2020. 6 | // Copyright © 2020 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/first-unique-character-in-a-string/ 12 | class Solution { 13 | 14 | /// Finds the first non-repeating character in a string. 15 | /// 16 | /// - Parameter s: The string. 17 | /// - Returns: Index of first non-repeating character, if non-repeating character 18 | /// doesn't exist returns -1. 19 | /// 20 | /// - Complexity: 21 | /// - time: O(n), where n is the number of letters in s. 22 | /// - space: O(n), where n is the number of letters in s. 23 | func firstUniqChar(_ s: String) -> Int { 24 | var dict = [Character: Int]() 25 | 26 | for c in s { 27 | dict[c, default: 0] += 1 28 | } 29 | 30 | for (i, c) in s.enumerated() { 31 | guard dict[c] == 1 else { continue } 32 | return i 33 | } 34 | 35 | return -1 36 | } 37 | 38 | } 39 | -------------------------------------------------------------------------------- /Solutions/300-399/389 Find the Difference.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 389 Find the Difference.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 24/09/2020. 6 | // Copyright © 2020 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/find-the-difference/ 12 | class Solution { 13 | 14 | /// Finds the letter that appears just in `t`. 15 | /// 16 | /// - Parameters: 17 | /// - s: The string. 18 | /// - t: The string. 19 | /// - Returns: The letter that appears just in `t`. 20 | /// 21 | /// - Complexity: 22 | /// - time: O(n), where n is the length of `t`. 23 | /// - space: O(1), only constant space is used. The total number of unique characters 24 | /// is 26. 25 | func findTheDifference(_ s: String, _ t: String) -> Character { 26 | var dict = [Character: Int]() 27 | for ch in s { 28 | dict[ch, default: 0] += 1 29 | } 30 | 31 | for ch in t { 32 | guard let num = dict[ch], num > 0 else { return ch } 33 | dict[ch] = num - 1 34 | } 35 | 36 | return "\0" 37 | } 38 | 39 | } 40 | -------------------------------------------------------------------------------- /Solutions/300-399/392 Is Subsequence.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 392 Is Subsequence.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 30/06/2020. 6 | // Copyright © 2020 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/is-subsequence/ 12 | class Solution { 13 | 14 | /// Checks if s is subsequence of t. 15 | /// 16 | /// - Parameters: 17 | /// - s: The string. 18 | /// - t: The string. 19 | /// - Returns: True if s is a subsequence of t, otherwise returns false. 20 | /// 21 | /// - Complexity: 22 | /// - time: O(n), where n is the number of letters in t. 23 | /// - space: O(max(n, m)), where n is the number of letters in t, and m is the number 24 | /// of letters in s. 25 | func isSubsequence(_ s: String, _ t: String) -> Bool { 26 | guard s.count <= t.count else { return false } 27 | 28 | let s = Array(s) 29 | let t = Array(t) 30 | 31 | var i = 0 32 | var j = 0 33 | 34 | while i < s.count { 35 | guard j < t.count else { return false } 36 | 37 | if s[i] == t[j] { 38 | i += 1 39 | } 40 | 41 | j += 1 42 | } 43 | 44 | return true 45 | } 46 | 47 | } 48 | -------------------------------------------------------------------------------- /Solutions/400-499/409 Longest Palindrome.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 409 Longest Palindrome.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 14/08/2020. 6 | // Copyright © 2020 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/longest-palindrome/ 12 | class Solution { 13 | 14 | /// Finds the length of the longest palindromes that can be built with letters from a 15 | /// string. 16 | /// 17 | /// - Parameter s: The string. 18 | /// - Returns: The length of the longest palindromes 19 | /// 20 | /// - Complexity: 21 | /// - time: O(n), where n is the number of letters in the string. 22 | /// - space: O(n), where n is the number of letters in the string. 23 | func longestPalindrome(_ s: String) -> Int { 24 | var dict = [Character: Int]() 25 | for ch in s { 26 | dict[ch, default: 0] += 1 27 | } 28 | 29 | var ans = 0 30 | var hasOdd = false 31 | for (_, el) in dict.enumerated() { 32 | if el.value % 2 == 0 { 33 | ans += el.value 34 | } else { 35 | hasOdd = true 36 | ans += el.value - 1 37 | } 38 | } 39 | 40 | return ans + (hasOdd ? 1 : 0) 41 | } 42 | 43 | } 44 | -------------------------------------------------------------------------------- /Solutions/400-499/412 Fizz Buzz.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 412 Fizz Buzz.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 26/08/2020. 6 | // Copyright © 2020 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/fizz-buzz/ 12 | class Solution { 13 | 14 | /// Finds the string representation of numbers from 1 to n. 15 | /// 16 | /// - Parameter n: Upper bound. 17 | /// - Returns: The string representation of numbers. 18 | /// 19 | /// - Complexity: 20 | /// - time: O(n), where n is the upper bound. 21 | /// - space: O(n), where n is the upper bound. 22 | func fizzBuzz(_ n: Int) -> [String] { 23 | var ans = [String]() 24 | 25 | for i in 1...n { 26 | switch (i % 3 == 0, i % 5 == 0) { 27 | case (true, true): 28 | ans.append("FizzBuzz") 29 | 30 | case (false, true): 31 | ans.append("Buzz") 32 | 33 | case (true, false): 34 | ans.append("Fizz") 35 | 36 | default: 37 | ans.append(String(i)) 38 | } 39 | } 40 | 41 | return ans 42 | } 43 | 44 | } 45 | -------------------------------------------------------------------------------- /Solutions/400-499/413 Arithmetic Slices.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 413 Arithmetic Slices.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 18/02/2021. 6 | // Copyright © 2021 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/arithmetic-slices/ 12 | class Solution { 13 | 14 | /// Finds the number of arithmetic slices in array `A`. 15 | /// 16 | /// - Parameter A: The array. 17 | /// - Returns: The number of arithmetic slices. 18 | /// 19 | /// - Complexity: 20 | /// - time: O(n), where n is the length of `A`. 21 | /// - space: O(1), only constant space is used. 22 | func numberOfArithmeticSlices(_ A: [Int]) -> Int { 23 | let n = A.count 24 | guard n > 2 else { return 0 } 25 | var dp = 0 26 | var ans = 0 27 | 28 | for i in 2.. Int { 25 | var top3 = Set() 26 | 27 | for num in nums { 28 | top3.insert(num) 29 | guard top3.count > 3, let min = top3.min() else { continue } 30 | top3.remove(min) 31 | } 32 | 33 | guard top3.count == 3 else { 34 | return top3.max() ?? -1 35 | } 36 | 37 | return top3.min() ?? -1 38 | } 39 | 40 | } 41 | -------------------------------------------------------------------------------- /Solutions/400-499/416 Partition Equal Subset Sum.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 416 Partition Equal Subset Sum.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 27/11/2020. 6 | // Copyright © 2020 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/partition-equal-subset-sum/ 12 | class Solution { 13 | 14 | /// Finds if the array can be partitioned into two subsets such that the sum of 15 | /// elements in both subsets is equal. 16 | /// 17 | /// - Parameter nums: An array containing only positive integers. 18 | /// - Returns: True if the array can be partitioned, otherwise returns false. 19 | /// 20 | /// - Complexity: 21 | /// - time: O(m * n), where m is the `target`, and n is the length of `nums`. 22 | /// - space: O(m), where m is the `target`. 23 | func canPartition(_ nums: [Int]) -> Bool { 24 | guard !nums.isEmpty else { return false } 25 | 26 | var totalSum = nums.reduce(0, +) 27 | 28 | guard totalSum % 2 == 0 else { return false } 29 | 30 | let target = totalSum / 2 31 | var dp = [Bool](repeating: false, count: target + 1) 32 | dp[0] = true 33 | 34 | for num in nums { 35 | for j in stride(from: target, through: num, by: -1) { 36 | dp[j] = dp[j] || dp[j - num] 37 | } 38 | } 39 | 40 | return dp[target] 41 | } 42 | 43 | } 44 | -------------------------------------------------------------------------------- /Solutions/400-499/422 Valid Word Square.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 422 Valid Word Square.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 11/01/2021. 6 | // Copyright © 2021 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/valid-word-square/ 12 | class Solution { 13 | 14 | /// Finds if given sequence of words forms a valid word square. 15 | /// 16 | /// - Parameter words: A sequence of words. 17 | /// - Returns: True if sequence of words forms a valid word square, otherwise 18 | /// returns false. 19 | /// 20 | /// - Complexity: 21 | /// - time: O(n), where n is the number of characters in `words`. 22 | /// - space: O(n), where n is the number of characters in `words`. 23 | func validWordSquare(_ words: [String]) -> Bool { 24 | guard !words.isEmpty else { return true } 25 | 26 | let words = words.map { Array($0) } 27 | 28 | let n = words.count 29 | for (i, word) in words.enumerated() { 30 | for (j, w) in word.enumerated() { 31 | guard j < n, i < words[j].count else { return false } 32 | guard words[j][i] == w else { return false } 33 | } 34 | } 35 | 36 | return true 37 | } 38 | 39 | } 40 | -------------------------------------------------------------------------------- /Solutions/400-499/435 Non-overlapping Intervals.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 435 Non-overlapping Intervals.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 15/08/2020. 6 | // Copyright © 2020 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/non-overlapping-intervals/ 12 | class Solution { 13 | 14 | /// Finds the minimum number of intervals for removal to make the rest of the intervals 15 | /// non-overlapping. 16 | /// 17 | /// - Parameter intervals: The intervals. 18 | /// - Returns: The minimum number of intervals for removal. 19 | /// 20 | /// - Complexity: 21 | /// - time: O(n log(n)), where n is the number of intervals. 22 | /// - space: O(n), where n is the number of intervals. 23 | func eraseOverlapIntervals(_ intervals: [[Int]]) -> Int { 24 | guard !intervals.isEmpty else { return 0 } 25 | let intervals = intervals.sorted(by: { $0[1] != $1[1] ? $0[1] < $1[1] : $0[0] < $1[0] }) 26 | 27 | var end = Int.min 28 | var ans = 0 29 | 30 | for interval in intervals { 31 | if interval[0] >= end { 32 | end = interval[1] 33 | } else { 34 | ans += 1 35 | } 36 | } 37 | 38 | return ans 39 | } 40 | 41 | } 42 | -------------------------------------------------------------------------------- /Solutions/400-499/441 Arranging Coins.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 441 Arranging Coins.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 01/07/2020. 6 | // Copyright © 2020 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/arranging-coins/ 12 | class Solution { 13 | 14 | /// Finds the total number of full staircase rows that can be formed from n coins. 15 | /// 16 | /// - Parameter n: The number of coins. 17 | /// - Returns: The number of full staircase. 18 | /// 19 | /// - Complexity: 20 | /// - time: O(1), only constant time is used. 21 | /// - space: O(1), only constant space is used. 22 | func arrangeCoins(_ n: Int) -> Int { 23 | return Int(sqrt(2.0 * Double(n) + 0.25) - 0.5) 24 | } 25 | 26 | } 27 | -------------------------------------------------------------------------------- /Solutions/400-499/442 Find All Duplicates in an Array.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 442 Find All Duplicates in an Array.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 06/08/2020. 6 | // Copyright © 2020 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/find-all-duplicates-in-an-array/ 12 | class Solution { 13 | 14 | /// Finds all the elements that appear twice in an array. 15 | /// 16 | /// - Parameter nums: The array of integers. 17 | /// - Returns: All elements that appear twice. 18 | /// 19 | /// - Complexity: 20 | /// - time: O(n), where n is the length of the nums. 21 | /// - space: O(n), where n is the length of the nums. 22 | func findDuplicates(_ nums: [Int]) -> [Int] { 23 | var nums = nums 24 | var ans = [Int]() 25 | 26 | for num in nums { 27 | if nums[abs(num) - 1] < 0 { 28 | ans.append(num) 29 | } 30 | nums[abs(num) - 1] *= -1 31 | } 32 | 33 | return ans 34 | } 35 | 36 | } 37 | -------------------------------------------------------------------------------- /Solutions/400-499/452 Minimum Number of Arrows to Burst Balloons.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 452 Minimum Number of Arrows to Burst Balloons.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 10/10/2020. 6 | // Copyright © 2020 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/minimum-number-of-arrows-to-burst-balloons/ 12 | class Solution { 13 | 14 | /// Finds the minimum number of arrows that must be shot to burst all balloons. 15 | /// 16 | /// - Parameter points: An array of balloons points. 17 | /// - Returns: The minimum number of arrows. 18 | /// 19 | /// - Complexity: 20 | /// - time: O(n log(n)), where n is the number of points. 21 | /// - space: O(n), where n is the number of points. 22 | func findMinArrowShots(_ points: [[Int]]) -> Int { 23 | guard !points.isEmpty else { return 0 } 24 | let points = points.sorted(by: { $0[1] < $1[1] }) 25 | 26 | var ans = 1 27 | var end = points[0][1] 28 | 29 | for point in points { 30 | guard end < point[0] else { continue } 31 | ans += 1 32 | end = point[1] 33 | } 34 | 35 | return ans 36 | } 37 | 38 | } 39 | -------------------------------------------------------------------------------- /Solutions/400-499/454 4Sum II.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 454 4Sum II.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 17/12/2020. 6 | // Copyright © 2020 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/4sum-ii/ 12 | class Solution { 13 | 14 | /// Finds how many tuples `(i, j, k, l)` there are such that 15 | /// `A[i] + B[j] + C[k] + D[l]` is zero. 16 | /// 17 | /// - Parameters: 18 | /// - A: An array list of integer values. 19 | /// - B: An array list of integer values. 20 | /// - C: An array list of integer values. 21 | /// - D: An array list of integer values. 22 | /// - Returns: The number of tuples. 23 | /// 24 | /// - Complexity: 25 | /// - time: O(n^2), where n is the length of the given lists. 26 | /// - space: O(n^2), where n is the length of the given lists. 27 | func fourSumCount(_ A: [Int], _ B: [Int], _ C: [Int], _ D: [Int]) -> Int { 28 | var dict = [Int: Int]() 29 | 30 | for a in A { 31 | for b in B { 32 | dict[a + b, default: 0] += 1 33 | } 34 | } 35 | 36 | var ans = 0 37 | for c in C { 38 | for d in D { 39 | guard let val = dict[-(c+d)] else { continue } 40 | 41 | ans += val 42 | } 43 | } 44 | 45 | return ans 46 | } 47 | 48 | } 49 | -------------------------------------------------------------------------------- /Solutions/400-499/458 Poor Pigs.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 458 Poor Pigs.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 14/11/2020. 6 | // Copyright © 2020 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/poor-pigs/ 12 | class Solution { 13 | 14 | /// Finds how many pigs you need to figure out the poisonous bucket within `p` minutes. 15 | /// 16 | /// - Parameters: 17 | /// - buckets: The number of buckets. 18 | /// - minutesToDie: The number of minutes for a pig to die. 19 | /// - minutesToTest: The number of minutes for test. 20 | /// - Returns: The number of pigs. 21 | /// 22 | /// - Complexity: 23 | /// - time: O(1), only constant time is used. 24 | /// - space: O(1), only constant space is used. 25 | func poorPigs(_ buckets: Int, _ minutesToDie: Int, _ minutesToTest: Int) -> Int { 26 | let states = minutesToTest / minutesToDie + 1 27 | return Int(ceil(log(Double(buckets)) / log(Double(states)))) 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /Solutions/400-499/459 Repeated Substring Pattern.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 459 Repeated Substring Pattern.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 03/09/2020. 6 | // Copyright © 2020 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/repeated-substring-pattern/ 12 | class Solution { 13 | 14 | /// Checks if the input string can be constructed by taking a substring of it and 15 | /// appending multiple copies of the substring together. 16 | /// 17 | /// - Parameter s: The string. 18 | /// - Returns: True if the string can be constructed, otherwise return false. 19 | /// 20 | /// - Complexity: 21 | /// - time: O(n), where n is the length of the input string. 22 | /// - space: O(n), where n is the length of the input string. 23 | func repeatedSubstringPattern(_ s: String) -> Bool { 24 | let s = Array(s) 25 | var dp = [Int](repeating: 0, count: s.count) 26 | 27 | for i in 1.. 0, s[i] != s[j] { 31 | j = dp[j - 1] 32 | } 33 | 34 | if s[i] == s[j] { 35 | j += 1 36 | } 37 | 38 | dp[i] = j 39 | } 40 | 41 | let length = dp[s.count - 1] 42 | return length != 0 && s.count % (s.count - length) == 0 43 | } 44 | 45 | } 46 | -------------------------------------------------------------------------------- /Solutions/400-499/461 Hamming Distance.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 461 Hamming Distance.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 05/07/2020. 6 | // Copyright © 2020 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/hamming-distance/ 12 | class Solution { 13 | 14 | /// Calculates the Hamming distance between two integers. 15 | /// 16 | /// - Parameters: 17 | /// - x: The integer. 18 | /// - y: The integer. 19 | /// - Returns: The Hamming distance. 20 | /// 21 | /// - Complexity: 22 | /// - time: O(1), only constant time is used. 23 | /// - space: O(1), only constant space is used. 24 | func hammingDistance(_ x: Int, _ y: Int) -> Int { 25 | return (x ^ y).nonzeroBitCount 26 | } 27 | 28 | } 29 | -------------------------------------------------------------------------------- /Solutions/400-499/463 Island Perimeter.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 463 Island Perimeter.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 07/07/2020. 6 | // Copyright © 2020 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/island-perimeter/ 12 | class Solution { 13 | 14 | /// Determines the perimeter of the island. 15 | /// 16 | /// - Parameter grid: A map of the island, where 1 represents land and 0 represents 17 | /// water. 18 | /// - Returns: The perimeter of the island. 19 | /// 20 | /// - Complexity: 21 | /// - time: O(n * m), where n is the number of rows in the grid, and m is the number 22 | /// of columns in the grid. 23 | /// - space: O(1), only constant space is used. 24 | func islandPerimeter(_ grid: [[Int]]) -> Int { 25 | var ans = 0 26 | 27 | for i in 0.. 0, grid[i-1][j] == 1 { 32 | ans -= 2 33 | } 34 | if j > 0, grid[i][j-1] == 1 { 35 | ans -= 2 36 | } 37 | } 38 | } 39 | 40 | return ans 41 | } 42 | 43 | } 44 | -------------------------------------------------------------------------------- /Solutions/400-499/470 Implement Rand10() Using Rand7().swift: -------------------------------------------------------------------------------- 1 | // 2 | // 470 Implement Rand10() Using Rand7().swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 28/08/2020. 6 | // Copyright © 2020 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/implement-rand10-using-rand7/ 12 | class Solution : SolBase { 13 | 14 | /// Generates a uniform random integer in the range 1 to 10. 15 | /// 16 | /// - Returns: The random integer in the range 1 to 10. 17 | /// 18 | /// - Complexity: 19 | /// - time: O(1), only constant time is used in the average case, but O(∞) is the 20 | /// worst case. 21 | /// - space: O(1), only constant space is used. 22 | func rand10() -> Int { 23 | var ans = 40 24 | 25 | while ans >= 40 { 26 | ans = 7 * (rand7() - 1) + rand7() - 1 27 | } 28 | 29 | return ans % 10 + 1 30 | } 31 | } 32 | 33 | /// Provided code 34 | class SolBase { 35 | 36 | /// Generates a uniform random integer in the range 1 to 7. 37 | /// 38 | /// - Returns: The random integer in the range 1 to 7. 39 | func rand7() -> Int 40 | 41 | } 42 | -------------------------------------------------------------------------------- /Solutions/400-499/476 Number Complement.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 476 Number Complement.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 04/05/2020. 6 | // Copyright © 2020 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/number-complement/ 12 | class Solution { 13 | 14 | /// Flips the bits of num. 15 | /// 16 | /// - Parameter num: Positive integer. 17 | /// - Returns: Complement of num. 18 | /// 19 | /// - Complexity: 20 | /// - time: O(n), where n is the number of digits in num. 21 | /// - space: O(1), only constant space is used. 22 | func findComplement(_ num: Int) -> Int { 23 | guard num != 0 else { return 1 } 24 | 25 | var i = 1 26 | 27 | while i <= num { 28 | i <<= 1 29 | } 30 | 31 | return (i - 1) ^ num 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /Solutions/400-499/478 Generate Random Point in a Circle.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 478 Generate Random Point in a Circle.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 17/03/2021. 6 | // Copyright © 2021 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/generate-random-point-in-a-circle/ 12 | class Solution { 13 | 14 | private let radius: Double 15 | private let xCenter: Double 16 | private let yCenter: Double 17 | 18 | init(_ radius: Double, _ x_center: Double, _ y_center: Double) { 19 | self.radius = radius 20 | xCenter = x_center 21 | yCenter = y_center 22 | } 23 | 24 | /// Generates random point in a circle. 25 | /// 26 | /// - Returns: The random point in a circle. 27 | /// 28 | /// - Complexity: 29 | /// - time: O(1), only constant time is used. 30 | /// - space: O(1), only constant space is used. 31 | func randPoint() -> [Double] { 32 | let randomR = Double.random(in: 0.0...1.0).squareRoot() * radius 33 | let randomTheta = Double.random(in: 0.0...1.0) * 2 * Double.pi 34 | let newX = xCenter + randomR * cos(randomTheta) 35 | let newY = yCenter + randomR * sin(randomTheta) 36 | return [newX, newY] 37 | } 38 | 39 | } 40 | -------------------------------------------------------------------------------- /Solutions/400-499/485 Max Consecutive Ones.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 485 Max Consecutive Ones.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 06/09/2020. 6 | // Copyright © 2020 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/max-consecutive-ones/ 12 | class Solution { 13 | 14 | /// Finds the maximum number of consecutive 1s in a binary array. 15 | /// 16 | /// - Parameter nums: The binary array. 17 | /// - Returns: The maximum number of consecutive 1s. 18 | /// 19 | /// - Complexity: 20 | /// - time: O(n), where n is the length of nums. 21 | /// - space: O(1), only constant space is used. 22 | func findMaxConsecutiveOnes(_ nums: [Int]) -> Int { 23 | var ans = 0 24 | var currentMax = 0 25 | 26 | for i in nums { 27 | guard i != 1 else { 28 | currentMax += 1 29 | continue 30 | } 31 | ans = max(ans, currentMax) 32 | currentMax = 0 33 | } 34 | 35 | return max(ans, currentMax) 36 | } 37 | 38 | } 39 | -------------------------------------------------------------------------------- /Solutions/400-499/487 Max Consecutive Ones II.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 487 Max Consecutive Ones II.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 25/09/2020. 6 | // Copyright © 2020 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/max-consecutive-ones-ii/ 12 | class Solution { 13 | 14 | /// Finds the maximum number of consecutive 1s in a binary array if we can flip at 15 | /// most one 0. 16 | /// 17 | /// - Parameter nums: A binary array. 18 | /// - Returns: The maximum number of consecutive 1s. 19 | /// 20 | /// - Complexity: 21 | /// - time: O(n), where n is the length of the `nums`. 22 | /// - space: O(1), only constant space is used. 23 | func findMaxConsecutiveOnes(_ nums: [Int]) -> Int { 24 | var ans = 0 25 | var prev = 0 26 | var curr = 0 27 | 28 | for num in nums { 29 | if num == 0 { 30 | prev = curr + 1 31 | curr = 0 32 | } else { 33 | curr += 1 34 | } 35 | 36 | ans = max(ans, curr + prev) 37 | } 38 | 39 | return ans 40 | } 41 | 42 | } 43 | -------------------------------------------------------------------------------- /Solutions/400-499/495 Teemo Attacking.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 495 Teemo Attacking.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 26/09/2020. 6 | // Copyright © 2020 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/teemo-attacking/ 12 | class Solution { 13 | 14 | /// Finds the total time that the enemy is in poisoned condition. 15 | /// 16 | /// - Parameters: 17 | /// - timeSeries: Attacking time series. 18 | /// - duration: The poisoning time duration. 19 | /// - Returns: The total time that the enemy is in poisoned condition. 20 | /// 21 | /// - Complexity: 22 | /// - time: O(n), where n is the length of `timeSeries`. 23 | /// - space: O(1), only constant space is used. 24 | func findPoisonedDuration(_ timeSeries: [Int], _ duration: Int) -> Int { 25 | guard !timeSeries.isEmpty else { return 0 } 26 | 27 | var ans = duration 28 | for i in 0.. Int { 26 | guard amount > 0 else { return 1 } 27 | 28 | var ans = [Int](repeating: 0, count: amount+1) 29 | ans[0] = 1 30 | 31 | for coin in coins { 32 | guard coin <= amount else { continue } 33 | for i in coin...amount { 34 | ans[i] += ans[i - coin] 35 | } 36 | } 37 | 38 | return ans[amount] 39 | } 40 | 41 | } 42 | -------------------------------------------------------------------------------- /Solutions/500-599/520 Detect Capital.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 520 Detect Capital.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 01/08/2020. 6 | // Copyright © 2020 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/detect-capital/ 12 | class Solution { 13 | 14 | /// Finds whether the usage of capital letters is right or not. 15 | /// 16 | /// - Parameter word: The word. 17 | /// - Returns: True if the usage of capitals is right, otherwise returns false. 18 | /// 19 | /// - Complexity: 20 | /// - time: O(n), where n is the length of the word. 21 | /// - space: O(1), only constant space is used. 22 | func detectCapitalUse(_ word: String) -> Bool { 23 | guard word.count > 1 else { return true } 24 | 25 | let word = Array(word) 26 | 27 | for i in 1.. Int { 25 | var visited = [Bool](repeating: false, count: n + 1) 26 | calculate(n, 1, &visited) 27 | return ans 28 | } 29 | 30 | private func calculate(_ n: Int, _ position: Int, _ visited: inout [Bool]) { 31 | if position > n { 32 | ans += 1 33 | } 34 | 35 | for i in 1...n { 36 | guard !visited[i], (position % i == 0 || i % position == 0) else { continue } 37 | visited[i] = true 38 | calculate(n, position + 1, &visited) 39 | visited[i] = false 40 | } 41 | } 42 | 43 | } 44 | -------------------------------------------------------------------------------- /Solutions/500-599/532 K-diff Pairs in an Array.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 532 K-diff Pairs in an Array.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 03/10/2020. 6 | // Copyright © 2020 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/k-diff-pairs-in-an-array/ 12 | class Solution { 13 | 14 | /// Calculates the number of unique `k`-diff pairs in an array. 15 | /// 16 | /// - Parameters: 17 | /// - nums: The array of integers. 18 | /// - k: An integer. 19 | /// - Returns: The number of unique `k`-diff pairs. 20 | /// 21 | /// - Complexity: 22 | /// - time: O(n), where n is the length of the `nums`. 23 | /// - space: O(n), where n is the length of the `nums`. 24 | func findPairs(_ nums: [Int], _ k: Int) -> Int { 25 | var dict = [Int: Int]() 26 | 27 | for num in nums { 28 | dict[num, default: 0] += 1 29 | } 30 | 31 | var ans = 0 32 | 33 | for (_, el) in dict.enumerated() { 34 | guard (k == 0 && el.value > 1) || (k > 0 && dict.keys.contains(el.key + k)) else { 35 | continue 36 | } 37 | ans += 1 38 | } 39 | 40 | return ans 41 | } 42 | 43 | } 44 | -------------------------------------------------------------------------------- /Solutions/500-599/551 Student Attendance Record I.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 551 Student Attendance Record I.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 22/06/2020. 6 | // Copyright © 2020 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/student-attendance-record-i/ 12 | class Solution { 13 | 14 | /// Finds whether the student could be rewarded according to his attendance record. 15 | /// 16 | /// - Parameter s: A string representing an attendance record for a student. 17 | /// - Returns: True if the student could be rewarded, otherwise returns false. 18 | /// 19 | /// - Complexity: 20 | /// - time: O(n), where n is the number of records in s. 21 | /// - space: O(1), only constant space is used. 22 | func checkRecord(_ s: String) -> Bool { 23 | var a = 0 24 | var l = 0 25 | 26 | for c in s { 27 | if c == "A" { 28 | a += 1 29 | } 30 | 31 | if c == "L" { 32 | l += 1 33 | } else { 34 | l = 0 35 | } 36 | 37 | guard a < 2, l < 3 else { return false } 38 | } 39 | 40 | return true 41 | } 42 | 43 | } 44 | -------------------------------------------------------------------------------- /Solutions/500-599/582 Kill Process.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 582 Kill Process.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 15/02/2021. 6 | // Copyright © 2021 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/kill-process/ 12 | class Solution { 13 | 14 | /// Finds a list of PIDs of processes that will be killed. 15 | /// 16 | /// - Parameters: 17 | /// - pid: A list of the process IDs. 18 | /// - ppid: A list of process parent ID. 19 | /// - kill: An ID of the process to kill. 20 | /// - Returns: A list of PIDs. 21 | /// 22 | /// - Complexity: 23 | /// - time: O(n), where n is the number of processes. 24 | /// - space: O(n), where n is the number of processes. 25 | func killProcess(_ pid: [Int], _ ppid: [Int], _ kill: Int) -> [Int] { 26 | var dict = [Int: [Int]]() 27 | 28 | for (i, id) in pid.enumerated() { 29 | dict[ppid[i], default: [Int]()].append(id) 30 | } 31 | 32 | var ans = [Int]() 33 | var stack = [Int]() 34 | stack.append(kill) 35 | 36 | while !stack.isEmpty { 37 | let cur = stack.removeLast() 38 | ans.append(cur) 39 | guard let children = dict[cur] else { continue } 40 | stack.append(contentsOf: children) 41 | } 42 | 43 | return ans 44 | } 45 | 46 | } 47 | -------------------------------------------------------------------------------- /Solutions/500-599/594 Longest Harmonious Subsequence.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 594 Longest Harmonious Subsequence.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 04/02/2021. 6 | // Copyright © 2021 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/longest-harmonious-subsequence/ 12 | class Solution { 13 | 14 | /// Finds the length of the longest harmonious subsequence among all possible 15 | /// subsequences. 16 | /// 17 | /// - Parameter nums: An integer array. 18 | /// - Returns: The length of longest harmonious subsequence. 19 | /// 20 | /// - Complexity: 21 | /// - time: O(n), where n is the length of `nums`. 22 | /// - space: O(n), where n is the length of `nums`. 23 | func findLHS(_ nums: [Int]) -> Int { 24 | var dict = [Int: Int]() 25 | 26 | var ans = 0 27 | for num in nums { 28 | dict[num, default: 0] += 1 29 | if let val = dict[num + 1] { 30 | ans = max(ans, val + (dict[num] ?? 0)) 31 | } 32 | if let val = dict[num - 1] { 33 | ans = max(ans, val + (dict[num] ?? 0)) 34 | } 35 | } 36 | 37 | return ans 38 | } 39 | 40 | } 41 | -------------------------------------------------------------------------------- /Solutions/600-699/624 Maximum Distance in Arrays.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 624 Maximum Distance in Arrays.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 01/10/2020. 6 | // Copyright © 2020 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/maximum-distance-in-arrays/ 12 | class Solution { 13 | 14 | /// Finds the maximum distance between two integers. 15 | /// 16 | /// - Parameter arrays: Arrays where each array is sorted in ascending order. 17 | /// - Returns: The maximum distance. 18 | /// 19 | /// - Complexity: 20 | /// - time: O(n), where n is the length of `arrays`. 21 | /// - space: O(1), only constant space is used. 22 | func maxDistance(_ arrays: [[Int]]) -> Int { 23 | guard var minVal = arrays.first?.first, 24 | var maxVal = arrays.first?.last else { 25 | return -1 26 | } 27 | 28 | var ans = 0 29 | 30 | for i in 1.. Bool { 23 | var open = 0 24 | var close = 0 25 | 26 | for c in s { 27 | open += c == "(" ? 1 : -1 28 | close += c != ")" ? 1 : -1 29 | guard close >= 0 else { return false } 30 | open = max(open, 0) 31 | } 32 | 33 | return open == 0 34 | } 35 | 36 | } 37 | -------------------------------------------------------------------------------- /Solutions/700-799/704 Binary Search.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 704 Binary Search.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 08/10/2020. 6 | // Copyright © 2020 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/binary-search/ 12 | class Solution { 13 | 14 | /// Finds the index of `target` in the given array. 15 | /// 16 | /// - Parameters: 17 | /// - nums: A sorted (in ascending order) integer array. 18 | /// - target: The target value. 19 | /// - Returns: If the target exists in an array returns its index, otherwise 20 | /// returns -1. 21 | /// 22 | /// - Complexity: 23 | /// - time: O(log(n)), where n is the length of the `nums`. 24 | /// - space: O(1), only constant space is used. 25 | func search(_ nums: [Int], _ target: Int) -> Int { 26 | var low = 0 27 | var high = nums.count - 1 28 | 29 | while low <= high { 30 | var mid = low + (high - low) / 2 31 | 32 | guard nums[mid] != target else { return mid } 33 | 34 | if nums[mid] < target { 35 | low = mid + 1 36 | } else { 37 | high = mid - 1 38 | } 39 | } 40 | 41 | return -1 42 | } 43 | 44 | } 45 | -------------------------------------------------------------------------------- /Solutions/700-799/713 Subarray Product Less Than K.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 713 Subarray Product Less Than K.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 28/09/2020. 6 | // Copyright © 2020 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/subarray-product-less-than-k/ 12 | class Solution { 13 | 14 | /// Counts the number of contiguous subarrays where the product of all the elements 15 | /// in the subarray is less than `k`. 16 | /// 17 | /// - Parameters: 18 | /// - nums: An array of positive integers. 19 | /// - k: The value `k`. 20 | /// - Returns: The number of contiguous subarrays. 21 | /// 22 | /// - Complexity: 23 | /// - time: O(n), where n is the length of `nums`. 24 | /// - space: O(1), only constant space is used. 25 | func numSubarrayProductLessThanK(_ nums: [Int], _ k: Int) -> Int { 26 | guard k > 1 else { return 0 } 27 | var ans = 0 28 | var prod = 1 29 | var j = 0 30 | 31 | for (i, num) in nums.enumerated() { 32 | prod *= num 33 | while prod >= k { 34 | prod /= nums[j] 35 | j += 1 36 | } 37 | ans += i - j + 1 38 | } 39 | 40 | return ans 41 | } 42 | 43 | } 44 | -------------------------------------------------------------------------------- /Solutions/700-799/714 Best Time to Buy and Sell Stock with Transaction Fee.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 714 Best Time to Buy and Sell Stock with Transaction Fee.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 16/03/2021. 6 | // Copyright © 2021 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/ 12 | class Solution { 13 | 14 | /// Finds the maximum profit you can achieve. 15 | /// 16 | /// - Parameters: 17 | /// - prices: An array of prices. 18 | /// - fee: A transaction fee. 19 | /// - Returns: The maximum profit. 20 | /// 21 | /// - Complexity: 22 | /// - time: O(n), where n is the length of `prices`. 23 | /// - space: O(1), only constant space is used. 24 | func maxProfit(_ prices: [Int], _ fee: Int) -> Int { 25 | var ans = 0 26 | var hold = -prices[0] 27 | 28 | for i in 1.. [Int] { 23 | var ans = [Int]() 24 | 25 | for asteroid in asteroids { 26 | guard asteroid < 0 else { 27 | ans.append(asteroid) 28 | continue 29 | } 30 | 31 | while let last = ans.last, last > 0, last < abs(asteroid) { 32 | ans.removeLast() 33 | } 34 | 35 | if let last = ans.last, last == abs(asteroid) { 36 | ans.removeLast() 37 | } else if ans.isEmpty || ans.last ?? Int.max < 0 { 38 | ans.append(asteroid) 39 | } 40 | } 41 | 42 | return ans 43 | } 44 | 45 | } 46 | -------------------------------------------------------------------------------- /Solutions/700-799/744 Find Smallest Letter Greater Than Target.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 744 Find Smallest Letter Greater Than Target.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 13/03/2021. 6 | // Copyright © 2021 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/find-smallest-letter-greater-than-target/ 12 | class Solution { 13 | 14 | /// Finds the smallest element in the list that is greater than the given 15 | /// `target`. 16 | /// 17 | /// - Parameters: 18 | /// - letters: A list of sorted characters. 19 | /// - target: A target letter. 20 | /// - Returns: The smallest element in the list greater than the given 21 | /// `target`. 22 | /// 23 | /// - Complexity: 24 | /// - time: O(log n), where n is the length of `letters`. 25 | /// - space: O(1), only constant space is used. 26 | func nextGreatestLetter(_ letters: [Character], _ target: Character) -> Character { 27 | let n = letters.count 28 | var start = 0 29 | var end = n 30 | 31 | while start < end { 32 | let mid = start + (end - start) / 2 33 | 34 | if letters[mid] <= target { 35 | start = mid + 1 36 | } else { 37 | end = mid 38 | } 39 | } 40 | 41 | return letters[start % n] 42 | } 43 | 44 | } 45 | -------------------------------------------------------------------------------- /Solutions/700-799/750 Number Of Corner Rectangles.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 750 Number Of Corner Rectangles.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 29/01/2021. 6 | // Copyright © 2021 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/number-of-corner-rectangles/ 12 | class Solution { 13 | 14 | /// Finds the number of corner rectangles. 15 | /// 16 | /// - Parameter grid: A grid. 17 | /// - Returns: The number of corner rectangles. 18 | /// 19 | /// - Complexity: 20 | /// - time: O(n * m^2), where n is the number of rows in the `grid`, and m 21 | /// is the number of columns in the `grid`. 22 | /// - space: O(m^2), where m is the number of columns in the `grid`. 23 | func countCornerRectangles(_ grid: [[Int]]) -> Int { 24 | var count = [Int: Int]() 25 | var ans = 0 26 | 27 | for row in grid { 28 | for c1 in 0.. Int { 23 | var target = abs(target) 24 | var step = 0 25 | 26 | while target > 0 { 27 | step += 1 28 | target -= step 29 | } 30 | 31 | return target % 2 == 0 ? step : step + (step % 2) + 1 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /Solutions/700-799/760 Find Anagram Mappings.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 760 Find Anagram Mappings.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 03/02/2021. 6 | // Copyright © 2021 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/find-anagram-mappings/ 12 | class Solution { 13 | 14 | /// Finds an index mapping. 15 | /// 16 | /// - Parameters: 17 | /// - A: An array of integers. 18 | /// - B: An array of integers. 19 | /// - Returns: The mapped indexes. 20 | /// 21 | /// - Complexity: 22 | /// - time: O(n), where n is the length of `A` and `B`. 23 | /// - space: O(n), where n is the length of `A` and `B`. 24 | func anagramMappings(_ A: [Int], _ B: [Int]) -> [Int] { 25 | var dict = [Int: Int]() 26 | 27 | for (i, b) in B.enumerated() { 28 | dict[b] = i 29 | } 30 | 31 | var ans = [Int]() 32 | 33 | for a in A { 34 | guard let val = dict[a] else { continue } 35 | ans.append(val) 36 | } 37 | 38 | return ans 39 | } 40 | 41 | } 42 | -------------------------------------------------------------------------------- /Solutions/700-799/763 Partition Labels.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 763 Partition Labels.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 04/09/2020. 6 | // Copyright © 2020 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/partition-labels/ 12 | class Solution { 13 | 14 | /// Partitions a string into as many parts as possible so that each letter appears in 15 | /// at most one part. 16 | /// 17 | /// - Parameter S: The string. 18 | /// - Returns: A list of integers representing the size of parts. 19 | /// 20 | /// - Complexity: 21 | /// - time: O(n), where n is the length of the given string. 22 | /// - space: O(n), where n is the length of the given string. 23 | func partitionLabels(_ S: String) -> [Int] { 24 | var dict = [Character: Int]() 25 | 26 | for (i, ch) in S.enumerated() { 27 | dict[ch] = i 28 | } 29 | 30 | var j = 0 31 | var anchor = 0 32 | var ans = [Int]() 33 | for (i, ch) in S.enumerated() { 34 | j = max(j, dict[ch] ?? -1) 35 | 36 | guard i == j else { continue } 37 | ans.append(i - anchor + 1) 38 | anchor = i + 1 39 | } 40 | 41 | return ans 42 | } 43 | 44 | } 45 | -------------------------------------------------------------------------------- /Solutions/700-799/771 Jewels and Stones.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 771 Jewels and Stones.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 05/04/2020. 6 | // Copyright © 2020 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/jewels-and-stones 12 | class Solution { 13 | 14 | /// Return how many of your stones are also jewels. 15 | /// 16 | /// - Parameters: 17 | /// - J: Representing the types of stones that are jewels. 18 | /// - S: Representing the stones you have. 19 | /// 20 | /// - Returns: How many of your stones are jewels. 21 | /// 22 | /// - Complexity: 23 | /// - time: O(j + s), where j is the length of the J, and s is the length of the S. 24 | /// - space: O(j), where j is the length of the J. 25 | func numJewelsInStones(_ J: String, _ S: String) -> Int { 26 | var jewels = Set() 27 | for jewel in J { 28 | jewels.insert(jewel) 29 | } 30 | 31 | var ans = 0 32 | for stone in S { 33 | guard jewels.contains(stone) else { continue } 34 | ans += 1 35 | } 36 | 37 | return ans 38 | } 39 | 40 | } 41 | -------------------------------------------------------------------------------- /Solutions/700-799/784 Letter Case Permutation.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 784 Letter Case Permutation.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 16/02/2021. 6 | // Copyright © 2021 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/letter-case-permutation/ 12 | class Solution { 13 | 14 | /// Finds a list of all possible strings we could create. 15 | /// 16 | /// - Parameter S: A string. 17 | /// - Returns: A list of all possible strings. 18 | /// 19 | /// - Complexity: 20 | /// - time: O(2^n * n), where n is the length of `S`. 21 | /// - space: O(2^n * n), where n is the length of `S`. 22 | func letterCasePermutation(_ S: String) -> [String] { 23 | var ans = [[Character]]() 24 | ans.append([]) 25 | 26 | for ch in S { 27 | let n = ans.count 28 | if ch.isLetter { 29 | for i in 0.. Double { 26 | var dp = [[Double]](repeating: [Double](repeating: 0.0, count:102), count: 102) 27 | dp[0][0] = Double(poured) 28 | 29 | for row in 0...query_row { 30 | for col in 0...row { 31 | var q = (dp[row][col] - 1) / 2 32 | guard q > 0 else { continue } 33 | dp[row+1][col] += q 34 | dp[row+1][col+1] += q 35 | } 36 | } 37 | 38 | return min(1, dp[query_row][query_glass]) 39 | } 40 | 41 | } 42 | -------------------------------------------------------------------------------- /Solutions/800-899/800 Similar RGB Color.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 800 Similar RGB Color.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 17/02/2021. 6 | // Copyright © 2021 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/similar-rgb-color/ 12 | class Solution { 13 | 14 | /// Finds a 7 character color that is most similar to a given color, and has a 15 | /// shorthand. 16 | /// 17 | /// - Parameter color: The color. 18 | /// - Returns: A 7 character color. 19 | /// 20 | /// - Complexity: 21 | /// - time: O(1), only constant time is used. 22 | /// - space: O(1), only constant space is used. 23 | func similarRGB(_ color: String) -> String { 24 | let color = Array(color) 25 | var ans = "#" 26 | 27 | for i in 0..<3 { 28 | guard let tmp = Int(String(color[(i*2+1)..<(i*2+3)]), radix: 16) else { 29 | fatalError("Invalid color") 30 | } 31 | let round = ((tmp + 8) / 17) * 17 32 | ans = round > 0 ? "\(ans)\(String(round, radix: 16))" : "\(ans)00" 33 | } 34 | 35 | return ans 36 | } 37 | 38 | } 39 | -------------------------------------------------------------------------------- /Solutions/800-899/824 Goat Latin.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 824 Goat Latin.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 19/08/2020. 6 | // Copyright © 2020 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/goat-latin/ 12 | class Solution { 13 | 14 | /// Converts the sentence to "Goat Latin". 15 | /// 16 | /// - Parameter S: The sentence. 17 | /// - Returns: The sentence representing the conversion to Goat Latin. 18 | /// 19 | /// - Complexity: 20 | /// - time: O(n), where n is the length of the sentence. 21 | /// - space: O(m), where m is the length of the sentence on Goat Latin. 22 | func toGoatLatin(_ S: String) -> String { 23 | let vowels = Set(arrayLiteral: "a","e","i","o","u") 24 | var ans = S.split(separator: " ") 25 | 26 | for i in 0.. [[Int]] { 23 | var ans = A 24 | 25 | for i in 0.. Int { 23 | var left = -1 24 | var ans = 0 25 | 26 | for (i, seat) in seats.enumerated() { 27 | guard seat == 1 else { continue } 28 | 29 | ans = left == -1 ? max(ans, i) : max(ans, (i - left) / 2) 30 | 31 | left = i 32 | } 33 | 34 | guard let last = seats.last, last == 1 else { 35 | return max(ans, seats.count - left - 1) 36 | } 37 | 38 | return ans 39 | } 40 | 41 | } 42 | -------------------------------------------------------------------------------- /Solutions/800-899/858 Mirror Reflection.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 858 Mirror Reflection.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 17/11/2020. 6 | // Copyright © 2020 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/mirror-reflection/ 12 | class Solution { 13 | 14 | /// Finds the number of the receptor that the ray meets first. 15 | /// 16 | /// - Parameters: 17 | /// - p: Walls length. 18 | /// - q: The distance where a laser ray first meets the east wall. 19 | /// - Returns: The number of the receptor. 20 | /// 21 | /// - Complexity: 22 | /// - time: O(log(p)), where p is wall length. 23 | /// - space: O(1), only constant space is used. 24 | func mirrorReflection(_ p: Int, _ q: Int) -> Int { 25 | var m = q 26 | var n = p 27 | 28 | while m % 2 == 0, n % 2 == 0 { 29 | m /= 2 30 | n /= 2 31 | } 32 | 33 | if m % 2 == 0, n % 2 == 1 { 34 | return 0 35 | } 36 | 37 | if m % 2 == 1, n % 2 == 1 { 38 | return 1 39 | } 40 | 41 | if m % 2 == 1, n % 2 == 0 { 42 | return 2 43 | } 44 | 45 | return -1 46 | } 47 | 48 | } 49 | -------------------------------------------------------------------------------- /Solutions/800-899/869 Reordered Power of 2.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 869 Reordered Power of 2.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 21/03/2021. 6 | // Copyright © 2021 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/reordered-power-of-2/ 12 | class Solution { 13 | 14 | /// Finds if we can reorder digits in `N` and get the power of 2. 15 | /// 16 | /// - Parameter N: A positive integer. 17 | /// - Returns: True if the resulting number is a power of 2, otherwise returns false. 18 | /// 19 | /// - Complexity: 20 | /// - time: O(log^2 n), where n is the given `N`. 21 | /// - space: O(log n), where n is the given `N`. 22 | func reorderedPowerOf2(_ N: Int) -> Bool { 23 | let a = count(N) 24 | for i in 0..<31 { 25 | guard a == count(1 << i) else { continue } 26 | return true 27 | } 28 | return false 29 | } 30 | 31 | private func count(_ n: Int) -> [Int] { 32 | var n = n 33 | var ans = [Int](repeating: 0, count: 10) 34 | while n > 0 { 35 | ans[n % 10] += 1 36 | n /= 10 37 | } 38 | return ans 39 | } 40 | 41 | } 42 | -------------------------------------------------------------------------------- /Solutions/800-899/876 Middle of the Linked List.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 876 Middle of the Linked List.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 10/05/2020. 6 | // Copyright © 2020 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/middle-of-the-linked-list/ 12 | class Solution { 13 | 14 | /// Finds middle node of the Linked List. 15 | /// 16 | /// - Parameter head: Non-empty linked list. 17 | /// - Returns: A middle node of the linked list. 18 | /// 19 | /// - Complexity: 20 | /// - time: O(n), where n is the number of nodes in the linked list. 21 | /// - space: O(1), only constant space is used. 22 | func middleNode(_ head: ListNode?) -> ListNode? { 23 | var slow = head 24 | var fast = head 25 | 26 | while let fastNext = fast?.next { 27 | slow = slow?.next 28 | fast = fastNext.next 29 | } 30 | 31 | return slow 32 | } 33 | 34 | } 35 | 36 | /// Provided Code 37 | public class ListNode { 38 | 39 | public var val: Int 40 | public var next: ListNode? 41 | 42 | public init(_ val: Int) { 43 | self.val = val 44 | self.next = nil 45 | } 46 | 47 | } 48 | -------------------------------------------------------------------------------- /Solutions/800-899/881 Boats to Save People.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 881 Boats to Save People.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 13/01/2021. 6 | // Copyright © 2021 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/boats-to-save-people/ 12 | class Solution { 13 | 14 | /// Finds the minimum number of boats to carry every given person. 15 | /// 16 | /// - Parameters: 17 | /// - people: The people's weight. 18 | /// - limit: A maximum weight each boat can carry. 19 | /// - Returns: The minimum number of boats. 20 | /// 21 | /// - Complexity: 22 | /// - time: O(n log(n)), where n is the number of people. 23 | /// - space: O(n), where n is the number of people. 24 | func numRescueBoats(_ people: [Int], _ limit: Int) -> Int { 25 | var people = people.sorted() 26 | var ans = 0 27 | var i = 0 28 | var j = people.count - 1 29 | 30 | while i <= j { 31 | if people[i] + people[j] <= limit { 32 | i += 1 33 | } 34 | j -= 1 35 | 36 | ans += 1 37 | } 38 | 39 | return ans 40 | } 41 | 42 | } 43 | -------------------------------------------------------------------------------- /Solutions/900-999/901 Online Stock Span.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 901 Online Stock Span.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 19/05/2020. 6 | // Copyright © 2020 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/online-stock-span/ 12 | class StockSpanner { 13 | 14 | typealias Stock = (price: Int, span: Int) 15 | 16 | private var stack: [Stock] 17 | 18 | init() { 19 | stack = [Stock]() 20 | } 21 | 22 | /// Collects daily price quotes for the stock, and returns the span of that stock's 23 | /// price for the current day. 24 | /// 25 | /// - Parameter price: The daily price for the stock. 26 | /// - Returns: The span of that stock's price for the current day. 27 | /// 28 | /// - Complexity: 29 | /// - time: O(q), where q is the number of calls to *StockSpanner.next*. 30 | /// - space: O(q), where q is the number of calls to *StockSpanner.next*. 31 | func next(_ price: Int) -> Int { 32 | var span = 1 33 | 34 | while let last = stack.last, last.price <= price { 35 | span += last.span 36 | stack.removeLast() 37 | } 38 | 39 | stack.append((price, span)) 40 | return span 41 | } 42 | 43 | } 44 | -------------------------------------------------------------------------------- /Solutions/900-999/905 Sort Array By Parity.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 905 Sort Array By Parity.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 21/08/2020. 6 | // Copyright © 2020 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/sort-array-by-parity/ 12 | class Solution { 13 | 14 | /// Returns an array consisting of all the even elements of A, followed by all the odd 15 | /// elements of A. 16 | /// 17 | /// - Parameter A: The array. 18 | /// - Returns: All the even elements of A, followed by all the odd elements of A. 19 | /// 20 | /// - Complexity: 21 | /// - time: O(n), where n is the length of A. 22 | /// - space: O(n), where n is the length of A. 23 | func sortArrayByParity(_ A: [Int]) -> [Int] { 24 | var ans = A 25 | 26 | var i = 0 27 | var j = ans.count - 1 28 | 29 | while i < j { 30 | if ans[i] % 2 > ans[j] % 2 { 31 | ans.swapAt(i, j) 32 | } 33 | 34 | if ans[i] % 2 == 0 { 35 | i += 1 36 | } 37 | 38 | if ans[j] % 2 == 1 { 39 | j -= 1 40 | } 41 | } 42 | 43 | return ans 44 | } 45 | 46 | } 47 | -------------------------------------------------------------------------------- /Solutions/900-999/910 Smallest Range II.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 910 Smallest Range II.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 21/12/2020. 6 | // Copyright © 2020 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/smallest-range-ii/ 12 | class Solution { 13 | 14 | /// Finds the smallest possible difference between the maximum value of `B` and 15 | /// the minimum value of `B`. `B[i] = A[i] + K` or `B[i] = A[i] - K`. 16 | /// 17 | /// - Parameters: 18 | /// - A: An array of integers. 19 | /// - K: An integer. 20 | /// - Returns: The smallest possible difference. 21 | /// 22 | /// - Complexity: 23 | /// - time: O(n log(n)), where n is the length of `A`. 24 | /// - space: O(1), only constant space is used. 25 | func smallestRangeII(_ A: [Int], _ K: Int) -> Int { 26 | let n = A.count 27 | let a = A.sorted() 28 | var ans = a[n-1] - a[0] 29 | 30 | for i in 0.. Int { 32 | slideWindow.append(t) 33 | 34 | var remove = 0 35 | for time in slideWindow { 36 | guard t - time > timeLimit else { break } 37 | remove += 1 38 | } 39 | if remove > 0 { 40 | slideWindow.removeFirst(remove) 41 | } 42 | 43 | return slideWindow.count 44 | } 45 | 46 | } 47 | -------------------------------------------------------------------------------- /Solutions/900-999/941 Valid Mountain Array.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 941 Valid Mountain Array.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 10/12/2020. 6 | // Copyright © 2020 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/valid-mountain-array/ 12 | class Solution { 13 | 14 | /// Finds if and only if the given array is a valid mountain array. 15 | /// 16 | /// - Parameter A: An array of integers. 17 | /// - Returns: True if `A` is a valid mountain array, otherwise returns false. 18 | /// 19 | /// - Complexity: 20 | /// - time: O(n), where n is the length of `A`. 21 | /// - space: O(1), only constant space is used. 22 | func validMountainArray(_ A: [Int]) -> Bool { 23 | let n = A.count 24 | guard n >= 3 else { return false } 25 | 26 | var i = 0 27 | 28 | while (i + 1) < n, A[i] < A[i+1] { 29 | i += 1 30 | } 31 | 32 | guard i != 0, i != n - 1 else { return false } 33 | 34 | while (i + 1) < n, A[i] > A[i+1] { 35 | i += 1 36 | } 37 | 38 | return i == n - 1 39 | } 40 | 41 | } 42 | -------------------------------------------------------------------------------- /Solutions/900-999/957 Prison Cells After N Days.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 957 Prison Cells After N Days.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 03/07/2020. 6 | // Copyright © 2020 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/prison-cells-after-n-days/ 12 | class Solution { 13 | 14 | /// Calculates the state of the prison after N days. 15 | /// 16 | /// - Parameters: 17 | /// - cells: The initial state of the prison. 18 | /// - N: The number of days. 19 | /// - Returns: The state of the prison after N days. 20 | /// 21 | /// - Complexity: 22 | /// - time: O(1), only constant time is used. 23 | /// - space: O(1), only constant space is used. 24 | func prisonAfterNDays(_ cells: [Int], _ N: Int) -> [Int] { 25 | var ans = cells 26 | 27 | for _ in 0..<(N-1) % 14 + 1 { 28 | var cur = [Int](repeating: 0, count: 8) 29 | for i in 1..<7 { 30 | cur[i] = ans[i-1] == ans[i+1] ? 1 : 0 31 | } 32 | ans = cur 33 | } 34 | 35 | return ans 36 | } 37 | 38 | } 39 | -------------------------------------------------------------------------------- /Solutions/900-999/997 Find the Town Judge.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 997 Find the Town Judge.swift 3 | // LeetCode-Solutions 4 | // 5 | // Created by Aleksandar Dinic on 10/05/2020. 6 | // Copyright © 2020 Aleksandar Dinic. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Source: https://leetcode.com/problems/find-the-town-judge/ 12 | class Solution { 13 | 14 | /// Finds the Town Judge 15 | /// 16 | /// - Parameters: 17 | /// - N: Number of people in the Town. 18 | /// - trust: An array of pairs trust[i] = [a, b] representing that the person 19 | /// labelled a trusts the person labelled b. 20 | /// - Returns: The label of the town judge, otherwise returns -1. 21 | /// 22 | /// - Complexity: 23 | /// - time: O(max(t, n)), where t is the length of the *trust*, and n is the *N*. 24 | /// - space: O(n), where n is the *N*. 25 | func findJudge(_ N: Int, _ trust: [[Int]]) -> Int { 26 | var people = [Int](repeating: 0, count: N) 27 | 28 | for t in trust { 29 | people[t[0]-1] -= 1 30 | people[t[1]-1] += 1 31 | } 32 | 33 | for i in 1...N { 34 | guard people[i-1] == N-1 else { continue } 35 | return i 36 | } 37 | 38 | return -1 39 | } 40 | 41 | } 42 | --------------------------------------------------------------------------------