# Software Development Engineer Interview Questions

Software development engineer interview questions shared by candidates

## Top Interview Questions

Asked to implement a function that takes an integer and returns whether or not the number had an odd or even number of 1 bits. 6 AnswersIt started out with an ambiguous set-up so the first thing that needed to be figured out was what kind of number to be taken in. How many bits this value was. I was told to assume it was 32 bits. I mentioned that the number may be in 2's complement, I was told to only expect unsigned integers. The solution is pretty straight forward, it only requires a for loop that counts from 0 to 31 and checks whether the integer masked with 1 is equal to 1. If it is, add one to the accumulator and shift a bit to the right. Then I was told to extend this function to work for an n bit integer. With some hints I figured out that log base 2 of a number gave you the maximum number of bits it would take to store that number so simply replace the loop that went from 0 to 31 with a loop that goes from 0 to log_2(n). If the task is only for positive numbers, then my solution would be: bool is_odd_set_bits(unsigned number) { bool result = false; int n = number; do { result |= ((n % 2) == 1); n /= 2; } while ((n / 2) != 0); return result; } Show More Responses mod and div operators are good, but you could set yourself apart by using a more efficient algorithm. In terms of big O, it will be the same, but it will have a higher throughput since the operations are slightly faster. > bool is_odd_set_bits(unsigned number) { bool result = false; int n = number; while(n != 0) { result |= ((n & 0x01) == 1); n >> 1; } return result; } masking is faster than a mod operator, and bit shifting is faster than divisions i was trying this in java and found kinda small bug... so we should return false if the number is 3 which is 0000000011. I guess changing the line to: result ^= ((n & 0x01) == 1); will do the job... PC, your solution is incorrect. It will always return true if the number has at least one set bit. |

Pancakes, size varies, and are put in a stack with random order. You have one operation called Flip(int[] pancakes, int k) to flip all pancakes from the top one to kth pancake, write a sort(int[] pancakes]) method 6 AnswersYou can implement quicksort since swapping two items (i and j) can be done in three steps using the 1st item as a temporary position. Never mind the previous comment, misread the description of the Flip operation Could you make a more clear description the operation of Flip functon? Thanks! Show More Responses For example, if pancakes are {1,2,4,3}, (number means pancake sizes), and if we flip(pancakes, 2), then the first two pancakes are flipped and result will be {2,1,4,3} Well, selection sort would work, but it's slow. Find position j of the minimum between [i,n-1], starting with i = 0. If j != i, then use Flip(pancakes,n-j) to get it to the top, then flip to its subsequent minimum position i, therefore Flip(pancakes,n-i). Keep repeating until increasing i reaches n. Hmm, if indirect sorting is allowed (via pointers in extra space), then one could use quicksort, and place into target positions by flipping. But if that flipping is the only operation available, then even finding the minimum value AND it's current position for the selection sort above gets nontrivial (but doable). |

