├── ArraysAndStrings ├── 796-RotateString.swift ├── 136-SingleNumber.swift ├── 392-IsSequence.swift ├── 1864-MaxElementAfterDecrementing.swift ├── 448-FindAllDisappearedNumbers.swift ├── 1010-PairOfSongsDivby60.swift ├── 128-LongestConsecutiveSquence.swift ├── 383-RansomeNote.swift ├── 1656-OrderedStrea.swift ├── 238-ProductOfArrayExceptSelf.swift ├── 287-FindDuplicates.swift ├── 38-CountAndSay.swift ├── 697-DegreeOfAnArray.swift ├── 443-StringCompression.swift ├── AddTwoNums │ └── 415-AddStrings.swift ├── 1567-MaxLenOfSubarrayWithPosProd.swift └── 1347-MinStepsToMakeStringsAnagram.swift ├── ProblemSolving.playground ├── Resources │ ├── same-countries-1.png │ ├── same-countries-2.png │ └── same-countries-3.png ├── xcuserdata │ ├── osamabashir.xcuserdatad │ │ ├── xcdebugger │ │ │ └── Breakpoints_v2.xcbkptlist │ │ └── xcschemes │ │ │ └── xcschememanagement.plist │ ├── osamabinbashir.xcuserdatad │ │ └── xcschemes │ │ │ └── xcschememanagement.plist │ └── obashir.xcuserdatad │ │ └── xcschemes │ │ └── xcschememanagement.plist ├── playground.xcworkspace │ ├── xcuserdata │ │ ├── obashir.xcuserdatad │ │ │ └── UserInterfaceState.xcuserstate │ │ ├── osamabashir.xcuserdatad │ │ │ └── UserInterfaceState.xcuserstate │ │ └── osamabinbashir.xcuserdatad │ │ │ └── UserInterfaceState.xcuserstate │ └── contents.xcworkspacedata ├── Sources │ ├── LinkListNode.swift │ └── TreeNode.swift └── Pages │ ├── MergeTwoBinaryTrees.xcplaygroundpage │ └── Contents.swift │ ├── FindSmallestSetOfVertices.xcplaygroundpage │ └── Contents.swift │ ├── maxProfit.xcplaygroundpage │ └── Contents.swift │ ├── firstUniqueChar.xcplaygroundpage │ └── Contents.swift │ ├── trailingZeros.xcplaygroundpage │ └── Contents.swift │ ├── hasCycle.xcplaygroundpage │ └── Contents.swift │ ├── GroupAnagrams.xcplaygroundpage │ └── Contents.swift │ ├── isSymmetric.xcplaygroundpage │ └── Contents.swift │ ├── missingnumber.xcplaygroundpage │ └── Contents.swift │ ├── PowerOfThrre.xcplaygroundpage │ └── Contents.swift │ ├── CheckIfAll1KDistApart.xcplaygroundpage │ └── Contents.swift │ ├── inorderTraversal.xcplaygroundpage │ └── Contents.swift │ ├── lengthOfLongestSubstring.xcplaygroundpage │ └── Contents.swift │ ├── nondecreasingarray.xcplaygroundpage │ └── Contents.swift │ ├── SameCountries.xcplaygroundpage │ └── timeline.xctimeline │ ├── RandomPickWeigth.xcplaygroundpage │ └── Contents.swift │ ├── AllPathFromSourceToTarget.xcplaygroundpage │ └── Contents.swift │ ├── IntersectionofTwoLinkedLists.xcplaygroundpage │ └── Contents.swift │ ├── WordPattern.xcplaygroundpage │ └── Contents.swift │ ├── FilterRestaurant.xcplaygroundpage │ └── Contents.swift │ ├── SortIntegerByThePowerValue.xcplaygroundpage │ └── Contents.swift │ ├── DecodeString.xcplaygroundpage │ └── Contents.swift │ ├── MeetingRoom2.xcplaygroundpage │ └── Contents.swift │ ├── Combination.xcplaygroundpage │ └── Contents.swift │ ├── CountandSay.xcplaygroundpage │ └── Contents.swift │ ├── ClimbingStairs.xcplaygroundpage │ └── Contents.swift │ ├── FindLeavesOfBinaryTree.xcplaygroundpage │ └── Contents.swift │ ├── LongestCommonPrefix.xcplaygroundpage │ └── Contents.swift │ ├── MinIndexSumOfTwoList.xcplaygroundpage │ └── Contents.swift │ ├── MergeIntervals.xcplaygroundpage │ └── Contents.swift │ ├── GenerateParenthesis.xcplaygroundpage │ └── Contents.swift │ ├── CompressString.xcplaygroundpage │ └── Contents.swift │ ├── strStr.xcplaygroundpage │ └── Contents.swift │ ├── MinStack.xcplaygroundpage │ └── Contents.swift │ ├── LetterCasePermutation.xcplaygroundpage │ └── Contents.swift │ └── FindJudge.xcplaygroundpage │ └── Contents.swift ├── LinkList ├── 237-DeleteNode.swift ├── 876-MiddleOfTheNode.swift ├── 160-IntersectionOfTwoList.swift ├── 83-RemoveDupFromSortedList.swift ├── 2095-DeleteTheMiddleNodeOfLL.swift ├── 141-CycleDetection.swift ├── 19-RemoveNthNodeFromList.swift ├── 143-ReorderList.swift ├── 21-MergeList.swift ├── 82-RemoveDuplicatesFromSortedList2.swift ├── 203-RemoveLinkList.swift ├── 86-PartitionList.swift └── 142-LinkListCycle2.swift ├── Mix ├── 151-ReverseWordInAString.swift ├── 237-DeleteNodeInALinkedList.swift ├── 170-LargestNumbers.swift ├── 179-LargestNumber.swift ├── 160-IntersectionOfTwoLinkedList.swift ├── 1-TwoSum.swift ├── 49-GroupAnagrams.swift ├── 665-NonDecreasingArray.swift ├── 303-RangeSumQuery.swift ├── 648-ReplaceWords.swift ├── 350-IntersectionOfTwoArrays2.swift ├── 20-ValidParanthesis.swift ├── 209-MinSizeSubarraySum.swift ├── 238-ProductAarrayExceptSelf.swift ├── 3-LongestSubstringWithoutRepeatingChar.swift ├── 189-RotateArray.swift ├── 162-FindPeakElement.swift ├── 844-BackspaceStringCompare.swift ├── 12-IntToRoman.swift ├── 1333-FilterRestaurantsByVeganFreindlyPriceAndDistance.swift ├── 75-SortColors.swift ├── 1099-TwoSumLessThanK.swift ├── 528-RandomPickWithWeight.swift ├── 202-HappyNumber.swift ├── 38-CountAndSay.swift ├── 605-CanPlaceFlowers.swift ├── 443-StringCompression.swift ├── 1509-MinDifferenceInThreeMoves.swift ├── 56-MergeIntervals.swift ├── 234-PalindromeLinkList.swift ├── 414-ThirdLargestNum.swift ├── 593-ValidSquare.swift ├── 346-MovingAverages.swift └── 13-RomanToInteger.swift ├── Graph ├── 1557-MinNumOfVerticesToReachAllNode.swift ├── 997-FindJudge.swift ├── 797-AllPathFromSourceToTarget.swift ├── 841-KeysAndRoom.swift ├── DetectCycleInDirectedGraph.swift ├── 133-ColneGraph.swift ├── Connected Component │ ├── 323-CountComponent.swift │ └── 200-NumIslands.swift ├── 277-FindCelebrity.swift ├── 1706-WhereWillTheBallFall.swift ├── 261-GraphValidTree.swift ├── riversize.swift ├── 1376-TimeNeededToInformAllEmployees.swift └── 1306-JumpGame3.swift ├── Trees ├── 226-InvertBinaryTree.swift ├── 100-SameTree.swift ├── 112-pathsum.swift ├── 230-KthSmallestElementInBST.swift ├── 617-MergeTrees.swift ├── 129-SumRootToLeafNumbers.swift ├── 543-DiameterOfTree.swift ├── 116-PopulatingNextRightPointers.swift ├── 337-HouseRobber3.swift ├── 426-ConvertBSTToDD.swift ├── 687-LongestUniValuePath.swift ├── 117-PopulatingNextRightPointer2.swift ├── LCA │ └── 1650-LCA3.swift ├── 111-mindepth.swift ├── 951-FlipEquivalent.swift ├── 113-PathSum2.swift ├── 102-levelOrderTraversal.swift ├── 107-ReverseLevelOrderTraversal.swift ├── 298-BinTreeLongestConsecutiveSeq.swift ├── 105-ConstructTreeFromPreOrderAndInOrder.swift ├── 663-EqualTreePartition.swift ├── 106-ConstructPostInorderTree.swift ├── 637-AvgOfBinaryTree.swift ├── 1430-ValidSequence.swift ├── 250-CountOfUnivalSubtree.swift ├── 437-PathSum3.swift ├── 314-VerticalOrder.swift └── 103-ZigZagTraversal.swift ├── OA ├── 441-ArrangingCoins.swift ├── minGroups.swift ├── 628-MaxProdOfThreeNums.swift ├── 1492-kthFactor.swift ├── 1710-MaxUnitsOnATruck.swift ├── 118-PascalsTri.swift ├── gridCluster.swift ├── 1331-RankTransformOfAnArray.swift ├── MinNum.swift ├── 696-countBinarySubstring.swift ├── MaxQuality.swift ├── 1109-CorporateFlightBookings.swift ├── 496-NextGreaterElement.swift ├── PassStrength.swift ├── 138-CopyListWithRandomPtr.swift ├── 12-intToRoman.swift ├── 909-SnakesAndLadder.swift ├── 939-CousingInBinTree.swift └── minswaps.swift ├── Combinatorics And Backtracking ├── 78-Subsets.swift ├── 50-Pow.swift ├── 339-NestedWeightedList.swift ├── 90-subset2.swift ├── 247-StrobogrammaticNumbers2.swift ├── 77-combinations.swift ├── 46-permutation.swift ├── 39-CombinationSum.swift ├── 784-LetterCasePermutation.swift ├── 22-GenerateParanthesis.swift └── 216-CombinationSum3.swift ├── Stock problems ├── 122-BestTimeToBuyStock2.swift └── 121-BestTimeToBuySellStock.swift ├── CTCI ├── Search and Sort │ ├── 49-GroupAnagrams.swift │ ├── 88-MergeSortedArray.swift │ └── 74-SearchIn2DMatrix.swift ├── Graph And Tree │ ├── 4.2- MinimalTree.swift │ ├── 4.5-ValidateBST.swift │ ├── 4.4-IsBalanced.swift │ ├── 4.8-CommonAncestor.swift │ ├── 4.1 - RoutesBetween2Nodes.swift │ └── 4.10-CheckSubtree.swift └── DPAndRecursion │ └── 8.3-MagicIndex.swift ├── Others ├── PhoneNumber │ └── phoneNumber.swift └── NumberDictionary │ └── numberDictionatry.swift ├── DP ├── Fibnumber │ ├── 198-HouseRobber.swift │ ├── 70-ClimbigStairs.swift │ ├── NumberFactors.swift │ ├── 1137-tribnum.swift │ ├── 276-PainFence.swift │ ├── 509-fibnum.swift │ ├── 91-DecodeWays.swift │ ├── MinJumpFee.swift │ ├── 198-HouseRobbers2.swift │ ├── 45-JumpGame2.swift │ └── 256-PaintHouse.swift ├── LongestCommonSubsequence │ ├── LIS │ │ ├── 300-LIS.swift │ │ └── 673-NumberOfLIS.swift │ ├── FindMaxSumSubSeq.swift │ ├── 583-DeleteOperationForTwoString.swift │ └── MinDeleteionAndInsertionToTransformToOtherString.swift ├── Matrix │ ├── 62-UniquePaths.swift │ ├── 931-MinFallingPathSum.swift │ ├── 64-MinCostPath.swift │ └── 63-UniquePaths2.swift ├── 01Knapsack-Unbounded │ ├── 279-PerfectSquare.swift │ ├── 518-CoinChange2.swift │ └── 343-IntegerBreak.swift ├── LongestPalindromicSubsequence │ └── 647-CountOfPalindromiceSubstring.swift ├── 0-1KnapSack │ ├── 1049-LastStoneWeight2.swift │ ├── SubsetSumProblem.swift │ └── 0-1knapsack.swift └── WordBreak │ └── 139-WordBreak.Swift ├── Greedy ├── 1029-TwoCityScheduling.swift ├── 1130-MinCostTreeFromLeaveValues.swift └── 135-Candy.swift ├── Two-Pointers ├── 283-MoveZeroes.swift ├── 26-RemoveDuplicatesFromSortedArray.swift ├── 11-ContainerWithMostWater.swift ├── 75-SortColors.swift ├── 977-SquaresOfASortedArray.swift └── 713-SubarrayProductLessThanK.swift ├── TwoSum ├── 2Sum │ ├── 1-TwoSum.swift │ └── 1099-TwoSumLessThanK.swift ├── 3Sum │ ├── 259-3SumSmallerThanK.swift │ └── 16-3SumClosest.swift └── 1865-FindingPairWithCertainSum.swift ├── SlidingWindow ├── 187-RepeatedDNASequences.swift ├── 485-ConsectiveOne.swift ├── 1146-ConescutiveChar.swift ├── 1151-minSwapsToGroupAll1.swift ├── 3-LenghtOfLongestSubstr.swift ├── 904-FruitsInTheBasket.swift ├── 1869-LongerContiguousSegOfOnesThanZeros.swift ├── 1004-MaxConsecutiveOne.swift ├── 424-LongestRepeatingCharReplacement.swift ├── 1248-NumberOfNiceSubarray.swift └── 992-SubarrayWithKDiffInt.swift ├── BinSearch ├── 162-FindPeakElement.swift ├── 852-PeakIndexInAMountainArray.swift ├── 153-FindMinInRotatedArray.swift ├── 744-FindSmallestLetterGreaterThanTarget.swift ├── 875-KokoEatingBananas.swift └── CutWoods.swift ├── MergeIntervals ├── 252-MeetingRooms.swift ├── 452-MinNumberOfArrows.swift ├── 56-MergeIntervals.swift ├── CPUMaxLoad.swift ├── MyCalendar │ └── 731-MyCalendar2.swift └── 2021-BrightestRoom.swift ├── Stack And Queues ├── SortStack.swift ├── ParanthesisProblem │ ├── 921-MinimumAddtoMakeParenthesesValid.swift │ └── 1249-Minimum RemovetoMakeValidParentheses.swift ├── 71-SimplifyPath.swift ├── 1209-RemoveAllAdjDupl.swift └── 155-MinStack.swift ├── prefix sum ├── 560-SubArraySum.swift ├── 325-MaxSizeSubArraySizeK.swift └── 523-ContinuosSubArrSum.swift ├── 1248-CountNumberofNiceSubarrays.swift ├── Heaps ├── 2104-SumOfSubarrRanges.swift └── K-Elements │ └── 1481-LeastNumberOfKDistinctElement.swift ├── ExpressionEvaluation ├── 1612-checkIfTwoExpTreeAreEqual.py ├── 150-EvaluateReversePolishNotation.swift └── 224-BasicCalculator.swift ├── Trie └── 1065-IndexPairs.swift └── Maths └── 593-ValidSquare.swift /ArraysAndStrings/796-RotateString.swift: -------------------------------------------------------------------------------- 1 | func rotateString(_ s: String, _ goal: String) -> Bool { 2 | s.count == goal.count && (s + s).contains(goal) 3 | } -------------------------------------------------------------------------------- /ProblemSolving.playground/Resources/same-countries-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/osama10/Problem-Solving-In-Swift/HEAD/ProblemSolving.playground/Resources/same-countries-1.png -------------------------------------------------------------------------------- /ProblemSolving.playground/Resources/same-countries-2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/osama10/Problem-Solving-In-Swift/HEAD/ProblemSolving.playground/Resources/same-countries-2.png -------------------------------------------------------------------------------- /ProblemSolving.playground/Resources/same-countries-3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/osama10/Problem-Solving-In-Swift/HEAD/ProblemSolving.playground/Resources/same-countries-3.png -------------------------------------------------------------------------------- /LinkList/237-DeleteNode.swift: -------------------------------------------------------------------------------- 1 | func deleteNode(_ node: ListNode?) { 2 | var node = node 3 | node?.val = node?.next?.val ?? 0 4 | node?.next = node?.next?.next 5 | } -------------------------------------------------------------------------------- /Mix/151-ReverseWordInAString.swift: -------------------------------------------------------------------------------- 1 | // 151 2 | 3 | func reverseWords(_ s: String) -> String { 4 | s.split(separator: " ") 5 | .reversed() 6 | .joined(separator: " ") 7 | } -------------------------------------------------------------------------------- /Mix/237-DeleteNodeInALinkedList.swift: -------------------------------------------------------------------------------- 1 | // 237 2 | func deleteNode(_ node: ListNode?) { 3 | var head = node 4 | head?.val = head?.next?.val ?? 0 5 | head?.next = head?.next?.next 6 | } 7 | -------------------------------------------------------------------------------- /Mix/170-LargestNumbers.swift: -------------------------------------------------------------------------------- 1 | func largestNumber(_ nums: [Int]) -> String { 2 | let number = nums.map(String.init).sorted { $0 + $1 > $1 + $0 } 3 | return Int(number.joined()) == 0 ? "0" : number.joined() 4 | } -------------------------------------------------------------------------------- /Mix/179-LargestNumber.swift: -------------------------------------------------------------------------------- 1 | // 179 2 | func largestNumber(_ nums: [Int]) -> String { 3 | let numbers = nums.map(String.init).sorted{ $0 + $1 > $1 + $0 } 4 | let result = numbers.joined() 5 | return Int(result) == 0 ? "0" : result 6 | } 7 | -------------------------------------------------------------------------------- /ProblemSolving.playground/xcuserdata/osamabashir.xcuserdatad/xcdebugger/Breakpoints_v2.xcbkptlist: -------------------------------------------------------------------------------- 1 | 2 | 6 | 7 | -------------------------------------------------------------------------------- /Graph/1557-MinNumOfVerticesToReachAllNode.swift: -------------------------------------------------------------------------------- 1 | /// 1557 2 | 3 | func findSmallestSetOfVertices(_ n: Int, _ edges: [[Int]]) -> [Int] { 4 | var candidates = Set(0.. TreeNode? { 2 | guard let root = root else { return nil } 3 | let left = invertTree(root.right) 4 | let right = invertTree(root.left) 5 | return TreeNode(root.val, left, right) 6 | } -------------------------------------------------------------------------------- /ProblemSolving.playground/playground.xcworkspace/xcuserdata/osamabashir.xcuserdatad/UserInterfaceState.xcuserstate: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/osama10/Problem-Solving-In-Swift/HEAD/ProblemSolving.playground/playground.xcworkspace/xcuserdata/osamabashir.xcuserdatad/UserInterfaceState.xcuserstate -------------------------------------------------------------------------------- /ProblemSolving.playground/playground.xcworkspace/xcuserdata/osamabinbashir.xcuserdatad/UserInterfaceState.xcuserstate: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/osama10/Problem-Solving-In-Swift/HEAD/ProblemSolving.playground/playground.xcworkspace/xcuserdata/osamabinbashir.xcuserdatad/UserInterfaceState.xcuserstate -------------------------------------------------------------------------------- /ProblemSolving.playground/Sources/LinkListNode.swift: -------------------------------------------------------------------------------- 1 | import Foundation 2 | 3 | public class ListNode { 4 | public var val: Int 5 | public var next: ListNode? 6 | public init(_ val: Int, _ next: ListNode? = nil) { 7 | self.val = val 8 | self.next = next 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /Trees/100-SameTree.swift: -------------------------------------------------------------------------------- 1 | func isSameTree(_ p: TreeNode?, _ q: TreeNode?) -> Bool { 2 | if p == nil && q == nil { return true } 3 | 4 | if p == nil || q == nil { return false } 5 | 6 | return p?.val == q?.val && isSameTree(p?.left, q?.left) && isSameTree(p?.right, q?.right) 7 | } -------------------------------------------------------------------------------- /ProblemSolving.playground/playground.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /Mix/160-IntersectionOfTwoLinkedList.swift: -------------------------------------------------------------------------------- 1 | func getIntersectionNode(_ headA: ListNode?, _ headB: ListNode?) -> ListNode? { 2 | 3 | var a = headA 4 | var b = headB 5 | 6 | while a !== b { 7 | a = a == nil ? headB : a?.next 8 | b = b == nil ? headA : b?.next 9 | } 10 | 11 | return b 12 | } -------------------------------------------------------------------------------- /OA/441-ArrangingCoins.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func arrangeCoins(_ n: Int) -> Int { 3 | var row = 0 4 | var coinsNeeded = 0 5 | 6 | while coinsNeeded <= n { 7 | row += 1 8 | coinsNeeded += row 9 | } 10 | 11 | return row - 1 12 | } 13 | } -------------------------------------------------------------------------------- /Mix/1-TwoSum.swift: -------------------------------------------------------------------------------- 1 | // 1 2 | func twoSum(_ nums: [Int], _ target: Int) -> [Int] { 3 | var dict = [Int: Int]() 4 | 5 | for (index, value) in nums.enumerated() { 6 | if let firstIndex = dict[target - value] { 7 | return [firstIndex, index] 8 | } 9 | dict[value] = index 10 | } 11 | 12 | return [] 13 | } -------------------------------------------------------------------------------- /OA/minGroups.swift: -------------------------------------------------------------------------------- 1 | func minGroups(_ nums: [Int], _ k: Int) -> Int { 2 | let nums = nums.sorted() 3 | 4 | var start = 0 5 | var count = 1 6 | 7 | for end in 0.. k { 9 | start += 1 10 | count += 1 11 | } 12 | } 13 | 14 | return count 15 | } 16 | -------------------------------------------------------------------------------- /ArraysAndStrings/136-SingleNumber.swift: -------------------------------------------------------------------------------- 1 | func singleNumber(_ nums: [Int]) -> Int { 2 | // var result = 0 3 | // 4 | // for i in 0.. Int { 13 | nums.reduce(0, ^) 14 | } -------------------------------------------------------------------------------- /Combinatorics And Backtracking/78-Subsets.swift: -------------------------------------------------------------------------------- 1 | func subsets(_ nums: [Int]) -> [[Int]] { 2 | var result = [[Int]]() 3 | result.append([]) 4 | 5 | for num in nums { 6 | for subset in result { 7 | result.append(subset + [num]) 8 | } 9 | } 10 | 11 | return result 12 | } 13 | 14 | // Time N * 2N 15 | // Space N * 2N 16 | -------------------------------------------------------------------------------- /LinkList/876-MiddleOfTheNode.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func middleNode(_ head: ListNode?) -> ListNode? { 3 | var slow = head 4 | var fast = head 5 | 6 | while fast != nil && fast?.next != nil { 7 | slow = slow?.next 8 | fast = fast?.next?.next 9 | } 10 | 11 | return slow 12 | } 13 | } -------------------------------------------------------------------------------- /Trees/112-pathsum.swift: -------------------------------------------------------------------------------- 1 | func hasPathSum(_ root: TreeNode?, _ targetSum: Int) -> Bool { 2 | guard let root = root else { return false } 3 | 4 | if root.left == nil && root.right == nil { 5 | return root.val - targetSum == 0 6 | } 7 | 8 | return hasPathSum(root.left, targetSum - root.val ) || hasPathSum(root.right, targetSum - root.val ) 9 | 10 | } -------------------------------------------------------------------------------- /ProblemSolving.playground/Pages/MergeTwoBinaryTrees.xcplaygroundpage/Contents.swift: -------------------------------------------------------------------------------- 1 | 2 | import Foundation 3 | // 617 4 | 5 | func mergeTrees(_ t1: TreeNode?, _ t2: TreeNode?) -> TreeNode? { 6 | if t1 == nil { return t2 } 7 | if t2 == nil { return t1 } 8 | return TreeNode(t1!.val + t2!.val, mergeTrees(t1?.left, t2?.left), mergeTrees(t1?.right, t2?.right)) 9 | } 10 | -------------------------------------------------------------------------------- /Stock problems/122-BestTimeToBuyStock2.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func maxProfit(_ prices: [Int]) -> Int { 3 | var profit = 0 4 | 5 | for i in 1.. [[String]] { 3 | var group = [String: [String]]() 4 | 5 | for str in strs { 6 | let key = str.sorted() 7 | group[String(key), default: [String]()].append(str) 8 | } 9 | 10 | return Array(group.values) 11 | } 12 | } -------------------------------------------------------------------------------- /ProblemSolving.playground/Pages/FindSmallestSetOfVertices.xcplaygroundpage/Contents.swift: -------------------------------------------------------------------------------- 1 | import Foundation 2 | 3 | /// 1557 4 | 5 | func findSmallestSetOfVertices(_ n: Int, _ edges: [[Int]]) -> [Int] { 6 | var candidates = Set(0.. ListNode? { 3 | var a = headA 4 | var b = headB 5 | 6 | while a !== b { 7 | a = a == nil ? headB : a?.next 8 | b = b == nil ? headA : b?.next 9 | } 10 | 11 | return a 12 | 13 | } 14 | 15 | } -------------------------------------------------------------------------------- /Stock problems/121-BestTimeToBuySellStock.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func maxProfit(_ prices: [Int]) -> Int { 3 | var leastTillNow = Int.max 4 | var maxProf = 0 5 | 6 | for price in prices { 7 | leastTillNow = min(leastTillNow, price) 8 | maxProf = max(maxProf, price - leastTillNow) 9 | } 10 | 11 | return maxProf 12 | } 13 | } -------------------------------------------------------------------------------- /Mix/49-GroupAnagrams.swift: -------------------------------------------------------------------------------- 1 | /// 49 2 | func groupAnagrams(_ strs: [String]) -> [[String]] { 3 | var dict = [String: [String]]() 4 | 5 | for index in 0.. String { 2 | let numbers = string.filter { $0.isNumber } 3 | var phoneNumber = "" 4 | 5 | for (index, num) in numbers.enumerated() { 6 | if index != 0 && (index) % 3 == 0 { 7 | phoneNumber.append("-") 8 | } 9 | 10 | phoneNumber.append(num) 11 | } 12 | 13 | return phoneNumber 14 | } -------------------------------------------------------------------------------- /DP/Fibnumber/198-HouseRobber.swift: -------------------------------------------------------------------------------- 1 | func rob(_ nums: [Int]) -> Int { 2 | guard nums.count > 1 else { return nums[0] } 3 | var dp = Array(repeating: -1, count: nums.count) 4 | 5 | dp[0] = nums[0] 6 | dp[1] = max(nums[0], nums[1]) 7 | 8 | for house in 2.. Int { 2 | if nums.count <= 3 { return nums.reduce(1, *) } 3 | let nums = nums.sorted() 4 | 5 | let last = nums.count - 1 6 | 7 | let product1 = nums[0] * nums[1] * nums[last] 8 | let product2 = nums[last - 2] * nums[last - 1] * nums[last] 9 | 10 | return max(product1, product2) 11 | } -------------------------------------------------------------------------------- /ProblemSolving.playground/Pages/maxProfit.xcplaygroundpage/Contents.swift: -------------------------------------------------------------------------------- 1 | import Foundation 2 | 3 | func maxProfit(_ prices: [Int]) -> Int { 4 | var maxProfit = 0 5 | var minBuy = prices.first! 6 | 7 | for price in prices[1...] { 8 | minBuy = min(minBuy, price) 9 | maxProfit = max(maxProfit, price - minBuy) 10 | } 11 | 12 | return maxProfit 13 | } 14 | 15 | maxProfit([7,1,5,3,6,4]) 16 | 17 | -------------------------------------------------------------------------------- /Trees/230-KthSmallestElementInBST.swift: -------------------------------------------------------------------------------- 1 | func kthSmallest(_ root: TreeNode?, _ k: Int) -> Int { 2 | var arr = [Int]() 3 | inOrder(root, &arr) 4 | return arr[k - 1] 5 | } 6 | 7 | func inOrder(_ root: TreeNode?, _ arr: inout[Int]) { 8 | guard let root = root else { return } 9 | inOrder(root.left, &arr) 10 | arr.append(root.val) 11 | inOrder(root.right, &arr) 12 | } -------------------------------------------------------------------------------- /Greedy/1029-TwoCityScheduling.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func twoCitySchedCost(_ costs: [[Int]]) -> Int { 3 | let costs = costs.sorted { ($0[0] - $0[1]) < ($1[0] - $1[1]) } 4 | let n = costs.count 5 | 6 | var cost1 = 0 7 | 8 | for i in 0.. Int { 5 | if s.isEmpty { return -1 } 6 | var frequencyTable = [String.Element: Int]() 7 | s.forEach { frequencyTable[$0] = (frequencyTable[$0] ?? 0) + 1 } 8 | for (index, char) in s.enumerated() where frequencyTable[char] == 1 { return index } 9 | return -1 10 | } 11 | -------------------------------------------------------------------------------- /Two-Pointers/283-MoveZeroes.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func moveZeroes(_ nums: inout [Int]) { 3 | var nonZeroIndex = 0 4 | var currIndex = 0 5 | 6 | while currIndex < nums.count { 7 | if nums[currIndex] != 0 { 8 | nums.swapAt(currIndex, nonZeroIndex) 9 | nonZeroIndex += 1 10 | } 11 | 12 | currIndex += 1 13 | } 14 | } 15 | } -------------------------------------------------------------------------------- /LinkList/83-RemoveDupFromSortedList.swift: -------------------------------------------------------------------------------- 1 | func deleteDuplicates(_ head: ListNode?) -> ListNode? { 2 | var curr = head 3 | 4 | while curr != nil { 5 | if curr?.val == curr?.next?.val { 6 | curr?.next = curr?.next?.next 7 | } else { 8 | curr = curr?.next 9 | } 10 | 11 | 12 | } 13 | 14 | return head 15 | } -------------------------------------------------------------------------------- /OA/1492-kthFactor.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func kthFactor(_ n: Int, _ k: Int) -> Int { 3 | if k == 1 { return 1 } 4 | var factorCount = 1 5 | 6 | for i in 2...n { 7 | if n % i == 0 { 8 | factorCount += 1 9 | if factorCount == k { 10 | return i 11 | } 12 | } 13 | } 14 | 15 | return -1 16 | } 17 | } -------------------------------------------------------------------------------- /ProblemSolving.playground/Pages/trailingZeros.xcplaygroundpage/Contents.swift: -------------------------------------------------------------------------------- 1 | /// 172 https://www.geeksforgeeks.org/count-trailing-zeroes-factorial-number/ 2 | import Foundation 3 | 4 | func trailingZeroes(_ n: Int) -> Int { 5 | if n < 5 { return 0 } 6 | var count = 0 7 | var n = n 8 | 9 | while n >= 5 { 10 | n = n / 5 11 | count += n 12 | } 13 | 14 | return count 15 | } 16 | 17 | 18 | trailingZeroes(25) 19 | -------------------------------------------------------------------------------- /Mix/665-NonDecreasingArray.swift: -------------------------------------------------------------------------------- 1 | // 665 2 | func checkPossibility(_ nums: [Int]) -> Bool { 3 | var p: Int? = nil 4 | 5 | for i in 0.. nums[i + 1] { 7 | if let _ = p { return false } 8 | else { p = i } 9 | } 10 | } 11 | 12 | guard let i = p else { return true } 13 | return i == 0 || i == nums.count - 2 || nums[i - 1] <= nums[i + 1] || nums[i] <= nums[i + 2] 14 | } 15 | -------------------------------------------------------------------------------- /TwoSum/2Sum/1-TwoSum.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func twoSum(_ nums: [Int], _ target: Int) -> [Int] { 3 | var dict = [Int: Int]() 4 | 5 | for (index, num) in nums.enumerated() { 6 | if let firstIndex = dict[target - num] { 7 | return [firstIndex, index] 8 | } 9 | 10 | dict[num] = index 11 | } 12 | 13 | 14 | return [] 15 | } 16 | } -------------------------------------------------------------------------------- /Trees/617-MergeTrees.swift: -------------------------------------------------------------------------------- 1 | func mergeTrees(_ root1: TreeNode?, _ root2: TreeNode?) -> TreeNode? { 2 | guard let root1 = root1, 3 | let root2 = root2 4 | else { return root1 == nil ? root2 : root1 } 5 | 6 | let val = root1.val + root2.val 7 | 8 | let leftChild = mergeTrees(root1.left, root2.left) 9 | let rightChild = mergeTrees(root1.right, root2.right) 10 | 11 | return TreeNode(val, leftChild, rightChild) 12 | } 13 | -------------------------------------------------------------------------------- /DP/Fibnumber/70-ClimbigStairs.swift: -------------------------------------------------------------------------------- 1 | func climbStairs(_ n: Int) -> Int { 2 | var memo = [Int:Int]() 3 | return numberOfWays(n, &memo) 4 | } 5 | 6 | func numberOfWays(_ n: Int, _ memo: inout [Int: Int]) ->Int{ 7 | if n == 1 { return 1 } 8 | else if n == 2 { return 2 } 9 | else if memo[n] != nil { 10 | return memo[n]! 11 | } 12 | 13 | memo[n] = numberOfWays(n - 1, &memo) + numberOfWays( n - 2, &memo) 14 | return memo[n]! 15 | 16 | } -------------------------------------------------------------------------------- /Mix/303-RangeSumQuery.swift: -------------------------------------------------------------------------------- 1 | class NumArray { 2 | var prefixSum = [Int]() 3 | init(_ nums: [Int]) { 4 | 5 | prefixSum.append(nums[0]) 6 | 7 | for i in 1.. Int { 14 | return left > 0 ? prefixSum[right] - prefixSum[left - 1] : prefixSum[right] 15 | } 16 | } -------------------------------------------------------------------------------- /Mix/648-ReplaceWords.swift: -------------------------------------------------------------------------------- 1 | func replaceWords(_ dictionary: [String], _ sentence: String) -> String { 2 | var splitSentence = sentence 3 | .split(separator: " ") 4 | .map(String.init) 5 | 6 | for root in dictionary { 7 | for index in 0.. [String] { 3 | if s.count < 10 { return [] } 4 | let s = Array(s) 5 | var start = 0 6 | var end = 9 7 | var dict = [String: Int]() 8 | 9 | while end < s.count { 10 | let dna = String(s[start...end]) 11 | dict[dna, default: 0] += 1 12 | end += 1 13 | start += 1 14 | } 15 | 16 | return dict.filter { $0.value > 1 }.map{ $0.key } 17 | } 18 | } -------------------------------------------------------------------------------- /Mix/350-IntersectionOfTwoArrays2.swift: -------------------------------------------------------------------------------- 1 | // 350 2 | func intersect(_ nums1: [Int], _ nums2: [Int]) -> [Int] { 3 | var intesection = [Int]() 4 | 5 | var dict = [Int:Int]() 6 | 7 | nums1.forEach { dict[$0] = (dict[$0] ?? 0) + 1 } 8 | nums2.forEach { num in 9 | if let count = dict[num], count > 0 { 10 | intesection.append(num) 11 | dict[num] = count - 1 12 | } else { dict[num] = nil } 13 | } 14 | return intesection 15 | } -------------------------------------------------------------------------------- /ProblemSolving.playground/Pages/hasCycle.xcplaygroundpage/Contents.swift: -------------------------------------------------------------------------------- 1 | //: [Previous](@previous) 2 | 3 | import Foundation 4 | 5 | // 141 6 | func hasCycle(_ head: ListNode?) -> Bool { 7 | if head == nil || head?.next == nil { return false } 8 | var fast = head, slow = head 9 | while fast != nil { 10 | fast = fast?.next?.next 11 | slow = slow?.next 12 | if fast === slow { return true } 13 | 14 | } 15 | return false 16 | } 17 | 18 | -------------------------------------------------------------------------------- /SlidingWindow/485-ConsectiveOne.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func findMaxConsecutiveOnes(_ nums: [Int]) -> Int { 3 | var start = 0 4 | var maxLength = 0 5 | 6 | for (end, value) in nums.enumerated() { 7 | 8 | if value == 0 { 9 | start = end + 1 10 | 11 | } 12 | 13 | maxLength = max(maxLength, end - start + 1) 14 | } 15 | 16 | return maxLength 17 | } 18 | } -------------------------------------------------------------------------------- /Combinatorics And Backtracking/50-Pow.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func myPow(_ x: Double, _ n: Int) -> Double { 3 | let result = calPow(x, abs(n)) 4 | return n < 0 ? 1 / result : result 5 | } 6 | 7 | func calPow(_ x: Double, _ n: Int) -> Double { 8 | 9 | if n == 0 { 10 | return 1.0 11 | } 12 | 13 | let pow = calPow(x, n / 2) 14 | 15 | return n % 2 == 0 ? pow * pow : pow * pow * x 16 | } 17 | } -------------------------------------------------------------------------------- /Combinatorics And Backtracking/339-NestedWeightedList.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func depthSum(_ nestedList: [NestedInteger]) -> Int { 3 | dfs(1, nestedList) 4 | } 5 | 6 | func dfs(_ depth: Int, _ nestedList: [NestedInteger]) -> Int { 7 | var sum = 0 8 | 9 | for value in nestedList { 10 | sum += value.isInteger() ? value.getInteger() * depth : dfs(depth + 1, value.getList()) 11 | } 12 | 13 | return sum 14 | } 15 | } -------------------------------------------------------------------------------- /BinSearch/162-FindPeakElement.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func findPeakElement(_ nums: [Int]) -> Int { 3 | var start = 0 4 | var end = nums.count - 1 5 | 6 | while start < end { 7 | let mid = start + (end - start) / 2 8 | 9 | if nums[mid] > nums[mid + 1] { 10 | end = mid 11 | } else { 12 | start = mid + 1 13 | } 14 | } 15 | 16 | return start 17 | } 18 | } -------------------------------------------------------------------------------- /Mix/20-ValidParanthesis.swift: -------------------------------------------------------------------------------- 1 | // 20 2 | func isValid(_ s: String) -> Bool { 3 | let matching : [Character: Character] = [ "]" : "[", ")" : "(", "}" : "{" ] 4 | let openBrackets = Set("([{") 5 | var stack = [Character]() 6 | 7 | for bracket in s { 8 | if openBrackets.contains(bracket) { stack.append(bracket) } 9 | else { guard let openBracket = stack.popLast(), matching[bracket] == openBracket else { return false } } 10 | } 11 | 12 | return stack.isEmpty 13 | } 14 | -------------------------------------------------------------------------------- /ProblemSolving.playground/Pages/GroupAnagrams.xcplaygroundpage/Contents.swift: -------------------------------------------------------------------------------- 1 | 2 | import Foundation 3 | /// 49 4 | func groupAnagrams(_ strs: [String]) -> [[String]] { 5 | var dict = [String: [String]]() 6 | 7 | for index in 0.. Int { 2 | 3 | var dp = Array(repeating: 1, count: nums.count) 4 | var maxSubseq = 1 5 | 6 | for end in 1.. nums[start] && dp[end] <= dp[start] { 9 | dp[end] = dp[start] + 1 10 | maxSubseq = max(maxSubseq, dp[end]) 11 | } 12 | } 13 | } 14 | 15 | return maxSubseq 16 | } 17 | -------------------------------------------------------------------------------- /LinkList/2095-DeleteTheMiddleNodeOfLL.swift: -------------------------------------------------------------------------------- 1 | func deleteMiddle(_ head: ListNode?) -> ListNode? { 2 | 3 | var fast = head 4 | var slow = head 5 | var prev: ListNode? = nil 6 | 7 | while fast != nil && fast?.next != nil { 8 | prev = slow 9 | fast = fast?.next?.next 10 | slow = slow?.next 11 | 12 | } 13 | 14 | prev?.next = slow?.next 15 | 16 | return prev == nil ? nil : head 17 | } -------------------------------------------------------------------------------- /Mix/209-MinSizeSubarraySum.swift: -------------------------------------------------------------------------------- 1 | // 209 2 | func minSubArrayLen(_ target: Int, _ nums: [Int]) -> Int { 3 | var minLength = Int.max 4 | var start = 0 5 | var currentSum = 0 6 | 7 | for i in 0..= target { 10 | minLength = min(minLength, (i - start + 1)) 11 | currentSum -= nums[start] 12 | start += 1 13 | } 14 | } 15 | 16 | return minLength == Int.max ? 0 : minLength 17 | } -------------------------------------------------------------------------------- /BinSearch/852-PeakIndexInAMountainArray.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func peakIndexInMountainArray(_ arr: [Int]) -> Int { 3 | var start = 0 4 | var end = arr.count - 1 5 | 6 | while start < end { 7 | let mid = start + (end - start) / 2 8 | 9 | if arr[mid] > arr[mid + 1] { 10 | end = mid 11 | } else { 12 | start = mid + 1 13 | } 14 | } 15 | 16 | return start 17 | } 18 | } -------------------------------------------------------------------------------- /CTCI/Graph And Tree/4.2- MinimalTree.swift: -------------------------------------------------------------------------------- 1 | func sortedArrayToBST(_ nums: [Int]) -> TreeNode? { 2 | createHeightBalancedTree(nums, 0, nums.count - 1) 3 | } 4 | 5 | func createHeightBalancedTree(_ nums: [Int], _ lo: Int, _ hi: Int) -> TreeNode? { 6 | if lo > hi { return nil } 7 | let mid = (hi + lo)/2 8 | let root = TreeNode(nums[mid]) 9 | 10 | root.left = createHeightBalancedTree(nums, lo, mid - 1) 11 | root.right = createHeightBalancedTree(nums, mid + 1 , hi) 12 | 13 | return root 14 | } -------------------------------------------------------------------------------- /Mix/238-ProductAarrayExceptSelf.swift: -------------------------------------------------------------------------------- 1 | func productExceptSelf(_ nums: [Int]) -> [Int] { 2 | 3 | var left = Array(repeating: 1, count: nums.count) 4 | var right = Array(repeating: 1, count: nums.count) 5 | 6 | var result = [Int]() 7 | 8 | for i in 1.. Int { 2 | return sumNumbers(root, 0, 0) 3 | } 4 | 5 | 6 | func sumNumbers(_ root: TreeNode?, _ currNum: Int, _ total: Int) -> Int { 7 | guard let root = root else { return total } 8 | let currNum = currNum * 10 + root.val 9 | 10 | if root.left == nil && root.right == nil { 11 | return currNum + total 12 | } 13 | 14 | return total + sumNumbers(root.left, currNum, total) + sumNumbers(root.right, currNum, total) 15 | } -------------------------------------------------------------------------------- /BinSearch/153-FindMinInRotatedArray.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func findMin(_ nums: [Int]) -> Int { 3 | var start = 0 4 | var end = nums.count - 1 5 | 6 | while start < end { 7 | let mid = start + (end - start) / 2 8 | if nums[mid] > nums[end] { 9 | start = mid + 1 10 | } else { 11 | end = mid 12 | } 13 | } 14 | 15 | return nums[start] 16 | } 17 | } -------------------------------------------------------------------------------- /LinkList/141-CycleDetection.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func hasCycle(_ head: ListNode?) -> Bool { 3 | if head == nil { return false } 4 | 5 | var fast = head 6 | var slow = head 7 | 8 | while (fast != nil && fast?.next != nil) { 9 | slow = slow?.next 10 | fast = fast?.next?.next 11 | 12 | if fast === slow { 13 | return true 14 | } 15 | } 16 | 17 | 18 | return false 19 | } 20 | 21 | } -------------------------------------------------------------------------------- /OA/1710-MaxUnitsOnATruck.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func maximumUnits(_ boxTypes: [[Int]], _ truckSize: Int) -> Int { 3 | let boxTypes = boxTypes.sorted { $0[1] > $1 [1] } 4 | var truckSize = truckSize 5 | var maxUnits = 0 6 | 7 | for boxType in boxTypes { 8 | let boxes = min(truckSize, boxType[0]) 9 | let units = boxType[1] 10 | truckSize -= boxes 11 | maxUnits += boxes * units 12 | } 13 | 14 | return maxUnits 15 | } 16 | } -------------------------------------------------------------------------------- /ProblemSolving.playground/Pages/isSymmetric.xcplaygroundpage/Contents.swift: -------------------------------------------------------------------------------- 1 | import Foundation 2 | 3 | //101 4 | 5 | func isSymmetric(_ root: TreeNode?) -> Bool { checkForSymmetry(root, root) } 6 | 7 | func checkForSymmetry(_ tree1: TreeNode?, _ tree2: TreeNode?) -> Bool { 8 | if tree1 == nil && tree2 == nil { return true } 9 | if tree1 == nil || tree2 == nil { return false } 10 | 11 | return tree1?.val == tree2?.val && checkForSymmetry(tree1?.left, tree2?.right) && checkForSymmetry(tree1?.right, tree2?.left) 12 | 13 | } 14 | -------------------------------------------------------------------------------- /MergeIntervals/252-MeetingRooms.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func canAttendMeetings(_ intervals: [[Int]]) -> Bool { 3 | guard intervals.count > 1 else { return true } 4 | let intervals = intervals.sorted { $0[0] < $1[0] } 5 | var currInterval = intervals[0] 6 | 7 | for interval in intervals[1...intervals.count-1] { 8 | if interval[0] < currInterval[1] { 9 | return false 10 | } else { 11 | currInterval = interval 12 | } 13 | } 14 | 15 | return true 16 | } 17 | 18 | } -------------------------------------------------------------------------------- /Mix/3-LongestSubstringWithoutRepeatingChar.swift: -------------------------------------------------------------------------------- 1 | // 3 2 | func lengthOfLongestSubstring(_ s: String) -> Int { 3 | if s.count < 2 { return s.count } 4 | var start = 0 5 | var indexMap = [Character: Int]() 6 | var result = Int.min 7 | 8 | for (index, char) in s.enumerated() { 9 | if let lastIndex = indexMap[char], start <= lastIndex { 10 | start = lastIndex + 1 11 | } 12 | result = max((index - start + 1), result) 13 | indexMap[char] = index 14 | } 15 | 16 | return result 17 | } -------------------------------------------------------------------------------- /ProblemSolving.playground/Sources/TreeNode.swift: -------------------------------------------------------------------------------- 1 | import Foundation 2 | 3 | public class TreeNode { 4 | public var val: Int 5 | public var left: TreeNode? 6 | public var right: TreeNode? 7 | public init() { self.val = 0; self.left = nil; self.right = nil; } 8 | public init(_ val: Int) { self.val = val; self.left = nil; self.right = nil; } 9 | public init(_ val: Int, _ left: TreeNode?, _ right: TreeNode?) { 10 | self.val = val 11 | self.left = left 12 | self.right = right 13 | } 14 | } 15 | 16 | -------------------------------------------------------------------------------- /ProblemSolving.playground/xcuserdata/osamabashir.xcuserdatad/xcschemes/xcschememanagement.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | SchemeUserState 6 | 7 | ProblemSolving (Playground).xcscheme 8 | 9 | isShown 10 | 11 | orderHint 12 | 0 13 | 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /ProblemSolving.playground/xcuserdata/osamabinbashir.xcuserdatad/xcschemes/xcschememanagement.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | SchemeUserState 6 | 7 | ProblemSolving (Playground).xcscheme 8 | 9 | isShown 10 | 11 | orderHint 12 | 0 13 | 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /ProblemSolving.playground/Pages/missingnumber.xcplaygroundpage/Contents.swift: -------------------------------------------------------------------------------- 1 | import Foundation 2 | 3 | func missingNumber(_ nums: [Int]) -> Int { 4 | let givenSum = nums.reduce(0, +) 5 | let actualSum = (0...nums.count).reduce(0,+) 6 | return actualSum - givenSum 7 | } 8 | 9 | //func missingNumber(_ nums: [Int]) -> Int { 10 | // 11 | // var result = nums.count 12 | // for i in 0.. [Int] { 4 | var stack = stack 5 | var sortedStack = [Int]() 6 | 7 | while !stack.isEmpty { 8 | let num = stack.removeLast() 9 | while !sortedStack.isEmpty && sortedStack.last! > num { 10 | let sortedNum = sortedStack.removeLast() 11 | stack.append(sortedNum) 12 | } 13 | sortedStack.append(num) 14 | } 15 | 16 | return sortedStack 17 | } -------------------------------------------------------------------------------- /prefix sum/560-SubArraySum.swift: -------------------------------------------------------------------------------- 1 | func subarraySum(_ nums: [Int], _ k: Int) -> Int { 2 | var dict = [Int: Int]() 3 | var count = 0 4 | var currPrefixSum = 0 5 | 6 | nums.forEach { num in 7 | currPrefixSum += num 8 | if currPrefixSum == k { 9 | count += 1 10 | } 11 | 12 | count += dict[currPrefixSum - k , default: 0] 13 | dict[currPrefixSum] = dict[currPrefixSum, default: 0] + 1 14 | } 15 | 16 | return count 17 | } -------------------------------------------------------------------------------- /Two-Pointers/26-RemoveDuplicatesFromSortedArray.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func removeDuplicates(_ nums: inout [Int]) -> Int { 3 | guard !nums.isEmpty else { return 0 } 4 | var nextNonDuplicateIndex = 1 5 | 6 | for (index, value) in nums[1.. Bool { 9 | var val = x 10 | while val%3 == 0 { val /= 3 } 11 | return val == 1 12 | } 13 | 14 | isPowerOfThree(45) 15 | isPowerOfThree(27) 16 | isPowerOfThree(1) 17 | isPowerOfThree(2) 18 | isPowerOfThree(0) 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | -------------------------------------------------------------------------------- /Mix/189-RotateArray.swift: -------------------------------------------------------------------------------- 1 | // 189 2 | func rotate(_ nums: inout [Int], _ k: Int) { 3 | if k == 0 { return } 4 | let k = k%nums.count 5 | reverse(&nums, 0, nums.count - 1) 6 | reverse(&nums, 0, k - 1) 7 | reverse(&nums, k, nums.count - 1) 8 | } 9 | 10 | 11 | func reverse(_ nums: inout [Int], _ start: Int, _ end: Int) { 12 | var start = start 13 | var end = end 14 | 15 | while start < end { 16 | let temp = nums[start] 17 | nums[start] = nums[end] 18 | nums[end] = temp 19 | start += 1 20 | end -= 1 21 | } 22 | } -------------------------------------------------------------------------------- /CTCI/DPAndRecursion/8.3-MagicIndex.swift: -------------------------------------------------------------------------------- 1 | func magicIndex(_ nums: [Int]) -> Int { 2 | var left = 0 3 | var right = nums.count - 1 4 | 5 | while left <= right { 6 | let mid = (left + right) / 2 7 | 8 | if nums[mid] == mid { 9 | return mid 10 | } else if nums[mid] > mid { 11 | right = min(mid - 1, nums[mid]) 12 | } else { 13 | left = max(mid + 1, nums[mid]) 14 | } 15 | } 16 | 17 | return -1 18 | } 19 | 20 | 21 | magicIndex([0, 2, 3, 4, 5]) 22 | magicIndex([2, 2, 2, 2, 2]) 23 | -------------------------------------------------------------------------------- /ProblemSolving.playground/Pages/CheckIfAll1KDistApart.xcplaygroundpage/Contents.swift: -------------------------------------------------------------------------------- 1 | 2 | import Foundation 3 | 4 | /// 1437 5 | func kLengthApart(_ nums: [Int], _ k: Int) -> Bool { 6 | 7 | var lastIndex = -1 8 | 9 | for i in 0.. Int { 3 | var left = 0 4 | var right = height.count - 1 5 | var maxArea = 0 6 | 7 | while left < right { 8 | let area = min(height[left], height[right]) * (right - left) 9 | maxArea = max(area, maxArea) 10 | if height[left] < height[right] { 11 | left += 1 12 | } else { 13 | right -= 1 14 | } 15 | } 16 | 17 | return maxArea 18 | } 19 | } -------------------------------------------------------------------------------- /Graph/997-FindJudge.swift: -------------------------------------------------------------------------------- 1 | //997 2 | 3 | func findJudge(_ N: Int, _ trust: [[Int]]) -> Int { 4 | 5 | var candidates = (1...N).reduce(into: Set()) { (set, val) in set.insert(val) } 6 | var trustCount = [Int: Int]() 7 | 8 | trust.forEach { (dependency) in 9 | candidates.remove(dependency[0]) 10 | trustCount[dependency[1], default: 0] += 1 11 | } 12 | 13 | if candidates.count != 1 { return -1 } 14 | for candidate in candidates { 15 | if trustCount[candidate, default: 0] == N - 1 { return candidate } 16 | } 17 | 18 | return -1 19 | 20 | } -------------------------------------------------------------------------------- /BinSearch/744-FindSmallestLetterGreaterThanTarget.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func nextGreatestLetter(_ letters: [Character], _ target: Character) -> Character { 3 | var left = 0 4 | var right = letters.count - 1 5 | 6 | 7 | while left <= right { 8 | let mid = (left + right) / 2 9 | 10 | if letters[mid] > target { 11 | right = mid - 1 12 | } else { 13 | left = mid + 1 14 | } 15 | } 16 | 17 | return letters[left % letters.count] 18 | } 19 | } -------------------------------------------------------------------------------- /DP/LongestCommonSubsequence/FindMaxSumSubSeq.swift: -------------------------------------------------------------------------------- 1 | func findMSIS(_ nums: [Int]) -> Int { 2 | var dp = Array(repeating: 0, count: nums.count) 3 | dp[0] = nums[0] 4 | 5 | for i in 1.. nums[j] && dp[i] < dp[j] + nums[i] { 10 | dp[i] = dp[j] + nums[i] 11 | } 12 | } 13 | } 14 | 15 | return dp.max() ?? 0 16 | } 17 | 18 | findMSIS([4,1,2,6,10,1,12]) 19 | findMSIS([-4,10,3,7,15]) 20 | findMSIS([1,3,8,4,14,6,14,1,9,4,13,3,11,17,29]) 21 | -------------------------------------------------------------------------------- /Mix/162-FindPeakElement.swift: -------------------------------------------------------------------------------- 1 | // 162 2 | func findPeakElement(_ nums: [Int]) -> Int { 3 | guard nums.count > 1 else { return 0 } 4 | return peakFinder(nums: nums, hi: nums.count - 1, lo: 0) 5 | } 6 | 7 | func peakFinder(nums: [Int], hi: Int, lo: Int) -> Int { 8 | let mid = (lo + (hi - lo)/2) 9 | if (mid == 0 || nums[mid - 1] <= nums[mid]) && (mid == (nums.count - 1) || nums[mid + 1] <= nums[mid] ){ return mid } 10 | return (mid > 0 && nums[mid - 1] >= nums[mid]) ? 11 | peakFinder(nums: nums, hi: mid - 1, lo: lo) : 12 | peakFinder(nums: nums, hi: hi, lo: mid + 1) 13 | } -------------------------------------------------------------------------------- /ProblemSolving.playground/Pages/inorderTraversal.xcplaygroundpage/Contents.swift: -------------------------------------------------------------------------------- 1 | //: [Previous](@previous) 2 | 3 | import Foundation 4 | 5 | var str = "Hello, playground" 6 | 7 | func inorderTraversal(_ root: TreeNode?) -> [Int] { 8 | if root == nil { return [] } 9 | var path = [Int]() 10 | traverseInorder(root, &path) 11 | return path 12 | } 13 | 14 | func traverseInorder(_ node: TreeNode?, _ path: inout[Int]) { 15 | if node == nil { return } 16 | traverseInorder(node?.left, &path) 17 | path.append(node!.val) 18 | traverseInorder(node?.right, &path) 19 | 20 | } 21 | -------------------------------------------------------------------------------- /ProblemSolving.playground/Pages/lengthOfLongestSubstring.xcplaygroundpage/Contents.swift: -------------------------------------------------------------------------------- 1 | import Foundation 2 | 3 | /// 3 4 | 5 | func lengthOfLongestSubstring(_ s: String) -> Int { 6 | if s.count < 2 { return s.count } 7 | var dict = [Character: Int]() 8 | var start = 0 9 | var maxSize = 0 10 | 11 | for (index, char) in s.enumerated() { 12 | if let val = dict[char], val >= start { start = val + 1 } 13 | dict[char] = index 14 | maxSize = max(maxSize, (index - start + 1)) 15 | } 16 | return maxSize 17 | } 18 | 19 | lengthOfLongestSubstring("dvdf") 20 | -------------------------------------------------------------------------------- /SlidingWindow/1146-ConescutiveChar.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func maxPower(_ s: String) -> Int { 3 | var start = 0 4 | var set = Set() 5 | var maxLen = 0 6 | let s = Array(s) 7 | 8 | for (end, char) in s.enumerated() { 9 | set.insert(char) 10 | 11 | if set.count > 1 { 12 | set.remove(s[start]) 13 | start = end 14 | } 15 | 16 | maxLen = max(maxLen, end - start + 1) 17 | } 18 | 19 | return maxLen 20 | } 21 | } -------------------------------------------------------------------------------- /DP/Fibnumber/NumberFactors.swift: -------------------------------------------------------------------------------- 1 | /* 2 | Given a number ‘n’, implement a method to count how many possible ways there are to express ‘n’ as the sum of 1, 3, or 4. 3 | */ 4 | func countWays(_ n: Int) -> Int { 5 | var dp = Array(repeating: 0, count: n + 1) 6 | if n == 0 { return 0 } 7 | if n < 3 { return 1 } 8 | 9 | dp[0] = 1 10 | dp[1] = 1 11 | dp[2] = 1 12 | dp[3] = 2 13 | 14 | for num in 4...n { 15 | dp[num] = dp[num - 1] + dp[num - 3] + dp[num - 4] 16 | } 17 | 18 | return dp[n] 19 | } 20 | 21 | countWays(4) 22 | countWays(5) 23 | countWays(6) 24 | -------------------------------------------------------------------------------- /Trees/543-DiameterOfTree.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | var maxDiameter = Int.min 3 | 4 | func diameterOfBinaryTree(_ root: TreeNode?) -> Int { 5 | guard let root = root else { return 0 } 6 | findDiameter(root) 7 | return maxDiameter - 1 8 | } 9 | 10 | func findDiameter(_ root: TreeNode?) -> Int { 11 | guard let root = root else { return 0 } 12 | let left = findDiameter(root.left) 13 | let right = findDiameter(root.right) 14 | maxDiameter = max(maxDiameter, left + right + 1) 15 | return max(left, right) + 1 16 | } 17 | } -------------------------------------------------------------------------------- /ArraysAndStrings/392-IsSequence.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func isSubsequence(_ s: String, _ t: String) -> Bool { 3 | let sequence = Array(s) 4 | let target = Array(t) 5 | 6 | var seqPtr = 0 7 | var targetPtr = 0 8 | 9 | 10 | while seqPtr < sequence.count && targetPtr < target.count { 11 | if sequence[seqPtr] == target[targetPtr] { 12 | seqPtr += 1 13 | } 14 | 15 | 16 | targetPtr += 1 17 | } 18 | 19 | return seqPtr == sequence.count 20 | } 21 | } -------------------------------------------------------------------------------- /DP/Matrix/62-UniquePaths.swift: -------------------------------------------------------------------------------- 1 | func uniquePaths(_ m: Int, _ n: Int) -> Int { 2 | var memo = Array(repeating: Array(repeating: -1, count: n), count: m) 3 | return calUniquePaths(m - 1, n - 1, &memo) 4 | } 5 | 6 | func calUniquePaths(_ m: Int, _ n : Int, _ memo: inout [[Int]]) -> Int { 7 | if m == 0 && n == 0 { 8 | return 1 9 | } 10 | 11 | if m < 0 || n < 0 { return 0 } 12 | 13 | if memo[m][n] == -1 { 14 | memo[m][n] = calUniquePaths(m, n - 1, &memo) + calUniquePaths(m - 1, n, &memo) 15 | } 16 | 17 | return memo[m][n] 18 | } 19 | 20 | uniquePaths(3, 2) 21 | -------------------------------------------------------------------------------- /Stack And Queues/ParanthesisProblem/921-MinimumAddtoMakeParenthesesValid.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func minAddToMakeValid(_ s: String) -> Int { 3 | var count = 0 4 | var stack = [Character]() 5 | 6 | for char in s { 7 | if char == "(" { 8 | stack.append("(") 9 | } else { 10 | if !stack.isEmpty { 11 | stack.removeLast() 12 | } else { 13 | count += 1 14 | } 15 | } 16 | } 17 | 18 | return count + stack.count 19 | } 20 | } -------------------------------------------------------------------------------- /ArraysAndStrings/1864-MaxElementAfterDecrementing.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func maximumElementAfterDecrementingAndRearranging(_ arr: [Int]) -> Int { 3 | let arr = arr.sorted() 4 | var result = [Int]() 5 | 6 | for i in 0.. 1 ? result[i - 1] + 1 : arr[i] 12 | result.append(val) 13 | } 14 | } 15 | 16 | return result.max() ?? 1 17 | } 18 | } -------------------------------------------------------------------------------- /ArraysAndStrings/448-FindAllDisappearedNumbers.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func findDisappearedNumbers(_ nums: [Int]) -> [Int] { 3 | var result = [Int]() 4 | var nums = nums 5 | for num in nums { 6 | let newIndex = abs(num) - 1 7 | 8 | if nums[newIndex] > 0 { 9 | nums[newIndex] = num * -1 10 | } 11 | } 12 | 13 | for i in 1...nums.count { 14 | if nums[i - 1] > 0 { 15 | result.append(i) 16 | } 17 | } 18 | 19 | return result 20 | } 21 | 22 | } -------------------------------------------------------------------------------- /DP/Fibnumber/1137-tribnum.swift: -------------------------------------------------------------------------------- 1 | /* 2 | The Tribonacci sequence Tn is defined as follows: 3 | 4 | T0 = 0, T1 = 1, T2 = 1, and Tn+3 = Tn + Tn+1 + Tn+2 for n >= 0. 5 | 6 | Given n, return the value of Tn. 7 | */ 8 | 9 | func tribonacci(_ n: Int) -> Int { 10 | guard n > 2 else { return n == 0 ? 0 : 1 } 11 | var tribNumber = Array(repeating: 0, count: n + 1) 12 | tribNumber[1] = 1 13 | tribNumber[2] = 1 14 | 15 | for state in 3...n { 16 | tribNumber[state] = tribNumber[state - 1] + tribNumber[state - 2] + tribNumber[state - 3] 17 | } 18 | 19 | return tribNumber[n] 20 | } 21 | -------------------------------------------------------------------------------- /1248-CountNumberofNiceSubarrays.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func numberOfSubarrays(_ nums: [Int], _ k: Int) -> Int { 3 | var count = 0 4 | var prefixCount = Array(repeating: 0, count: nums.count) 5 | var oddCount = 0 6 | 7 | for num in nums { 8 | prefixCount[oddCount] += 1 9 | 10 | if num % 2 == 1 { 11 | oddCount += 1 12 | } 13 | 14 | if oddCount >= k { 15 | count += prefixCount[oddCount - k] 16 | } 17 | } 18 | 19 | return count 20 | } 21 | } -------------------------------------------------------------------------------- /Greedy/1130-MinCostTreeFromLeaveValues.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func mctFromLeafValues(_ arr: [Int]) -> Int { 3 | 4 | var arr = [Int.max] + arr + [Int.max] 5 | var ans = 0 6 | 7 | while arr.count > 3 { 8 | let minVal = arr.min()! 9 | let index: Int = arr.firstIndex(of: minVal)! 10 | let product1 = arr[index - 1] == Int.max ? Int.max : arr[index - 1] * minVal 11 | let product2 = arr[index + 1] == Int.max ? Int.max : arr[index + 1] * minVal 12 | ans += min(product1, product2) 13 | arr.remove(at: index) 14 | } 15 | 16 | return ans 17 | } 18 | 19 | } -------------------------------------------------------------------------------- /LinkList/19-RemoveNthNodeFromList.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func removeNthFromEnd(_ head: ListNode?, _ n: Int) -> ListNode? { 3 | var prev = head 4 | 5 | var fast = head 6 | var slow = head 7 | 8 | for _ in 1...n { 9 | fast = fast?.next 10 | } 11 | 12 | if fast == nil { return head?.next } 13 | 14 | while fast?.next != nil { 15 | slow = slow?.next 16 | fast = fast?.next 17 | } 18 | 19 | slow?.next = slow?.next?.next 20 | 21 | return head 22 | } 23 | } -------------------------------------------------------------------------------- /OA/118-PascalsTri.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func generate(_ numRows: Int) -> [[Int]] { 3 | if numRows == 1 { return [[1]] } 4 | 5 | var triangle = [[1]] 6 | 7 | for row in 2...numRows { 8 | let prevRow = triangle.last! 9 | var newRow = [1] 10 | 11 | for j in 1.. Int { 5 | var ans = 0 6 | var arr = [Int]() 7 | 8 | for row in 0.. Int { 3 | var freqTable = Array(repeating: 0, count: 60) 4 | var count = 0 5 | 6 | for duration in time { 7 | let remainder = duration % 60 8 | 9 | if remainder == 0 { 10 | count += freqTable[0] 11 | } else { 12 | count += freqTable[60 - remainder] 13 | } 14 | 15 | freqTable[remainder] += 1 16 | } 17 | 18 | return count 19 | } 20 | } 21 | 22 | -------------------------------------------------------------------------------- /Mix/844-BackspaceStringCompare.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func backspaceCompare(_ s: String, _ t: String) -> Bool { 3 | finalString(s) == finalString(t) 4 | } 5 | 6 | func finalString(_ string: String) -> String { 7 | guard !string.isEmpty else { return "" } 8 | var stack = [Character]() 9 | 10 | for char in string { 11 | if char != "#" { 12 | stack.append(char) 13 | } else { 14 | stack.popLast() 15 | } 16 | } 17 | 18 | return stack.isEmpty ? "" : String(String(stack)) 19 | } 20 | } -------------------------------------------------------------------------------- /Heaps/2104-SumOfSubarrRanges.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func subArrayRanges(_ nums: [Int]) -> Int { 3 | var ans = 0 4 | 5 | for (idx, num1) in nums.enumerated() { 6 | var maxNum = Int.min 7 | var minNum = Int.max 8 | 9 | minNum = min(num1, minNum) 10 | maxNum = max(num1, maxNum) 11 | 12 | for num2 in nums[idx+1.. Int { 3 | var sortedfreqTable = arr 4 | .reduce(into: [Int: Int]()) { $0[$1, default: 0] += 1} 5 | .sorted { $0.value < $1.value } 6 | 7 | var k = k 8 | 9 | for (index,value) in sortedfreqTable.enumerated() { 10 | k -= value.value 11 | sortedfreqTable[index] = k >= 0 ? (value.key, 0) : (value.key, abs(k)) 12 | if k <= 0 { break } 13 | } 14 | 15 | return sortedfreqTable.filter { $0.value > 0 }.count 16 | 17 | } 18 | } 19 | 20 | -------------------------------------------------------------------------------- /OA/1331-RankTransformOfAnArray.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func arrayRankTransform(_ arr: [Int]) -> [Int] { 3 | let sortedArray = arr.enumerated() 4 | .reduce(into: [Int: [Int]]()) { 5 | $0[$01.element, default: [Int]()].append($1.offset) 6 | }.sorted { $0.key < $1.key } 7 | 8 | var result = Array(repeating: 1, count: arr.count) 9 | var rank = 1 10 | 11 | 12 | for val in sortedArray { 13 | for index in val.value { 14 | result[index] = rank 15 | } 16 | rank += 1 17 | } 18 | 19 | return result 20 | } 21 | } -------------------------------------------------------------------------------- /CTCI/Search and Sort/88-MergeSortedArray.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func merge(_ nums1: inout [Int], _ m: Int, _ nums2: [Int], _ n: Int) { 3 | var index1 = m - 1 4 | var index2 = n - 1 5 | var mergedIndex = m + n - 1 6 | 7 | while index2 >= 0 { 8 | if index1 >= 0 && nums1[index1] >= nums2[index2] { 9 | nums1[mergedIndex] = nums1[index1] 10 | index1 -= 1 11 | } else { 12 | nums1[mergedIndex] = nums2[index2] 13 | index2 -= 1 14 | } 15 | 16 | mergedIndex -= 1 17 | } 18 | } 19 | } -------------------------------------------------------------------------------- /ExpressionEvaluation/1612-checkIfTwoExpTreeAreEqual.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def checkEquivalence(self, root1: 'Node', root2: 'Node') -> bool: 3 | def find_vals(root): 4 | vals = defaultdict(lambda: 0) 5 | 6 | def pre_order(root): 7 | if root is None: 8 | return 9 | if root.val != "+": 10 | vals[root.val] += 1 11 | pre_order(root.left) 12 | pre_order(root.right) 13 | 14 | pre_order(root) 15 | return vals 16 | 17 | return find_vals(root1) == find_vals(root2) 18 | -------------------------------------------------------------------------------- /Graph/797-AllPathFromSourceToTarget.swift: -------------------------------------------------------------------------------- 1 | // 797 2 | 3 | // O(N* 2N) 4 | func allPathsSourceTarget(_ graph: [[Int]]) -> [[Int]] { 5 | var allPaths = [[Int]]() 6 | var paths = [Int]() 7 | dfs(graph, &paths, &allPaths, 0) 8 | return allPaths 9 | } 10 | 11 | func dfs(_ graph:[[Int]], _ paths: inout[Int], _ allPaths : inout[[Int]], _ node: Int) { 12 | paths.append(node) 13 | 14 | if node == graph.count - 1 { 15 | allPaths.append(paths) 16 | } else { 17 | for neighbor in graph[node] { 18 | dfs(graph, &paths, &allPaths, neighbor) 19 | } 20 | } 21 | 22 | paths.removeLast() 23 | } 24 | -------------------------------------------------------------------------------- /Graph/841-KeysAndRoom.swift: -------------------------------------------------------------------------------- 1 | func canVisitAllRooms(_ rooms: [[Int]]) -> Bool { 2 | var graph = Array(repeating: [Int](), count: rooms.count) 3 | var visited = Set() 4 | for (room, keys) in rooms.enumerated() { 5 | graph[room] = keys 6 | } 7 | 8 | isConnected(graph, 0, &visited) 9 | return visited.count == rooms.count 10 | } 11 | 12 | func isConnected(_ graph: [[Int]], _ current: Int, _ visited: inout Set) { 13 | visited.insert(current) 14 | 15 | for node in graph[current] { 16 | if !visited.contains(node) { 17 | isConnected(graph, node, &visited) 18 | } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /Mix/12-IntToRoman.swift: -------------------------------------------------------------------------------- 1 | /// 12 2 | 3 | func intToRoman( _ number: Int) -> String { 4 | let numbers = [1, 4, 5, 9, 10, 40, 50, 90, 5 | 100, 400, 500, 900, 1000] 6 | let symbols = ["I", "IV", "V", "IX", "X", "XL", 7 | "L", "XC", "C", "CD", "D", "CM", "M"] 8 | 9 | var index = numbers.count - 1 10 | var num = number 11 | var result = "" 12 | 13 | while index >= 0 && num > 0 { 14 | let freq = num / numbers[index] 15 | num %= numbers[index] 16 | result += String(repeating: symbols[index], count: freq) 17 | index -= 1 18 | } 19 | 20 | return result 21 | } 22 | -------------------------------------------------------------------------------- /Mix/1333-FilterRestaurantsByVeganFreindlyPriceAndDistance.swift: -------------------------------------------------------------------------------- 1 | func filterRestaurants(_ restaurants: [[Int]], _ veganFriendly: Int, _ maxPrice: Int, _ maxDistance: Int) -> [Int] { 2 | var sortedRestaurants = [(id: Int, rating: Int)]() 3 | restaurants.forEach { restaurant in 4 | if (veganFriendly == 0 || veganFriendly == restaurant[2]) && restaurant[3] <= maxPrice && restaurant[4] <= maxDistance { 5 | sortedRestaurants.append((restaurant[0], restaurant[1])) 6 | } 7 | } 8 | sortedRestaurants.sort{ $0.rating > $1.rating || ($0.rating == $1.rating && $0.id > $1.id) } 9 | return sortedRestaurants.map { $0.id } 10 | } -------------------------------------------------------------------------------- /Two-Pointers/75-SortColors.swift: -------------------------------------------------------------------------------- 1 | func sortColors(_ nums: inout [Int]) { 2 | var zeroIndex = 0 3 | var currentIndex = 0 4 | var twoIndex = nums.count - 1 5 | 6 | while currentIndex <= twoIndex { 7 | if nums[currentIndex] == 0 { 8 | nums.swapAt(currentIndex,zeroIndex) 9 | currentIndex += 1 10 | zeroIndex += 1 11 | } else if nums[currentIndex] == 2 { 12 | nums.swapAt(currentIndex,twoIndex) 13 | twoIndex -= 1 14 | } else { 15 | currentIndex += 1 16 | 17 | } 18 | } 19 | } -------------------------------------------------------------------------------- /Mix/75-SortColors.swift: -------------------------------------------------------------------------------- 1 | // 75 2 | func sortColors(_ nums: inout [Int]) { 3 | var zeroIndex = 0 4 | var currentIndex = 0 5 | var twoIndex = nums.count - 1 6 | 7 | while currentIndex <= twoIndex { 8 | if nums[currentIndex] == 0 { 9 | nums.swapAt(currentIndex,zeroIndex) 10 | currentIndex += 1 11 | zeroIndex += 1 12 | } else if nums[currentIndex] == 2 { 13 | nums.swapAt(currentIndex,twoIndex) 14 | twoIndex -= 1 15 | } else { 16 | currentIndex += 1 17 | 18 | } 19 | } 20 | } -------------------------------------------------------------------------------- /OA/MinNum.swift: -------------------------------------------------------------------------------- 1 | func minNum(_ num: Int) -> Int { 2 | var numArr = [Int]() 3 | var num = num 4 | 5 | while num != 0 { 6 | numArr.append( num % 10 ) 7 | num /= 10 8 | } 9 | 10 | var num1 = 0 11 | var num2 = 0 12 | 13 | numArr.sort() 14 | 15 | for i in stride(from: 0, to: numArr.count, by: 2) { 16 | num1 = num1 * 10 + numArr[i] 17 | } 18 | 19 | for i in stride(from: 1, to: numArr.count, by: 2) { 20 | num2 = num2 * 10 + numArr[i] 21 | } 22 | 23 | return num1 + num2 24 | } 25 | 26 | 27 | minNum(4523) // 59 28 | minNum(98435) // 407 29 | minNum(713451) // 282 30 | -------------------------------------------------------------------------------- /SlidingWindow/1151-minSwapsToGroupAll1.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func minSwaps(_ data: [Int]) -> Int { 3 | let totalOnes = data.reduce(0, +) 4 | 5 | var currWindowOneCount = 0 6 | var start = 0 7 | var end = 0 8 | var swaps = Int.max 9 | 10 | while end < data.count { 11 | 12 | currWindowOneCount += data[end] 13 | end += 1 14 | 15 | if end - start > totalOnes { 16 | currWindowOneCount -= data[start] 17 | start += 1 18 | } 19 | 20 | swaps = min(swaps, totalOnes - currWindowOneCount) 21 | } 22 | 23 | return swaps 24 | } 25 | 26 | } -------------------------------------------------------------------------------- /MergeIntervals/452-MinNumberOfArrows.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func findMinArrowShots(_ points: [[Int]]) -> Int { 3 | /* 4 | [1, 6] 5 | [2, 8] 6 | [7, 12] 7 | [10, 12] 8 | */ 9 | guard points.count > 1 else { return 1 } 10 | let points = points.sorted{ $0[1] < $1[1] } 11 | 12 | var arrows = 1 13 | var firstEnd = points[0][1] 14 | 15 | for point in points { 16 | if firstEnd < point[0] { 17 | arrows += 1 18 | firstEnd = point[1] 19 | } 20 | } 21 | 22 | return arrows 23 | } 24 | } -------------------------------------------------------------------------------- /OA/696-countBinarySubstring.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func countBinarySubstrings(_ s: String) -> Int { 3 | var result = 0 4 | let sArr = s.map {Character(String($0))} 5 | var groups:[Int] = [] 6 | var i = 0 7 | while i < sArr.count { 8 | var j = i+1 9 | let val = sArr[i] 10 | while j < sArr.count && sArr[j] == val { 11 | j += 1 12 | } 13 | groups.append(j-i) 14 | i = j 15 | } 16 | 17 | for i in 0.. Int { 3 | var maxCount = 0 4 | var numSet = Set(nums) 5 | 6 | for num in nums { 7 | if !numSet.contains(num - 1) { 8 | var count = 1 9 | var next = num + 1 10 | 11 | while numSet.contains(next) { 12 | next = next + 1 13 | count += 1 14 | } 15 | 16 | maxCount = max(maxCount, count) 17 | } 18 | } 19 | 20 | return maxCount 21 | } 22 | } -------------------------------------------------------------------------------- /ArraysAndStrings/383-RansomeNote.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func canConstruct(_ ransomNote: String, _ magazine: String) -> Bool { 3 | var ransomLetterCount = ransomNote.reduce(into: [Character: Int]()) { $0[$1, default: 0] += 1 } 4 | var magazineLetterCount = magazine.reduce(into: [Character: Int]()) { $0[$1, default: 0] += 1 } 5 | 6 | for (key, value) in ransomLetterCount { 7 | if let parentValue = magazineLetterCount[key]{ 8 | if parentValue < value { return false } 9 | } else { 10 | return false 11 | } 12 | } 13 | 14 | return true 15 | } 16 | 17 | 18 | } -------------------------------------------------------------------------------- /TwoSum/2Sum/1099-TwoSumLessThanK.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func twoSumLessThanK(_ nums: [Int], _ k: Int) -> Int { 3 | guard nums.count > 1 else { return -1 } 4 | 5 | let nums = nums.sorted() 6 | var left = 0 7 | var right = nums.count - 1 8 | var maxSum = Int.min 9 | 10 | while left < right { 11 | let sum = nums[left] + nums[right] 12 | if sum < k { 13 | maxSum = max(maxSum, sum) 14 | left += 1 15 | } else { 16 | right -= 1 17 | } 18 | } 19 | 20 | return maxSum == Int.min ? -1 : maxSum 21 | } 22 | } -------------------------------------------------------------------------------- /ArraysAndStrings/1656-OrderedStrea.swift: -------------------------------------------------------------------------------- 1 | 2 | class OrderedStream { 3 | var stream : [String] 4 | var nextId = 0 5 | 6 | init(_ n: Int) { 7 | stream = Array(repeating: "", count: n) 8 | } 9 | 10 | func insert(_ idKey: Int, _ value: String) -> [String] { 11 | stream[idKey - 1] = value 12 | 13 | var result = [String]() 14 | let start = nextId 15 | 16 | for i in start.. Int { 2 | var dp = Array(repeating: Int.max, count: n + 1) 3 | let maxPossibileSquareIndex = Int(sqrt(Double(n))) + 1 4 | let possibileSquares = (0.. Int { 5 | calWays(n, k) 6 | } 7 | 8 | func calWays(_ n: Int, _ colors: Int) -> Int { 9 | 10 | if n == 1 { 11 | return colors 12 | } 13 | 14 | if n == 2 { 15 | return colors * colors 16 | } 17 | 18 | 19 | if let totalWays = memo[n] { 20 | return totalWays 21 | } 22 | 23 | memo[n] = (colors - 1) * (calWays(n - 1, colors) + calWays(n - 2, colors) ) 24 | 25 | return memo[n]! 26 | } 27 | } -------------------------------------------------------------------------------- /DP/Fibnumber/509-fibnum.swift: -------------------------------------------------------------------------------- 1 | /* 2 | The Fibonacci numbers, commonly denoted F(n) form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0 and 1. That is, 3 | 4 | F(0) = 0, F(1) = 1 5 | F(n) = F(n - 1) + F(n - 2), for n > 1. 6 | 7 | Given n, calculate F(n). 8 | */ 9 | 10 | func fib(_ n: Int) -> Int { 11 | guard n > 1 else { return n } 12 | var fibNumber = Array(repeating: 0, count: n + 1) 13 | fibNumber[1] = 1 14 | 15 | for state in 2...n { 16 | fibNumber[state] = fibNumber[state - 1] + fibNumber[state - 2] 17 | } 18 | 19 | return fibNumber[n] 20 | 21 | } 22 | 23 | fib(4) -------------------------------------------------------------------------------- /Mix/1099-TwoSumLessThanK.swift: -------------------------------------------------------------------------------- 1 | 2 | /// 1099 . Two Sum Less Than K (https://leetcode.com/problems/two-sum-less-than-k/): Given an array A of integers and integer K, return the maximum S such that there exists i < j with A[i] + A[j] = S and S < K. If no i, j exist satisfying this equation, return -1. 3 | 4 | func twoSumLessThanK(_ arr: [Int], _ k: Int) -> Int { 5 | var lo = 0 6 | var hi = arr.count - 1 7 | var result = Int.min 8 | 9 | while lo < hi { 10 | let sum = arr[lo] + arr[hi] 11 | if sum < k { 12 | result = max(sum, result) 13 | lo += 1 14 | } 15 | else { hi -= 1 } 16 | } 17 | 18 | return result 19 | } 20 | -------------------------------------------------------------------------------- /SlidingWindow/3-LenghtOfLongestSubstr.swift: -------------------------------------------------------------------------------- 1 | func lengthOfLongestSubstring(_ s: String) -> Int { 2 | guard s.count > 1 else { return s.count } 3 | 4 | var str = Array(s) 5 | var start = 0 6 | var end = 0 7 | var seen = [Character: Int]() 8 | var maxLength = Int.min 9 | 10 | for (index, char) in s.enumerated() { 11 | if let lastIndex = seen[char], start <= lastIndex { 12 | start = lastIndex + 1 13 | } 14 | 15 | maxLength = max(index - start + 1, maxLength) 16 | seen[char] = index 17 | } 18 | 19 | return maxLength 20 | } -------------------------------------------------------------------------------- /LinkList/143-ReorderList.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func reorderList(_ head: ListNode?) { 3 | var node = head, stack = [node] 4 | while let next = node?.next { 5 | stack.append(next) 6 | node = next 7 | } 8 | 9 | node = head 10 | while let next = node?.next, let endNode = stack.removeLast() { 11 | 12 | node?.next = endNode 13 | endNode.next = next 14 | 15 | node = next 16 | 17 | if node?.next === endNode { 18 | node?.next = nil 19 | break 20 | } 21 | } 22 | } 23 | } 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /Trees/116-PopulatingNextRightPointers.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func connect(_ root: Node?) -> Node? { 3 | guard let root = root else { return root } 4 | var queue = [root] 5 | 6 | while !queue.isEmpty { 7 | let size = queue.count - 1 8 | for i in 0...size { 9 | let node = queue.removeFirst() 10 | if i != size { 11 | node.next = queue.first 12 | } 13 | 14 | if node.left != nil { queue.append(node.left!) } 15 | if node.right != nil { queue.append(node.right!) } 16 | } 17 | } 18 | 19 | return root 20 | } 21 | 22 | } 23 | 24 | -------------------------------------------------------------------------------- /Trees/337-HouseRobber3.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | func rob(_ root: TreeNode?) -> Int { 4 | let (rob, notRob) = maxAmount(root) 5 | return max(rob, notRob) 6 | } 7 | 8 | func maxAmount(_ root: TreeNode?) -> (rob: Int, notRob: Int) { 9 | guard let root = root else { return (0, 0) } 10 | 11 | let leftAmount = maxAmount(root.left) 12 | let rightAmount = maxAmount(root.right) 13 | 14 | let rob = root.val + leftAmount.notRob + rightAmount.notRob 15 | let notRob = max(leftAmount.rob, leftAmount.notRob) + max(rightAmount.rob, rightAmount.notRob) 16 | return (rob, notRob) 17 | } 18 | 19 | } 20 | -------------------------------------------------------------------------------- /DP/Matrix/931-MinFallingPathSum.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func minFallingPathSum(_ matrix: [[Int]]) -> Int { 3 | var dp = matrix 4 | 5 | for row in 1..= 0) ? dp[row - 1][col - 1] : Int.max //case 2 10 | let val3 = (col + 1 < matrix[0].count) ? dp[row - 1][col + 1] : Int.max // case 3 11 | 12 | dp[row][col] = min(val1, val2, val3) + matrix[row][col] 13 | } 14 | } 15 | 16 | return dp.last?.min() ?? 0 17 | } 18 | } -------------------------------------------------------------------------------- /Trie/1065-IndexPairs.swift: -------------------------------------------------------------------------------- 1 | func indexPairs(_ text: String, _ words: [String]) -> [[Int]] { 2 | 3 | let trie = Trie() 4 | trie.addWords(words) 5 | 6 | let text = Array(text) 7 | var result = [[Int]]() 8 | 9 | for i in 0.. Int { 16 | if frequencyItem.isEmpty { return 0 } 17 | if frequencyItem.count == 1 { return frequencyItem[0] } 18 | let index = Int.random(in: 0.. Bool { 2 | checkForValidBST(tree, Int.min, Int.max) 3 | } 4 | 5 | 6 | func checkForValidBST(_ root: TreeNode?, _ min: Int, _ max: Int) -> Bool { 7 | guard let root = root else { return true } 8 | 9 | if min >= root.val || max <= root.val { 10 | return false 11 | } 12 | 13 | let leftVal = root.left?.val ?? Int.min 14 | let rightVal = root.right?.val ?? Int.max 15 | 16 | let isValid = root.val < rightVal && root.val > leftVal 17 | 18 | return isValid 19 | && checkForValidBST(root.left, min, root.val) 20 | && checkForValidBST(root.right, root.val, max) 21 | } 22 | -------------------------------------------------------------------------------- /OA/MaxQuality.swift: -------------------------------------------------------------------------------- 1 | func maxQuality(_ packets: [Int], _ channels: Int) -> Int { 2 | var packets = packets.map(Double.init).sorted() 3 | var median: Double = 0 4 | 5 | for _ in 1.. Bool { 6 | var defectedIndex = -1 7 | 8 | for index in 0.. nums[index + 1] { 10 | if defectedIndex == -1 { defectedIndex = index} 11 | else { return false } 12 | } 13 | } 14 | 15 | return (defectedIndex == -1 || defectedIndex == 0 || defectedIndex == nums.count - 2 || (nums[defectedIndex] <= nums[defectedIndex + 2]) || (nums[defectedIndex - 1] <= nums[defectedIndex + 1]) ) 16 | } 17 | 18 | checkPossibility([3,4,2,3]) 19 | checkPossibility([1,5,6,4,5]) 20 | 21 | 22 | -------------------------------------------------------------------------------- /ProblemSolving.playground/xcuserdata/obashir.xcuserdatad/xcschemes/xcschememanagement.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | SchemeUserState 6 | 7 | Leetcode (Playground).xcscheme 8 | 9 | isShown 10 | 11 | orderHint 12 | 0 13 | 14 | ProblemSolving (Playground).xcscheme 15 | 16 | isShown 17 | 18 | orderHint 19 | 0 20 | 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /SlidingWindow/904-FruitsInTheBasket.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func totalFruit(_ fruits: [Int]) -> Int { 3 | var start = 0 4 | var dict = [Int: Int]() 5 | var length = 0 6 | 7 | for (end, fruit) in fruits.enumerated() { 8 | dict[fruit] = end 9 | 10 | if dict.keys.count == 3 { 11 | let minKey = Array(dict.values).min()! 12 | let index = dict[fruits[minKey]]! 13 | dict[fruits[minKey]] = nil 14 | start = index + 1 15 | } 16 | 17 | length = max(end - start + 1, length) 18 | } 19 | 20 | return length 21 | } 22 | } -------------------------------------------------------------------------------- /Combinatorics And Backtracking/90-subset2.swift: -------------------------------------------------------------------------------- 1 | func subsetsWithDup(_ nums: [Int]) -> [[Int]] { 2 | var result = [[Int]]() 3 | let nums = nums.sorted() 4 | result.append([]) 5 | var start = 0 6 | var end = 0 7 | 8 | for i in 0.. 0 && nums[i - 1] == nums[i] { 12 | start = end + 1 13 | } 14 | 15 | end = result.count - 1 16 | 17 | for j in start...end { 18 | var subset = result[j] 19 | subset.append(nums[i]) 20 | result.append(subset) 21 | 22 | } 23 | } 24 | 25 | 26 | return result 27 | } 28 | -------------------------------------------------------------------------------- /Mix/202-HappyNumber.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | func isHappy(_ n: Int) -> Bool { 4 | var fast = n 5 | var slow = n 6 | 7 | repeat { 8 | slow = findHappyNumber(slow) 9 | fast = findHappyNumber(findHappyNumber(fast)) 10 | } while (slow != fast) 11 | 12 | 13 | return slow == 1 14 | } 15 | 16 | func findHappyNumber(_ n: Int) -> Int { 17 | var result = 0 18 | var n = n 19 | 20 | while n != 0 { 21 | let digit = n % 10 22 | n = n / 10 23 | result += digit * digit 24 | } 25 | 26 | 27 | return result 28 | } 29 | } -------------------------------------------------------------------------------- /SlidingWindow/1869-LongerContiguousSegOfOnesThanZeros.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func checkZeroOnes(_ s: String) -> Bool { 3 | var startOfZero = 0 4 | var startOfOne = 0 5 | 6 | var maxLen0 = 0 7 | var maxLen1 = 0 8 | 9 | for (end, char) in s.enumerated() { 10 | 11 | if char == "0" { 12 | startOfOne = end + 1 13 | } else { 14 | startOfZero = end + 1 15 | } 16 | 17 | maxLen0 = max(maxLen0, end - startOfZero + 1) 18 | maxLen1 = max(maxLen1, end - startOfOne + 1) 19 | 20 | } 21 | 22 | return maxLen1 > maxLen0 23 | } 24 | } -------------------------------------------------------------------------------- /Two-Pointers/977-SquaresOfASortedArray.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func sortedSquares(_ nums: [Int]) -> [Int] { 3 | var left = 0 4 | var right = nums.count - 1 5 | var count = nums.count - 1 6 | var result = Array(repeating: 0, count: nums.count) 7 | let nums = nums.map { $0 * $0 } 8 | 9 | while count >= 0 { 10 | if nums[left] > nums[right] { 11 | result[count] = nums[left] 12 | left += 1 13 | } else { 14 | result[count] = nums[right] 15 | right -= 1 16 | } 17 | 18 | count -= 1 19 | } 20 | 21 | return result 22 | } 23 | } -------------------------------------------------------------------------------- /Stack And Queues/71-SimplifyPath.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func simplifyPath(_ path: String) -> String { 3 | let directories = path.split(separator: "/").map(String.init) 4 | var stack = [String]() 5 | 6 | for directory in directories { 7 | if directory == "." || directory.isEmpty { 8 | continue 9 | } 10 | 11 | if directory == ".." { 12 | if !stack.isEmpty { 13 | stack.removeLast() 14 | } 15 | } else { 16 | stack.append(directory) 17 | } 18 | } 19 | 20 | return "/" + stack.joined(separator: "/") 21 | } 22 | } -------------------------------------------------------------------------------- /ArraysAndStrings/238-ProductOfArrayExceptSelf.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func productExceptSelf(_ nums: [Int]) -> [Int] { 3 | var left = Array(repeating: 1, count: nums.count) 4 | var right = Array(repeating: 1, count: nums.count) 5 | 6 | var result = [Int]() 7 | 8 | for i in 1.. String { n == 1 ? "1" : charCount(countAndSay(n-1)) } 3 | 4 | func charCount(_ str: String) -> String { 5 | if str.isEmpty { return "" } 6 | var prevChar: Character? 7 | var count = 0 8 | var result = "" 9 | 10 | for char in str { 11 | if prevChar == nil { 12 | prevChar = char 13 | count += 1 14 | } else if prevChar! == char { 15 | count += 1 16 | } else { 17 | result += String(count) + String(prevChar!) 18 | prevChar = char 19 | count = 1 20 | } 21 | } 22 | 23 | result += String(count) + String(prevChar!) 24 | return result 25 | } -------------------------------------------------------------------------------- /OA/1109-CorporateFlightBookings.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func corpFlightBookings(_ bookings: [[Int]], _ n: Int) -> [Int] { 3 | var prefixSum = Array(repeating: 0, count: n) 4 | 5 | for booking in bookings { 6 | let start = booking[0] - 1 7 | let end = booking[1] - 1 8 | let seats = booking[2] 9 | 10 | prefixSum[start] += seats 11 | 12 | if end < n-1 { 13 | prefixSum[end + 1] -= seats 14 | } 15 | } 16 | 17 | 18 | for i in 1.. Int { 2 | var lo = 1 3 | var hi = piles.max() ?? 0 4 | 5 | while lo < hi { 6 | let mid = (lo + hi) / 2 7 | if isPossibile(mid,piles, h) { 8 | hi = mid 9 | } else { 10 | lo = mid + 1 11 | } 12 | } 13 | 14 | return lo 15 | } 16 | 17 | func isPossibile(_ speed: Int, _ piles: [Int],_ k: Int) -> Bool { 18 | guard speed > 0 else { return false } 19 | 20 | var count = 0 21 | 22 | for bananas in piles { 23 | count = count + bananas / speed 24 | if bananas % speed != 0 { count += 1 } 25 | } 26 | 27 | return count <= k 28 | } -------------------------------------------------------------------------------- /Trees/426-ConvertBSTToDD.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | var head: Node? 3 | var tail: Node? 4 | 5 | func treeToDoublyList(_ root: Node?) -> Node? { 6 | 7 | makeList(root) 8 | 9 | head?.left = tail 10 | tail?.right = head 11 | 12 | return head 13 | } 14 | 15 | 16 | func makeList(_ root: Node?) { 17 | guard let root = root else { return } 18 | 19 | makeList(root.left) 20 | 21 | if tail != nil { 22 | root.left = tail 23 | tail?.right = root 24 | } else { 25 | head = root 26 | } 27 | 28 | tail = root 29 | makeList(root.right) 30 | } 31 | } -------------------------------------------------------------------------------- /CTCI/Graph And Tree/4.4-IsBalanced.swift: -------------------------------------------------------------------------------- 1 | func isBalanced(_ root: TreeNode?) -> Bool { 2 | isBalancedUtil(root) != Int.min 3 | } 4 | 5 | 6 | func isBalancedUtil(_ root: TreeNode?) -> Int { 7 | guard let root = root else { return 0 } 8 | 9 | let leftHeight = isBalancedUtil(root.left) 10 | 11 | if leftHeight == Int.min { 12 | return leftHeight 13 | } 14 | 15 | let rightHeight = isBalancedUtil(root.right) 16 | 17 | if rightHeight == Int.min { 18 | return rightHeight 19 | } 20 | 21 | return abs(leftHeight - rightHeight) < 2 22 | ? max(leftHeight, rightHeight) + 1 23 | : Int.min 24 | } -------------------------------------------------------------------------------- /ProblemSolving.playground/Pages/SameCountries.xcplaygroundpage/timeline.xctimeline: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /MergeIntervals/56-MergeIntervals.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func merge(_ intervals: [[Int]]) -> [[Int]] { 3 | guard intervals.count > 1 else { return intervals } 4 | let intervals = intervals.sorted { $0[0] < $1[0] } 5 | var mergedIntervals = [[Int]]() 6 | var prevInterval = intervals[0] 7 | 8 | for interval in intervals[1...intervals.count-1] { 9 | if prevInterval[1] >= interval[0] { 10 | prevInterval[1] = max(interval[1], prevInterval[1]) 11 | } else { 12 | mergedIntervals.append(prevInterval) 13 | prevInterval = interval 14 | } 15 | } 16 | 17 | mergedIntervals.append(prevInterval) 18 | 19 | return mergedIntervals 20 | } 21 | 22 | } -------------------------------------------------------------------------------- /Mix/605-CanPlaceFlowers.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func canPlaceFlowers(_ flowerbed: [Int], _ n: Int) -> Bool { 3 | guard n > 0 else { return true } 4 | var current = 0 5 | var flowerbed = flowerbed 6 | 7 | var n = n 8 | 9 | while current < flowerbed.count && n > 0 { 10 | if flowerbed[current] == 0 11 | && ( current == flowerbed.count - 1 || flowerbed[current + 1] == 0 ) 12 | && ( current == 0 || flowerbed[current - 1 ] == 0 ){ 13 | flowerbed[current] = 1 14 | n -= 1 15 | } 16 | 17 | current += 1 18 | } 19 | 20 | 21 | return n == 0 22 | } 23 | } -------------------------------------------------------------------------------- /OA/496-NextGreaterElement.swift: -------------------------------------------------------------------------------- 1 | func nextGreaterElement(_ nums1: [Int], _ nums2: [Int]) -> [Int] { 2 | var stack = [Int]() 3 | var map = [Int: Int]() 4 | 5 | for num in nums2 { 6 | while !stack.isEmpty, num > stack.last! { 7 | map[stack.removeLast()] = num 8 | } 9 | 10 | stack.append(num) 11 | } 12 | 13 | for num in stack { 14 | map[num] = -1 15 | } 16 | 17 | var result = [Int]() 18 | 19 | for num in nums1 { 20 | if let maxNum = map[num] { 21 | result.append(maxNum) 22 | } 23 | } 24 | 25 | return result 26 | } -------------------------------------------------------------------------------- /Stack And Queues/1209-RemoveAllAdjDupl.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func removeDuplicates(_ s: String, _ k: Int) -> String { 3 | var stack = [(char: Character, count: Int)]() 4 | 5 | for char in s { 6 | var count = 1 7 | 8 | if let last = stack.last, last.char == char { 9 | count += last.count 10 | } 11 | 12 | stack.append((char, count)) 13 | 14 | if let last = stack.last, last.count == k { 15 | for _ in 0.. Int { 4 | if chars.count == 1 { return 1 } 5 | var readPtr = 0, writePtr = 0 6 | 7 | while readPtr < chars.count { 8 | var length = 0 9 | let char = chars[readPtr] 10 | while readPtr < chars.count && chars[readPtr] == char { 11 | readPtr += 1 12 | length += 1 13 | } 14 | 15 | 16 | chars[writePtr] = chars[readPtr] 17 | 18 | writePtr += 1 19 | 20 | if length > 1 { 21 | for digit in String(length) { 22 | chars[writePtr] = digit 23 | writePtr += 1 24 | } 25 | } 26 | } 27 | 28 | return writePtr 29 | } -------------------------------------------------------------------------------- /CTCI/Search and Sort/74-SearchIn2DMatrix.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func searchMatrix(_ matrix: [[Int]], _ target: Int) -> Bool { 3 | if matrix.isEmpty { return false } 4 | let m = matrix.count 5 | let n = matrix[0].count 6 | var end = m * n - 1 7 | var start = 0 8 | 9 | while start <= end { 10 | let mid = start + (end - start) / 2 11 | let midValue = matrix[mid / n][mid % n] 12 | if midValue == target { 13 | return true 14 | }else if midValue > target { 15 | end = mid - 1 16 | } else { 17 | start = mid + 1 18 | } 19 | } 20 | 21 | return false 22 | } 23 | } -------------------------------------------------------------------------------- /Others/NumberDictionary/numberDictionatry.swift: -------------------------------------------------------------------------------- 1 | func getName(_ names: [String], _ numbers: [String], _ prefix: String) -> String { 2 | var numberDict = [(number: String, name: String)]() 3 | 4 | for i in 0.. Int { 16 | if frequencyItem.isEmpty { return 0 } 17 | if frequencyItem.count == 1 { return frequencyItem[0] } 18 | let index = Int.random(in: 0.. Int { 5 | dfs(root) 6 | return longestPathLength 7 | } 8 | 9 | func dfs(_ root: TreeNode?) -> Int { 10 | guard let root = root else { return -1 } 11 | 12 | var leftPath = dfs(root.left) + 1 13 | var rightPath = dfs(root.right) + 1 14 | 15 | if let leftVal = root.left?.val, leftVal != root.val { 16 | leftPath = 0 17 | } 18 | 19 | if let rightVal = root.right?.val, rightVal != root.val { 20 | rightPath = 0 21 | } 22 | 23 | longestPathLength = max(longestPathLength, leftPath + rightPath) 24 | 25 | return max(leftPath, rightPath) 26 | 27 | } 28 | -------------------------------------------------------------------------------- /Trees/117-PopulatingNextRightPointer2.swift: -------------------------------------------------------------------------------- 1 | func connect(_ root: Node?) -> Node? { 2 | guard let root = root else { return root } 3 | var queue = [root] 4 | 5 | while !queue.isEmpty { 6 | var level = [Node]() 7 | var prevNode: Node? 8 | for node in queue { 9 | if prevNode != nil { 10 | prevNode?.next = node 11 | } 12 | prevNode = node 13 | 14 | if node.left != nil { 15 | level.append(node.left!) 16 | } 17 | 18 | if node.right != nil { 19 | level.append(node.right!) 20 | } 21 | } 22 | queue = level 23 | } 24 | 25 | return root 26 | } 27 | -------------------------------------------------------------------------------- /Trees/LCA/1650-LCA3.swift: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a Node. 3 | * public class Node { 4 | * public var val: Int 5 | * public var left: Node? 6 | * public var right: Node? 7 | * public var parent: Node? 8 | * public init(_ val: Int) { 9 | * self.val = val 10 | * self.left = nil 11 | * self.right = nil 12 | * self.parent = nil 13 | * } 14 | * } 15 | */ 16 | 17 | class Solution { 18 | 19 | func lowestCommonAncestor(_ p: Node?,_ q: Node?) -> Node? { 20 | var a = p 21 | var b = q 22 | 23 | while a !== b { 24 | a = a != nil ? a?.parent : q 25 | b = b != nil ? b?.parent: p 26 | } 27 | 28 | return a 29 | } 30 | } -------------------------------------------------------------------------------- /MergeIntervals/CPUMaxLoad.swift: -------------------------------------------------------------------------------- 1 | func maxLoad(_ intervals: [[Int]]) -> Int { 2 | var maxLoad = Int.min 3 | var currLoad = 0 4 | let intervals = intervals.sorted { $0[0] < $1[0] } 5 | var endTimes = [(time: Int, load: Int)]() 6 | endTimes.append((intervals[0][1], intervals[0][2])) 7 | 8 | for interval in intervals[1...intervals.count-1] { 9 | while !endTimes.isEmpty && endTimes[0].time <= interval[0] { 10 | currLoad -= endTimes[0].load 11 | endTimes.removeFirst() 12 | } 13 | currLoad += interval[2] 14 | maxLoad = max(currLoad, maxLoad) 15 | endTimes.append((interval[1], interval[2])) 16 | endTimes.sort { $0.time < $1.time } 17 | } 18 | 19 | return maxLoad 20 | } 21 | -------------------------------------------------------------------------------- /ProblemSolving.playground/Pages/AllPathFromSourceToTarget.xcplaygroundpage/Contents.swift: -------------------------------------------------------------------------------- 1 | import Foundation 2 | 3 | /// 797 4 | 5 | //func allPathsSourceTarget(_ graph: [[Int]]) -> [[Int]] { 6 | // var path = [Int]() 7 | // var allPath = [[Int]]() 8 | // 9 | // dfs(graph, 0, &path, &allPath) 10 | // return allPath 11 | //} 12 | // 13 | //func dfs(_ graph: [[Int]], _ source: Int, _ path: inout [Int], _ allPath: inout [[Int]]) { 14 | // path.append(source) 15 | // 16 | // if source == graph.count - 1 { 17 | // allPath.append(path) 18 | // path.popLast() 19 | // return 20 | // } 21 | // 22 | // for negihbor in graph[source] { dfs(graph, negihbor, &path, &allPath) } 23 | // 24 | // path.popLast() 25 | //} 26 | 27 | 28 | 29 | -------------------------------------------------------------------------------- /SlidingWindow/1004-MaxConsecutiveOne.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func longestOnes(_ nums: [Int], _ k: Int) -> Int { 3 | var start = 0 4 | var maxRepatingOneCount = 0 5 | var length = 0 6 | 7 | for (end, value) in nums.enumerated() { 8 | if value == 1 { 9 | maxRepatingOneCount += 1 10 | } 11 | 12 | if end - start + 1 - maxRepatingOneCount > k { 13 | if nums[start] == 1 { 14 | maxRepatingOneCount -= 1 15 | } 16 | 17 | start += 1 18 | } 19 | 20 | length = max(length, end - start + 1) 21 | } 22 | 23 | return length 24 | } 25 | } -------------------------------------------------------------------------------- /ArraysAndStrings/287-FindDuplicates.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func findDuplicate(_ nums: [Int]) -> Int { 3 | var lo = 1 4 | var hi = nums.count - 1 5 | var duplicates = -1 6 | 7 | while lo <= hi { 8 | var count = 0 9 | 10 | var curr = ( lo + hi ) / 2 11 | 12 | for num in nums { 13 | if num <= curr { 14 | count += 1 15 | } 16 | } 17 | 18 | if count > curr { 19 | duplicates = curr 20 | hi = curr - 1 21 | } else { 22 | lo = curr + 1 23 | } 24 | } 25 | 26 | return duplicates 27 | } 28 | } 29 | 30 | -------------------------------------------------------------------------------- /ArraysAndStrings/38-CountAndSay.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func countAndSay(_ n: Int) -> String { 3 | if n == 1 { return "1" } 4 | 5 | return compressString(Array(countAndSay( n - 1))) 6 | 7 | } 8 | 9 | func compressString(_ string: [Character]) -> String { 10 | var result = "" 11 | var readPtr = 0 12 | 13 | while readPtr < string.count { 14 | var length = 0 15 | let char = string[readPtr] 16 | 17 | while readPtr < string.count && char == string[readPtr] { 18 | readPtr += 1 19 | length += 1 20 | } 21 | 22 | result.append(String(length)) 23 | result.append(char) 24 | 25 | } 26 | 27 | return result 28 | } 29 | } -------------------------------------------------------------------------------- /ArraysAndStrings/697-DegreeOfAnArray.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func findShortestSubArray(_ nums: [Int]) -> Int { 3 | var left = [Int: Int]() 4 | var right = [Int: Int]() 5 | var count = [Int: Int]() 6 | var degree = 0 7 | var length = Int.max 8 | 9 | for (index, num) in nums.enumerated() { 10 | if left[num] == nil { 11 | left[num] = index 12 | } 13 | right[num] = index 14 | count[num, default: 0] += 1 15 | degree = max(degree, count[num, default: 0]) 16 | } 17 | 18 | for num in nums { 19 | if count[num, default: 0] == degree { 20 | length = min(length, right[num, default: 0] - left[num, default: 0] + 1) 21 | } 22 | } 23 | 24 | return length 25 | } 26 | } -------------------------------------------------------------------------------- /prefix sum/325-MaxSizeSubArraySizeK.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func maxSubArrayLen(_ nums: [Int], _ k: Int) -> Int { 3 | var prefixSum = 0 4 | var maxLength = 0 5 | var dict = [Int: Int]() 6 | 7 | for (end, value) in nums.enumerated() { 8 | prefixSum += value 9 | 10 | if prefixSum == k { 11 | maxLength = end + 1 12 | } 13 | 14 | if let index = dict[prefixSum - k] { 15 | maxLength = max(end - index, maxLength) 16 | } 17 | 18 | if dict[prefixSum] == nil { 19 | dict[prefixSum] = end 20 | } 21 | 22 | } 23 | 24 | return maxLength 25 | } 26 | } -------------------------------------------------------------------------------- /ArraysAndStrings/443-StringCompression.swift: -------------------------------------------------------------------------------- 1 | func compress(_ chars: inout [Character]) -> Int { 2 | guard chars.count != 1 else { return 1 } 3 | var readPtr = 0 4 | var writePtr = 0 5 | 6 | while readPtr < chars.count { 7 | let char = chars[readPtr] 8 | var length = 0 9 | 10 | while readPtr < chars.count && chars[readPtr] == char { 11 | readPtr += 1 12 | length += 1 13 | } 14 | 15 | chars[writePtr] = char 16 | writePtr += 1 17 | 18 | if length > 1 { 19 | for digit in String(length) { 20 | chars[writePtr] = digit 21 | writePtr += 1 22 | } 23 | } 24 | 25 | } 26 | 27 | return writePtr 28 | } -------------------------------------------------------------------------------- /ArraysAndStrings/AddTwoNums/415-AddStrings.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func addStrings(_ num1: String, _ num2: String) -> String { 3 | var num1 = Array(num1) 4 | var num2 = Array(num2) 5 | 6 | var carry = 0 7 | var result = "" 8 | 9 | while !num1.isEmpty || !num2.isEmpty { 10 | let val1 = num1.isEmpty ? "0" : num1.removeLast() 11 | let val2 = num2.isEmpty ? "0" : num2.removeLast() 12 | 13 | let sum = Int(String(val1))! + Int(String(val2))! + carry 14 | 15 | result.append("\(sum%10)") 16 | carry = sum / 10 17 | } 18 | 19 | if carry != 0 { 20 | result.append("\(carry)") 21 | } 22 | 23 | return String(result.reversed()) 24 | } 25 | 26 | } -------------------------------------------------------------------------------- /DP/LongestPalindromicSubsequence/647-CountOfPalindromiceSubstring.swift: -------------------------------------------------------------------------------- 1 | func countSubstrings(_ s: String) -> Int { 2 | var dp : [[Bool]] = Array(repeating: Array(repeating: false, count: s.count), count: s.count) 3 | var count = 0 4 | 5 | for i in 0.. Int { 2 | guard let root = root else { return 0 } 3 | var depth = 0 4 | var queue = [root] 5 | 6 | while !queue.isEmpty { 7 | var level = [TreeNode]() 8 | depth += 1 9 | 10 | for node in queue { 11 | if node.left == nil && node.right == nil { 12 | return depth 13 | } 14 | 15 | if let leftChild = node.left { 16 | level.append(leftChild) 17 | 18 | } 19 | 20 | if let rightChild = node.right { 21 | level.append(rightChild) 22 | } 23 | 24 | } 25 | queue = level 26 | } 27 | 28 | return depth 29 | 30 | } 31 | -------------------------------------------------------------------------------- /LinkList/21-MergeList.swift: -------------------------------------------------------------------------------- 1 | func mergeTwoLists(_ l1: ListNode?, _ l2: ListNode?) -> ListNode? { 2 | if l1 == nil { return l2 } 3 | if l2 == nil { return l1 } 4 | var l1 = l1 5 | var l2 = l2 6 | 7 | var dummyHead = ListNode(0) 8 | var dummy = dummyHead 9 | 10 | while l1 != nil && l2 != nil { 11 | if l1!.val < l2!.val { 12 | dummy.next = ListNode(l1!.val) 13 | l1 = l1?.next 14 | } else { 15 | dummy.next = ListNode(l2!.val) 16 | l2 = l2?.next 17 | } 18 | 19 | 20 | dummy = (dummy.next)! 21 | } 22 | 23 | dummy.next = l1 == nil ? l2 : l1 24 | 25 | return dummyHead.next 26 | } -------------------------------------------------------------------------------- /Mix/1509-MinDifferenceInThreeMoves.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func minDifference(_ nums: [Int]) -> Int { 3 | guard nums.count >= 5 else { return 0 } 4 | let nums = nums.sorted() 5 | 6 | var lastIndex = nums.count - 1 7 | 8 | // check removing first three 9 | var minDiff = nums[lastIndex] - nums[3] 10 | 11 | // check removing first 2 and last 12 | minDiff = min(minDiff, nums[lastIndex - 1] - nums[2]) 13 | 14 | // check removing first and last 2 15 | minDiff = min(minDiff, nums[lastIndex - 2] - nums[1]) 16 | 17 | // check removing last 3 18 | minDiff = min(minDiff, nums[lastIndex - 3] - nums[0]) 19 | 20 | return minDiff 21 | } 22 | } 23 | 24 | 25 | -------------------------------------------------------------------------------- /Combinatorics And Backtracking/247-StrobogrammaticNumbers2.swift: -------------------------------------------------------------------------------- 1 | func findStrobogrammatic(_ n: Int) -> [String] { 2 | backtrack(n, n) 3 | } 4 | 5 | func backtrack(_ n: Int, _ original: Int) -> [String] { 6 | if n == 0 { 7 | return [""] 8 | } 9 | 10 | if n == 1 { 11 | return ["0", "1", "8"] 12 | } 13 | 14 | let prevResults = backtrack(n - 2, original) 15 | var result = [String]() 16 | 17 | for prevResult in prevResults { 18 | if n != original { 19 | result.append("0\(prevResult)0") 20 | } 21 | result.append("1\(prevResult)1") 22 | result.append("8\(prevResult)8") 23 | result.append("6\(prevResult)9") 24 | result.append("9\(prevResult)6") 25 | 26 | } 27 | 28 | return result 29 | } -------------------------------------------------------------------------------- /OA/PassStrength.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func uniqueLetterString(_ S: String) -> Int { 3 | var dict:[Character:[Int]] = [:] 4 | var arrayS = Array(S) 5 | var res = 0 6 | 7 | for i in 0.. Bool { 3 | isFlipeEquivalent(root1, root2) 4 | } 5 | 6 | func isFlipeEquivalent(_ root1: TreeNode?, _ root2: TreeNode?) -> Bool { 7 | guard let root1 = root1, 8 | let root2 = root2 9 | else { return root1 === root2 } 10 | 11 | if root1.val != root2.val { return false } 12 | 13 | if (root1.left?.val == root2.left?.val) 14 | && (root1.right?.val == root2.right?.val) { 15 | return isFlipeEquivalent(root1.left, root2.left) && isFlipeEquivalent(root1.right, root2.right) 16 | 17 | } 18 | 19 | return isFlipeEquivalent(root1.right, root2.left) && isFlipeEquivalent(root1.left, root2.right) 20 | 21 | } 22 | 23 | 24 | } 25 | -------------------------------------------------------------------------------- /MergeIntervals/MyCalendar/731-MyCalendar2.swift: -------------------------------------------------------------------------------- 1 | class MyCalendarTwo { 2 | typealias Booking = (start: Int, end: Int) 3 | 4 | var single = [Booking]() 5 | var double = [Booking]() 6 | init() { 7 | 8 | } 9 | 10 | func book(_ start: Int, _ end: Int) -> Bool { 11 | 12 | for booking in double { 13 | if start < booking.end && end > booking.start { 14 | return false 15 | } 16 | } 17 | 18 | for booking in single { 19 | if start < booking.end && end > booking.start { 20 | double.append( (max(booking.start, start), min(booking.end, end)) ) 21 | } 22 | } 23 | 24 | single.append((start, end)) 25 | return true 26 | } 27 | 28 | } -------------------------------------------------------------------------------- /DP/Fibnumber/91-DecodeWays.swift: -------------------------------------------------------------------------------- 1 | func numDecodings(_ s: String) -> Int { 2 | var memo = [Int: Int]() 3 | return numDecodings(s.map{ String($0) }, 0, &memo) 4 | } 5 | 6 | func numDecodings(_ s: [String], _ index: Int, _ memo: inout [Int: Int]) -> Int { 7 | if index == s.count { 8 | return 1 9 | } 10 | 11 | if let value = memo[index] { 12 | return value 13 | } 14 | 15 | if s[index] == "0" { 16 | return 0 17 | } 18 | 19 | if index == s.count - 1 { 20 | return 1 21 | } 22 | 23 | var count = numDecodings(s, index + 1, &memo) 24 | 25 | if let num = Int(s[index] + s[index + 1]), num <= 26 { 26 | count += numDecodings(s, index + 2, &memo) 27 | } 28 | 29 | memo[index] = count 30 | return count 31 | } -------------------------------------------------------------------------------- /ProblemSolving.playground/Pages/IntersectionofTwoLinkedLists.xcplaygroundpage/Contents.swift: -------------------------------------------------------------------------------- 1 | //: [Previous](@previous) 2 | 3 | import Foundation 4 | // 160 5 | func getIntersectionNode(_ headA: ListNode?, _ headB: ListNode?) -> ListNode? { 6 | if headA == nil || headB == nil { return nil } 7 | 8 | var a = headA 9 | var b = headB 10 | 11 | while a !== b { 12 | a = (a == nil) ? headB : a?.next 13 | b = (b == nil) ? headA : b?.next 14 | } 15 | 16 | return a 17 | } 18 | 19 | 20 | func getIntersectionNode1(_ headA: ListNode?, _ headB: ListNode?) -> ListNode? { 21 | 22 | var a = headA 23 | var b = headB 24 | 25 | while a !== b { 26 | a = a == nil ? headB : a?.next 27 | b = b == nil ? headA : b?.next 28 | } 29 | 30 | return a 31 | 32 | } 33 | -------------------------------------------------------------------------------- /Combinatorics And Backtracking/77-combinations.swift: -------------------------------------------------------------------------------- 1 | func combine(_ n: Int, _ k: Int) -> [[Int]] { 2 | var allCombination = [[Int]]() 3 | var combination = [Int]() 4 | genComb(k, n, 0, &combination, &allCombination) 5 | return allCombination 6 | } 7 | 8 | 9 | func genComb(_ k: Int, 10 | _ n: Int, 11 | _ start: Int, 12 | _ comb: inout [Int], 13 | _ allCombination: inout [[Int]]) { 14 | if k == comb.count { 15 | allCombination.append(comb) 16 | return 17 | } 18 | 19 | if k < comb.count { return } 20 | 21 | if start < n { 22 | for next in start.. ListNode? { 3 | var sentinel: ListNode? = ListNode(0, head) 4 | var pred = sentinel 5 | var head = head 6 | 7 | while head != nil { 8 | if head?.next != nil && head?.val == head?.next?.val { 9 | 10 | while(head?.next != nil && head?.val == head?.next?.val) { 11 | head = head?.next 12 | } 13 | 14 | pred?.next = head?.next 15 | 16 | } else { 17 | pred = pred?.next 18 | } 19 | 20 | head = head?.next 21 | } 22 | 23 | return sentinel?.next 24 | } 25 | } -------------------------------------------------------------------------------- /Mix/56-MergeIntervals.swift: -------------------------------------------------------------------------------- 1 | /// 56 2 | func merge(_ intervals: [[Int]]) -> [[Int]] { 3 | 4 | if intervals.isEmpty { return [] } 5 | 6 | let intervals = intervals.sorted{ $0[0] < $1[0] } 7 | var currentInterval = intervals[0] 8 | var mergedIntervals = [[Int]]() 9 | 10 | for interval in intervals[1..= interval[0] { 12 | currentInterval[1] = max(currentInterval[1], interval[1]) 13 | } else { 14 | mergedIntervals.append(currentInterval) 15 | currentInterval = interval 16 | } 17 | } 18 | mergedIntervals.append(currentInterval) 19 | 20 | return mergedIntervals 21 | } 22 | 23 | 24 | merge([[1,3],[2,6],[8,10],[15,18]]) 25 | merge([[1,4],[4,5]]) 26 | merge([[1,4]]) 27 | merge([[1,4],[2,3]]) -------------------------------------------------------------------------------- /LinkList/203-RemoveLinkList.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func removeElements(_ head: ListNode?, _ val: Int) -> ListNode? { 3 | if head == nil { return nil } 4 | var head = head 5 | var prev: ListNode? 6 | var curr = head 7 | 8 | while curr != nil { 9 | if curr?.val == val { 10 | if prev == nil { 11 | curr = curr?.next 12 | head = curr 13 | 14 | } else { 15 | prev?.next = curr?.next 16 | curr = curr?.next 17 | } 18 | 19 | } else { 20 | prev = curr 21 | curr = curr?.next 22 | } 23 | 24 | } 25 | 26 | return head 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Mix/234-PalindromeLinkList.swift: -------------------------------------------------------------------------------- 1 | //234 2 | func isPalindrome(_ head: ListNode?) -> Bool { 3 | var fast = head, slow = head 4 | 5 | while fast != nil { 6 | fast = fast?.next?.next 7 | slow = slow?.next 8 | } 9 | 10 | fast = head 11 | slow = reverseList(slow) 12 | 13 | while slow != nil { 14 | if fast?.val != slow?.val { return false } 15 | slow = slow?.next 16 | fast = fast?.next 17 | } 18 | 19 | return true 20 | } 21 | 22 | 23 | func reverseList( _ head: ListNode?) -> ListNode? { 24 | var prev : ListNode? = nil 25 | var current = head 26 | 27 | while current != nil { 28 | let next = current?.next 29 | current?.next = prev 30 | prev = current 31 | current = next 32 | } 33 | 34 | return prev 35 | } 36 | -------------------------------------------------------------------------------- /ProblemSolving.playground/Pages/WordPattern.xcplaygroundpage/Contents.swift: -------------------------------------------------------------------------------- 1 | import Foundation 2 | 3 | /// 290 4 | 5 | func wordPattern(_ pattern: String, _ s: String) -> Bool { 6 | let words = s.split(separator: " ") 7 | if words.count != pattern.count { return false } 8 | let pattern = Array(pattern) 9 | var wordLastOccurence = [String.SubSequence: Int]() 10 | var patternLastOccuerece = [String.Element: Int]() 11 | 12 | for index in 0.. Int { 3 | var start = 0 4 | var repeatingcharCount = 0 5 | var dict = [Character: Int]() 6 | var length = 0 7 | let s = Array(s) 8 | 9 | for (end, char) in s.enumerated() { 10 | dict[char, default: 0] += 1 11 | repeatingcharCount = max(repeatingcharCount, dict[char]!) 12 | 13 | if (end - start + 1 - repeatingcharCount) > k { 14 | let key = s[start] 15 | dict[key]! -= 1 16 | start += 1 17 | } 18 | 19 | length = max(end - start + 1, length ) 20 | } 21 | 22 | return length 23 | } 24 | } -------------------------------------------------------------------------------- /Combinatorics And Backtracking/46-permutation.swift: -------------------------------------------------------------------------------- 1 | func permute(_ nums: [Int]) -> [[Int]]{ 2 | var visited = Set() 3 | var currePer = [Int]() 4 | var result = [[Int]]() 5 | permuteThroughDFS(nums, &visited, &currePer, &result) 6 | return result 7 | } 8 | 9 | func permuteThroughDFS(_ nums: [Int], _ visisted: inout Set, _ currPer: inout [Int], _ all: inout [[Int]]) { 10 | 11 | if currPer.count == nums.count { 12 | all.append(currPer) 13 | return 14 | } 15 | 16 | for num in nums { 17 | if !visisted.contains(num) { 18 | currPer.append(num) 19 | visisted.insert(num) 20 | permuteThroughDFS(nums, &visisted, &currPer, &all) 21 | currPer.removeLast() 22 | visisted.remove(num) 23 | } 24 | } 25 | } -------------------------------------------------------------------------------- /Graph/DetectCycleInDirectedGraph.swift: -------------------------------------------------------------------------------- 1 | /// https://algorithms.tutorialhorizon.com/graph-detect-cycle-in-a-directed-graph/ 2 | func hasCycle(_ graph: SimpleGraph) -> Bool { 3 | if graph.totalVertices == 0 { return false } 4 | var enqued = Set() 5 | for source in 0..) -> Bool { 12 | 13 | enqued.insert(source) 14 | 15 | for neigbor in graph.vertices[source] { 16 | if enqued.contains(neigbor) { return true } 17 | else { if checkCycles(graph, source: neigbor, enqued: &enqued){ return true } } 18 | } 19 | 20 | enqued.remove(source) 21 | return false 22 | } 23 | -------------------------------------------------------------------------------- /ProblemSolving.playground/Pages/FilterRestaurant.xcplaygroundpage/Contents.swift: -------------------------------------------------------------------------------- 1 | 2 | import Foundation 3 | /// 1333 4 | 5 | func filterRestaurants(_ restaurants: [[Int]], _ veganFriendly: Int, _ maxPrice: Int, _ maxDistance: Int) -> [Int] { 6 | var sortedRestaurants = [(id: Int, rating: Int)]() 7 | restaurants.forEach { restaurant in 8 | if (veganFriendly == 0 || veganFriendly == restaurant[2]) && restaurant[3] <= maxPrice && restaurant[4] <= maxDistance { 9 | sortedRestaurants.append((restaurant[0], restaurant[1])) 10 | } 11 | } 12 | sortedRestaurants.sort{ $0.rating > $1.rating || ($0.rating == $1.rating && $0.id > $1.id) } 13 | return sortedRestaurants.map { $0.id } 14 | } 15 | 16 | filterRestaurants([[1,4,1,40,10],[2,8,0,50,5],[3,8,1,30,4],[4,10,0,10,3],[5,1,1,15,1]], 0, 50, 10) 17 | -------------------------------------------------------------------------------- /ProblemSolving.playground/Pages/SortIntegerByThePowerValue.xcplaygroundpage/Contents.swift: -------------------------------------------------------------------------------- 1 | 2 | import Foundation 3 | 4 | /// 1387 5 | 6 | func getKth(_ lo: Int, _ hi: Int, _ k: Int) -> Int { 7 | 8 | var result = [(Int, Int)]() 9 | var map = [1: 1] 10 | 11 | (lo...hi).forEach { result.append(($0, getPower($0, &map))) } 12 | 13 | result.sort { ($0.1 < $1.1 ) || ($0.0 < $1.0 && $0.1 == $0.1) } 14 | 15 | return result[k - 1].0 16 | } 17 | 18 | func getPower(_ x: Int, _ memoizedMap: inout [Int: Int]) -> Int { 19 | if let power = memoizedMap[x] { return power } 20 | var n = x 21 | var count = 0 22 | while n != 1 { 23 | n = (n % 2 == 0) ? n/2 : ((3 * n) + 1) 24 | count += 1 25 | } 26 | memoizedMap[x] = count 27 | return count 28 | } 29 | 30 | print(getKth(1, 1, 1)) 31 | -------------------------------------------------------------------------------- /prefix sum/523-ContinuosSubArrSum.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func checkSubarraySum(_ nums: [Int], _ k: Int) -> Bool { 3 | if nums.count == 1 { 4 | return false 5 | } 6 | 7 | var prefixSum = nums[0] 8 | 9 | var start = 0 10 | var dict = [ nums[0] % k: 0] 11 | 12 | for i in 1..= 2 { return true } 20 | } else { 21 | dict[remainder] = i 22 | } 23 | } 24 | 25 | return false 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Trees/113-PathSum2.swift: -------------------------------------------------------------------------------- 1 | func pathSum(_ root: TreeNode?, _ targetSum: Int) -> [[Int]] { 2 | guard let root = root else { return [] } 3 | var allPaths = [[Int]]() 4 | var path = [Int]() 5 | 6 | pathSum(root, targetSum, &path, &allPaths) 7 | return allPaths 8 | } 9 | 10 | func pathSum(_ root: TreeNode?, _ targetSum: Int, _ path: inout [Int], _ allPaths: inout [[Int]]) { 11 | guard let root = root else { return } 12 | 13 | path.append(root.val) 14 | 15 | if root.left == nil && root.right == nil { 16 | if targetSum == root.val { 17 | allPaths.append(path) 18 | } 19 | } 20 | 21 | pathSum(root.left, targetSum - root.val, &path, &allPaths) 22 | pathSum(root.right, targetSum - root.val, &path, &allPaths) 23 | 24 | path.removeLast() 25 | 26 | } 27 | -------------------------------------------------------------------------------- /Trees/102-levelOrderTraversal.swift: -------------------------------------------------------------------------------- 1 | func levelOrder(_ root: TreeNode?) -> [[Int]] { 2 | guard let root = root else { return [] } 3 | var queue = [TreeNode]() 4 | queue.append(root) 5 | var result = [[Int]]() 6 | 7 | while !queue.isEmpty { 8 | var newChildren = [TreeNode]() 9 | var level = [Int]() 10 | 11 | for node in queue { 12 | level.append(node.val) 13 | 14 | if let leftChild = node.left { 15 | newChildren.append(leftChild) 16 | } 17 | 18 | if let rightChild = node.right { 19 | newChildren.append(rightChild) 20 | } 21 | } 22 | 23 | result.append(level) 24 | queue = newChildren 25 | } 26 | 27 | return result 28 | } 29 | -------------------------------------------------------------------------------- /DP/LongestCommonSubsequence/LIS/673-NumberOfLIS.swift: -------------------------------------------------------------------------------- 1 | func findNumberOfLIS(_ nums: [Int]) -> Int { 2 | var dp = Array(repeating: 1, count: nums.count) 3 | var count = Array(repeating: 1, count: nums.count) 4 | var maxSubseq = 1 5 | 6 | for i in 1.. nums[j] && dp[i] <= dp[j]{ 9 | dp[i] = dp[j] + 1 10 | maxSubseq = max(maxSubseq, dp[i]) 11 | count[i] = count[j] 12 | } else if dp[i] == dp[j] + 1 { 13 | count[i] += count[j] 14 | } 15 | } 16 | } 17 | 18 | var counter = 0 19 | 20 | for i in 0.. Node? { 2 | guard let node = node else { return nil } 3 | 4 | var queue = [node] 5 | 6 | dict[node] = Node(node.val) 7 | 8 | while !queue.isEmpty { 9 | let current = queue.removeFirst() 10 | 11 | for neighbor in current.neighbors { 12 | if let neighbor = neighbor { 13 | if dict[neighbor] == nil { 14 | let newNode = Node(neighbor.val) 15 | dict[neighbor] = newNode 16 | queue.append(neighbor) 17 | } 18 | 19 | dict[current]!.neighbors.append(dict[neighbor]!) 20 | 21 | } 22 | 23 | } 24 | 25 | } 26 | 27 | return dict[node] 28 | } 29 | -------------------------------------------------------------------------------- /DP/Fibnumber/MinJumpFee.swift: -------------------------------------------------------------------------------- 1 | func minJumpFee(_ fee: [Int]) -> Int { 2 | var memo = Array(repeating: -1, count: fee.count + 1) 3 | return calMinJumps(fee, fee.count, &memo) 4 | } 5 | 6 | func calMinJumps(_ fee: [Int], _ stair: Int, _ memo: inout [Int]) -> Int { 7 | if stair < 1 { 8 | return 0 9 | } 10 | 11 | if stair == 1 || stair == 2 { 12 | return fee[0] 13 | } 14 | 15 | 16 | if memo[stair] == -1 { 17 | let feeOfOneJump = calMinJumps(fee, stair - 1, &memo) + fee[stair - 1] 18 | let feeOfTwoJump = calMinJumps(fee, stair - 2, &memo) + fee[stair - 2] 19 | let feeOfThreeJump = calMinJumps(fee, stair - 3, &memo) + fee[stair - 3] 20 | 21 | memo[stair] = min(feeOfOneJump, feeOfTwoJump, feeOfThreeJump) 22 | 23 | } 24 | 25 | return memo[stair] 26 | } 27 | -------------------------------------------------------------------------------- /Mix/414-ThirdLargestNum.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | typealias LargestNum = (first: Int, second:Int, third: Int) 3 | 4 | func thirdMax(_ nums: [Int]) -> Int { 5 | var largestNum: LargestNum = (Int.min, Int.min, Int.min) 6 | let uniqueNums = Set(nums) 7 | 8 | for num in uniqueNums { 9 | if num > largestNum.first { 10 | largestNum = (num, largestNum.first, largestNum.second) 11 | } else if num > largestNum.second { 12 | largestNum = (largestNum.first, num, largestNum.second) 13 | } else if num > largestNum.third { 14 | largestNum = (largestNum.first, largestNum.second, num) 15 | } 16 | } 17 | 18 | return largestNum.third == Int.min ? largestNum.first : largestNum.third 19 | } 20 | 21 | } -------------------------------------------------------------------------------- /ProblemSolving.playground/Pages/DecodeString.xcplaygroundpage/Contents.swift: -------------------------------------------------------------------------------- 1 | import Foundation 2 | 3 | /// 394 4 | func decodeString(_ s: String) -> String { 5 | 6 | var stack = [(String, Int)]() 7 | var result = "" 8 | var num = 0 9 | 10 | for char in s { 11 | switch char { 12 | case _ where char.isNumber: 13 | num *= 10 14 | num += Int(String(char))! 15 | case "[": 16 | stack.append((result, num)) 17 | result = "" 18 | num = 0 19 | case "]": 20 | let (prevResult, freq) = stack.removeLast() 21 | result = prevResult + String(repeating: result, count: freq) 22 | default: 23 | result += String(char) 24 | } 25 | } 26 | 27 | return result 28 | } 29 | 30 | decodeString("3[a2[c]]") 31 | 32 | -------------------------------------------------------------------------------- /ProblemSolving.playground/Pages/MeetingRoom2.xcplaygroundpage/Contents.swift: -------------------------------------------------------------------------------- 1 | import Foundation 2 | /// 253 https://github.com/Seanforfun/Algorithm-and-Leetcode/blob/master/leetcode/253.%20Meeting%20Rooms%20II.md 3 | 4 | 5 | /// with PQUE 6 | func minMeetingRoom(_ intervals: [[Int]]) -> Int { 7 | 8 | var intervals = intervals 9 | var rooms = 0 10 | var pQueue = Heap(sort: < ) 11 | 12 | intervals.sort { $0[0] < $1[0] } 13 | 14 | intervals.forEach { interval in 15 | pQueue.insert(interval[1]) 16 | if interval[0] < pQueue.peek()! { rooms += 1 } 17 | else { pQueue.remove() } 18 | } 19 | 20 | return rooms 21 | } 22 | 23 | 24 | 25 | minMeetingRoom([[0, 30],[5, 10],[15, 20]]) 26 | minMeetingRoom([[0, 1],[2, 3],[4, 5]]) 27 | minMeetingRoom([[0, 60],[20, 30],[18, 25]]) 28 | minMeetingRoom([]) 29 | -------------------------------------------------------------------------------- /Trees/107-ReverseLevelOrderTraversal.swift: -------------------------------------------------------------------------------- 1 | func levelOrderBottom(_ root: TreeNode?) -> [[Int]] { 2 | guard let root = root else { return [] } 3 | var queue = [TreeNode]() 4 | queue.append(root) 5 | var result = [[Int]]() 6 | 7 | while !queue.isEmpty { 8 | var newChildren = [TreeNode]() 9 | var level = [Int]() 10 | 11 | for node in queue { 12 | level.append(node.val) 13 | 14 | if let leftChild = node.left { 15 | newChildren.append(leftChild) 16 | } 17 | 18 | if let rightChild = node.right { 19 | newChildren.append(rightChild) 20 | } 21 | } 22 | result.append(level) 23 | queue = newChildren 24 | } 25 | 26 | return result.reversed() 27 | } -------------------------------------------------------------------------------- /Two-Pointers/713-SubarrayProductLessThanK.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func numSubarrayProductLessThanK(_ nums: [Int], _ k: Int) -> Int { 3 | 4 | var start = 0 5 | var currentProduct = 1 6 | var count = 0 7 | 8 | for (end,value) in nums.enumerated() { 9 | 10 | if value >= k { 11 | start = end + 1 12 | currentProduct = 1 13 | continue 14 | } 15 | 16 | currentProduct *= value 17 | 18 | while currentProduct >= k { 19 | currentProduct = currentProduct / nums[start] 20 | start += 1 21 | } 22 | 23 | count += end - start + 1 24 | 25 | } 26 | 27 | return count 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /CTCI/Graph And Tree/4.8-CommonAncestor.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | var lca: TreeNode? 3 | 4 | func lowestCommonAncestor(_ root: TreeNode?, _ p: TreeNode?, _ q: TreeNode?) -> TreeNode? { 5 | 6 | guard let p = p, 7 | let q = q 8 | else { return nil } 9 | 10 | lcaUtil(root, p, q) 11 | return lca ?? TreeNode(2) 12 | } 13 | 14 | func lcaUtil(_ root: TreeNode?, _ node1: TreeNode, _ node2: TreeNode) -> Bool { 15 | guard let root = root else { return false } 16 | 17 | let left = lcaUtil(root.left, node1, node2) ? 1 : 0 18 | let right = lcaUtil(root.right, node1, node2) ? 1 : 0 19 | let mid = (root.val == node1.val || root.val == node2.val) ? 1 : 0 20 | 21 | if (left + right + mid) >= 2 { 22 | lca = root 23 | return true 24 | } 25 | 26 | return (left + right + mid) == 1 27 | } 28 | 29 | } -------------------------------------------------------------------------------- /Trees/298-BinTreeLongestConsecutiveSeq.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | var maxLength = 0 3 | 4 | func longestConsecutive(_ root: TreeNode?) -> Int { 5 | dfs(root) 6 | return maxLength 7 | } 8 | 9 | func dfs(_ root: TreeNode?) -> Int { 10 | guard let root = root else { return 0 } 11 | 12 | var leftCount = dfs(root.left) + 1 13 | var rightCount = dfs(root.right) + 1 14 | 15 | if let left = root.left, left.val != root.val + 1 { 16 | leftCount = 1 17 | } 18 | 19 | if let right = root.right, right.val != root.val + 1 { 20 | rightCount = 1 21 | } 22 | 23 | let length = max(leftCount, rightCount) 24 | maxLength = max(maxLength, length) 25 | 26 | return length 27 | 28 | } 29 | } -------------------------------------------------------------------------------- /DP/01Knapsack-Unbounded/518-CoinChange2.swift: -------------------------------------------------------------------------------- 1 | /// 518 https://www.geeksforgeeks.org/coin-change-dp-7/ 2 | func change(_ amount: Int, _ coins: [Int]) -> Int { 3 | var cache = Array(repeating: Array(repeating: -1, count: coins.count + 1), count: amount + 1) 4 | return coinChangeUtil(coins, amount, coins.count, &cache) 5 | } 6 | 7 | 8 | func coinChangeUtil(_ coin: [Int], _ amount: Int, _ index: Int, _ cache: inout [[Int]]) -> Int { 9 | 10 | if amount == 0 { return 1 } 11 | 12 | if amount < 0 { return 0 } 13 | 14 | if index <= 0 && amount > 0 { return 0 } 15 | 16 | if cache[amount][index] != -1 { return cache[amount][index] } 17 | 18 | cache[amount][index] = coinChangeUtil(coin, amount, index - 1, &cache) + coinChangeUtil(coin, amount - coin[index - 1], index, &cache) 19 | 20 | return cache[amount][index] 21 | } 22 | 23 | change(10, [10]) -------------------------------------------------------------------------------- /ArraysAndStrings/1567-MaxLenOfSubarrayWithPosProd.swift: -------------------------------------------------------------------------------- 1 | func getMaxLen(_ nums: [Int]) -> Int { 2 | var startOfArray = -1 3 | var startOfNegative = -1 4 | var numOfNegatives = 0 5 | 6 | var length = 0 7 | 8 | for (i, num) in nums.enumerated() { 9 | if num == 0 { 10 | startOfArray = i 11 | startOfNegative = -1 12 | numOfNegatives = 0 13 | } else if num < 0 { 14 | if startOfNegative == -1 { 15 | startOfNegative = i 16 | } 17 | 18 | numOfNegatives += 1 19 | } 20 | let end = numOfNegatives % 2 == 0 ? startOfArray : startOfNegative 21 | length = max(length, i - end) 22 | } 23 | 24 | return length 25 | } 26 | -------------------------------------------------------------------------------- /SlidingWindow/1248-NumberOfNiceSubarray.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func numberOfSubarrays(_ nums: [Int], _ k: Int) -> Int { 3 | atMostKOdd(nums, k) - atMostKOdd(nums, k - 1) 4 | } 5 | 6 | func atMostKOdd(_ nums: [Int], _ k: Int) -> Int { 7 | var start = 0 8 | var length = 0 9 | var oddCount = 0 10 | 11 | for (end, num) in nums.enumerated() { 12 | 13 | if num % 2 == 1 { 14 | oddCount += 1 15 | } 16 | 17 | while oddCount > k { 18 | if nums[start] % 2 == 1 { 19 | oddCount -= 1 20 | } 21 | 22 | start += 1 23 | } 24 | 25 | length += (end - start) + 1 26 | } 27 | 28 | return length 29 | } 30 | } -------------------------------------------------------------------------------- /Combinatorics And Backtracking/39-CombinationSum.swift: -------------------------------------------------------------------------------- 1 | func combinationSum(_ candidates: [Int], _ target: Int) -> [[Int]] { 2 | var comb = [Int]() 3 | var all = [[Int]]() 4 | calCombinationSum(candidates, 0, target, 0, &comb, &all) 5 | return all 6 | } 7 | 8 | func calCombinationSum(_ candidates: [Int], _ start: Int,_ target: Int, _ sum: Int, _ comb: inout[Int], _ all: inout [[Int]]) { 9 | if target < sum { 10 | return 11 | } 12 | 13 | if target == sum { 14 | all.append(comb) 15 | return 16 | } 17 | 18 | for next in start...candidates.count-1 { 19 | comb.append(candidates[next]) 20 | calCombinationSum(candidates, next, target, sum + candidates[next], &comb, &all ) 21 | comb.removeLast() 22 | } 23 | } -------------------------------------------------------------------------------- /DP/Matrix/64-MinCostPath.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func minPathSum(_ grid: [[Int]]) -> Int { 3 | var dp = Array(repeating: 4 | Array(repeating: 0, count: grid[0].count), 5 | count : grid.count) 6 | 7 | dp[0][0] = grid[0][0] 8 | 9 | for row in 1.. Int { 3 | var count = 0 4 | let nums = nums.sorted() 5 | 6 | func findNum(_ left: Int, _ right: Int, _ target: Int) { 7 | var left = left 8 | var right = right 9 | 10 | while left < right { 11 | let sum = nums[left] + nums[right] 12 | if sum < target { 13 | count += right - left 14 | left += 1 15 | } else { 16 | right -= 1 17 | } 18 | } 19 | } 20 | 21 | for (index, num) in nums.enumerated() { 22 | findNum(index + 1, nums.count - 1, target - num) 23 | } 24 | 25 | return count 26 | } 27 | } -------------------------------------------------------------------------------- /DP/0-1KnapSack/1049-LastStoneWeight2.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | var memo = [String: Int]() 3 | 4 | func lastStoneWeightII(_ stones: [Int]) -> Int { 5 | minWeightLeft(stones, 0, 0, 0) 6 | } 7 | 8 | func minWeightLeft(_ stones: [Int], _ index: Int, _ subset1: Int, _ subset2: Int) -> Int { 9 | if index == stones.count { 10 | return abs(subset1 - subset2) 11 | } 12 | 13 | let key = "\(index)-\(subset1)" 14 | 15 | if memo[key] == nil { 16 | let val = stones[index] 17 | let diffWithI = minWeightLeft(stones, index + 1, subset1 + val, subset2) 18 | let diffWithoutI = minWeightLeft(stones, index + 1, subset1, subset2 + val) 19 | memo[key] = min(diffWithI, diffWithoutI) 20 | } 21 | 22 | 23 | return memo[key]! 24 | } 25 | } -------------------------------------------------------------------------------- /DP/WordBreak/139-WordBreak.Swift: -------------------------------------------------------------------------------- 1 | func wordBreak(_ s: String, _ wordDict: [String]) -> Bool { 2 | var cache = [String: Bool]() 3 | return wordBreakUtil(s, Set(wordDict), &cache) 4 | } 5 | 6 | func wordBreakUtil(_ word: String, _ wordDict: Set, _ cache: inout [String: Bool]) -> Bool { 7 | if let isPrefix = cache[word] { return isPrefix } 8 | 9 | var prefix = "" 10 | 11 | for char in word { 12 | prefix.append(char) 13 | if wordDict.contains(prefix) { 14 | let remaingWord = word.suffix(word.count - prefix.count) 15 | if remaingWord.isEmpty { return true } 16 | 17 | if wordBreakUtil(String(remaingWord), wordDict, &cache) { 18 | cache[word] = true 19 | return true 20 | } 21 | } 22 | 23 | } 24 | 25 | cache[word] = false 26 | return false 27 | } 28 | -------------------------------------------------------------------------------- /TwoSum/1865-FindingPairWithCertainSum.swift: -------------------------------------------------------------------------------- 1 | class FindSumPairs { 2 | 3 | private var dict1: [Int: Int] 4 | private var dict2: [Int: Int] 5 | private var nums2: [Int] 6 | 7 | init(_ nums1: [Int], _ nums2: [Int]) { 8 | self.dict1 = nums1.reduce(into: [Int: Int](), { $0[$1, default: Int(0)] += 1 }) 9 | self.dict2 = nums2.reduce(into: [Int: Int](), { $0[$1, default: Int(0)] += 1 }) 10 | self.nums2 = nums2 11 | } 12 | 13 | func add(_ index: Int, _ val: Int) { 14 | dict2[nums2[index], default: Int(0)] -= 1 15 | nums2[index] += val 16 | dict2[nums2[index], default: Int(0)] += 1 17 | } 18 | 19 | func count(_ tot: Int) -> Int { 20 | return dict1.reduce(into: 0) { 21 | if let val = dict2[tot - $1.0] { 22 | $0 += $1.1 * val 23 | } 24 | } 25 | } 26 | } -------------------------------------------------------------------------------- /Graph/Connected Component/323-CountComponent.swift: -------------------------------------------------------------------------------- 1 | func countComponents(_ n: Int, _ edges: [[Int]]) -> Int { 2 | var graph = Array(repeating: [Int](), count: n) 3 | var visited = Set() 4 | var totalComponents = 0 5 | 6 | for edge in edges { 7 | graph[edge[0]].append(edge[1]) 8 | graph[edge[1]].append(edge[0]) 9 | 10 | } 11 | 12 | for node in 0..) { 23 | visted.insert(current) 24 | 25 | for node in graph[current] { 26 | if !visted.contains(node) { 27 | isConnected(graph, node, &visted) 28 | } 29 | } 30 | } -------------------------------------------------------------------------------- /OA/138-CopyListWithRandomPtr.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func copyRandomList(_ head: Node?) -> Node? { 3 | if head == nil { return nil } 4 | 5 | var newHead = Node(-1) 6 | var copiedList: Node? = newHead 7 | var cache = [Node: Node]() 8 | var curr = head 9 | 10 | while let oldNode = curr { 11 | copiedList?.next = cache[oldNode] ?? Node(oldNode.val) 12 | copiedList = copiedList?.next 13 | cache[oldNode] = copiedList 14 | 15 | if let random = oldNode.random { 16 | copiedList?.random = cache[random] ?? Node(random.val) 17 | cache[random] = copiedList?.random 18 | } 19 | 20 | curr = curr?.next 21 | 22 | } 23 | 24 | 25 | return newHead.next 26 | } 27 | } -------------------------------------------------------------------------------- /DP/0-1KnapSack/SubsetSumProblem.swift: -------------------------------------------------------------------------------- 1 | /// https://www.geeksforgeeks.org/subset-sum-problem-dp-25/ 2 | 3 | func checkSubSum(_ arr: [Int], _ sum: Int) -> Bool { 4 | var cache : [[Bool?]] = Array(repeating: Array(repeating: nil, count: sum + 1), count: arr.count + 1) 5 | return hasSubSetSum(arr, sum, arr.count, &cache) 6 | } 7 | 8 | func hasSubSetSum( _ arr: [Int], _ sum: Int, _ index: Int, _ cache: inout [[Bool?]]) -> Bool { 9 | if sum == 0 { return true } 10 | if index <= 0 { return false } 11 | if let alreadyCal = cache[index][sum] { return alreadyCal } 12 | if arr[index - 1] <= sum { 13 | if hasSubSetSum(arr, sum - arr[index - 1], index - 1, &cache) { 14 | cache[index][sum] = true 15 | return true 16 | } 17 | } 18 | cache[index][sum] = hasSubSetSum(arr, sum, index - 1, &cache) 19 | 20 | return cache[index][sum]! 21 | } -------------------------------------------------------------------------------- /ProblemSolving.playground/Pages/Combination.xcplaygroundpage/Contents.swift: -------------------------------------------------------------------------------- 1 | import Foundation 2 | // 77 3 | func combine(_ n: Int, _ k: Int) -> [[Int]] { 4 | var result: [[Int]] = [] 5 | var combination: [Int] = [] 6 | for num in 1...n { 7 | backtrack(n, k, num: num, combination: &combination, result: &result) 8 | 9 | } 10 | return result 11 | } 12 | 13 | 14 | func backtrack(_ n: Int, _ k : Int, num: Int, combination: inout [Int], result: inout [[Int]]) { 15 | combination.append(num) 16 | if combination.count == k { 17 | result.append(combination) 18 | } else { 19 | if num + 1 <= n { 20 | for next in num+1...n { 21 | backtrack(n, k, num: next, combination: &combination, result: &result) 22 | } 23 | } 24 | 25 | } 26 | 27 | combination.removeLast() 28 | } 29 | 30 | combine(4, 2) 31 | -------------------------------------------------------------------------------- /ProblemSolving.playground/Pages/CountandSay.xcplaygroundpage/Contents.swift: -------------------------------------------------------------------------------- 1 | //: [Previous](@previous) 2 | 3 | import Foundation 4 | 5 | //38 6 | 7 | func countAndSay(_ n: Int) -> String { 8 | if n == 1 { return "1" } 9 | let say = countAndSay(n - 1) 10 | return charCount(say) 11 | } 12 | 13 | func charCount(_ str: String) -> String { 14 | 15 | if str.isEmpty { return "" } 16 | 17 | var result = "" 18 | var prev: Character? 19 | var count = 0 20 | 21 | for char in str { 22 | if prev == nil { 23 | prev = char 24 | count += 1 25 | } else if prev! == char { count += 1 } 26 | else { 27 | result += "\(count)\(prev!)" 28 | prev = char 29 | count = 1 30 | } 31 | } 32 | result += "\(count)\(prev!)" 33 | return result 34 | } 35 | 36 | print(countAndSay(5)) 37 | -------------------------------------------------------------------------------- /Trees/105-ConstructTreeFromPreOrderAndInOrder.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | var preOrderIndex = 0 3 | var inOrderIndexDict = [Int: Int]() 4 | 5 | func buildTree(_ preorder: [Int], _ inorder: [Int]) -> TreeNode? { 6 | for i in 0.. TreeNode? { 15 | guard left <= right else { return nil } 16 | 17 | let rootIndex = inOrderIndexDict[preorder[preOrderIndex]]! 18 | let rootVal = preorder[preOrderIndex] 19 | 20 | preOrderIndex += 1 21 | 22 | let leftTree = buildTree(preorder, left, rootIndex - 1) 23 | let rightTree = buildTree(preorder, rootIndex + 1, right) 24 | 25 | return TreeNode(rootVal, leftTree, rightTree) 26 | 27 | } 28 | 29 | } -------------------------------------------------------------------------------- /Trees/663-EqualTreePartition.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | var subRootSums = [Int]() 3 | 4 | func checkEqualTree(_ root: TreeNode?) -> Bool { 5 | let totalSum = calRootSum(root) 6 | subRootSums.removeLast() 7 | 8 | guard totalSum % 2 == 0 else { return false } 9 | for sum in subRootSums { 10 | if sum == totalSum / 2 { 11 | return true 12 | } 13 | } 14 | 15 | return false 16 | } 17 | 18 | 19 | func calRootSum(_ root: TreeNode?) -> Int { 20 | guard let root = root else { return 0 } 21 | 22 | let leftSum = calRootSum(root.left) 23 | let rightSum = calRootSum(root.right) 24 | 25 | let totalSum = leftSum + rightSum + root.val 26 | 27 | subRootSums.append(totalSum) 28 | 29 | return totalSum 30 | } 31 | } -------------------------------------------------------------------------------- /LinkList/86-PartitionList.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func partition(_ head: ListNode?, _ x: Int) -> ListNode? { 3 | var smallHead = ListNode(0) 4 | var currSmall = smallHead 5 | 6 | var bigHead = ListNode(0) 7 | var currBig = bigHead 8 | 9 | var curr = head 10 | 11 | while curr != nil { 12 | let newNode = ListNode(curr!.val) 13 | if curr!.val < x { 14 | currSmall.next = newNode 15 | currSmall = (currSmall.next)! 16 | } else { 17 | currBig.next = newNode 18 | currBig = (currBig.next)! 19 | } 20 | 21 | curr = curr?.next 22 | } 23 | 24 | currBig.next = nil 25 | currSmall.next = bigHead.next 26 | 27 | 28 | return smallHead.next 29 | } 30 | } -------------------------------------------------------------------------------- /Stack And Queues/155-MinStack.swift: -------------------------------------------------------------------------------- 1 | 2 | class MinStack { 3 | var stack = [Int]() 4 | var minStack = [Int]() 5 | init() { 6 | 7 | } 8 | 9 | func push(_ val: Int) { 10 | stack.append(val) 11 | if let x = minStack.last { 12 | minStack.append( min(x, val) ) 13 | } else { 14 | minStack.append(val) 15 | } 16 | 17 | } 18 | 19 | func pop() { 20 | stack.popLast() 21 | minStack.popLast() 22 | } 23 | 24 | func top() -> Int { 25 | stack.last ?? -1 26 | } 27 | 28 | func getMin() -> Int { 29 | minStack.last ?? -1 30 | } 31 | } 32 | 33 | /** 34 | * Your MinStack object will be instantiated and called as such: 35 | * let obj = MinStack() 36 | * obj.push(val) 37 | * obj.pop() 38 | * let ret_3: Int = obj.top() 39 | * let ret_4: Int = obj.getMin() 40 | */ -------------------------------------------------------------------------------- /ProblemSolving.playground/Pages/ClimbingStairs.xcplaygroundpage/Contents.swift: -------------------------------------------------------------------------------- 1 | /// 70 2 | import Foundation 3 | 4 | func climbStairs(_ n: Int) -> Int { 5 | var memo = [Int:Int]() 6 | return numberOfWays(n, &memo) 7 | } 8 | 9 | func numberOfWays(_ n: Int, _ memo: inout [Int: Int]) ->Int{ 10 | if n == 1 { return 1 } 11 | else if n == 2 { return 2 } 12 | else if memo[n] != nil { 13 | return memo[n]! 14 | } 15 | 16 | memo[n] = numberOfWays(n - 1, &memo) + numberOfWays( n - 2, &memo) 17 | return memo[n]! 18 | 19 | } 20 | 21 | func numberOfWaysBottomUp( _ n: Int) -> Int { 22 | if n < 3 { return n } 23 | var dp = Array(repeating: 0, count: n + 1) 24 | 25 | dp[1] = 1 26 | dp[2] = 2 27 | 28 | for i in 3.. [[Int]] { 6 | var path = [[Int]]() 7 | 8 | func helper(_ node: TreeNode?) -> Int { 9 | if node == nil { return -1 } 10 | let maxDepth = max(helper(node?.left), helper(node?.right)) + 1 11 | if path.count == maxDepth { path.append([Int]()) } 12 | path[maxDepth].append(node!.val) 13 | return maxDepth 14 | } 15 | 16 | helper(root) 17 | 18 | return path 19 | } 20 | 21 | 22 | var leaf1 = TreeNode(4) 23 | var leaf2 = TreeNode(5) 24 | var leaf3 = TreeNode(3) 25 | var node = TreeNode(2, leaf1, leaf2) 26 | var root = TreeNode(1, node, leaf3) 27 | 28 | 29 | findLeaves(root) 30 | -------------------------------------------------------------------------------- /ProblemSolving.playground/Pages/LongestCommonPrefix.xcplaygroundpage/Contents.swift: -------------------------------------------------------------------------------- 1 | import Foundation 2 | 3 | //14 4 | func longestCommonPrefix(_ strs: [String]) -> String { 5 | if strs.isEmpty { return "" } 6 | if strs.count == 1 { return strs.first!} 7 | 8 | var commonPrefix = strs[0] 9 | for str in strs.dropFirst() { 10 | commonPrefix = common(commonPrefix, str) 11 | if commonPrefix.isEmpty { return "" } 12 | } 13 | 14 | return commonPrefix 15 | } 16 | 17 | func common(_ str1: String, _ str2: String) -> String { 18 | if str1 == str2 { return str1 } 19 | var commonPrefix = str1 20 | 21 | while !commonPrefix.isEmpty { 22 | if str2.hasPrefix(commonPrefix) { return commonPrefix } 23 | commonPrefix = String(commonPrefix.dropLast()) 24 | } 25 | 26 | return commonPrefix 27 | } 28 | 29 | longestCommonPrefix(["flower","flow","flight"]) 30 | -------------------------------------------------------------------------------- /ProblemSolving.playground/Pages/MinIndexSumOfTwoList.xcplaygroundpage/Contents.swift: -------------------------------------------------------------------------------- 1 | import Foundation 2 | 3 | /// 599 4 | func findRestaurant(_ list1: [String], _ list2: [String]) -> [String] { 5 | 6 | var leastIndexSum = Int.max 7 | var commons = [(String,Int)]() 8 | var result = [String]() 9 | let dict2 = list2.enumerated().reduce(into: [String: Int]()){ (map, data) in map[data.element] = data.offset } 10 | 11 | for index1 in 0.. Bool; 4 | */ 5 | 6 | class Solution : Relation { 7 | func findCelebrity(_ n: Int) -> Int { 8 | var candidate = 0 9 | 10 | for people in 0.. Bool { 24 | for people in 0.. [[Int]] { 5 | 6 | if intervals.isEmpty { return [] } 7 | 8 | let intervals = intervals.sorted{ $0[0] < $1[0] } 9 | var currentInterval = intervals[0] 10 | var mergedIntervals = [[Int]]() 11 | 12 | for interval in intervals[1..= interval[0] { 14 | currentInterval[1] = max(currentInterval[1], interval[1]) 15 | } else { 16 | mergedIntervals.append(currentInterval) 17 | currentInterval = interval 18 | } 19 | } 20 | mergedIntervals.append(currentInterval) 21 | 22 | return mergedIntervals 23 | } 24 | 25 | 26 | merge([[1,3],[2,6],[8,10],[15,18]]) 27 | merge([[1,4],[4,5]]) 28 | merge([[1,4]]) 29 | merge([[1,4],[2,3]]) 30 | 31 | 32 | -------------------------------------------------------------------------------- /ProblemSolving.playground/Pages/GenerateParenthesis.xcplaygroundpage/Contents.swift: -------------------------------------------------------------------------------- 1 | import Foundation 2 | 3 | /// 22 4 | // O((4^n)/sqrt(n) 5 | func generateParethesis (n:Int) ->[String] { 6 | if n == 0 { return [] } 7 | var allCombinations = [String]() 8 | backTracking(&allCombinations, "", 0, 0, max: n) 9 | return allCombinations 10 | } 11 | 12 | 13 | func backTracking(_ allCombinations: inout [String], _ combination: String, _ open: Int, _ close: Int, max: Int) { 14 | if 2 * max == combination.count { allCombinations.append(combination) } 15 | else { 16 | if open < max { 17 | backTracking(&allCombinations, combination + "(", open + 1, close, max: max) 18 | } 19 | if close < open { 20 | backTracking(&allCombinations, combination + ")", open , close + 1, max: max) 21 | } 22 | } 23 | } 24 | 25 | generateParethesis(n: 1) 26 | 27 | 28 | -------------------------------------------------------------------------------- /Trees/106-ConstructPostInorderTree.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | var preOrderIndex = 0 3 | var inOrderIndexDict = [Int: Int]() 4 | 5 | func buildTree(_ inorder: [Int], _ postorder: [Int]) -> TreeNode? { 6 | for i in 0.. TreeNode? { 15 | guard left <= right else { return nil } 16 | 17 | let rootIndex = inOrderIndexDict[postorder[preOrderIndex]]! 18 | let rootVal = postorder[preOrderIndex] 19 | preOrderIndex -= 1 20 | 21 | let rightTree = buildTree(postorder, rootIndex + 1, right) 22 | let leftTree = buildTree(postorder, left, rootIndex - 1) 23 | 24 | 25 | return TreeNode(rootVal, leftTree, rightTree) 26 | 27 | } 28 | } -------------------------------------------------------------------------------- /Trees/637-AvgOfBinaryTree.swift: -------------------------------------------------------------------------------- 1 | func averageOfLevels(_ root: TreeNode?) -> [Double] { 2 | guard let root = root else { return [] } 3 | var queue = [TreeNode]() 4 | queue.append(root) 5 | var result = [Double]() 6 | 7 | 8 | while !queue.isEmpty { 9 | var newChildren = [TreeNode]() 10 | 11 | let count = queue.count 12 | var sum = 0 13 | 14 | for node in queue { 15 | sum += node.val 16 | 17 | if let leftChild = node.left { 18 | newChildren.append(leftChild) 19 | } 20 | 21 | if let rightChild = node.right { 22 | newChildren.append(rightChild) 23 | } 24 | 25 | } 26 | 27 | result.append(Double(sum)/Double(count)) 28 | queue = newChildren 29 | } 30 | 31 | 32 | return result 33 | } 34 | -------------------------------------------------------------------------------- /DP/01Knapsack-Unbounded/343-IntegerBreak.swift: -------------------------------------------------------------------------------- 1 | /* 2 | Given an integer n, break it into the sum of k positive integers, where k >= 2, and maximize the product of those integers. 3 | 4 | Return the maximum product you can get. 5 | 6 | Example 1: 7 | 8 | Input: n = 2 9 | Output: 1 10 | Explanation: 2 = 1 + 1, 1 × 1 = 1. 11 | 12 | Example 2: 13 | 14 | Input: n = 10 15 | Output: 36 16 | Explanation: 10 = 3 + 3 + 4, 3 × 3 × 4 = 36. 17 | 18 | 19 | 20 | 3 + 1 = 3 21 | 2 + 2 = 4 22 | 1 + 3 = 3 23 | */ 24 | 25 | func integerBreak(_ n: Int) -> Int { 26 | var dp = Array(repeating: 0, count: n + 1) 27 | dp[1] = 1 28 | 29 | for i in 1...n { 30 | for j in 1.. Int { 2 | guard nums.count > 1 else { return nums[0] } 3 | //var dp = Array(repeating: -1, count: nums.count) 4 | 5 | var n0 = nums[0] 6 | var n1 = max(nums[0], nums[1]) 7 | 8 | for house in 2.. Int { 19 | if nums.count == 1 { return nums[0] } 20 | if nums.count == 2 { return max(nums[0], nums[1]) } 21 | 22 | let houseWithFirst = Array(nums.dropLast()) 23 | let houseWithoutFirst = Array(nums.dropFirst()) 24 | 25 | return max(robUtils(houseWithFirst), robUtils(houseWithoutFirst)) 26 | } 27 | 28 | rob([2,3,2]) 29 | rob([1,2,3,1]) 30 | rob([1,2,3]) 31 | -------------------------------------------------------------------------------- /LinkList/142-LinkListCycle2.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func detectCycle(_ head: ListNode?) -> ListNode? { 3 | guard let head = head else { return nil } 4 | var ptr1 = intersection(head) 5 | 6 | if ptr1 == nil { return nil } 7 | 8 | var ptr2: ListNode? = head 9 | 10 | while ptr1 !== ptr2 { 11 | ptr1 = ptr1?.next 12 | ptr2 = ptr2?.next 13 | } 14 | 15 | return ptr1 16 | } 17 | 18 | func intersection(_ head: ListNode?) -> ListNode? { 19 | var fast = head 20 | var slow = head 21 | 22 | while (fast != nil && fast?.next != nil) { 23 | slow = slow?.next 24 | fast = fast?.next?.next 25 | 26 | if fast === slow { 27 | return fast 28 | } 29 | } 30 | 31 | return nil 32 | } 33 | } -------------------------------------------------------------------------------- /DP/LongestCommonSubsequence/583-DeleteOperationForTwoString.swift: -------------------------------------------------------------------------------- 1 | // 583 2 | func minDistance(_ word1: String, _ word2: String) -> Int { 3 | var dp = Array(repeating: Array(repeating: -1, count: word2.count + 1), count: word1.count + 1) 4 | let word1 = Array(word1), word2 = Array(word2) 5 | let lcs = lcsUtil(word1, word2, word1.count, word2.count, &dp) 6 | return word1.count + word2.count - (2 * lcs) 7 | } 8 | 9 | func lcsUtil(_ text1: Array, _ text2: Array, _ p1: Int, _ p2: Int, _ cache: inout [[Int]] ) -> Int { 10 | if p1 == 0 || p2 == 0 { return 0 } 11 | if cache[p1][p2] != -1 { return cache[p1][p2] } 12 | if text1[p1 - 1] == text2[p2 - 1] { cache[p1][p2] = 1 + lcsUtil(text1, text2, p1 - 1, p2 - 1, &cache) } 13 | else { cache[p1][p2] = max(lcsUtil(text1, text2, p1 - 1, p2, &cache), lcsUtil(text1, text2, p1, p2 - 1, &cache)) } 14 | return cache[p1][p2] 15 | } -------------------------------------------------------------------------------- /OA/12-intToRoman.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func intToRoman( _ number: Int) -> String { 3 | 4 | let numbers = [1, 4, 5, 9, 5 | 10, 40, 50, 90, 6 | 100, 400, 500, 900, 7 | 1000] 8 | 9 | let symbols = ["I", "IV", "V", "IX", 10 | "X", "XL", "L", "XC", 11 | "C", "CD", "D", "CM", 12 | "M"] 13 | 14 | var roman = "" 15 | var number = number 16 | 17 | for index in stride(from: numbers.count - 1, to: -1, by: -1) { 18 | let freq = number / numbers[index] 19 | number = number % numbers[index] 20 | let romanSymbols = String(repeating: symbols[index], 21 | count: freq) 22 | roman.append(romanSymbols) 23 | } 24 | 25 | return roman 26 | } 27 | } -------------------------------------------------------------------------------- /Trees/1430-ValidSequence.swift: -------------------------------------------------------------------------------- 1 | func isValidSequence(_ root: TreeNode?, _ arr: [Int]) -> Bool { 2 | guard let root = root else { return false } 3 | return isValidSequence(root, arr, 0) 4 | } 5 | 6 | func isValidSequence(_ root: TreeNode?, _ arr: [Int], _ index: Int) -> Bool { 7 | guard let root = root else { return false } 8 | 9 | if index > arr.count - 1 { 10 | return false 11 | } 12 | 13 | if root.val != arr[index] { 14 | return false 15 | } 16 | 17 | if root.left == nil && root.right == nil { 18 | if index != arr.count - 1 { 19 | return false 20 | } else { 21 | return true 22 | } 23 | } 24 | 25 | return isValidSequence(root.left, arr, index + 1) || isValidSequence(root.right, arr, index + 1) 26 | 27 | } -------------------------------------------------------------------------------- /DP/LongestCommonSubsequence/MinDeleteionAndInsertionToTransformToOtherString.swift: -------------------------------------------------------------------------------- 1 | func longestCommonSubsequence(_ text1: String, _ text2: String) -> Int { 2 | let text1 = Array(text1) 3 | let text2 = Array(text2) 4 | var dp = Array(repeating: Array(repeating: 0, count: text2.count + 1), count: text1.count + 1) 5 | 6 | 7 | for l1 in 1...text1.count { 8 | for l2 in 1...text2.count { 9 | if text1[l1 - 1] == text2[l2 - 1] { 10 | dp[l1][l2] = dp[l1 - 1][l2 - 1] + 1 11 | } else { 12 | dp[l1][l2] = max(dp[l1 - 1][l2], dp[l1][l2 - 1]) 13 | } 14 | } 15 | } 16 | return dp[text1.count][text2.count] 17 | } 18 | 19 | func findMDI(_ str1: String, _ str2: String) -> (deletes: Int, inserts: Int) { 20 | let maxSubseqLength = longestCommonSubsequence(str1, str2) 21 | return (str1.count - maxSubseqLength, str2.count - maxSubseqLength) 22 | } -------------------------------------------------------------------------------- /ProblemSolving.playground/Pages/CompressString.xcplaygroundpage/Contents.swift: -------------------------------------------------------------------------------- 1 | 2 | import Foundation 3 | /// 443 4 | 5 | func compress(_ chars: inout [Character]) -> Int { 6 | if chars.count == 1 { return 1 } 7 | 8 | var readPtr = 0, writePtr = 0 9 | 10 | while readPtr < chars.count { 11 | var totalLength = 0 12 | let char = chars[readPtr] 13 | 14 | while readPtr < chars.count && chars[readPtr] == char { 15 | readPtr += 1 16 | totalLength += 1 17 | } 18 | 19 | chars[writePtr] = char 20 | writePtr += 1 21 | 22 | if totalLength > 1 { 23 | for digit in String(totalLength) { 24 | chars[writePtr] = digit 25 | writePtr += 1 26 | } 27 | } 28 | } 29 | 30 | return writePtr 31 | 32 | } 33 | 34 | var chars: [Character] = ["a","a","b","b","c","c","c"] 35 | compress(&chars) 36 | 37 | -------------------------------------------------------------------------------- /ProblemSolving.playground/Pages/strStr.xcplaygroundpage/Contents.swift: -------------------------------------------------------------------------------- 1 | //: [Previous](@previous) 2 | 3 | import Foundation 4 | 5 | //28 6 | func strStr(_ haystack: String, _ needle: String) -> Int { 7 | 8 | if haystack == needle || needle.isEmpty { return 0 } 9 | if haystack.count <= needle.count || haystack.isEmpty { return -1 } 10 | 11 | let haystack = Array(haystack) 12 | let needle = Array(needle) 13 | 14 | var index = 0 15 | 16 | while index < haystack.count{ 17 | if haystack[index] == needle[0] { 18 | var needleIndex = 0 19 | while index + needleIndex < haystack.count && haystack[index + needleIndex] == needle[needleIndex] { 20 | needleIndex += 1 21 | if needleIndex == needle.count { return index } 22 | } 23 | } 24 | 25 | index += 1 26 | } 27 | 28 | return -1 29 | 30 | } 31 | 32 | strStr("abc", "c") 33 | -------------------------------------------------------------------------------- /CTCI/Graph And Tree/4.1 - RoutesBetween2Nodes.swift: -------------------------------------------------------------------------------- 1 | /// 4.1 Route Between Nodes: Given a directed graph, design an algorithm to find out whether there is a route between two nodes. 2 | 3 | func hasRoute(_ source: Int, _ target: Int, graph: [[Int]]) -> Bool { 4 | var visited = Set() 5 | return depthFirstSearch(source, target, graph, &visited) 6 | } 7 | 8 | func depthFirstSearch(_ current: Int, _ target: Int, _ graph: [[Int]], _ visited: inout Set) -> Bool { 9 | visited.insert(current) 10 | 11 | if current == target { return true } 12 | 13 | for neighbor in graph[current] { 14 | if !visited.contains(neighbor) && depthFirstSearch(neighbor, target, graph, &visited) { 15 | return true 16 | } 17 | } 18 | 19 | visited.remove(current) 20 | return false 21 | } 22 | 23 | let graph = [[1,2], [0], [3], [0], [5], [0]] 24 | 25 | 26 | print(hasRoute(3, 1, graph: graph)) 27 | -------------------------------------------------------------------------------- /TwoSum/3Sum/16-3SumClosest.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func threeSumClosest(_ nums: [Int], _ target: Int) -> Int { 3 | var minDiff = Int.max 4 | let nums = nums.sorted() 5 | 6 | for (index, value) in nums.enumerated() { 7 | var left = index + 1 8 | var right = nums.count - 1 9 | 10 | while left < right { 11 | 12 | let sum = nums[right] + nums[left] + value 13 | let diff = target - sum 14 | 15 | if diff == 0 { 16 | return target 17 | } 18 | 19 | if abs(diff) < abs(minDiff) { 20 | minDiff = diff 21 | } 22 | 23 | if sum < target { 24 | left += 1 25 | } else { 26 | right -= 1 27 | } 28 | } 29 | } 30 | 31 | return target - minDiff 32 | } 33 | 34 | 35 | 36 | } -------------------------------------------------------------------------------- /DP/Matrix/63-UniquePaths2.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func uniquePathsWithObstacles(_ obstacleGrid: [[Int]]) -> Int { 3 | 4 | var memo = Array(repeating: Array(repeating: -1, count: obstacleGrid[0].count), 5 | count: obstacleGrid.count) 6 | 7 | return calUniquePaths(obstacleGrid, obstacleGrid.count - 1, obstacleGrid[0].count - 1, &memo) 8 | } 9 | 10 | func calUniquePaths(_ grid: [[Int]], _ row: Int, _ col : Int, _ memo: inout [[Int]]) -> Int { 11 | 12 | if row == 0 && col == 0 { 13 | return grid[row][col] == 0 ? 1 : 0 14 | } 15 | 16 | if row < 0 || col < 0 { return 0 } 17 | 18 | if grid[row][col] == 1 { 19 | return 0 20 | } 21 | 22 | if memo[row][col] == -1 { 23 | memo[row][col] = calUniquePaths(grid,row, col - 1, &memo) + calUniquePaths(grid,row - 1, col, &memo) 24 | } 25 | 26 | return memo[row][col] 27 | } 28 | } -------------------------------------------------------------------------------- /Mix/593-ValidSquare.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func calDistance(_ p1: [Int], _ p2: [Int]) -> Int { 3 | (p2[1] - p1[1]) * (p2[1] - p1[1]) + (p2[0] - p1[0]) * (p2[0] - p1[0]) 4 | } 5 | 6 | func validSquare(_ p1: [Int], _ p2: [Int], _ p3: [Int], _ p4: [Int]) -> Bool { 7 | var points = [p1, p2, p3, p4] 8 | points.sort { $0[0] < $1[0] || $0[0] == $1[0] && $0[1] < $1[1] } 9 | 10 | if calDistance(points[0], points[3]) != calDistance(points[1], points[2]) { 11 | return false 12 | } 13 | 14 | let distance1 = calDistance(points[0], points[1]) 15 | let distance2 = calDistance(points[0], points[2]) 16 | let distance3 = calDistance(points[3], points[2]) 17 | let distance4 = calDistance(points[3], points[1]) 18 | 19 | 20 | return ( distance1 != 0 21 | && distance1 == distance2 22 | && distance2 == distance3 23 | && distance3 == distance4 ) 24 | 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Combinatorics And Backtracking/784-LetterCasePermutation.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func letterCasePermutation(_ s: String) -> [String] { 3 | var result = [String]() 4 | findLetterCasePermutation(Array(s), 0, "", &result) 5 | return result 6 | } 7 | 8 | 9 | func findLetterCasePermutation(_ word: [Character], _ index: Int, _ permutation: String ,_ result: inout [String]) { 10 | 11 | if index == word.count { 12 | result.append(permutation) 13 | return 14 | } 15 | if word[index].isNumber { 16 | let permutation = permutation + String(word[index]) 17 | findLetterCasePermutation(word, index + 1, permutation, &result) 18 | } else { 19 | findLetterCasePermutation(word, index + 1, permutation + word[index].lowercased(), &result) 20 | 21 | findLetterCasePermutation(word, index + 1, permutation + word[index].uppercased(), &result) 22 | } 23 | 24 | 25 | } 26 | 27 | } -------------------------------------------------------------------------------- /DP/Fibnumber/45-JumpGame2.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | var memo = [Int: Int]() 3 | 4 | func jump(_ nums: [Int]) -> Int { 5 | minJumps(nums, 0) 6 | } 7 | 8 | func minJumps(_ nums: [Int], _ curr: Int) -> Int { 9 | 10 | if curr >= nums.count - 1 { 11 | return 0 12 | } 13 | 14 | if nums[curr] == 0 { 15 | return Int.max 16 | } 17 | 18 | if let totalJumps = memo[curr] { 19 | return totalJumps 20 | } 21 | 22 | var totalJumps = Int.max 23 | 24 | for jump in 1...nums[curr] { 25 | let tempJump = minJumps(nums, curr + jump) 26 | if tempJump != Int.max { 27 | totalJumps = min(totalJumps, tempJump + 1) 28 | } 29 | } 30 | 31 | memo[curr] = totalJumps 32 | 33 | return totalJumps 34 | 35 | } 36 | } -------------------------------------------------------------------------------- /Graph/Connected Component/200-NumIslands.swift: -------------------------------------------------------------------------------- 1 | func numIslands(_ grid: [[Character]]) -> Int { 2 | var grid = grid 3 | var totalIslands = 0 4 | 5 | for row in 0.. grid.count - 1 || col < 0 || col > grid[0].count - 1 || grid[row][col] == "0" { 20 | return 21 | } 22 | 23 | grid[row][col] = "0" 24 | 25 | findNumberOfIslands(&grid, row - 1, col) 26 | findNumberOfIslands(&grid, row + 1, col) 27 | findNumberOfIslands(&grid, row, col - 1) 28 | findNumberOfIslands(&grid, row, col + 1) 29 | 30 | } 31 | -------------------------------------------------------------------------------- /Maths/593-ValidSquare.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func calDistance(_ p1: [Int], _ p2: [Int]) -> Int { 3 | (p2[1] - p1[1]) * (p2[1] - p1[1]) + (p2[0] - p1[0]) * (p2[0] - p1[0]) 4 | } 5 | 6 | func validSquare(_ p1: [Int], _ p2: [Int], _ p3: [Int], _ p4: [Int]) -> Bool { 7 | var points = [p1, p2, p3, p4] 8 | points.sort { $0[0] < $1[0] || $0[0] == $1[0] && $0[1] < $1[1] } 9 | 10 | if calDistance(points[0], points[3]) != calDistance(points[1], points[2]) { 11 | return false 12 | } 13 | 14 | let distance1 = calDistance(points[0], points[1]) 15 | let distance2 = calDistance(points[0], points[2]) 16 | let distance3 = calDistance(points[3], points[2]) 17 | let distance4 = calDistance(points[3], points[1]) 18 | 19 | 20 | return ( distance1 != 0 21 | && distance1 == distance2 22 | && distance2 == distance3 23 | && distance3 == distance4 ) 24 | 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Trees/250-CountOfUnivalSubtree.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | var count = 0 3 | 4 | func countUnivalSubtrees(_ root: TreeNode?) -> Int { 5 | isUnivalSubtree(root) 6 | return count 7 | } 8 | 9 | func isUnivalSubtree(_ root: TreeNode?) -> Bool { 10 | guard let root = root else { return true } 11 | 12 | if root.left == nil && root.right == nil { 13 | count += 1 14 | return true 15 | } 16 | 17 | let isLeftUnival = isUnivalSubtree(root.left) 18 | let isRightUnival = isUnivalSubtree(root.right) 19 | 20 | if (!isLeftUnival || !isRightUnival) { return false } 21 | 22 | if let left = root.left, left.val != root.val { return false } 23 | 24 | if let right = root.right, right.val != root.val { return false } 25 | 26 | count += 1 27 | return true 28 | 29 | } 30 | } -------------------------------------------------------------------------------- /CTCI/Graph And Tree/4.10-CheckSubtree.swift: -------------------------------------------------------------------------------- 1 | func isSubtree(_ root: TreeNode?, _ subRoot: TreeNode?) -> Bool { 2 | if root == nil && subRoot == nil { return true } 3 | 4 | guard let subRoot = subRoot, 5 | let root = root 6 | else { return false } 7 | 8 | if isIdentical(root, subRoot) { 9 | return true 10 | } 11 | 12 | return isSubtree(root.left, subRoot) || isSubtree(root.right, subRoot) 13 | } 14 | 15 | func isIdentical(_ root: TreeNode?, _ subRoot: TreeNode?) -> Bool { 16 | if root == nil && subRoot == nil { return true } 17 | 18 | guard let subRoot = subRoot, 19 | let root = root 20 | else { return false } 21 | 22 | 23 | return subRoot.val == root.val && 24 | isIdentical(root.left, subRoot.left) && 25 | isIdentical(root.right, subRoot.right) 26 | 27 | } -------------------------------------------------------------------------------- /Combinatorics And Backtracking/22-GenerateParanthesis.swift: -------------------------------------------------------------------------------- 1 | func generateParenthesis(_ n: Int) -> [String] { 2 | var allParenthesis = [String]() 3 | bracketGenerator(n, 0, 0, "", &allParenthesis) 4 | return allParenthesis 5 | } 6 | 7 | func bracketGenerator(_ total: Int, 8 | _ openBracket: Int, 9 | _ closeBracket: Int, 10 | _ parenthesis: String, 11 | _ allParenthesis: inout [String]) { 12 | 13 | if parenthesis.count == 2 * total { 14 | allParenthesis.append(parenthesis) 15 | } else { 16 | if openBracket < total { 17 | bracketGenerator(total, openBracket + 1, closeBracket, parenthesis + "(", &allParenthesis) 18 | } 19 | 20 | if closeBracket < openBracket { 21 | bracketGenerator(total, openBracket, closeBracket + 1, parenthesis + ")", &allParenthesis) 22 | 23 | } 24 | } 25 | } -------------------------------------------------------------------------------- /Graph/1706-WhereWillTheBallFall.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func findBall(_ grid: [[Int]]) -> [Int] { 3 | var result = [Int]() 4 | 5 | for col in 0.. Int { 13 | if row == grid.count { 14 | return col 15 | } 16 | 17 | if isStuck(row, col, grid) { 18 | return -1 19 | } 20 | 21 | return canFallOut(row + 1, col + grid[row][col], grid) 22 | } 23 | 24 | func isStuck(_ row: Int, _ col: Int, _ grid: [[Int]]) -> Bool { 25 | if col == 0 && grid[row][col] == -1 26 | || col == grid[0].count - 1 && grid[row][col] == 1 27 | || grid[row][col] == 1 && grid[row][col + 1] == -1 28 | || grid[row][col] == -1 && grid[row][col - 1] == 1 { 29 | return true 30 | } 31 | 32 | return false 33 | } 34 | } 35 | 36 | -------------------------------------------------------------------------------- /Graph/261-GraphValidTree.swift: -------------------------------------------------------------------------------- 1 | func validTree(_ n: Int, _ edges: [[Int]]) -> Bool { 2 | guard n - 1 == edges.count else { return false } 3 | var graph = Array(repeating: [Int](), count: n) 4 | var visited = Set() 5 | 6 | for edge in edges { 7 | graph[edge[0]].append(edge[1]) 8 | graph[edge[1]].append(edge[0]) 9 | } 10 | 11 | return !hasCycle(graph, 0, -1, &visited) && visited.count == n 12 | } 13 | 14 | func hasCycle(_ graph: [[Int]], _ currentNode: Int, _ parentNode: Int, _ visited: inout Set) -> Bool { 15 | 16 | visited.insert(currentNode) 17 | 18 | for child in graph[currentNode] { 19 | if !visited.contains(child) { 20 | if hasCycle(graph, child, currentNode, &visited) { 21 | return true 22 | } 23 | } else if parentNode != child { 24 | return true 25 | } 26 | } 27 | 28 | return false 29 | } 30 | -------------------------------------------------------------------------------- /OA/909-SnakesAndLadder.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | func snakesAndLadders(_ board: [[Int]]) -> Int { 4 | let length = board.count 5 | var stepMap: [Int : Int] = [1:0] 6 | var queue = [1] 7 | 8 | func get(_ num: Int) -> Int { 9 | let quot = (num - 1) / length // 4 10 | let rem = (num - 1) % length // 0 11 | let row = length - 1 - quot // 4 12 | let col = (length - row) % 2 == 1 ? rem : (length - 1 - rem) 13 | return board[row][col] == -1 ? num : board[row][col] 14 | } 15 | 16 | while !queue.isEmpty { 17 | let s = queue.removeFirst() 18 | if s == length * length { 19 | return stepMap[s]! 20 | } 21 | 22 | for i in 1...6 { 23 | if s + i > length * length { 24 | break 25 | } 26 | else { 27 | let s2 = get(s + i) 28 | if stepMap[s2] == nil { 29 | stepMap[s2] = stepMap[s]! + 1 30 | queue.append(s2) 31 | } 32 | } 33 | } 34 | } 35 | return -1 36 | } 37 | } -------------------------------------------------------------------------------- /Greedy/135-Candy.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func candy(_ ratings: [Int]) -> Int { 3 | 4 | var leftCandies = Array(repeating: 1, count: ratings.count) 5 | var rightCandies = Array(repeating: 1, count: ratings.count) 6 | var minCandies = 0 7 | 8 | for index in 1.. ratings[index - 1] { 10 | leftCandies[index] = leftCandies[index - 1] + 1 11 | } 12 | } 13 | 14 | for index in stride(from: ratings.count-2, to: -1, by: -1) { 15 | if ratings[index] > ratings[index + 1] { 16 | rightCandies[index] = rightCandies[index + 1] + 1 17 | } 18 | } 19 | 20 | for (leftCandy, rightCandy) in zip(leftCandies, rightCandies) { 21 | minCandies += max(leftCandy, rightCandy) 22 | } 23 | 24 | return minCandies 25 | } 26 | } 27 | 28 | -------------------------------------------------------------------------------- /OA/939-CousingInBinTree.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func isCousins(_ root: TreeNode?, _ x: Int, _ y: Int) -> Bool { 3 | var queue = [root] 4 | 5 | while !queue.isEmpty { 6 | let count = queue.count 7 | var foundIndex = [Int]() 8 | 9 | for i in 0.. [[Int]] { 3 | var comb = [Int]() 4 | var allComb = [[Int]]() 5 | calCombination(k, n, 1, &comb, &allComb) 6 | return allComb 7 | } 8 | 9 | func calCombination(_ k: Int, 10 | _ target: Int, 11 | _ start: Int, 12 | _ comb: inout [Int], 13 | _ allCombination: inout [[Int]]) { 14 | 15 | if k == comb.count && target == 0 { 16 | allCombination.append(comb) 17 | return 18 | } 19 | 20 | if target < 0 || k == comb.count { 21 | return 22 | } 23 | 24 | if start < 10 { 25 | for num in start...9 { 26 | comb.append(num) 27 | calCombination(k, target - num, num + 1, &comb, &allCombination) 28 | comb.removeLast() 29 | } 30 | } 31 | 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /DP/Fibnumber/256-PaintHouse.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | var memo = [String: Int]() 3 | 4 | func minCost(_ costs: [[Int]]) -> Int { 5 | getMinCost(costs, 0, -1) 6 | } 7 | 8 | func getMinCost(_ costs: [[Int]], _ current: Int, _ chosenColor: Int) -> Int { 9 | if current == costs.count { 10 | return 0 11 | } 12 | 13 | let key = "\(current)-\(chosenColor)" 14 | var minCost = Int.max 15 | 16 | if memo[key] == nil { 17 | let houseCosts = costs[current] 18 | 19 | for (color, thisColorCost) in houseCosts.enumerated() { 20 | if color != chosenColor { 21 | let costOfChoosingThisColor = getMinCost(costs, current + 1, color) 22 | minCost = min(minCost, costOfChoosingThisColor + thisColorCost) 23 | } 24 | } 25 | memo[key] = minCost 26 | } 27 | 28 | return memo[key]! 29 | } 30 | } -------------------------------------------------------------------------------- /Mix/346-MovingAverages.swift: -------------------------------------------------------------------------------- 1 | class MovingAverage { 2 | 3 | /** Initialize your data structure here. */ 4 | var queue = [Double]() 5 | let size: Int 6 | var front = -1 7 | var rear = -1 8 | var sum = 0.0 9 | 10 | init(_ size: Int) { 11 | self.size = size 12 | } 13 | 14 | func next(_ val: Int) -> Double { 15 | enque(Double(val)) 16 | return sum/Double(queueSize()) 17 | } 18 | 19 | private func enque(_ val: Double) { 20 | rear += 1 21 | if front == -1 { 22 | front = 0 23 | } else if queueSize() > size { 24 | sum -= queue[front] 25 | front += 1 26 | } 27 | queue.append(val) 28 | sum += val 29 | } 30 | 31 | private func queueSize() -> Int { rear - front + 1} 32 | } 33 | 34 | let averages = MovingAverage(3) 35 | averages.next(1) 36 | averages.next(10) 37 | averages.next(3) 38 | averages.next(5) 39 | -------------------------------------------------------------------------------- /ProblemSolving.playground/Pages/MinStack.xcplaygroundpage/Contents.swift: -------------------------------------------------------------------------------- 1 | import Foundation 2 | 3 | /// 155 https://leetcode.com/problems/min-stack/ 4 | 5 | 6 | class MinStack { 7 | var array: [Int] 8 | var minStack: [Int] 9 | /** initialize your data structure here. */ 10 | init() { 11 | array = [] 12 | minStack = [] 13 | } 14 | 15 | func push(_ x: Int) { 16 | array.append(x) 17 | guard let y = minStack.last else { 18 | minStack.append(x) 19 | return 20 | } 21 | minStack.append( y < x ? y : x) 22 | } 23 | 24 | func pop() { 25 | array.popLast() 26 | minStack.popLast() 27 | } 28 | 29 | func top() -> Int { return array.last! } 30 | 31 | func getMin() -> Int { 32 | return minStack.last! 33 | } 34 | } 35 | 36 | let min = MinStack() 37 | min.push(0) 38 | min.push(1) 39 | min.push(0) 40 | 41 | min.getMin() 42 | min.pop() 43 | -------------------------------------------------------------------------------- /Trees/437-PathSum3.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | var dict = [Int: Int]() 3 | var count = 0 4 | 5 | func pathSum(_ root: TreeNode?, _ targetSum: Int) -> Int { 6 | var prefixSum = 0 7 | pathSum(root, targetSum, prefixSum) 8 | return count 9 | } 10 | 11 | func pathSum(_ root: TreeNode?, _ target: Int, _ prefixSum: Int) { 12 | guard let root = root else { return } 13 | 14 | let prefixSum = prefixSum + root.val 15 | 16 | if prefixSum == target { 17 | count += 1 18 | } 19 | 20 | if let otherCount = dict[prefixSum - target] { 21 | count += otherCount 22 | } 23 | 24 | dict[prefixSum] = dict[prefixSum, default: 0] + 1 25 | 26 | pathSum(root.left, target, prefixSum) 27 | pathSum(root.right, target, prefixSum) 28 | 29 | dict[prefixSum] = dict[prefixSum, default: 0] - 1 30 | } 31 | } -------------------------------------------------------------------------------- /Graph/riversize.swift: -------------------------------------------------------------------------------- 1 | // https://www.algoexpert.io/questions/River%20Sizes 2 | func riverSizes(_ matrix: [[Int]]) -> [Int] { 3 | var matrix = matrix 4 | var result = [Int]() 5 | for row in 0..= matrix.count || col >= matrix[0].count || matrix[row][col] != 1 { return } 19 | riverSize += 1 20 | matrix[row][col] = -1 21 | dfs(&matrix, row - 1, col, &riverSize) 22 | dfs(&matrix, row + 1, col, &riverSize) 23 | dfs(&matrix, row , col - 1, &riverSize) 24 | dfs(&matrix, row , col + 1, &riverSize) 25 | } 26 | -------------------------------------------------------------------------------- /ExpressionEvaluation/150-EvaluateReversePolishNotation.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func operations(_ token: String) -> (Int, Int) -> Int { 3 | switch token { 4 | case "+": return { $0 + $1 } 5 | case "-": return { $0 - $1 } 6 | case "*": return { $0 * $1 } 7 | case "/": return { $0 / $1 } 8 | default: fatalError("not possible") 9 | } 10 | } 11 | 12 | func evalRPN(_ tokens: [String]) -> Int { 13 | var stack = [Int]() 14 | 15 | for token in tokens { 16 | if let number = Int(token) { 17 | stack.append(number) 18 | } else { 19 | let secondNum = stack.removeLast() 20 | let firstNum = stack.removeLast() 21 | let operation = operations(token) 22 | stack.append(operation(firstNum, secondNum)) 23 | } 24 | } 25 | 26 | return stack.removeLast() 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Graph/1376-TimeNeededToInformAllEmployees.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func numOfMinutes(_ n: Int, _ headID: Int, _ manager: [Int], _ informTime: [Int]) -> Int { 3 | var graph = [Int: [Int]]() 4 | 5 | for employee in 0.. [String] { 7 | var allPermutations = [String]() 8 | let charArr = Array(S) 9 | backtrack(0, "", &allPermutations, S: charArr) 10 | return allPermutations 11 | } 12 | 13 | 14 | func backtrack(_ index: Int, _ string: String, _ allPermutations : inout [String], S: Array) { 15 | print("a") 16 | if string.count == S.count { 17 | allPermutations.append(string) 18 | return 19 | } 20 | if S[index].isNumber { backtrack(index + 1, string + "\(S[index])", &allPermutations, S: S) } 21 | else { 22 | backtrack(index + 1, string + S[index].lowercased(), &allPermutations, S: S) 23 | backtrack(index + 1, string + S[index].uppercased(), &allPermutations, S: S) 24 | } 25 | 26 | } 27 | 28 | letterCasePermutation("CA") 29 | 30 | 31 | -------------------------------------------------------------------------------- /SlidingWindow/992-SubarrayWithKDiffInt.swift: -------------------------------------------------------------------------------- 1 | /* 2 | The idea here is exactly(K) = atMost(k) - atMost(K-1) 3 | */ 4 | class Solution { 5 | func subarraysWithKDistinct(_ nums: [Int], _ k: Int) -> Int { 6 | let v1 = subarraysWithAtMostKDistinct(nums, k) 7 | let v2 = subarraysWithAtMostKDistinct(nums, k - 1) 8 | return v1 - v2 9 | } 10 | 11 | func subarraysWithAtMostKDistinct(_ nums: [Int], _ k: Int) -> Int { 12 | var start = 0 13 | var length = 0 14 | var map = [Int: Int]() 15 | 16 | for (end, num) in nums.enumerated() { 17 | map[num] = end 18 | 19 | if map.keys.count == k + 1 { 20 | let delIndex = map.values.min()! 21 | map[nums[delIndex]] = nil 22 | start = delIndex + 1 23 | } 24 | 25 | length += end - start 26 | } 27 | 28 | return length 29 | } 30 | 31 | } -------------------------------------------------------------------------------- /Stack And Queues/ParanthesisProblem/1249-Minimum RemovetoMakeValidParentheses.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func minRemoveToMakeValid(_ s: String) -> String { 3 | var stack = [Int]() 4 | var closeBracketIndex = Set() 5 | var result = "" 6 | 7 | for (index, char) in s.enumerated() { 8 | if char == "(" { 9 | stack.append(index) 10 | } else if char == ")" { 11 | if stack.isEmpty { 12 | closeBracketIndex.insert(index) 13 | } else { 14 | stack.removeLast() 15 | } 16 | } 17 | } 18 | 19 | closeBracketIndex = closeBracketIndex.union(stack) 20 | 21 | for (index, char) in s.enumerated() { 22 | if !closeBracketIndex.contains(index) { 23 | result.append(char) 24 | } 25 | } 26 | 27 | return result 28 | } 29 | 30 | } -------------------------------------------------------------------------------- /ProblemSolving.playground/Pages/FindJudge.xcplaygroundpage/Contents.swift: -------------------------------------------------------------------------------- 1 | 2 | import Foundation 3 | 4 | 5 | ///997 6 | 7 | func findJudge(_ N: Int, _ trust: [[Int]]) -> Int { 8 | 9 | var candidates = (1...N).reduce(into: Set()) { (set, val) in set.insert(val) } 10 | var trustCount = [Int: Int]() 11 | 12 | trust.forEach { (dependency) in 13 | let personWhoTrust = dependency[0] 14 | let personBeingTrusted = dependency[1] 15 | candidates.remove(personWhoTrust) 16 | trustCount[personBeingTrusted, default: 0] += 1 17 | } 18 | 19 | if candidates.count > 1 { return -1 } 20 | for candidate in candidates { 21 | if trustCount[candidate, default: 0] == N - 1 { return candidate } 22 | } 23 | 24 | return -1 25 | 26 | } 27 | 28 | findJudge(2, [[1,2]]) 29 | findJudge(3, [[1,3],[2,3]]) 30 | findJudge(3, [[1,3],[2,3],[3,1]]) 31 | findJudge(3, [[1,2],[2,3]]) 32 | findJudge(4, [[1,3],[1,4],[2,3],[2,4],[4,3]]) 33 | findJudge(1, []) 34 | -------------------------------------------------------------------------------- /ExpressionEvaluation/224-BasicCalculator.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | var index = 0 3 | 4 | func calculate(_ s: String) -> Int { 5 | evaluateExpression(Array(s.replacingOccurrences(of: " ", with: ""))) 6 | } 7 | 8 | func evaluateExpression(_ expression: [Character]) -> Int { 9 | guard index < expression.count else { return 0 } 10 | var number = 0 11 | var operand = 1 12 | var result = 0 13 | 14 | while index < expression.count { 15 | let char = expression[index] 16 | index += 1 17 | if char.isNumber { 18 | number = number * 10 + Int(String(char))! 19 | } else if char == "("{ 20 | number = evaluateExpression(expression) 21 | } else if char == ")" { 22 | break 23 | } else { 24 | result += number * operand 25 | number = 0 26 | operand = char == "+" ? 1 : -1 27 | } 28 | } 29 | 30 | return result + (number * operand) 31 | } 32 | 33 | } -------------------------------------------------------------------------------- /Graph/1306-JumpGame3.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func canReach(_ arr: [Int], _ start: Int) -> Bool { 3 | var queue = [start] 4 | var visited = Set() 5 | 6 | while !queue.isEmpty { 7 | let curr = queue.removeFirst() 8 | 9 | if arr[curr] == 0 { return true } 10 | 11 | visited.insert(curr) 12 | 13 | let nextIndex1 = curr + arr[curr] 14 | let nextIndex2 = curr - arr[curr] 15 | 16 | if nextIndex1 >= 0 17 | && nextIndex1 < arr.count 18 | && !visited.contains(nextIndex1) { 19 | queue.append(nextIndex1) 20 | } 21 | 22 | if nextIndex2 >= 0 23 | && nextIndex2 < arr.count 24 | && !visited.contains(nextIndex2) { 25 | queue.append(nextIndex2) 26 | } 27 | } 28 | 29 | return false 30 | 31 | } 32 | } -------------------------------------------------------------------------------- /Mix/13-RomanToInteger.swift: -------------------------------------------------------------------------------- 1 | /// 13 2 | 3 | func romanMapper(char: Character) -> Int { 4 | 5 | switch char { 6 | case "I": 7 | return 1 8 | case "V": 9 | return 5 10 | case "X": 11 | return 10 12 | case "L": 13 | return 50 14 | case "C": 15 | return 100 16 | case "D": 17 | return 500 18 | case "M": 19 | return 1000 20 | default: 21 | return -1 // return error case 22 | } 23 | } 24 | func romanToInt(_ s: String) -> Int { 25 | let romanNumber = Array(s) 26 | var index = 0 27 | var result = 0 28 | 29 | while index < romanNumber.count { 30 | let currentNum = romanMapper(char: romanNumber[index]) 31 | 32 | if (index < romanNumber.count - 1) { 33 | let nextNumber = romanMapper(char: romanNumber[index + 1]) 34 | result += currentNum < nextNumber ? -currentNum : currentNum 35 | } else { 36 | result += currentNum 37 | } 38 | 39 | index += 1 40 | } 41 | 42 | return result 43 | } 44 | -------------------------------------------------------------------------------- /MergeIntervals/2021-BrightestRoom.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func brightestPosition(_ lights: [[Int]]) -> Int { 3 | let startRanges = lights 4 | .map { $0[0] - $0[1] } 5 | .sorted() 6 | 7 | let endRanges = lights 8 | .map { $0[0] + $0[1] } 9 | .sorted() 10 | 11 | var startIndex = 0 12 | var endIndex = 0 13 | 14 | var currLights = 0 15 | var maxLights = 0 16 | var brightestArea = 0 17 | 18 | while startIndex < startRanges.count { 19 | let start = startRanges[startIndex] 20 | let end = endRanges[endIndex] 21 | 22 | if start > end { 23 | endIndex += 1 24 | currLights -= 1 25 | } 26 | 27 | currLights += 1 28 | startIndex += 1 29 | 30 | if currLights > maxLights { 31 | maxLights = currLights 32 | brightestArea = start 33 | } 34 | 35 | } 36 | return brightestArea 37 | 38 | } 39 | } -------------------------------------------------------------------------------- /Trees/314-VerticalOrder.swift: -------------------------------------------------------------------------------- 1 | func verticalOrder(_ root: TreeNode?) -> [[Int]] { 2 | guard let root = root else { return [] } 3 | 4 | var queue = [(node: root, column: 0)] 5 | var result = [[Int]]() 6 | var dict = [Int: [Int]]() 7 | var minCol = Int.max 8 | var maxCol = Int.min 9 | 10 | while !queue.isEmpty { 11 | let (node, column) = queue.removeFirst() 12 | dict[column, default: [Int]()].append(node.val) 13 | 14 | minCol = min(minCol, column) 15 | maxCol = max(maxCol, column) 16 | 17 | if let leftChild = node.left { 18 | queue.append((leftChild, column - 1)) 19 | } 20 | 21 | if let rightChild = node.right { 22 | queue.append((rightChild, column + 1)) 23 | } 24 | } 25 | 26 | 27 | for i in minCol...maxCol { 28 | if let child = dict[i] { 29 | result.append(child) 30 | } 31 | } 32 | 33 | return result 34 | } 35 | -------------------------------------------------------------------------------- /ArraysAndStrings/1347-MinStepsToMakeStringsAnagram.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func minSteps(_ s: String, _ t: String) -> Int { 3 | var sFreq = Array(repeating: 0, count: 26) 4 | var tFreq = Array(repeating: 0, count: 26) 5 | var steps = 0 6 | 7 | let characters = "abcdefghijklmnopqrstuvwxyz" 8 | 9 | for (sChar,tChar) in zip(s,t) { 10 | let sIndex = getIndex(sChar) 11 | let tIndex = getIndex(tChar) 12 | sFreq[sIndex] += 1 13 | tFreq[tIndex] += 1 14 | } 15 | 16 | 17 | for char in characters { 18 | let index = getIndex(char) 19 | if sFreq[index] > tFreq[index] { 20 | steps += sFreq[index] - tFreq[index] 21 | } 22 | } 23 | 24 | return steps 25 | } 26 | 27 | func getIndex(_ char: Character) -> Int { 28 | Int(String(char.asciiValue!))! - Int(String(Character("a").asciiValue!))! 29 | } 30 | } -------------------------------------------------------------------------------- /DP/0-1KnapSack/0-1knapsack.swift: -------------------------------------------------------------------------------- 1 | /// https://www.educative.io/courses/grokking-dynamic-programming-patterns-for-coding-interviews/RM1BDv71V60 2 | func knapsack(_ wt:[Int], _ val: [Int], _ totalWt: Int) -> Int{ 3 | var cache = Array(repeating: Array(repeating: -1, count: totalWt + 1), count: wt.count + 1) 4 | return knapsackRecursive(wt, val, totalWt, &cache, index: 0) 5 | } 6 | 7 | func knapsackRecursive(_ wt:[Int], _ val: [Int], _ totalWt: Int, _ cache: inout [[Int]], index: Int) -> Int { 8 | if totalWt <= 0 || index > wt.count - 1 { return 0 } 9 | if cache[index][totalWt] != -1 { return cache[index][totalWt] } 10 | var profit1 = 0 11 | if totalWt >= wt[index] { profit1 = val[index] + knapsackRecursive(wt, val, totalWt - wt[index], &cache, index: index + 1) } 12 | let profit2 = knapsackRecursive(wt, val, totalWt, &cache, index: index + 1) 13 | cache[index][totalWt] = max(profit1, profit2) 14 | return cache[index][totalWt] 15 | } 16 | 17 | knapsack([1, 2, 3, 5], [1, 6, 10, 16], 7) 18 | -------------------------------------------------------------------------------- /OA/minswaps.swift: -------------------------------------------------------------------------------- 1 | func minSwaps(_ data: [Int]) -> Int { 2 | let totalOnes = data.reduce(0, +) 3 | 4 | var currWindowOneCount = 0 5 | var start = 0 6 | var end = 0 7 | var swaps = Int.max 8 | 9 | while end < data.count { 10 | currWindowOneCount += data[start] 11 | end += 1 12 | if end - start > totalOnes { 13 | currWindowOneCount -= data[end] 14 | start += 1 15 | } 16 | 17 | swaps = min(swaps, currWindowOneCount) 18 | } 19 | 20 | return swaps 21 | } 22 | 23 | 24 | func minimumSwaps(_ data: [Int]) -> Int { 25 | var countOfZero = 0 , swapForZero = 0, countOfOne = 0, swapForOne = 0 26 | 27 | for num in data { 28 | if num == 0 { 29 | swapForZero += countOfOne 30 | countOfZero += 1 31 | } else { 32 | swapForOne += countOfZero 33 | countOfOne += 1 34 | } 35 | } 36 | 37 | return min(swapForOne, swapForZero) 38 | } -------------------------------------------------------------------------------- /Trees/103-ZigZagTraversal.swift: -------------------------------------------------------------------------------- 1 | func zigzagLevelOrder(_ root: TreeNode?) -> [[Int]] { 2 | guard let root = root else { return [] } 3 | var queue = [TreeNode]() 4 | queue.append(root) 5 | var result = [[Int]]() 6 | 7 | while !queue.isEmpty { 8 | var newChildren = [TreeNode]() 9 | var level = [Int]() 10 | 11 | for node in queue { 12 | level.append(node.val) 13 | 14 | if let leftChild = node.left { 15 | newChildren.append(leftChild) 16 | } 17 | 18 | if let rightChild = node.right { 19 | newChildren.append(rightChild) 20 | } 21 | } 22 | 23 | result.append(level) 24 | queue = newChildren 25 | } 26 | 27 | for level in 0.. Int { 4 | var left = 1 5 | var right = woodLengths.max() ?? 0 6 | var res = 0 7 | while left < right { 8 | let length = (left + right) / 2 9 | 10 | if isValid(woodLengths, length, k) { 11 | left = length + 1 12 | res = length 13 | } else { 14 | right = length 15 | } 16 | } 17 | 18 | return res 19 | } 20 | 21 | func isValid(_ woodLengths: [Int], _ length: Int, _ k: Int) -> Bool { 22 | var count = 0 23 | 24 | for woodLength in woodLengths { 25 | if woodLength >= length { 26 | count += woodLength / length 27 | } else { 28 | return false 29 | } 30 | } 31 | 32 | return count >= k 33 | } 34 | 35 | cutWoods([5, 9, 7], 3) 36 | cutWoods([5, 9, 7], 4) 37 | cutWoods([1, 2, 3], 7) 38 | cutWoods([232, 124, 456], 7) 39 | --------------------------------------------------------------------------------