Java Interview Questions | Glassdoor

# Java Interview Questions

6,007

interview questions shared by candidates

## Java Interview Questions

Sort: RelevancePopular Date

Sep 11, 2015
 Given an array of randomly arranged lower case letters, uppercase letters, and numbers, sort the array such that all lower case letters come before all uppercase letters, come before all numbers. The classes of characters do not need to be in order in their respective sections.7 Answersimport java.util.Arrays; public class SortLowerUpperAndNumbers { static Character array[] = new Character[] { 'B', 'g', '3', 'a'}; public static void main(String[] args) { Arrays.sort(array, (Character o1, Character o2) -> o2 - o1); for (int i = 0; i < array.length; i++) { System.out.println(array[i]); } } }ArrayList newArr = new ArrayList(); for x in oldArr if x is lowercase newArr.add(x) for x in oldArr if x is uppercase newArr.add( x) for x in oldArr if x is number newArr.add( x) An O(n) solutionTo clarify, the solution to such a problem should run in linear time and use constant space. So the first two solutions, while presumably valid, are not quite doing enoughShow More ResponsesIs it like the dutch national flag problem?Using Dutch Flag problem, in where clause I can use 2 Hash Set which contains only lower case letters and upper case letters respectively. Then implementing HashSet.contains(value) in Switch statement cases and rest swapping values based upon it.Solution in java: Arrays.sort(arr, Collections.reverseOrder());i = j = 0 for j in range(0,len(arr)): if arr[j] != 0: if (i < j): temp = arr[i] arr[i] = arr[j] arr[j] = temp i += 1

### Software Engineer at Dropbox was asked...

Mar 29, 2015

May 14, 2011

Sep 6, 2012
 1. mutable, non mutable classes in Java 2. declaring constants in Java 3. x^y algorithm and its optimization. 4. second largest number from Binary Tree7 AnswersFor #4, is it possible the question was "how to find the second largest number in a Binary Search Tree"? If so, it can be done in O(log n) by starting at the root node, traversing right repeatedly until you reach a leaf node, and then returning the parent of that last node. If its just some random binary tree without any ordering, you'd have to traverse the whole tree.For #4, is it possible the question was "how to find the second largest number in a Binary Search Tree"? If so, it can be done in O(log n) by starting at the root node, traversing right repeatedly until you reach a leaf node, and then returning the parent of that last node. If its just some random binary tree without any ordering, you'd have to traverse the whole tree.Method1: Do a in order tree walk and return the last but one element. O(n) Method2: We can go the right sub-tree repeatedly until next is null. Then return the parent. O(logn)Show More Responses1.) Langauge trivia up for interpretation. For immutable classes, you can declare fields final (so noone can change your data), you can declare the class itself final (so noone can subclass you). 2.) static final whatever is a constant, optimized by the JVM at compile time 3.) Optimizing an exponential algorithm's tricky depending on what you're doing. I'd look for memoization to reduce the amount of work you're doing - an really slow algorithm likely includes massive amounts of rework (e.g. naive Fibonacci). 4.) Go right until you can't go right anymore (find the greatest node). If there is a left node (e.g. greatest -> left != null), go left once and then go right again until you can't go right anymore, and that node will be the second largest. If there is no left node, greatest -> parent is the second largest.Code for the last question in java with a recursive function: public static Integer getSecondLargest(Node root) { if (root == null) { return null; } Integer currentSecondLargest = null; if (root.myRight != null) { currentSecondLargest = root.myValue; Integer contenderFromRightSubTree = getSecondLargest(root.myRight); if (contenderFromRightSubTree != null) { currentSecondLargest = contenderFromRightSubTree; } } else if (root.myRight != null) { currentSecondLargest = root.myLeftmyValue; } return currentSecondLargest; }For 3, There is an algorithm described here that can be done in O(n^1.59) time: http://www.cs.berkeley.edu/~vazirani/algorithms/chap2.pdfpublic int findTreeSecLargest(Node root) { int count = 0; if (root != null) { // last right left return 1; // second return 2; count = 1 + findTreeSecLargest(root.right); } // second node of the last right node if (count == 2) { System.out.println("sec large " + root.x); } return count; }

Oct 31, 2016

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

