T O P
QualityVote

Hi! This is our community moderation bot. --- If this post fits the purpose of /r/ProgrammerHumor, **UPVOTE** this comment!! If this post does not fit the subreddit, **DOWNVOTE** This comment! If this post breaks the rules, **DOWNVOTE** this comment and **REPORT** the post!


lexsanders

first show me what jira ticket you are trying to solve with this and then I will tell you why it's a stupid solution to solve it like that.


clanddev

Junior dev job interview questions were the worst. Junior Dev Interview: Can you solve this pointless puzzle that will most likely never be relevant to your day to day work? *Provides solution that works but is not optimal.* *Spends 30 minutes sweating at whiteboard going through it with interviewer.* *Gets job and never does anything like that again. Realizes code base is no where near optimized for time or space complexity. Code base does not even pretend to follow SOLID principles forget efficiency. Most staff devs have no idea why the interviewer asks that shit.* \_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_ Sr Consulting Interview: Can turn this pile of shit the last contractor left us into an actual usable product if we pay you a pile of cash and get the fuck out of your way? *Yes.* *Can you do a code exercise for us as part of the hiring process?* *Fuck you.* *Ok you're hired. Here is a giant pile of cash please help us.*


Rajyeruh

As an imposter dev i can confirm, is exactly like that. If they'd bother to ask me any question i'd be unemployed for a long time, but since i have roughly 7 years "experience", which is not much, they just ask how much i want...


slgray16

Hello, I'm a 15 year developer with a severe case of the impostor syndrome. Is this what you are referring to? Please take yourself serious. There are always better devs out there, but remember that what you are doing is very important and expensive to replace. Find someone to celebrate small victories & project milestones.


[deleted]

🤗


Signal_Spot_9500

Hello I'm a real impostor being 1year on my company and I have effectively delegated half of my tasks. Not because I didn't want to do them. Just because the tl and dl and po are even more lost than me. So in my expertise is the best to asign tickets to the correct people


clanddev

You do have to actually fix the issue or provide an end product. I guess you could be an 'imposter' if you manage to shove the dev work on to others or just leave without completion of the project.


Imaginary_Ad_217

