ETernaryState, where the third state represents Unknown, has its place. It prevents you from having to do Optional<Boolean> isPresent or ifPresent checks all over the place and standardizes code use case.
Use a while loop. Alternatively, use recursion. Alternatively to that, construct a HashSet from the array and check if it has less elements than the array.
Alternatively, copy and paste 1000000 if statements to manually check each element, add additional if statements to cover all bases of course. I see no problem with this practice whatsoever.
Just to confirm, would the ideal solution be to keep count of every value in a hashtable, and if we encounter a value that already has a count of 1, we return true?
A hashtable is not needed, you can do with a hashset as you only care about if a number has appeared twice. The first time its not in the hashset so you add it and the second time you abort execution and return that the list contains duplicates.
Bucket sort only approaches O(n) when the number of buckets approaches nand you get a good distribution from your input keys to the buckets (i.e., you don't cluster many values into just a few available buckets).
Which is basically what a hashtable is going to do: bucketize the input, and you can abort early when you detect a duplicate.
I see. I thought its obvious that an O notation usually has some criteria but I guess it wasn't. Neither was it that you'd implement bucket sort with a hash map and not an array. Because that's very likely more memory efficient. So thanks for pointing that out I guess.
Well, a hashmap (generic term, not talking about a specific language) puts elements into buckets. How you choose to arrange those buckets in memory is up to the implementation. Same thing for handling collisions: you can resolve collisions in many ways, such as using a linked list or array, or using another internal hashmap with a different function.
The average case of bucket sort, from what I read, is technically O(n+(n²/k)+k) where k is numBuckets, but that simplifies to O(n) when n â k, but that still assumes you avoid a lot of clustering.
Yeah correct. I expected that to be clear to everyone but that wasnt the case. As you can see you come to the same conclusion as I stated to begin with: you can sort in O(n) with bucket sort.
I didnt want to elaborate on this because this wasnt about how to sort a dataset but how to find out if it has duplicates. And any sorting algorithm will always iterate over the whole dataset which is not optimal. So I said youll be even more faster if you abort when you found a duplicate instead of running through the whole dataset even if you have perfect conditions for the sorting algorithm.
Im hindsight its clear how that was too few information and that I assumed too much.
I read his "sorted list" as set or map, because there's no other default container which has inbuilt sorting (unless I forgot one).
And you don't need to check for an existing number in those cases, because on insertion they either throw an exception or return the previous non-null value which renders the recommended check moot.
Sets and maps do not have builtin sorting. Sets and maps don't consider their contents to be in any particular order at all: not sorting order, not insertion order, nothing.
I believe both sets and maps maintain their keys in a sorted order in the C++ stl. It uses "less" by default but you can also provide your own compare function.
For "set" and "map", I believe you're right, but you really should use "unordered_set" and "unordered_map", to get the typical O(1) access, insertion, removal.
I think the typical "sorted set" implementation uses some sort of balancing binary tree to get better access and insertion times.
That really depends on the implementation, e.g. in java a TreeSet actually creates an order and so demands that the objects are comparable. A HashSet doesnt but also does not keep order. Generally speaking there is the option for both.
There are subtypes that provide ordering, but the general concept of a set does not. This is true regardless of language, but Java models it well: Set is not ordered; SortedSet, a subtype of Set, is.
I don't understand what they're trying to do. Why is the for loop iterating up to length²?
Update: oh I see now...by going up to the square and then using modulo, for example for an array of 4 it will compare index 0 against 1,2,3, then index 1 against 0,2,4, then index 2 against 0,1,3.
Clever execution but seems expensive AF and with lots of redundancy. Although having return true rather than setting a variable and returning at the end of the loop could potentially reduce that cost (only if a duplicate were present)
This would be the simpler way to write the same algorithm. It runs length² times because it's two loops inside one another. OPs friend just used a very hacky way so he can only use a single index
For even more improved performance you can just do the single loop through. Push every found number to a hashtable. And return true whenever any number already exists in said hash table.
Technically? But that's a niche situation and at that point you may have bigger problems. Not to mention that in this case an efficient algorithm is all the more important.
Sure, but creating a hash and copying data aka performing a white into a new hash table is far more expensive than doing the two loops - especially for certain lengths of num[].
Worst case, we both compute a hash for each object in an array - but I'm not blowing up the cache by creating a new copy of the data, nor am I waiting on reads and writes to storage - malloc() is slow, and if you have "images" in your array you will be doing malloc() over and over as you create a new hash for every image - or worse, resize an existing area.
In short, no, sorry, you're still wrong for the reasons I mention.
People are discussing complexity and variable naming while the author does not appear to be aware loops can actually be nested... If I was an interviewer reading the code this will be my conclusion.
Whatever the compiler is doing behind the scenes, a developer looking at that code still has to figure out how the three variables are related to each other.
Yes it does. The variable is just a nice name for a ram address and the address aswell as the value in that address change all the time. This is the most not constant possible. A constant is a fixed address with a fixed value that gets initialized on process start and stays like that until program end.
To communicate that in code there are some keywords like const in C, final in Java and the likes. Some even have some prohibition functions included to stop the developer from changing a constant but that usually only affects the ram address. Only for primitive data both values get frozen by the compiler.
class Solution {
public boolean containsDuplicate(int[] nums) {
boolean trueFalse = false;
for (int i = 0; i < (nums.length * nums.length); i++){
int x = i / nums.length;
int y = i % nums.length;
if (x != y && nums[y] == nums[x]){
trueFalse = true;
}
}
return trueFalse;
}
}
I wonder if the prompt said it can be solved in O(n) so they thought that means they should have a single loop but cannot have a nested loop aaaaandâŚ. Voila!
The reason it won't accept is usually leetcode has a time quota for solutions and since this is a O(n²) solution it would take really long for bigger arrays that leetcode might be testing for. Specifically since this question can be solved in O(n)
How would X advance to being anything but 0 in this language?
Any number less than length/length (which the loop never makes it up to) is going to be truncated to an integer, and that integer is 0.
Edit: As Jahill2000 pointed out - they are incrementing len*len. Nevermind. Why do two loops when you can do one loop twice as long, but still with too many variables. /s
Ah, yep. I didn't pay attention to the loop condition too closely....got focused on the "why in God's name are they doing the two slowest uops just to check for dupes?!"
Despite the horrible code, the main problem is that the solution only works for small arrays when the multiplication of the length doesnât overflow ints
682
u/pittybrave Jan 13 '23
lol honestly the worst thing here is naming a boolean trueFalse. literally horrific
134
u/whizvox int getRand() { return 4; } Jan 13 '23
Assignment: Complete this challenge with only one for-loop.
115
u/[deleted] Jan 13 '23
Well, it's unnecessarily slower (div and mod) and does redundant comparisons
35
u/illyay Jan 13 '23
Because thereâs a Boolean named trueFalse which made the compiler have an existential crisis
82
u/kristallnachte Jan 13 '23
That's honestly not the stupidest way to do that.
It's not like good...or super clear, but using just the one variable to track both array indexes is novel.
11
u/MurdoMaclachlan public boolean isInt(int i) { return true; } Jan 13 '23
Image Transcription: Code
I'm a human volunteer content transcriber and you could be too! If you'd like more information on what we do and why we do it, click here!
17
u/ComputerSystemsProf Jan 13 '23
I wonder if the prompt said it can be solved in O(n) so they thought that means they should have a single loop but cannot have a nested loop aaaaandâŚ. Voila!
6
u/oakskog Jan 13 '23
6
u/YATA1242 Jan 13 '23
Everyone can code⌠some people can code well
4
u/shizzy0 Jan 13 '23
Use return true and itâs almost clever.
3
u/Environmental-Egg276 Jan 13 '23
Why tf would you name a boolean trueFalse?
3
u/lazyygothh Jan 13 '23
I know nothing about code and donât understand
4
u/madhousechild Jan 13 '23
Do the constraints allow nums.length to be zero?
2
u/GodlessAristocrat Jan 13 '23 edited Jan 13 '23
How would X advance to being anything but 0 in this language?
Any number less than length/length (which the loop never makes it up to) is going to be truncated to an integer, and that integer is 0.
Edit: As Jahill2000 pointed out - they are incrementing len*len. Nevermind. Why do two loops when you can do one loop twice as long, but still with too many variables. /s
1
u/paspielka Jan 13 '23
Pretty sure you donât need that if statement you can just return it also no indentation after the x, y variables. What can i say default java user.
1
u/menjav Jan 13 '23
Despite the horrible code, the main problem is that the solution only works for small arrays when the multiplication of the length doesnât overflow ints
1
u/commit_bat Jan 13 '23
I'll take truefalse over Foo and bar
1
u/[deleted] Jan 14 '23
nums.length * nums.length⌠if only there was some handy operation to simplify this expressionâŚ
1
u/InevitableOne7496 Jan 14 '23
I donât know shit and I know this is stupid
1
u/donnert Jan 14 '23
"Asking for a friend" - that's funny!
-3
u/Detroit06 Jan 13 '23
Because it's Java /s