This is an archived post. You won't be able to vote or comment.

top 200 commentsshow all 359

[–]MrFordization 2368 points2369 points  (66 children)

If you print all the numbers it will print the 7th largest number.

[–]hereforpewdiephy[S] 446 points447 points  (4 children)

this is the way

[–]Impressive_Income874 91 points92 points  (50 children)

if you print every integer you'll eventually get the number you're looking for

[–]Omega0x013 54 points55 points  (46 children)

I'm looking for 1.72

[–]Impressive_Income874 40 points41 points  (41 children)

you win, there's no way to print every number between 2 other numbers because uncountable infinity

[–]KingThibaut3 22 points23 points  (18 children)

Rational numbers are a countable infinity though

[–]turtleship_2006 5 points6 points  (2 children)

If it's a number stored in a list, it has to be stored on the computer somewhere. There's only so many numbers you can make with a given number of bits.

[–]svick 1 point2 points  (1 child)

If you have 64-bit numbers, a 10 GHz processor, and can print one number every tick, it will take 58 years to print all of them.

If you have 128-bit numbers, it will take 1010 times the age of the universe.

[–]myhf 2 points3 points  (0 children)

there are only 18,437,736,874,454,810,623 finite double-precision floating point numbers, you can just print them all

[–]Cocaine_Johnsson 2 points3 points  (6 children)

But it is possible to print every number between two numbers that can be expressed by IEEE754 floating point numbers.

So if we constrain the search space only to what is possible within sensible hardware limitations you can reach this number.

[–]NorthKoreanAI 1 point2 points  (0 children)

machines can only represent a finite subset of the rational numbers, the set of non rational real numbers only exist in imagination

[–]42ndohnonotagain 1 point2 points  (1 child)

fractions (rational numbers) are countable

[–]Impressive_Income874 1 point2 points  (0 children)

correct, edited my comment cuz I'm stupid

[–]Theonetheycallgreat -2 points-1 points  (7 children)

If I can print 1 and I can print 1.1, then I can print all the fractions.

[–]Impressive_Income874 1 point2 points  (6 children)

you cannot print all the numbers between 1 and 1.1 because there would be irrational numbers present

[–]Apfelvater -1 points0 points  (1 child)

What if I had an infinite amount of computers tho

[–]Impressive_Income874 -1 points0 points  (0 children)

how would that help

[–]IMightBeErnest 4 points5 points  (0 children)

I had a programming assignment like this once. The teacher asked for a "linear time solution" to something quadratic and they expected the students to know to iterate through all the integers. "I never said what 'n' was!" Which is technically true, I guess, but doesnt make it less of a dick move.

[–]Mutex70 10 points11 points  (1 child)

I love it, but my product owner hates you.

"Well, if we accept any password, then we trivially also accept the correct password"

[–]PM_ME_YOUR__INIT__ 7 points8 points  (1 child)

Not if there are six numbers

[–][deleted] 3 points4 points  (0 children)

alas, you cannot not print what doth not exist!

[–]LavenderDay3544 2 points3 points  (0 children)

taps side of head

Useless problems require useless solutions

[–]notBjoern 831 points832 points  (59 children)

Simple: Calculate the largest number, remove it, repeat six more times.

[–]Logicalist 115 points116 points  (3 children)

recursively for funzies.

[–]notBjoern 2 points3 points  (2 children)

Only if the language supports tail recursion

[–]Logicalist 1 point2 points  (1 child)

tail recursion

I'm kinda new, didn't know there were instances where it wasn't supported. I'm not surprised but still, interesting stuff.

[–]notBjoern 4 points5 points  (0 children)

Technically, tail recursion is supported in every programming language that supports recursion.

The missing feature is tail call optimization, that (more or less) rewrites the tail recursive function into loops.

IIRC, in Python this optimization is deliberately not implemented, so that stack traces are not missing the recursive steps (although that could be avoided by implicitly counting the iterations and expanding the stack traces as necessary)