You are given an array with n positive integers where all values in the array are repeated except for one. Return the one that is not repeated. 8 Answerspublic static int notRepeated(int[] given) { Map m = new HashMap(); for(i=0; i < given.length; i++) { if(m.get(given[i])) { m.put(given[i], 2); } else m.put(given[i], 1); for(x:m) { if(x == 1) return x; } } } If you have an array of positive integers with only ONE non repeated integer, the easiest thing is just xor them all. Whatever you return will be the answer. Perl answer below sub findNotRepeated{ my ($arr) = @_; if(@$arr==0) { return - 1; } my $val = 0; foreach(@$arr) { $val ^= $_; } return($val); } sub findMissingElement{ my ($arr,$arr2) = @_; if(@$arr==0 || @$arr2 == 0 ) { print " arr2=" .@$arr2 . "X\n";; return - 1; } my $val = 0; foreach((@$arr , @$arr2)) { $val ^= $_; } return($val); } first sort the array.n then 1)for i=1 to n { if ( element [i] !=element [i+1] ) { cout< Show More Responses This answer is in-place with O(n) complexity. A slight improvement over the space complexity of the Hash Map answer. public int returnNonRepeat(int[] input) { if(input.length < 3) return -1; else { int repeat = null; if(input[0] == input[1]) repeat = input[0]; else if(input[0] == input[2]) return input[1]; else return input[0]; for(int i = 2; i Cant use XOR as it fails when any element repeats odd number of times..... Can use hash map with O(n) time and O(n) space only 2 possible solutions 1.) using sorting 2.) using additional space. which will be less than o(n) sub find_odd { my @a = @{$_[0]}; my ($i, $n); $n = $a[0]; for $i (1 .. $#a) { $n = $n ^ $a[$i]; } printf("number is %s\n", $n); } Use xor |

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

Given a binary tree with the usual left and right pointers on each node, and additionally a parent pointer, make an algorithm to discover the closest ancestor to 2 nodes on the tree. 7 AnswersTime complexity is : O(max height of binary tree) public void findCommonAncestor(Node current,int a,int b){ if(current.getKey() a && current.getKey()>b){ findCommonAncestor(current.getLeft(), a, b); }else{ System.out.println(" least common ancestor is "+current.getKey()); } } analog76, your solution is not complete. @clusterfudge, what do you mean by incomplete? Can you be more precise?. Common ancestor - first encounter of node value between a and b. Otherwise either you go left or right node. Show More Responses As far as I concern it is a binary tree not binary SEARCH tree. thanks @naipton. 1) Find matching node for the first value in the tree. If the node found create a set contains all its parents till the root. 2) Use postorder traversal for recording all the ancestor. 3) P1 is parent, P2 is grand parent and P3 is ggparent and continue till root. V1={P1,P2,P3,P4,....root} 4) Similary find all the parent of second value V2={P1,P2,P3,.root}. 5) traverse both set and first matching element in both sets is lowest common ancestor. Find height of node 1 as h1 and height of node 2 as h2 by travelling to the root. Time O(2 lg N). If h1 > h2, then move node1 by h1 - h2 and vice versa. THen, use two pointers to move one parent at a time until parent nodes are same. Complexity - O( 3 lg N) Assuming each node has a unique ID (its memory address, for example), you can solve this in O( 2 lg N ) where N is the number of nodes in the tree. findCommonAncestor(Node x, Node y): 1. Initialize a hashmap, call it `parentsMap`. 2. Starting from x, visit all its parents up to and including the tree root, and for each parent `p`, set parentsMap[p.id] = true 3. Starting from y, begin to visit its parents and for each parent `p`, check parentsMap[p.id]. If true, return p.id. Else, continue visiting parents until `p` is null, at which point we return null. |

Given the head pointers to two linked lists of unknown length, find the node of intersection if they do intersect. 5 AnswersSuppose that the pointers are head1 and head2. Move head1 and increment a count1 till head1 reaches null. Move head2 and increment count2 till head2 reaches null. If head1 > head2 or head2 > head1, move the respective pointer to such a position in the linked list so that the length of the linked lists from there are equal. Then, start checking if both pointers point to the same node and incrementing both until that condition is met. If they do point to the same node at some point, that is the node of intersection. Otherwise, there is no intersection. I don't understand the interview candidate's solution. I don't think I will work properly. If the last 3rd node of List A and last node of List B intersects, this algorithm will not find the answer. My solutions: Suppose length of List A is m, length of List B is n, If space cost is more of a concern, do a O(n^2) search because it will cost constant space to find the intersect. (nested for loop) If time is more of a concern, 1. traverse through both list to figure out the length. Identify the smaller list(suppose it's list A). cost O(m+n). 2. traverse List A, build a binary search tree with the address of pointers of the list as payload O(m log(m)). 3. Traverse through list B and search the tree for each element in list B. if found, then it's the intersection.O(n log(m)). the general complexity is O(m+n+(m+n)log(m)) = O((m+n)log(m)). If we don't suppose A is the shorter, then the time complexity will be O((m+n)log(min(m,n))) pblm can be solved by making a circular linked list. Start with head1 and traverse thru the list and modify the lastnode.nxtptr -> head2 Now start with head2 and traverse. If you reach the head2 again then the list do intersect. Show More Responses Vijay has the best solution with linear time. Vijay's solution works great for finding out whether they intersect, but the question asks for finding the node of intersection. I think William's solution will work best for finding the node of intersection. The obvious one is an O(n^2) solution by traversing the first list with the nodes of the second list and doing a comparison. |

