Engineering Interview Questions in Canada | Glassdoor

# Engineering Interview Questions in Canada

6,281

Engineering interview questions shared by candidates

## Top Interview Questions

Sort: RelevancePopular Date

### Software Engineer at Facebook was asked...

Nov 3, 2012
 implement sqrt without using math libray9 Answerse^((ln(x))/2)I think exp and ln still require a Math library. How about using Newton's method to find the root of f(x) = x^2 - a, where x is the solution (the sought square root) and where a is the number for which you want to find the square root?I would have implemented either Taylor or MacLaurin series, centered at an integer number that is closest to the number that you want to find the square root for, such that the square root of this integer is clean. So if you wanted to find the square root of 8.5, I would centre the series at 9 (sqrt(9) = 3), then compute the series at that point. I'd probably choose between 8 and 10 terms, as that is what is used in any scientific calculator.Show More ResponsesActually, to add to that, I wouldn't be able to include 8 - 10 terms, as that would rely on the square root operation itself.... so I'd have to rely on a linear approximation.This is the way to go. Fast inverse square root as used in Quake III. float Q_rsqrt( float number ) { long i; float x2, y; const float threehalfs = 1.5F; x2 = number * 0.5F; y = number; i = * ( long * ) &y; // evil floating point bit level hacking i = 0x5f3759df - ( i >> 1 ); // what the fuck? y = * ( float * ) &i; y = y * ( threehalfs - ( x2 * y * y ) ); // 1st iteration // y = y * ( threehalfs - ( x2 * y * y ) ); // 2nd iteration, this can be removed return y; }For detailed explanation of the algorithm, see http://en.wikipedia.org/wiki/Fast_inverse_square_rootI wouldn't know about this algorithm, but I can think of a (definitely slower than this one) bisection algorithm to find the root of x^2 = number.Often what they are looking for is a programming data structures oriented solution. Such as using binary search to find sq root etc.poop

### Software Engineer at Morgan Stanley was asked...

Feb 28, 2012
 A few questions on basic command-line syntax in Unix shells: 1. How would you log output and error messages from a command to a file? 2. How would you run the same command on every file in a directory? 3. How would you find the PID of a named process (say if you wanted to kill it)?5 Answers1. command >file 2>&1 2. cd dir; for i in *; do command; done 3. ps | grep processname or ps -C processname#3 I disagree, more like ps aux |awk '\$0 ~ /ProcessName/ && \$0 !~ /awk/ {print \$2}' If you want the PID#3 To find the PID: pgrep -xShow More Responses#3 - to find the PID Or simply use: pidofOpps!! there is typo; it should be: pidof

### Software Engineer, Google Fiber at Google was asked...

Sep 12, 2012
 Recently I attended the interview at Google and I was asked "You are given a sorted list of disjoint intervals and an interval, e.g. [(1, 5), (10, 15), (20, 25)] and (12, 27). Your task is to merge them into a sorted list of disjoint intervals: [(1, 5), (10, 27)]."9 Answershttp://www.mycareerstack.com/question/324/find-the-intervals-from-a-set-of-intervals-in-which-a-given-point-lies/You can use line-sweep algorithm for that.First you need to sort the pairs according to their starts. Then we compare each two first pair together if they have intersection or not. if the end of the first pair is greater or equal to beginning of the second pair then they have intersection and it is obviously : start = min(start_first pair, start_second pair), end= max(end_first pair, end_second pair); this new pair will be compared with the next pair.. till the end. if there is not an intersection we leave it az an interval. We can use queue to hold the pairsShow More Responsesgoogle_interview = ( [(1, 5), (10, 15), (20, 25) ], (12,27) ) just_insert = ( [(1, 5), (10, 15), (20, 25), (80,89)], (17, 18) ) join_case = ( [(1, 5), (10, 15), (20, 25), (80,89)], (12, 22) ) empty_case = ( [], (1,10) ) def merge(orig,anew): """ If the input items are sorted, and interval is a 2-tuple, create a new list of intervals, such that we join together any overlapping intervals into a single tuple describing the combined range of the two or three tuples that could collide when we merge another interval into a list""" newlist = [] if len(orig)==0: return [anew] n = 0 # get items that are before the join while norig[n]: middleitem = orig[n] if n=orig[n+1] and middleitem middleitem: # print "break",orig[n] break if orig[n] > middleitem: # print "extend" middleitem = orig[n] # print "skip",orig[n] n = n + 1 # now append remaining items newlist = newlist + [tuple(middleitem)] newlist += orig[n:] return newlist def test(tup): print 'merge( '+repr(tup)+', '+ repr(tup)+ ' )' print ' -> ', merge(tup, tup ) print ' ' print "Test begin" test( google_interview ) test( just_insert ) test( join_case ) test( empty_case ) print "Test end"n*lgn sorted by lower bound and gogogo scan once.JAVA CODE: import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; /** * Created by admin on 3/2/16. */ class Interval { int start; int end; Interval() {start = 0;end =0;} Interval(int s, int e) { start = s; end = e; } } public class Solution { public List insert(List intervals, Interval newInterval) { ArrayList result = new ArrayList(); intervals.add(newInterval); return merge(intervals); } public List merge(List intervals) { ArrayList result = new ArrayList(); if (intervals == null || intervals.size() == 0) { return result; } Collections.sort(intervals, new Comparator() { public int compare(Interval a, Interval b) { return a.start - b.start; } }); for (int i=0;i= intervals.get(i+1).start) { current.end = Math.max(current.end, intervals.get(i+1).end); i++; } result.add(current); } return result; } } Time Complexity: nlgn + n = O(nlgn)Here is an implementation of the line sweep algorithm. https://gist.github.com/korayucar/e047749845d93bf5ad488ac9e42ce048int[] mergeDisjointIntervals(int[] intervals, int[] range){ ArrayList result = new ArrayList(); for(int i=0;irange&&high is inside return 0; } else if(lowrange&&high overlaps tail return -1; } else if(low>range&&lowrange){ // 1 -> overlaps head return 1; } else{ // 2 -> does not overlap return 2; } }int[] mergeDisjointIntervals(int[] intervals, int[] range){ ArrayList result = new ArrayList(); for(int i=0;irange&&high is inside return 0; } else if(lowrange&&high overlaps tail return -1; } else if(low>range&&lowrange){ // 1 -> overlaps head return 1; } else{ // 2 -> does not overlap return 2; } }

### Software Engineer at McKesson was asked...

Jun 6, 2011
 Given an array of 1001 elements, consists all numbers from 1-1000. Only one number is repeated. Write a function that returns the repeated number.4 AnswersHonestly, there's two possible answers you could give, depending on whether you want space efficiency or time efficiency (assuming that the array is *not* sorted). For time efficiency, ironically, the brute-force method is fastest. You make a counter array of size 1000, all indices initialized to 0, which takes O(n) time. Then, you run the following: for (int i = 0; i 1) // pre-increment the counter, then check if we've counted 2. return array[i]; } Overall, the time-efficient algorithm takes O(2n) = O(n) time, but takes O(n) additional space. The space-efficient algorithm just quick- or heap-sorts the array in place, then runs a binary search, comparing the value to the index. If the value == array[mid], search higher; otherwise search lower. Leave the loop once (high - low == 1), and then return that value. This will take O(n log n) time due to the sorting process, but only take up O(1) extra space. Of course, if the array comes pre-sorted, you would trivially just run binary search as described above.hey, i have one quick solution, create a function that will take up an initial value and end value, that will add up all numbers between them. create another function to add all elements in the array. call the first function, with value (1, 1000) and call the second function. compare the value. whatever the difference is, that is the repeated number.I think Lucas has the right idea with his counter but there's one flaw to his posted solution. His check should be (if ++counter[array[i]-1] > 1). If you do indeed declare the count tracker as int counter (which is the values counter to counter), doing counter[array[i]] would cause an out of bounds problem for array[i] = 1000. A third alternative, along the lines of dsutandi's idea, is to recognize (if you took a number series class) that the sum of 1 to n = n *(n+1) / 2. So you can loop through the incoming array, sum up all the values, then subtract that sum against the afforementioned value (inserting 1000 for n) and that would be your duplicate. For example: int sum = 0; for (int i = 0; i < 1001; i++){ sum += array[i]; } return sum - (1000*1001)/2;Show More Responseshere is my take : use following formula to get ideal sum : ideal_sum= n*(n+1)/2 real_sum=summation_of_all numbers in array repeated number = abs(real_sum-ideal_sum)