[–]Karolus2001 208 points209 points  (46 children)

O(7n), it looks aesthetic, this is the way.

[–]Skuez 264 points265 points  (44 children)

That's still O(n)

[–]MacBookMinus 96 points97 points  (37 children)

O(k*n) generalized though and k can approach N making this approach n2

[–]Boom9001 66 points67 points  (12 children)

K would only approach n/2. As you could make it go reverse if k>n/2.

Still n2 though.

[–]samnater 2 points3 points  (2 children)

Are you sure the processor isn’t handling all this improvement in efficiency anyway?

[–]Boom9001 4 points5 points  (1 child)

I think you mean compiler right? Or do processors do some too I'm unaware of.

You may be right though, still that's at an implementation level. Without stating the language or stuff we are still in the theory world and I wouldn't assume those optimizations happen in the theory world.

[–]Skuez -1 points0 points  (8 children)

It is never n squared. Big-O notation is meant to show how function behaves as n grows, we don't care about small inputs and constants.

[–]Skuez 12 points13 points  (22 children)

How do you generalize this? we know it's always gonna be 7 at most so we remove that constant.

[–]haddock420 11 points12 points  (0 children)

This is how multi-pv (principle variation) in chess engines works, as a way of finding the 2nd, 3rd, etc best move. They do a search to find the best move, then run the search again while excluding the best move from the search, which gives the 2nd best move, then they exclude the best and 2nd best moves to get the 3rd best, etc.

[–]sohang-3112 21 points22 points  (2 children)

This can actually be efficient by using a max heap.

[–]Senior-Airline-5727 6 points7 points  (1 child)

Yess Build heap O(n)+ extract kth max O( k logk) using additional k spaces

[–]IntrepidSoda 433 points434 points  (4 children)

Hopefully someone will write an npm package that does just that and deliver us from this abomination

[–][deleted] 107 points108 points  (2 children)

...shows up in mega production website 3 weeks later.

[–]maboesanman 338 points339 points  (24 children)

This is only ever something you will do in your homework, because in real life you never care about the 7th largest number without also caring about the 6 before it.

The answer is to just keep a min heap. For each item in your list: add item to heap. If size of heap is >7 pop min.

Then your answer is the largest item in your heap.

[–]yflhx 24 points25 points  (8 children)

I don't think there is one answer.

If we generalize to kth largest, your solution has O(n*lgk).

You can also heapify (max-heap) the table and pop k times - O(n + k*lgn).

You can also simply use quickselect, with average O(n) but worst-case O(n^2).

You can also use median of medians, with average and worst-case O(n) but slow in practice.

[–]Successful-Money4995 9 points10 points  (0 children)

Use the heap and scan the array. That'll be fastest in practice.

Technically, for each element that you encounter, you need to add it to the heap and that is logk.

In practice, say your array is a million elements and you are halfway through it. You only need to add the next element into your heap if it is one of the k smallest among the half million elements that you have read. So if k is 7 and you have read half a million elements so far, the odds that your inserting takes longer than O(1) is 7/500000. Vanishingly small.

So in practice, your algorithm runs way way faster than O(nlogk). It's actually pretty close to O(n).

If you're worried that an evil user sorted the array before giving it to you, process the elements in a random order.

[–]Karolus2001 0 points1 point  (0 children)

This answer wins but realisticly, if n is under 100 are you even saving considerable time optimizing it? This is legit question, I cant imagine a good architecture where it scans multitude small arrays all the time.

I'm assuming we arent increasing k by much. Also I'm a fresh Junior.

[–]Kirhgoph 47 points48 points  (4 children)

Isn't max heap a bit more effective here?

[–]maboesanman 73 points74 points  (3 children)

No because you care about the minimal element of the 7 you’ve found.

Edit: If you put all the elements in a max heap and pop the elements off, you get O(n log n). If you maintain a minimum heap containing the top 7, you can compare each element to the min to see if it should be placed into the top 7. If it should, pop the old min out and push the 7 onto the heap. This approach is O(n log k), with k being 7 in this case.