Write a program to find the square root of a double. 5 Answersuse binary search to narrow down the search space and keep multiplying the answer in each iteration by itself to check if it is equal to the double given. If it is lesser, move up the lower bound, else move down the upper bound. One easy to remember method that also has much better performance than binary searching for the result is the Babylonian Method. It is similar to Newton's method for finding derivatives. See the algorithm here: http://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method Also, combining this algorithm with the Rough Estimation also described on that page will compute the squareroot of most double numbers in less than 10 iterations. Is it too obvious to ask if you can do double^.5 ? Show More Responses I would respond by showing that I am thinking about the problem as it is defined, not by making assumtions about what is implied. This can result in product that does not meet the requirement specifications, which can be very costly: "What do you mean, a program or a function? A program would require input and output mechanisms to make it meaningful, but makes it pretty usesless as a job assessment question. A function makes more sense in this context. " There's a variation of the problem which says "find the square root of a double up to the third decimal digit". I'd just multiply the original number by 10^position (meaning, for 3 digit accuracy it'd be 10^3) and ran a simple loop to find the closest integer. As soon as i*i > 10^position * number, you can return (i-1)/10^position. It's hella slow and unimaginative, but it works and you won't sound like you knew this problem ahead of time (if you come up with a Babylonian solution). |

Given two very large binary trees T1, with millions of nodes, and T2, with hun- dreds of nodes, create an algorithm to decide if T2 is a subtree of T1. 6 AnswersPerhaps I'm missing something here but I think this could be a trivial problem. You could simply do a binary search on T1 all the while looking for the root node of T2. If you find it, then T2 is a sub-tree of T1. As binary search is O(log n) this would be quite efficient too. Ja, you got the first part right, but the second part would be to verify that T2 is exactly the same as T1 -- so time would be O(log n + m) where m is the number of nodes in T2 What Ja means is that you do not compare the node values, but the nodes themselves. In fact, the question needs to be refined, are we looking for identical trees (node values and the tree structures) or just references (addresses)? Show More Responses This is a very hard problem. Look up subtree matching and you'll see what this is about. The first couple of posters seem to be confusing binary trees with BST. The first posters are indeed wrong. Binary trees are in no particular order (unlike binary SEARCH trees). |

