Two-Sum Problem - Swift Tutorial - iOS Interview Coding Challenge

  Переглядів 30,673

Sean Allen

Sean Allen

День тому

The next video in my iOS Interview questions series all about coding challenges explains the two-sum problem and its multiple solutions in Swift. We'll solve this problem three different ways with varying levels of efficiency (Big O Notation)
iOS Dev Courses - seanallen.teachable.com/
More on Big O Notation:
Cracking the coding Interview: • Big O Notation
Xcode Project Source Code:
www.dropbox.com/sh/emzllk50ai...
iOS Dev Courses:
seanallen.teachable.com/
Twitter:
Sean Allen - / seanallen_dev
Hired.com:
hired.com/x/1n01g
Book and learning recommendations that help out the channel if you decide to purchase (Affiliate Links):
Paul Hudson's Hacking With Swift:
gumroad.com/a/762098803
Donny Wals - Combine:
gumroad.com/a/909014131
Mark Moeyken’s SwiftUI Books:
www.bigmountainstudio.com/swiftui-views-book/fzc51
Objc.io Books (Thinking in SwiftUI & Advanced Swift):
gumroad.com/a/656585843
Ray Wenderlich Books:
store.raywenderlich.com/a/208...
#swift #softwaredeveloper #iosdeveloper