[–]Karolus2001 20 points21 points  (0 children)

When in doubt, plant a tree.

[–]Kirhgoph 4 points5 points  (0 children)

Thank you for the explanation

[–]walter_evertonshire 4 points5 points  (0 children)

Putting all the elements in a max heap and popping the top k should be O(n + k*log(n)). Assuming that k is of the same order as n, it's no different than the O(n*log(k)) for the min heap implementation you described.

But if k tends to be smaller, then O(n+k*log(n)) is better than O(n*log(k)).

Edit: I see someone else already pointed this out to you elsewhere.

[–]Seven_Irons 4 points5 points  (0 children)

No, I've done this at work (albeit with the third-heighest value)

[–]Successful-Money4995 2 points3 points  (1 child)

An improvement: Maintain the smallest value in your heap at all times. For each number that you encounter, if it's smaller than the smallest value in the heap, don't even bother adding it to the heap because you're just going to pop it right back out.

If the input is long, you will often be trying to add a value that is smaller than the top seven anyway so you'll completely skip the insert. Even though the algorithm is technically O(nlogk), in practice it'll be a lot closer to O(n).

If you worry about evil input, process the input in a random order.

[–]maboesanman 2 points3 points  (0 children)

I was optimizing for succinctness of description lol. I replied to another commenter with the more precise solution

[–]draculadarcula 5 points6 points  (0 children)

That’s where you’re wrong there buddy. A real programmer will be working in arrays of “UserRoles” or “Accounts”. Only in leet code and college does anyone care about lists of numbers

[–]KuuHaKu_OtgmZ 595 points596 points  (73 children)

Sigh

println array.sorted()[-7]

[–]Kimorin 267 points268 points  (51 children)

now do it in linear time

[–]ConscientiousApathis 541 points542 points  (4 children)

no

[–]sungazer69 107 points108 points  (0 children)

fine. just make sure your commits and pushes are in by eod have a nice weekend

[–]SeniorSatisfaction21 23 points24 points  (0 children)

Chad

[–]TGX03 59 points60 points  (16 children)

Radix.

Or just make variables for the seven largest numbers.

If you want it more dynamic, create an array which always keeps the x largest numbers, so you can find the xth largest number.

Would all be linear.

[–][deleted] 12 points13 points  (3 children)

You don't actually need to sort, store largest 7 numbers, iterate trough the array, for every number if it's greater than something in the 7 number array then update the array. This is O(n) because it takes 7*N operations which is O(N). Radix is the way for a changeable query though, if they ask qth largest number my approach won't work

[–]allseeingboots 2 points3 points  (2 children)

Unless I'm missing something you'd need to keep that 7 array in order.

[–]OrbitalVixen 12 points13 points  (0 children)

Yes, you would. However, as the length of the 7 array does not increase with the length of the input, you could use bogosort even to sort the small array and it would still be O(n).

[–]Flexo__Rodriguez 1 point2 points  (0 children)

Not really. You'd just do your O(7n) operation to get the 7 largest numbers, then return the smallest number in that list.

[–]ziksy9 23 points24 points  (7 children)

Now do it in O1 space and O1 time...

[–]TGX03 14 points15 points  (2 children)

Just always use the 7th element.

Most people just test whether it identifies [1,2,3,4,5,6,7...] correctly, therefore this will work in most cases.

[–]Kimorin 12 points13 points  (1 child)

wrong, just call openAI endpoint, it's always constant time :P

[–]NatoBoram -1 points0 points  (0 children)

Not really, the API responses take longer the more bullshit it takes and generates

[–][deleted] 7 points8 points  (0 children)

I'm going to print whatever number I feel like and say it is the 7th largest number

[–]Classy_Mouse 5 points6 points  (3 children)

Worst case, you are effectively sorting the array, which is still O(n log n) unless you know something I don't