Make a program that writes a Binary Search Tree to a file. Now create a program that reads those files and recreates a Binary Search Tree. 5 AnswersThe BST should be read in > and save each values into a file. Its important that the tree is parsed in preorder- or regenerating tree will give a completely different tree. The solution by Jeevan is perfect. Inorder/Postorder - it is not possible to reconstruct the tree. calling insert(node), for every node read from file will re-create the original tree. Here's a code to do it: __________________________________________ #include #include "math.h" using namespace std; class BinaryTree { public: BinaryTree::BinaryTree(int v) : value(v) {left = NULL; right = NULL;}; int value; BinaryTree *left; BinaryTree *right; }; void dfs(BinaryTree *root, FILE *fp) { fprintf(fp, "%d|", root->value); if(root->left == NULL) fprintf(fp, "N|"); else dfs(root->left, fp); if(root->right == NULL) fprintf(fp, "N|"); else dfs(root->right, fp); } void serializeTree(BinaryTree *root) { FILE *fp = fopen("tree_serialized.txt", "w"); dfs(root, fp); fclose(fp); } BinaryTree* dfs_r(FILE *fp) { fpos_t position; fgetpos (fp, &position); char isN; fscanf(fp, "%c|", &isN); if(isN != 'N') { fsetpos(fp, &position); // integer, this node exists int value; fscanf(fp, "%d|", &value); BinaryTree *newroot = new BinaryTree(value); newroot->left = dfs_r(fp); newroot->right = dfs_r(fp); return newroot; } else { // no children // NULL already set by constructor return NULL; } } BinaryTree *deSerializeTree() { FILE *fp = fopen("tree_serialized.txt", "r"); BinaryTree *newT = dfs_r(fp); fclose(fp); return newT; } int main() { // Construct a binary tree BinaryTree root(4); BinaryTree n2(2); BinaryTree n6(6); BinaryTree n1(1); BinaryTree n3(3); root.left = &n2; root.right = &n6; n2.left = &n1; n2.right = &n3; // Serialize and de-serialize it serializeTree(&root); BinaryTree *newRoot = deSerializeTree(); return 0; } Show More Responses Preorder and postOrder are both correct. /*Java Code for Question - preOrder traversal is the way to go!*/ import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.LinkedList; import java.util.List; public class SimpleBinarySearchTree> implements Serializable { /** * */ private static final long serialVersionUID = 1L; Node root; private class Node implements Serializable{ T data; Node left; Node right; public Node(T data){ this.data=data; left=null; right=null; } } public SimpleBinarySearchTree(){ } public void add(T data){ root=addhelp(root,data); } private Node addhelp(Node node,T data){ if(node == null){ node=new Node(data); return node; } else if(node.data.compareTo(data) > 0){ node.left=addhelp(node.left,data); } else{ node.right= addhelp(node.right,data); } return node; } public void printPreOrder(){ printhelp(root); } private void printhelp(Node node){ if (node !=null){ System.out.println(node.data); printhelp(node.left); printhelp(node.right); } } public List preOrder() { List list = new LinkedList(); return preOrder(list,root); } /** * Helper method to list out items in BST in preOrder traversal * @param list the list of the items so far in preOrder traversal * @param curr the curr node being checked * @return list of items in BST in preOrder traversal */ private List preOrder(List list,Node curr){ if (curr != null){ list.add(curr.data); preOrder(list,curr.left); preOrder(list,curr.right); } return list; } public static void main(String args[]){ SimpleBinarySearchTree tree= new SimpleBinarySearchTree(); tree.add(6); tree.add(2); tree.add(8); tree.add(1); tree.add(3); tree.add(5); tree.add(9); SimpleBinarySearchTree tree2=null; try{ FileOutputStream fout = new FileOutputStream("/Users/Ore/Desktop/tree.ser"); ObjectOutputStream oos = new ObjectOutputStream(fout); oos.writeObject(tree); oos.close(); System.out.println("Done"); }catch(Exception ex){ ex.printStackTrace(); } try{ FileInputStream fin = new FileInputStream("/Users/Ore/Desktop/tree.ser"); ObjectInputStream ois = new ObjectInputStream(fin); tree2 = (SimpleBinarySearchTree) ois.readObject(); }catch(Exception ex){ ex.printStackTrace(); } List list = new LinkedList(); list=tree2.preOrder(); SimpleBinarySearchTree tree3= new SimpleBinarySearchTree(); for(int i=0;i |

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

How would you implement a top 3 word count in a text editor application? 7 AnswersWhat is the answer to this question? Would one just parse through the whole document and hash each word occurrence, with the key as the word itself, and the value as the number of occurrence? Can we use a BST to store word and length values? And then do a pre-order traversal? Another approach would be to sort in place in n log n. Then scan the sorted list of words and maintain a count of top three. Show More Responses max-Heap This can be done using Linked Hash. Each element of Hash has two pointer. Min pointing to element which comes next in the seq with count. When we add new word, either it will be added to hash or updated its count. If count is updated then we need to correct the Min and Max pointer accordingly. Also we need to corecct obj.Min.Max pointer and obj.Max.Min pointer accordingly. Keep track of the Max and Min element of the heap elements. Other optimization can be done to improve the worst case scenario like storing head pointer of list of words which has same count. Using Heap and Hash will solve the problem optimally. Keep a hash of word as key and count as value. And keep a Min heap of 3 elements. Build the heap with first 3 elements. For every new element increase the count in HashMap. Check if the element is in the heap, then update the count and reheapify. Else check if the element count is greater than top element of Min heap, if yes then replace that element with our new element and reheapify. Else don''t touch our heap and keep counting. This will make sure the heap will always have top 3 elements. Complexity: O(n) as heapify is constant always. MaxHeap/priorityQueue whose key is the word itself and the priority is the word count. When you need the top three words, just pop the heap three times 3*O(logN). |

