• Log InLog In
  • Register
Liquid`
Team Liquid Liquipedia
EDT 06:34
CEST 12:34
KST 19:34
  • 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
[ASL22] Ro24 Preview: Siren's Call8[ASL22] Ro24 Preview: Summer's End9Serral wins HomeStory Cup 2915Serral wins Maestros of the Game 244ByuL, and the Limitations of Standard Play3
Community News
Stellar Fest TWO the Moon (Dec 16-20)8Weekly Cups (August 24-30): Patches' balance mod takes over2New 3v3 BGH Ladder (and more) on ShieldBattery!40Weekly Cups (August 17-23): Zerg dominate the week6Weekly Cups (August 10-16): SHIN doubles5
StarCraft 2
General
Weekly Cups (August 10-16): SHIN doubles Nexon wins bid to develop StarCraft IP content, distribute Overwatch mobile game SC4ALL II: SC2 Player Announcement 6/8 - Maru Weekly Cups (August 24-30): Patches' balance mod takes over How would you feel about frequent/monthly balance patches for SC2?
Tourneys
IntoTheTV X SOOP SC2 League : Weekly & Monthly SC2 INu's Battles#20 [BO.9] 2026 GSTL Announcement Stellar Fest TWO the Moon (Dec 16-20) PIG STY FESTIVAL 8.0! (13 - 23 August)
Strategy
[G] Having the right mentality to improve
Custom Maps
Nexus Wars 2021 GUIDE [M] (2) Industrial Park
External Content
Mutation # 541 Binary Choice The PondCast: SC2 News & Results Mutation # 540 Dodge This Mutation # 539 Thunder Dome
Brood War
General
BGH Auto Balance -> http://bghmmr.eu/ BW General Discussion Making an Online Broodwar Manager Game ASL22 General Discussion [Personal Project Share] Terran Defense v0.60
Tourneys
KCM Race Survival 2026 Season 3 [Megathread] Daily Proleagues BSL LAN Party - Kraków 29-30 August - OPEN SIGNUPS [ASL22] Ro24 Group F
Strategy
Replay Review Process - What do you do? Game Theory for Starcraft Odyssey Mineral Stack Saturation Fighting Spirit mining rates
Other Games
General Games
[Maplestory Hardcore] Let's Play~!! General RTS Discussion Thread Stratus: Battle for the sky now on steam Early acc Nintendo Switch Thread Stormgate/Frost Giant Megathread
Dota 2
Official 'what is Dota anymore' discussion
League of Legends
[TL LoL EUW IHs] Teemo shall perish TSM pausing esports and CLG Dead
Heroes of the Storm
Heroes of the Storm 2.0
Hearthstone
Deck construction bug
TL Mafia
TL Mafia Power Rank TL Mafia Community Thread NeO.D_StephenKing vs This Guy From 1 Million Dance
Community
General
US Politics Mega-thread Things Aren’t Peaceful in Palestine Russo-Ukrainian War Thread Canadian Politics Mega-thread European Politico-economics QA Mega-thread
Fan Clubs
MarineLorD Fan Club The Creator Fan Club The ShoWTimE Fan Club
Media & Entertainment
Movie Discussion! Anime Discussion Thread
Sports
Football (Soccer) Thread TeamLiquid Health and Fitness Initiative For 2023 MLB/Baseball 2023 NBA General Discussion
World Cup 2022
Tech Support
Computer Build, Upgrade & Buying Resource Thread
TL Community
The Automated Ban List Northern Ireland Global Starcraft
Blogs
Regacy Esports: The Bh…
regacyesports
Violent Games and Crime Rate…
TrAiDoS
LOCKPICKING NOOB
LUCKY_NOOB
Cathedral Of CS And NY pizza a…
FuDDx
Please support my new stand…
Peanutsc
Customize Sidebar...

Website Feedback

Closed Threads



Active: 7545 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
Hyrule19252 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
KCM Race Survival
10:00
2026 Season 3 Week 8
Kim Chul Min (afreeca) 668
LiquipediaDiscussion
[ Submit Event ]
Live Streams
Refresh
StarCraft 2
Lowko186
EnDerr 30
StarCraft: Brood War
firebathero 5567
Bisu 2710
Shuttle 1275
Hyuk 654
Pusan 425
Horang2 382
EffOrt 318
Stork 174
ZerO 170
Zeus 121
[ Show more ]
Snow 113
Light 99
ToSsGirL 74
Shinee 51
Rush 51
Larva 42
sSak 27
Barracks 25
910 24
Sacsri 22
Sexy 18
NotJumperer 17
Noble 15
soO 15
SilentControl 8
Counter-Strike
olofmeister1275
byalli719
Other Games
singsing1716
shoxiejesuss717
ceh9666
crisheroes363
XaKoH 225
Mew2King90
Organizations
StarCraft: Brood War
lovetv 8
[ Show 11 non-featured ]
StarCraft 2
• Berry_CruncH252
• StrangeGG 53
• AfreecaTV YouTube
• intothetv
• Kozan
• IndyKCrew
• Migwel
StarCraft: Brood War
• BSLYoutube
• STPLYoutube
• ZZZeroYoutube
League of Legends
• Jankos1210
Upcoming Events
OSC
11h 56m
IntoTheTV X SOOP
1d
CranKy Ducklings
1d 23h
Sparkling Tuna Cup
2 days
OSC
3 days
Shopify Rebellion Sundays
3 days
Mixu vs TBD
Spirit vs TBD
Clem vs TBD
Afreeca Starleague
3 days
Soma vs Shuttle
BeSt vs Rush
WardiTV Weekly
4 days
Afreeca Starleague
4 days
Leta vs ggaemo
Jaedong vs Queen
GSL
5 days
[ Show More ]
PiGosaur Cup
5 days
Kung Fu Cup
6 days
Replay Cast
6 days
The PondCast
6 days
Liquipedia Results

Completed

Proleague 2026-09-02
PiG Sty Festival 8.0
Light Tournament 2026

Ongoing

KCM Race Survival 2026 Season 3
K-JUNGMAN
ASL Season 22
Super Anchor Qualifying S3
CSL 2026 AUTUMN (S22)
RSL Revival: Season 6
Calamity Invitational
Big Dog Cup 2026 Div 1
BLAST Open Fall 2026
Esports World Cup 2026
Esports World Cup 2026: LCQ
BLAST Bounty Summer 2026
BLAST Bounty Summer Qual
Stake Ranked Episode 3
XSE Pro League 2026
IEM Cologne Major 2026

Upcoming

Acropolis #5
Acropolis #5 - TRS
Escore Tournament S3: King of Kings
Blizzard Classic Cup 2026
Acropolis #5 - GSA
Acropolis #5 - GSB
Acropolis #5 - GSC
HSC XXX
Stellar Fest 2: Lunar Cup
SC4ALL II: StarCraft II
Kung Fu Cup 2026 Grand Finals
RSL Offline Finals
BLAST Rivals Fall 2026
IEM Beijing 2026
Stake Ranked Episode 5
PGL Masters Bucharest 2026
1win Private Club #2
Thunderpick World Champ. '26
ESL Pro League Season 24
Stake Ranked Episode 4
1win Private Club #1
Logitech G Play Connect 2026
SL StarSeries Fall 2026
FISSURE Playground #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.