├── HackerRank.png ├── Algorithms ├── AVeryBigSum.swift ├── SimpleArraySum.swift ├── TaumAndBday.swift ├── CamelCase.swift ├── TheHurdleRace.swift ├── BirthdayCakeCandles.swift ├── CatsAndMouse.swift ├── IntroToTutorialChallenges.swift ├── AngryProfessor.swift ├── MarcsCakewalk.swift ├── UtopianTree.swift ├── SequenceEquation.swift ├── Mini-MaxSum.swift ├── TimeConversion.swift ├── ElectronicsShop.swift ├── Pangrams.swift ├── ViralAdvertising.swift ├── Staircase.swift ├── GradingStudents.swift ├── Kangaroo.swift ├── MigratoryBirds.swift ├── DiagonalDifference.swift ├── ChocolateFeast.swift ├── HackerRankInAString.swift ├── CompareTheTriplets.swift ├── BonApettit.swift ├── CutTheSticks.swift ├── DesignerPDFViwer.swift ├── FindDigits.swift ├── PlusMinus.swift ├── InsertionSort2.swift ├── AppleAndOrange.swift ├── DivisibleSumPairs.swift ├── BreakingTheRecords.swift ├── MinimunDistances.swift ├── MarsExploration.swift ├── BeautifulBinaryString.swift ├── EqualizeTheArray.swift ├── ServiceLane.swift └── BeautifulDaysAtTheMovies.swift ├── README.md ├── Interview-Preparation-Kit ├── Arrays │ ├── LeftRotation.swift │ ├── MinimumSwaps2.swift │ ├── NewYearChaos.swift │ ├── ArrayManipulation.swift │ └── 2DArray.swift ├── DictionariesAndHashmps │ ├── TwoStrings.swift │ └── RansomNote.swift ├── StringManipulation │ └── AlternatingCharacters.swift ├── Sorting │ ├── MarkandToys.swift │ └── BubbleSort.swift └── Warmup-Challenges │ ├── RepeatedString.swift │ ├── SockMerchant.swift │ ├── CountingValleys.swift │ └── JumpingOnTheClouds.swift └── .gitignore /HackerRank.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/azolinmf/HackerRank-swift-solutions/HEAD/HackerRank.png -------------------------------------------------------------------------------- /Algorithms/AVeryBigSum.swift: -------------------------------------------------------------------------------- 1 | func aVeryBigSum(ar: [Int]) -> Int { 2 | 3 | return ar.reduce(0, +) 4 | 5 | } 6 | -------------------------------------------------------------------------------- /Algorithms/SimpleArraySum.swift: -------------------------------------------------------------------------------- 1 | func simpleArraySum(ar: [Int]) -> Int { 2 | 3 | return ar.reduce(0, +) 4 | 5 | } 6 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # HackerRank Swift Solutions 2 | ![](HackerRank.png) 3 | 4 | My solutions in Swift for HackerRank tests. 5 | 6 | -------------------------------------------------------------------------------- /Algorithms/TaumAndBday.swift: -------------------------------------------------------------------------------- 1 | func taumBday(b: Int, w: Int, bc: Int, wc: Int, z: Int) -> Int { 2 | 3 | return b*min(bc,(wc + z)) + w*min(wc, (bc+z)) 4 | } 5 | -------------------------------------------------------------------------------- /Algorithms/CamelCase.swift: -------------------------------------------------------------------------------- 1 | func camelcase(s: String) -> Int { 2 | 3 | return s.filter { $0.isUppercase }.count + 1 4 | 5 | } 6 | 7 | //filters the 's' array looking for uppercase letters 8 | //adds 1 to count the first word 9 | -------------------------------------------------------------------------------- /Algorithms/TheHurdleRace.swift: -------------------------------------------------------------------------------- 1 | func hurdleRace(k: Int, height: [Int]) -> Int { 2 | 3 | guard let max = height.max() else { return 0 } 4 | let doses = Int(max - k) 5 | if doses > 0 { return doses } 6 | return 0 7 | } 8 | -------------------------------------------------------------------------------- /Algorithms/BirthdayCakeCandles.swift: -------------------------------------------------------------------------------- 1 | func birthdayCakeCandles(ar: [Int]) -> Int { 2 | var numbers = ar 3 | numbers.sort(by: >) 4 | 5 | guard let index = numbers.lastIndex(of: numbers[0]) else { return 0 } 6 | 7 | return Int(index + 1) 8 | 9 | } 10 | -------------------------------------------------------------------------------- /Algorithms/CatsAndMouse.swift: -------------------------------------------------------------------------------- 1 | func catAndMouse(x: Int, y: Int, z: Int) -> String { 2 | 3 | if abs(x-z) == abs(y-z) { 4 | return ("Mouse C") 5 | } 6 | if abs(x-z) < abs(y-z) { 7 | return ("Cat A") 8 | } 9 | return ("Cat B") 10 | } 11 | -------------------------------------------------------------------------------- /Algorithms/IntroToTutorialChallenges.swift: -------------------------------------------------------------------------------- 1 | func introTutorial(V: Int, arr: [Int]) -> Int { 2 | guard let index = arr.firstIndex(of: V) else { return 0 } 3 | return index 4 | } 5 | 6 | //using guard statement to safely ensure 7 | //that the number V exists in the array 8 | -------------------------------------------------------------------------------- /Algorithms/AngryProfessor.swift: -------------------------------------------------------------------------------- 1 | func angryProfessor(k: Int, a: [Int]) -> String { 2 | 3 | var onTime = 0 4 | 5 | for student in a { 6 | if student <= 0 { 7 | onTime += 1 8 | } 9 | } 10 | 11 | if onTime < k { return "YES" } 12 | else { return "NO" } 13 | } 14 | -------------------------------------------------------------------------------- /Algorithms/MarcsCakewalk.swift: -------------------------------------------------------------------------------- 1 | func marcsCakewalk(calorie: [Int]) -> Int { 2 | let sorted = calorie.sorted(by: >) 3 | var count = 0 4 | 5 | for (index, element) in sorted.enumerated() { 6 | count += Int(pow(2.0, Double(index))) * element 7 | } 8 | 9 | return count 10 | } 11 | -------------------------------------------------------------------------------- /Algorithms/UtopianTree.swift: -------------------------------------------------------------------------------- 1 | func utopianTree(n: Int) -> Int { 2 | 3 | if n == 0 { return 1 } 4 | var height = 1 5 | for i in 1...n { 6 | if i%2 != 0 { 7 | height = height*2 8 | } else { 9 | height += 1 10 | } 11 | } 12 | return height 13 | } 14 | -------------------------------------------------------------------------------- /Algorithms/SequenceEquation.swift: -------------------------------------------------------------------------------- 1 | func permutationEquation(p: [Int]) -> [Int] { 2 | 3 | var array: [Int] = [] 4 | for i in 1...p.count { 5 | let number = (p.firstIndex(of: i) ?? 0) + 1 6 | let pos = (p.firstIndex(of: number) ?? 0) + 1 7 | array.append(pos) 8 | } 9 | return array 10 | } 11 | -------------------------------------------------------------------------------- /Algorithms/Mini-MaxSum.swift: -------------------------------------------------------------------------------- 1 | func miniMaxSum(arr: [Int]) -> Void { 2 | 3 | var numbers = arr 4 | numbers.sort() 5 | 6 | let minimun = numbers.reduce(0, +) - numbers[4] 7 | let maximun = numbers.reduce(0, +) - numbers[0] 8 | 9 | let miniMax = String(minimun) + " " + String(maximun) 10 | print(miniMax) 11 | } 12 | -------------------------------------------------------------------------------- /Algorithms/TimeConversion.swift: -------------------------------------------------------------------------------- 1 | func timeConversion(s: String) -> String { 2 | 3 | let date1 = DateFormatter() 4 | date1.dateFormat = "h:mm:ssa" 5 | let date = date1.date(from: s) 6 | 7 | let date2 = DateFormatter() 8 | date2.dateFormat = "HH:mm:ss" 9 | 10 | return date2.string(from: date!) 11 | 12 | } 13 | -------------------------------------------------------------------------------- /Algorithms/ElectronicsShop.swift: -------------------------------------------------------------------------------- 1 | var spent = [Int]() 2 | 3 | for keyboard in keyboards { 4 | for drive in drives { 5 | if keyboard + drive <= b { 6 | spent.append(keyboard + drive) 7 | } 8 | } 9 | } 10 | 11 | if spent.count >= 1 { return spent.max()! } 12 | else { return -1 } 13 | -------------------------------------------------------------------------------- /Algorithms/Pangrams.swift: -------------------------------------------------------------------------------- 1 | func pangrams(s: String) -> String { 2 | 3 | var alphabet = "abcdefghijklmnopqrstuvwxyz" 4 | var sArray = Array(s.lowercased()) 5 | 6 | for letter in alphabet { 7 | if !sArray.contains(letter) { 8 | return "not pangram" 9 | } 10 | } 11 | 12 | return "pangram" 13 | } 14 | 15 | -------------------------------------------------------------------------------- /Algorithms/ViralAdvertising.swift: -------------------------------------------------------------------------------- 1 | func viralAdvertising(n: Int) -> Int { 2 | 3 | var result: Double = 0 4 | var people: Double = 5 5 | var reached: Double = 0 6 | 7 | for _ in 1...n { 8 | result = floor(people/2.0) 9 | people = result*3 10 | reached += result 11 | } 12 | return Int(reached) 13 | 14 | } 15 | -------------------------------------------------------------------------------- /Algorithms/Staircase.swift: -------------------------------------------------------------------------------- 1 | func staircase(n: Int) -> Void { 2 | 3 | var line = "" 4 | for index in stride(from: n - 1, to: -1, by: -1) { 5 | let spaces = String(repeating: " ", count: index) 6 | let hash = String(repeating: "#", count: n - index) 7 | 8 | line = spaces + hash 9 | 10 | print(line) 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /Algorithms/GradingStudents.swift: -------------------------------------------------------------------------------- 1 | func gradingStudents(grades: [Int]) -> [Int] { 2 | 3 | var results = [Int]() 4 | 5 | for grade in grades { 6 | if grade >= 38 && grade%5 > 2 { 7 | results.append(grade + (5 - grade%5)) 8 | } else { 9 | results.append(grade) 10 | } 11 | } 12 | 13 | return results 14 | } 15 | -------------------------------------------------------------------------------- /Algorithms/Kangaroo.swift: -------------------------------------------------------------------------------- 1 | func kangaroo(x1: Int, v1: Int, x2: Int, v2: Int) -> String { 2 | 3 | if (x1 > x2 && v1 >= v2) || (v2 >= v1) { 4 | return "NO" 5 | } else { 6 | let jump = (x1 - x2)%(v2 - v1) 7 | if jump == 0 { 8 | return "YES" 9 | } else { 10 | return "NO" 11 | } 12 | } 13 | 14 | } 15 | -------------------------------------------------------------------------------- /Algorithms/MigratoryBirds.swift: -------------------------------------------------------------------------------- 1 | func migratoryBirds(arr: [Int]) -> Int { 2 | 3 | var bird = 0 4 | var counts = [Int: Int]() 5 | var array = arr 6 | array.sort() 7 | 8 | array.forEach { counts[$0] = (counts[$0] ?? 0) + 1 } 9 | 10 | if let (value, count) = counts.max(by: {$0.1 < $1.1}) { 11 | bird = value 12 | } 13 | 14 | return bird 15 | } 16 | -------------------------------------------------------------------------------- /Interview-Preparation-Kit/Arrays/LeftRotation.swift: -------------------------------------------------------------------------------- 1 | // HackerRank tests 2 | // Warmup challenges 3 | // Arrays: Left Rotation 4 | // Created by Maria Fernanda Azolin on 28/06/20. 5 | 6 | func rotLeft(a: [Int], d: Int) -> [Int] { 7 | 8 | let n = a.count 9 | let lastArray = Array(a[.. String { 2 | 3 | let set1 = NSCountedSet(array: Array(s1)) 4 | let set2 = NSCountedSet(array: Array(s2)) 5 | 6 | for letter in set1 { 7 | if set2.count(for: letter) >= 1 { 8 | return "YES" 9 | } 10 | } 11 | 12 | return "NO" 13 | 14 | } 15 | -------------------------------------------------------------------------------- /Interview-Preparation-Kit/StringManipulation/AlternatingCharacters.swift: -------------------------------------------------------------------------------- 1 | func alternatingCharacters(s: String) -> Int { 2 | 3 | var remove = 0 4 | let arr = Array(s) 5 | for (index, letter) in arr.enumerated() { 6 | if index < arr.count-1 { 7 | if letter == arr[index+1] { 8 | remove += 1 9 | } 10 | } 11 | } 12 | return remove 13 | } 14 | -------------------------------------------------------------------------------- /Algorithms/DiagonalDifference.swift: -------------------------------------------------------------------------------- 1 | func diagonalDifference(arr: [[Int]]) -> Int { 2 | 3 | var firstDiagonal = 0 4 | var secondDiagonal = 0 5 | 6 | let size = arr[0].count 7 | 8 | for index in 0...size-1 { 9 | firstDiagonal += arr[index][index] 10 | secondDiagonal += arr[(size-index-1)][index] 11 | } 12 | 13 | return abs(firstDiagonal - secondDiagonal) 14 | 15 | } 16 | -------------------------------------------------------------------------------- /Algorithms/ChocolateFeast.swift: -------------------------------------------------------------------------------- 1 | //https://www.hackerrank.com/challenges/chocolate-feast/problem 2 | 3 | func chocolateFeast(n: Int, c: Int, m: Int) -> Int { 4 | 5 | var bars = Int(floor(Double(n/c))) 6 | var wrappers = bars 7 | 8 | while wrappers >= m { 9 | let newBars = Int(floor(Double(wrappers/m))) 10 | wrappers = newBars + wrappers%m 11 | bars += newBars 12 | } 13 | 14 | return bars 15 | } 16 | -------------------------------------------------------------------------------- /Algorithms/HackerRankInAString.swift: -------------------------------------------------------------------------------- 1 | func hackerrankInString(s: String) -> String { 2 | let str = Array("hackerrank") 3 | 4 | if s.count < str.count { 5 | return "NO" 6 | } 7 | 8 | var counter = 0 9 | for letter in s { 10 | if counter < str.count && letter == str[counter] { 11 | counter += 1 12 | } 13 | } 14 | 15 | return counter == str.count ? "YES" : "NO" 16 | } 17 | -------------------------------------------------------------------------------- /Interview-Preparation-Kit/Sorting/MarkandToys.swift: -------------------------------------------------------------------------------- 1 | func maximumToys(prices: [Int], k: Int) -> Int { 2 | 3 | var toys = prices 4 | var money = k 5 | toys.sort() 6 | 7 | var index = 0 8 | while(money > 0 ) { 9 | if money - toys[index] >= 0 { 10 | money -= toys[index] 11 | } else { 12 | return index 13 | } 14 | index += 1 15 | } 16 | 17 | return index 18 | } 19 | 20 | 21 | -------------------------------------------------------------------------------- /Algorithms/CompareTheTriplets.swift: -------------------------------------------------------------------------------- 1 | func compareTriplets(a: [Int], b: [Int]) -> [Int] { 2 | 3 | var alice = 0 4 | var bob = 0 5 | var result = [Int]() 6 | 7 | for (index, points) in a.enumerated() { 8 | if points > b[index] { 9 | alice += 1 10 | } else if points < b[index] { 11 | bob += 1 12 | } 13 | } 14 | 15 | result.append(alice) 16 | result.append(bob) 17 | 18 | return result 19 | } 20 | -------------------------------------------------------------------------------- /Algorithms/BonApettit.swift: -------------------------------------------------------------------------------- 1 | func bonAppetit(bill: [Int], k: Int, b: Int) -> Void { 2 | 3 | var separetedBill = 0 4 | 5 | for (index, item) in bill.enumerated() { 6 | if index != k { 7 | separetedBill += item 8 | } 9 | } 10 | separetedBill = separetedBill/2 11 | 12 | if b == separetedBill { 13 | print("Bon Appetit") 14 | } else { 15 | let cost = b - separetedBill 16 | print(cost) 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Algorithms/CutTheSticks.swift: -------------------------------------------------------------------------------- 1 | func cutTheSticks(arr: [Int]) -> [Int] { 2 | 3 | var sticks = arr 4 | sticks.sort() 5 | 6 | var length = [Int]() 7 | 8 | while sticks.count > 0 { 9 | length.append(sticks.count) 10 | 11 | let minor = sticks[0] 12 | for index in 0...sticks.count-1 { 13 | sticks[index] -= minor 14 | } 15 | 16 | sticks = sticks.filter { $0 > 0 } 17 | } 18 | 19 | return length 20 | } 21 | -------------------------------------------------------------------------------- /Algorithms/DesignerPDFViwer.swift: -------------------------------------------------------------------------------- 1 | func designerPdfViewer(h: [Int], word: String) -> Int { 2 | 3 | var heights = [Int]() 4 | 5 | for element in word { 6 | let letter = element as Character 7 | if let value = letter.asciiValue { 8 | let position = letter.isUppercase ? value - 65 : value - 97 9 | let height = h[Int(position)] 10 | heights.append(Int(height)) 11 | } 12 | } 13 | 14 | return word.count * (heights.max() ?? 1) 15 | } 16 | -------------------------------------------------------------------------------- /Algorithms/FindDigits.swift: -------------------------------------------------------------------------------- 1 | func findDigits(n: Int) -> Int { 2 | 3 | let digits = String(n).compactMap{ $0.wholeNumberValue } 4 | var divisors = 0 5 | for digit in digits { 6 | if digit != 0 && n%digit == 0 { 7 | divisors += 1 8 | } 9 | } 10 | return divisors 11 | } 12 | 13 | //first we split the integer in its separeted digits 14 | //for each digit we check if the whole number is divisible by it 15 | //but first we check if the digit is not 0 16 | //as division by zero is undefined 17 | -------------------------------------------------------------------------------- /Algorithms/PlusMinus.swift: -------------------------------------------------------------------------------- 1 | func plusMinus(arr: [Int]) -> Void { 2 | 3 | let size = Double(arr.count) 4 | var positives: Double = 0.000000 5 | var negatives: Double = 0.000000 6 | var zeros: Double = 0.000000 7 | 8 | for number in arr { 9 | if number > 0 { 10 | positives += 1 11 | } else if number < 0 { 12 | negatives += 1 13 | } else { 14 | zeros += 1 15 | } 16 | } 17 | 18 | print(positives/size) 19 | print(negatives/size) 20 | print(zeros/size) 21 | } 22 | -------------------------------------------------------------------------------- /Algorithms/InsertionSort2.swift: -------------------------------------------------------------------------------- 1 | func insertionSort2(n: Int, arr: [Int]) -> Void { 2 | var array = arr 3 | for index in 1.. 0 && array[position - 1] > value { 8 | array[position] = array[position - 1] 9 | position -= 1 10 | } 11 | array[position] = value 12 | 13 | for element in array { 14 | print(element, terminator : " ") 15 | } 16 | print("") 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Algorithms/AppleAndOrange.swift: -------------------------------------------------------------------------------- 1 | func countApplesAndOranges(s: Int, t: Int, a: Int, b: Int, apples: [Int], oranges: [Int]) -> Void { 2 | 3 | var numberOfApples = 0 4 | var numberOfOranges = 0 5 | 6 | for apple in apples { 7 | if a + apple >= s && a + apple <= t { 8 | numberOfApples += 1 9 | } 10 | } 11 | 12 | for orange in oranges { 13 | if b + orange >= s && b + orange <= t { 14 | numberOfOranges += 1 15 | } 16 | } 17 | 18 | print(numberOfApples) 19 | print(numberOfOranges) 20 | } 21 | -------------------------------------------------------------------------------- /Algorithms/DivisibleSumPairs.swift: -------------------------------------------------------------------------------- 1 | func divisibleSumPairs(n: Int, k: Int, ar: [Int]) -> Int { 2 | 3 | var counter = 0 4 | for (index, element) in ar.enumerated() { 5 | let sum = getPairsSum(ar: ar, index: index) 6 | counter += sum.filter{$0%k == 0}.count 7 | } 8 | return counter 9 | } 10 | 11 | func getPairsSum(ar: [Int], index: Int) -> [Int] { 12 | if index > ar.count-2 { 13 | return [] 14 | } 15 | 16 | var pairSum = [Int]() 17 | for i in (index + 1)...ar.count-1 { 18 | pairSum.append(ar[index] + ar[i]) 19 | } 20 | return pairSum 21 | } 22 | -------------------------------------------------------------------------------- /Interview-Preparation-Kit/Sorting/BubbleSort.swift: -------------------------------------------------------------------------------- 1 | func countSwaps(a: [Int]) -> Void { 2 | 3 | var swaps = 0 4 | var array = a 5 | 6 | for i in 0...(array.count-1) { 7 | for j in 0...(array.count-2) { 8 | // Swap adjacent elements if they are in decreasing order 9 | if array[j] > array[j + 1] { 10 | array.swapAt(j, j + 1) 11 | swaps += 1 12 | } 13 | } 14 | } 15 | 16 | print("Array is sorted in \(swaps) swaps.") 17 | print("First Element: \(array.first!)") 18 | print("Last Element: \(array.last!)") 19 | } 20 | -------------------------------------------------------------------------------- /Algorithms/BreakingTheRecords.swift: -------------------------------------------------------------------------------- 1 | func breakingRecords(scores: [Int]) -> [Int] { 2 | 3 | var max = scores.first! 4 | var min = scores.first! 5 | var maxCounter = 0 6 | var minCounter = 0 7 | 8 | var result = [Int]() 9 | 10 | for element in scores { 11 | if element < min { 12 | min = element 13 | minCounter += 1 14 | } 15 | if element > max { 16 | max = element 17 | maxCounter += 1 18 | } 19 | } 20 | result.append(maxCounter) 21 | result.append(minCounter) 22 | 23 | return result 24 | 25 | } 26 | -------------------------------------------------------------------------------- /Algorithms/MinimunDistances.swift: -------------------------------------------------------------------------------- 1 | func minimumDistances(a: [Int]) -> Int { 2 | var minDistance = a.count; 3 | let lastPos = a.count-1 4 | 5 | for (index, element) in a.enumerated() { 6 | if index < lastPos { 7 | let aux = a[index+1...lastPos] 8 | if aux.contains(element) { 9 | let distance = (aux.firstIndex(of: element) ?? 0) - index 10 | if distance < minDistance { 11 | minDistance = distance 12 | } 13 | } 14 | } 15 | } 16 | return minDistance != a.count ? minDistance : -1 17 | } 18 | -------------------------------------------------------------------------------- /Interview-Preparation-Kit/Warmup-Challenges/RepeatedString.swift: -------------------------------------------------------------------------------- 1 | // HackerRank tests 2 | // Warmup challenges 3 | // Repeated String 4 | // Created by Maria Fernanda Azolin on 29/06/20. 5 | 6 | func repeatedString(s: String, n: Int) -> Int { 7 | 8 | let subStringCounter = s.filter{ $0 == "a" }.count 9 | let closedRepetitions = Int(floor(Double(n/s.count))) 10 | let rest = n%(s.count) 11 | 12 | var aCounter = closedRepetitions * subStringCounter 13 | 14 | let endIndex = s.index(s.startIndex, offsetBy: rest) 15 | let lastSubString = String(s[.. Int { 2 | 3 | var errors = 0 4 | 5 | for (index,letter) in s.enumerated() { 6 | if index%3 == 0 || index%3 == 2 { 7 | if letter != "S" { 8 | errors += 1 9 | } 10 | } else if index%3 == 1 { 11 | if letter != "O" { 12 | errors += 1 13 | } 14 | } 15 | 16 | } 17 | 18 | return errors 19 | 20 | } 21 | 22 | //given the string SOS, index 0 and 2 are "S" 23 | //and index 1 is "O" 24 | //so we consider this string as the pattern and look 25 | //for differences in the given word, comparing 26 | //the letter at the index 27 | -------------------------------------------------------------------------------- /Algorithms/BeautifulBinaryString.swift: -------------------------------------------------------------------------------- 1 | func beautifulBinaryString(b: String) -> Int { 2 | 3 | let bArray = Array(b) 4 | var counter = 0 5 | var skip = 0 6 | 7 | for index in 2.. Int { 7 | 8 | //itera o array 9 | //ve se a posicao do array contem oq deveria 10 | //se nao, coloca o numero errado onde ele deveria estar 11 | //caso sim, vai pra proxima posicao 12 | 13 | var array = arr 14 | var index = 0 15 | var swaps = 0 16 | 17 | while index < array.count - 1 { 18 | let correctNumber = index + 1 19 | if correctNumber != array[index] { 20 | array.swapAt(index, array[index] - 1) 21 | swaps += 1 22 | } else { 23 | index += 1 24 | } 25 | } 26 | 27 | return swaps 28 | } 29 | -------------------------------------------------------------------------------- /Interview-Preparation-Kit/Warmup-Challenges/SockMerchant.swift: -------------------------------------------------------------------------------- 1 | // 2 | // HackerRank tests 3 | // Warmup challenges 4 | // Sock Merchant 5 | // Created by Maria Fernanda Azolin on 28/06/20. 6 | // 7 | //see the problem below: 8 | //www.hackerrank.com/challenges/sock-merchant/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=warmup 9 | 10 | 11 | import Foundation 12 | 13 | func sockMerchant(n: Int, ar: [Int]) -> Int { 14 | 15 | var numberOfPairs = 0 16 | var socksArray = [Int]() 17 | 18 | for a in ar { 19 | if let index = socksArray.firstIndex(of: a) { 20 | numberOfPairs += 1 21 | socksArray.remove(at: index) 22 | } else { 23 | socksArray.append(a) 24 | } 25 | } 26 | 27 | return numberOfPairs 28 | } 29 | -------------------------------------------------------------------------------- /Interview-Preparation-Kit/Warmup-Challenges/CountingValleys.swift: -------------------------------------------------------------------------------- 1 | // 2 | // HackerRank tests 3 | // Warmup challenges 4 | // Counting Valleys 5 | // Created by Maria Fernanda Azolin on 28/06/20. 6 | // 7 | 8 | func countingValleys(n: Int, s: String) -> Int { 9 | 10 | var level = 0 11 | var wasDescending = false 12 | var numberOfValleys = 0 13 | 14 | for direction in s { 15 | 16 | if direction == "U" { 17 | level += 1 18 | } else { 19 | level -= 1 20 | } 21 | 22 | if level < 0 { 23 | if !wasDescending { 24 | numberOfValleys += 1 25 | wasDescending = true 26 | } 27 | } else { 28 | if wasDescending { 29 | wasDescending = false 30 | } 31 | } 32 | 33 | } 34 | -------------------------------------------------------------------------------- /Interview-Preparation-Kit/Arrays/NewYearChaos.swift: -------------------------------------------------------------------------------- 1 | // HackerRank tests 2 | // Array challenges 3 | // New Year Chaos 4 | // Created by Maria Fernanda Azolin on 28/06/20. 5 | 6 | func minimumBribes(q: [Int]) -> Void { 7 | 8 | var numberOfDisplacements = 0 9 | 10 | for index in (0.. 2 { 14 | print("Too chaotic") 15 | return 16 | } 17 | 18 | let initialPos = q[index] - 1 19 | let range = max(0,initialPos - 2).. q[index] { 23 | numberOfDisplacements += 1 24 | } 25 | } 26 | } 27 | 28 | print(numberOfDisplacements) 29 | } 30 | -------------------------------------------------------------------------------- /Interview-Preparation-Kit/Warmup-Challenges/JumpingOnTheClouds.swift: -------------------------------------------------------------------------------- 1 | // HackerRank tests 2 | // Warmup challenges 3 | // Jumping on the clouds 4 | // Created by Maria Fernanda Azolin on 28/06/20. 5 | 6 | func jumpingOnClouds(c: [Int]) -> Int { 7 | 8 | var jumps = 0 9 | var positions = c.count 10 | var iterator = 0 11 | 12 | while(iterator < positions-1) { 13 | 14 | var nextPos = iterator + 2 15 | 16 | if nextPos < positions { 17 | if c[nextPos] == 0 { 18 | iterator += 2 19 | } else { 20 | iterator += 1 21 | } 22 | } else { 23 | if iterator == positions { 24 | return jumps 25 | } 26 | iterator += 1 27 | } 28 | 29 | jumps += 1 30 | } 31 | 32 | print(jumps) 33 | return jumps 34 | } 35 | -------------------------------------------------------------------------------- /Algorithms/EqualizeTheArray.swift: -------------------------------------------------------------------------------- 1 | func equalizeArray(arr: [Int]) -> Int { 2 | 3 | //cria um counted set com cada numero do array inicial 4 | //ve quem tem a maior quantia de repetidos nesse counted set 5 | //retira quem nao for esse numero com maior repeticao, e faz um array final so com o mais repetido 6 | //faz tamanho do array inicial - tamanho do array final 7 | 8 | var countedSet = NSCountedSet() 9 | 10 | for number in arr { 11 | countedSet.add(number) 12 | } 13 | 14 | var max = 0 15 | var mostRepeated = 0 16 | for number in countedSet { 17 | if countedSet.count(for: number) > max { 18 | max = countedSet.count(for: number) 19 | mostRepeated = number as! Int 20 | } 21 | } 22 | 23 | let finalArray = arr.filter { $0 == mostRepeated } 24 | 25 | return arr.count - finalArray.count 26 | } 27 | -------------------------------------------------------------------------------- /Interview-Preparation-Kit/Arrays/ArrayManipulation.swift: -------------------------------------------------------------------------------- 1 | // HackerRank tests 2 | // Array challenges 3 | // Array Manipulation 4 | // Created by Maria Fernanda Azolin on 29/06/20 5 | 6 | func arrayManipulation(n: Int, queries: [[Int]]) -> Int { 7 | 8 | //other solutions would be simpler to understand, but 9 | //using DIFFERENCE ARRAY was necessary to avoid timeOut 10 | 11 | var zeros = [Int](repeating: 0, count: n) 12 | var diff = zeros 13 | 14 | for query in queries { 15 | let k = query[2] 16 | let a = query[0] - 1 17 | let b = query[1] - 1 18 | 19 | diff[a] += k 20 | if b+1 <= diff.count-1 { 21 | diff[b+1] -= k 22 | } 23 | } 24 | 25 | var level = 0 26 | for (index, element) in zeros.enumerated() { 27 | level += diff[index] 28 | zeros[index] = level 29 | } 30 | 31 | return zeros.max()! 32 | } 33 | -------------------------------------------------------------------------------- /Interview-Preparation-Kit/Arrays/2DArray.swift: -------------------------------------------------------------------------------- 1 | // HackerRank tests 2 | // Array challenges 3 | // 2D Array 4 | // Created by Maria Fernanda Azolin on 28/06/20. 5 | func hourglassSum(arr: [[Int]]) -> Int { 6 | 7 | let initialLine = 0 8 | let lastLine = 3 9 | let initialColumn = 0 10 | let lastColumn = 3 11 | 12 | var sumsArray = [Int]() 13 | 14 | for line in initialLine...lastLine { 15 | for column in initialColumn...lastColumn { 16 | let sum = sumOfHourGlass(arr: arr, line: line, column: column) 17 | sumsArray.append(sum) 18 | } 19 | } 20 | 21 | sumsArray.sort() 22 | 23 | return sumsArray[sumsArray.count-1] 24 | } 25 | 26 | func sumOfHourGlass(arr: [[Int]], line: Int, column: Int) -> Int { 27 | return arr[line][column] + arr[line][column+1] + arr[line][column+2] 28 | + arr[line+1][column+1] 29 | + arr[line+2][column] + arr[line+2][column+1] + arr[line+2][column+2] 30 | } 31 | -------------------------------------------------------------------------------- /Algorithms/ServiceLane.swift: -------------------------------------------------------------------------------- 1 | //Disclaimer: this problem was poorly written 2 | //and the template is kind of wrong 3 | //as the widths are not passed to the function 4 | 5 | //To fix it and solve the problem, 6 | //change the method call and receive width instead of the n parameter 7 | //so 8 | // func serviceLane(n: Int, cases: [[Int]]) -> [Int] { 9 | //turns into 10 | // func serviceLane(width: [Int], cases: [[Int]]) -> [Int] { 11 | //and 12 | // let result = serviceLane(n: n, cases: cases) 13 | //turns into 14 | // let result = serviceLane(width: width, cases: cases) 15 | 16 | 17 | func serviceLane(width: [Int], cases: [[Int]]) -> [Int] { 18 | var results: [Int] = [] 19 | 20 | for i in 0...cases.count-1 { 21 | let initial = cases[i][0] 22 | let final = cases[i][1] 23 | 24 | var newWidths: [Int] = [] 25 | for pos in initial...final { 26 | newWidths.append(width[pos]) 27 | } 28 | results.append(newWidths.min() ?? 0) 29 | } 30 | 31 | return results 32 | } 33 | -------------------------------------------------------------------------------- /Algorithms/BeautifulDaysAtTheMovies.swift: -------------------------------------------------------------------------------- 1 | //my approach for this test was: 2 | //create an array in the range given by the parameters 3 | //create an array with the reversed pairs of these numbers 4 | //^used map function to transform the first array here 5 | //create a third array with the absolute difference between the pairs of numbers 6 | //use filter to find which ones of these matched the condition 7 | //aka which one was diivisible by k parameter 8 | 9 | //also, created an auxiliar function to return a reversed Integer 10 | 11 | func beautifulDays(i: Int, j: Int, k: Int) -> Int { 12 | 13 | let days = Array(i...j) 14 | let reversedDays = days.map { reverseInt(number: $0) } 15 | 16 | var difference = [Int]() 17 | for (index,day) in days.enumerated() { 18 | difference.append(abs(day - reversedDays[index])) 19 | } 20 | 21 | return difference.filter { $0%k == 0 }.count 22 | } 23 | 24 | func reverseInt(number: Int) -> Int { 25 | var n = number 26 | var reversed = 0 27 | while (n != 0) { 28 | reversed = reversed*10 29 | reversed += n%10 30 | n = n/10 31 | } 32 | return reversed 33 | } 34 | -------------------------------------------------------------------------------- /Interview-Preparation-Kit/DictionariesAndHashmps/RansomNote.swift: -------------------------------------------------------------------------------- 1 | func checkMagazine(magazine: [String], note: [String]) -> Void { 2 | 3 | //my early solution was fine and working, but the time complexity was O(n2) 4 | //because of the firstIndex() inside the for loop 5 | //That caused timeOut in some cases. 6 | //A way to solve this was using NSCountedSet 7 | //a nice explanation: https://www.hackingwithswift.com/example-code/arrays/how-to-count-objects-in-a-set-using-nscountedset 8 | //early solution: 9 | // if magazine.count < note.count { 10 | // print("No") 11 | // return 12 | // } 13 | // var magazineCopy = magazine 14 | // for notes in note { 15 | // if !magazineCopy.contains(notes) { 16 | // print("No") 17 | // return 18 | // } 19 | // if let index = magazineCopy.firstIndex(of: notes) { 20 | // magazineCopy.remove(at: index) 21 | // } 22 | // } 23 | // print("Yes") 24 | // return 25 | 26 | let magazineWords = NSCountedSet(array: magazine) 27 | let noteWords = NSCountedSet(array: note) 28 | for noteWord in noteWords { 29 | //if any word appears more times in the note than it appears in the 30 | //magazine, the ransom note can't be made 31 | if magazineWords.count(for: noteWord) < noteWords.count(for: noteWord) { 32 | print("No") 33 | return 34 | } 35 | } 36 | print("Yes") 37 | 38 | } 39 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Xcode 2 | # 3 | # gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore 4 | 5 | ## User settings 6 | xcuserdata/ 7 | 8 | ## compatibility with Xcode 8 and earlier (ignoring not required starting Xcode 9) 9 | *.xcscmblueprint 10 | *.xccheckout 11 | 12 | ## compatibility with Xcode 3 and earlier (ignoring not required starting Xcode 4) 13 | build/ 14 | DerivedData/ 15 | *.moved-aside 16 | *.pbxuser 17 | !default.pbxuser 18 | *.mode1v3 19 | !default.mode1v3 20 | *.mode2v3 21 | !default.mode2v3 22 | *.perspectivev3 23 | !default.perspectivev3 24 | 25 | ## Obj-C/Swift specific 26 | *.hmap 27 | 28 | ## App packaging 29 | *.ipa 30 | *.dSYM.zip 31 | *.dSYM 32 | 33 | ## Playgrounds 34 | timeline.xctimeline 35 | playground.xcworkspace 36 | 37 | # Swift Package Manager 38 | # 39 | # Add this line if you want to avoid checking in source code from Swift Package Manager dependencies. 40 | # Packages/ 41 | # Package.pins 42 | # Package.resolved 43 | # *.xcodeproj 44 | # 45 | # Xcode automatically generates this directory with a .xcworkspacedata file and xcuserdata 46 | # hence it is not needed unless you have added a package configuration file to your project 47 | # .swiftpm 48 | 49 | .build/ 50 | 51 | # CocoaPods 52 | # 53 | # We recommend against adding the Pods directory to your .gitignore. However 54 | # you should judge for yourself, the pros and cons are mentioned at: 55 | # https://guides.cocoapods.org/using/using-cocoapods.html#should-i-check-the-pods-directory-into-source-control 56 | # 57 | # Pods/ 58 | # 59 | # Add this line if you want to avoid checking in source code from the Xcode workspace 60 | # *.xcworkspace 61 | 62 | # Carthage 63 | # 64 | # Add this line if you want to avoid checking in source code from Carthage dependencies. 65 | # Carthage/Checkouts 66 | 67 | Carthage/Build/ 68 | 69 | # Accio dependency management 70 | Dependencies/ 71 | .accio/ 72 | 73 | # fastlane 74 | # 75 | # It is recommended to not store the screenshots in the git repo. 76 | # Instead, use fastlane to re-generate the screenshots whenever they are needed. 77 | # For more information about the recommended setup visit: 78 | # https://docs.fastlane.tools/best-practices/source-control/#source-control 79 | 80 | fastlane/report.xml 81 | fastlane/Preview.html 82 | fastlane/screenshots/**/*.png 83 | fastlane/test_output 84 | 85 | # Code Injection 86 | # 87 | # After new code Injection tools there's a generated folder /iOSInjectionProject 88 | # https://github.com/johnno1962/injectionforxcode 89 | 90 | iOSInjectionProject/ 91 | --------------------------------------------------------------------------------