• Log InLog In
  • Register
Liquid`
Team Liquid Liquipedia
EDT 04:11
CEST 10:11
KST 17:11
  • Home
  • Forum
  • Calendar
  • Streams
  • Liquipedia
  • Features
  • Store
  • EPT
  • TL+
  • StarCraft 2
  • Brood War
  • Smash
  • Heroes
  • Counter-Strike
  • Overwatch
  • Liquibet
  • Fantasy StarCraft
  • TLPD
  • StarCraft 2
  • Brood War
  • Blogs
Forum Sidebar
Events/Features
News
Featured News
Serral wins HomeStory Cup 297Serral wins Maestros of the Game 243ByuL, and the Limitations of Standard Play3Team Liquid Map Contest #22: Results and Winners7Code S Season 2 (2026): RO4 and Finals Preview12
Community News
BSL Season 22 Full Overview & Conclusion7BSL Season 22 Full Overview & Conclusion7Weekly Cups (June 29-July 5): Solar Doubles0MC vs IdrA, Boxer vs Nal_rA to be Legacy Matches @ BlizzCon445.0.16 Hotfix (June 30) - Balance + Bug Fixes40
StarCraft 2
General
Serral wins HomeStory Cup 29 Serral wins Maestros of the Game 2 Reynor: GSL Loss Wasn't About Preparation Format 5.0.16 patch for SC2 goes live (8 worker start) What is your PC setup in 2026 for SCBW/SC2 ?
Tourneys
GSL CK #5 Race War WardiTV Summer Cup 2026 RSL Revival: Season 6 - Qualifiers and Main Event HomeStory Cup 29 Vespene Cup #1 — $300+ USD, July 10
Strategy
[G] Having the right mentality to improve
Custom Maps
New Map Maker - Looking for Advice - Love or Hate Work In Progress Melee Maps [D]RTS in all its shapes and glory <3
External Content
The PondCast: SC2 News & Results Mutation # 534 Burning Evacuation Mutation # 533 Die Together Mutation # 532 Nuclear Family
Brood War
General
ASL 22 Proposed Map Pool ASL22 General Discussion Pros Debate: Zerg Unfairly Nerfed? (ASL S22 map) BSL Season 22 Full Overview & Conclusion BGH Auto Balance -> http://bghmmr.eu/
Tourneys
[ASL22] Wildcard Qualifier IPSL Spring 2026 Top 4! [Megathread] Daily Proleagues CSLAN 4 is Coming!
Strategy
Fighting Spirit mining rates Simple Questions, Simple Answers Creating a full chart of Zerg builds Relatively freeroll strategies
Other Games
General Games
Stormgate/Frost Giant Megathread General RTS Discussion Thread Path of Exile Summer Games Done Quick 2026! Nintendo Switch Thread
Dota 2
Looking for a Dota Mentor Official 'what is Dota anymore' discussion
League of Legends
Heroes of the Storm
Simple Questions, Simple Answers Heroes of the Storm 2.0
Hearthstone
Deck construction bug
TL Mafia
NeO.D_StephenKing vs This Guy From 1 Million Dance TL Mafia Community Thread TL Mafia Power Rank Vanilla Mini Mafia
Community
General
US Politics Mega-thread Russo-Ukrainian War Thread UK Politics Mega-thread YouTube Thread Canadian Politics Mega-thread
Fan Clubs
The IdrA Fan Club The HerO Fan Club!
Media & Entertainment
Movie Discussion! Anime Discussion Thread Series you have seen recently...
Sports
2024 - 2026 Football Thread McBoner: A hockey love story Tennis[sport] Formula 1 Discussion TeamLiquid Health and Fitness Initiative For 2023
World Cup 2022
Tech Support
Simple Questions Simple Answers FPS when play League Of Legend on laptop How to clean a TTe Thermaltake keyboard?
TL Community
The Automated Ban List
Blogs
Major Shifts in the Gaming I…
TrAiDoS
An Exploration of th…
waywardstrategy
Gauntlet SC2: A Retrospectiv…
Ctone23
ramps on octagon
StaticNine
Funny Nicknames
LUCKY_NOOB
Evil Gacha Games and the…
ffswowsucks
StarCraft improvement
iopq
Customize Sidebar...

Website Feedback

Closed Threads



Active: 3795 users

The Big Programming Thread - Page 378

Forum Index > General Forum
Post a Reply
Prev 1 376 377 378 379 380 1032 Next
Thread Rules
1. This is not a "do my homework for me" thread. If you have specific questions, ask, but don't post an assignment or homework problem and expect an exact solution.
2. No recruiting for your cockamamie projects (you won't replace facebook with 3 dudes you found on the internet and $20)
3. If you can't articulate why a language is bad, don't start slinging shit about it. Just remember that nothing is worse than making CSS IE6 compatible.
4. Use [code] tags to format code blocks.
waxypants
Profile Blog Joined September 2009
United States479 Posts
October 21 2013 17:45 GMT
#7541
On October 21 2013 06:01 EscPlan9 wrote:
Show nested quote +
On October 21 2013 02:34 phar wrote:
On October 20 2013 22:33 Mstring wrote:
On October 20 2013 21:58 gedatsu wrote:
On October 20 2013 09:18 EscPlan9 wrote:
On October 20 2013 04:58 spinesheath wrote:
On October 20 2013 04:33 phar wrote:
On October 20 2013 02:38 gedatsu wrote:
On October 20 2013 02:07 phar wrote:
On October 20 2013 01:03 gedatsu wrote:
[quote]
Suppose arr = [2000000000,2000000000,1]
Your hash vector will get really long.

Not only that, but the function will fail due to hash collisions. So two open things to solve:

1) What if input is larger than memory
2) What if two numbers hash to the same hash value

He can't get hash collisions as he is using the value itself as its hash. But yeah, with a more sane hash function you can get collisions. Use the built-in hash table here.

Yea sorry I was getting a step ahead of himself. I meant that after he solves the problem you pointed out (identity hash function), he will then have to solve the problem of hash collisions.

The idea is to not try to implement the hashtable yourself, but to just use an existing one instead. Those come with built in strategies for collisions.


I'm very confused by the responses here. I wasn't implementing a hash table myself. I was using built-in hash structures found in most languages, in the code above it was Javascript. If a key is found, you can detect it and handle it however you want - in this case all I do is change the value because I found another instance of the element. If a key is not found, one is created. Pretty simple...

As to "what if two numbers hash to the same hash value"? How does that even matter. Like if you run the code above, you'll find out the Keys '1', '2', and '3' all have a value of 2, and the Key '4' has a value of 1. The crux of the problem was to find non-duplicate elements in an array. So all non-duplicate elements would have a value of 1... and that's it. It doesn't matter if they hash to the same value - as long as the value is 1 in my solution, then we found a unique element in the array.

I've never used javascript so I may be wrong, but it seems like you're not using a hash table at all. Instead you're just using a regular array and naming it "hash". That is not what a hash table is.

Lol! If only you spent ten seconds googling before you posted so you could have known just how wrong you indeed are XD

He's not entirely wrong. It's not an array, but it's also not a hash table. It's object (why [object Object] of course, what else is there in js? lol), which has a few key differences from an actual hash table. See here for more detail:

http://stackoverflow.com/questions/368280/javascript-hashmap-equivalent


Javascript is pretty lol indeed. Yes, to be 100% accurate, it is not a hash table. It is just an object that can be used similarly to a hash table. I've been using Javascript exclusively at work lately so I happened to write it in Javascript. If I remember correctly, Perl also can make use of hash tables just as simply.


idk about js and perl, but in python you can. the responses to your solution were brain-exploding indeed.
gedatsu
Profile Joined December 2011
1286 Posts
October 21 2013 18:36 GMT
#7542
On October 22 2013 02:45 waxypants wrote:
Show nested quote +
On October 21 2013 06:01 EscPlan9 wrote:
On October 21 2013 02:34 phar wrote:
On October 20 2013 22:33 Mstring wrote:
On October 20 2013 21:58 gedatsu wrote:
On October 20 2013 09:18 EscPlan9 wrote:
On October 20 2013 04:58 spinesheath wrote:
On October 20 2013 04:33 phar wrote:
On October 20 2013 02:38 gedatsu wrote:
On October 20 2013 02:07 phar wrote:
[quote]
Not only that, but the function will fail due to hash collisions. So two open things to solve:

1) What if input is larger than memory
2) What if two numbers hash to the same hash value

He can't get hash collisions as he is using the value itself as its hash. But yeah, with a more sane hash function you can get collisions. Use the built-in hash table here.

Yea sorry I was getting a step ahead of himself. I meant that after he solves the problem you pointed out (identity hash function), he will then have to solve the problem of hash collisions.

The idea is to not try to implement the hashtable yourself, but to just use an existing one instead. Those come with built in strategies for collisions.


I'm very confused by the responses here. I wasn't implementing a hash table myself. I was using built-in hash structures found in most languages, in the code above it was Javascript. If a key is found, you can detect it and handle it however you want - in this case all I do is change the value because I found another instance of the element. If a key is not found, one is created. Pretty simple...

As to "what if two numbers hash to the same hash value"? How does that even matter. Like if you run the code above, you'll find out the Keys '1', '2', and '3' all have a value of 2, and the Key '4' has a value of 1. The crux of the problem was to find non-duplicate elements in an array. So all non-duplicate elements would have a value of 1... and that's it. It doesn't matter if they hash to the same value - as long as the value is 1 in my solution, then we found a unique element in the array.

I've never used javascript so I may be wrong, but it seems like you're not using a hash table at all. Instead you're just using a regular array and naming it "hash". That is not what a hash table is.

Lol! If only you spent ten seconds googling before you posted so you could have known just how wrong you indeed are XD

He's not entirely wrong. It's not an array, but it's also not a hash table. It's object (why [object Object] of course, what else is there in js? lol), which has a few key differences from an actual hash table. See here for more detail:

http://stackoverflow.com/questions/368280/javascript-hashmap-equivalent


Javascript is pretty lol indeed. Yes, to be 100% accurate, it is not a hash table. It is just an object that can be used similarly to a hash table. I've been using Javascript exclusively at work lately so I happened to write it in Javascript. If I remember correctly, Perl also can make use of hash tables just as simply.


idk about js and perl, but in python you can. the responses to your solution were brain-exploding indeed.

Do you really think it is "brain-exploding indeed" to not assume that something declared as being equal to {} (with such brackets being used to initialize arrays in the C family, by far the world's primary group of programming languages), and being indexed as an array, is in fact not an array but an entirely different and more complex data structure?

Your brain must explode quite often, then. My condolences.
Shield
Profile Blog Joined August 2009
Bulgaria4824 Posts
October 21 2013 19:01 GMT
#7543
What GUI builder should I choose for Java? Is this one good?
waxypants
Profile Blog Joined September 2009
United States479 Posts
October 21 2013 21:47 GMT
#7544
On October 22 2013 03:36 gedatsu wrote:
Show nested quote +
On October 22 2013 02:45 waxypants wrote:
On October 21 2013 06:01 EscPlan9 wrote:
On October 21 2013 02:34 phar wrote:
On October 20 2013 22:33 Mstring wrote:
On October 20 2013 21:58 gedatsu wrote:
On October 20 2013 09:18 EscPlan9 wrote:
On October 20 2013 04:58 spinesheath wrote:
On October 20 2013 04:33 phar wrote:
On October 20 2013 02:38 gedatsu wrote:
[quote]
He can't get hash collisions as he is using the value itself as its hash. But yeah, with a more sane hash function you can get collisions. Use the built-in hash table here.

Yea sorry I was getting a step ahead of himself. I meant that after he solves the problem you pointed out (identity hash function), he will then have to solve the problem of hash collisions.

The idea is to not try to implement the hashtable yourself, but to just use an existing one instead. Those come with built in strategies for collisions.


I'm very confused by the responses here. I wasn't implementing a hash table myself. I was using built-in hash structures found in most languages, in the code above it was Javascript. If a key is found, you can detect it and handle it however you want - in this case all I do is change the value because I found another instance of the element. If a key is not found, one is created. Pretty simple...

As to "what if two numbers hash to the same hash value"? How does that even matter. Like if you run the code above, you'll find out the Keys '1', '2', and '3' all have a value of 2, and the Key '4' has a value of 1. The crux of the problem was to find non-duplicate elements in an array. So all non-duplicate elements would have a value of 1... and that's it. It doesn't matter if they hash to the same value - as long as the value is 1 in my solution, then we found a unique element in the array.

I've never used javascript so I may be wrong, but it seems like you're not using a hash table at all. Instead you're just using a regular array and naming it "hash". That is not what a hash table is.

Lol! If only you spent ten seconds googling before you posted so you could have known just how wrong you indeed are XD

He's not entirely wrong. It's not an array, but it's also not a hash table. It's object (why [object Object] of course, what else is there in js? lol), which has a few key differences from an actual hash table. See here for more detail:

http://stackoverflow.com/questions/368280/javascript-hashmap-equivalent


Javascript is pretty lol indeed. Yes, to be 100% accurate, it is not a hash table. It is just an object that can be used similarly to a hash table. I've been using Javascript exclusively at work lately so I happened to write it in Javascript. If I remember correctly, Perl also can make use of hash tables just as simply.


idk about js and perl, but in python you can. the responses to your solution were brain-exploding indeed.

Do you really think it is "brain-exploding indeed" to not assume that something declared as being equal to {} (with such brackets being used to initialize arrays in the C family, by far the world's primary group of programming languages), and being indexed as an array, is in fact not an array but an entirely different and more complex data structure?

Your brain must explode quite often, then. My condolences.


1) It's obviously not C. It seems there are at least a handful of languages which use this syntax for associative arrays.
2) There is an obvious array declaration right above which uses a different bracket syntax.
3) Everybody (not just you) seemed to be assuming that { } was syntax for a naive dynamic sparse array, which is quite a weird assumption.
4) It's fine to not know the syntax, but instead of checking, people started making weird assumptions and stating things as fact as if they actually knew. This, leading up to a condescending post boiling down to "learn your data structures bro".

Ok my brain didn't explode, but it hurt a little bit while skimming through the posts.
n0ah
Profile Joined June 2011
United States250 Posts
October 21 2013 22:03 GMT
#7545
Is there anything like a "light-weight" C compiler? I want to re-teach myself C in my free time, but I don't want to install a bunch of resource-heavy software. Any suggestions?
If this is to end in fire, then we will all burn together
waxypants
Profile Blog Joined September 2009
United States479 Posts
October 21 2013 22:05 GMT
#7546
On October 19 2013 20:07 wherebugsgo wrote:
Show nested quote +
On October 19 2013 16:33 spinesheath wrote:
On October 19 2013 15:55 wherebugsgo wrote:
You're given an array of numbers such that every element in the array is duplicated except for one. Provide an efficient algorithm to determine the singleton element.

Is that the exact wording of the question? Does "duplicated" mean that the duplicate and the original are in unrelated slots of the array, or are they adjacent? Can there be multiple sets of duplicates of the same number, as in 2, 4, 6 of the number? What range are the numbers from?

Then there also is the question how one defines efficient. It's an inefficient use of programmer time if you don't just use some stupid algorithm that works and is easy to read and understand. Unless that piece of code is a performance bottleneck that needs to be faster. But I'm going to assume that low execution time is the goal here anyways.


I paraphrased, but basically you can expect to encounter two of every element in the array except for one element. The array is unsorted and the duplicates can appear anywhere. There won't be multiple (read: more than 2) instances of the same number, though the answer would remain the same for even-number duplicates-i.e. you could have 4 of the same number and 2 of another and 6 of another and finding the singleton still works the same.

There is no specification on the range of the numbers, though you can assume that you won't need multiple data structures to represent a single number. i.e. if it makes it easier for you, assume they are 32 bit ints or whatever.

My first solution required O(nlogn) time, and O(1) space. I pretty quickly realized that the time complexity can be improved to O(n) time and there's a relatively simple way of doing that by adding a data structure that takes O(n) space, but the "brilliant" answer (as the interviewer described it-I'd call it elegant) requires no additional space and is also O(n) time.

+ Show Spoiler [my shitty answer] +
Sort the array, then step through the array until you find that two consecutive elements are not the same. Sorting takes O(nlogn) time and stepping through the array takes O(n) time; O(nlogn + n) is in O(nlogn).

You could use radix sort and get an O(n) sort, I suppose.


+ Show Spoiler [an approximately equally shitty answer] +
Instead of sorting the array, maintain a hash table and a second sum variable. Iterate through the array and for each integer, check if it's in the hash table. If it isn't, then add it to the sum, and store it. If it is, then subtract it from the sum. When we've gone through the entire array, the singleton is the only element we never subtracted, thus the sum variable is the singleton.

This works in O(n) time since hash accesses are O(1), and we need O(n) space for the hash table.


+ Show Spoiler [the model answer] +

Just iterate through the array and XOR everything together. A[0] XOR A[1] XOR .... XOR A[n]. The result of this computation is the singleton element.

This works since XOR is commutative and associative. a XOR a is just 0, and 0 XOR a is a. Since all of the elements are duplicated except one of them, all the duplicates will XOR out to 0 and then the singleton will be left at the end.

This holds true also for arrays in which you have even multiples of elements, not just duplicates, though it fails when there are odd multiples.


If you guys like this sort of stuff or need interview practice, here's a few more interesting problems I encountered at career fairs/interviews and company visit sessions:

1. This problem is similar to the one I posed before, but it has a pretty major twist.

The problem statement is to find the missing integer in the array with the following rules:

a. An array A contains every integer from 0 to N except for one of them.
b. The elements of the array A may appear in any order.
c. We can't actually access an entire element of the array all at once. In other words if you index the array you won't get back the whole element. + Show Spoiler +
in other words, normally if you access an array element at index i, you would call A[i] and you would be returned the element at the ith position in A. In this problem you can't do that.
Instead, what you can do is ask for the jth bit of the ith element of the array. In other words, I could ask for the 4th bit of the first element of A, and I would be returned the bit in the 4th position of the element ordinarily given by A[0].
d. The algorithm must return the missing integer by looking through at most O(N) bits.




2. Give an approach (or code) to writing an equivalent of the C function atoi. + Show Spoiler +
I've also been asked how to implement strlen
If you're not a C programmer, atoi is a function that converts an ASCII string to an integer. Describe the limitations or shortcomings of your approch (or code) in as much detail as you can.




3. Suppose we have a function that computes rand2() (i.e. a fair coin toss-it outputs 1 or 2 with equal probability). Design an algorithm that uses this function to simulate a fair die roll, i.e. a function that should output a random number from 1 to 6 with equal probability.



I don't really understand the bit lookup constraint on problem 1. What do you mean by "looking through at most O(N) bits". O(N) is not an amount, it's a complexity. So are you trying to say "at most N bits", or are you trying to say that the number of lookups should not increase more than linearly with N? I don't see how it could be the first, so I'm going to assume the second. If I further assume that the integers are of a fixed size (32-bit unsigned integers for example), then I can trivially write a function to bypass your constraints with the number of lookups varying linearly with N. If N has no upper limit in the problem, then technically I believe the trivial bypass becomes N*log(N). Please clarify, BUT
+ Show Spoiler +

I think the problem can be solved using the XOR trick again like the other problem. In the other problem, numbers were in equal pairs, so XORing them canceled out all except the one without a pair. In this problem, every number has a pair (0, N), (1, N-1), (2, N-2), etc. If you invert all numbers greater than N/2 prior to XORing, then you have equal pairs again. By invert, I mean invert(x) = N - x. I think the remaining XOR sum will either be the missing number or its inverse (it depends on how many inversions you did while traversing the list). Of course, all of this is assuming I am allowed to trivially bypass your constraint

gedatsu
Profile Joined December 2011
1286 Posts
October 21 2013 22:15 GMT
#7547
On October 22 2013 07:05 waxypants wrote:
Show nested quote +
On October 19 2013 20:07 wherebugsgo wrote:
On October 19 2013 16:33 spinesheath wrote:
On October 19 2013 15:55 wherebugsgo wrote:
You're given an array of numbers such that every element in the array is duplicated except for one. Provide an efficient algorithm to determine the singleton element.

Is that the exact wording of the question? Does "duplicated" mean that the duplicate and the original are in unrelated slots of the array, or are they adjacent? Can there be multiple sets of duplicates of the same number, as in 2, 4, 6 of the number? What range are the numbers from?

Then there also is the question how one defines efficient. It's an inefficient use of programmer time if you don't just use some stupid algorithm that works and is easy to read and understand. Unless that piece of code is a performance bottleneck that needs to be faster. But I'm going to assume that low execution time is the goal here anyways.


I paraphrased, but basically you can expect to encounter two of every element in the array except for one element. The array is unsorted and the duplicates can appear anywhere. There won't be multiple (read: more than 2) instances of the same number, though the answer would remain the same for even-number duplicates-i.e. you could have 4 of the same number and 2 of another and 6 of another and finding the singleton still works the same.

There is no specification on the range of the numbers, though you can assume that you won't need multiple data structures to represent a single number. i.e. if it makes it easier for you, assume they are 32 bit ints or whatever.

My first solution required O(nlogn) time, and O(1) space. I pretty quickly realized that the time complexity can be improved to O(n) time and there's a relatively simple way of doing that by adding a data structure that takes O(n) space, but the "brilliant" answer (as the interviewer described it-I'd call it elegant) requires no additional space and is also O(n) time.

+ Show Spoiler [my shitty answer] +
Sort the array, then step through the array until you find that two consecutive elements are not the same. Sorting takes O(nlogn) time and stepping through the array takes O(n) time; O(nlogn + n) is in O(nlogn).

You could use radix sort and get an O(n) sort, I suppose.


+ Show Spoiler [an approximately equally shitty answer] +
Instead of sorting the array, maintain a hash table and a second sum variable. Iterate through the array and for each integer, check if it's in the hash table. If it isn't, then add it to the sum, and store it. If it is, then subtract it from the sum. When we've gone through the entire array, the singleton is the only element we never subtracted, thus the sum variable is the singleton.

This works in O(n) time since hash accesses are O(1), and we need O(n) space for the hash table.


+ Show Spoiler [the model answer] +

Just iterate through the array and XOR everything together. A[0] XOR A[1] XOR .... XOR A[n]. The result of this computation is the singleton element.

This works since XOR is commutative and associative. a XOR a is just 0, and 0 XOR a is a. Since all of the elements are duplicated except one of them, all the duplicates will XOR out to 0 and then the singleton will be left at the end.

This holds true also for arrays in which you have even multiples of elements, not just duplicates, though it fails when there are odd multiples.


If you guys like this sort of stuff or need interview practice, here's a few more interesting problems I encountered at career fairs/interviews and company visit sessions:

1. This problem is similar to the one I posed before, but it has a pretty major twist.

The problem statement is to find the missing integer in the array with the following rules:

a. An array A contains every integer from 0 to N except for one of them.
b. The elements of the array A may appear in any order.
c. We can't actually access an entire element of the array all at once. In other words if you index the array you won't get back the whole element. + Show Spoiler +
in other words, normally if you access an array element at index i, you would call A[i] and you would be returned the element at the ith position in A. In this problem you can't do that.
Instead, what you can do is ask for the jth bit of the ith element of the array. In other words, I could ask for the 4th bit of the first element of A, and I would be returned the bit in the 4th position of the element ordinarily given by A[0].
d. The algorithm must return the missing integer by looking through at most O(N) bits.




2. Give an approach (or code) to writing an equivalent of the C function atoi. + Show Spoiler +
I've also been asked how to implement strlen
If you're not a C programmer, atoi is a function that converts an ASCII string to an integer. Describe the limitations or shortcomings of your approch (or code) in as much detail as you can.




3. Suppose we have a function that computes rand2() (i.e. a fair coin toss-it outputs 1 or 2 with equal probability). Design an algorithm that uses this function to simulate a fair die roll, i.e. a function that should output a random number from 1 to 6 with equal probability.



I don't really understand the bit lookup constraint on problem 1. What do you mean by "looking through at most O(N) bits". O(N) is not an amount, it's a complexity. So are you trying to say "at most N bits", or are you trying to say that the number of lookups should not increase more than linearly with N? I don't see how it could be the first, so I'm going to assume the second. If I further assume that the integers are of a fixed size (32-bit unsigned integers for example), then I can trivially write a function to bypass your constraints with the number of lookups varying linearly with N. If N has no upper limit in the problem, then technically I believe the trivial bypass becomes N*log(N). Please clarify, BUT
+ Show Spoiler +

I think the problem can be solved using the XOR trick again like the other problem. In the other problem, numbers were in equal pairs, so XORing them canceled out all except the one without a pair. In this problem, every number has a pair (0, N), (1, N-1), (2, N-2), etc. If you invert all numbers greater than N/2 prior to XORing, then you have equal pairs again. By invert, I mean invert(x) = N - x. I think the remaining XOR sum will either be the missing number or its inverse (it depends on how many inversions you did while traversing the list). Of course, all of this is assuming I am allowed to trivially bypass your constraint


You cannot assume fixed size numbers, and you are correct in assuming the second understanding of O(N). But, to xor two numbers together, you must look at all of their bits, i.e. 2*logN bit accesses, which will lead you to O(NlogN) accesses total.

I solved the problem on the previous page if you're interested.
waxypants
Profile Blog Joined September 2009
United States479 Posts
October 21 2013 22:17 GMT
#7548
On October 22 2013 07:05 waxypants wrote:
Show nested quote +
On October 19 2013 20:07 wherebugsgo wrote:
On October 19 2013 16:33 spinesheath wrote:
On October 19 2013 15:55 wherebugsgo wrote:
You're given an array of numbers such that every element in the array is duplicated except for one. Provide an efficient algorithm to determine the singleton element.

Is that the exact wording of the question? Does "duplicated" mean that the duplicate and the original are in unrelated slots of the array, or are they adjacent? Can there be multiple sets of duplicates of the same number, as in 2, 4, 6 of the number? What range are the numbers from?

Then there also is the question how one defines efficient. It's an inefficient use of programmer time if you don't just use some stupid algorithm that works and is easy to read and understand. Unless that piece of code is a performance bottleneck that needs to be faster. But I'm going to assume that low execution time is the goal here anyways.


I paraphrased, but basically you can expect to encounter two of every element in the array except for one element. The array is unsorted and the duplicates can appear anywhere. There won't be multiple (read: more than 2) instances of the same number, though the answer would remain the same for even-number duplicates-i.e. you could have 4 of the same number and 2 of another and 6 of another and finding the singleton still works the same.

There is no specification on the range of the numbers, though you can assume that you won't need multiple data structures to represent a single number. i.e. if it makes it easier for you, assume they are 32 bit ints or whatever.

My first solution required O(nlogn) time, and O(1) space. I pretty quickly realized that the time complexity can be improved to O(n) time and there's a relatively simple way of doing that by adding a data structure that takes O(n) space, but the "brilliant" answer (as the interviewer described it-I'd call it elegant) requires no additional space and is also O(n) time.

+ Show Spoiler [my shitty answer] +
Sort the array, then step through the array until you find that two consecutive elements are not the same. Sorting takes O(nlogn) time and stepping through the array takes O(n) time; O(nlogn + n) is in O(nlogn).

You could use radix sort and get an O(n) sort, I suppose.


+ Show Spoiler [an approximately equally shitty answer] +
Instead of sorting the array, maintain a hash table and a second sum variable. Iterate through the array and for each integer, check if it's in the hash table. If it isn't, then add it to the sum, and store it. If it is, then subtract it from the sum. When we've gone through the entire array, the singleton is the only element we never subtracted, thus the sum variable is the singleton.

This works in O(n) time since hash accesses are O(1), and we need O(n) space for the hash table.


+ Show Spoiler [the model answer] +

Just iterate through the array and XOR everything together. A[0] XOR A[1] XOR .... XOR A[n]. The result of this computation is the singleton element.

This works since XOR is commutative and associative. a XOR a is just 0, and 0 XOR a is a. Since all of the elements are duplicated except one of them, all the duplicates will XOR out to 0 and then the singleton will be left at the end.

This holds true also for arrays in which you have even multiples of elements, not just duplicates, though it fails when there are odd multiples.


If you guys like this sort of stuff or need interview practice, here's a few more interesting problems I encountered at career fairs/interviews and company visit sessions:

1. This problem is similar to the one I posed before, but it has a pretty major twist.

The problem statement is to find the missing integer in the array with the following rules:

a. An array A contains every integer from 0 to N except for one of them.
b. The elements of the array A may appear in any order.
c. We can't actually access an entire element of the array all at once. In other words if you index the array you won't get back the whole element. + Show Spoiler +
in other words, normally if you access an array element at index i, you would call A[i] and you would be returned the element at the ith position in A. In this problem you can't do that.
Instead, what you can do is ask for the jth bit of the ith element of the array. In other words, I could ask for the 4th bit of the first element of A, and I would be returned the bit in the 4th position of the element ordinarily given by A[0].
d. The algorithm must return the missing integer by looking through at most O(N) bits.




2. Give an approach (or code) to writing an equivalent of the C function atoi. + Show Spoiler +
I've also been asked how to implement strlen
If you're not a C programmer, atoi is a function that converts an ASCII string to an integer. Describe the limitations or shortcomings of your approch (or code) in as much detail as you can.




3. Suppose we have a function that computes rand2() (i.e. a fair coin toss-it outputs 1 or 2 with equal probability). Design an algorithm that uses this function to simulate a fair die roll, i.e. a function that should output a random number from 1 to 6 with equal probability.



I don't really understand the bit lookup constraint on problem 1. What do you mean by "looking through at most O(N) bits". O(N) is not an amount, it's a complexity. So are you trying to say "at most N bits", or are you trying to say that the number of lookups should not increase more than linearly with N? I don't see how it could be the first, so I'm going to assume the second. If I further assume that the integers are of a fixed size (32-bit unsigned integers for example), then I can trivially write a function to bypass your constraints with the number of lookups varying linearly with N. If N has no upper limit in the problem, then technically I believe the trivial bypass becomes N*log(N). Please clarify, BUT
+ Show Spoiler +

I think the problem can be solved using the XOR trick again like the other problem. In the other problem, numbers were in equal pairs, so XORing them canceled out all except the one without a pair. In this problem, every number has a pair (0, N), (1, N-1), (2, N-2), etc. If you invert all numbers greater than N/2 prior to XORing, then you have equal pairs again. By invert, I mean invert(x) = N - x. I think the remaining XOR sum will either be the missing number or its inverse (it depends on how many inversions you did while traversing the list). Of course, all of this is assuming I am allowed to trivially bypass your constraint



+ Show Spoiler +

Also, I believe you can go through one bit at a time, XORing all of the bit 0s, then all of the bit 1s, bit 2s, etc. Based on the results of each (compared to what you expect the result to be IF all the numbers were present), you can figure out the missing bit 0, bit 1, bit 2, etc. This is N*log(N) lookups though, so I'm not sure if it qualifies.

Yoshi-
Profile Joined October 2008
Germany10227 Posts
October 21 2013 22:17 GMT
#7549
I think the only appropriate solution to any of these problems, would be to reconsider why you would even run into them, since pretty much all of them are so absurd that they only should occur in terrible design.
waxypants
Profile Blog Joined September 2009
United States479 Posts
October 21 2013 22:19 GMT
#7550
On October 22 2013 07:15 gedatsu wrote:
Show nested quote +
On October 22 2013 07:05 waxypants wrote:
On October 19 2013 20:07 wherebugsgo wrote:
On October 19 2013 16:33 spinesheath wrote:
On October 19 2013 15:55 wherebugsgo wrote:
You're given an array of numbers such that every element in the array is duplicated except for one. Provide an efficient algorithm to determine the singleton element.

Is that the exact wording of the question? Does "duplicated" mean that the duplicate and the original are in unrelated slots of the array, or are they adjacent? Can there be multiple sets of duplicates of the same number, as in 2, 4, 6 of the number? What range are the numbers from?

Then there also is the question how one defines efficient. It's an inefficient use of programmer time if you don't just use some stupid algorithm that works and is easy to read and understand. Unless that piece of code is a performance bottleneck that needs to be faster. But I'm going to assume that low execution time is the goal here anyways.


I paraphrased, but basically you can expect to encounter two of every element in the array except for one element. The array is unsorted and the duplicates can appear anywhere. There won't be multiple (read: more than 2) instances of the same number, though the answer would remain the same for even-number duplicates-i.e. you could have 4 of the same number and 2 of another and 6 of another and finding the singleton still works the same.

There is no specification on the range of the numbers, though you can assume that you won't need multiple data structures to represent a single number. i.e. if it makes it easier for you, assume they are 32 bit ints or whatever.

My first solution required O(nlogn) time, and O(1) space. I pretty quickly realized that the time complexity can be improved to O(n) time and there's a relatively simple way of doing that by adding a data structure that takes O(n) space, but the "brilliant" answer (as the interviewer described it-I'd call it elegant) requires no additional space and is also O(n) time.

+ Show Spoiler [my shitty answer] +
Sort the array, then step through the array until you find that two consecutive elements are not the same. Sorting takes O(nlogn) time and stepping through the array takes O(n) time; O(nlogn + n) is in O(nlogn).

You could use radix sort and get an O(n) sort, I suppose.


+ Show Spoiler [an approximately equally shitty answer] +
Instead of sorting the array, maintain a hash table and a second sum variable. Iterate through the array and for each integer, check if it's in the hash table. If it isn't, then add it to the sum, and store it. If it is, then subtract it from the sum. When we've gone through the entire array, the singleton is the only element we never subtracted, thus the sum variable is the singleton.

This works in O(n) time since hash accesses are O(1), and we need O(n) space for the hash table.


+ Show Spoiler [the model answer] +

Just iterate through the array and XOR everything together. A[0] XOR A[1] XOR .... XOR A[n]. The result of this computation is the singleton element.

This works since XOR is commutative and associative. a XOR a is just 0, and 0 XOR a is a. Since all of the elements are duplicated except one of them, all the duplicates will XOR out to 0 and then the singleton will be left at the end.

This holds true also for arrays in which you have even multiples of elements, not just duplicates, though it fails when there are odd multiples.


If you guys like this sort of stuff or need interview practice, here's a few more interesting problems I encountered at career fairs/interviews and company visit sessions:

1. This problem is similar to the one I posed before, but it has a pretty major twist.

The problem statement is to find the missing integer in the array with the following rules:

a. An array A contains every integer from 0 to N except for one of them.
b. The elements of the array A may appear in any order.
c. We can't actually access an entire element of the array all at once. In other words if you index the array you won't get back the whole element. + Show Spoiler +
in other words, normally if you access an array element at index i, you would call A[i] and you would be returned the element at the ith position in A. In this problem you can't do that.
Instead, what you can do is ask for the jth bit of the ith element of the array. In other words, I could ask for the 4th bit of the first element of A, and I would be returned the bit in the 4th position of the element ordinarily given by A[0].
d. The algorithm must return the missing integer by looking through at most O(N) bits.




2. Give an approach (or code) to writing an equivalent of the C function atoi. + Show Spoiler +
I've also been asked how to implement strlen
If you're not a C programmer, atoi is a function that converts an ASCII string to an integer. Describe the limitations or shortcomings of your approch (or code) in as much detail as you can.




3. Suppose we have a function that computes rand2() (i.e. a fair coin toss-it outputs 1 or 2 with equal probability). Design an algorithm that uses this function to simulate a fair die roll, i.e. a function that should output a random number from 1 to 6 with equal probability.



I don't really understand the bit lookup constraint on problem 1. What do you mean by "looking through at most O(N) bits". O(N) is not an amount, it's a complexity. So are you trying to say "at most N bits", or are you trying to say that the number of lookups should not increase more than linearly with N? I don't see how it could be the first, so I'm going to assume the second. If I further assume that the integers are of a fixed size (32-bit unsigned integers for example), then I can trivially write a function to bypass your constraints with the number of lookups varying linearly with N. If N has no upper limit in the problem, then technically I believe the trivial bypass becomes N*log(N). Please clarify, BUT
+ Show Spoiler +

I think the problem can be solved using the XOR trick again like the other problem. In the other problem, numbers were in equal pairs, so XORing them canceled out all except the one without a pair. In this problem, every number has a pair (0, N), (1, N-1), (2, N-2), etc. If you invert all numbers greater than N/2 prior to XORing, then you have equal pairs again. By invert, I mean invert(x) = N - x. I think the remaining XOR sum will either be the missing number or its inverse (it depends on how many inversions you did while traversing the list). Of course, all of this is assuming I am allowed to trivially bypass your constraint


You cannot assume fixed size numbers, and you are correct in assuming the second understanding of O(N). But, to xor two numbers together, you must look at all of their bits, i.e. 2*logN bit accesses, which will lead you to O(NlogN) accesses total.

I solved the problem on the previous page if you're interested.


Ok I will think more about it then.

gedatsu
Profile Joined December 2011
1286 Posts
October 21 2013 22:19 GMT
#7551
On October 22 2013 07:17 Yoshi- wrote:
I think the only appropriate solution to any of these problems, would be to reconsider why you would even run into them, since pretty much all of them are so absurd that they only should occur in terrible design.

Boo! Hiss!
waxypants
Profile Blog Joined September 2009
United States479 Posts
October 21 2013 22:24 GMT
#7552
On October 22 2013 07:17 Yoshi- wrote:
I think the only appropriate solution to any of these problems, would be to reconsider why you would even run into them, since pretty much all of them are so absurd that they only should occur in terrible design.


Because they are fun and they stretch your brain a little bit? The process and analysis/comparison of different solutions are more important than the solution itself in terms of learning. Although, coming up with the cleverest/fastest solution is where the fun part comes in.
CorsairHero
Profile Joined December 2008
Canada9491 Posts
October 21 2013 22:29 GMT
#7553
On October 22 2013 07:03 n0ah wrote:
Is there anything like a "light-weight" C compiler? I want to re-teach myself C in my free time, but I don't want to install a bunch of resource-heavy software. Any suggestions?

cygwin or install dualboot linux for gcc
© Current year.
RoyGBiv_13
Profile Blog Joined August 2010
United States1275 Posts
Last Edited: 2013-10-21 22:35:48
October 21 2013 22:30 GMT
#7554
On October 22 2013 07:03 n0ah wrote:
Is there anything like a "light-weight" C compiler? I want to re-teach myself C in my free time, but I don't want to install a bunch of resource-heavy software. Any suggestions?


GCC is your best bet. No C compiler is really that heavy, but the associated build tools and libraries can take up quite a bit of disk space. http://www.mingw.org/ is one of the best ports for Windows. Nearly every distro of Linux already has GCC installed.

If you want to relearn C, though, I would suggest picking up a 30$ arduino board and screwing around with hardware. It's fun and will probably teach you a bunch.

Edit: Or Cygwin works, but I file that under the "resource-heavy software" category.
Any sufficiently advanced technology is indistinguishable from magic
waxypants
Profile Blog Joined September 2009
United States479 Posts
Last Edited: 2013-10-21 22:46:52
October 21 2013 22:46 GMT
#7555
A quick search turned up TCC (tiny c compiler). I downloaded it, it's a couple megs and compiled HelloWorld just fine on Windows! I imagine though that it has some quirks, so you're better off using MingW or gcc if you want to avoid a bloated install of MSVC with IDE. For the record, I've never used MingW, but I assume it's good and relatively lightweight.
n0ah
Profile Joined June 2011
United States250 Posts
October 21 2013 22:55 GMT
#7556
Actually I do have an Arduino board... I buried it in my closet a long time ago haha... I guess I could pull that out and try some stuff... I just miss programming (I'm a computer engineer, not computer scientist). My programming skills were never excellent or anything, and I don't feel like I learned all of the concepts from my school so I wanted to go through it again in my free time.

Thanks for your replies guys.
If this is to end in fire, then we will all burn together
RoyGBiv_13
Profile Blog Joined August 2010
United States1275 Posts
October 21 2013 22:56 GMT
#7557
On October 22 2013 07:46 waxypants wrote:
A quick search turned up TCC (tiny c compiler). I downloaded it, it's a couple megs and compiled HelloWorld just fine on Windows! I imagine though that it has some quirks, so you're better off using MingW or gcc if you want to avoid a bloated install of MSVC with IDE. For the record, I've never used MingW, but I assume it's good and relatively lightweight.


Yeah, TCC works as well as long as you stick to the standard C library, which is probably the case.
Any sufficiently advanced technology is indistinguishable from magic
CorsairHero
Profile Joined December 2008
Canada9491 Posts
October 21 2013 23:35 GMT
#7558
On October 22 2013 07:30 RoyGBiv_13 wrote:
Show nested quote +
On October 22 2013 07:03 n0ah wrote:
Is there anything like a "light-weight" C compiler? I want to re-teach myself C in my free time, but I don't want to install a bunch of resource-heavy software. Any suggestions?


GCC is your best bet. No C compiler is really that heavy, but the associated build tools and libraries can take up quite a bit of disk space. http://www.mingw.org/ is one of the best ports for Windows. Nearly every distro of Linux already has GCC installed.

If you want to relearn C, though, I would suggest picking up a 30$ arduino board and screwing around with hardware. It's fun and will probably teach you a bunch.

Edit: Or Cygwin works, but I file that under the "resource-heavy software" category.

Imo, if you're going to spend $30, then the raspberry pi is a much more powerful tool
© Current year.
tofucake
Profile Blog Joined October 2009
Hyrule19228 Posts
October 21 2013 23:38 GMT
#7559
On October 22 2013 07:46 waxypants wrote:
A quick search turned up TCC (tiny c compiler). I downloaded it, it's a couple megs and compiled HelloWorld just fine on Windows! I imagine though that it has some quirks, so you're better off using MingW or gcc if you want to avoid a bloated install of MSVC with IDE. For the record, I've never used MingW, but I assume it's good and relatively lightweight.

mingw is great. There's a bit more hassle setting it up compared to Cygwin, and it can be weird to use, but the end product is better imo
Liquipediaasante sana squash banana
icystorage
Profile Blog Joined November 2008
Jollibee19350 Posts
Last Edited: 2013-10-22 01:15:24
October 22 2013 00:59 GMT
#7560
guys. i want to google something but i dont know the keywords. what i want to do is that i want a checker that checks if my { ends with }.

is it too confusing? i forgot what that is called >.>

nvm. ctrl+f does the trick lol
LiquidDota StaffAre you ready for a Miracle-? We are! The International 2017 Champions!
Prev 1 376 377 378 379 380 1032 Next
Please log in or register to reply.
Live Events Refresh
Next event in 2h 50m
[ Submit Event ]
Live Streams
Refresh
StarCraft: Brood War
Tasteless 388
firebathero 180
Free 151
Larva 139
Bale 54
PianO 47
ToSsGirL 39
NaDa 32
ZergMaN 23
ggaemo 15
[ Show more ]
Nal_rA 12
IntoTheRainbow 10
Noble 10
League of Legends
JimRising 660
Counter-Strike
summit1g8183
Other Games
ceh9505
Happy257
Organizations
Other Games
gamesdonequick2429
BasetradeTV225
StarCraft 2
Blizzard YouTube
StarCraft: Brood War
BSLTrovo
[ Show 14 non-featured ]
StarCraft 2
• Berry_CruncH296
• AfreecaTV YouTube
• intothetv
• Kozan
• IndyKCrew
• LaughNgamezSOOP
• Migwel
• sooper7s
StarCraft: Brood War
• BSLYoutube
• STPLYoutube
• ZZZeroYoutube
Dota 2
• lizZardDota258
League of Legends
• Rush1434
• Stunt544
Upcoming Events
WardiTV Weekly
2h 50m
The PondCast
1d 1h
Replay Cast
2 days
CrankTV Team League
2 days
Replay Cast
3 days
CrankTV Team League
3 days
Replay Cast
3 days
RSL Revival
4 days
Clem vs Lambo
Scarlett vs Cure
CranKy Ducklings
4 days
IPSL
4 days
Dragon vs Hawk
[ Show More ]
RSL Revival
5 days
Classic vs Trap
herO vs SHIN
Sparkling Tuna Cup
5 days
IPSL
5 days
Bonyth vs Ret
WardiTV Weekly
6 days
Monday Night Weeklies
6 days
Liquipedia Results

Completed

YSL S3
HSC XXIX
Eternal Conflict S2 E2

Ongoing

IPSL Spring 2026
Acropolis #4
CSL 2026 Summer (S21)
RSL Revival: Season 6
CranK Gathers Season 4: BW vs SC2 Team League
SCTL 2026 Spring
XSE Pro League 2026
IEM Cologne Major 2026
Stake Ranked Episode 2
CS Asia Championships 2026
Asian Champions League 2026
IEM Atlanta 2026
PGL Astana 2026
BLAST Rivals Spring 2026

Upcoming

Escore Tournament S3: W3
ASL S22 SEASON OPEN Day 1
Escore Tournament S3: W4
ASL S22 SEASON OPEN Day 2
Escore Tournament S3: W5
CSLAN 4
Blizzard Classic Cup 2026
HSC XXX
SC4ALL II: StarCraft II
Kung Fu Cup 2026 Grand Finals
Light Tournament 2026
Eternal Conflict S2 Finale
Eternal Conflict S2 E3
Logitech G Connect 2026
StarSeries Fall 2026
FISSURE Playground #5
BLAST Open Fall 2026
Esports World Cup 2026
BLAST Bounty Summer 2026
BLAST Bounty Summer Qual
Stake Ranked Episode 3
TLPD

1. ByuN
2. TY
3. Dark
4. Solar
5. Stats
6. Nerchio
7. sOs
8. soO
9. INnoVation
10. Elazer
1. Rain
2. Flash
3. EffOrt
4. Last
5. Bisu
6. Soulkey
7. Mini
8. Sharp
Sidebar Settings...

Advertising | Privacy Policy | Terms Of Use | Contact Us

Original banner artwork: Jim Warren
The contents of this webpage are copyright © 2026 TLnet. All Rights Reserved.