КОМЕНТАРІ: 104
@seanallen
@seanallen 4 роки тому
Watch Next - iOS Take Home Project - Job Interview Practice - Free Preview - ukposts.info/have/v-deo/hYN6mWiwbXyWxmw.html
@danylokurylo3142
@danylokurylo3142 4 роки тому
Wow! The pointer solution is so clever! Simple and beautiful :)
@seanallen
@seanallen 4 роки тому
Glad you liked it, Danil!
@vrezhgulyan6834
@vrezhgulyan6834 5 років тому
I really think showing the linear solution with a set here would’ve been highly beneficial. Our last solution works only because the array is sorted and this problem in interviews is almost never sorted. The solution below is always linear. var seenSet: Set = [] for num in array { If seenSet.contains(sum - num) { return true } else { seenSet.insert(num) } } return false
@carlosswiftdev2703
@carlosswiftdev2703 Рік тому
What's wrong with just using .sorted() on the array first?
@vrezhgulyan6834
@vrezhgulyan6834 Рік тому
@@carlosswiftdev2703 when you use internal functions like sorted during an interview, you have to add their time complexity. Sorting at best is usually nlogn which is always going to be slower the n (linear) which is what the above solution with a set is
@carlosswiftdev2703
@carlosswiftdev2703 Рік тому
​@@vrezhgulyan6834 Awesome thank you for the explanation. I could do with watching some CS50 videos to fully understand time complexity.
@JayMutzafi
@JayMutzafi 6 років тому
Fast? Finally a video I don't need to speed up. :)
@seanallen
@seanallen 6 років тому
Haha, Jay... that's nice to hear. The #1 piece of constructive feedback I get is that I talk too fast. Glad to hear it works for you!
@JayMutzafi
@JayMutzafi 6 років тому
Sean Allen I totally get, and of course slow down if you need to, I can always speed it up. Keep up the good work :)
@whansen101
@whansen101 6 років тому
Thanks and I hope you realize how much value you are bringing to iOS developers. These algos are not easy to learn and you are doing a great job at chunking down the larger concept into code that is easy to absorb.
@seanallen
@seanallen 6 років тому
Thanks for the kind words, Warren. Happy to hear I'm helping!
@AgamRandhawa
@AgamRandhawa 6 років тому
That was the best explanation I found on youtube until now.
@seanallen
@seanallen 6 років тому
Thanks Prabhdeep!
@MrSaberjack
@MrSaberjack 5 років тому
@Sean If you look at the documentation the remove(at: Index) is of complexity O(n) it would add more computation in binarySearch flow /// - Complexity: O(*n*), where *n* is the length of the array. public mutating func remove(at index: Int) -> [Element].Element
@Tamagochi73
@Tamagochi73 6 років тому
In brute-force methode you can loop j starting from i+1 instead of from 0, because for j = 0...i you've done in the previous loops. The loop should say "for j in i+1..
@seanallen
@seanallen 6 років тому
Thanks for the contribution, Tamagochi. Always interesting to see the many different ways problems can be solved (with differing levels of efficiency/complexity).
@vastu09
@vastu09 6 років тому
First of all, thank you very much, your videos are very well explained and easy to understand. I think it's worth mentioning that the array need to be sorted for binary search and pointer move approach.
@seanallen
@seanallen 6 років тому
Thanks Kapil! You are right, they need to be sorted. I thought I mentioned that (maybe I didn't)
@ciso
@ciso Рік тому
​@@seanallen You said that the array is sorted 0:53 and the comment for binary search also said "(because its sorted)" but imo it would have been nice if you explained why the array has to be sorted in a bit more detail.
@benduke4842
@benduke4842 6 років тому
Thanks so much for your videos. I love these videos as I can grasp it easier if I am stepped through it. Thanks to your delegate tutorial, I was able to do my app which is on the app store now :) thanks so much for doing these videos please keep doing them.
@seanallen
@seanallen 6 років тому
+Ben Duke That's awesome, Ben! Makes me happy to hear I was able to help get your app on the store. More on the way!
@karunav3087
@karunav3087 Рік тому
Pointer solution is really good bro.. i also solved this problem with 2 for loops but whatever you suggested its simply short and sweet
@leeper
@leeper 6 років тому
Your last two videos explain starting with a sorted array. Do you plan on reviewing any sorting algorithms? Love your videos btw man. Easy to follow and you do a great job explaining concepts!
@seanallen
@seanallen 6 років тому
+Jordan Leeper thanks for the kind words, Jordan. Glad you enjoy the channel! I have a video planned for merge sort, but probably won't do all the sorting algorithms. Thanks for watching!
@seanallen
@seanallen 6 років тому
This was a long one.... Happy to help answer questions or clear up any confusion in the comments!
@kennethroark917
@kennethroark917 6 років тому
Thank you Sean!
@seanallen
@seanallen 6 років тому
Glad you enjoyed it, Kenneth.
@VitalyBokser
@VitalyBokser 4 роки тому
great video series and explanations
@seanallen
@seanallen 4 роки тому
Glad you liked it!
@sheetalshinde17
@sheetalshinde17 4 роки тому
perfect!!!! Can you please make video on how to calculate time complexity of a program.It would be really helpful Thanks In Advance.
@dodilodi1278
@dodilodi1278 Рік тому
in Brute Force method, we could even skip the last iteration because the last number(14) has already been compared to all other numbers, like: for i in 0..
@kristijanrotim2906
@kristijanrotim2906 6 років тому
Just today I had oral exam in data structures and algorithms and was talking about brute force, binary search, notations etc... It fantastic to see how to work with something like that in swift :D keep crushing it
@seanallen
@seanallen 6 років тому
That's awesome, Kristijan! I remember when I was learning this stuff, it was very rare to find examples written in Swift. That's the whole point of this series... I want to change that! Glad you enjoyed it!
@am13476
@am13476 6 років тому
nice one, Move pointer is definitely the easy one :D
@seanallen
@seanallen 6 років тому
+Adis Mulabdic I agree... sometimes the better solution can end up being pretty easy once you figure it out.
@jerrick.warren
@jerrick.warren 4 роки тому
Man! Thanks! Revisiting Algorithms on the Job Search! This explanation is dope. Any book Recommendations for Interview Questions?
@seanallen
@seanallen 4 роки тому
Glad you liked it, Jerrick. As always, you can't go wrong with cracking the coding interview. check out seanallen.co/store for a link
@GG-hk5iz
@GG-hk5iz 4 роки тому
Hey Sean Will Brute Force code work if we have multiple combinations for sum in array ?
@rahulbandal9185
@rahulbandal9185 6 років тому
Another great video.
@seanallen
@seanallen 6 років тому
+rahul bandal Thanks, Rahul!
@muhammadusman7603
@muhammadusman7603 Рік тому
The pointer solution doesn't work well in different scenarios like [3, 2, 4] and the target is 6
@nikhilmuskur7722
@nikhilmuskur7722 6 років тому
Nice Explanation....Are you planning to do a separate video on Time complexity and how to calculate it?
@seanallen
@seanallen 6 років тому
+nik mur Hey nik, that wasn't really in the plans since it's not Swift specific. There are a lot of great resources on UKposts that explain that already. They can do a better job than I can, since it's not really my area of expertise.
@nikhilmuskur7722
@nikhilmuskur7722 6 років тому
Thanks for the reply......... BTW loved the FOR-LOOP humor..... include more humor in your video's if you can :)
@seanallen
@seanallen 6 років тому
Haha, I've thrown those types of jokes in previous videos every once in a while... it's usually during late-night editing when I'm starting to get a little delirious, lol.
@nikhilmuskur7722
@nikhilmuskur7722 6 років тому
Today tried the code myself.........only thing I was improve was removing duplicates if you don't have a return after the is found statement.
@GrandAmericaMotorcycleRides
@GrandAmericaMotorcycleRides 2 роки тому
I like hidden basketball references like 23 lol
@michaelstram
@michaelstram 6 років тому
How would you do this if we are doing this with 2 arrays and need to find if elements in both equal a sum?
@gaga4282
@gaga4282 4 роки тому
let's try twoSumPointers(array: [3,2,4], sum: 6)
@kaideumers6102
@kaideumers6102 3 роки тому
The array isn’t sorted
@colonelkob
@colonelkob 6 років тому
Nice video Sean!
@seanallen
@seanallen 6 років тому
+Ben Cleary Thanks Ben. Interested to see if you have any alternate solutions 😀
@colonelkob
@colonelkob 6 років тому
ok it took a little while, but i've gone an iteration route, with a dictionary as a lookup table gist.github.com/bencleary1989/ba80119e85cf9b94a41447cf648595b5 all in all my first thought was option 3
@seanallen
@seanallen 6 років тому
Nice solution Ben! I've added it to the source code download (with a credit to you).
@colonelkob
@colonelkob 6 років тому
Thanks Sean 👍
@techwithchavan4986
@techwithchavan4986 Рік тому
Why is the input ascending ordered? Else we would need to sort it first and which makes loop count higher
@skyjacker91
@skyjacker91 5 років тому
Hey Sean, I'm not sure if this is the right place to ask you questions about this sort of old post you have, but when I downloaded your source code and ran 2. Binary Search method, the code wouldn't run and stops at "let = hasCompliment = binarySearch(array: ~~~)" while saying "Use of unresolved identifier 'binarySearch'. By any means would you know why I'm getting this error? Thanks
@MyRandomNick
@MyRandomNick 6 років тому
Could you add a tutorial about Big O Notations?
@seanallen
@seanallen 6 років тому
That's on the list, for sure. I just have a VERY long video "to-do" list. I'll get there eventually 😃
@allpurposeee5357
@allpurposeee5357 5 років тому
Just saw this video and i wanted to confirm something. The Linear Solution you did for it ...... Its fine for the Array you took. But you are taking 3 presumptions to solve this. 1. Data in array is sorted, 2. There is ONLY 1 match to get the sum value 3. No Value in Array is repeated (this one goes for all 3) Can you confirm if I am thinking wrong here ? or am i right ?
@filippo5157
@filippo5157 6 років тому
Isn't "complement" written with "e" ? just to make sure I understand correctly. Anyway great video as always!
@seanallen
@seanallen 6 років тому
Hey Filippo... it sure is. That was a typo on my part. Good catch!
@eer9279
@eer9279 3 роки тому
With brute force method, if array contains two or more same object and you add "where a != b" line, the algorithm will not work
@GG-hk5iz
@GG-hk5iz 6 років тому
Hey Sean. Any idea about solving 3 sum or 4 sum problem?
@seanallen
@seanallen 6 років тому
I have not tried those types of problems, Gunjan, so I wouldn't really know off the top of my head.
@wensmusic8636
@wensmusic8636 2 роки тому
When you say array.count - 1 where is the - 1 coming from? i understand that you need to get the highIndex, but i dont understand how you're able to get the highIndex from - 1? This is for the last func twoSumPointers
@justanotheryordle8752
@justanotheryordle8752 3 роки тому
if you change "let numbers3" to "var numbers3" and under it add "numbers3.sort()". Input: _______________________________________________________ var numbers3 = [1, 20, 31, 14, 15, 3] numbers3.sort() print(numbers3) Output: _______________________________________________________ [1, 3, 14, 15, 20, 31] Then no matter if the largest number is in the middle or 1st or anywhere it will sort them from low to high and you will get the right answer. Also thank you for this amazing video! really helped me a lot.
@richardhope1200
@richardhope1200 6 років тому
Nice tutorial Sean. I have added some code to your last method to filter and sort the array(I know it's sorted already. But if it wasn't here it is) as a bit of input from me to potentially reduce the iterations inside the while loop. func comparePointers(array: [Int], sum: Int) -> Bool { //Firstly apply a filter to eliminate all numbers greater than the sum and sort, in case numbers are not sorted. Thus reducing the amount of numbers the while loop has to iterate through. var filteredArray = array.filter({return $0 < sum}).sorted() print(filteredArray) var lowIndex = 0 var highIndex = filteredArray.count - 1 while lowIndex < highIndex { let sumOfItems = filteredArray[lowIndex] + filteredArray[highIndex] if sumOfItems == sum { print("Sum of \(filteredArray[lowIndex]) and \(filteredArray[highIndex]) = \(sum)") return true } else if sumOfItems < sum { lowIndex += 1 } else if sumOfItems > sum { highIndex -= 1 } } print("Pointers have crossed") return false }
@seanallen
@seanallen 6 років тому
Nice, Richard! Glad you enjoyed the video and took the time to build upon it and improve it! As you know, there is much more you could do with this code. I probably could have done an hour long video on this, but had to keep it a reasonable length 😃
@JayMutzafi
@JayMutzafi 6 років тому
So just to clarify, move pointer method only works on sorted array so we can just use sort on the array first and then apply that method and should be good?
@mayankverma4879
@mayankverma4879 6 років тому
Hey Sean, it's a request, i have struck at a coding problem that, i wanted to save a image which is picked from local gallery and then save it into sqlite database or any database.Thanks Keep posting...
@farshadtube2012
@farshadtube2012 3 роки тому
Hi Sean, The pointer algorithm isn't sufficient for all condition, let say input array is [3,2,4] and the sum is 6.
@eer9279
@eer9279 3 роки тому
You have to sort the array first
@farrasdoko4967
@farrasdoko4967 3 роки тому
The last solution isn't working if we looking for the index and not the value itself. For example I'm looking for `n` below: ``` // it's working if we looking for this n array[index] = n // but not working for array[n] = 10 ```
@XsiadzBiskup
@XsiadzBiskup 4 роки тому
Shouldn't the tempArray be initiated outside of the loop in point 2? When you're removing the n-th element in each loop from tempArray, you're only removing this single element, because you have (var tempArray = array) in the line above. If you'd initiate tempArray outside of the loop you'd shorten tempArray by n elements for each binary search.
@Brisbane275
@Brisbane275 6 років тому
Hi Sean, I was testing your method Brute Force, and it has a bug, cause in your array you have 2 of number 7, and if you try bruteForceTwoSum(array:numbers, sum:14) it will return false, but it should return true, cause you have 2 unique number 7
@seanallen
@seanallen 6 років тому
Hmmm... did you download the source code in the description and check that out? I just double checked my code and ran it with a sum of 14 and I'm returning TRUE in that situation. Try downloading the source code (link in description) and comparing it to what you have. Let me know if you're still returning false, but it seems to be working in my source code.
@ponmanir6017
@ponmanir6017 Рік тому
In 15.25 sec output is 1 and 12 = 13. Why it's not showing 6 and 7 = 13?
@isaacclark9825
@isaacclark9825 6 років тому
For method 2, there is an assumption here that you can copy the array and then remove an element from the copy in constant time. Is that a good assumption? I would not expect so.
@seanallen
@seanallen 6 років тому
Adding an additional "single" step to an algorithm, doesn't change it's time complexity. For example an algorithm that is 2n (meaning you need to iterate through the array twice), is still considered linear time because it the big picture, the 2 in front of the n is a minimal change. You typically drop the constants (in this case, the 2 in front of the end) when dealing with time complexity. However... adding an extra temporary array does take up memory, so this changes the space complexity, but not really the time complexity.
@isaacclark9825
@isaacclark9825 6 років тому
Adding a step inside a loop normally does not affect run time because most steps are constant time. But a step that copies an array cannot run in constant time. The longer the array, the longer it takes to copy. You have a step that takes o(n) inside of a loop that runs n times. If that was all of the code, clearly that should be o(n^2). I may be overly sensitive to this issue because I have been tutoring algorithm students for the past few years. I notice now that you did not make any prediction of the run time for method two, so you really did not make a mistake here. Great video by the way. I just found your videos yesterday and I am going through them all.
@seanallen
@seanallen 6 років тому
Thanks, Isaac. Glad you're enjoying the videos! Admittedly, CS isn't my strong suite (I don't come from a computer science background), so I may make a misstep or two along the way. Thanks for pointing it out. (I don't take it personally 😁 )
@Metaksa6666
@Metaksa6666 3 роки тому
I guess the 3rd approach works only for a sorted array
@anshulabhinav13
@anshulabhinav13 6 років тому
For solutions 2 & 3, you are assuming that the array is sorted, this can' t be a given assumption. Sorting itself takes a best case O(NlogN) time, so you need to factor that as well when calculating the total running time.
@seanallen
@seanallen 6 років тому
I should have been more clear about the givens on this problem. It is part of the problem that the array you are given is sorted. I based this video off of this Google Interview exercise, and in this exercise the array given is sorted. ukposts.info/have/v-deo/kHumk4l8e3eqzKs.html Again, I probably should have been more clear about the problem's description.
@anshulabhinav13
@anshulabhinav13 6 років тому
Got it !! And btw, you are doing a great job with the videos, keep it up :)
@seanallen
@seanallen 6 років тому
Thanks Anshul!
@ion.mardari
@ion.mardari 5 років тому
Hi Anshul, So if we sort the array in the third example, the time complexity would be O(n log n)? Thanks.
@Robin-fg6jv
@Robin-fg6jv 3 роки тому
If I run this code on leetcode It gives the wrong answer: Input: [3,2,4] Target: 6 The output I am getting: [1,1] Expected Output : [1,2]
@IbrahimAkar
@IbrahimAkar 6 років тому
at 0.75 speed you sound pretty hammered and it's hard to take a drunk programmer seriously... :-)
@seanallen
@seanallen 6 років тому
Hahaha, Ibrahim, that's hilarious. 😂 😂 😂
@mikumikuareka
@mikumikuareka 6 років тому
Wan't bruteforce solution give us false for 14?
@vaibhavmunjal
@vaibhavmunjal 4 роки тому
Hi Sean , Great tutorial however solution #3 (index pointer) will not work if the input is negative number array ex- ([-1,-2,-3,-4,-5] , -8). In this scenario the else if logic will have to be reversed . else if sumOfTwoItems < sumValue { highIndex -= 1 }else if sumOfTwoItems > sumValue { lowIndex += 1 } Please comment . Btw great videos:)
@seanallen
@seanallen 4 роки тому
Thank for pointing that out. Good catch!
@RicardoTrevino24
@RicardoTrevino24 2 роки тому
This works if theres only one solution for the sum
@RichOffKs
@RichOffKs 2 роки тому
this doesnt work for the two sum problem on leetcode
@bitj4ke
@bitj4ke 5 років тому
Hey sean! I just realized you can use ".contains" function in the tempArray in twoSumBinarySearch with compliment function. Hehe let numbers = [1, 3, 6, 7, 7, 12, 14] func twoSumBinarySearch(array: [Int], sum: Int) -> Bool { if array.count == 0 { return false } for i in 0..
@vrezhgulyan6834
@vrezhgulyan6834 5 років тому
Jco Bea doing contains just loops through the array. Which makes it N^2 like the first solution. The main point of twoSumBinarySearch is to get the time complexity down. Which the binary search part does.
@bitj4ke
@bitj4ke 5 років тому
Okay bro. Thanks
@dozirlik
@dozirlik 4 роки тому
I like your videos man. But one friendly advice; there are too many people here who are not native speakers. Please for them, speak a bit slower. Thanks for your videos.
@seanallen
@seanallen 4 роки тому
This is a very old video of mine. I've gotten a lot better 😀
@TheSaurabhp9
@TheSaurabhp9 3 роки тому
your logic will fail with [3,2,4] with sum 6.
@ponmanir6017
@ponmanir6017 Рік тому
It will fix 6 and 7 = 13 //Find all two elements pair in the array that add up to given sum func findPairGiverSum(numbers: [Int], sum: Int) { let sortedNumber = numbers.sorted() // print(sortedNumber) var left = 0 var right = sortedNumber.count - 1 while(left < right){ // print("index (\(left), \(right))") if(left != 0 && sortedNumber[left] == sortedNumber[left - 1]){ left = left + 1 continue } let pSum = sortedNumber[left] + sortedNumber[right] if(pSum == sum){ print("(\(sortedNumber[left]), \(sortedNumber[right]))") right = right - 1 left = left + 1 }else if(pSum > sum){ right = right - 1 }else{ left = left + 1 } } } //findPairGiverSum(numbers: [2,3,4,3,4,1,6,6,6,7,5,9,1,8,9], sum: 10) //findPairGiverSum(numbers: [0,1,2,4,4,7,5,3,4,1,8], sum: 8) findPairGiverSum(numbers: [1,3,6,7,7,12,14], sum: 13)
iOS Interview Questions and Answers with Sample Code
1:06:47
Richard Topchii - Swift and Apple Platforms
Переглядів 17 тис.
Binary Search - Swift Tutorial - iOS Interview Coding Challenge
7:42
I PUT MY ARMOR ON (Creeper) (PG Version)
00:19
Sam Green
Переглядів 3,2 млн
I Solved 1583 Leetcode Questions  Here's What I Learned
20:37
ThePrimeTime
Переглядів 452 тис.
Two Sum Problem | Leetcode | Swift | iOS coding interview
10:31
Harsivo Edu
Переглядів 3,3 тис.
Three sum problem in Swift #leetcode #swift #datastructuresandalgorithms
14:25
Swift Algorithms | Reverse String | LeetCode #344
7:35
AppStuff
Переглядів 1,2 тис.
iOS Dev Job Interview - Must Know Topics
2:27:40
Sean Allen
Переглядів 63 тис.
My Two Sum Swift 5 Solution | Leetcode
15:34
Kelvin Fok
Переглядів 512
Почему сканер ставят так не удобно?
0:47
Не шарю!
Переглядів 104 тис.
The Worst Product I've Ever Reviewed... For Now
25:04
Marques Brownlee
Переглядів 7 млн
Интел подвинься, ARM уже в ПК!
14:06
PRO Hi-Tech
Переглядів 137 тис.
Broken Flex Repair #technology #mobilerepair
0:55
ideal institute aligarh
Переглядів 15 млн
Subscribe for more!! #procreate #logoanimation #roblox
0:11
Animations by danny
Переглядів 3,2 млн