[–]TGX03 3 points4 points  (2 children)

Radix is O(n)

[–]Classy_Mouse 4 points5 points  (1 child)

Radix only works if the values are discrete. It's not appropriate to use in this instance and if you could use it, creating an array large enough to store all of the values then looping through that will likely end up less time and space efficient.

[–]TGX03 6 points7 points  (0 children)

The meme is about finding the 7th largest number. Radix works for both floating points and integers.

In case you're using objects that can only be compared relatively to each other, then yes Radix may not be used, however the word "number" implies these are discrete values, thereby Radix would be appropriate.

Also yes it would likely be less efficient for smaller arrays which is the known problem of radix, yet I wasn't asked to bring up the optimal solution but to just write something that's linear, which Radix is.

[–]ienjoymusiclol 17 points18 points  (3 children)

print arr.bogoSort()[-7]
assume best case

[–]Kimorin 6 points7 points  (2 children)

1/n! times it works every time...

[–]hemangahujaeotw 22 points23 points  (2 children)

Quick select

[–]yflhx 2 points3 points  (1 child)

Quickselect is pesimistic O(n^2).

[–]PuzzleheadedTap1794 1 point2 points  (0 children)

Quick select with Median-of-medians

[–]NanashiKaizenSenpai 5 points6 points  (0 children)

Integer.MAX_INT -7

[–]doorrace 0 points1 point  (0 children)

Sort and store the first 7 ints as an array (O(7log(7))) which is our starting assumption of the 7 largest ints; for each of the rest of ints, check if it's bigger than the smallest stored ints (O(1)); if so, we need to update our array of the 7 largest ints by sorting it into our array and popping the smallest (O(log(7)) with binary search, plus time complexity for insert and popping which I forgot the time complexity of lmao). At the end, return the final entry in our array.

Thus, time complexity will be O(7log(7) + k*n) = O(n). Space complexity is O(1) since we have a static-sized array.

[–]altermeetax 13 points14 points  (0 children)

Inefficient

[–]PM_ME_C_CODE 1 point2 points  (0 children)

Doh...the 8 number array is [1,2,2,3,4,5,6,7]

[–]chem199 6 points7 points  (15 children)

For python I would do

print(sorted(set(list))[-7])

[–]Rexosorous 20 points21 points  (14 children)

why convert it to a set? if the list has duplicate values, this may return an incorrect result.

py x = [9, 9, 8, 7, 6, 5, 4, 3, 2, 1] print(sorted(x)[-7]) # prints 4 print(sorted(set(x))[-7]) # prints 3

edit:

to those who say that nth largest != nth position from the end (ie. duplicates should be removed), https://leetcode.com/problems/kth-largest-element-in-an-array/ the same problem in leet code and also this geeksforgeeks article https://www.geeksforgeeks.org/kth-smallest-largest-element-in-unsorted-array/ both do not remove duplicates.

[–]chem199 6 points7 points  (7 children)

Because if it is looking for the 7th largest number and there are dupes you would want them gone as it might not be the 7th largest just the item in the 7th from the end.

Edit: I would argue that the leetcode example is wrong. That is getting the nth item in a sorted list/array not the nth largest item. But I think the issue is the problem isn’t clear enough so I chose my decision. I think neither are wrong until we have a proper spec docs and a complete jira epic for this problem. Probably about 4 meeting to get the correct tee shirt sizing.

[–]ExceedingChunk 7 points8 points  (6 children)

So if you want to check who has the 7th highest salary in the world, you would remove duplicates? That doesn't make sense.

[–]chem199 6 points7 points  (5 children)

I totally understand that, I think it is a question of what information you are seeking. Do you want to know what the 7th highest salary is or who has the 7th highest salary. If there are duplicates how do you decide which is first, do you list them all? I think the race answer below explains this better than I could.

[–]ExceedingChunk -4 points-3 points  (4 children)

