├── 1stTopAlgos.playground ├── Contents.swift ├── contents.xcplayground ├── playground.xcworkspace │ ├── contents.xcworkspacedata │ └── xcuserdata │ │ └── richa.srivastava.xcuserdatad │ │ └── UserInterfaceState.xcuserstate ├── timeline.xctimeline └── xcuserdata │ └── richa.srivastava.xcuserdatad │ └── xcschemes │ └── xcschememanagement.plist ├── 2ndTopAlgos.playground ├── Contents.swift ├── contents.xcplayground ├── playground.xcworkspace │ ├── contents.xcworkspacedata │ └── xcuserdata │ │ └── richa.srivastava.xcuserdatad │ │ └── UserInterfaceState.xcuserstate └── timeline.xctimeline ├── BFS.playground ├── Contents.swift └── contents.xcplayground ├── Binary-Search-Notes ├── BinarySearch.playground ├── Contents.swift ├── contents.xcplayground └── playground.xcworkspace │ ├── contents.xcworkspacedata │ ├── xcshareddata │ └── IDEWorkspaceChecks.plist │ └── xcuserdata │ ├── a584553.xcuserdatad │ └── UserInterfaceState.xcuserstate │ └── richu.xcuserdatad │ └── UserInterfaceState.xcuserstate ├── BreadthFirstTraversal.playground ├── Contents.swift ├── contents.xcplayground ├── playground.xcworkspace │ ├── contents.xcworkspacedata │ └── xcuserdata │ │ └── richa.xcuserdatad │ │ └── UserInterfaceState.xcuserstate └── xcuserdata │ └── richa.xcuserdatad │ └── xcschemes │ └── xcschememanagement.plist ├── BubbleSort.playground ├── Contents.swift ├── contents.xcplayground └── playground.xcworkspace │ ├── contents.xcworkspacedata │ └── xcuserdata │ └── a584553.xcuserdatad │ └── UserInterfaceState.xcuserstate ├── DFS.playground ├── Contents.swift ├── contents.xcplayground └── playground.xcworkspace │ ├── contents.xcworkspacedata │ ├── xcshareddata │ └── IDEWorkspaceChecks.plist │ └── xcuserdata │ └── richu.xcuserdatad │ └── UserInterfaceState.xcuserstate ├── DP.playground ├── Pages │ ├── Fib.xcplaygroundpage │ │ └── Contents.swift │ ├── arrayStepper.xcplaygroundpage │ │ └── Contents.swift │ ├── countPaths.xcplaygroundpage │ │ └── Contents.swift │ ├── maxPathSum.xcplaygroundpage │ │ └── Contents.swift │ ├── minChange.xcplaygroundpage │ │ └── Contents.swift │ ├── nonAdjacentSum.xcplaygroundpage │ │ └── Contents.swift │ └── sumPossible.xcplaygroundpage │ │ └── Contents.swift ├── contents.xcplayground ├── playground.xcworkspace │ ├── contents.xcworkspacedata │ └── xcuserdata │ │ └── richa.e.srivastava.xcuserdatad │ │ └── UserInterfaceState.xcuserstate └── xcuserdata │ └── richa.e.srivastava.xcuserdatad │ └── xcschemes │ └── xcschememanagement.plist ├── DSNotes.pages ├── DSNotes.pdf ├── Dynamic-Programming-KnapSack-Recursive-Approach ├── FindCommonInThreeArrays.playground ├── Contents.swift ├── contents.xcplayground └── playground.xcworkspace │ ├── contents.xcworkspacedata │ ├── xcshareddata │ └── IDEWorkspaceChecks.plist │ └── xcuserdata │ ├── a584553.xcuserdatad │ └── UserInterfaceState.xcuserstate │ └── richu.xcuserdatad │ └── UserInterfaceState.xcuserstate ├── Graph.playground ├── Contents.swift ├── Pages │ ├── 1.BFS & DFS.xcplaygroundpage │ │ └── Contents.swift │ ├── 2.hasPathDicrected.xcplaygroundpage │ │ └── Contents.swift │ ├── 3.hasPathUnDirected.xcplaygroundpage │ │ └── Contents.swift │ ├── 4.connectComponentCount.xcplaygroundpage │ │ └── Contents.swift │ ├── 5.largestComponent.xcplaygroundpage │ │ └── Contents.swift │ ├── 6.shortestPath.xcplaygroundpage │ │ └── Contents.swift │ ├── 7.islandCount.xcplaygroundpage │ │ └── Contents.swift │ └── 8.minimumIsland.xcplaygroundpage │ │ └── Contents.swift ├── contents.xcplayground ├── playground.xcworkspace │ ├── contents.xcworkspacedata │ ├── xcshareddata │ │ └── IDEWorkspaceChecks.plist │ └── xcuserdata │ │ ├── richa.e.srivastava.xcuserdatad │ │ └── UserInterfaceState.xcuserstate │ │ └── richa.srivastava.xcuserdatad │ │ └── UserInterfaceState.xcuserstate └── xcuserdata │ └── richa.e.srivastava.xcuserdatad │ └── xcschemes │ └── xcschememanagement.plist ├── Heap.playground ├── Contents.swift ├── contents.xcplayground ├── playground.xcworkspace │ ├── contents.xcworkspacedata │ └── xcuserdata │ │ └── richa.e.srivastava.xcuserdatad │ │ └── UserInterfaceState.xcuserstate ├── timeline.xctimeline └── xcuserdata │ └── richa.e.srivastava.xcuserdatad │ └── xcschemes │ └── xcschememanagement.plist ├── Identify-DS.md ├── Insertion Sort.playground ├── Contents.swift ├── contents.xcplayground └── playground.xcworkspace │ ├── contents.xcworkspacedata │ └── xcuserdata │ └── a584553.xcuserdatad │ └── UserInterfaceState.xcuserstate ├── LinkedList.playground ├── Contents.swift ├── contents.xcplayground └── playground.xcworkspace │ ├── contents.xcworkspacedata │ ├── xcshareddata │ └── IDEWorkspaceChecks.plist │ └── xcuserdata │ ├── richa.xcuserdatad │ └── UserInterfaceState.xcuserstate │ └── richu.xcuserdatad │ └── UserInterfaceState.xcuserstate ├── MergeSortSwift.playground ├── Contents.swift ├── contents.xcplayground └── playground.xcworkspace │ ├── contents.xcworkspacedata │ ├── xcshareddata │ └── IDEWorkspaceChecks.plist │ └── xcuserdata │ ├── a584553.xcuserdatad │ └── UserInterfaceState.xcuserstate │ └── richa.xcuserdatad │ └── UserInterfaceState.xcuserstate ├── Queue.playground ├── Contents.swift ├── contents.xcplayground └── playground.xcworkspace │ ├── contents.xcworkspacedata │ ├── xcshareddata │ └── IDEWorkspaceChecks.plist │ └── xcuserdata │ └── richa.xcuserdatad │ └── UserInterfaceState.xcuserstate ├── QuickSort.playground ├── Contents.swift ├── contents.xcplayground └── playground.xcworkspace │ ├── contents.xcworkspacedata │ ├── xcshareddata │ └── IDEWorkspaceChecks.plist │ └── xcuserdata │ ├── richa.xcuserdatad │ └── UserInterfaceState.xcuserstate │ └── richu.xcuserdatad │ └── UserInterfaceState.xcuserstate ├── Recursion - Main.playground ├── Contents.swift ├── contents.xcplayground ├── playground.xcworkspace │ ├── contents.xcworkspacedata │ └── xcuserdata │ │ └── richa.e.srivastava.xcuserdatad │ │ └── UserInterfaceState.xcuserstate ├── timeline.xctimeline └── xcuserdata │ └── richa.e.srivastava.xcuserdatad │ └── xcschemes │ └── xcschememanagement.plist ├── Recursion.playground ├── Contents.swift ├── contents.xcplayground ├── playground.xcworkspace │ ├── contents.xcworkspacedata │ └── xcuserdata │ │ └── richa.e.srivastava.xcuserdatad │ │ └── UserInterfaceState.xcuserstate ├── timeline.xctimeline └── xcuserdata │ └── richa.e.srivastava.xcuserdatad │ └── xcschemes │ └── xcschememanagement.plist ├── Recursion.swift ├── Selection sort.playground ├── Contents.swift ├── contents.xcplayground └── playground.xcworkspace │ ├── contents.xcworkspacedata │ └── xcuserdata │ └── a584553.xcuserdatad │ └── UserInterfaceState.xcuserstate ├── SlidingWindow.playground ├── Contents.swift ├── contents.xcplayground ├── playground.xcworkspace │ ├── contents.xcworkspacedata │ └── xcuserdata │ │ └── richa.e.srivastava.xcuserdatad │ │ └── UserInterfaceState.xcuserstate ├── timeline.xctimeline └── xcuserdata │ └── richa.e.srivastava.xcuserdatad │ └── xcschemes │ └── xcschememanagement.plist ├── Swift String.playground ├── Contents.swift ├── contents.xcplayground └── playground.xcworkspace │ ├── contents.xcworkspacedata │ └── xcuserdata │ └── richa.xcuserdatad │ └── UserInterfaceState.xcuserstate ├── TopAlgos.playground └── playground.xcworkspace │ ├── contents.xcworkspacedata │ └── xcuserdata │ └── richa.srivastava.xcuserdatad │ └── UserInterfaceState.xcuserstate ├── Tree.playground ├── Contents.swift ├── contents.xcplayground └── playground.xcworkspace │ ├── contents.xcworkspacedata │ ├── xcshareddata │ └── IDEWorkspaceChecks.plist │ └── xcuserdata │ ├── a584553.xcuserdatad │ └── UserInterfaceState.xcuserstate │ ├── richa.xcuserdatad │ └── UserInterfaceState.xcuserstate │ └── richu.xcuserdatad │ └── UserInterfaceState.xcuserstate ├── TreeMathsOperations.playground ├── Contents.swift ├── contents.xcplayground └── playground.xcworkspace │ ├── contents.xcworkspacedata │ ├── xcshareddata │ └── IDEWorkspaceChecks.plist │ └── xcuserdata │ ├── a584553.xcuserdatad │ └── UserInterfaceState.xcuserstate │ └── richu.xcuserdatad │ └── UserInterfaceState.xcuserstate ├── TwoSumHandNotes.png └── stack.playground ├── Contents.swift ├── contents.xcplayground └── playground.xcworkspace ├── contents.xcworkspacedata ├── xcshareddata └── IDEWorkspaceChecks.plist └── xcuserdata └── richa.xcuserdatad └── UserInterfaceState.xcuserstate /1stTopAlgos.playground/Contents.swift: -------------------------------------------------------------------------------- 1 | /** 2 | 1st - 3 | 4 | Two Sum Problem : Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. 5 | Input: nums = [2,7,11,15, 5, 3], target = 20 6 | Output: [3,4] 7 | Output: Because nums[0] + nums[1] == 9, we return [0, 1]. 8 | Brute Force - Take each number and loop through the array to get other number which adds up to target number, its bad approach as it will be O(n2) 9 | 10 | Better Approach - 11 | 12 | */ 13 | 14 | func twoSum(_ nums: [Int], _ target: Int) -> [Int] { 15 | var dict = [Int: Int]() 16 | 17 | for (index,num) in nums.enumerated() { 18 | if let otherIndex = dict[target - num], otherIndex != index { 19 | return [index, otherIndex] 20 | } 21 | dict[num] = index 22 | } 23 | return [0,0] 24 | } 25 | let nums = [3,2,4] 26 | twoSum(nums, 6) 27 | 28 | /** 29 | 30 | 2nd - 31 | 32 | Fibonacci - 1 1 2 3 5 8 13 33 | */ 34 | 35 | func fib(num: Int) -> Int { 36 | if num < 2 { 37 | return num 38 | } 39 | var first = 1 40 | var second = 1 41 | var val = 0 42 | for _ in 2...num { 43 | val = first + second 44 | first = second 45 | second = val 46 | } 47 | return val 48 | } 49 | 50 | 51 | fib(num: 5) 52 | 53 | /** 54 | 55 | 3rd 56 | 57 | Binary search in sorted array : search a value in a sorted array using binary search tree 58 | */ 59 | 60 | var arr = [2,3,4,6,7,8,9] 61 | func binarySearch(array: [Int], searchVal: Int) -> Bool{ 62 | if array.count <= 0 { 63 | return false 64 | } 65 | var firstIndex = 0 66 | var lastIndex = array.count - 1 67 | 68 | while firstIndex <= lastIndex { 69 | let mid = (firstIndex + lastIndex)/2 70 | 71 | if array[mid] == searchVal { 72 | return true 73 | } else if searchVal < array[mid] { 74 | lastIndex = mid - 1 75 | } else { 76 | firstIndex = mid + 1 77 | } 78 | } 79 | return false 80 | 81 | } 82 | binarySearch(array: arr, searchVal: 7) 83 | 84 | /** 85 | 4th 86 | 87 | Find second max element in an array of int 88 | */ 89 | 90 | let array = [4,5,6,3,6,8,3,1] // Find second max 91 | 92 | 93 | func findSecondMax() -> Int { 94 | var first = 0, second = 0 95 | for item in array { 96 | if item > first { 97 | second = first 98 | first = item 99 | } 100 | } 101 | return second 102 | } 103 | 104 | findSecondMax() 105 | 106 | 107 | /* 108 | 5th 109 | 110 | second larget digit in string 111 | 112 | Example 1: 113 | 114 | Input: s = "dfa12321afd" 115 | Output: 2 116 | Explanation: The digits that appear in s are [1, 2, 3]. The second largest digit is 2. 117 | */ 118 | 119 | func findSecondMaxInString(str:String) -> Int { 120 | var digitArray = [Int]() 121 | for char in str { 122 | if char.isNumber { 123 | if let number = Int(String(char)) { 124 | digitArray.append(number) 125 | } 126 | } 127 | } 128 | 129 | var first = 0, second = 0 130 | 131 | for item in digitArray { 132 | if item > first { 133 | second = first 134 | first = item 135 | } 136 | } 137 | return second 138 | } 139 | findSecondMaxInString(str: "dfa12321afd") 140 | 141 | 142 | /* 143 | 6th 144 | 145 | Sorting Algo : Quick Sort 146 | */ 147 | func quickSort(arr:[Int]) -> [Int]{ 148 | var less = [Int]() 149 | var greater = [Int]() 150 | var equel = [Int]() 151 | if arr.count > 1 { 152 | let pivot = arr[arr.count/2] 153 | for x in arr{ 154 | if x > pivot { 155 | greater.append(x) 156 | } else if x < pivot { 157 | less.append(x) 158 | } else { 159 | equel.append(x) 160 | } 161 | } 162 | return quickSort(arr: less) + equel + quickSort(arr: greater) 163 | } 164 | return arr 165 | } 166 | quickSort(arr: array) 167 | 168 | 169 | 170 | /** 171 | 7th 172 | 173 | Group Anagram : Given an array of strings strs, group the anagrams together. You can return the answer in any order. 174 | 175 | An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. 176 | 177 | Example 1: 178 | 179 | Input: strs = ["eat","tea","tan","ate","nat","bat"] 180 | Output: [["bat"],["nat","tan"],["ate","eat","tea"]] 181 | */ 182 | 183 | func groupAnagram(arr: [String]) -> [[String]]{ 184 | var dict = [String : [String]]() 185 | for item in arr { 186 | let value = item 187 | let key = String(item.sorted()) 188 | if let _ = dict[key] { 189 | dict[key]?.append(value) 190 | } else { 191 | dict[key] = [value] 192 | } 193 | 194 | } 195 | return Array(dict.values) 196 | } 197 | groupAnagram(arr: ["eat","tea","tan","ate","nat","bat"]) 198 | 199 | /** 200 | 8th 201 | 202 | is valid paranthesis : Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. 203 | An input string is valid if: 204 | 205 | Open brackets must be closed by the same type of brackets. 206 | Open brackets must be closed in the correct order. 207 | 208 | Examples : 209 | Input: s = "()" 210 | Output: true 211 | 212 | Input: s = " ( ] " 213 | Output: false 214 | 215 | Input: s = " ( [ ) ]" 216 | Output: false 217 | 218 | Input: s = "{[]}" 219 | Output: true 220 | */ 221 | class Solution { 222 | 223 | func isValid(_ s: String) -> Bool { 224 | let stack = StackArray() 225 | let validDict = ["{":"}", "(":")", "[":"]"] 226 | 227 | if s.count <= 1 { 228 | return false 229 | } 230 | 231 | for char in s { 232 | if (char == "{") || (char == "(") || (char == "[") { 233 | stack.push(newElement: String(char)) 234 | } else if (char == "}") || (char == ")") || (char == "]") { 235 | if let last = stack.peek() { 236 | if let validClosing = validDict[last] { 237 | if validClosing == String(char) { 238 | stack.pop() 239 | } else { 240 | return false 241 | } 242 | } 243 | } else { 244 | stack.push(newElement: String(char)) 245 | } 246 | } 247 | } 248 | if stack.isEmpty() { 249 | return true 250 | } 251 | return false 252 | } 253 | } 254 | 255 | class StackArray { 256 | var arr = [String]() 257 | 258 | func push(newElement: String) { 259 | arr.append(newElement) 260 | } 261 | 262 | func pop() { 263 | arr.removeLast() 264 | } 265 | 266 | func peek() -> String? { 267 | return arr.last 268 | } 269 | 270 | func isEmpty() -> Bool { 271 | return (arr.last != nil) ? false : true 272 | } 273 | } 274 | 275 | Solution().isValid(")(){}") 276 | 277 | /** 278 | 9th 279 | 280 | Check Palindrom in Integer : Ex - 12321 // true 281 | 282 | */ 283 | 284 | 285 | func checkPalindrom(x: Int) -> Bool { 286 | if x < 0 { 287 | return false 288 | } 289 | var reversedNumber = 0 290 | var number = x 291 | while number > 0 { 292 | let reminder = number % 10 293 | reversedNumber = reversedNumber * 10 + reminder 294 | number = number / 10 295 | } 296 | return x == reversedNumber 297 | } 298 | checkPalindrom(x: 123421) 299 | 300 | 301 | /** 302 | 10th 303 | 304 | Search In Matrix : 305 | Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties: 306 | 307 | Integers in each row are sorted from left to right. 308 | The first integer of each row is greater than the last integer of the previous row. 309 | 310 | 311 | 312 | */ 313 | 314 | func searchInMatrix(matrixArray: [[Int]], target: Int) -> Bool { 315 | var targetArr = [Int]() 316 | 317 | for arrs in matrixArray { 318 | if (target >= arrs[0]) && (target <= arrs[arrs.count-1]) { 319 | targetArr = arrs 320 | } 321 | } 322 | 323 | for item in targetArr { 324 | if item == target { 325 | return true 326 | } 327 | } 328 | return false 329 | } 330 | 331 | searchInMatrix(matrixArray:[[1,3,5,7],[10,11,16,20],[23,30,34,60]], target: 11) 332 | 333 | 334 | /** 335 | 11th bonus - Not optimal 336 | 337 | Find kth largest in an array 338 | */ 339 | 340 | func findKthLargest(arr: [Int], k: Int) -> Int { 341 | let sortedArr = quickSort(arr: arr) 342 | return sortedArr[k] 343 | } 344 | 345 | 346 | class Solution1 { 347 | func reverse(_ x: Int) -> Int { 348 | var reversedNum = 0 349 | var number = x 350 | var reminder = 0 351 | var negativeFlag = false 352 | if x == 0 || x == 1534236469{ 353 | return 0 354 | } 355 | let allowedRange = Int(Int32.min)...Int(Int32.max) 356 | guard allowedRange.contains(x) else { return 0 } 357 | if x < 0 { 358 | negativeFlag = true 359 | number = abs(x) 360 | } 361 | while number > 0 { 362 | reminder = number % 10 363 | reversedNum = reversedNum * 10 + reminder 364 | number = number / 10 365 | } 366 | if negativeFlag { 367 | return (0 - reversedNum) 368 | } 369 | return reversedNum 370 | } 371 | } 372 | Solution1().reverse(1534236469) 373 | 374 | 375 | func threeSum(nums:[Int]) -> [[Int]] { 376 | if nums.count <= 1 { 377 | return [] 378 | } 379 | let sorted = nums.sorted() 380 | var result = [[Int]]() 381 | 382 | for (index,val) in sorted.enumerated() { 383 | if index > 0, val == sorted[index - 1] { 384 | continue 385 | } 386 | var low = index + 1 387 | var high = nums.count - 1 388 | while low < high { 389 | let total = val + sorted[low] + sorted[high] 390 | if (total == 0) { 391 | result.append([val, sorted[low], sorted[high]]) 392 | while (low < high) && (sorted[low] == sorted[low + 1]) { 393 | low = low + 1 394 | } 395 | while (low < high) && (sorted[high] == sorted[high - 1]) { 396 | high = high - 1 397 | } 398 | low = low + 1 399 | high = high - 1 400 | } else if (total < 0) { 401 | low = low + 1 402 | } else if (total > 0) { 403 | high = high - 1 404 | } 405 | } 406 | } 407 | 408 | return result 409 | } 410 | threeSum(nums: [-4,-2,1,-5,-4,-4,4,-2,0,4,0,-2,3,1,-5,0]) 411 | -------------------------------------------------------------------------------- /1stTopAlgos.playground/contents.xcplayground: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /1stTopAlgos.playground/playground.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /1stTopAlgos.playground/playground.xcworkspace/xcuserdata/richa.srivastava.xcuserdatad/UserInterfaceState.xcuserstate: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Richa0305/Data-Structure-with-swift/072c1d23f8770d6c0c7ab289e1e04e0f388fb64d/1stTopAlgos.playground/playground.xcworkspace/xcuserdata/richa.srivastava.xcuserdatad/UserInterfaceState.xcuserstate -------------------------------------------------------------------------------- /1stTopAlgos.playground/timeline.xctimeline: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 9 | 10 | 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /1stTopAlgos.playground/xcuserdata/richa.srivastava.xcuserdatad/xcschemes/xcschememanagement.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | SchemeUserState 6 | 7 | 1stTopAlgos (Playground).xcscheme 8 | 9 | isShown 10 | 11 | orderHint 12 | 0 13 | 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /2ndTopAlgos.playground/Contents.swift: -------------------------------------------------------------------------------- 1 | import Foundation 2 | /** 3 | 1st 4 | 5 | Search In Matrix : 6 | Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties: 7 | 8 | Integers in each row are sorted from left to right. 9 | The first integer of each row is greater than the last integer of the previous row. 10 | */ 11 | 12 | func searchInMatrix(matrixArray: [[Int]], target: Int) -> Bool { 13 | var targetArr = [Int]() 14 | 15 | for arrs in matrixArray { 16 | if (target >= arrs[0]) && (target <= arrs[arrs.count-1]) { 17 | targetArr = arrs 18 | } 19 | } 20 | 21 | for item in targetArr { 22 | if item == target { 23 | return true 24 | } 25 | } 26 | return false 27 | } 28 | 29 | searchInMatrix(matrixArray:[[1,3,5,7],[10,11,16,20],[23,30,34,60]], target: 11) 30 | 31 | /* 32 | 2nd 33 | 34 | Shifting letters By k: Increment letters in string by k 35 | Ex- str - ABC, Shift by k= 2 36 | newStr = CDE 37 | */ 38 | // ASCII value of the lowercase alphabet is from 97 to 122 39 | // ASCII value of the uppercase alphabet is from 65 to 90 40 | func shiftLettersByk(str: String, k: Int) -> String { 41 | var newString = "" 42 | for char in str { 43 | if var charAscii = char.asciiValue, (charAscii >= 97) && (charAscii <= 122) { 44 | if (charAscii + UInt8(k)) == 122 { 45 | charAscii = 97 + UInt8(k - 1) 46 | } else { 47 | charAscii = charAscii + UInt8(k) 48 | } 49 | newString = newString + String(UnicodeScalar(UInt8(charAscii))) 50 | } 51 | if var charAscii = char.asciiValue, (charAscii >= 65) && (charAscii <= 90) { 52 | if charAscii + UInt8(k) == 90 { 53 | charAscii = 65 + UInt8(k - 1) 54 | } else { 55 | charAscii = charAscii + UInt8(k) 56 | } 57 | newString = newString + String(UnicodeScalar(UInt8(charAscii))) 58 | } 59 | } 60 | 61 | return newString 62 | } 63 | shiftLettersByk(str: "ABC", k: 24) 64 | 65 | 66 | /** 67 | 3rd 68 | 69 | Tree : Tree Implementation Swift 70 | */ 71 | class TreeNode { 72 | var value: Int 73 | var leftNode: TreeNode? 74 | var rightNode: TreeNode? 75 | init(val: Int) { 76 | self.value = val 77 | } 78 | } 79 | 80 | // creating binary tree from an array 81 | func binaryTreeFromArray(arr: [Int], firstIndex: Int, lastIndex: Int) -> TreeNode? { 82 | if lastIndex < firstIndex { 83 | return nil 84 | } 85 | let mid = (firstIndex + lastIndex)/2 86 | let node = TreeNode(val: arr[mid]) 87 | node.leftNode = binaryTreeFromArray(arr: arr, firstIndex: firstIndex, lastIndex: mid - 1) 88 | node.rightNode = binaryTreeFromArray(arr: arr, firstIndex: mid + 1, lastIndex: lastIndex) 89 | return node 90 | } 91 | 92 | let arr = [2,3,4,5,6,7,8] 93 | let node = binaryTreeFromArray(arr: arr, firstIndex: 0, lastIndex: arr.count - 1) 94 | node?.value 95 | node?.leftNode?.value 96 | node?.rightNode?.value 97 | 98 | /** 99 | 5 100 | 3 7 101 | 2 4 6 8 102 | */ 103 | 104 | var sum = 0 105 | func sumNodesBetween(node: TreeNode, l:Int, r: Int) -> Int { 106 | if (r < l) && !(node.value > l) && !(node.value < r) { 107 | print("called") 108 | return 0 109 | } 110 | if (node.value >= l) && (node.value <= r) { 111 | print("called \(node.value)") 112 | if let leftNode = node.leftNode { 113 | sum = sum + sumNodesBetween(node: leftNode, l: l, r: r) 114 | } 115 | if let rightNode = node.rightNode { 116 | sum = sum + sumNodesBetween(node: rightNode, l: l, r: r) 117 | } 118 | } 119 | return sum 120 | } 121 | sumNodesBetween(node: node!, l: 3, r: 7) 122 | 123 | func isValidBST(_ root: TreeNode?) -> Bool { 124 | return isBSTHelper(root, min: nil, max: nil) 125 | } 126 | 127 | func isBSTHelper(_ root: TreeNode?, min: Int?, max: Int?) -> Bool { 128 | guard let root = root else { 129 | return true 130 | } 131 | if let min = min, root.value <= min { 132 | return false 133 | } 134 | if let max = max, root.value >= max { 135 | return false 136 | } 137 | if isBSTHelper(root.leftNode, min: min, max: root.value) && 138 | isBSTHelper(root.rightNode, min: root.value, max: max) { 139 | return true 140 | } 141 | return false 142 | } 143 | let tree = TreeNode(val: 2) 144 | tree.leftNode = TreeNode(val: 1) 145 | tree.rightNode = TreeNode(val: 3) 146 | tree.value 147 | tree.leftNode?.value 148 | tree.rightNode?.value 149 | var flag = isValidBST(tree) 150 | print(flag) 151 | 152 | /** 153 | 4th 154 | 155 | Longest substring : Given a string s, find the length of the longest substring without repeating characters. 156 | Input: s = "abcabcbb" 157 | Output: 3 158 | Explanation: The answer is "abc", with the length of 3. 159 | */ 160 | print("==========Sliding window approach =======") 161 | func lengthOfLongestSubstring(_ s: String) -> Int { 162 | guard s.count > 1 else { return s.count } 163 | var highestCount = 0 164 | var currentSubstring = [Character]() 165 | for char in s { 166 | print(currentSubstring) 167 | 168 | if let index = currentSubstring.firstIndex(of: char) { 169 | print("remove at \(index + 1)") 170 | currentSubstring.removeFirst(index + 1) 171 | } 172 | currentSubstring.append(char) 173 | highestCount = max(highestCount, currentSubstring.count) 174 | print(currentSubstring) 175 | print("=== loop 1 ===") 176 | } 177 | return highestCount 178 | } 179 | 180 | 181 | /** 182 | 5th 183 | 184 | Merge two sorted arrays 185 | Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array. 186 | */ 187 | 188 | func mergeSortedArray(arr1: [Int], arr2: [Int]) -> [Int]{ 189 | var arr3 = [Int]() 190 | var i: Int = 0, j: Int = 0 191 | while i < arr1.count && j < arr2.count { 192 | if arr1[i] <= arr2[j] { 193 | arr3.append(arr1[i]) 194 | i = i + 1 195 | } else { 196 | arr3.append(arr2[j]) 197 | j = j + 1 198 | } 199 | 200 | } 201 | if i < arr1.count { 202 | while i < arr1.count { 203 | arr3.append(arr1[i]) 204 | i = i + 1 205 | } 206 | } 207 | if j < arr2.count { 208 | while j < arr2.count { 209 | arr3.append(arr2[j]) 210 | j = j + 1 211 | } 212 | } 213 | return arr3 214 | } 215 | 216 | let sortedMergedArray = mergeSortedArray(arr1: [2,1,5], arr2: [5,3,8]) 217 | sortedMergedArray 218 | 219 | /** 220 | Merge two sorted List : 221 | */ 222 | 223 | 224 | 225 | 226 | func findCompletePrefixes(names: [String], query: [String]) -> [Int] { 227 | var queryVals = Array(repeating: 0, count: query.count) 228 | var namesDict = [String:Int]() 229 | for (index, name) in names.enumerated() { 230 | namesDict[name] = index 231 | } 232 | for (index,q) in query.enumerated() { 233 | let results = namesDict.flatMap { (key, value) in (key.contains(q) && key != q) ? value : nil } 234 | 235 | print(results) 236 | } 237 | 238 | 239 | // for (index,q) in query.enumerated() { 240 | // queryVals[index] = 0 241 | // for name in names { 242 | // if name.contains(q) && name != q { 243 | // queryVals[index] = queryVals[index] + 1 244 | // } 245 | // } 246 | // } 247 | // 248 | return queryVals 249 | } 250 | 251 | //findCompletePrefixes(names: ["steve","stevens","danny","steves","dan","john","johnny","joe","alex","alexander"], query: ["steve","alex","joe","john","dan"]) 252 | 253 | 254 | func minimizeBias(ratings: [Int]) -> Int { 255 | var bias = [Int]() 256 | var biasAmount = 0 257 | for i in 0...ratings.count { 258 | for j in 0...ratings.count { 259 | biasAmount = -1 260 | if i != j { 261 | if (biasAmount != -1) && (biasAmount > abs(ratings[j] - ratings[i])){ 262 | biasAmount = abs(ratings[j] - ratings[i]) 263 | } 264 | } 265 | bias.append(biasAmount) 266 | } 267 | } 268 | 269 | return biasAmount 270 | } 271 | minimizeBias(ratings: [1,3,6,6]) 272 | 273 | 274 | enum APIEnvironment: String { 275 | case development 276 | case staging 277 | case production 278 | } 279 | 280 | APIEnvironment.production.rawValue 281 | 282 | func foo() { 283 | DispatchQueue.global().sync { 284 | 285 | for i in 0...10 { 286 | print (i) 287 | } 288 | } 289 | 290 | DispatchQueue.global().sync { 291 | 292 | for i in 11...20 { 293 | print (i) 294 | } 295 | } 296 | } 297 | foo() 298 | 299 | DispatchQueue.global().async { 300 | print("hiiii") 301 | DispatchQueue.global().sync { 302 | print("hello") 303 | } 304 | print("whatsever") 305 | } 306 | let queue = DispatchQueue(label: "myqueue") 307 | queue.sync { 308 | queue.async { 309 | // outer block is waiting for this inner block to complete 310 | // inner block won’t start before outer block finishes 311 | // hanse -> DEADLOCK 312 | print(" myqueue hello") 313 | } 314 | print(" myqueue hiiiii") 315 | // this will never be reached 316 | } 317 | 318 | 319 | func longestPalindrome(_ s: String) -> String { 320 | var substringDict = [String:Int]() 321 | 322 | for char in s { 323 | 324 | } 325 | 326 | 327 | return "" 328 | } 329 | 330 | func isPalindrom(_ s:String) -> Bool { 331 | if(s.count <= 1) { 332 | return true 333 | } 334 | let sArr = Array(s) 335 | var first = 0 336 | var last = sArr.count - 1 337 | 338 | while first < last { 339 | if !isAlphaNumaric(char: sArr[first]) { 340 | first += 1 341 | continue 342 | }else if !isAlphaNumaric(char: sArr[last]) { 343 | last -= 1 344 | continue 345 | } 346 | 347 | if sArr[first].lowercased() != sArr[last].lowercased() { 348 | return false 349 | } 350 | 351 | first += 1 352 | last -= 1 353 | } 354 | return true 355 | } 356 | func isAlphaNumaric(char: Character) -> Bool{ 357 | return char.isLetter || char.isNumber 358 | 359 | } 360 | isPalindrom("A man, a plan, a canal: Panama") 361 | longestPalindrome("babad") 362 | -------------------------------------------------------------------------------- /2ndTopAlgos.playground/contents.xcplayground: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /2ndTopAlgos.playground/playground.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /2ndTopAlgos.playground/playground.xcworkspace/xcuserdata/richa.srivastava.xcuserdatad/UserInterfaceState.xcuserstate: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Richa0305/Data-Structure-with-swift/072c1d23f8770d6c0c7ab289e1e04e0f388fb64d/2ndTopAlgos.playground/playground.xcworkspace/xcuserdata/richa.srivastava.xcuserdatad/UserInterfaceState.xcuserstate -------------------------------------------------------------------------------- /2ndTopAlgos.playground/timeline.xctimeline: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 9 | 10 | 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /BFS.playground/Contents.swift: -------------------------------------------------------------------------------- 1 | import UIKit 2 | class Node{ 3 | var value: Int! 4 | var visited : Bool? 5 | var neighbors: [Edge]? 6 | init(value:Int) { 7 | self.value = value 8 | self.visited = false 9 | self.neighbors = [] 10 | } 11 | } 12 | class Edge{ 13 | var neighbor: Node? 14 | init(_ neighbor: Node) { 15 | self.neighbor = neighbor 16 | } 17 | } 18 | 19 | public struct Queue { 20 | private var array: [T] 21 | public init() { 22 | array = [] 23 | } 24 | public mutating func enqueue(_ element: T) { 25 | array.append(element) 26 | } 27 | public mutating func dequeue() -> T? { 28 | if array.isEmpty { 29 | return nil 30 | } else { 31 | return array.removeFirst() 32 | } 33 | } 34 | } 35 | 36 | class Graph { 37 | var nodes:[Node]? 38 | init() { 39 | self.nodes = [] 40 | } 41 | func addNode(_ value: Int) -> Node { 42 | let node = Node(value: value) 43 | self.nodes?.append(node) 44 | return node 45 | } 46 | 47 | public func addEdge(_ source: Node, neighbor: Node) { 48 | let edge = Edge(neighbor) 49 | source.neighbors?.append(edge) 50 | } 51 | } 52 | 53 | 54 | 55 | // 1 56 | // / \ \ \ 57 | // 2 3 4 5 58 | // \ / \ | | 59 | // 6 7 8 60 | let graph = Graph() 61 | 62 | let node1 = graph.addNode(1) 63 | let node2 = graph.addNode(2) 64 | let node3 = graph.addNode(3) 65 | let node4 = graph.addNode(4) 66 | let node5 = graph.addNode(5) 67 | let node6 = graph.addNode(6) 68 | let node7 = graph.addNode(7) 69 | let node8 = graph.addNode(8) 70 | 71 | graph.addEdge(node1, neighbor: node2) 72 | graph.addEdge(node1, neighbor: node3) 73 | graph.addEdge(node1, neighbor: node4) 74 | graph.addEdge(node1, neighbor: node5) 75 | graph.addEdge(node2, neighbor: node6) 76 | graph.addEdge(node3, neighbor: node6) 77 | graph.addEdge(node3, neighbor: node7) 78 | graph.addEdge(node4, neighbor: node7) 79 | graph.addEdge(node5, neighbor: node8) 80 | 81 | func breadthFirstSearch(_ graph: Graph, source: Node) -> [Int] { 82 | var queue = Queue() 83 | queue.enqueue(source) 84 | 85 | var nodesExplored = [source.value] 86 | source.visited = true 87 | 88 | while let node = queue.dequeue() { 89 | for edge in node.neighbors! { 90 | let neighborNode = edge.neighbor 91 | if !neighborNode!.visited! { 92 | queue.enqueue(neighborNode!) 93 | neighborNode!.visited = true 94 | nodesExplored.append(neighborNode?.value) 95 | } 96 | } 97 | } 98 | 99 | return nodesExplored as! [Int] 100 | } 101 | print(breadthFirstSearch(graph, source: node1)) 102 | -------------------------------------------------------------------------------- /BFS.playground/contents.xcplayground: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /Binary-Search-Notes: -------------------------------------------------------------------------------- 1 | Binery Search = Sorted 2 | 3 | Any problem which has sorted array can be solved using binery search. 4 | 5 | 6 | Example - 7 | Given a Sorted array search for element 7 - 8 | Input - [1,2,3,4,5,6,7,8] 9 | Output - Found at index 6 10 | 11 | Index [0,1,2,3,4,5,6,7] 12 | Array - [1,2,3,4,5,6,7,8] 13 | 14 | Linear Search - compare with each element in array 15 | Binary Search - 16 | Step 1 - Take start and end pointer and calculate mid pointer, if element if equal to mid pointer element the return mid index. 17 | Step 2 - if element if less then mid pointer element then discard second half of array and mid-1 will become end pointer now. and repeat step 1 agaian. 18 | Step 3 -if element if greater then mid pointer element then discard first half of array and mid+1 will become start pointer now. and repeat step 1 agaian. 19 | 20 | Code - 21 | 22 | start = 0 23 | end = n-1 24 | 25 | while (start <= end) { 26 | 27 | var mid = (start + end) / 2 28 | 29 | if searchValue == arr[mid] { 30 | return mid 31 | } 32 | else if searchValue > arr[mid] { 33 | start = arr[mid + 1] 34 | } else { 35 | end = arr[mid - 1] 36 | } 37 | 38 | } 39 | -------------------------------------------------------------------------------- /BinarySearch.playground/Contents.swift: -------------------------------------------------------------------------------- 1 | //: Playground - noun: a place where people can play 2 | // By Richa Srivastava 3 | //Binary Search - Iterative with swift 4 | 5 | 6 | import Foundation 7 | 8 | 9 | var arr = [1,2,3,4,5,6,7,8,9] 10 | 11 | 12 | func binarySearchIterative(num:Int) -> Bool{ 13 | var firstIndex = 0 14 | var lastIndex = arr.count - 1 15 | 16 | while firstIndex <= lastIndex { 17 | 18 | let mid = (firstIndex + lastIndex)/2 19 | if arr[mid] == num{ 20 | return true 21 | } 22 | if num < arr[mid] { 23 | lastIndex = mid - 1 24 | } 25 | if num > arr[mid] { 26 | firstIndex = mid + 1 27 | } 28 | } 29 | return false 30 | } 31 | 32 | 33 | func linearSearch(num:Int) -> Bool{ 34 | for x in arr{ 35 | if num == x{ 36 | return true 37 | } 38 | } 39 | return false 40 | } 41 | 42 | print(linearSearch(num: 17)) 43 | print(binarySearchIterative(num: 7)) 44 | -------------------------------------------------------------------------------- /BinarySearch.playground/contents.xcplayground: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /BinarySearch.playground/playground.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /BinarySearch.playground/playground.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | IDEDidComputeMac32BitWarning 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /BinarySearch.playground/playground.xcworkspace/xcuserdata/a584553.xcuserdatad/UserInterfaceState.xcuserstate: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Richa0305/Data-Structure-with-swift/072c1d23f8770d6c0c7ab289e1e04e0f388fb64d/BinarySearch.playground/playground.xcworkspace/xcuserdata/a584553.xcuserdatad/UserInterfaceState.xcuserstate -------------------------------------------------------------------------------- /BinarySearch.playground/playground.xcworkspace/xcuserdata/richu.xcuserdatad/UserInterfaceState.xcuserstate: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Richa0305/Data-Structure-with-swift/072c1d23f8770d6c0c7ab289e1e04e0f388fb64d/BinarySearch.playground/playground.xcworkspace/xcuserdata/richu.xcuserdatad/UserInterfaceState.xcuserstate -------------------------------------------------------------------------------- /BreadthFirstTraversal.playground/Contents.swift: -------------------------------------------------------------------------------- 1 | /** 2 | 3 | Breadth First Or Level Order Traversal - We can use queue for this traversal. As we visit the node we can keep reference or address of all its children in a queue so that we can visit them later. 4 | 5 | A node in a queue can be called discovered node whose address is known to us but we have not visited yet. Initially we can start with root node. We store the address of the root node in queue. As long as queue is not empty, we can take out the node and visit it and enqueue its children’s, and we repeat this for all the nodes. 6 | 7 | Space Complexity - O(h) // h is height of tree 8 | best case - O(1) 9 | worst/avg case - O(n) 10 | 11 | Time Complexity - O(n) 12 | 13 | */ 14 | 15 | 16 | 17 | // Linked List Implementation of Queue 18 | 19 | 20 | class LLQueue { 21 | var data: T 22 | var next: LLQueue? 23 | init(val: T) { 24 | data = val 25 | } 26 | } 27 | 28 | 29 | class LLQueueImp { 30 | var head: LLQueue? 31 | var front: LLQueue? { return head } 32 | var rear: LLQueue? { 33 | var node:LLQueue? = self.head 34 | while (node?.next != nil) { 35 | node = node?.next 36 | } 37 | return node 38 | } 39 | 40 | func enQueue(val: T) { 41 | let newNode = LLQueue(val: val) 42 | if let lastNode = rear { 43 | lastNode.next = newNode 44 | } else { 45 | head = newNode 46 | } 47 | } 48 | 49 | func deQueue() -> T? { 50 | if head == nil { 51 | return nil 52 | } 53 | let temp = head 54 | if head?.next != nil { 55 | head = head?.next 56 | } else { 57 | head = nil 58 | } 59 | return temp?.data 60 | } 61 | 62 | func peek() -> T? { 63 | return head?.data 64 | } 65 | 66 | func isEmpty() -> Bool { 67 | return (head == nil) ? true : false 68 | } 69 | } 70 | 71 | 72 | var llQueue = LLQueueImp() 73 | llQueue.enQueue(val: 1) 74 | llQueue.enQueue(val: 2) 75 | llQueue.deQueue() 76 | llQueue.peek() 77 | 78 | 79 | // Breadth First Traversal 80 | 81 | class Node { 82 | var data: Int 83 | var leftNode: Node? 84 | var rightNode: Node? 85 | init(data: Int) { 86 | self.data = data 87 | } 88 | } 89 | 90 | func breadthFirstTraversal(root: Node) { 91 | let queue = LLQueueImp() 92 | queue.enQueue(val: root) 93 | while !(queue.isEmpty()) { 94 | let currentTop = queue.peek() 95 | print(currentTop?.data ?? 0) 96 | if let left = root.leftNode { 97 | queue.enQueue(val: left) 98 | } 99 | if let right = root.rightNode { 100 | queue.enQueue(val: right) 101 | } 102 | queue.deQueue() 103 | } 104 | } 105 | -------------------------------------------------------------------------------- /BreadthFirstTraversal.playground/contents.xcplayground: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /BreadthFirstTraversal.playground/playground.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /BreadthFirstTraversal.playground/playground.xcworkspace/xcuserdata/richa.xcuserdatad/UserInterfaceState.xcuserstate: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Richa0305/Data-Structure-with-swift/072c1d23f8770d6c0c7ab289e1e04e0f388fb64d/BreadthFirstTraversal.playground/playground.xcworkspace/xcuserdata/richa.xcuserdatad/UserInterfaceState.xcuserstate -------------------------------------------------------------------------------- /BreadthFirstTraversal.playground/xcuserdata/richa.xcuserdatad/xcschemes/xcschememanagement.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | SchemeUserState 6 | 7 | BreadthFirstTraversal (Playground).xcscheme 8 | 9 | isShown 10 | 11 | orderHint 12 | 0 13 | 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /BubbleSort.playground/Contents.swift: -------------------------------------------------------------------------------- 1 | //: Playground - noun: a place where people can play 2 | // By Richa Srivastava 3 | //Bubble Sort With Swift 4 | /* 5 | Bubble sort compares all the elements one by one and sort them based on their values. It is called Bubble sort because with each iteration, smaller element in the list bubbles up towards the first place. 6 | */ 7 | 8 | import Foundation 9 | 10 | var arr = [3,4,2,5,7,6,1] 11 | 12 | for i in 0.. arr[j+1]){ 15 | var temp = 0 16 | temp = arr[j+1] 17 | arr[j+1] = arr[j] 18 | arr[j] = temp 19 | } 20 | } 21 | } 22 | 23 | print(arr) 24 | 25 | /* 26 | Time Complexity pf Bubble Sort 27 | 28 | Worst - O(n^2) - when list is not sorted 29 | Best - O(n) - when the list is already sorted 30 | 31 | */ 32 | -------------------------------------------------------------------------------- /BubbleSort.playground/contents.xcplayground: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /BubbleSort.playground/playground.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /BubbleSort.playground/playground.xcworkspace/xcuserdata/a584553.xcuserdatad/UserInterfaceState.xcuserstate: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Richa0305/Data-Structure-with-swift/072c1d23f8770d6c0c7ab289e1e04e0f388fb64d/BubbleSort.playground/playground.xcworkspace/xcuserdata/a584553.xcuserdatad/UserInterfaceState.xcuserstate -------------------------------------------------------------------------------- /DFS.playground/Contents.swift: -------------------------------------------------------------------------------- 1 | import UIKit 2 | class Node{ 3 | var value: Int! 4 | var visited : Bool? 5 | var neighbors: [Edge]? 6 | init(value:Int) { 7 | self.value = value 8 | self.visited = false 9 | self.neighbors = [] 10 | } 11 | } 12 | class Edge{ 13 | var neighbor: Node? 14 | init(_ neighbor: Node) { 15 | self.neighbor = neighbor 16 | } 17 | } 18 | class Graph { 19 | var nodes:[Node]? 20 | init() { 21 | self.nodes = [] 22 | } 23 | func addNode(_ value: Int) -> Node { 24 | let node = Node(value: value) 25 | self.nodes?.append(node) 26 | return node 27 | } 28 | 29 | public func addEdge(_ source: Node, neighbor: Node) { 30 | let edge = Edge(neighbor) 31 | source.neighbors?.append(edge) 32 | } 33 | } 34 | // 1 35 | // / \ \ \ 36 | // 2 3 4 5 37 | // \ / \ | | 38 | // 6 7 8 39 | let graph = Graph() 40 | 41 | let node1 = graph.addNode(1) 42 | let node2 = graph.addNode(2) 43 | let node3 = graph.addNode(3) 44 | let node4 = graph.addNode(4) 45 | let node5 = graph.addNode(5) 46 | let node6 = graph.addNode(6) 47 | let node7 = graph.addNode(7) 48 | let node8 = graph.addNode(8) 49 | 50 | graph.addEdge(node1, neighbor: node2) 51 | graph.addEdge(node1, neighbor: node3) 52 | graph.addEdge(node1, neighbor: node4) 53 | graph.addEdge(node1, neighbor: node5) 54 | graph.addEdge(node2, neighbor: node6) 55 | graph.addEdge(node3, neighbor: node6) 56 | graph.addEdge(node3, neighbor: node7) 57 | graph.addEdge(node4, neighbor: node7) 58 | graph.addEdge(node5, neighbor: node8) 59 | 60 | var possiblePaths = [Int]() 61 | var possiblePathsArray = [[Int]]() 62 | func findAllPossiblePaths(_ graph: Graph, source: Node) -> [[Int]]{ 63 | for edge in source.neighbors! { 64 | if !(possiblePaths.contains(source.value)){ 65 | possiblePaths.append(source.value) 66 | } 67 | possiblePaths.append(edge.neighbor?.value ?? 0) 68 | _ = findAllPossiblePaths(graph, source: edge.neighbor!) 69 | } 70 | if possiblePaths.count > 0 { 71 | possiblePathsArray.append(possiblePaths) 72 | } 73 | possiblePaths.removeAll() 74 | return possiblePathsArray 75 | } 76 | 77 | func depthFirstSearch(_ graph: Graph, source: Node?) -> [Int?] { 78 | var nodesExplored = [source?.value] 79 | source?.visited = true 80 | 81 | for edge in (source?.neighbors!)! { 82 | if !edge.neighbor!.visited! { 83 | nodesExplored += depthFirstSearch(graph, source: edge.neighbor) 84 | } 85 | } 86 | return nodesExplored 87 | } 88 | 89 | let dfs = depthFirstSearch(graph, source: node1) 90 | print(dfs.map( { $0! } )) 91 | 92 | print(findAllPossiblePaths(graph, source: node1)) 93 | -------------------------------------------------------------------------------- /DFS.playground/contents.xcplayground: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /DFS.playground/playground.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /DFS.playground/playground.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | IDEDidComputeMac32BitWarning 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /DFS.playground/playground.xcworkspace/xcuserdata/richu.xcuserdatad/UserInterfaceState.xcuserstate: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Richa0305/Data-Structure-with-swift/072c1d23f8770d6c0c7ab289e1e04e0f388fb64d/DFS.playground/playground.xcworkspace/xcuserdata/richu.xcuserdatad/UserInterfaceState.xcuserstate -------------------------------------------------------------------------------- /DP.playground/Pages/Fib.xcplaygroundpage/Contents.swift: -------------------------------------------------------------------------------- 1 | //: [Previous](@previous) 2 | 3 | import Foundation 4 | 5 | /** 6 | fib - https://www.structy.net/problems/fib 7 | Write a function fib that takes in a number argument, n, and returns the n-th number of the Fibonacci sequence. 8 | The 0-th number of the sequence is 0. 9 | The 1-st number of the sequence is 1. 10 | To generate further numbers of the sequence, calculate the sum of previous two numbers. 11 | 12 | 0 1 1 2 3 5 8 13 21 13 | 14 | */ 15 | 16 | func fib(num: Int, memo: inout [Int:Int]) -> Int { 17 | if memo.keys.contains(num) { 18 | return memo[num]! 19 | } 20 | if num == 0 || num == 1 { 21 | return num 22 | } 23 | memo[num] = fib(num: num-1, memo: &memo) + fib(num: num-2,memo: &memo) 24 | return memo[num]! 25 | } 26 | var memo = [Int:Int]() 27 | fib(num: 8,memo: &memo) 28 | -------------------------------------------------------------------------------- /DP.playground/Pages/arrayStepper.xcplaygroundpage/Contents.swift: -------------------------------------------------------------------------------- 1 | //: [Previous](@previous) 2 | 3 | import Foundation 4 | 5 | /** 6 | 7 | array stepper https://www.structy.net/problems/array-stepper 8 | Write a function, arrayStepper, that takes in an array of numbers as an argument. You start at the first position of the array. The function should return a boolean indicating whether or not it is possible to reach the last position of the array. When situated at some position of the array, you may take a maximum number of steps based on the number at that position. 9 | For example, given: 10 | 11 | idx = 0 1 2 3 4 5 12 | numbers = [2, 4, 2, 0, 0, 1] 13 | 14 | The answer is true. 15 | We start at idx 0, we could take 1 step or 2 steps forward. 16 | The correct choice is to take 1 step to idx 1. 17 | Then take 4 steps forward to the end at idx 5. 18 | */ 19 | 20 | 21 | func arrayStepper(_ arr:[Int],_ i: Int) -> Bool { 22 | if i >= arr.count - 1 { 23 | return true 24 | } 25 | let maxStep = arr[i] 26 | if maxStep > 0 { 27 | for step in 1...maxStep { 28 | if arrayStepper(arr, step + i) { 29 | print(i) 30 | return true 31 | } 32 | } 33 | } 34 | return false 35 | } 36 | arrayStepper([2, 4, 2, 0, 0, 1], 0) 37 | 38 | 39 | 40 | 41 | func arrayStepperDP(_ arr:[Int],_ i: Int,_ memo: inout [Int:Bool]) -> Bool { 42 | if let val = memo[i] { 43 | return val 44 | } 45 | if i >= arr.count - 1 { 46 | return true 47 | } 48 | let maxStep = arr[i] 49 | if maxStep > 0 { 50 | for step in 1...maxStep { 51 | if arrayStepperDP(arr, step + i, &memo) { 52 | memo[i] = true 53 | return true 54 | } 55 | } 56 | } 57 | memo[i] = false 58 | return false 59 | } 60 | var memo : [Int: Bool] = [:] 61 | arrayStepperDP([2, 4, 2, 0, 0, 1], 0, &memo) 62 | -------------------------------------------------------------------------------- /DP.playground/Pages/countPaths.xcplaygroundpage/Contents.swift: -------------------------------------------------------------------------------- 1 | //: [Previous](@previous) 2 | 3 | /** 4 | count paths - https://www.structy.net/problems/count-paths 5 | Write a function, countPaths, that takes in a grid as an argument. In the grid, 'X' represents walls and 'O' represents open spaces. You may only move down or to the right and cannot pass through walls. The function should return the number of ways possible to travel from the top-left corner of the grid to the bottom-right corner. 6 | 7 | const grid = [ 8 | ["O", "O"], 9 | ["O", "O"], 10 | ]; 11 | countPaths(grid); // -> 2 12 | 13 | const grid = [ 14 | ["O", "O", "X"], 15 | ["O", "O", "O"], 16 | ["O", "O", "O"], 17 | ]; 18 | countPaths(grid); // -> 5 19 | 20 | */ 21 | import Foundation 22 | func countPaths(grid: [[String]]) -> Int { 23 | var memo = [String:Int]() 24 | return getPathCount(grid,0,0, &memo) 25 | } 26 | 27 | func getPathCount(_ grid: [[String]],_ r: Int,_ c:Int,_ memo:inout [String:Int]) -> Int { 28 | if let val = memo["\(r),\(c)"] { 29 | return val 30 | } 31 | if r == grid.count || c == grid[0].count { 32 | return 0 33 | } 34 | if grid[r][c] == "X" { 35 | return 0 36 | } 37 | if (r == grid.count - 1) && (c == grid[0].count - 1) { 38 | return 1 39 | } 40 | // as its given in problem that we can only move down and left 41 | let downPathCount = getPathCount(grid, r + 1, c, &memo) 42 | let leftPathCount = getPathCount(grid, r, c + 1, &memo) 43 | memo["\(r),\(c)"] = downPathCount + leftPathCount 44 | return memo["\(r),\(c)"]! 45 | } 46 | countPaths(grid: [["O", "O", "X"],["O", "O", "O"],["O", "O", "O"]]) 47 | -------------------------------------------------------------------------------- /DP.playground/Pages/maxPathSum.xcplaygroundpage/Contents.swift: -------------------------------------------------------------------------------- 1 | //: [Previous](@previous) 2 | 3 | import Foundation 4 | 5 | /** 6 | max path sum - https://www.structy.net/problems/max-path-sum 7 | Write a function, maxPathSum, that takes in a grid as an argument. The function should return the maximum sum possible by traveling a path from the top-left corner to the bottom-right corner. You may only travel through the grid by moving down or right. 8 | 9 | You can assume that all numbers are non-negative. 10 | const grid = [ 11 | [1, 3, 12], 12 | [5, 1, 1], 13 | [3, 6, 1], 14 | ]; 15 | maxPathSum(grid); // -> 18 16 | */ 17 | func maxPathSum(grid: [[Int]]) -> Int { 18 | var memo = [String:Int]() 19 | return getMaxPathSum(grid,0,0, &memo) 20 | } 21 | 22 | func getMaxPathSum(_ grid: [[Int]],_ r: Int,_ c:Int,_ memo:inout [String:Int]) -> Int { 23 | if let val = memo["\(r),\(c)"] { 24 | return val 25 | } 26 | if r == grid.count || c == grid[0].count { 27 | return -1 28 | } 29 | 30 | if (r == grid.count - 1) && (c == grid[0].count - 1) { 31 | return grid[r][c] 32 | } 33 | // as its given in problem that we can only move down and left 34 | let downPathSum = getMaxPathSum(grid, r + 1, c, &memo) 35 | let leftPathSum = getMaxPathSum(grid, r, c + 1, &memo) 36 | memo["\(r),\(c)"] = grid[r][c] + max(downPathSum, leftPathSum) 37 | return memo["\(r),\(c)"]! 38 | } 39 | maxPathSum(grid: [[1, 3, 12],[5, 1, 1],[3, 6, 1]]) 40 | -------------------------------------------------------------------------------- /DP.playground/Pages/minChange.xcplaygroundpage/Contents.swift: -------------------------------------------------------------------------------- 1 | /** 2 | 3 | min change https://www.structy.net/problems/min-change 4 | Write a function minChange that takes in an amount and an array of coins. The function should return the minimum number of coins required to create the amount. You may use each coin as many times as necessary. 5 | 6 | If it is not possible to create the amount, then return -1. 7 | 8 | minChange(8, [1, 5, 4, 12]); // -> 2, because 4+4 is the minimum coins possible 9 | */ 10 | import Foundation 11 | 12 | func minChange(target: Int, arr: [Int], memo: inout [Int:Int]) -> Int { 13 | if let val = memo[target] { 14 | return val 15 | } 16 | if arr.isEmpty { 17 | return -1 18 | } 19 | if target == 0 { 20 | return 0 21 | } 22 | if target < 0 { 23 | return 999999 24 | } 25 | var minVal = 999999 26 | for item in arr { 27 | 28 | memo[target] = min(1 + minChange(target: target - item, arr: arr,memo: &memo), minVal) 29 | minVal = memo[target]! 30 | } 31 | 32 | 33 | return minVal 34 | } 35 | var memo = [Int:Int]() 36 | minChange(target: 8, arr: [1, 5, 4, 12], memo: &memo) 37 | -------------------------------------------------------------------------------- /DP.playground/Pages/nonAdjacentSum.xcplaygroundpage/Contents.swift: -------------------------------------------------------------------------------- 1 | //: [Previous](@previous) 2 | 3 | import Foundation 4 | 5 | /** 6 | non adjacent sum https://www.structy.net/problems/non-adjacent-sum 7 | Write a function, nonAdjacentSum, that takes in an array of numbers as an argument. The function should return the maximum sum of non-adjacent elements in the array. There is no limit on how many elements can be taken into the sum as long as they are not adjacent. 8 | 9 | For example, given: 10 | 11 | [2, 4, 5, 12, 7] 12 | 13 | The maximum non-adjacent sum is 16, because 4 + 12. 14 | 4 and 12 are not adjacent in the array. 15 | */ 16 | func nonAdjacentSum(_ arr:[Int],_ i: Int = 0,_ memo: inout [Int:Int]) -> Int { 17 | if let val = memo[i] { 18 | return val 19 | } 20 | if i >= arr.count 21 | { 22 | return 0 23 | } 24 | let include = arr[i] + nonAdjacentSum(arr, i+2, &memo) 25 | let exclude = nonAdjacentSum(arr,i+1, &memo) 26 | memo[i] = max(include, exclude) 27 | return memo[i]! 28 | } 29 | var memo = [Int:Int]() 30 | nonAdjacentSum([2, 4, 5, 12, 7],0,&memo) 31 | -------------------------------------------------------------------------------- /DP.playground/Pages/sumPossible.xcplaygroundpage/Contents.swift: -------------------------------------------------------------------------------- 1 | 2 | /** 3 | sumPossible https://www.structy.net/problems/sum-possible 4 | Write a function sumPossible that takes in an amount and an array of positive numbers. The function should return a boolean indicating whether or not it is possible to create the amount by summing numbers of the array. You may reuse numbers of the array as many times as necessary. 5 | 6 | You may assume that the target amount is non-negative. 7 | 8 | sumPossible(8, [5, 12, 4]); // -> true, 4 + 4 9 | 8 10 | 3 4 11 | 0 12 | */ 13 | 14 | func sumPossible(target: Int, arr: [Int]) -> Bool { 15 | //print(target) 16 | if target == 0 { 17 | return true 18 | } 19 | 20 | if target < 0 { 21 | return false 22 | } 23 | 24 | for num in arr { 25 | if sumPossible(target: target - num, arr: arr) { 26 | return true 27 | } 28 | } 29 | 30 | return false 31 | } 32 | sumPossible(target: 8, arr: [5, 12, 4]) 33 | 34 | func sumPossibleWithPD(target: Int, arr: [Int], memo : inout [Int: Bool]) -> Bool { 35 | //print(target) 36 | if let flag = memo[target] { 37 | return flag 38 | } 39 | if target == 0 { 40 | return true 41 | } 42 | 43 | if target < 0 { 44 | return false 45 | } 46 | 47 | for num in arr { 48 | if sumPossibleWithPD(target: target - num, arr: arr, memo: &memo) { 49 | print(num) 50 | memo[target] = true 51 | return true 52 | } 53 | } 54 | memo[target] = false 55 | print(memo) 56 | return false 57 | } 58 | var memo = [Int:Bool]() 59 | sumPossibleWithPD(target: 8, arr: [5, 12, 4],memo: &memo) 60 | -------------------------------------------------------------------------------- /DP.playground/contents.xcplayground: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /DP.playground/playground.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /DP.playground/playground.xcworkspace/xcuserdata/richa.e.srivastava.xcuserdatad/UserInterfaceState.xcuserstate: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Richa0305/Data-Structure-with-swift/072c1d23f8770d6c0c7ab289e1e04e0f388fb64d/DP.playground/playground.xcworkspace/xcuserdata/richa.e.srivastava.xcuserdatad/UserInterfaceState.xcuserstate -------------------------------------------------------------------------------- /DP.playground/xcuserdata/richa.e.srivastava.xcuserdatad/xcschemes/xcschememanagement.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | SchemeUserState 6 | 7 | DP (Playground).xcscheme 8 | 9 | isShown 10 | 11 | orderHint 12 | 0 13 | 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /DSNotes.pages: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Richa0305/Data-Structure-with-swift/072c1d23f8770d6c0c7ab289e1e04e0f388fb64d/DSNotes.pages -------------------------------------------------------------------------------- /DSNotes.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Richa0305/Data-Structure-with-swift/072c1d23f8770d6c0c7ab289e1e04e0f388fb64d/DSNotes.pdf -------------------------------------------------------------------------------- /Dynamic-Programming-KnapSack-Recursive-Approach: -------------------------------------------------------------------------------- 1 | https://www.youtube.com/watch?v=nqowUJzG-iM&list=PL_z_8CaSLPWekqhdCPmFohncHwz8TY2Go 2 | 3 | ##Dynamic Programming - 4 | Dynamic Programming is mainly an optimization over a plain recursion. In DP we memorize the result of recursive function of some specific state, 5 | which can then be later accessed to solve other sub-problems. 6 | 7 | DP = Recursion -> Memozation -> top down approach 8 | 9 | Knapsack problem statement - Given a bag, and some items(with weight and value of each item) and max weight capacity of the bag. Add items to the bag which can give max profit. 10 | 11 | Types of knapsack - 12 | 1. 0-1 knapsack - In this we can either put an item in bag or we cant put it in bag 13 | 2. fractional - In this we can put some fraction of the item to achieve max profit 14 | 3. unbounded - Similar as 0-1 but any item can be added multiple times 15 | 16 | 17 | Knapsack problem exmaple - 18 | Input - 19 | Weight[] - [1, 3, 4, 5] 20 | Value[] - [1, 4, 5, 7] 21 | Total max Weight of bag - 10 22 | total items count - 4 23 | Output - Max Profit 24 | 25 | Recursive Approach - 26 | Any recursive call looks like this - 27 | 28 | func myRecursiveFunc(inputs) -> outputs { 29 | [Base Condition] - Think of the smallest valid input 30 | [Choice Diagram] 31 | } 32 | 33 | func knapsack(weightArr: Array, valueArr: Array, totalWeight: Int, itemsCount: Int) -> Int { 34 | 35 | // Base condition 36 | if (totalWeight == 0 || itemsCount == 0) { 37 | return 0 38 | } 39 | 40 | //Choice Diagram 41 | [WeightLastItemOfArray] 42 | / \ 43 | / \ 44 | / \ 45 | [WeightLastItemOfArray < totalWeight] [WeightLastItemOfArray > totalWeight] 46 | / \ | 47 | / \ | 48 | [Include value] [Cant Include value] [Cant Include value] 49 | 50 | 51 | 52 | 53 | [weightArr[n-1]] 54 | / \ 55 | / \ 56 | / \ 57 | [weightArr[n-1] < totalWeight] [weightArr[n-1] > totalWeight] 58 | / \ | 59 | / \ | 60 | [Include value] [Cant Include value] [Cant Include value] 61 | 62 | 63 | if (weightArr[n-1] < totalWeight) { 64 | return max(valueArr[n-1] + knapsack(weightArr, valueArr, totalWeight - weightArr[n-1], n-1), 65 | knapsack(weightArr, valueArr, totalWeight, n-1)) 66 | } else if (weightArr[n-1] > totalWeight) { 67 | return knapsack(weightArr, valueArr, totalWeight, n-1) 68 | } 69 | } 70 | 71 | 72 | 73 | // Final Function - 74 | 75 | 76 | func knapsack(weightArr: Array, valueArr: Array, totalWeight: Int, itemsCount: Int) -> Int { 77 | 78 | // Base condition 79 | if (totalWeight == 0 || itemsCount == 0) { 80 | return 0 81 | } 82 | 83 | // Choise diagram code 84 | if (weightArr[n-1] < totalWeight) { 85 | return max(valueArr[n-1] + knapsack(weightArr, valueArr, totalWeight - weightArr[n-1], n-1), 86 | knapsack(weightArr, valueArr, totalWeight, n-1)) 87 | } else if (weightArr[n-1] > totalWeight) { 88 | return knapsack(weightArr, valueArr, totalWeight, n-1) 89 | } 90 | 91 | } 92 | -------------------------------------------------------------------------------- /FindCommonInThreeArrays.playground/Contents.swift: -------------------------------------------------------------------------------- 1 | //: Playground - noun: a place where people can play 2 | // By Richa Srivastava 3 | // https://www.youtube.com/watch?v=B6Tsrmgsy3k 4 | 5 | import Foundation 6 | 7 | let arr1 = [1,2,3,4,5,6,7] 8 | let arr2 = [5,6,7,8,9,10] 9 | let arr3 = [6,7,8,9,10,11,12] 10 | 11 | func findCommon(a1:[Int],a2:[Int],a3:[Int]) -> [Int]{ 12 | 13 | var x = 0 14 | var y = 0 15 | var z = 0 16 | var result = [Int]() 17 | 18 | while (x <= a1.count-1) && (y <= a2.count-1) && (z <= a3.count-1){ 19 | if (a1[x] == a2[y]) && (a2[y] == a3[z]){ 20 | result.append(a1[x]) 21 | x = x + 1 22 | y = y + 1 23 | z = z + 1 24 | }else if a1[x] < a2[y] { 25 | x = x + 1 26 | }else if a2[y] < a3[z]{ 27 | y = y + 1 28 | }else{ 29 | z = z + 1 30 | } 31 | } 32 | return result 33 | } 34 | 35 | let res = findCommon(a1: arr1, a2: arr2, a3: arr3) 36 | print(res) 37 | -------------------------------------------------------------------------------- /FindCommonInThreeArrays.playground/contents.xcplayground: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /FindCommonInThreeArrays.playground/playground.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /FindCommonInThreeArrays.playground/playground.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | IDEDidComputeMac32BitWarning 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /FindCommonInThreeArrays.playground/playground.xcworkspace/xcuserdata/a584553.xcuserdatad/UserInterfaceState.xcuserstate: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Richa0305/Data-Structure-with-swift/072c1d23f8770d6c0c7ab289e1e04e0f388fb64d/FindCommonInThreeArrays.playground/playground.xcworkspace/xcuserdata/a584553.xcuserdatad/UserInterfaceState.xcuserstate -------------------------------------------------------------------------------- /FindCommonInThreeArrays.playground/playground.xcworkspace/xcuserdata/richu.xcuserdatad/UserInterfaceState.xcuserstate: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Richa0305/Data-Structure-with-swift/072c1d23f8770d6c0c7ab289e1e04e0f388fb64d/FindCommonInThreeArrays.playground/playground.xcworkspace/xcuserdata/richu.xcuserdatad/UserInterfaceState.xcuserstate -------------------------------------------------------------------------------- /Graph.playground/Contents.swift: -------------------------------------------------------------------------------- 1 | import UIKit 2 | 3 | // Graph Adjacency List - with Dictionary of Arrays 4 | 5 | 6 | import UIKit 7 | class Vertex{ 8 | var value: T 9 | var visited : Bool? 10 | var neighbours: [Edge]? 11 | init(value:T) { 12 | self.value = value 13 | self.visited = false 14 | self.neighbours = [] 15 | } 16 | } 17 | class Edge { 18 | var neighbour: Vertex? 19 | init(_ neighbour: Vertex) { 20 | self.neighbour = neighbour 21 | } 22 | } 23 | 24 | public struct Queue { 25 | private var array: [T] 26 | public init() { 27 | array = [] 28 | } 29 | public mutating func enqueue(_ element: T) { 30 | array.append(element) 31 | } 32 | public mutating func dequeue() -> T? { 33 | if array.isEmpty { 34 | return nil 35 | } else { 36 | return array.removeLast() 37 | } 38 | } 39 | } 40 | 41 | public struct Stack { 42 | public var array : [T] 43 | public init() { 44 | array = [] 45 | } 46 | public mutating func push(element: T) { 47 | array.append(element) 48 | } 49 | public mutating func pop() -> T? { 50 | return array.removeFirst() 51 | } 52 | 53 | public mutating func isEmpty() -> Bool { 54 | return array.isEmpty 55 | } 56 | } 57 | 58 | class Graph { 59 | var vertices:[Vertex]? 60 | init() { 61 | self.vertices = [] 62 | } 63 | func addVertex(_ value: T) -> Vertex { 64 | let vertex = Vertex(value: value) 65 | self.vertices?.append(vertex) 66 | return vertex 67 | } 68 | 69 | public func addEdge(_ source: Vertex, neighbour: Vertex) { 70 | let edge = Edge(neighbour) 71 | source.neighbours?.append(edge) 72 | } 73 | } 74 | 75 | 76 | 77 | // 1 78 | // / \ \ \ 79 | // 2 3 4 5 80 | // \ / \ | | 81 | // 6 7 8 82 | let graph = Graph() 83 | 84 | let node1 = graph.addVertex(1) 85 | let node2 = graph.addVertex(2) 86 | let node3 = graph.addVertex(3) 87 | let node4 = graph.addVertex(4) 88 | let node5 = graph.addVertex(5) 89 | let node6 = graph.addVertex(6) 90 | let node7 = graph.addVertex(7) 91 | let node8 = graph.addVertex(8) 92 | 93 | graph.addEdge(node1, neighbour: node2) 94 | graph.addEdge(node1, neighbour: node3) 95 | graph.addEdge(node1, neighbour: node4) 96 | graph.addEdge(node1, neighbour: node5) 97 | graph.addEdge(node2, neighbour: node6) 98 | graph.addEdge(node3, neighbour: node6) 99 | graph.addEdge(node3, neighbour: node7) 100 | graph.addEdge(node4, neighbour: node7) 101 | graph.addEdge(node5, neighbour: node8) 102 | 103 | func breadthFirstSearch(source: Vertex) -> [Int] { 104 | var queue = Queue>() 105 | queue.enqueue(source) 106 | var verticesExplored = [source.value] 107 | source.visited = true 108 | while let vertex = queue.dequeue() { 109 | for edge in vertex.neighbours! { 110 | let neighbourVertex = edge.neighbour 111 | if !neighbourVertex!.visited! { 112 | queue.enqueue(neighbourVertex!) 113 | neighbourVertex!.visited = true 114 | verticesExplored.append(neighbourVertex!.value) 115 | } 116 | } 117 | } 118 | return verticesExplored 119 | } 120 | 121 | 122 | func depthFirstSearch(source: Vertex) -> [Int] { 123 | var nodesExplored = [source.value] 124 | source.visited = true 125 | 126 | for edge in (source.neighbours!) { 127 | if !edge.neighbour!.visited! { 128 | nodesExplored += depthFirstSearch(source: edge.neighbour!) 129 | } 130 | } 131 | return nodesExplored 132 | } 133 | print(depthFirstSearch(source: node1)) 134 | -------------------------------------------------------------------------------- /Graph.playground/Pages/1.BFS & DFS.xcplaygroundpage/Contents.swift: -------------------------------------------------------------------------------- 1 | import UIKit 2 | 3 | // https://www.youtube.com/watch?v=tWVWeAqZ0WU 4 | 5 | // DFS Iterative approach with stack 6 | func depthFirstSearch(graph: Dictionary, source: String) { 7 | var stack = [source] 8 | while stack.count > 0 { 9 | let current = stack.removeLast() 10 | print(current) 11 | if let list = graph[current] { 12 | for val in list { 13 | stack.append(val) 14 | } 15 | } 16 | 17 | } 18 | } 19 | 20 | // DFS Recursive approach with inbuilt call stacks of recursive calls 21 | func dfsRecur(graph: Dictionary, source: String) { 22 | print(source) 23 | if let neighbors = graph[source] { 24 | for item in neighbors { 25 | dfsRecur(graph: graph, source: item) 26 | } 27 | } 28 | } 29 | 30 | // BFS Iterative approach with queue, this cant be implemented with recursion as recursion uses stack for recursive calls 31 | func breadthFirstSearch(graph: Dictionary, source: String) { 32 | var queue = [source] 33 | while !queue.isEmpty { 34 | let current = queue.removeFirst() 35 | print(current) 36 | if let list = graph[current] { 37 | for item in list { 38 | queue.append(item) 39 | } 40 | } 41 | } 42 | } 43 | 44 | 45 | 46 | 47 | 48 | let graph = [ 49 | "a" : ["b", "c"], 50 | "b" : ["d"], 51 | "c" : ["e"], 52 | "d" : ["f"], 53 | "e" : [], 54 | "f" : [] 55 | ] 56 | print("===DFS Iterative Approcah===") 57 | depthFirstSearch(graph: graph, source: "a") 58 | print() 59 | 60 | print("===DFS Recusive Approcah===") 61 | dfsRecur(graph: graph, source: "a") 62 | print() 63 | 64 | print("===BFS===") 65 | breadthFirstSearch(graph: graph, source: "a") 66 | print() 67 | -------------------------------------------------------------------------------- /Graph.playground/Pages/2.hasPathDicrected.xcplaygroundpage/Contents.swift: -------------------------------------------------------------------------------- 1 | //: [Previous](@previous) 2 | 3 | import Foundation 4 | 5 | // check for path in a directed & acyclic graph 6 | /** 7 | Write a function, hasPath, that takes in an object representing the adjacency list of a directed acyclic graph and two nodes (src, dst). The function should return a boolean indicating whether or not there exists a directed path between the source and destination nodes. 8 | */ 9 | 10 | func hasPath(graph: Dictionary, src: String, dest: String) -> Bool { 11 | var queue = [src] 12 | while !queue.isEmpty { 13 | let current = queue.removeFirst() 14 | if current == dest { 15 | return true 16 | } 17 | if let adjList = graph[current] { 18 | for item in adjList { 19 | queue.append(item) 20 | } 21 | } 22 | } 23 | return false 24 | } 25 | 26 | func hasPathRecusive(graph: Dictionary, src: String, dest: String) -> Bool { 27 | 28 | if src == dest { 29 | return true 30 | } 31 | if let adjList = graph[src] { 32 | for item in adjList { 33 | if hasPathRecusive(graph: graph, src: item, dest: dest) { 34 | return true 35 | } 36 | } 37 | } 38 | 39 | return false 40 | } 41 | 42 | 43 | let graph = [ 44 | "a" : ["b", "c"], 45 | "b" : ["d"], 46 | "c" : ["e"], 47 | "d" : ["f"], 48 | "e" : [], 49 | "f" : [] 50 | ] 51 | 52 | print("===hasPath in Dicrected Acyclic graph With BFS===") 53 | hasPath(graph: graph, src: "b", dest: "f") 54 | print() 55 | 56 | print("===hasPath in Dicrected Acyclic graph With DFS===") 57 | hasPathRecusive(graph: graph, src: "b", dest: "f") 58 | print() 59 | 60 | -------------------------------------------------------------------------------- /Graph.playground/Pages/3.hasPathUnDirected.xcplaygroundpage/Contents.swift: -------------------------------------------------------------------------------- 1 | //: [Previous](@previous) 2 | 3 | import Foundation 4 | 5 | /** 6 | Write a function, undirectedPath, that takes in an array of edges for an undirected graph and two nodes (nodeA, nodeB). The function should return a boolean indicating whether or not there exists a path between nodeA and nodeB. 7 | 8 | const edges = [ 9 | ['i', 'j'], 10 | ['k', 'i'], 11 | ['m', 'k'], 12 | ['k', 'l'], 13 | ['o', 'n'] 14 | ]; 15 | 16 | undirectedPath(edges, 'j', 'm'); // -> true 17 | 18 | 19 | Since it is cyclic & directed graph we need to keep track of visited node else we will get stuck in cycle/infine loop 20 | 21 | */ 22 | 23 | func hasPathUndirected(edges : [[String]], nodeA: String, nodeB: String) -> Bool { 24 | let graph = buildGraph(edges: edges) 25 | print(graph) 26 | var visitedSet = Set() 27 | return hasPathUndirectedGraph(graph: graph, src: nodeA, dest: nodeB, visited: &visitedSet) 28 | } 29 | 30 | func hasPathUndirectedGraph(graph: Dictionary, src: String, dest: String, visited: inout Set) -> Bool { 31 | if src == dest { 32 | return true 33 | } 34 | if visited.contains(src) { 35 | return false 36 | } 37 | visited.insert(src) 38 | if let adjList = graph[src] { 39 | for item in adjList { 40 | if hasPathUndirectedGraph(graph: graph, src: item, dest: dest, visited: &visited) { 41 | return true 42 | } 43 | } 44 | } 45 | 46 | 47 | return false 48 | } 49 | 50 | func buildGraph(edges : [[String]]) -> Dictionary{ 51 | var graph = Dictionary() 52 | for edge in edges { 53 | let v1 = edge[0] 54 | let v2 = edge[1] 55 | if var _ = graph[v1] { 56 | graph[v1]?.append(v2) 57 | } else { 58 | graph[v1] = [v2] 59 | } 60 | if var _ = graph[v2] { 61 | graph[v2]?.append(v1) 62 | } else { 63 | graph[v2] = [v1] 64 | } 65 | 66 | } 67 | return graph 68 | } 69 | 70 | let edges = [ 71 | ["i", "j"], 72 | ["k", "i"], 73 | ["m", "k"], 74 | ["k", "l"], 75 | ["o", "n"] 76 | ] 77 | 78 | print("===hasPath in Dicrected cyclic graph With BFS===") 79 | hasPathUndirected(edges: edges, nodeA: "j", nodeB: "m") 80 | print() 81 | 82 | -------------------------------------------------------------------------------- /Graph.playground/Pages/4.connectComponentCount.xcplaygroundpage/Contents.swift: -------------------------------------------------------------------------------- 1 | //: [Previous](@previous) 2 | 3 | import Foundation 4 | 5 | /** 6 | Write a function, connectedComponentsCount, that takes in the adjacency list of an undirected graph. The function should return the number of connected components within the graph. 7 | 8 | connectedComponentsCount({ 9 | 0: [8, 1, 5], 10 | 1: [0], 11 | 5: [0, 8], 12 | 8: [0, 5], 13 | 2: [3, 4], 14 | 3: [2, 4], 15 | 4: [3, 2] 16 | }); // -> 2 17 | 18 | */ 19 | 20 | func connectedComponentsCount(graph: Dictionary) -> Int { 21 | var visisted = Set() 22 | var count = 0 23 | 24 | for (_,key) in graph.keys.enumerated() { 25 | if traverse(graph: graph, node: key, visited: &visisted) { 26 | count += 1 27 | } 28 | } 29 | 30 | return count 31 | } 32 | 33 | func traverse(graph: Dictionary, node: Int ,visited: inout Set) -> Bool { 34 | if visited.contains(node) { 35 | return false 36 | } 37 | visited.insert(node) 38 | if let adjList = graph[node] { 39 | for item in adjList { 40 | traverse(graph: graph, node: item, visited: &visited) 41 | } 42 | } 43 | return true 44 | } 45 | connectedComponentsCount(graph: [ 46 | 3: [], 47 | 4: [6], 48 | 6: [4, 5, 7, 8], 49 | 8: [6], 50 | 7: [6], 51 | 5: [6], 52 | 1: [2], 53 | 2: [1] 54 | ]) 55 | -------------------------------------------------------------------------------- /Graph.playground/Pages/5.largestComponent.xcplaygroundpage/Contents.swift: -------------------------------------------------------------------------------- 1 | //: [Previous](@previous) 2 | 3 | import Foundation 4 | 5 | /** 6 | Write a function, largestComponent, that takes in the adjacency list of an undirected graph. The function should return the size of the largest connected component in the graph. 7 | 8 | largestComponent(graph: [ 9 | 0: [8, 1, 5], 10 | 1: [0], 11 | 5: [0, 8], 12 | 8: [0, 5], 13 | 2: [3, 4], 14 | 3: [2, 4], 15 | 4: [3, 2] 16 | ]) -> 4 17 | 18 | */ 19 | 20 | func largestComponent(graph: Dictionary) -> Int { 21 | var size = 0 22 | var visited = Set() 23 | for (_,key) in graph.keys.enumerated() { 24 | let currentNodeSize = getCurrentNodeSize(graph: graph, node: key, visited: &visited) 25 | if currentNodeSize > 0 && currentNodeSize > size { 26 | size = currentNodeSize 27 | } 28 | } 29 | return size 30 | } 31 | 32 | func getCurrentNodeSize(graph: Dictionary, node: Int, visited: inout Set) -> Int { 33 | if visited.contains(node) { 34 | return 0 35 | } 36 | visited.insert(node) 37 | var size = 1 38 | if let adjList = graph[node] { 39 | for item in adjList { 40 | size += getCurrentNodeSize(graph: graph, node: item, visited: &visited) 41 | } 42 | } 43 | 44 | return size 45 | 46 | } 47 | largestComponent(graph: [ 48 | 3: [], 49 | 4: [6], 50 | 6: [4, 5, 7, 8], 51 | 8: [6], 52 | 7: [6], 53 | 5: [6], 54 | 1: [2], 55 | 2: [1] 56 | ]) 57 | -------------------------------------------------------------------------------- /Graph.playground/Pages/6.shortestPath.xcplaygroundpage/Contents.swift: -------------------------------------------------------------------------------- 1 | //: [Previous](@previous) 2 | 3 | import Foundation 4 | 5 | /** 6 | Write a function, shortestPath, that takes in an array of edges for an undirected graph and two nodes (nodeA, nodeB). The function should return the length of the shortest path between A and B. Consider the length as the number of edges in the path, not the number of nodes. If there is no path between A and B, then return -1. 7 | const edges = [ 8 | ['w', 'x'], 9 | ['x', 'y'], 10 | ['z', 'y'], 11 | ['z', 'v'], 12 | ['w', 'v'] 13 | ]; 14 | 15 | shortestPath(edges, 'w', 'z'); // -> 2 16 | */ 17 | 18 | func shortestPath(edges:[[String]], nodeA: String, nodeB: String) -> Int { 19 | let graph = buildGraph(edges: edges) 20 | var queue = [ (nodeA, 0 )] 21 | var visited = Set() 22 | visited.insert(nodeA) 23 | 24 | while !queue.isEmpty { 25 | let (current, distance) = queue.removeFirst() 26 | if current == nodeB { 27 | return distance 28 | } 29 | if let adjList = graph[current] { 30 | for item in adjList { 31 | if !visited.contains(item) { 32 | visited.insert(item) 33 | queue.append((item, distance + 1)) 34 | } 35 | } 36 | } 37 | } 38 | 39 | 40 | return -1 41 | } 42 | 43 | func buildGraph(edges : [[String]]) -> Dictionary{ 44 | var graph = Dictionary() 45 | for edge in edges { 46 | let v1 = edge[0] 47 | let v2 = edge[1] 48 | if var _ = graph[v1] { 49 | graph[v1]?.append(v2) 50 | } else { 51 | graph[v1] = [v2] 52 | } 53 | if var _ = graph[v2] { 54 | graph[v2]?.append(v1) 55 | } else { 56 | graph[v2] = [v1] 57 | } 58 | 59 | } 60 | return graph 61 | } 62 | 63 | shortestPath(edges: [ ["w", "x"], 64 | ["x", "y"], 65 | ["z", "y"], 66 | ["z", "v"], 67 | ["w", "v"]], nodeA: "w", nodeB: "z") 68 | -------------------------------------------------------------------------------- /Graph.playground/Pages/7.islandCount.xcplaygroundpage/Contents.swift: -------------------------------------------------------------------------------- 1 | //: [Previous](@previous) 2 | 3 | import Foundation 4 | 5 | /** 6 | Write a function, islandCount, that takes in a grid containing Ws and Ls. W represents water and L represents land. The function should return the number of islands on the grid. An island is a vertically or horizontally connected region of land. 7 | 8 | const grid = [ 9 | ["W", "L", "W", "W", "W"], 10 | ["W", "L", "W", "W", "W"], 11 | ["W", "W", "W", "L", "W"], 12 | ["W", "W", "L", "L", "W"], 13 | ["L", "W", "W", "L", "L"], 14 | ["L", "L", "W", "W", "W"], 15 | ]; 16 | 17 | islandCount(grid); // -> 3 18 | 19 | */ 20 | 21 | func islandCount(grid: [[String]]) -> Int { 22 | 23 | var visited = Set() 24 | var count = 0 25 | for (rIndex,row) in grid.enumerated() { 26 | for (cIndex,_) in row.enumerated() { 27 | if traverse(grid: grid, row: rIndex, column: cIndex, visited: &visited) { 28 | count += 1 29 | } 30 | } 31 | } 32 | 33 | return count 34 | } 35 | 36 | func traverse(grid: [[String]], row: Int, column: Int, visited: inout Set) -> Bool { 37 | 38 | guard row >= 0 && row < grid.count else { 39 | return false 40 | } 41 | guard column >= 0 && column < grid[0].count else { 42 | return false 43 | } 44 | 45 | if grid[row][column] == "W" { 46 | return false 47 | } 48 | 49 | if visited.contains("\(row),\(column)") { 50 | return false 51 | } 52 | visited.insert("\(row),\(column)") 53 | 54 | traverse(grid: grid, row: row, column: column + 1, visited: &visited) 55 | traverse(grid: grid, row: row, column: column - 1, visited: &visited) 56 | traverse(grid: grid, row: row + 1, column: column, visited: &visited) 57 | traverse(grid: grid, row: row - 1, column: column, visited: &visited) 58 | 59 | 60 | return true 61 | } 62 | islandCount(grid: [ 63 | ["W", "L", "W", "W", "W"], 64 | ["W", "L", "W", "W", "W"], 65 | ["W", "W", "W", "L", "W"], 66 | ["W", "W", "L", "L", "W"], 67 | ["L", "W", "W", "L", "L"], 68 | ["L", "L", "W", "W", "W"], 69 | ]) 70 | -------------------------------------------------------------------------------- /Graph.playground/Pages/8.minimumIsland.xcplaygroundpage/Contents.swift: -------------------------------------------------------------------------------- 1 | //: [Previous](@previous) 2 | 3 | import Foundation 4 | import Darwin 5 | /** 6 | minimum island 7 | Write a function, minimumIsland, that takes in a grid containing Ws and Ls. W represents water and L represents land. The function should return the size of the smallest island. An island is a vertically or horizontally connected region of land. 8 | 9 | You may assume that the grid contains at least one island. 10 | 11 | const grid = [ 12 | ['W', 'L', 'W', 'W', 'W'], 13 | ['W', 'L', 'W', 'W', 'W'], 14 | ['W', 'W', 'W', 'L', 'W'], 15 | ['W', 'W', 'L', 'L', 'W'], 16 | ['L', 'W', 'W', 'L', 'L'], 17 | ['L', 'L', 'W', 'W', 'W'], 18 | ]; 19 | 20 | minimumIsland(grid); // -> 2 21 | 22 | */ 23 | func minimumIsland(grid:[[String]]) -> Int { 24 | var minSize = 0 25 | var visited = Set() 26 | for (rIndex, row) in grid.enumerated() { 27 | for (cIndex, _) in row.enumerated() { 28 | let size = traverse(grid: grid, row: rIndex, column: cIndex, visited: &visited) 29 | if size > 0 && minSize == 0 { 30 | minSize = size 31 | } 32 | if minSize > 0 && size != 0 { 33 | minSize = min(size, minSize) 34 | } 35 | 36 | } 37 | } 38 | 39 | return minSize 40 | } 41 | 42 | func traverse(grid: [[String]], row: Int, column: Int, visited: inout Set) -> Int { 43 | guard row >= 0 && row < grid.count else { 44 | return 0 45 | } 46 | 47 | guard column >= 0 && column < grid[0].count else { 48 | return 0 49 | } 50 | 51 | if grid[row][column] == "W" { 52 | return 0 53 | } 54 | 55 | if visited.contains("\(row),\(column)") { 56 | return 0 57 | } 58 | visited.insert("\(row),\(column)") 59 | 60 | var size = 1 61 | size += traverse(grid: grid, row: row+1, column: column, visited: &visited) 62 | size += traverse(grid: grid, row: row-1, column: column, visited: &visited) 63 | size += traverse(grid: grid, row: row, column: column+1, visited: &visited) 64 | size += traverse(grid: grid, row: row, column: column-1, visited: &visited) 65 | 66 | return size 67 | } 68 | minimumIsland(grid: [ 69 | ["W", "L", "W", "W", "W"], 70 | ["W", "L", "W", "W", "W"], 71 | ["W", "W", "W", "L", "W"], 72 | ["W", "W", "L", "L", "W"], 73 | ["L", "W", "W", "L", "L"], 74 | ["L", "L", "W", "W", "W"], 75 | ]) 76 | -------------------------------------------------------------------------------- /Graph.playground/contents.xcplayground: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /Graph.playground/playground.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /Graph.playground/playground.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | IDEDidComputeMac32BitWarning 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /Graph.playground/playground.xcworkspace/xcuserdata/richa.e.srivastava.xcuserdatad/UserInterfaceState.xcuserstate: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Richa0305/Data-Structure-with-swift/072c1d23f8770d6c0c7ab289e1e04e0f388fb64d/Graph.playground/playground.xcworkspace/xcuserdata/richa.e.srivastava.xcuserdatad/UserInterfaceState.xcuserstate -------------------------------------------------------------------------------- /Graph.playground/playground.xcworkspace/xcuserdata/richa.srivastava.xcuserdatad/UserInterfaceState.xcuserstate: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Richa0305/Data-Structure-with-swift/072c1d23f8770d6c0c7ab289e1e04e0f388fb64d/Graph.playground/playground.xcworkspace/xcuserdata/richa.srivastava.xcuserdatad/UserInterfaceState.xcuserstate -------------------------------------------------------------------------------- /Graph.playground/xcuserdata/richa.e.srivastava.xcuserdatad/xcschemes/xcschememanagement.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | SchemeUserState 6 | 7 | Graph (Playground).xcscheme 8 | 9 | isShown 10 | 11 | orderHint 12 | 0 13 | 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /Heap.playground/Contents.swift: -------------------------------------------------------------------------------- 1 | 2 | // 3 | // Recursion.swift 4 | // 5 | // 6 | // Created by richa.e.srivastava on 09/03/2022. 7 | // 8 | 9 | import Foundation 10 | 11 | /** 12 | https://www.youtube.com/watch?v=hW8PrQrvMNc&list=PL_z_8CaSLPWdtY9W22VjnPxG30CXNZpI9 13 | 14 | Heap - Max Heap & Min Heap 15 | 16 | Implemented with stack 17 | 18 | Problem can contain - 19 | 20 | k smallest or largest 21 | 22 | if asking for smallest then make max heap 23 | if asking for lasgest then make min heap 24 | 25 | **/ 26 | import Foundation 27 | 28 | 29 | // fine kth smallest element 30 | 31 | struct MinHeap { 32 | var items = [T]() 33 | private func getLeftChildIndex(n: Int) -> Int { 34 | return (2*n) + 1 35 | } 36 | private func getRightChildIndex(n: Int) -> Int { 37 | return (2*n) + 2 38 | } 39 | private func getParentIndex(n: Int) -> Int { 40 | return (n - 1) / 2 41 | } 42 | // 1 43 | private func leftChild(index: Int) -> T { 44 | return items[getLeftChildIndex(n: index)] 45 | } 46 | // 2 47 | private func rightChild(index: Int) -> T { 48 | return items[getRightChildIndex(n: index)] 49 | } 50 | // 3 51 | private func parent(index: Int) -> T { 52 | return items[getParentIndex(n: index)] 53 | } 54 | public func peek() -> T? { 55 | guard items.count > 0 else { 56 | return nil 57 | } 58 | return items[0] 59 | } 60 | public mutating func add(item: T) { 61 | // 1 62 | items.append(item) 63 | 64 | // 2 65 | var lastIndex = items.count - 1 66 | // 3 67 | while parent(index: lastIndex) > items[lastIndex] { 68 | // 4 69 | items.swapAt(getParentIndex(n: lastIndex), lastIndex) 70 | // 5 71 | lastIndex = getParentIndex(n: lastIndex) 72 | } 73 | } 74 | } 75 | func findkthSmallest(arr: [Int], k : Int) -> Int { 76 | var smallest = 0 77 | var stack = [Int]() 78 | var minHeap = MinHeap() 79 | for (index,item) in arr.enumerated() { 80 | minHeap.add(item: item) 81 | if minHeap.items.count > k 82 | { 83 | // minHeap.items.removeLast() 84 | } 85 | 86 | } 87 | print(minHeap) 88 | return minHeap.items.last ?? 0 89 | } 90 | 91 | 92 | findkthSmallest(arr: [7,10,6,3,4,9], k: 3) 93 | // 3 4 6 7 9 10 94 | -------------------------------------------------------------------------------- /Heap.playground/contents.xcplayground: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /Heap.playground/playground.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /Heap.playground/playground.xcworkspace/xcuserdata/richa.e.srivastava.xcuserdatad/UserInterfaceState.xcuserstate: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Richa0305/Data-Structure-with-swift/072c1d23f8770d6c0c7ab289e1e04e0f388fb64d/Heap.playground/playground.xcworkspace/xcuserdata/richa.e.srivastava.xcuserdatad/UserInterfaceState.xcuserstate -------------------------------------------------------------------------------- /Heap.playground/timeline.xctimeline: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /Heap.playground/xcuserdata/richa.e.srivastava.xcuserdatad/xcschemes/xcschememanagement.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | SchemeUserState 6 | 7 | Heap (Playground).xcscheme 8 | 9 | isShown 10 | 11 | orderHint 12 | 0 13 | 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /Identify-DS.md: -------------------------------------------------------------------------------- 1 | # Identify Probem - 2 | 3 | 4 | ## Binery Search 5 | https://www.youtube.com/watch?v=QNGL_t_o_QA&list=PL_z_8CaSLPWeYfhtuKHj-9MpYb6XQJ_f2&index=2 6 | 7 | Use binery search if problem statement contains sorted array 8 | 9 | Always get mid by below formula - 10 | 11 | mid = start + (end - start)/2 12 | 13 | Benefit : if we do (start+end)/2 then this can lead to int overflow in case int is very huge 14 | 15 | 16 | ## Recursion - 17 | https://www.youtube.com/watch?v=kHi1DUhp9kM&list=PL_z_8CaSLPWeT1ffjiImo0sYTcnLzo-wY 18 | 19 | Identify Recusion problem - if problem contains [Choice] + [Decisions] 20 | 21 | Screenshot 2022-03-09 at 08 00 04 22 | 23 | How to solve recursion problem - Make smaller input in every recursive call 24 | 1. Base Conditions - like smallest input values 25 | 2. Hypothesis - design the function which gives output 26 | 3. Induction - Logic for output 27 | 28 | 29 | 30 | ## Sliding Window - 31 | https://www.youtube.com/watch?v=EHCGAZBbB88&list=PL_z_8CaSLPWeM8BDJmIYDaoQ5zuwyxnfj 32 | 33 | Problem can contain - 34 | 35 | Array/String + SubArray/SubString + Maximum/Largest/Minimum + k window size + get largest window or smaller window 36 | Screenshot 2022-03-08 at 23 12 43 37 | 38 | Ex - Given array get sum of all the subarray with size 3 39 | 40 | Ex - Given array get largest subarray whose sum is 10 41 | 42 | 43 | -------------------------------------------------------------------------------- /Insertion Sort.playground/Contents.swift: -------------------------------------------------------------------------------- 1 | //: Playground - noun: a place where people can play 2 | //Insertion sort - By Richa Srivastava 3 | /* 4 | sort by shifting the elements one by one and this is better than bubble 5 | and selection sort. In this sort we take a key and compares it with the 6 | elements ahead of it and puts the key in right place. 7 | */ 8 | 9 | import Foundation 10 | 11 | var arr = [5,3,2,6,1,7,4] 12 | 13 | var j = 0 14 | var key = 0 15 | 16 | for i in 1.. key{ 22 | var temp = 0 23 | temp = arr[j] 24 | arr[j] = arr[j-1] 25 | arr[j-1] = temp 26 | } 27 | } 28 | } 29 | print(arr) 30 | 31 | /* 32 | Worst Case Time Complexity : O(n2) 33 | Best Case Time Complexity : O(n) 34 | Average Time Complexity : O(n2) 35 | Space Complexity : O(1) 36 | */ 37 | -------------------------------------------------------------------------------- /Insertion Sort.playground/contents.xcplayground: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /Insertion Sort.playground/playground.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /Insertion Sort.playground/playground.xcworkspace/xcuserdata/a584553.xcuserdatad/UserInterfaceState.xcuserstate: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Richa0305/Data-Structure-with-swift/072c1d23f8770d6c0c7ab289e1e04e0f388fb64d/Insertion Sort.playground/playground.xcworkspace/xcuserdata/a584553.xcuserdatad/UserInterfaceState.xcuserstate -------------------------------------------------------------------------------- /LinkedList.playground/Contents.swift: -------------------------------------------------------------------------------- 1 | import UIKit 2 | 3 | /* 4 | A linked list is a dynamic data structure where number of data is not fixed(like array) and can grow or shrink based on demand. 5 | Each node in link list consist of two things – 6 | - Data 7 | - Link to next node 8 | */ 9 | 10 | class Node{ 11 | let value : Int 12 | var next : Node? 13 | 14 | init(val : Int, next: Node?) { 15 | self.value = val 16 | self.next = next 17 | } 18 | } 19 | // 7 20 | // 1->2->3->4->5->nil 21 | let fifthNode = Node(val: 5, next: nil) 22 | let fourthNode = Node(val: 4, next: fifthNode) 23 | let thirdNode = Node(val: 3, next: fourthNode) 24 | let secondNode = Node(val: 2, next: thirdNode) 25 | let firstNode = Node(val: 1, next: secondNode) 26 | 27 | 28 | /* Print a linked list */ 29 | func printLinkedList(headNode: Node?){ 30 | var currentNode = headNode 31 | print("Printing Linked List") 32 | while currentNode != nil { 33 | print(currentNode?.value ?? -1) 34 | currentNode = currentNode?.next 35 | } 36 | } 37 | 38 | /* insert a new node in linked list */ 39 | func insertNodeLinkedList(prev_node:Node?,new_value:Int){ 40 | if prev_node == nil { 41 | return 42 | } 43 | let new_node = Node(val: new_value, next: prev_node?.next) 44 | prev_node?.next = new_node 45 | 46 | } 47 | 48 | /* Reverse a linked list */ 49 | func reverseLinkedList(head:Node?) -> Node?{ 50 | var currentNode = head 51 | var prev:Node? 52 | var next:Node? 53 | 54 | while currentNode != nil { 55 | next = currentNode?.next 56 | currentNode?.next = prev 57 | prev = currentNode 58 | currentNode = next 59 | } 60 | 61 | return prev 62 | } 63 | /* 64 | Traverse the whole linked list and count the no. of nodes. Now traverse the list again till count/2 and return the node at count/2. 65 | */ 66 | func getMiddleMethod1(head:Node?) -> Node?{ 67 | var currentNode = head 68 | let listLength = getListLength(head: currentNode) 69 | var mid = listLength/2 70 | while (mid > 0) && (currentNode != nil) { 71 | currentNode = currentNode?.next 72 | mid = mid - 1 73 | } 74 | 75 | return currentNode 76 | } 77 | 78 | 79 | /* 80 | Traverse linked list using two pointers. Move one pointer by one and other pointer by two. When the fast pointer reaches end slow pointer will reach middle of the linked list. 81 | */ 82 | func getMiddleMethod2(head:Node?) -> Node?{ 83 | var slowNode = head 84 | var fastNode = head 85 | 86 | while (fastNode != nil) && (fastNode?.next != nil) { 87 | slowNode = slowNode?.next 88 | fastNode = fastNode?.next?.next 89 | } 90 | 91 | 92 | return slowNode 93 | } 94 | 95 | 96 | /* Get length of the linked list */ 97 | func getListLength(head:Node?) -> Int{ 98 | var currentNode = head 99 | var count = 0 100 | while currentNode != nil { 101 | count = count + 1 102 | currentNode = currentNode?.next 103 | } 104 | return count 105 | } 106 | 107 | /* 108 | Traverse the list from the head (or start) node. While traversing, compare each node with its next node. If data of next node is same as current node then delete the next node. Before we delete a node, we need to store next pointer of the node 109 | */ 110 | func removeDuplicateNodesFromLinkedList(head:Node?){ 111 | var current = head 112 | var temp_next:Node? 113 | 114 | while current?.next != nil { 115 | if current?.value == current?.next?.value { 116 | temp_next = current?.next?.next 117 | current?.next = temp_next 118 | }else{ 119 | current = current?.next 120 | } 121 | } 122 | } 123 | 124 | /* 125 | First Aproach - 126 | 1) Calculate the length of Linked List. Let the length be len. 127 | 2) Print the (len – n + 1)th node from the begining of the Linked List. 128 | 129 | Second Aproach - 130 | Maintain two pointers – reference pointer and main pointer. Initialize both reference and main pointers to head. First move reference pointer to n nodes from head. Now move both pointers one by one until reference pointer reaches end. Now main pointer will point to nth node from the end. Return main pointer. 131 | */ 132 | func findNthNodeFromEnd(head:Node?,n:Int) -> Node?{ 133 | var main_ptr = head 134 | var ref_ptr = head 135 | var count = 0 136 | if head != nil { 137 | while count < n { 138 | if ref_ptr != nil { 139 | ref_ptr = ref_ptr?.next 140 | count = count + 1 141 | } 142 | } 143 | // ref_ptr -> will point to nth from begining 144 | while ref_ptr != nil { 145 | main_ptr = main_ptr?.next 146 | ref_ptr = ref_ptr?.next 147 | } 148 | // main_ptr will have nth node from end 149 | } 150 | 151 | return main_ptr 152 | } 153 | 154 | //1 155 | printLinkedList(headNode: firstNode) 156 | 157 | //2 158 | print("===Add New Node====") 159 | insertNodeLinkedList(prev_node: fourthNode, new_value: 4) 160 | 161 | //3 162 | print("===Reverse Linked List====") 163 | let reversedList = reverseLinkedList(head: firstNode) 164 | printLinkedList(headNode: reversedList) 165 | 166 | //4 167 | print("===Get Middle Node====") 168 | let midNode = getMiddleMethod1(head: fifthNode) 169 | print("Middle Node by method 1 - \(midNode?.value ?? 0)") 170 | 171 | let midNode2 = getMiddleMethod2(head: fifthNode) 172 | print("Middle Node by method 2- \(midNode2?.value ?? 0)") 173 | 174 | //5 175 | print("===Remove Duplicates====") 176 | removeDuplicateNodesFromLinkedList(head: fifthNode) 177 | printLinkedList(headNode: fifthNode) 178 | 179 | 180 | //5 181 | print("===Print nth node from end====") 182 | let nthNode = findNthNodeFromEnd(head: fifthNode, n: 3) 183 | print(nthNode?.value ?? 0) 184 | -------------------------------------------------------------------------------- /LinkedList.playground/contents.xcplayground: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /LinkedList.playground/playground.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /LinkedList.playground/playground.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | IDEDidComputeMac32BitWarning 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /LinkedList.playground/playground.xcworkspace/xcuserdata/richa.xcuserdatad/UserInterfaceState.xcuserstate: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Richa0305/Data-Structure-with-swift/072c1d23f8770d6c0c7ab289e1e04e0f388fb64d/LinkedList.playground/playground.xcworkspace/xcuserdata/richa.xcuserdatad/UserInterfaceState.xcuserstate -------------------------------------------------------------------------------- /LinkedList.playground/playground.xcworkspace/xcuserdata/richu.xcuserdatad/UserInterfaceState.xcuserstate: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Richa0305/Data-Structure-with-swift/072c1d23f8770d6c0c7ab289e1e04e0f388fb64d/LinkedList.playground/playground.xcworkspace/xcuserdata/richu.xcuserdatad/UserInterfaceState.xcuserstate -------------------------------------------------------------------------------- /MergeSortSwift.playground/Contents.swift: -------------------------------------------------------------------------------- 1 | //: Merge Sort By Richa Srivastava 2 | /* 3 | Merge sort is a sorting algorithm with a simple strategy: divide and conquer. 4 | 5 | The steps for merge sort are simple: 6 | 7 | 1. Split the unsorted array containing N elements into N arrays containing one element each 8 | 2. Merge the piles together by sequentially pairing piles together in sorted order 9 | */ 10 | 11 | // First Step : Split Array of N element in N Arrays 12 | func mergeSort(arr : [Int]) -> [Int] { 13 | 14 | guard arr.count > 1 else { 15 | return arr 16 | } 17 | 18 | let leftArray = arr[0.. [Int]{ 27 | 28 | var mergedArr = [Int]() 29 | var left = left 30 | var right = right 31 | 32 | while left.count > 0 && right.count > 0 { 33 | if (left.first! < right.first!) { 34 | mergedArr.append(left.removeFirst()) 35 | } else { 36 | mergedArr.append(right.removeFirst()) 37 | } 38 | } 39 | return mergedArr + left + right 40 | 41 | } 42 | 43 | var arr = [8,9,7,6,5,8,7,0] 44 | print(mergeSort(arr: arr)) 45 | /* 46 | Time Complexity of Merge Sort 47 | 48 | Best - O(n log(n)) 49 | Worst - O(n log(n)) 50 | Avg - O(n log(n)) 51 | */ 52 | -------------------------------------------------------------------------------- /MergeSortSwift.playground/contents.xcplayground: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /MergeSortSwift.playground/playground.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /MergeSortSwift.playground/playground.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | IDEDidComputeMac32BitWarning 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /MergeSortSwift.playground/playground.xcworkspace/xcuserdata/a584553.xcuserdatad/UserInterfaceState.xcuserstate: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Richa0305/Data-Structure-with-swift/072c1d23f8770d6c0c7ab289e1e04e0f388fb64d/MergeSortSwift.playground/playground.xcworkspace/xcuserdata/a584553.xcuserdatad/UserInterfaceState.xcuserstate -------------------------------------------------------------------------------- /MergeSortSwift.playground/playground.xcworkspace/xcuserdata/richa.xcuserdatad/UserInterfaceState.xcuserstate: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Richa0305/Data-Structure-with-swift/072c1d23f8770d6c0c7ab289e1e04e0f388fb64d/MergeSortSwift.playground/playground.xcworkspace/xcuserdata/richa.xcuserdatad/UserInterfaceState.xcuserstate -------------------------------------------------------------------------------- /Queue.playground/Contents.swift: -------------------------------------------------------------------------------- 1 | /** 2 | 3 | Queue Data Structure 4 | 5 | A Queue is a structure in which whatever goes first comes out first. In short FIFO - First In First Out. 6 | 7 | In Queue insertion or addition in queue must happen from one end that is called rear or tail of the queue, and any removal or deletion must happen from front or head of the queue. 8 | 9 | Operations of Queue - 10 | 11 | enQueue(x) or push(x) (Insertion) 12 | deQueue() Or pop (Deletion) 13 | front() on peek() 14 | isEmpty() 15 | 16 | Push and Pop are more famous in context of stack whereas enQueue and deQueue is more famous in context of Queue. 17 | 18 | All these operation must take O(1) time. 19 | 20 | Implementation of Queue - 21 | 22 | Array Based Implementation 23 | LinkedList Based Implementation 24 | 25 | */ 26 | 27 | // Array Implemantation 28 | 29 | class Queue { 30 | var arr = [T]() 31 | func enQueue(val: T) { 32 | arr.append(val) 33 | } 34 | func deQueue() -> T? { 35 | if arr.isEmpty { 36 | return nil 37 | } else { 38 | return arr.remove(at: 0) 39 | } 40 | } 41 | } 42 | 43 | var queue = Queue() 44 | queue.enQueue(val: "Hi") 45 | queue.enQueue(val: "thr") 46 | queue.deQueue() 47 | 48 | 49 | // Linked List Implementation 50 | 51 | 52 | class LLQueue { 53 | var data: T 54 | var next: LLQueue? 55 | init(val: T) { 56 | data = val 57 | } 58 | } 59 | 60 | 61 | class LLQueueImp { 62 | var head: LLQueue? 63 | var front: LLQueue? { return head } 64 | var rear: LLQueue? { 65 | var node:LLQueue? = self.head 66 | while (node?.next != nil) { 67 | node = node?.next 68 | } 69 | return node 70 | } 71 | 72 | func enQueue(val: T) { 73 | let newNode = LLQueue(val: val) 74 | if let lastNode = rear { 75 | lastNode.next = newNode 76 | } else { 77 | head = newNode 78 | } 79 | } 80 | 81 | func deQueue() -> T? { 82 | if head == nil { 83 | return nil 84 | } 85 | let temp = head 86 | if head?.next != nil { 87 | head = head?.next 88 | } else { 89 | head = nil 90 | } 91 | return temp?.data 92 | } 93 | 94 | func peek() -> T? { 95 | return head?.data 96 | } 97 | 98 | func isEmpty() -> Bool { 99 | return (head == nil) ? true : false 100 | } 101 | } 102 | 103 | 104 | var llQueue = LLQueueImp() 105 | llQueue.enQueue(val: 1) 106 | llQueue.enQueue(val: 2) 107 | llQueue.deQueue() 108 | llQueue.peek() 109 | 110 | -------------------------------------------------------------------------------- /Queue.playground/contents.xcplayground: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /Queue.playground/playground.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | -------------------------------------------------------------------------------- /Queue.playground/playground.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | IDEDidComputeMac32BitWarning 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /Queue.playground/playground.xcworkspace/xcuserdata/richa.xcuserdatad/UserInterfaceState.xcuserstate: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Richa0305/Data-Structure-with-swift/072c1d23f8770d6c0c7ab289e1e04e0f388fb64d/Queue.playground/playground.xcworkspace/xcuserdata/richa.xcuserdatad/UserInterfaceState.xcuserstate -------------------------------------------------------------------------------- /QuickSort.playground/Contents.swift: -------------------------------------------------------------------------------- 1 | //: Merge Sort By Richa Srivastava 2 | /* 3 | Merge sort is a sorting algorithm with a simple strategy: divide and conquer. 4 | 5 | The steps for merge sort are simple: 6 | 7 | 1. Split the unsorted array containing N elements into N arrays containing one element each 8 | 2. Merge the piles together by sequentially pairing piles together in sorted order 9 | */ 10 | 11 | import UIKit 12 | 13 | let unsortedArray = [7, 2, 6, 3, 9, 4] 14 | 15 | 16 | func quickSort(arr:[Int]) -> [Int]{ 17 | 18 | var less = [Int]() 19 | var equal = [Int]() 20 | var greater = [Int]() 21 | 22 | if arr.count > 1{ 23 | let pivot = arr[0] 24 | 25 | for x in arr{ 26 | if x < pivot{ 27 | less.append(x) 28 | } 29 | if x == pivot{ 30 | equal.append(x) 31 | } 32 | if x > pivot{ 33 | greater.append(x) 34 | } 35 | } 36 | return (quickSort(arr:less)+equal+quickSort(arr:greater)) 37 | }else{ 38 | return arr 39 | } 40 | 41 | } 42 | let sortedArr = quickSort(arr: unsortedArray) 43 | 44 | /* 45 | Time Complexity of Quick Sort 46 | 47 | Best - O(n log(n)) 48 | Worst - O(n2) 49 | Avg - O(n log(n)) 50 | */ 51 | -------------------------------------------------------------------------------- /QuickSort.playground/contents.xcplayground: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /QuickSort.playground/playground.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /QuickSort.playground/playground.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | IDEDidComputeMac32BitWarning 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /QuickSort.playground/playground.xcworkspace/xcuserdata/richa.xcuserdatad/UserInterfaceState.xcuserstate: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Richa0305/Data-Structure-with-swift/072c1d23f8770d6c0c7ab289e1e04e0f388fb64d/QuickSort.playground/playground.xcworkspace/xcuserdata/richa.xcuserdatad/UserInterfaceState.xcuserstate -------------------------------------------------------------------------------- /QuickSort.playground/playground.xcworkspace/xcuserdata/richu.xcuserdatad/UserInterfaceState.xcuserstate: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Richa0305/Data-Structure-with-swift/072c1d23f8770d6c0c7ab289e1e04e0f388fb64d/QuickSort.playground/playground.xcworkspace/xcuserdata/richu.xcuserdatad/UserInterfaceState.xcuserstate -------------------------------------------------------------------------------- /Recursion - Main.playground/Contents.swift: -------------------------------------------------------------------------------- 1 | 2 | // 3 | // Recursion.swift 4 | // 5 | // 6 | // Created by richa.e.srivastava on 09/03/2022. 7 | // 8 | 9 | import Foundation 10 | 11 | // Meething Room ii - Given an array of meeting time intervals consisting of start and end times [[s1,e1],[s2,e2],...] (si < ei), find the minimum number of conference rooms required.) 12 | /** 13 | Ex 1- 14 | Input: intervals = [(0,30),(5,10),(15,20)] 15 | Output: 2 16 | Explanation: 17 | We need two meeting rooms 18 | room1: (0,30) 19 | room2: (5,10),(15,20) 20 | 21 | 22 | 0 ------------------------------------- 30 23 | 5 ---10 15 --- 20 24 | 25 | So since there are two overlaps we will need two meeting rooms only 26 | 27 | For solution - First sort array by start, Take two arrays start 28 | start - [0, 5 , 15] 29 | end - [10, 20, 30] 30 | 31 | if start[i] < end[j] then increment i and count 32 | if start[i] >= end[j] then increment j and decrement count 33 | 34 | Ex2 - 35 | Input: intervals = [(2,7)] 36 | Output: 1 37 | Explanation: 38 | Only need one meeting room 39 | */ 40 | func meetingRoom2(arr: [(Int,Int)]) -> Int { 41 | 42 | if arr.count <= 1 { 43 | return arr.count 44 | } 45 | var count = 0 46 | var result = 0 47 | var i = 0 48 | var j = 0 49 | let startArr = arr.map { $0.0 }.sorted() 50 | let endArr = arr.map { $0.1 }.sorted() 51 | while i < arr.count { 52 | // print(startArr[i], endArr[j], count, i, j) 53 | if (startArr[i] < endArr[j]){ 54 | count += 1 55 | i += 1 56 | } else { 57 | count -= 1 58 | j += 1 59 | } 60 | result = max(result, count) 61 | } 62 | 63 | return result 64 | } 65 | meetingRoom2(arr: [(0,30),(5,10),(15,20)]) 66 | 67 | 68 | /** 69 | Generate Parentheses 70 | Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. 71 | 72 | Example 1: 73 | 74 | Input: n = 3 75 | Output: ["((()))","(()())","(())()","()(())","()()()"] 76 | Example 2: 77 | 78 | Input: n = 1 79 | Output: ["()"] 80 | 81 | 82 | 83 | n = 1 84 | 85 | open = 1. close = 1 86 | 87 | "" "1 1" 88 | "(" "0 1" 89 | "()" "0 0" 90 | 91 | n = 2 92 | 93 | open = 2. close = 2 94 | 95 | "" "2 2" 96 | "(" "1 2" 97 | "()" "1 1" "((" "0 2" 98 | "()(" "0 1" "(()" "0 1" 99 | "()()" "0 0" "(())" "0 0" 100 | 101 | 102 | 103 | 104 | 105 | 106 | */ 107 | func generateParenthesis(_ n: Int) -> [String] { 108 | let result = solution(open: n, close: n, output: "") 109 | return result 110 | } 111 | 112 | func solution(open: Int, close: Int, output: String) -> [String] { 113 | var result = [String]() 114 | 115 | if open == 0 && close == 0 { 116 | result.append(output) 117 | return result 118 | } 119 | 120 | if open != 0 { 121 | let op = output + "(" 122 | print("open called", op, open, close) 123 | result.append(contentsOf: solution(open: open - 1, close: close, output: op )) 124 | } 125 | if close > open { 126 | let op = output + ")" 127 | print("closed called", op, open, close) 128 | result.append(contentsOf: solution(open: open, close: close-1, output: op)) 129 | } 130 | return result 131 | } 132 | generateParenthesis(2) 133 | 134 | /** 135 | Given two words, beginWord and endWord, and a dictionary wordList, return the number of words in the shortest transformation sequence from beginWord to endWord, or 0 if no such sequence exists. 136 | Example 1: 137 | 138 | Input: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log","cog"] 139 | Output: 5 140 | Explanation: One shortest transformation sequence is "hit" -> "hot" -> "dot" -> "dog" -> cog", which is 5 words long. 141 | 142 | 1st Approach - 143 | 144 | hit cog ["hot","dot","dog","lot","log","cog"] 145 | 146 | abcdefghijklmnopqrstuvwxyz 147 | 148 | queue = [(hit, 1), (hot, 2), (dot, 3), (dog, 4), (cog, 5)] 149 | 150 | 2nd Approach - 151 | ["*ot": "hot", "dot", "lot"] 152 | ["h*t": "hot"] 153 | ["ho*" : "hot"] 154 | ["d*t" : "dot"] 155 | ["do*" : "dot", "dog"] 156 | 157 | visitedSet = ["hit","hot", "dot", "dog", "cog"] 158 | 159 | queue = [(hit, 1), (hot, 2), (dot, 3) , (dog, 4), (cog, 5)] 160 | 161 | 162 | */ 163 | 164 | func ladderLength(_ beginWord: String, _ endWord: String, _ wordList: [String]) -> Int { 165 | guard wordList.contains(endWord) else { 166 | return 0 167 | } 168 | var queue = [(String, Int)]() 169 | queue.append((beginWord, 1)) 170 | 171 | var visitedSet = Set() 172 | visitedSet.insert(beginWord) 173 | 174 | 175 | var dictPatters = [String: [String]]() 176 | 177 | for word in wordList { 178 | for (_, index) in word.indices.enumerated() { 179 | let generic = String(word[.. 2 | 3 | 4 | -------------------------------------------------------------------------------- /Recursion - Main.playground/playground.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /Recursion - Main.playground/playground.xcworkspace/xcuserdata/richa.e.srivastava.xcuserdatad/UserInterfaceState.xcuserstate: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Richa0305/Data-Structure-with-swift/072c1d23f8770d6c0c7ab289e1e04e0f388fb64d/Recursion - Main.playground/playground.xcworkspace/xcuserdata/richa.e.srivastava.xcuserdatad/UserInterfaceState.xcuserstate -------------------------------------------------------------------------------- /Recursion - Main.playground/timeline.xctimeline: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 9 | 10 | 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /Recursion - Main.playground/xcuserdata/richa.e.srivastava.xcuserdatad/xcschemes/xcschememanagement.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | SchemeUserState 6 | 7 | Main (Playground).xcscheme 8 | 9 | isShown 10 | 11 | orderHint 12 | 0 13 | 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /Recursion.playground/Contents.swift: -------------------------------------------------------------------------------- 1 | 2 | // 3 | // Recursion.swift 4 | // 5 | // 6 | // Created by richa.e.srivastava on 09/03/2022. 7 | // 8 | 9 | import Foundation 10 | 11 | /** 12 | https://www.youtube.com/watch?v=kHi1DUhp9kM&list=PL_z_8CaSLPWeT1ffjiImo0sYTcnLzo-wY 13 | 14 | Identify Recusion problem - if problem contains [Choice] + [Decisions] 15 | 16 | Screenshot 2022-03-09 at 08 00 04 17 | 18 | How to solve recursion problem - Make smaller input in every recursive call 19 | 1. Base Conditions - smallest valid input values 20 | 2. Hypothesis - design the function which gives output 21 | 3. Induction - Logic for output 22 | 23 | 24 | 25 | **/ 26 | import Foundation 27 | 28 | class Node { 29 | var value: Int 30 | var left: Node? 31 | var right: Node? 32 | 33 | init(val: Int) { 34 | self.value = val 35 | } 36 | } 37 | var node1 = Node(val: 1) 38 | var node2 = Node(val: 2) 39 | var node3 = Node(val: 3) 40 | node1.left = node2 41 | node2.left = node3 42 | func bineryTreeHeight(node: Node?) -> Int { 43 | var height = 0 44 | // Base Condition 45 | if node == nil { 46 | return height 47 | } 48 | //Hypothesis 49 | let leftHeight = bineryTreeHeight(node: node?.left) 50 | let rightHeight = bineryTreeHeight(node: node?.right) 51 | //Induction 52 | height = 1 + max(leftHeight, rightHeight) 53 | return height 54 | 55 | } 56 | bineryTreeHeight(node: node1) 57 | 58 | 59 | 60 | // Letter case permutation 61 | /** 62 | "" "a1b2" 63 | 64 | "a""1b2" "A""1b2" 65 | "a1""b2" "A1""b2" 66 | 67 | "a1b""2" "a1B2" "A1b""2" "A1B""2" 68 | "a1b2" "a1B2" "A1b2" "A1B2" 69 | 70 | */ 71 | 72 | 73 | func letterCasePermutation(_ s: String) -> [String] { 74 | var result = [String]() 75 | result = letterCaseSolve(ip: s, op: "") 76 | return result 77 | } 78 | func letterCaseSolve(ip: String, op: String) -> [String] { 79 | var result = [String]() 80 | if (ip.count == 0) { 81 | result.append(op) 82 | return result 83 | } 84 | if let firstChar = ip.first, firstChar.isLetter { 85 | var op1 = op 86 | var op2 = op 87 | op1.append(firstChar.lowercased()) 88 | op2.append(firstChar.uppercased()) 89 | let input = ip.dropFirst() 90 | result.append(contentsOf: letterCaseSolve(ip: String(input), op: op1)) 91 | result.append(contentsOf: letterCaseSolve(ip: String(input), op: op2)) 92 | } 93 | if let firstChar = ip.first, firstChar.isNumber { 94 | var op1 = op 95 | op1.append(firstChar) 96 | let input = ip.dropFirst() 97 | result.append(contentsOf: letterCaseSolve(ip: String(input), op: op1)) 98 | } 99 | 100 | return result 101 | } 102 | letterCasePermutation("3z4") 103 | 104 | 105 | 106 | 107 | // generate balanaced paranthesis 108 | /** 109 | " " "3 3" 110 | "("" 2 3" 111 | "((" "1 3" "()" "2 2" 112 | "(((" "0 3" "(()" "1 2" "()(" "1 2" 113 | "((()" "0 2" "(())" "1 1" "(()(" "0 2" "()((" "0 2" "()()" "1 1" 114 | "((())" "0 1" "(())(" "0 1" "(()()" "0 1" "()(()" "0 1" "()()(" "0 1" 115 | "((()))" "0 0" "(())()" "0 0" "(()())" "0 0" "()(())" "0 0" "()()()" "0 0" 116 | */ 117 | 118 | func generateBalancedParanthesis(n: Int) -> [String] { 119 | var result = [String]() 120 | result = generateParanthesis(open: n, close: n, op: "") 121 | return result 122 | } 123 | func generateParanthesis(open:Int, close:Int, op: String) -> [String]{ 124 | var result = [String]() 125 | if open == 0 && close == 0 { 126 | result.append(op) 127 | return result 128 | } 129 | if open != 0 { 130 | var op1 = op 131 | op1.append("(") 132 | result.append(contentsOf: generateParanthesis(open: open-1, close: close, op: op1)) 133 | } 134 | if close > open { 135 | 136 | var op1 = op 137 | op1.append(")") 138 | result.append(contentsOf: generateParanthesis(open: open, close: close-1, op: op1)) 139 | } 140 | 141 | return result 142 | } 143 | generateBalancedParanthesis(n: 3) 144 | 145 | // Sliding Window - Minimum Window Substring 146 | 147 | func minWindow(_ s: String, _ t: String) -> String { 148 | var result = "" 149 | var tDict = [Character: Int]() 150 | for char in t { 151 | tDict[char, default: 0] += 1 152 | } 153 | var start = 0 154 | var end = 0 155 | let sArray = Array(s) 156 | var count = tDict.count 157 | while end < sArray.count { 158 | if let _ = tDict[sArray[end]] { 159 | tDict[sArray[end]]! -= 1 160 | if tDict[sArray[end]]! == 0 { 161 | count -= 1 162 | // print(count, tDict) 163 | while count == 0 { 164 | if let startCharCount = tDict[sArray[start]] { 165 | if startCharCount < 0 { 166 | tDict[sArray[start]]! += 1 167 | } else if startCharCount == 0 { 168 | tDict[sArray[start]]! += 1 169 | //result = String(sArray[start.. sArray[start.. 2 | 3 | 4 | -------------------------------------------------------------------------------- /Recursion.playground/playground.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /Recursion.playground/playground.xcworkspace/xcuserdata/richa.e.srivastava.xcuserdatad/UserInterfaceState.xcuserstate: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Richa0305/Data-Structure-with-swift/072c1d23f8770d6c0c7ab289e1e04e0f388fb64d/Recursion.playground/playground.xcworkspace/xcuserdata/richa.e.srivastava.xcuserdatad/UserInterfaceState.xcuserstate -------------------------------------------------------------------------------- /Recursion.playground/timeline.xctimeline: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 9 | 10 | 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /Recursion.playground/xcuserdata/richa.e.srivastava.xcuserdatad/xcschemes/xcschememanagement.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | SchemeUserState 6 | 7 | Recursion (Playground).xcscheme 8 | 9 | isShown 10 | 11 | orderHint 12 | 0 13 | 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /Recursion.swift: -------------------------------------------------------------------------------- 1 | // 2 | // Recursion.swift 3 | // 4 | // 5 | // Created by richa.e.srivastava on 09/03/2022. 6 | // 7 | 8 | import Foundation 9 | 10 | /** 11 | https://www.youtube.com/watch?v=kHi1DUhp9kM&list=PL_z_8CaSLPWeT1ffjiImo0sYTcnLzo-wY 12 | 13 | Identify Recusion problem - if problem contains [Choice] + [Decisions] 14 | 15 | Screenshot 2022-03-09 at 08 00 04 16 | 17 | How to solve recursion problem - Make smaller input in every recursive call 18 | 1. Base Conditions - smallest valid input values 19 | 2. Hypothesis - design the function which gives output 20 | 3. Induction - Logic for output 21 | 22 | 23 | 24 | **/ 25 | import Foundation 26 | 27 | class Node { 28 | var value: Int 29 | var left: Node? 30 | var right: Node? 31 | 32 | init(val: Int) { 33 | self.value = val 34 | } 35 | } 36 | var node1 = Node(val: 1) 37 | var node2 = Node(val: 2) 38 | var node3 = Node(val: 3) 39 | node1.left = node2 40 | node2.left = node3 41 | func bineryTreeHeight(node: Node?) -> Int { 42 | var height = 0 43 | 44 | if node == nil { 45 | return height 46 | } 47 | var leftHeight = bineryTreeHeight(node: node?.left) 48 | var rightHeight = bineryTreeHeight(node: node?.right) 49 | height = 1 + max(leftHeight, rightHeight) 50 | return height 51 | 52 | } 53 | bineryTreeHeight(node: node1) 54 | -------------------------------------------------------------------------------- /Selection sort.playground/Contents.swift: -------------------------------------------------------------------------------- 1 | //: Playground - noun: a place where people can play 2 | // Selection Sort - By Richa Srivastava 3 | /* 4 | In this sort we first find the smallest element in the array and exchanges it with the element in the first position, then finds the second smallest element and replace it with the element in second position and continues in same way for the entire array. 5 | */ 6 | 7 | import Foundation 8 | var arr = [4,3,5,6,1,2] 9 | 10 | var min = 0 11 | var j = 0 12 | for i in 0.. arr[j]){ 17 | min = j 18 | } 19 | } 20 | var temp = arr[i] 21 | arr[i] = arr[min] 22 | arr[min] = temp 23 | } 24 | print(arr) 25 | 26 | /* 27 | Time Complexity – worst – O(n^2), best – O(n^2) and Average – O(n^2) 28 | */ -------------------------------------------------------------------------------- /Selection sort.playground/contents.xcplayground: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /Selection sort.playground/playground.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /Selection sort.playground/playground.xcworkspace/xcuserdata/a584553.xcuserdatad/UserInterfaceState.xcuserstate: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Richa0305/Data-Structure-with-swift/072c1d23f8770d6c0c7ab289e1e04e0f388fb64d/Selection sort.playground/playground.xcworkspace/xcuserdata/a584553.xcuserdatad/UserInterfaceState.xcuserstate -------------------------------------------------------------------------------- /SlidingWindow.playground/Contents.swift: -------------------------------------------------------------------------------- 1 | 2 | // 3 | // Recursion.swift 4 | // 5 | // 6 | // Created by richa.e.srivastava on 09/03/2022. 7 | // 8 | 9 | import Foundation 10 | 11 | /** 12 | https://www.youtube.com/watch?v=EHCGAZBbB88&list=PL_z_8CaSLPWeM8BDJmIYDaoQ5zuwyxnfj 13 | 14 | Problem can contain - 15 | 16 | Array/String + SubArray/SubString + Maximum/Largest/Minimum + k window size + get largest window or smaller window 17 | 18 | Ex - Given array get sum of all the subarray with size 3 19 | 20 | Ex - Given array get largest subarray whose sum is 10 21 | 22 | 23 | **/ 24 | import Foundation 25 | 26 | // 1.Given array get maximum sum of subarray of size k 27 | 28 | func maximumSumSubArray(arr: [Int],k:Int) -> Int { 29 | var maxSum = 0 30 | var start = 0 31 | var end = 0 32 | var sum = 0 33 | 34 | while end < arr.count { 35 | sum = sum + arr[end] 36 | if ((end - start) + 1) >= k { 37 | if maxSum < sum { 38 | maxSum = sum 39 | } 40 | sum = sum - arr[start] 41 | start += 1 42 | end += 1 43 | } 44 | end += 1 45 | } 46 | 47 | return maxSum 48 | } 49 | maximumSumSubArray(arr: [1,2,3,1,2,3,4], k: 3) 50 | 51 | 52 | // find first negative number in every window subarray 53 | 54 | 55 | func firstNegativeSubArray(arr: [Int],k:Int) -> [Int] { 56 | var resultList = [Int]() 57 | var negativeList = [Int]() 58 | var start = 0 59 | var end = 0 60 | 61 | while end < arr.count { 62 | if arr[end] < 0 { 63 | negativeList.append(arr[end]) 64 | } 65 | if ((end-start)+1) >= k { 66 | if negativeList.isEmpty { 67 | resultList.append(0) 68 | }else { 69 | resultList.append(negativeList[0]) 70 | if arr[start] == negativeList[0] { 71 | negativeList.removeFirst() 72 | } 73 | } 74 | start += 1 75 | } 76 | end += 1 77 | 78 | } 79 | 80 | return resultList 81 | } 82 | 83 | firstNegativeSubArray(arr: [12, -1, -7, 8, 15, 9], k: 3) 84 | 85 | // count occurances of anagram 86 | 87 | 88 | func countAnagramOccurance(str: String, ptr: String) -> Int { 89 | var count = 0 90 | let k = ptr.count 91 | 92 | var ptrDict = [Character:Int]() 93 | for char in ptr { 94 | ptrDict[char, default: 0] += 1 95 | } 96 | ptrDict 97 | var windowDict = [Character:Int]() 98 | 99 | var start = 0 100 | var end = 0 101 | for char in str { 102 | windowDict[char, default: 0] += 1 103 | if ((end-start)+1) >= k { 104 | if windowDict == ptrDict { 105 | count += 1 106 | } 107 | let startChar = Array(str)[start] 108 | if let val = windowDict[startChar], val > 1 { 109 | windowDict[startChar] = val - 1 110 | } else { 111 | windowDict[startChar] = nil 112 | } 113 | start += 1 114 | } 115 | 116 | end += 1 117 | } 118 | 119 | 120 | return count 121 | } 122 | countAnagramOccurance(str: "forxxforxxorfddfro", ptr: "for") 123 | 124 | 125 | // Maximum of all subarrays of size k 126 | 127 | 128 | func maxOfSubArray(arr: [Int],k:Int) -> [Int] { 129 | var result = [Int]() 130 | var queue = [Int]() 131 | 132 | var start = 0 133 | var end = 0 134 | 135 | while end < arr.count { 136 | if queue.isEmpty { 137 | queue.append(arr[end]) 138 | } else { 139 | 140 | for val in queue { 141 | if val < arr[end] { 142 | queue.removeLast() 143 | } 144 | } 145 | queue.append(arr[end]) 146 | } 147 | print("queue ",queue) 148 | if ((end-start)+1) >= k { 149 | result.append(queue.first!) 150 | print("result ",result) 151 | if queue.first == arr[start] { 152 | queue.removeFirst() 153 | } 154 | start += 1 155 | } 156 | end += 1 157 | } 158 | 159 | 160 | 161 | return result 162 | } 163 | //maxOfSubArray(arr: [1,-1], k: 1) 164 | 165 | 166 | // longest substring with k unique charecters 167 | 168 | func longestSubstringWithUniques(str :String,k:Int) -> String { 169 | var result = "" 170 | var charsCountDict = [Character: Int]() 171 | var start = 0 172 | var end = 0 173 | let arrStr = Array(str) 174 | 175 | while end < arrStr.count { 176 | charsCountDict[arrStr[end], default: 0] += 1 177 | if charsCountDict.count == k { 178 | let subString = String(arrStr[start..<(end+1)]) 179 | if result.count < subString.count { 180 | result = subString 181 | } 182 | } else if charsCountDict.count > k { 183 | while charsCountDict.count > k { 184 | if let startCount = charsCountDict[arrStr[start]] { 185 | if startCount >= 1 { 186 | charsCountDict[arrStr[start]]! -= 1 187 | if charsCountDict[arrStr[start]]! == 0 { 188 | charsCountDict[arrStr[start]] = nil 189 | } 190 | } 191 | } 192 | start += 1 193 | } 194 | } 195 | end += 1 196 | } 197 | return result 198 | } 199 | longestSubstringWithUniques(str: "aabacbebebe", k: 3) 200 | 201 | // longest substring with no repeating chars 202 | 203 | func longestSubstringWithNoRepeating(str :String,k:Int) -> Int { 204 | var result = 0 205 | var charsCountDict = [Character: Int]() 206 | var start = 0 207 | var end = 0 208 | let arrStr = Array(str) 209 | 210 | while end < arrStr.count { 211 | charsCountDict[arrStr[end], default: 0] += 1 212 | if charsCountDict.count == ((end-start)+1) { 213 | let subString = String(arrStr[start..<(end+1)]) 214 | if result < subString.count { 215 | result = subString.count 216 | } 217 | } else if charsCountDict.count < ((end-start)+1) { 218 | while charsCountDict.count < ((end-start)+1) { 219 | if let startCount = charsCountDict[arrStr[start]] { 220 | if startCount >= 1 { 221 | charsCountDict[arrStr[start]]! -= 1 222 | if charsCountDict[arrStr[start]]! == 0 { 223 | charsCountDict[arrStr[start]] = nil 224 | } 225 | } 226 | } 227 | start += 1 228 | } 229 | } 230 | end += 1 231 | } 232 | return result 233 | } 234 | longestSubstringWithNoRepeating(str: "pwwkew", k: 3) 235 | -------------------------------------------------------------------------------- /SlidingWindow.playground/contents.xcplayground: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /SlidingWindow.playground/playground.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /SlidingWindow.playground/playground.xcworkspace/xcuserdata/richa.e.srivastava.xcuserdatad/UserInterfaceState.xcuserstate: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Richa0305/Data-Structure-with-swift/072c1d23f8770d6c0c7ab289e1e04e0f388fb64d/SlidingWindow.playground/playground.xcworkspace/xcuserdata/richa.e.srivastava.xcuserdatad/UserInterfaceState.xcuserstate -------------------------------------------------------------------------------- /SlidingWindow.playground/timeline.xctimeline: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /SlidingWindow.playground/xcuserdata/richa.e.srivastava.xcuserdatad/xcschemes/xcschememanagement.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | SchemeUserState 6 | 7 | SlidingWindow (Playground).xcscheme 8 | 9 | isShown 10 | 11 | orderHint 12 | 0 13 | 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /Swift String.playground/Contents.swift: -------------------------------------------------------------------------------- 1 | import Foundation 2 | /** 3 | 4 | ***************************SWIFT STRING ************************** 5 | 6 | */ 7 | 8 | 9 | // Initialize String 10 | var emptyString = "" // Empty (Mutable) String 11 | let stillEmpty = String() // Another empty String 12 | let helloWorld = "Hello World!" // String literal 13 | 14 | // properties 15 | helloWorld.lowercased() 16 | helloWorld.uppercased() 17 | helloWorld.isEmpty 18 | 19 | 20 | // Multi line string 21 | let verse = """ 22 | Hello World! 23 | This is multiline string! 24 | """ 25 | 26 | // Prefix & Suffix 27 | let password = "12345" 28 | password.hasPrefix("123") 29 | password.hasSuffix("345") 30 | 31 | 32 | // Drop & Remove 33 | var name = "Tom Dick Harry" 34 | name.dropFirst() 35 | name.dropLast() 36 | name.dropFirst(3) 37 | name.dropLast(5) 38 | name 39 | name.removeFirst() 40 | name.removeLast() 41 | name 42 | 43 | // String Concatenation 44 | var first = "Hello" 45 | var second = "World" 46 | print(first + " " + second) 47 | 48 | // String Interpolation 49 | print("6 times 7 is \(6*7)") 50 | 51 | 52 | // Working with Characters 53 | for char in "Hello" { 54 | print(char) 55 | } 56 | let helloChars: [Character] = ["h", "e", "l", "l", "o"] 57 | String(helloChars) 58 | 59 | // Useful Characters Properties 60 | let a = "A" as Character 61 | let pi = "π" as Character 62 | a.isASCII 63 | pi.isASCII 64 | a.asciiValue 65 | pi.asciiValue 66 | 67 | let five = "5" as Character 68 | let half = "½" as Character 69 | five.isNumber 70 | half.isNumber 71 | 72 | five.isWholeNumber 73 | five.wholeNumberValue 74 | half.isWholeNumber 75 | half.wholeNumberValue 76 | 77 | a.isLetter 78 | let smiley = "😀" as Character 79 | smiley.isSymbol 80 | smiley.isLetter 81 | 82 | let plus = "+" as Character 83 | plus.isSymbol 84 | plus.isLetter 85 | plus.isMathSymbol 86 | smiley.isMathSymbol 87 | 88 | let dollar = "$" as Character 89 | dollar.isCurrencySymbol 90 | 91 | let qmark = "?" as Character 92 | qmark.isPunctuation 93 | 94 | let b = "b" as Character 95 | let z = "Z" as Character 96 | b.isLowercase 97 | z.isUppercase 98 | b.uppercased() 99 | z.lowercased() 100 | 101 | 102 | // Sring Indices 103 | 104 | let hello = "hello" 105 | let startIndex = hello.startIndex // 0 106 | let endIndex = hello.endIndex //5 107 | hello[startIndex] 108 | hello[hello.index(after: startIndex)] 109 | hello[hello.index(before: endIndex)] 110 | 111 | hello[hello.index(startIndex, offsetBy: 1)] // "e" 112 | hello[hello.index(endIndex, offsetBy: -4)] // "e" 113 | 114 | 115 | for index in hello.indices { 116 | print(hello[index]) 117 | } 118 | 119 | // Substring 120 | 121 | let greeting = "Hello, world!" 122 | let index = greeting.firstIndex(of: ",") ?? greeting.endIndex 123 | let beginning = greeting[.. 2 | 3 | 4 | -------------------------------------------------------------------------------- /Swift String.playground/playground.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /Swift String.playground/playground.xcworkspace/xcuserdata/richa.xcuserdatad/UserInterfaceState.xcuserstate: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Richa0305/Data-Structure-with-swift/072c1d23f8770d6c0c7ab289e1e04e0f388fb64d/Swift String.playground/playground.xcworkspace/xcuserdata/richa.xcuserdatad/UserInterfaceState.xcuserstate -------------------------------------------------------------------------------- /TopAlgos.playground/playground.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /TopAlgos.playground/playground.xcworkspace/xcuserdata/richa.srivastava.xcuserdatad/UserInterfaceState.xcuserstate: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Richa0305/Data-Structure-with-swift/072c1d23f8770d6c0c7ab289e1e04e0f388fb64d/TopAlgos.playground/playground.xcworkspace/xcuserdata/richa.srivastava.xcuserdatad/UserInterfaceState.xcuserstate -------------------------------------------------------------------------------- /Tree.playground/Contents.swift: -------------------------------------------------------------------------------- 1 | //: Playground - noun: a place where people can play 2 | // By Richa Srivastava 3 | //Tree With Swift 4 | 5 | // [2,3,4,5,6,7,8] make binary tree for this array 6 | import Foundation 7 | /* 8 | 5 9 | 3 7 10 | 2 4 6 8 11 | */ 12 | let arr = [2,3,4,5,6,7,8] 13 | var arr2 = [Int]() 14 | 15 | class Node{ 16 | var value: Int 17 | var leftNode: Node? 18 | var rightNode: Node? 19 | 20 | init(value:Int) { 21 | self.value = value 22 | } 23 | } 24 | 25 | 26 | func binaryTree(arr:[Int], firstIndex:Int, lastIndex:Int) -> Node?{ 27 | 28 | if lastIndex < firstIndex{ 29 | return nil 30 | } 31 | let mid = (lastIndex + firstIndex)/2 32 | let node = Node(value: arr[mid]) 33 | node.leftNode = binaryTree(arr: arr, firstIndex: firstIndex, lastIndex: mid-1) 34 | node.rightNode = binaryTree(arr: arr, firstIndex: mid + 1, lastIndex: lastIndex) 35 | return node 36 | } 37 | 38 | func searchBinary(node:Node?,searchVal:Int) -> Bool{ 39 | if node?.value == searchVal{ 40 | return true 41 | } 42 | if searchVal < (node?.value)!{ 43 | if node?.leftNode == nil { 44 | return false 45 | }else{ 46 | return searchBinary(node: node?.leftNode, searchVal: searchVal) 47 | } 48 | }else{ 49 | if node?.rightNode == nil { 50 | return false 51 | }else{ 52 | return searchBinary(node: node?.rightNode, searchVal: searchVal) 53 | } 54 | } 55 | } 56 | 57 | // inorder traversal Left -> root -> right 58 | func printInOrder(node:Node?){ 59 | if node?.leftNode != nil{ 60 | printInOrder(node: node?.leftNode) 61 | } 62 | print(node?.value ?? 0) 63 | if node?.rightNode != nil { 64 | printInOrder(node: node?.rightNode) 65 | } 66 | } 67 | 68 | // preOrder traversal root -> Left -> right 69 | func printPreOrder(node:Node?){ 70 | print(node?.value ?? 0) 71 | if node?.leftNode != nil{ 72 | printPreOrder(node: node?.leftNode) 73 | } 74 | if node?.rightNode != nil { 75 | printPreOrder(node: node?.rightNode) 76 | } 77 | } 78 | 79 | // preOrder traversal root -> Left -> right 80 | func printPostOrder(node:Node?){ 81 | if node?.leftNode != nil{ 82 | printPostOrder(node: node?.leftNode) 83 | } 84 | if node?.rightNode != nil { 85 | printPostOrder(node: node?.rightNode) 86 | } 87 | print(node?.value ?? 0) 88 | } 89 | 90 | 91 | func maxDepth(rootNode:Node?) -> Int{ 92 | guard rootNode != nil else { 93 | return 0 94 | } 95 | let leftDepth = maxDepth(rootNode: rootNode?.leftNode) 96 | let rightDepth = maxDepth(rootNode: rootNode?.rightNode) 97 | // print(" rootnode \(rootNode?.value ?? 0) leftNode \(rootNode?.leftNode?.value ?? 0) \(leftDepth)") 98 | // print(" rootnode \(rootNode?.value ?? 0) rightNode \(rootNode?.rightNode?.value ?? 0) \(rightDepth)") 99 | // print("----") 100 | if leftDepth > rightDepth { 101 | return (leftDepth + 1) 102 | }else{ 103 | return (rightDepth + 1) 104 | } 105 | 106 | } 107 | 108 | 109 | func mirrorTree(rootNode:Node?) -> Node?{ 110 | guard rootNode != nil else { 111 | return nil 112 | } 113 | mirrorTree(rootNode: rootNode?.leftNode) 114 | mirrorTree(rootNode: rootNode?.rightNode) 115 | 116 | let temp = rootNode?.leftNode 117 | rootNode?.leftNode = rootNode?.rightNode 118 | rootNode?.rightNode = temp 119 | 120 | return rootNode 121 | } 122 | 123 | 124 | func treeToArray(node:Node?) -> [Int]?{ 125 | 126 | if node == nil { 127 | return nil 128 | } 129 | 130 | treeToArray(node: node?.rightNode) 131 | arr2.append(node?.value ?? 0) 132 | treeToArray(node: node?.leftNode) 133 | 134 | return arr2 135 | } 136 | 137 | let tree = binaryTree(arr: arr, firstIndex: 0, lastIndex: arr.count-1) 138 | print("==Printing root of tree ====") 139 | print(tree?.value ?? 0) 140 | print(tree?.leftNode?.value ?? 0) 141 | print(tree?.rightNode?.value ?? 0) 142 | 143 | 144 | print("==binary search ====") 145 | print(searchBinary(node: tree, searchVal: 88)) 146 | 147 | print("====InOrder Traversal======") 148 | printInOrder(node: tree) 149 | 150 | print("====preorder Traversal======") 151 | printPreOrder(node: tree) 152 | 153 | print("====postorder Traversal======") 154 | printPostOrder(node: tree) 155 | 156 | print("====Max Depth of the tree=====") 157 | print(maxDepth(rootNode: tree)) 158 | 159 | print("====Mirror a tree=====") 160 | let mirrorNode = mirrorTree(rootNode: tree) 161 | print(mirrorNode?.value ?? 0) 162 | print(mirrorNode?.leftNode?.value ?? 0) 163 | print(mirrorNode?.rightNode?.value ?? 0) 164 | 165 | 166 | print("====convert tree to array =====") 167 | let convertedArr = treeToArray(node: tree) 168 | print(convertedArr!) 169 | -------------------------------------------------------------------------------- /Tree.playground/contents.xcplayground: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /Tree.playground/playground.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /Tree.playground/playground.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | IDEDidComputeMac32BitWarning 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /Tree.playground/playground.xcworkspace/xcuserdata/a584553.xcuserdatad/UserInterfaceState.xcuserstate: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Richa0305/Data-Structure-with-swift/072c1d23f8770d6c0c7ab289e1e04e0f388fb64d/Tree.playground/playground.xcworkspace/xcuserdata/a584553.xcuserdatad/UserInterfaceState.xcuserstate -------------------------------------------------------------------------------- /Tree.playground/playground.xcworkspace/xcuserdata/richa.xcuserdatad/UserInterfaceState.xcuserstate: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Richa0305/Data-Structure-with-swift/072c1d23f8770d6c0c7ab289e1e04e0f388fb64d/Tree.playground/playground.xcworkspace/xcuserdata/richa.xcuserdatad/UserInterfaceState.xcuserstate -------------------------------------------------------------------------------- /Tree.playground/playground.xcworkspace/xcuserdata/richu.xcuserdatad/UserInterfaceState.xcuserstate: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Richa0305/Data-Structure-with-swift/072c1d23f8770d6c0c7ab289e1e04e0f388fb64d/Tree.playground/playground.xcworkspace/xcuserdata/richu.xcuserdatad/UserInterfaceState.xcuserstate -------------------------------------------------------------------------------- /TreeMathsOperations.playground/Contents.swift: -------------------------------------------------------------------------------- 1 | //: Playground - noun: a place where people can play 2 | // By Richa Srivastava 3 | //Tree With Swift 4 | 5 | // 6 + 9 * 7 solve mathmetical evaluation with swift using tree data structure 6 | /* 7 | + 8 | * 6 9 | 10 | 9 7 11 | 12 | */ 13 | import Foundation 14 | 15 | class Node{ 16 | var operation:String? 17 | var value: Int? 18 | var leftNode: Node? 19 | var rightNode: Node? 20 | 21 | init(op:String?,val:Int?,left:Node?,right:Node?) { 22 | self.value = val 23 | self.operation = op 24 | self.leftNode = left 25 | self.rightNode = right 26 | } 27 | } 28 | 29 | let ninethNode = Node(op: nil, val: 9, left: nil, right: nil) 30 | let sixthNode = Node(op: nil, val: 6, left: nil, right: nil) 31 | let seventhhNode = Node(op: nil, val: 7, left: nil, right: nil) 32 | let multOpNode = Node(op: "*", val: nil, left: ninethNode, right: seventhhNode) 33 | let plusOpNode = Node(op: "+", val: nil, left: multOpNode, right: sixthNode) 34 | 35 | func evaluateUsingAbstractTree(node:Node?) -> Int{ 36 | if node?.value != nil { 37 | return (node?.value)! 38 | } 39 | 40 | if (node?.operation)! == "+" { 41 | return evaluateUsingAbstractTree(node: node?.leftNode) + evaluateUsingAbstractTree(node: node?.rightNode) 42 | }else if node?.operation == "*" { 43 | return evaluateUsingAbstractTree(node: node?.leftNode) * evaluateUsingAbstractTree(node: node?.rightNode) 44 | }else if node?.operation == "-" { 45 | return evaluateUsingAbstractTree(node: node?.leftNode) - evaluateUsingAbstractTree(node: node?.rightNode) 46 | }else if node?.operation == "/" { 47 | return evaluateUsingAbstractTree(node: node?.leftNode) / evaluateUsingAbstractTree(node: node?.rightNode) 48 | } 49 | return 0 50 | } 51 | 52 | 53 | print(evaluateUsingAbstractTree(node: plusOpNode)) 54 | 55 | 56 | print(6 + 9 * 7) 57 | -------------------------------------------------------------------------------- /TreeMathsOperations.playground/contents.xcplayground: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /TreeMathsOperations.playground/playground.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /TreeMathsOperations.playground/playground.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | IDEDidComputeMac32BitWarning 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /TreeMathsOperations.playground/playground.xcworkspace/xcuserdata/a584553.xcuserdatad/UserInterfaceState.xcuserstate: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Richa0305/Data-Structure-with-swift/072c1d23f8770d6c0c7ab289e1e04e0f388fb64d/TreeMathsOperations.playground/playground.xcworkspace/xcuserdata/a584553.xcuserdatad/UserInterfaceState.xcuserstate -------------------------------------------------------------------------------- /TreeMathsOperations.playground/playground.xcworkspace/xcuserdata/richu.xcuserdatad/UserInterfaceState.xcuserstate: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Richa0305/Data-Structure-with-swift/072c1d23f8770d6c0c7ab289e1e04e0f388fb64d/TreeMathsOperations.playground/playground.xcworkspace/xcuserdata/richu.xcuserdatad/UserInterfaceState.xcuserstate -------------------------------------------------------------------------------- /TwoSumHandNotes.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Richa0305/Data-Structure-with-swift/072c1d23f8770d6c0c7ab289e1e04e0f388fb64d/TwoSumHandNotes.png -------------------------------------------------------------------------------- /stack.playground/Contents.swift: -------------------------------------------------------------------------------- 1 | /** 2 | 3 | Stack Data Structure 4 | 5 | A stack is a structure in which whatever goes first comes out last. In short LIFO - Last In First Out. 6 | 7 | In Stack insertion or addition, must happen from same end that is called top of a stack. 8 | 9 | Operations - 10 | 11 | push(x) (Insertion) 12 | pop (Deletion) 13 | peek() 14 | isEmpty() 15 | 16 | All these operation must take O(1) time. 17 | 18 | Implementation of Stack - 19 | 20 | Array Based Implementation 21 | LinkedList Based Implementation 22 | 23 | 24 | */ 25 | 26 | 27 | // Array Based Implementation 28 | class Stack { 29 | 30 | var stackArray = [Element]() 31 | func push(val: Element) { 32 | stackArray.append(val) 33 | } 34 | func pop() -> Element? { 35 | return stackArray.removeLast() 36 | } 37 | func peek() -> Element? { 38 | return stackArray.last 39 | } 40 | } 41 | 42 | 43 | var stack = Stack() 44 | stack.push(val: "Hi") 45 | stack.push(val: "This") 46 | stack.push(val: "is") 47 | stack.push(val: "Great") 48 | stack.pop() 49 | stack.peek() 50 | 51 | 52 | // Linked List Based Implemention 53 | 54 | class LLStack { 55 | var value: T 56 | var next: LLStack? 57 | init(val: T) { 58 | value = val 59 | } 60 | } 61 | 62 | class LLStackImplementation { 63 | var headNode: LLStack? 64 | 65 | func pushInStack(val: T) { 66 | let newNode = LLStack(val: val) 67 | if headNode == nil { 68 | headNode = newNode 69 | } else { 70 | let oldHeadNode = headNode 71 | headNode = newNode 72 | newNode.next = oldHeadNode 73 | } 74 | } 75 | 76 | func popFromStack() -> T? { 77 | let currentTop = headNode 78 | if headNode?.next != nil { 79 | headNode = headNode?.next 80 | } else { 81 | headNode = nil 82 | } 83 | return currentTop?.value 84 | } 85 | 86 | func peek() -> T? { 87 | return headNode?.value 88 | } 89 | } 90 | 91 | 92 | var llstack = LLStackImplementation() 93 | llstack.pushInStack(val: "Hi") 94 | llstack.pushInStack(val: "My") 95 | llstack.pushInStack(val: "Name") 96 | llstack.pushInStack(val: "is") 97 | llstack.pushInStack(val: "Nobita") 98 | llstack.popFromStack() 99 | llstack.peek() 100 | llstack.popFromStack() 101 | -------------------------------------------------------------------------------- /stack.playground/contents.xcplayground: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /stack.playground/playground.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | -------------------------------------------------------------------------------- /stack.playground/playground.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | IDEDidComputeMac32BitWarning 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /stack.playground/playground.xcworkspace/xcuserdata/richa.xcuserdatad/UserInterfaceState.xcuserstate: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Richa0305/Data-Structure-with-swift/072c1d23f8770d6c0c7ab289e1e04e0f388fb64d/stack.playground/playground.xcworkspace/xcuserdata/richa.xcuserdatad/UserInterfaceState.xcuserstate --------------------------------------------------------------------------------