### Senior Software Engineer at Amazon was asked...

Aug 16, 2012
 Write a function that divides one number by another, without using the division operator, and make it better than O(n).7 AnswersThis can be done in a recursive function, the following code is in Python. # get result of a/b without using a "divide" operator def div(a,b): if a < b: return 0 else: return div(a-b, b)+1 This is how human being do the division naturally, however, the running time of this is O(n/m), where n is the size of a, and m is the size of b, which means, O(n/m) is guaranteed to be less than O(n), when m is larger than 1. -MaximThe answer above is still O(n). We can use binary search and find the answer in the interval [1,a] and use multiplication operator.Totally agree with Vasil. Other option: Long Division Algorithm. O(log n) anyway.Show More Responseswhy not just a * b^(-1) :-)// Write a function that divides one number by another, without using the division operator, // Assume that x%y = 0 // O(log n) (function() { 'use strict'; var divide = function(x, y) { var xLength = (x + '').length; var i = 0; var result = 0; var xAry = ('' + x).split(); var xStart = ''; for (i = 1; i = y) { xStart -= y; result = parseInt(result, 10) + 1; } } } return result; }; console.log(divide(1000, 4)); })();Use logarithms? O(1) log(x/y) = log(x) - log(y) = log(answer) answer = 10 ^ log(answer)Convert the number to divide into the base of the number that you are dividing with and then shift the 'bits' to the right by 1 then convert back to decimal