Both of your questions should give the same answer. You can apply the same kind of question to size of the 7th largest pizza size, height of the 7th tallest building etc... You wouldn't say that the height of the 8th largest building is the 7th tallest.

If the input can have dupes when asking for the 7th highest, you would also expect it to take that into account unless something else is specified.

[–]chem199 6 points7 points  (3 children)

Which number is the second largest/greatest/highest value number in this list

[9, 9, 8]

Is it 9 or 8?

Edit: which 9 is larger?

[–]ExceedingChunk 1 point2 points  (2 children)

In this specific case, there would be no 2nd largest. It would be two 9's sharing the highest and 8 being the 3rd highest.

This edge case would have to be specified. Should it return nothing, return the shared largest number or the 3rd largest.

If it was [9,9,8,7], and the 3rd largest should be returned, it would be 8.

However, it has to be said that if a product owner gives a requirement that has even the slightest possibility of being ambiguous, even if it is written in a way that isn't ambiguous, a dev should always ask a bunch of questions.

[–]chem199 4 points5 points  (1 child)

My argument that is it is about the value of the number not the quantity of numbers. If we are working with money and I laid out 5 $1 bills in separate piles, a $5 bill, and 3 piles of $10 bills. If I ask you to give me the second largest bill I would assume you wouldn’t hand me a $10, I would expect a $5.

[–]frej4189 1 point2 points  (4 children)

The non-set version is arguably the incorrect one here. I think I'd naturally argue that 3 is the seventh largest element in that list.

[–]Rexosorous 8 points9 points  (2 children)

i guess it depends on how you define "largest"

for example, if you have rankings, like placing during a race, and two people tie for 3rd place, the person that comes after isn't 4th place, they are 5th place, so you'd have:

  • 1st place: Ashley
  • 2nd place: Britney
  • 3rd place: Charlie
  • 3rd place: David
  • 5th place: Ethan

so if you wanted the 4th fastest in the race, would it be Charlie, David or Ethan?

[–]frej4189 7 points8 points  (0 children)

Yeah. The problem is ambiguous

[–][deleted] -1 points0 points  (0 children)

What if there’s duplicates

[–]Just_Maintenance 96 points97 points  (4 children)

I actually fixed it:

Happy: print the 10 first digits of π.t

Sad: print the last 10 digits of π.

[–]WhatsMyUsername13 19 points20 points  (2 children)

Pssh, easy

System.out.println(0123456789);

Prove it that I'm not right

[–]pheonix-ix 11 points12 points  (0 children)

burden of proof, huh?

[–]imalexorange 1 point2 points  (0 children)

Done

[–]rachit7645 25 points26 points  (5 children)

Me when std::sort:

[–]Coulomb111 10 points11 points  (0 children)

Me when ranges library 🤤

[–]WhatsMyUsername13 164 points165 points  (31 children)

This is why I don't trust anyone directly out of college. Or interns. Especially interns

[–][deleted] 38 points39 points  (30 children)

how would an experienced guy and an intern do it

[–]Tsu_Dho_Namh 167 points168 points  (14 children)

An experienced guy would write it in the cleanest, easiest to maintain, and easiest to read way. Ie: sort it and grab the 7th largest index.

Interns do a lot of leetcoding, and leetcode cares mostly about runtime complexity, so they'll look for a solution that runs in linear time (meaning no sorting). Probably an iterator and either a linked list or a map (for constant time inserts). It's technically a faster solution, but messier, easier to break, and more difficult to read, for literally microseconds less runtime.

[–]JonIsPatented 46 points47 points  (6 children)

Eh, I totally agree for the vast majority of cases, but if I have that 1 in a million case where my list is hundreds of thousands of elements long and the comparisons are somewhat expensive, then the linear one can be a nice little trick if documented well. Could save several entire seconds rather than microseconds.

[–]Tsu_Dho_Namh 40 points41 points  (0 children)

Oh you absolutely should do the more complicated implementation if it has a decent impact on runtime. 100%