Describe and code an algorithm that returns the first duplicate character in a string? 11 AnswersSimple Python example. Not sure it's most efficient. def findDup(str): match=[] i=1 while (i first clarify if it is ASCII or UNICODE string For ASCII, create BOOL checkArray [128] = {false}; walk the string and update the index of checkArray based of the character. for (int index=0;index< strlen(str); index++) { if (checkArray[str[index]] == true) { printf (str[index]); return; } else { checkArray[str[index]] = true; } } public class FirstDupCharacter { public static void main(String[] args) { System.out.println(findDupCharacter("abcdefghiaklmno")); } private static Character findDupCharacter(final String input) { final Set set = new HashSet(); Character dup = null; for (int i = 0; i < input.length(); i++) { if (set.contains(input.charAt(i))) { dup = input.charAt(i); break; } else { set.add(input.charAt(i)); } } return dup; } } Show More Responses String samp = "Testing"; samp = samp.toLowerCase(); char chararr[] = samp.toCharArray(); int size = chararr.length; char repeat = ' '; for (int i=0;i for (int i=0;i public static in findDuplicateChar(String s) { if (s == null) return -1; char[] characters = s.toCharArray(); Map charsMap = HashMap(); for ( int index = 0; index < characters.length; index++ ) { // insert the character into the map. // returns null for a new entry // returns the index if it previously if it existed Integer initialOccurence = charsMap.put(characters[index], index); if ( initialOccurence != null) { return initialOccurance; } //there where no characters that where duplicates return -1; } } Another python solution: def findFirstNonRepeatedCharInOneIteration(str1): for i,j in enumerate(str1): if j in str1[:i] or j in str1[i+1:]: print "First non-repeated character is "+ j break str1 = "abcdefglhjkkjokylf" findFirstNonRepeatedCharInOneIteration(str1) function getFirstDuplicateCharacter(str) { const seen = new Set(); for (const char of str) { if (seen.has(char)) return char; seen.add(char); } } import java.io.*; import java.util.*; /* * code an algorithm that returns the first duplicate character in a string? */ class Solution { public static void main(String[] args) { String input = ""; int j = removeduplicate(input); if(j == input.length()){ System.out.println("String has unique characters" ); } else{ System.out.println("duplicate character is "+input.charAt(j)); } } public static int removeduplicate(String input){ Set set = new HashSet(); boolean flag = false; int i =0; for(; i import java.io.*; import java.util.*; class Solution { public static void main(String[] args) { String input = ""; int j = removeduplicate(input); if(j == input.length()){ System.out.println("String has unique characters" ); } else{ System.out.println("duplicate character is "+input.charAt(j)); } } public static int removeduplicate(String input){ Set set = new HashSet(); boolean flag = false; int i =0; for(; i public static int removeduplicate(String input){ Set set = new HashSet(); boolean flag = false; int i =0; for(; i |

**21**–

**30**of

**4,124**Interview Questions

## See Interview Questions for Similar Jobs

- Software Engineer
- Software Development Engineer
- Senior Software Engineer
- Software Developer
- Software Development Engineer I
- Software Engineer In Test
- QA Engineer
- Intern
- Software Development Engineer In Test (SDET)
- Quality Assurance Engineer
- Software Test Engineer
- Test Engineer
- Software QA Engineer
- Software Engineer Intern
- Software Development Engineer II
- Senior Software Development Engineer
- Software Engineering
- Java Developer
- Business Analyst