### Associate Software Engineer at Electronic Arts was asked...

Apr 9, 2009
 Given 100 white marbles and 100 black marbles and two jaws. Put these marbles in the two jars in a way that would maximize the chance of retrieving a white marble from any given jaw.4 Answersdivide black marbles into the two jars first. then divide the white marbles on top of that in the two jars.Really that is what you would answer? What if they stirred the jars around after you distributed the marbles? Personally I think a better answer is to put 1 white marble in the first far and 99 white marbles and 100 black marbles in the second jar. If you choose the jar at random you now have a 74.87% chance of getting a white marble, regardless of the marbles position in the jar.qq is right, that is the optimum combination.Show More Responses2 colours, 2 jars. White in one, black in the other

### Multimedia Driver Software Engineering at Qualcomm was asked...

Jun 27, 2012
 Explain a situation where a deadlock would occur.3 AnswersTwo processes each holding a resource tries to access the other's resource.Or you could forget to unlock.There are 4 conditions from Coffman's: A deadlock situation can arise if all of the following conditions hold simultaneously in a system: 1. Mutual Exclusion: At least two resource must be non-shareable. Only one process can use the resource at any given instant of time. 2. Hold and Wait or Resource Holding: A process is currently holding at least one resource and requesting additional resources which are being held by other processes. 3. No Preemption: The operating system must not de-allocate resources once they have been allocated; they must be released by the holding process voluntarily. 4. Circular Wait: A process must be waiting for a resource which is being held by another process, which in turn is waiting for the first process to release the resource. In general, there is a set of waiting processes, P = {P1, P2, ..., PN}, such that P1 is waiting for a resource held by P2, P2 is waiting for a resource held by P3 and so on until PN is waiting for a resource held by P1.

### Senior Software Engineer at TripAdvisor was asked...

Dec 2, 2013
 After asking the details of my current role, he only gave me a simple coding question. Write a function using C++ or Java that is passed an integer and it returns the number of bits set to 1. Is there a way to improve your solution and make it faster and more efficient?3 AnswersThere are obviously multiple solutions: Solution 1: Set sum = 0 Find the remainder by dividing by 2. Divide by 2 for the next iteration. Solution 2--much better. Set sum = 0 Start loop Set mask = 1 sum += mask & number Loop return sumThere is another way, that is explained here: http://en.wikipedia.org/wiki/Hamming_weigh (with just 24 operation and without any cycle you can find the number of bit set to 1)An example in Java with 10000 results in answer 5 int number = 10000; int numberOfBitsSet = 0; for (int i = 1; i <= number;) { int result = (i & number); if (result != 0) { numberOfBitsSet++; } i = i << 1; } System.out.println(numberOfBitsSet);

### Quality Assurance Engineer at Sandvine was asked...

Sep 26, 2012
 You have 9 marbles which are all the same weight, except for one which is slightly heavier than the others. You also have an old?style balance, which allows you to weigh two piles of marbles to see which one is heavier (or if they are of equal weight). What is the fewest number of weighings that you can make which will tell you which marble is the heavier one ?4 AnswersThe fewest number of weightings is 2. Divide 9 marbles in 3 groups of 3. Weight #1A: 3 in each side. If balance, Weigtht #2A:1 in each side. If balance then the non-weighting is the one, otherwise the heavy side is the one. Weight #1B: 3 in each side. If not balance, then the heavy one has a defect one Weight #2B: Same as in #2AI disagree on the above, you can divide 9 marbles into three groups of: 4, 4 and 1. Then, weigh 4 and 4 together. If the balance is "balanced", it means the one left aside is the heaviest marble. So, you could accomplish the task in just one weighing, but the chances of that are pretty low. However, that is what the question asks, in my opinion.As little as one, up to three. 4 and 4 on each side. If it is balanced, you found the heaviest one. If unbalanced, take the heavier group and divide it into 2 and 2, then 1 and 1.Show More Responsesin 2 weightings you will definitely get an answer. getting answer in one weighing is not always a possibility

### Junior Mechanical Engineer at Jacobs was asked...

Aug 9, 2012
 What will happen to the boiling point of a liquid under vacuum? Will it rise or decrease?3 Answersit will rise because the vapour pressure becomes zeroit should decrease because of very little pressure. Water should boil more easily up in the mountains due to altitude.It should decrease, because according to the PVT relationship (e.g. PV=nRT), if pressure decreased, the boiling temperature should also be decreased.
110 of 6,281 Interview Questions