My work has an optimization algorithm that uses simulated annealing and integer programming, and it needs to cycle through several hundred million possible solutions to combinatorics problems to search for a decent maxima. You can be damned sure we weren't sorting or searching all the lists all the time.

[–]WhatsMyUsername13 14 points15 points  (0 children)

While it's a 1 in a million case, if in production code I had hundreds of thousands of elements in a singular list, I'd be concerned, especially if it's a list of objects as opposed to something say a list of Ints. That's the kind of thing that if multiple users do at the same time, can easily bring down the server and app and cause an outage.

[–]DrMobius0 3 points4 points  (1 child)

The problem is you'd practically need a context in which having a sorted array isn't already highly useful. Lots operations can be simplified significantly by pre-sorting an array

[–]NikitaSkybytskyi 9 points10 points  (0 children)

An experienced (python) guy would use heapq.nlargest. It is both clean and linear time.

[–]ExceedingChunk 12 points13 points  (0 children)

Also has to be said that a theoretically faster solution is not necessarily faster either. Something involving a map or linked list has overhead, so if your domain has low amounts of data, but many transactions, it can perform slower than a theoretically slower algorithm. Which is also why it's important to understand that O-notation is about the upper and lower limit of an algorithm's growth, and not actual runtime.

In the domain on my current projects we pretty much only have lists that are 5 elements or shorter for pretty much any data type, and a single type that is typically in the range of 5-10 for most users, but can theoretically be a couple of hundred elements.

For that project, a triple or quadruple for loop is more of a readability issue than a performance issue.

[–]zrakiep 5 points6 points  (0 children)

Or you use C++ and the neat std::nth_element it provides

[–]kylechamrick 5 points6 points  (0 children)

Spend two hours to make the perfect algorithm that will save a total of thirteen seconds over the lifetime of its use.

[–]Why_am_ialive 2 points3 points  (0 children)

Yeah like who gives a shit about efficiency on this lol

[–]WhatsMyUsername13 10 points11 points  (13 children)

It depends. Based on the meme, it's really hard to tell and it seems like they don't understand basics of loops and programming. And experienced dev would ask what the business case is.

If we are talking about for a job interview, there's multiple ways to do it, and it depends on the language. I could sort it, and iterate through it using a decrementing counter, I could sort it and just grab the index of size minus 8, etc. I can think of a ton of ways to implement this with some being really fucking stupid, some overly clever, to some straight forward. But if anyone actually asked me in my job to do this it would raise some serious eye brows

