Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 10 years ago.
Improve this question
I was asked this in WRITTEN form through a recruiter, with the previous question being string related, and the previous one being about Inversion of Control:
How would you find the second largest element in an array?
Being a Project manager who has is self teaching/learning JAVA, my response was:
How is large defined (integers? parsing of: strings/objects? ) How large is the array? Bubble sort , then return the second to last index. Temporarily store the largest and second to largest variable, sort through the array, replacing the appropriate variables, then return the second largest variable. There are many ways, however to develop an appropriate function that isn’t expensive would require more information. If the range is very wide, make several lean methods, measure the array length, and apply the appropriate method on the array.
Is this a valid response to the question, and if not, what do you think it needs improvement on? I'm asking this because of the extreme gap presented in the common recruitment atmosphere, and am having difficult understanding the actual intended purpose of similar structured questions, and need your feedback to understand what/how to approach/reply.
UPDATE I received notification that they typically see code, but provided no parameters or guidelines, and replied with this:
I can not provide a codified answer, not knowing at least the first two pieces of information. The first will allow for parsing, as numbers are sorted universally, while strings, objects, and others are parsed subjectively. The second part, dealing with the array length, and whether or not it is static, is definitely relavent as a developer, as expensive code (whether in computation time facing the user, or hardware costs to the client) can be costly. The question is worded poorly for an exact technical response, especially given that it is in written format, where there is no feedback. I am merely typing my considerations as a reply, the same as if it were asked in person. The context I am given from the previous questions is that they are looking for someone who understands IoC practices (bullet 3) and would be parsing Strings (given bullet 2) in potentially a transaction (try/catch) situation (bullet 4) and then find (current issue). If the questionnaire's purpose is to see how I approach a problem, then my response is valid. If they would like further clarification, I would be happy to accomodate, but if they are requiring a codified answer AND unwilling to provide the necessary context, then I am unwilling to work with them, as it would highlight there misunderstanding of how to interact with external customers, who DO need guidance when one "simple" question is asked, but other pieces of information are needed to best accommodate, the central reason behind any business seeking outside specialized help. I hope this response in not read in a harsh tone, as my cadence when replying out loud is quite the opposite, as further information is required, including if sole development in JAVA is within the scope of this job, as I am skilled in JS and Python as well, and this was not discussed yesterday. Hopefully you and your client can understand that with the recruiter method, a layer of abstraction can be beneficial in many areas, but in situations like this, it can hinder and cloud perceptions without direct communication and feedback. Please feel free to provide this in addition to my answer.
and received acclaim for this reply. Thank you for your help, as I am really trying to get a programming job, but have no prior formal experience and this guidance really helps.
In this case, I think the interviewer really wants to know in order to find 2nd largest element, does one have to sort the entire array(and pick the second element) or is there any better approach?
The answer is you don't have to sort the entire array in order to find top k elements. Sorting will take O(nlgn) time whereas finding top k items will take only O(nlogk).
You can explain the answer using simple example. If you have to find 2nd largest card in 100 cards with numbers ranging some low to high. The cards are not sorted. To find 2nd largest card, all of you have to do is hold top 2 cards that you have seen so far in your hand. As you pick new cards, see if it is larger than the one in your hand, if so replace the new largest with the smallest in hand. At the end of this process, you will end up holding top 2 cards.
EDIT: Like others said, bubble sort has worst runtime O(n^2). For fun, Check out President Obama's answer to sorting interview question. http://www.youtube.com/watch?v=k4RRi_ntQc8
The most efficient to do the needed task is obvious: iterate once on the array and looking for the "largest" element, all the while storing also the previous "largest" element. At the end of the array, your previous "largest" element is the one your method needs to return.
To formulate your answer, I see 2 choices:
Beginning your answer by "Assuming the array contains int elements..." or something approaching.
Using an undefined isLargest() or isLarger() method and explain that the purpose of the method is to check if the current element is largest currently examined, whatever it means.
This is pretty subjective, but frankly I agree with your question-about-the-question -- they should have defined what it is your array contains.
What you could have done is written something like "Assuming the elements in the array are all integers, here's how I'd do it" and then give your answer with that assumption.
I'd follow the same steps with your other requests for additional info -- make an assumption, declare your assumption, then proceed with that assumption in mind.
Seems valid - I just fear they wanted CODE. I think maybe you should have just assumed integers and written something IN ADDITION to what you said.
My initial gut reaction would be "Modified Merge Sort", implemented using a ForkJoinPool. It's still O(n log[n]), but the actual runtime would be faster than a serial implementation.
You may ask why not quicksort, and it's because worst case for quicksort is O(n^2), which would be bad for an extremely large dataset. Modified Merge Sort has more predictable performance and a better worst case scenario O(n log[n])
Related
I was solving a Codeforces problem yesterday. The problem's URL is this
I will just explain the question in short below.
Given a binary string, divide it into a minimum number of subsequences
in such a way that each character of the string belongs to exactly one
subsequence and each subsequence looks like "010101 ..." or "101010
..." (i.e. the subsequence should not contain two adjacent zeros or
ones).
Now, for this problem, I had submitted a solution yesterday during the contest. This is the solution. It got accepted temporarily and on final test cases got a Time limit exceeded status.
So today, I again submitted another solution and this passed all the cases.
In the first solution, I used HashSet and in the 2nd one I used LinkedHashSet. I want to know, why didn't HashSet clear all the cases? Does this mean I should use LinkedHashSet whenever I need a Set implementation? I saw this article and found HashSet performs better than LinkedHashSet. But why my code doesn't work here?
This question would probably get more replies on Codeforces, but I'll answer it here anyways.
After a contest ends, Codeforces allows other users to "hack" solutions by writing custom inputs to run on other users' programs. If the defending user's program runs slowly on the custom input, the status of their code submission will change from "Accepted" to "Time Limit Exceeded".
The reason why your code, specifically, changed from "Accepted" to "Time Limit Exceeded" is that somebody created an "anti-hash test" (a test on which your hash function results in many collisions) on which your program ran slower than usual. If you're interested in how such tests are generated, you can find several posts on Codeforces, like this one: https://codeforces.com/blog/entry/60442.
As linked by #Photon, there's a post on Codeforces explaining why you should avoid using Java.HashSet and Java.HashMap: https://codeforces.com/blog/entry/4876, which is essentially due to anti-hash tests. In some instances, adding the extra log(n) factor from a balanced BST may not be so bad (by using TreeSet or TreeMap). In many cases, an extra log(n) factor won't make your code time out, and it gives you protection from anti-hash tests.
How do you determine whether your algorithm is fast enough to add the log(n) factor? I guess this comes with some experience, but most people suggest performing some sort of calculation. Most online judges (including Codeforces) show the time that your program is allowed to run on a particular problem (usually somewhere between one and four seconds), and you can use 10^9 constant-time operations per second as a rule of thumb when performing calculations.
need help with an optimized solution for the following problem http://acm.ro/prob/probleme/B.pdf.
Depending on the cost i either traverse the graph using only new edges, or using only
old edges, both of them work, but i need to pass test in a limited number of milliseconds,
and the algorithm for the old edges is dragging me down.
I need a way to optimize this, any suggestions are welcome
EDIT: for safety reasons i am taking the algorithm down, i'm sorry, i'm new so I don't
know what i need to do to delete the post now that it has answers
My initial algorithmic suggestion relied on an incorrect reading of the problem. Further, a textbook breadth-first search or Dijkstra on a graph of this size is unlikely to finish in a reasonable amount of time. There's likely an early-termination trick that you can employ for large cases; the thread Niklas B. linked to suggests several (as well as some other approaches). I couldn't find an early-termination trick that I could prove worked.
These micro-optimisation notes are still relevant, however:
I'd suggest not using Java's built-in Queue container for this (or any other built-in Java containers for anything else in a programming contest). It turns your 4-byte int into a gargantual Integer structure. This is very probably where your blowup is coming from. You can use a 500000-long int[] to store the data in your queue and two ints for the front and back of the queue instead. In general, you want to avoid instantiating Objects in Java contest programming because of their overhead.
Likewise, I'd suggest representing the edges of the graph as either a single big int[] or a 500000-long int[][] to cut down on that piece of overhead.
I only saw one queue in you code. That means you are searching from one direction only.
You may want to take a look at
Bidirectional Search
So I am trying to design an algorithm to calculate the specific items I can buy, based on the amount of money I have, to get the most value of the purchase, given that each item has specific value. So my plan was to use nested if else statements etc... But that is extremely inefficient. Any input?
I am not asking for anyone to solve this for me. I am simply asking if this way is one of the least efficient but still successful way of doing it.
It sounds like you're trying to implement the Knapsack problem.
You can read about it here:
http://en.wikipedia.org/wiki/Knapsack_problem
I dont completely understand the question but, depending on your conditions a switch block could be better, but its actual performance increase is little
ref: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html
I am creating a tree in java to model the Extensive-form of a game for an AI. The tree will be an 25-ary tree (a tree in which each branch at most has 25 child branches) because at each turn of the game there are 25 different moves. Because the number of new branches that have to be created in each new layer of the tree is 25^n I'm very concerned with making this efficient. (I intend to remorselessly cut of branches to keep them from growing in order to keep things from getting bogged down). What is the best way to model such a tree when efficiency is such a concern? My first impression is to have a node object where each node has a parent node and an array of child nodes but this means creating a lot of objects. Ultimately these are my questions:
Is this the fastest way create and manage my tree?
What is a good way to figure out how much time any given algorithm or process in a program is going to take? (the only one I've thought of so far is to create a date before the process and then after and compare the # of milliseconds that have passed)
Any other thoughts are also welcome. My question implies and is related to a great number of other questions, i would expect. If i have been ambiguous or unclear please comment to let me know instead of down-voting and storming off as this isn't productive.
Realistically, the way you described is the best approach. It'll perform reasonably well compared to anything else you could do and will be straightforward to implement.
Time and again people are asking questions about how to do something "efficiently". The best answer is nearly always, "don't even bother trying". Unless your improvement is an algorithmic one, it's unlikely to make much difference anyway, and especially in a case like this, the extra effort and complexity isn't worth whatever miniscule gain you might be able to achieve.
Putting it another way, and to borrow a quote (though I can't remember the originator), the first rule of optimization is: don't.
Having said that, if you really feel the need to squeeze every last drop of speed, you could try caching and re-using objects (instead of discarding them completely, keep track of them in a free object store, and then when you need to create a new object, first check the free object store to check if there is an existing one). As always, you'll need to measure performance before and after to see if it really helps (chances are it won't help much, unless physical memory is really constrained, in which case garbage collection can become expensive).
I agree with the previous comment about only optimizing once you have implemented the rest of the application.
On the other hand, I do realize a few things that may be of importance:
Branching factor of 25: Although not ridiculously huge, it is still large with respect to other problems. For a tree, you will definitely have to have a list for each node to indicate the list of SubNodes. You can do this either by making a Node class which has a collection of nodes within it, or have an external Map that maps a given node to a list of children nodes.
Removing and adding of elements will be done: This lends itself to a LinkedList implementation of the stored children since you don't want to perform costly removes and adds. A HashSet may work also, but the problem is that you may need more memory.
Iteration of the elements may or may not be done: If you want to iterate over the entire list at each step, LinkedLists are fine. If you want to prioritize the nodes then you may be saving memory by using a priority queue data structure. Priority queues are especially helpful if you are going to implement a heuristic function and evaluate which child to move to at any given node.
Thats all I have so far, but I'll keep updating if I think of more things, or if you update your content.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
When interviewing college coops/interns or recent graduates it helps to have a Java programming question that they can do on a white board in 15 minutes. Does anyone have examples of good questions like this? A C++ question I was once asked in an interview was to write a string to integer function which is along the lines of the level of question I am looking for examples of.
Is there any reason why it has to be on a whiteboard? Personally, I'd rather sit them in front of a keyboard and have them write some code. Our test used to be a simple 100 (IIRC) line Swing text editor. We then broke it a few simple ways, some making the code not compile and some a little more subtle, and gave the candidates half and hour and a list of problems to fix.
Even if you can't have them do anything hands on make sure that you do give them some explicitly technical questions. In another round of interviews there were a surprising number of recent graduates who were just buzzword-spouting IDE-jockeys, so they could look OKish waving their hands around in front of a whiteboard talking about Enterprise-this and SOA-that, but when given a simple Java fundamentals multiple choice exam asking things about what final and protected meant did horrifyingly badly.
I've always thought that algorithmic questions should be language agnostic. If you want to test the java level of a student, focus on the language: its keywords (from common one like static to more exotic one, like volatile), generics, overloading, boxing/unboxing of variable, standard libraries.
Some stuff that has showed up on SO:
IsPalindrome(string s)
ReverseWordsInString(string s): "I know java" --> "java know I"
Other stuff that springs to mind:
multiply a Vector with a Matrix (can this be done OO-Style?)
echo (yes, a simple clone of the unix tool)
cat (15 min should be enough, should weed out the clueless)
a simple container for ints. Like ArrayList. Bonus question: Generic?
Write a function to swap variable values using pointers (Really poor ones will fall for this)
Write a program to find the distance between two points in the XY plane. Make use of a class to store the points.
Demonstrate the use of polymorphism in java using as simple program.
Write a program to print the first n prime numbers.
Write a program to replace a string in a file with another.
If you don't know what questions to ask them, then may be you are not the right one to interview them in Java. With all due respect, I hate when people ask me questions in interviews which they themselves don't know answers for. Answers for most of the questions can be found online by googling in a few secs. If someone has experience in Java, they will definitely know Abstract class, interface etc as they are the core building blocks. If he/she does not know 'volatile' keyword - big deal.
I agree with Nicolas in regards to separating the algorithmic questions from the actual language questions.
One thing that you might want to consider is giving them a couple simple algorithm questions that they can write up the pseudo code for on the white board (ex. "Explain to me the Bubble sort and show me the pseudo code for it."
Then once they have demonstrated their algorithmic knowledge you can move on to the Java questions. Since some people work better in front of a computer than in front of the whiteboard, I would give them something simple, but leveraging their knowledge of Java, that they can implement in 30 minutes or so in using the same IDE that you are using at the company. This way if they claim to know the IDE you can also get an idea of how well they know it.
Write a function that merges two sorted lists -- stopping at limit. Look for the easy optimizations and correct boundary checks / sublist calls. Tell them T implements compareTo.
public List<T> merge(List<T> one, List<T> two, int limit)
Write a function that returns true if any two integers in the array sum to the given sum. Have them try to do better than n squared using some sort of set or data structure.
public boolean containsSum(int[] nums, int sum)
I would avoid asking them questions that would have been covered in their undergrad classes. I would be more curious about their ability to apply everything they've learned to solve complex technical problems. If your business has a specific need for an IT solution you could use that as a starting point. You could ask the candidate what technologies they would use and the pros and cons of using those technologies versus alternate technologies. As the discussion progresses you could get a feel for their technical skills, problem solving skills, interpersonal skills, etc. I think it is important to avoid coaching them, even in awkward moments. This is important to weed out the BSers.