Jan 14, 2010
 How would you find the pairs of numbers that added to some specific number in an array. 7 Answersi program in java..so i will talk from the arrayLists perspective. suppose we want to find out a+b = 123; for(int i=0; i2000 records.but below that, sorting and above operation is efficient. you must play with different possibilities.Your answer (using arrayList.indexOf(...)) is worse than sorting. Sorting is O(log n), finding an item in an unsorted array using ArrayList.indexOf is O(n). Given an unsorted array input (e.g. int[] input), sort it using Array.sort(input) ... this is O(log n). Start at input[0] of the sorted array and calculate it's complementary value. Go to the end of the array and iterate backwards until you find the complementary value or less. If it's less repeat for input[1] and iterate backwards from the previous last item ... keep going. This is at worst proportional to n/2, ie O(n).I realize I wasn't totally clear in my first paragraph ... searching for the complementary value of one item is O(n), but you have to the search for (at worst) every item, so your solution is O(n^2).Show More ResponsesDuh - sorting is O(nlog n) ...Using hashing, this can be done in O(N). store the n/2 mod i in the corresponding hash bucket. Now check the each hash bucket and you are done.sort the array (o(n(log(n)) and take two pointers at both the ends say p1 and p2 if p1+ p2 move the pointer p2 by 1 and add to check if (p1+p2) > n -> move the pointer p1 by 1 and add to check if (p1+p2) = n ->print the pair [traversal takes o(n)] finally thus can be done in o(n)I will not waste o(nlogn) in sorting the array. Instead assuming that the sum we looking for is k, i will divide the array into 2 arrays. First array will contain all values which are less than k/2 Second array will contain all values > k/2 This is bcoz in a sum if one number is less than k/2, the other has to be larger. I will iterate over the smaller array of the 2 since they would rarely be equal. For each x in array 1, i will find the k-x in array 2. Complexity will be O(n).

### Software Engineer at Yelp was asked...

Sep 20, 2013
 Main Technical Question: Write a function that takes as input an array of words input => ['cat', 'star', 'act', 'god', 'arts', 'dog', 'rats'] and returns a sorted array output => ['cat', 'act', 'god', 'dog', 'start', 'arts', 'rats']6 Answershttp://stackoverflow.com/questions/15045640/how-to-check-if-two-words-are-anagrams-in-javaBelow is a pythonic implementation of the same, assumption is we are allowed to built-in sorted method. words = ['cat', 'star', 'act', 'god', 'arts', 'dog', 'rats'] print sorted(words,key=lambda x:sorted(x))Below is a pythonic implementation of the same, assumption is we are allowed to built-in sorted method. words = ['cat', 'star', 'act', 'god', 'arts', 'dog', 'rats'] print sorted(words,key=lambda x:sorted(x))Show More ResponsesFollow senthill comment, I think they need another step of sorting based on the length. words = ['cat', 'star', 'act', 'god', 'arts', 'dog', 'rats'] words = sorted(words,key=lambda x:sorted(x)) sorted(words, key=lambda x:len(x))public static void insertionSort(String[] arr) { for(int i=1;i arr[j+1].length()) { String temp = arr[j]; arr[j] = arr[j+1]; arr[j+1] = temp; } } return arr; }import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.Set; public class Anagrams_Yelp { public Anagrams_Yelp() { String[] words = {"masterschool","cat", "star", "act", "god", "arts", "dog", "rats","schoolmaster"}; printAnagramsTogether(words); } private void printAnagramsTogether(String[] words) { ArrayList finalList = new ArrayList(); HashMap> map = new HashMap>(); for (int i = 0; i list = map.get(myString); list.add(str); map.put(myString, list); }else{ ArrayList list = new ArrayList(); list.add(str); map.put(myString, list); } } Set keySet = map.keySet(); Iterator objIterator = keySet.iterator(); while(objIterator.hasNext()){ ArrayList list = map.get(objIterator.next()); finalList.addAll(list); } int i = 0; while(i

### QA Engineer at Salesforce was asked...

Nov 14, 2010
 Another question was: what's the difference between an abstract class and an interface. Can a class inherit both from an abstract class and an interface at the same time? 6 AnswersThe answer is yes in C++ but no in Java.Uh, this question is as dumb as the first answer. A Java class can extend at most one class, and implement one or more interfaces. A combination of the above is allowed.I agree with the 2nd postShow More ResponsesYes, In java class can`t have more than one super class but it can extend a super class and implement interface at one time.See this for differences between abstract class and interface, the first part of the question: http://www.interview-questions-java.com/abstract-class-interface.htmDifference between interface and abstract is , abstract can contain both abstract and non-abstract that is concrete methods, but interface has only all abstract methods....and i agree with ans 2

Jan 15, 2010