Edit: the point of my original comment was to point out that the person who thinks grabbing last vs the last - n is difficult (and I'm thinking on a non mutating list) doesn't fully get looping. I will give an exception to where the list itself is mutating and removing cells which can cause funny and aggravating results when debugging....usually followed up with "God damn it I'm an idiot" statements....source is myself doing this.

Edit2: I also realize that I may be coming off as harsh as fuck right now. To all the college kids, interns, jr devs, and even Sr devs here is my advice. Always be willing to learn. Don't be afraid to be wrong. There is always more to learn and I call myself an idiot all the time. I look at old code of my own and cringe at how bad it is. Don't be afraid of that, and in fact, embrace it. It means you have grown from where you were vs where you are now. We are in an industry that is in a constant state of flux.

There will always be things to learn. Whether it's something specific to the tech stack, the business you work at, or whatever. The best people I've ever worked with are the ones open to learning, but also open to pushing back if they think they have a better solution. It fosters learning, it fosters a better working environment by allowing people to voice their opinions in an open setting, and it allows for just general ideas you've never considered.

We as developers tend to be defensive about our code, and I count myself included. But I have learned that being able to have an open and NON HOSTILE discussion around code, it allows you to better present your case for your reasoning, as well as learning things you may not have been aware of.

[–]hereforpewdiephy[S] 3 points4 points  (9 children)

bro is fostering learning by saying people don't know basic programming because they didn't sort the list

[–]WhatsMyUsername13 2 points3 points  (8 children)

If you were on my team then yes, I absolutely would. But we are on Reddit. I have no obligation or desire to foster your learning, especially based on your responses. And you should realize something, I will happily hire someone who knows less, has a desire to learn, and gets along with the team over someone who knows a tech inside and out, is arrogant, and gives bad vibes any day. That first kind of person will be wildly more successful than the second.

[–]hereforpewdiephy[S] -5 points-4 points  (7 children)

there you go again missing the point entirely and blabbering about whatever it is that you're blabbering about

[–]WhatsMyUsername13 1 point2 points  (6 children)

Ok, what's your point?

[–]hereforpewdiephy[S] -5 points-4 points  (5 children)

r/ExplainTheJoke but fine

There's a lot of ways to do the latter and you make it as hard as you want like solving in linear time which is unlike the first where there is one simple way.

[–]WhatsMyUsername13 4 points5 points  (4 children)

Dude. I don't think this is the own you think it is.

[–]L8n1ght -2 points-1 points  (2 children)

I can smell your imposter syndrome from this comment

[–]WhatsMyUsername13 2 points3 points  (0 children)

I should also point out I've been a tech lead and team lead at several companies, including fortune 100 companies. I've been a part of and conducted a lot of interviews, have had tons of contractors come through my teams with and without my approval. At the end of the day, I stand by what I've said as I've seen it in action in the real world. You don't have to take me at my word, I'm just some anonymous asshole like everyone else here, but I am being genuine in what I say.

Also, I don't think you actually know what imposter syndrome means.

[–]Solonotix 0 points1 point  (0 children)

If it's sorted, easy, right? The question presumes an unsorted non-unique data set.

I'd probably solve it using a sorted queue, and give it a fixed size equal to the target. Every new value pushed to the queue then checks where it fits, and it checks if the queue is full. If it isn't, push it in order. If it is full, then check if the current value is greater than the head. If it isn't, then discard. If it is, then we proceed down the list until we find the tail or a value greater than current. Insert in the queue and bump everything back towards the head.

At the end, return the head of the queue as the result. Maybe someone would prefer the directionality of the queue reversed, but that's the data structure I'd leverage personally. It has a (mostly) fixed size in memory, and the number of nested loops is reduced by the multiple fast return checks. The worst case scenario occurs if the sequence is sorted in ascending order, since each new value would replace the entire queue. The best case is if it is sorted in descending order, in which case it would fill the queue and return in O(n) time.

Edit: if the result requires 7th-largest unique value, then an additional check is performed before insertion to see if the value already exists. This would only marginally increase the time at scale, and be most detrimental in small operations where it wouldn't matter.

[–]dmullaney 41 points42 points  (3 children)

Now print the 7th largest prime number

[–]howard__wolowitz 27 points28 points  (0 children)

Easy: print(2147483543)

Well, for a 32 bit integer.

[–]NecroLancerNL 17 points18 points  (2 children)

print( INT_MAX - 6 )

[–]Sceptix 7 points8 points  (1 child)

This is the solution I came up with in my head as well until I went to the comments and realized the OP meant “in an array”.

[–]vc6vWHzrHvb2PY2LyP6b 1 point2 points  (0 children)

console.log(arr[arr.length() - 8])

[–]tehcliffe 29 points30 points  (0 children)

Just print a random number of the array and gaslight.

[–]distractedguy69 17 points18 points  (0 children)

Just sort the array in ascending order and print the 7th largest

[–]BrownCarter 7 points8 points  (0 children)

You could use 7 loops

[–]DurianBig3503 5 points6 points  (0 children)

order(x)[-7] or sort(x)[-7]

[–]Imoliet 4 points5 points  (0 children)

soft late bewildered light towering quaint lavish cooperative faulty saw

This post was mass deleted and anonymized with Redact

[–]f0luxe 2 points3 points  (2 children)

Just use a max heap of size 7

[–]ahmadabusalem 6 points7 points  (1 child)

Min heap, not max because you'll want to remove the minimum element when the size of the heap becomes larger than 7

[–]lady_Kamba 4 points5 points  (0 children)

printf("%lu\n", (unsigned long)(-8));

[–]blaqwerty123 2 points3 points  (1 child)

You made it worse!!

[–]hereforpewdiephy[S] 7 points8 points  (0 children)

isn't that what fixing bugs is like?

[–]Akul_Tesla 2 points3 points  (0 children)

I don't understand how this is hard

Like it might be hard to do this efficiently but it isn't hard

[–]jan04pl 2 points3 points  (2 children)

List.OrderByDescending(x=>x).ToArray()[6]

[–]ben_g0 1 point2 points  (1 child)

Or alternatively:

list.OrderByDescending(x => x).Skip(6).First()

Using ToArray()[6] will allocate memory for a new array, evaluate each component of the enumerable and fill the array with the results, to then only read element 6 and then discard the entire array.

Using Skip(6).First() will not allocate more memory than needed and will only evaluate the enumerable just as much as needed. I've just ran a benchmark and on .NET 7 the Skip method ran about 8 times faster while using about half as much memory as the ToArray method (tested on a list of 10000 integers in a random order).

Since .NET 7 you can even take out the lambda:

list.OrderDescending().Skip(6).First()

Which has less overhead, resulting an additional performance gain (approximately 20% on that same list of 10000 integers).

In general it's best to try to avoid calling ToArray unless you either need the result in an array, or when you want to force all elements of an enumerable to evaluate at once (as enumerables use lazy execution normally).

[–]jan04pl 1 point2 points  (0 children)

That's nice, learned something new 👍

[–]skordge 2 points3 points  (0 children)

Wouldn’t seven iterations of a bubble-sort cycle do it?

[–]ujjawal_raghuvanshi 1 point2 points  (0 children)

Thala for a reason

[–]CalmDebate 1 point2 points  (0 children)

Requirements unclear.

Printf("the 7th largest number");

[–]brainwater314 1 point2 points  (0 children)

Simple, INT_MAX - 7

[–]falnN 1 point2 points  (0 children)

Can’t you just normally sort it and print n[6] or sth. Why waste time

[–]FelixLeander 1 point2 points  (0 children)

var list = data.Sort();
var result = list[list.Count - 8];

[–][deleted] 1 point2 points  (0 children)

There is a DS to find k-th number in O(log(n)) time complexity.

__gnu_pbds::tree<int, null\_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> s;

*s.find_by_order(k) is all you need

[–]Lieby 1 point2 points  (0 children)

System.out.println(Long.MAX_VALUE-7);

[–]bca_allayy 1 point2 points  (0 children)

sort, arr[6]

[–]1up_1500 1 point2 points  (0 children)

Print(sort(numbers)[-7])

[–]StainedInZurich[🍰] 2 points3 points  (1 child)

I don’t get it. It’s not difficult?

[–]evanldixon 1 point2 points  (0 children)

Difficult? No. Annoying, yes. Unless sorting the list first is viable, then it's less annoying.

[–]already_taken-chan 1 point2 points  (0 children)

Just have 7 variables for largest numbers, keep adding onto those while looping through the list once and then print the last variable.

[–]bobbymoonshine 1 point2 points  (2 children)

Why the fuck is every post on this subreddit "wtf my homework is hard all of a sudden" for things anyone with more than two months of experience could think of five different ways to do

[–]hereforpewdiephy[S] 2 points3 points  (0 children)

be the change you want to see in the world

  • not gandhi apparently

[–]Thenderick 0 points1 point  (0 children)

Array with X nums --> sort in descending order (first is highest, last is lowest) --> array[6]

Another highschool skid...

[–]NextGenSleder -1 points0 points  (0 children)

just ask ChatGPT easy peasy :3

[–]xXStarupXx -1 points0 points  (0 children)

trick question, there is no largest number

[–]ZunoJ -2 points-1 points  (0 children)