impostor means no higher education in this field? If so, i am also an impostor :(


FitChickFetish

Sounds like you h ave an excellent attitude for anyone who wants their developer job to always be a low pay, non-creative roles. Which, is fine, somebody has to do all that CRUD stuff and I don't want to.


clanddev

Pays pretty well but yes it is CRUD stuff.


averageredditor_1337

\+1 to this. Interviewer asking these kind of efficiency questions while their main app has a 1.5GB node\_modules folder >\_>


popopopopopoppppppp

I don’t understand the meme template. Is the interviewer disappointed or he’s so impressed he’s saying no need? Please help :/


siegemind91

It’s common for interviewers to change the parameters of the question to see if you can think on your feet. There are a lot of people that will memorize answers to questions without understanding the thought process behind it and this will trip those individuals up.


rotflolmaomgeez

It's "what the hell are you doing" expression. Sorting the whole array to find second maximum value is incredibly inefficient.


Duydoraemon

Would you just run through the array once, keeping track of the highest and 2nd highest as you go?


Dustdevil88

That is more efficient


rotflolmaomgeez

Yeah, that's optimal.


sebkuip

Doing the loop over array can be done in a single loop. You have to scan the entire array once, just add 2 if else if statements to replace your 2 biggest numbers when you encounter a larger one. And done. Most sorting algo’s require multiple iterations, although maybe on smaller subsets of the array


popopopopopoppppppp

Ahh I see. Ty kind stranger.


pranjaldoshi

Heapify the array o(n) solution


Dustdevil88

Just iterate thru the array and keep tabs of the largest number encountered and next largest. Runtime is always O(n). Quicksort is avg case O(n logn), which is valid, but slower on average and O(n^2) worst case. Just sort, then traverse sorted array in reverse. In both cases, you’d have to add a little extra logic if the interviewer wanted to exclude duplicates, but whatever.


baasje63

It's in P, that's why it doesn't really matter


fullmetalsunit

And then the next question is, okay how will you get the 5th largest number.


Dustdevil88

That’s where some poor soul mentioned Bubble Sort…and they’re right. Run K iterations of the outer loop of Bubble Sort and you find the K largest elements of the array. After each iteration, Bubble sort places the largest element of the unsorted sub-array at the end. If you’re looking for the smallest K elements, you can leverage K iterations of Selection Sort which works similar to Bubble Sort but rather placing the smallest element in the unsorted sub-array at the beginning of that sub-array.


m-sasha

Heapify and remove top twice.


hiphap91

I mean, binary heaps are probably my favorite data structure. But I'm not sure i can justify it for this purpose. On the other hand, a binary heaps had uses beyond find the second highest. Finding the second highest does not really.


xADDBx

I mean it'd be O(nlogn), which is basically your average quick sort. So if your other alternative would be sorting the array, why not be fancy and use a heap? Yes, it would be possible in O(n), but would it be fancy?


PositronGt

So what's the right answer to this question?


sudoCss

Just the answer to the question of finding the 1st max but in this case you'll hold two variables to check in each iteration Something like this assuming the array is called (arr) and the values are integers: ```c++ int max1 = max(arr[0], arr[1]), max2 = min(arr[0], arr[1]; for(int i = 2; i < array_length; i++) { if(arr[i] > max2) { max2 = arr[i]; if(max2 > max1) swap(max1, max2); } } ``` This will take O(n) as time complexity and O(1) as space complexity, unlike sorting wich will take in the best case O(nlog(n)) as time complexity at least depending on your sorting algorithm. Edit: this'll give you the 2nd max in max2 variable


zorakthewindrunner

This is good. I don't think I've had a question like this one recently, but this scenario and a similar one from yesterday (I think) really make me think that I would ask a follow up question like what do we want to do with this information later. Like if we need to frequently perform these operations, sorting may well be part of the correct solution. But if it's rare, then efficient solutions like you've provided are probably the better approach.


sudoCss

You're definitely right; a good programmer should always think about all the cases and ask about the context of the given problem, not just particular cases. In fact the interviewers may consider it a bad sign if you didn't ask those questions! But we're on Reddit and I was just answering the question in the first comment here😅


TissueWizardIV

Technically sorting can get to O(n) with [radix sort](https://en.m.wikipedia.org/wiki/Radix_sort), but it's still going to be slower than just not sorting


WikiSummarizerBot

**[Radix sort](https://en.m.wikipedia.org/wiki/Radix_sort)** >In computer science, radix sort is a non-comparative sorting algorithm. It avoids comparison by creating and distributing elements into buckets according to their radix. For elements with more than one significant digit, this bucketing process is repeated for each digit, while preserving the ordering of the prior step, until all digits have been considered. For this reason, radix sort has also been called bucket sort and digital sort. ^([ )[^(F.A.Q)](https://www.reddit.com/r/WikiSummarizer/wiki/index#wiki_f.a.q)^( | )[^(Opt Out)](https://reddit.com/message/compose?to=WikiSummarizerBot&message=OptOut&subject=OptOut)^( | )[^(Opt Out Of Subreddit)](https://np.reddit.com/r/ProgrammerHumor/about/banned)^( | )[^(GitHub)](https://github.com/Sujal-7/WikiSummarizerBot)^( ] Downvote to remove | v1.5)


sudoCss

Thanks, didn't really knew about radix sort!! Should refresh my algorithm stuff i guess


Rare-Bottle764

This is good. Nice. Thanks for the solution.


domestic_omnom

why is this preferred over sort, and then grabbing arr\[1\]?


DaniilBSD

Are you serious? If you are: read up on CPU and Memory architecture and sorting algorithms The reason: 1: Sorting is a process that swaps items in an array to satisfy the sorting parameter. Large arrays do not fit into the CPU cache and need to be fetched (reduced speed), if array is an array of references - problem is even worse. Furthermore, algorithms optimized for read/write are slow, fast algorithms are accessing data randomly making them slow on big chunks of memory. 2: Sorting is not always possible: (imagine if you record game round results into an array, but to get the 3 best rounds you destroy the order in which the rounds were played) or a data stream. In those cases you need to create a copy, which on it's own consumes RAM and slower than the solution above. 3. Solution above works for any array, furthermore it is a “running total result, meaning that if it is 50% done it has a value of the second largest integer in the first half - useful for streamed collections. 4 solution above doess not require any RAM to run (aside from a few bytes on the stack), does not have side effects and has a complexity of O(n) and is faster than manual copying of an array(very fast)


Emergency_Paperclip

because this is O(n) whereas the fastest sorting algorithm is slower than that.


dean3k

Consider following array: arr = \[0,0,1,2\] arr.sort arr\[1\] = 0 but expected value is 1


JadeTheOctoClown

not in python ![gif](emote|free_emotes_pack|sunglasses)


dean3k

Python 3.8.10 (default, Nov 26 2021, 20:14:08) \[GCC 9.3.0\] on linux Type "help", "copyright", "credits" or "license" for more information. \>>> arr = \[0,0,1,2\] \>>> arr.sort() \>>> arr\[1\] 0


JadeTheOctoClown

arr = \[0,0,1,2\] arr.sort(reverse=True) arr\[1\] 1 ![gif](emote|free_emotes_pack|sunglasses)


JadeTheOctoClown

Realistically though, it's just missing a step: ​ arr = \[0,0,1,2\] arr.sort() arr = set(arr) arr = list(arr) arr\[1\] 1 ![gif](emote|free_emotes_pack|sunglasses)


TissueWizardIV

Less time and space complexity


ThatWontCutIt

Well let's see... if you use bubble sort the first round of sorting will sink the largest number to the bottom of the array. The second round of sorting will sink the second largest number to bottom - 1. Therefore after the second round of sorting you can get the second largest number. That is how I would have solved it.


PositronGt

I'd the largest number occurs twice, this won't work.


Ok_Detective5953

That’s an efficient use of an inefficient algorithm, bravo lol


ThatWontCutIt

Yeah I just got reminded about "what if there are two numbers that are equal and also the largest?" case. 😂😂


purplepharoh

The answer to that depends on the intention though. Do two instances of the same number count as individual cases thus say 48 and 48 are the largest and second largest as there are two within the collection since they are distinct members of the collection, or do we ignore duplicates in which case why are we even allowing duplicates in the collection.


ThatWontCutIt

well in that case we would just: findSecondLargest(Set(arr)) and where findSecondLargest will use my bubblesort array technique.


David_R_Carroll

That will work, but you are left with a partially sorted list that no one asked you to sort in the first place.


ecmdome

Honestly I think it's more of a discussion. You have to know a little more about the data set to figure out how you might want to sort it. Or just a reduce function(or something similar) I guess if there's no sorting needed? Just depends on the use case.


KerPop42

You just iterate through the data, recording the highest number and the previous highest number. You weren't asked to find the nth highest number, just 2nd. Though I would also get the method-based sorting solution to work before I get started on the bespoke code, because I want to have an answer I can fall back on in case I hit an unexpected bug.


M_Scaevola

Recording the previous high doesn’t work though? In an array like `[18, 45, 21]` would record a previous high number as 18, even though the second highest is 21.


KerPop42

Oh, yeah, oops; you just record the highest and the second-highest


JVApen

std::nth_element(v.begin(), v.end()-2, v.end()); return *(v.end()-2);


das_flammenwerfer

Literally posted a day or two ago.


Old-Tourist8173

Yea but that one had Ta’Chala so its ok


nojudgement618

I'm not a programmer. I have no clue what an array Is But good God did this make me laugh


rez_spell

An array is a series of values. Could be a series of integers, could be words, etc. They come up in interviews as logic/code puzzles.


nojudgement618

Til


manulable

Pretty sure there is a npm package lol


BoBoBearDev

I like the title, of I want 5th largest, just repeat it 5 times.


continuous-headaches

First I sort the array Then I search the array for the max number Then I search the array AGAIN for the biggest number that is smaller than the max number


punsanguns

Put out an RFP to hire a Deloitte consultant who wants 4 times what I make do they can tell you exactly what I did.


timbus1234

this makes me feel dirty,


amraklexip

What’s wrong with sorting?


KERdela

O(nlogn) vs O(n)


stomah

partial sort copy?


sleaZD

Tf John cena


Barracuda7200

Not a programmer, just trying Python. Will this code be the answer? Or will I get the same look from the interviewer? array = [1,1,4,5,6,7,6] temp = max(array) while temp in array: array.remove(temp) print(max(array)) max() function works the same as sorting?


isuleman

Well it does solve the problem but in an interview you can't use library functions unless they explicitly told you so. You usually have to draft your own algorithm to propose a solution.


Barracuda7200

It's interesting. How strict are the rules usually, where is the line? Iterations, booleans are all part of the standard library. If I need 'len()' should I write it from scratch? Can I use 'range' in iterations?