Java Interview Questions
interview questions shared by candidates
Java Interview Questions
IOS Developer at Facebook was asked...
Verify that a binary search tree is indeed a binary search tree. 15 Answerspublic static boolean isBST(Node n) { if (null == n) return true; return (null != isBSTI(n)); } public static ArrayList isBSTI(Node n) { int min = n.val; int max = n.val; if (left != null) { ArrayList leftR = isBST(n.left); if (leftR.get(1) > val) return null; min = leftR.get(0); } if (right != null) { ArrayList rightR = isBST(n.right); if (rightR.get(0) (Arrays.asList(new Integer[] { min, max })); } The idea is if we traverse binary search tree "in-order", output of number is in ascending orders. So here it goes. Not checked for syntax errors, but should work. BOOL Inorder(NODE *node) { static NODE *prev = NULL; // Do need to initialize this as statics are zeroed memory. if (node == NULL) { return true; } if (false == Inorder(node->left)) { return false; } if (prev && node->num num) { return false; } prev = node; return Inorder(node->right); } Principle. Every node in a binary tree must have left node value parent node Bool checknode(node) { If node.left then { If node.left.value > node.value then Return false If checknode(node.left) == false then Return false } If node.right then { If node.right.value < node.value then Return false If checknode(node.right) == false then Return false } Return true } Show More Responses Very simple and efficient way: public static boolean isBinaryTree(TreeNode root) { if(root == null) return true; if(!((root.rightSon == null || root.value root.leftSon.value))) return false; if(!(root.rightSon == null || isBinaryTree(root.rightSon))) return false; if(!(root.leftSon == null || isBinaryTree(root.leftSon))) return false; return true; } This is the class TreeNode in java: class TreeNode { public int value; public TreeNode rightSon; public TreeNode leftSon; public TreeNode(int value, TreeNode rightSon, TreeNode leftSon) { this.value = value; this.rightSon = rightSon; this.leftSon = leftSon; } }; you can try with this example: //Decide if is a binary tree TreeNode tree = new TreeNode(15,new TreeNode(18,new TreeNode(22,new TreeNode(30,null,null),new TreeNode(21,null,null)),new TreeNode(16,null,null)), new TreeNode(10,new TreeNode(12,new TreeNode(13,null,null),new TreeNode(11,null,null)),new TreeNode(8,null,null))); boolean res = isBinaryTree(tree); System.out.println("Result: " + res); //EXAMPLE: // 15 // 10 18 // 8 12 16 22 // 11 13 21 30 // private static boolean isReallyBST(Node root) { return followsBST(root.left, root.value, true) && followsBST(root.right, root.value, false); } private static boolean followsBST(Node node, Integer parent, boolean isLeft) { if (node == null) { return true; } boolean follows = isLeft ? node.value = parent; return follows && followsBST(node.left, node.value, true) && followsBST(node.right, node.value, false); } A simpler approach is to do an inorder traversal keeping track of last seen element. If it is always increasing then we can prove that tree is BST. class TreeNode { var value: Int? var leftChild: TreeNode? var rightChild: TreeNode? } func isBST(node: TreeNode, min: Int, max: Int) -> Bool { print("value: " + String(node.value!)) print("min: " + String(min)) print("max: " + String(max)) if node.value! max { return false } if let leftChild = node.leftChild { if isBST(leftChild, min: min, max: node.value!) == false { return false } } if let rightChild = node.rightChild { if isBST(rightChild, min: node.value!, max: max) == false { return false } } return true } // Creating BST let minValue = Int.min let maxValue = Int.max let node2 = TreeNode() node2.value = 2 node2.leftChild = nil node2.rightChild = nil let node7 = TreeNode() node7.value = 7 node7.leftChild = nil node7.rightChild = nil let node11 = TreeNode() node11.value = 11 node11.leftChild = nil node11.rightChild = nil let node15 = TreeNode() node15.value = 15 node15.leftChild = nil node15.rightChild = nil let node5 = TreeNode() node5.value = 5 node5.leftChild = node2 node5.rightChild = node7 let node13 = TreeNode() node13.value = 13 node13.leftChild = node11 node13.rightChild = node15 let node10 = TreeNode() node10.value = 10 node10.leftChild = node5 node10.rightChild = node13 if isBST(node10, min: minValue, max: maxValue) == true { print("Tree is BST.") }else { print("Tree is not BST.") } class TreeNode { var value: Int? var leftChild: TreeNode? var rightChild: TreeNode? } func isBST(node: TreeNode, min: Int, max: Int) -> Bool { print("value: " + String(node.value!)) print("min: " + String(min)) print("max: " + String(max)) if node.value! max { return false } if let leftChild = node.leftChild { if isBST(leftChild, min: min, max: node.value!) == false { return false } } if let rightChild = node.rightChild { if isBST(rightChild, min: node.value!, max: max) == false { return false } } return true } // Creating BST let minValue = Int.min let maxValue = Int.max let node2 = TreeNode() node2.value = 2 node2.leftChild = nil node2.rightChild = nil let node7 = TreeNode() node7.value = 7 node7.leftChild = nil node7.rightChild = nil let node11 = TreeNode() node11.value = 11 node11.leftChild = nil node11.rightChild = nil let node15 = TreeNode() node15.value = 15 node15.leftChild = nil node15.rightChild = nil let node5 = TreeNode() node5.value = 5 node5.leftChild = node2 node5.rightChild = node7 let node13 = TreeNode() node13.value = 13 node13.leftChild = node11 node13.rightChild = node15 let node10 = TreeNode() node10.value = 10 node10.leftChild = node5 node10.rightChild = node13 if isBST(node10, min: minValue, max: maxValue) == true { print("Tree is BST.") }else { print("Tree is not BST.") } boolean isBST(Node root) { if (root == null) return true; if ((root.left != null && root.data root.right.data)) { return false; } return isBST(root.left) && isBST(root.right); } func isIndeeBST(root: Node?) -> Bool { if root == nil { return true } if root.left != nil && root.right != nil { if root.left?.value > root.right?.value { return false } } if root.left != nil { if root.left?.value > root.value { return false } } if root.right != nil { if root.right?.value < root.value { return false } } return isIndeeBST(root.left) & isIndeeBST(root.right) } 4 2 6 => YES 1 3 5 7 4 2 6 . => NO 1 3 3 7 class TreeNode { var data: Int var left: TreeNode? var right: TreeNode? public init(_ val: Int) { self.val = val self.left = nil self.right = nil } } class Solution { func isValidBST(_ root: TreeNode?) -> Bool { return isValidBST(root, min: Int.min, max: Int.max) } func isValidBST(_ root: TreeNode?, min: Int, max: Int) -> Bool { guard root != nil else { return true } if root!.data max { return false } return isValidBST(root?.left, min: min, max: root!.data - 1) && isValidBST(root?.right, min: root!.data + 1, max: max) } } Show More Responses All the above answers, except the in-order traversal technique, are incorrect. The correct solution is as follows: ` func isBSTHelper(min: Int, max: Int, tree: TreeNode?) -> Bool { guard let tree = tree else { return true } if tree.value = max { return false } return isBSTHelper(min: min, max: tree.value, tree: tree.left) && isBSTHelper(min: tree.value, max: max, tree: tree.right) } func isBST(_ t: TreeNode) -> Bool { return isBSTHelper(min: Int.min, max: Int.max, tree: t) } // example: let tree = ... isBST(tree) ` One or more comments have been removed. |
Implement division without using multiplication or division. It should work most efficient and fast. 11 Answersexp(ln(a)-ln(b))=a/b What if one or both of a,b is less than zero. ln(x) for x < 0 is not defined. we can use bit shift operator. e.g. 4 is 100 in binary we want to divide 4 by 2 so right shift 4 by 1 bit 4>>1, so we get 010 which is 2. Show More Responses This solution rounds down to the nearest signed integer // Implement division without using multiplication or division. It should work most efficient and fast. int Divide(int divisor, int dividend) { int divisionCount; int tmp = dividend; if (tmp - divisor > 0) { tmp = tmp - divisor; divisionCount++; } // This will apply the correct sign to the quotient if ((divisor & 8) ^ (dividend & 8) != 0) { divisionCount = divisionCount | 8; } return divisionCount; } // correcting previous answer int Divide(int divisor, int dividend) { int divisionCount; int tmp = dividend; if (tmp - divisor > 0) { tmp = tmp - divisor; divisionCount++; } // This will apply the correct sign to the quotient if ((divisor & 0x80000000) ^ (dividend & 0x80000000) != 0) { divisionCount = divisionCount | 80000000; } return divisionCount; } can anyone post solution in java? public class Solution { public static void main(String[] args){ int top=32; int bottom=4; int count=0; boolean negative=(top*bottom)=bottom){ top=top-bottom; count++; } System.out.print((negative)?"-":""+String.valueOf(count)+"..."+top); } } Obviously the interviewer would not allow us to use Math functions like exp, log etc. We are supposed to use the Long division method or the Newton Raphson method to find the quotient. Newton Raphson is the fastest but uses operator * (multiplication) though. http://stackoverflow.com/a/5284915 Python version that gives you an idea how it works: i = 0 while divisor = 0: if dividend >= divisor: dividend -= divisor result |= 1 >= 1 i-=1 plus some code to check for 0 and support negative values #Write a program to do division without division or multiplication 2 3 def division(dividend, divisor_initial): 4 divisor_final = divisor_initial 5 quotient = 1 6 while dividend - divisor_final > divisor_initial: 7 quotient += 1 8 divisor_final = divisor_final + divisor_initial 9 number = divisor_final - divisor_initial 10 remainder = dividend - divisor_final 11 return quotient,remainder 12 13 14 def main(): 15 print division( 101, 3) 16 17 18 if __name__ == "__main__": 19 main() |
Software Engineer at Google was asked...
Write a function Brackets(int n) that prints all combinations of well-formed brackets. For Brackets(3) the output would be ((())) (()()) (())() ()(()) ()()() 11 Answerspublic class Parenth2 { static int total = 3; static private void Brackets(String output, int open, int close, int pairs) { if ((open == pairs) && (close == pairs) && output.length() == total * 2) { System.out.println(output); } else { if (open < pairs) Brackets(output + "(", open + 1, close, pairs); if (close < open) Brackets(output + ")", open, close + 1, pairs); } } public static void main(String[] args) { Brackets("", 0, 0, total); } } You almost got thte answer, just a couple of errors... /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author Owner */ public class Parenth4 { static private void Brackets(String output, int open, int close, int pairs, boolean opened, boolean closed, int total) { if ((open == pairs) && (close == pairs) && output.length() == total * 2) { System.out.println(output); } else { if ((open < pairs)) Brackets(output + "(", open + 1, close, pairs,true, closed, total); if ((close < open)&& opened) Brackets(output + ")", open, close + 1, pairs,opened,closed, total); } } public static void Brackets(int total) { Brackets("", 0, 0, total,false,false, total); } public static void main(int number){ Brackets(number); } } This is a DP/memoization question, I believe. The base case is 0 and 1 bracket (the answer is empty or (). The recurrence is: bracket(n) = all combination of results from bracket(n-1) and from bracket (1) from bracket(n-2) and bracket(2) . . from bracket(1) and bracket(n-1) lastly, '(' . bracket(n-1) ')' The DP version of the above recurrence is straightforward. (Btw, this recurrence obviously will produce duplicate, but it's not hard to produce a modification that does not produce duplicate.) ;) Show More Responses Here is a F# implementation: let rec Br total output openp closep = if openp = total && closep = total then printfn "%s" output else if openp < total then Br total (output + "( ") (openp + 1) closep if closep < openp then Br total (output + " )") openp (closep + 1) let Brackets total = Br total "" 0 0 Brackets 5 let read = System.Console.ReadLine() void parens(int nPairs) { parens("", nPairs, nPairs); } void parens(string ans, int leftCount, int rightCount) { if (leftCount==0 && rightCount==0) { cout 0) { parens(ans+"(", leftCount-1, rightCount); } if (rightCount>leftCount) { parens(ans+")", leftCount, rightCount-1); } } To Remove duplicates simply use java Set :) public static String bracket(int a) { Set s = new TreeSet(); bracketIntern(s, a, "", ""); System.out.println(s); return s.toString(); } public static void bracketIntern(Set set,int a, String preFix,String suffix) { if(a == 1) { set.add(preFix+"()"+suffix); return; } bracketIntern(set, a-1, preFix+"()", suffix); bracketIntern(set, a-1, preFix+"(", ")"+suffix); bracketIntern(set, a-1, preFix, "()"+suffix); } I think you can also build a trie, and the traverse the trie to print out all the combinations. Complete python program to print the all combinations of well-formed brackets. How to calculate its Big-o? The recursive recurrence seems a little bit complicated. ---- def brackets(n): sol = [] li = [' ' for x in range(n*2)] def recu_brackets(opened, closed): if n - opened: li[opened + closed] = '(' recu_brackets(opened + 1, closed) if n - closed and opened > closed: li[opened + closed] = ')' recu_brackets(opened, closed + 1) if opened == n and closed == n: sol.append(''.join(li)) recu_brackets(0, 0) print ' '.join(sol) brackets(3) wasn't all that neat. o well public class MakeBrackets{ static List make(int number){ List list = new LinkedList(); if (number == 0) {list.add(""); return list;} if (number == 1) {list.add("()"); return list;} for (int i = 0; i < number; i++){ for (String item : make(i)){ for (String item2 : make(number - 1 - i)){ list.add("(" + item + ")" + item2); } } } return list; } public static void main(String[] args){ System.out.println(make(Integer.parseInt(args[0]))); } } def brackets(n): return bracketsPrefix("", n, n) def bracketsPrefix(prefix, opens, closes): total = 0 assert opensopens: total += bracketsPrefix(prefix+")", opens, closes-1) if opens>0: total += bracketsPrefix(prefix+"(", opens-1, closes) return total if __name__=="__main__": for i in range(6): n = brackets(i) print i,n x = raw_input("** ") One or more comments have been removed. |
Software Engineer at Google was asked...
Write a function to get maximum consecutive sum of integers from an array. 12 AnswersSour code: int LargestSubSum(int[] arr) { int maxSum = 0;//this is value to return int tempSum = 0;//this is to keep track of current sum. check Q16 for more details for(int i=0; i0)//still can be part of the final largest sum's part { tempSum += arr[i]; if(tempSum>maxSum) maxSum = tempSum; } else//this can be discarded as the possiblity being part for largest sum tempSum = 0;//reset } return maxSum;//do not forget to return } I also made a video to demo the whole process to solve this problem including a test case at http://youtu.be/Q7Rf79mLs7M public static int recursiveMaxSum(int set [], int index){ if(index==set.length) return 0; if(set[index] < 0) return rMaxSum(set, ++index); return set[index] + rMaxSum(set, ++index); } Show More Responses Penguin: Try this case {5,-1,2,-2} the max sum is 5-1+2=6. I am not sure why my reply (2nd reply) was tagged as not helpful, but that's the working code including a testing case. In Java public static int findMaxConsecutive(int[] arr){ int max =0; int temp = 0; for(int i=0; i function maxarr($arr, $len) { $maxsofar = 0; $maxendinghere = 0; foreach ($arr as $entry) { $maxendinghere = max(0, $maxendinghere + $entry); $maxsofar = max($maxendinghere, $maxsosfar); } } There is an easy recursive solution for this that runs in O(nlgn). Split the array in two, then the MCS (maximum consecutive sum) is the maximum of: MCS(first half), MCS(second half), or sum of consecutive numbers passing the middle point or SUM(maximum of numbers up to the end of first half, maximum of numbers from start of the second half) not sure that all these propositions are working in real cases : let's consider this array : t = [ -1,-2,10,11,-2,-1 ] none of your solutions seem to consider a sub sum that can be bounded inside the array. I feel like a solution with two iterators should fit. a function sum(int beg, int end, int* array) returning the sum between the indexes. and something like : int highestConsecutive(int* array){ int beg=0, end=len(array); int biggest_sum=-MAXINT; for(end=len(array);end>0;--end){ for(beg=0; beg < end; ++beg){ int s_btw=sum(beg,end); biggest_sum=s_btw; } } return biggest_sum; } should return the highest consecutive sum.... I've not tested it since I've juste been writing it here, but I think that it's on the way to a correct solution, and it seems to have something like an n*log(n) complexity. such a solution even allows you to return the indexes of the sum found... this have to be checked and optimized but still... oups ^^ there a lack in this code it seems :) , lack of the if(s_btw > biggest_sum) :) appologize for this ;) def max_subarray(A): max_ending_here = max_so_far = 0 for x in A: max_ending_here = max(0, max_ending_here + x) max_so_far = max(max_so_far, max_ending_here) return max_so_far Source:http://en.wikipedia.org/wiki/Maximum_subarray_problem#Kadane.27s_algorithm Contrary to all the solutions posted the correct solution runs in O(n) and Lilica posted the Python solution with a link to the Wikipedia source. There's also a easy C solution that any Java or .Net developer should be able to understand. One or more comments have been removed. |
Software Development Engineer at Amazon was asked...
List all anagrams in a file. Assumptions: case-insensitive, a-z characters only, one word per line. For example, if the file contains dog, cat, ddd, goo, act, god -- output dog, god, act, cat 10 AnswersThankfully I was taking a theory course and one trick used in the course was "encoding" programs as a large natural number using product of primes. 1. Adapt the encoding as follows -- generate the first 26 primes and assign a prime to each letter 2a. For each word, take the product of each letter's prime. So #(act) = 2*5*prime(t) 2b. As you can see, #(cat) = 5*2*prime(t) = #(act) 3. Insert a handwavey argument about inserting the number/word pairing into a HashMap> Sort the words. Anagrams appear next to each other in the sorted list. Sorry, sort the letters in each word, then sort the words. Anagrams appear next to each other in the list. For example the sorted list for the input would be: act act ddd dgo dgo goo Show More Responses Thanks for sharing Bill For this set of input, the expected output should contain only [cat, act, god, dog]. I'm curious to see what "next steps" your algorithm will perform to provide this expected output You keep track of the mapping from the sorted word to the actual word in a pair, for example: [act, cat] [act, act] [ddd, ddd] [dgo, god] [dgo, dog] [goo, goo] Then you go through this list and count if you have a duplicate entry or not. If you do, like for act, you print out those duplicate entries: cat, act. Bill, your algorithm is O(n*log(n)) while the candidates would be O(n) - provided he uses a decent hash function donutello, bills algo is not n log n it is n*log(k) where as candidates algo is n * k again (multiplications for each word) where k = length of the longest word on top of that calculating primes is expensive anyway I would go with bills answer Bills algo is nlogk + nlgn. After sorting the k letters for n times you also have to sort the n words. #Get inputs a = [] f = open('input.txt','r') for line in f: line = line.strip() a.append(line) #Sort letters in a word def sort_letter(s): r = [] for i in s: r.append(i) t = sorted(r) v = ''.join(t) return v #Find anagrams d = {} for v in a: sv = sort_letter(v) if sv in d: d[sv].append(v) else: d[sv] = [v] #Print results for k,v in d.items(): if len(v) > 1: for s in v: print s think of each line as a set of characters, not a word, then create set of sets of characters which you fill from the input. then print the set (order does not matter as its not specified) |
Improve this piece of code, loop tracing, very basic printing problem 10 AnswersDid you get to choose which programming language? I guess, what happened is that I told them my strongest language was Java and they said you can write it in that language if you want. The "improve this piece of code" portion was in python, the loop tracing was in Java I believe, and the printing problem was open ended. But if you have programming experience you should be able to tell what the code does pretty easily, it's definitely not hard. Just know they might reject you regardless of if you do well. Maybe it's just the Covid-19 situation. Did they ask salary expectations? Do you think you might have been rejected because you asked for too much $? And you say you answered everything correctly you think? Show More Responses We didn't even get to salary expectations actually. Yea I'm very confident I answered everything correctly. It was definitely not a difficult assessment at all. I know it's kinda tough but try not to be discouraged, unfortunately it's not uncommon for you to ace a technical but still get rejected. All we did was have the technical thing on a google doc, then afterwards they explained what the company does, which is build custom software essentially, and then asked if I had questions. Hopefully you guys have better luck than I did. I have an interview with them this upcoming next week, I am sorry it did not work out I am sure you did great. Makes me a bit nervous you aced it and didnt get a call back. Appreciate it, hopefully you have better luck than I did. Don't give up regardless Any SQL questions? Like anything more complex than just basic JOINS? Also what exactly does "improve this piece of code" mean if you are willing to share? How would one prepare for that? That would be awesome to have some insight currently I am trying to grind leetcode to prepare but unsure if that is a good method, Got a rejection email from someone who did not even interview me stating they appreciated the chance to learn more about me. Very odd, the questions were simple and not difficult , first one was a loop tracing , second was fizzbuzz question and third was improve 2 for loops and you could write out the code or write a paragraph on how you would fix it. Ok, for starters I didn't get any SQL questions at all. The person who commented above me got the same interview questions as me. The improve this code one was me given a nested loop(so n^2 runtime), and then they asked me how I would go about improving this code's runtime. The given code is a brute force solution so you'll probably be fine. Hopefully that gives more detail about the question. As for leetcode/other stuff, I don't think that really helps tbh. I mean, these questions were not difficult by any stretch. The fact that you even know what leetcode is and are probably using it tells me you probably have enough skill to get the questions right. Unfortunately, it's pretty common to ace a technical and still get rejected. Just try to keep your head up, these are tough times. |
Software Engineer IV at Oracle was asked...
Two people are each stuck on their own island, connected by a ferryman with a lockable box. Each person has their own lock and key, but can't send the key along with the box. One person wants to send the other a diamond, but it must be placed into the box and locked or it will be stolen by the ferryman. How do you send the diamond without the ferryman stealing it? 10 AnswersThis is an analog version, if you like, of public key encryption. 1) person A sends key only in a unlocked box to person B. 2) person B sends key only in a unlocked box to person A. 3) 3rd trip person A puts diamonds in the box snaps the lock their holding closed. (At this point owner of the lock can't open the lock. Ensure all contents are in the box before engaging lock.) 4) once the lock box arrives to person B, they can use the key provided on the trip before to open and stare at the contents, And realizes he can pay the ferryman to give him/her ride off the island. Then place a thank you note in the box and close with lock initially held by person B and which now person A has the key. Option B for #4 step) send a thank you note and lock with which the diamonds were so cleverly send to you sealed with. ;) *** Now follow up question would be, how to ensure the ferryman didn't copy the keys during the first transfer of keys? Answer) well, I guess you could have exchanged open locks and not the keys between the two people, and if he could copy a lock on a boat - the ferryman should be looking into more rewarding currier. But why do they care about diamonds when their stuck on an island, not stranded just stuck - pay the ferryman. There is always a man in the middle, know what to trust and what not to. Focusing on security when you may have bigger problems is useless. A comment: What if the ferryman never comes back after you send your diamond first to other person with the locked box? Do you believe the other person is in with the ferryman? Did person A Paid the ferryman to take him/her off the island? Did the ferryman just take off with both of you in the dark? Did the boat sink? This is for sure "thanks for coming in, but you should only answer the question best possible without asking any questions. We can't have you make the BAs put details in specs - we would just have code it. Next please..." But here it goes, So did you chain lock your bike around its frame in high school? - since when did it become not ok to really express your thoughts when all job descriptions read: self motivated, talented, team player and innovative persons this is for you when your not allowed to engage in interviews in the same manner you would when your working there? Why does the interview meeting nothing like what the work environment will be? I hope most of these places you don't have 5 people show up at your cube and just ask you to loop using a for construct and alert different messages at patterned criteria, then just walk away with out telling if you did good or bad. Just getting ready for this process after 15 year. Well for the first time really I only worked for one employer all my life and internal interviews are not the same as with people who need to just weed out people on both ends of the bell curve. Must you just play along and give the answer 514 gives thumbs up to on three job and social sites? Or can you ask questions and be really who you are? Would love feedback..... Show More Responses This isn't meant to be an open-ended question. It's a test of your problem-solving abilities, and a good interviewer will say that up front. In technical interviews these days, interviewers want to know how you would attempt to solve problems you haven't seen before, or that don't seem to have a clear and obvious answer. For example, in this problem an important piece of information that wasn't presented is that the box can be locked with more than one lock. Once you realize that it's a much easier problem. If you haven't interviewed outside of your present company for a long time you have to remember that you're meeting a lot of people who know nothing about you other than what's on your resumé and are counting on the interview to determine whether or not you can do what your resumé says you can do. Be prepared to answer questions that show you can implement an algorithm given to you, or that you understand basic data structures and programming techniques. I also recommend the book "How to Land The Tech Job You Love", especially if you haven't done any interviewing in some time. Scott thanks for the feedback. How did you know they didn't present the dual lock sync option because its going to be implemented in pascal 5.0 and you can't gain dual locks to a resource. And if they did leave out vital information like that to dirty the waters why would expect implementation that didn't use the benefits of dual lock? The only thing that can move you closer to a solution to an unknown problem is more information, granted you understand the current known constraints and resources and know for fact they yield a solution with gaping holes to any solution you present. So than go with good enough and work within what you have or ask questions, same questions in different tones, different order anything but how can a sr. Engineer ignore pitfalls and not show a better way to do things? I spent 3 hours in 1st interview and 1 hr in a second - wasn't sure I applied for the right job 2 hrs into it and when presented with the FizzBuzz type questions, I had to ask why the inter type questions? - they said not many that come could answer some of thee. I don't know it all or even a little sometimes but I can't the job description from recruiters before applying for the position, can't ask questions to ensure I would be engaged in the job I'm being grilled for. But have you noticed the intertwine description and title on the improper use of engineer and developer? And how 70-75% of description are similar to the word for related job areas? None have anything to say about what you'll be doing other than: working in a fast paced, agile, team and solo, innovative company, exciting pop. , self-starter..... You get it. Two java developers sitting next to each other on the same team maybe working on very different projects and areas of computing, same with UI dev. for openGL is not the same as Core Animtion. Granted a talented developer should be able to do both and cut java script and CSS without RAD tools but why the deliverable project not discussed and how to approach it and common QAs printed off from google search "software engineer interview questions" - on of my sessions person asking the question actually said here is a popular question and printed out the question and presented it. And I just ask this so I can find the job I love and not hate 12 hr every 5 days of work and be engaged and give the employer my commitment to return in value what they pay me. I hope and strive not to deceive in any manner, it seems giving the right answer is no longer correct - you need to give measurable and a comparable answer so you can become a dot on a graph. But I do appreciate your comment and just venting about broken processes in an industry that is becoming less effeicient and from top to bottom, everyone hitting the pewllow at night saying not in my job description to get involved. And computing has a lot to offer all of us to become a better, heather and wiser and at the very core is one mind that is a computer but its been too busy processing finding errors and validating things it should know, or does know but developers and engineers applying for senior level positions need to be asked to write out a for loop. Kind of reminds me of the Finacial Industry, don't you think? Sorry about the rant, but I wil check out the book you suggested and I hope it's not another keywords to use, standardized resume somehow will make me standout. I found this to be interesting perspective if your qurious, won't tell you my perspective but a good read http://www.joelonsoftware.com/index.html Step 1: The person with the diamond, puts it in the box, locks it with his lock (Let's say Lock1). The ferryman takes it across. Step 2: Person 2 locks the box again with his lock (Lock2) Sends it back with the ferryman. Step 3 : Person 1 unlocks Lock1. Sends it back. Step 4 : Person 2 unlocks Lock 2 and retrieves the diamond. The upvoted answer has a flaw. The rules state you cannot send your key in the box. Here's how I'd solve it. 1) Person A sends a note in the box unlocked saying send me your lock open. If writing materials are not available, they can send a verbal message with the ferryman. 2) Person B places their lock inside the unlocked box and sends it back 3) Person A places the diamond in the box and locks it with Person B's lock 4) Person B receives the locked box, opens it with their key. Let's say person B has the diamond, and person A has the box. person A sends the empty box with the unlocked lock in it. person B opens the box, takes out the lock, puts the diamond in, locks the box, and sends it back to person A who unlocks the box and now has the diamond. You ride with the ferryman. There’s only one fully secure answer. You can’t place your lock on the unlocked box and hope it gets there. You have to follow the pattern of lock, lock, unlock, unlock. I think Anonymous answered it perfectly. There is no other fully secure solution. |
Technical Program Manager at Amazon was asked...
Given a string like "I'm being interviewed by Amazon" implement a method that reverses the given string so that it looks like "Amazon by interviewed being I'm". 10 AnswersIn java: String str = "I'm being interviewed by Amazon"; String pieces[] = foo.split(); String reversedFoo; for (int i = pieces.length - 1; i >= 0; i--) { reversedFoo += pieces[i]; if (i > 0) reversedFoo += " "; } System.out.println(reversedFoo); we can first reverse the whole string, and then reverse the individual words O(n) complexity /** * Jun Zheng, Rice Univ * An interview question of Amazon * Java 7, Eclipse * Reverse a sentence, e.g., "Amazon is so gay" to "gay so is Amazon" * @param str * @return */ private String reverseSentence(String str){ str=new StringBuffer(str).reverse().toString(); int j=0; for(int i=0;i Show More Responses Private String ReverseStr(String reverseMe){ StringTokenizer st = new StringTokenizer(reverseMe); int count; String[] iamReversed = new String[j=st.countTokens()] while(st.hasMoreElements()){ } } Pressed tab and enter and my comment got posted beofre even i could complete the code. here goes the complete method, Private String ReverseStr(String reverseMe){ StringTokenizer st = new StringTokenizer(reverseMe); int count; String[] iamReversed = new String[j=st.countTokens()] while(st.hasMoreElements()){ iamReversed[--j] = st.nextElement().toString()+" "; } return iamReversed; } int main() { string s; cout << "Enter string: "; getline(cin,s); string newstr; int spaces = 0, pos, start = 0; for ( int i = 0; i < s.length(); i++) if (s[i] == ' ') spaces++; for ( int i = 0; i < spaces; i++) { pos = s.find(" ",start); newstr = (s.substr(start,(pos-start))) + " " + newstr; start = pos + 1; } newstr = (s.substr(start,(s.length()-start))) + " " + newstr; cout << newstr << endl; return 0; } One liner in Python: def reverse(str): return " ".join(str.split(" ")[::-1]) 3-line solution in PowerShell: $str = "I'm being interviewed by Amazon".Split() $([array]::Reverse($str) ) [string]$str " ".join("I'm being interviewed by Amazon ".split()[::-1]) String s="I'm being interviewed by Amazon "; String []arr=s.split(" "); String ans=""; for(int i=arr.length-1;i>=0;i--){ ans=ans+arr[i]+" "; } System.out.println(ans); } |
Applications Developer at J.P. Morgan was asked...
1. Take an integer input and output the number of 1's in it's binary representation. 2. Implement a mergesort. 3. Explain your level of understanding of data structures (trees, etc.) 4. What makes java different than other languages? 9 Answers4. Garbage collection Hey, did you hear back from them about the final decision? Also, were u coding in Java or Python? If python, why did they ask you questions on java? Could u share those questions because I have been invited too They ask you what language you feel most comfortable with and ask you questions based on that (I said Java). I haven't heard back but I have been contacted by another recruiter from their Manhattan office so maybe better luck on this second try. Good Luck! Show More Responses Thanks man, best wishes to you too.. Nail it this time what questions on data structures/algo did they ask? You said they made you implement data str/algo you had not yet studied Did you get any update from them for the Feb 25th Interview at Brooklyn office? They asked me if I could write out in code how to traverse a tree, heap, etc. but I was not prepared to do that on the spot. I was only able to talk through it. Also asked what sorting algorithms I knew and wanted to see if I could mergesort two arrays in code which I had not practiced recently so I struggled. And no I have not heard back from the Feb 25th Interview in Brooklyn yet. I sent the recruiter an e-mail the week after to follow up but never received a response. I had my interview in 22 Feb still haven't heard any thing from them yet. Recruiter always say the are looking for other candidates at this time. public static String toBinaryString(int i) ex: public class IntegerToBinary { public static void main(String[] args) { // TODO Auto-generated method stub int i = 5; System.out.println(Integer.toBinaryString(i)); //output : 101 } } |
Get numeric number out of a roman string, linear time Given: mapping I = 1, V = 5, X = 10, L = 50, C = 100, D = 500, M = 1000 Input/Output: II = 2, III = 3, IV = 4 VI, VII, VIII IX = 9 XL = 40, XLIX = 49 9 Answers$char_map = array('I' => 1, ...); $input = 'XLIX'; $output = getNumeric($input, 0, count($input) - 1); function getNumeric($roman, $start, $end) { if ($start > end) { return 0; } else if ($start == $end) { return $char_map[$roman[$start]]; } else { $pivot = findPivot($roman, $start, $end); $num = $char_map[$roman[$pivot]] - getNumeric($roman, $start, $pivot -1) + getNumeric($roman, $pivot + 1, $end); return $num; } } function findPivot($roman, $start, $end) { //find max roman from start -> end $maxSoFar = 0; $pos = $start; for ($i = $start; $i $maxSoFar) { $maxSoFar = $char_map[$roman[$i]); $pos = $i; } } return $pos; } mapping = { 'I' : 1, 'V' : 5, 'X' : 10, 'L' : 50, 'C' : 100, 'D' : 500, 'M' : 1000, } def roman(string): prev = 0 totalsum = 0 for c in string: if mapping[c] <= prev: totalsum = totalsum + mapping[c] else: totalsum = totalsum - prev totalsum = totalsum + mapping[c] - prev prev = mapping[c] print(totalsum) roman("XCIX") #include #include #include #include void main() { int *a,len,i,j,k; char *rom; clrscr(); printf("Enter the Roman Numeral:"); scanf("%s",rom); len=strlen(rom); for(i=0;i0;i--) { if(a[i]>a[i-1]) k=k-a[i-1]; else if(a[i]==a[i-1] || a[i] Show More Responses Python: d = {'C': 100, 'D': 500, 'I': 1, 'L': 50, 'M': 1000, 'V': 5, 'X': 10} def f(w): return d[w] print sum(map(f, 'CDI')) >> 601 Ok, a bit more complex than the first posted solution: prev = 10*6 d = {'C': 100, 'D': 500, 'I': 1, 'L': 50, 'M': 1000, 'V': 5, 'X': 10} def f(w): global prev _p = prev prev = d[w] if _p < d[w]: return d[w] - 2 * _p else: return d[w] print sum(map(f, 'XLIX')) Here we have to use simple switch use case to solve this problem .. Java Code for the following:: -------------------------------------- import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class RomanToDecimal { /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { // TODO Auto-generated method stub BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String input = br.readLine().toUpperCase(); int size = input.length(); int decimal =0,j; for(int i=0;i=2) j =i-1; else j =0; char ch = input.charAt(i); switch(ch) { case 'M': { if(i!=0 && 'C'==input.charAt(j)) { decimal-=100; decimal+=900; } else decimal+=1000; break; } case 'D': { if(i!=0 &&'C'==input.charAt(j) ) { decimal-=100; decimal+=400; } else decimal+=500; break; } case 'C': { if(i!=0 && 'X'==input.charAt(j) ) { decimal-=10; decimal+=90; } else decimal+=100; break; } case 'L': { if(i!=0 && 'X'==input.charAt(j)) { decimal-=10; decimal+=40; } else decimal+=50; break; } case 'X': { if(i!=0 && 'I'==input.charAt(j)) { decimal-=1; decimal+=9; } else decimal+=10; break; } case 'V': { if(i!=0 && 'I'==input.charAt(j)) { decimal-=1; decimal+=4; } else decimal+=5; break; } case 'I': { decimal+=1; break; } } } System.out.println(decimal); } } var romanNumeralParse = function(romanString) { var charMap = { 'I' : 1, 'V' : 5, 'X' : 10, 'L' : 50, 'C' : 100, 'D' : 500, 'M' : 1000 }; var sumTotal = 0; for (var i = 0; i = nextCharValue) { sumTotal += (charValue + nextCharValue); } else { sumTotal += (nextCharValue - charValue); } } console.log(sumTotal); }; int getValOfChar(char c) { if (toupper(c) == 'I') { return 1; } if (toupper(c) == 'V') { return 5; } if (toupper(c) == 'X') { return 10; } if (toupper(c) == 'L') { return 50; } if (toupper(c) == 'C') { return 100; } if (toupper(c) == 'D') { return 500; } if (toupper(c) == 'M') { return 1000; } return -1; } int convertRomanToInt(const char* romanChar) { /* Get numeric number out of a roman string, linear time Given: mapping I = 1, V = 5, X = 10, L = 50, C = 100, D = 500, M = 1000 Input/Output: II = 2, III = 3, IV = 4 VI, VII, VIII IX = 9 XL = 40, XLIX = 49 */ // order.. I -> V -> X -> L -> C -> D -> M // start from last.. keep adding till you find an element which is less or bigger than current value. After that start substracting that value.. int prevCharVal = 0; int currentNumber = 0; for(int i = strlen(romanChar) -1; i >= 0; --i) { int cVal = getValOfChar(romanChar[i]); if (cVal == prevCharVal) { currentNumber += cVal; } else if (cVal > prevCharVal) { currentNumber += cVal; prevCharVal = cVal; } else { // This char val is less than previous... // this means, we need to substract. currentNumber -= cVal; } } return currentNumber; } O(n) import java.util.HashMap; import java.util.Map; import java.util.Scanner; public class RomanNumeralInterpreter { static final Map numerals = new HashMap(); static { numerals.put('I', 1); numerals.put('V', 5); numerals.put('X', 10); numerals.put('L', 50); numerals.put('C', 100); numerals.put('D', 500); numerals.put('M', 1000); } public static void main(String[] args) { final Scanner in = new Scanner(System.in); while (true) { System.out.println("Enter Roman number : "); final String roman = in.nextLine(); System.out.println(computeValue(roman.toCharArray(), 0)); } } private static int computeValue(char[] romanNumerals, int index) { if (index >= romanNumerals.length) return 0; int value = numerals.get(romanNumerals[index]); int i=index+1; while (i value) { value = val-value; } else { break; } i++; } System.out.println("Current value " + value + " at index " + index); return value + computeValue(romanNumerals, i); } } |