We pay for user submitted tutorials and articles that we publish. Anyone can send in a contributionLearn More
The eleventh post of the series of programming job interview challenge is out. 75 readers provided answers to job interview challenge #10 and most of them had the correct solution. The correct answer as Alex, the first one to provide a detailed solution, wrote:
Here’s an O(N) solution:
Have one variable that stores the sum of all the values. Iterate through the list to add all numbers to the variable, which for simplicity I will call “listSum”.
Now, take the theoretical sum of all numbers between 1…n+1: This can be computed in O(1), as the sum of numbers up to N is n(n+1)/2: So for numbers up to n+1, it’d be (n+1)(n+2)/2 (for instance, if the array is of size 9, we’d do 10*(11)/2, or a theoretical sum of 55). Call this sum “allSum”.
The missing number will be the result of computing “allSum - listSum”.
O(N)complexity, with only two tracking variables.
Those are the bloggers who wrote their solutions in their blogs:
The commentators who got it right are:
David Poll, Michael Mrozek, Mark R, OJ, Edward Shen, ken, Thaison Lam, Shailendra, Simon Ask Ulsnes, pavan kumar, Kirill Sorokin, Florian K., Stephen Burton, Poul Foged Nielsen, Micha? Bendowski, Ivan Grasso, Marius Klimantavicius, thebol, steve_barham, Shams Mahmood, Samuel Williams, Sebastian U, Tim C, Hegi, NathanLaan, Guy Gervais, anton, Mori, Stephen Goldbaum, kranthi, ZagNut, Angelo vd Sijpt, krzysztof kreja, AS, Luke, Richard Vasquez, Christof Jans, Pavel, Randoom, Luca Giurina, Josh Bjornson, leppie, Kris Warkentin, cleg, grigri, Austinian, John, Martin, Jesus DeLaTorre, Hugh Brown, Michael, Tim Kington, Chris Jobson, JJ (it should be ((n+1)*(n+2)/2)), st0le, Guido Domenici, Michael Dikman and Frank D.
This Weeks Question:
Given a list of n integers and another integer called m, determine (true / false) if there exist 2 numbers in that list which sum up to m.
Example: 2,6,4,9,1,12,7 and m=14 -> 2 and 12 sum up to 14, so the answer is true.
Provide the best algorithm in both manners: performance and memory to solve this puzzle. Don’t forget to mention the complexity of your solution!
You can get updates by RSS so you catch up with the next posts in this series and get the correct answer to today’s question. As always you may post the solution in your blog or comment. Comments will be approved next week.
Tags :Arraychallengejob interviewListquestionSum
Copyright © 2012 Dev102.com
Breeze : Designed by Amit Raz and Nitzan Kupererd