• Log InLog In
  • Register
Liquid`
Team Liquid Liquipedia
EDT 04:10
CEST 10:10
KST 17:10
  • 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: 3807 users

The Big Programming Thread - Page 377

Forum Index > General Forum
Post a Reply
Prev 1 375 376 377 378 379 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.
gedatsu
Profile Joined December 2011
1286 Posts
October 20 2013 12:58 GMT
#7521
On October 20 2013 09:18 EscPlan9 wrote:
Show nested quote +
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:
On October 20 2013 00:04 EscPlan9 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.


I probably would have given the hash table answer. Though I'm not sure if my implementation was the same as what you were describing:


var arr = [1,1,2,2,3,3,4];
var hash = {};

// build hash - give the value 1 when initially found, and add 1 for each duplicate
for (var i = 0; i < arr.length; i++) {
if (hash[ arr[i] ] {
hash[ arr[i] ] = 1 + hash[ arr[i] ];
} else {
hash[ arr[i] ] = 1;
}
}

// iterate through hash until found a key with a value of 1 indicating no duplicates
for (var k in hash) {
if (hash[k] === 1) {
print "Unique element found: " + k;
}
}


What would be pseudocode for your implementation you mentioned with keeping track of a separate sum variable? I just used the value of the hash-key as the "sum".

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.
teamamerica
Profile Blog Joined July 2010
United States958 Posts
Last Edited: 2013-10-20 13:29:58
October 20 2013 13:27 GMT
#7522
ed: I think I missed reading a page...sry!
RIP GOMTV. RIP PROLEAGUE.
Mstring
Profile Joined September 2011
Australia510 Posts
October 20 2013 13:33 GMT
#7523
On October 20 2013 21:58 gedatsu wrote:
Show nested quote +
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:
On October 20 2013 00:04 EscPlan9 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.


I probably would have given the hash table answer. Though I'm not sure if my implementation was the same as what you were describing:


var arr = [1,1,2,2,3,3,4];
var hash = {};

// build hash - give the value 1 when initially found, and add 1 for each duplicate
for (var i = 0; i < arr.length; i++) {
if (hash[ arr[i] ] {
hash[ arr[i] ] = 1 + hash[ arr[i] ];
} else {
hash[ arr[i] ] = 1;
}
}

// iterate through hash until found a key with a value of 1 indicating no duplicates
for (var k in hash) {
if (hash[k] === 1) {
print "Unique element found: " + k;
}
}


What would be pseudocode for your implementation you mentioned with keeping track of a separate sum variable? I just used the value of the hash-key as the "sum".

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
TimKim0713
Profile Joined June 2012
Korea (South)221 Posts
Last Edited: 2013-10-20 15:54:53
October 20 2013 15:54 GMT
#7524
Hello everyone...

Okay, so I am new too computer science, and I am just stuck on this problem that I should do as a practice before this quiz!

This is the link to practice problem... https://docs.google.com/file/d/0B17THXdfP8JwTGU1NzNaNWNfNTg/edit?usp=sharing
In general, we just learned array lists, and we have to use it to find maximum, minimum etc.

But, (THIS IS a BIGG BUT <-- :D)
With the problem is - search on arraylist -.
I feel like I know how to use it somewhat, but only function I know from arraylist is list.get();. I've seen .set(); but I don't really know about it... Are there any useful functions in arraylist?

Also if you can / want, could you give me a solution to the practice problems? I just want to see it as a reference and try to understand some part of it so I can reuse that part another time or so

Thank you.
spinesheath
Profile Blog Joined June 2009
Germany8679 Posts
October 20 2013 16:34 GMT
#7525
No, I won't give you a solution to the problem, that defeats its purpose. You should develop a very good understanding of these, it's essential knowledge.
The problems are all really similar though, and the expected solution probably just involves for loops. You should not need any special functions on arraylist except for add and remove for the last 2 problems as specified in the link.
If you have a good reason to disagree with the above, please tell me. Thank you.
TimKim0713
Profile Joined June 2012
Korea (South)221 Posts
October 20 2013 16:37 GMT
#7526
On October 21 2013 01:34 spinesheath wrote:
No, I won't give you a solution to the problem, that defeats its purpose. You should develop a very good understanding of these, it's essential knowledge.
The problems are all really similar though, and the expected solution probably just involves for loops. You should not need any special functions on arraylist except for add and remove for the last 2 problems as specified in the link.


but could you tell me about .set() function?
that's the one i've seen alot, but didn't quiet get it
spinesheath
Profile Blog Joined June 2009
Germany8679 Posts
Last Edited: 2013-10-20 16:46:56
October 20 2013 16:45 GMT
#7527
On October 21 2013 01:37 TimKim0713 wrote:
Show nested quote +
On October 21 2013 01:34 spinesheath wrote:
No, I won't give you a solution to the problem, that defeats its purpose. You should develop a very good understanding of these, it's essential knowledge.
The problems are all really similar though, and the expected solution probably just involves for loops. You should not need any special functions on arraylist except for add and remove for the last 2 problems as specified in the link.


but could you tell me about .set() function?
that's the one i've seen alot, but didn't quiet get it

Well, sure, although you should just google it, something like "<your programming language> ArrayList set" should bring up a proper documentation of the method.
Anyways, list.set(i, v) simply puts v into the list, replacing the value that was at index i before. After list.set(i, v) is used, get(i) will return v.
If you have a good reason to disagree with the above, please tell me. Thank you.
Fatalize
Profile Joined January 2011
France5210 Posts
October 20 2013 16:59 GMT
#7528
Programming in Prolog is so refreshing.

Unfortunately I'll have to do some Java soon, fuck this awful language
jarf1337
Profile Joined July 2010
United States146 Posts
October 20 2013 17:07 GMT
#7529
I have some CSS classes that apply dotted 1 pixel bottom borders to individual td tags in a table. It applies them all properly in firefox and chrome. In IE, they show properly EXCEPT for cells which also have a thick solid 2px border on the left or right... which makes IE turn my 1px dotted bottom border into a dashed border for no reason. Any ideas?

The thing that really drives me nuts is that there are no styles or CSS classes that even use a dashed border in the code. Internet Exploder at its finest!
wut kan i dew
phar
Profile Joined August 2011
United States1080 Posts
October 20 2013 17:34 GMT
#7530
On October 20 2013 22:33 Mstring wrote:
Show nested quote +
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:
On October 20 2013 00:04 EscPlan9 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.


I probably would have given the hash table answer. Though I'm not sure if my implementation was the same as what you were describing:


var arr = [1,1,2,2,3,3,4];
var hash = {};

// build hash - give the value 1 when initially found, and add 1 for each duplicate
for (var i = 0; i < arr.length; i++) {
if (hash[ arr[i] ] {
hash[ arr[i] ] = 1 + hash[ arr[i] ];
} else {
hash[ arr[i] ] = 1;
}
}

// iterate through hash until found a key with a value of 1 indicating no duplicates
for (var k in hash) {
if (hash[k] === 1) {
print "Unique element found: " + k;
}
}


What would be pseudocode for your implementation you mentioned with keeping track of a separate sum variable? I just used the value of the hash-key as the "sum".

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
Who after all is today speaking about the destruction of the Armenians?
wherebugsgo
Profile Blog Joined February 2010
Japan10647 Posts
October 20 2013 19:42 GMT
#7531
On October 20 2013 03:54 obesechicken13 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.


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.


How does this work? What are you XORing together?

Are you XORing 0 with every element or the previous element with the next element or what?
Diagrams would be helpful.

Also it still seems like you're doing this in O(n) time and I liked your previous solutions better since they were more intuitive. I don't think of using XOR when I want to solve a problem like this. That's something you learn to see in (?) programming competitions.

The only advantage I see with XOR over radix sort is that if you have really large integers then Radix sort would be slow.


Basically just start at the beginning of the array,and iterate through, XORing all the numbers together.

In a loop it would be as the guy after you described; you have a variable that stores the running XOR value and you XOR it with the current element of the array.

I'm on my phone, so it's unfortunately a bit hard for me to quote things. However, to whoever attempted the first problem (the one with the array where you can't access the whole element at once) accessing all of the bits does not take O(N) time because you are not guaranteed that the numbers are 32 bits. There is no set bound on the size of N, so think about how many bits that would be.

+ Show Spoiler +
examining all the bits is O(NlogN)
Manit0u
Profile Blog Joined August 2004
Poland17786 Posts
October 20 2013 19:47 GMT
#7532
On October 21 2013 02:07 jarf1337 wrote:
I have some CSS classes that apply dotted 1 pixel bottom borders to individual td tags in a table. It applies them all properly in firefox and chrome. In IE, they show properly EXCEPT for cells which also have a thick solid 2px border on the left or right... which makes IE turn my 1px dotted bottom border into a dashed border for no reason. Any ideas?

The thing that really drives me nuts is that there are no styles or CSS classes that even use a dashed border in the code. Internet Exploder at its finest!


Most likely you'll need to use some hacks to override that in IE. Myself, I've forsaken IE and whenever I make a page I don't even bother to check how it's going to look in it since I don't care (let the bastards suffer). As long as people will include special hacks for IE they'll think it's actually good for anything. When suddenly all the webpages start to look horrific they'll learn and either adapt or die.
Time is precious. Waste it wisely.
gedatsu
Profile Joined December 2011
1286 Posts
Last Edited: 2013-10-21 21:16:22
October 20 2013 20:16 GMT
#7533
On October 21 2013 04:42 wherebugsgo wrote:
Show nested quote +
On October 20 2013 03:54 obesechicken13 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.


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.


How does this work? What are you XORing together?

Are you XORing 0 with every element or the previous element with the next element or what?
Diagrams would be helpful.

Also it still seems like you're doing this in O(n) time and I liked your previous solutions better since they were more intuitive. I don't think of using XOR when I want to solve a problem like this. That's something you learn to see in (?) programming competitions.

The only advantage I see with XOR over radix sort is that if you have really large integers then Radix sort would be slow.


Basically just start at the beginning of the array,and iterate through, XORing all the numbers together.

In a loop it would be as the guy after you described; you have a variable that stores the running XOR value and you XOR it with the current element of the array.

I'm on my phone, so it's unfortunately a bit hard for me to quote things. However, to whoever attempted the first problem (the one with the array where you can't access the whole element at once) accessing all of the bits does not take O(N) time because you are not guaranteed that the numbers are 32 bits. There is no set bound on the size of N, so think about how many bits that would be.

+ Show Spoiler +
examining all the bits is O(NlogN)

Are we allowed to modify the array? Or can we only examine its original content?

edit: scratch that, figured it out.

+ Show Spoiler +
First look at bit 0 of every number. You know N, so you know how many of these "should" be 0 and how many should be 1. When N is odd, they should be equal, and when N is even, the 0s should outnumber the 1s by one. One of these halves will have contain one less element than is expected, and thus we know the missing number's bit in this position. Recurse on that half and look at bit next bit of these numbers. You can do that by allocating two new arrays, putting all the 0-bit numbers in array A and the 1-bit numbers in array B and then recursing on one of them.

Example:
0000
0001
0010
0011
0100
0101
0110
0111
1000
(missing 1001)
1010

1-bit: 4, should be 5
0-bit: 6, should be 6

The missing number has a 1 in bit 0. Recurse on the 1-bits.

0001
0011
0101
0111

1-bit 2, should be 2
0-bit 2, should be 3

The missing number has a 0 in bit 1. Recurse on the 0-bits.

0001
0101

0-bit 1, should be 2
1-bit 1, should be 1

The missing number has a 0 in bit 2. Recurse on the 0-bits.

0101

0-bit 1, should be 1
1-bit 0, should be 1

The missing number has a 1 in bit 3. We can now reconstruct the number because we know all of its bits.

Total number of inspected bits is sum of N/(2^i), i from 0 to log2(N) = 2N-1 = O(N)
Encdalf
Profile Joined February 2012
Germany66 Posts
Last Edited: 2013-10-20 20:19:55
October 20 2013 20:18 GMT
#7534
On October 21 2013 02:07 jarf1337 wrote:
I have some CSS classes that apply dotted 1 pixel bottom borders to individual td tags in a table. It applies them all properly in firefox and chrome. In IE, they show properly EXCEPT for cells which also have a thick solid 2px border on the left or right... which makes IE turn my 1px dotted bottom border into a dashed border for no reason. Any ideas?

The thing that really drives me nuts is that there are no styles or CSS classes that even use a dashed border in the code. Internet Exploder at its finest!


That's a pretty old bug in IE versions <= 7, or if your page is in quirksmode. Dotted was not supported (automatically replaced by dashed) untill IE7 and in IE7 dotted was only shown when the border was thicker than 1px.

In your case, the bug probably appears because your page is in quirksmode, so set a proper document header, and everything will be fine ;>

(If thats not the case and you want to optimize for IE7, you're screwed and most likely have to fall back to a graphic border [background image] )
EscPlan9
Profile Blog Joined December 2006
United States2777 Posts
Last Edited: 2013-10-20 22:33:33
October 20 2013 21:01 GMT
#7535
On October 21 2013 02:34 phar wrote:
Show nested quote +
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:
On October 20 2013 00:04 EscPlan9 wrote:
[quote]

I probably would have given the hash table answer. Though I'm not sure if my implementation was the same as what you were describing:


var arr = [1,1,2,2,3,3,4];
var hash = {};

// build hash - give the value 1 when initially found, and add 1 for each duplicate
for (var i = 0; i < arr.length; i++) {
if (hash[ arr[i] ] {
hash[ arr[i] ] = 1 + hash[ arr[i] ];
} else {
hash[ arr[i] ] = 1;
}
}

// iterate through hash until found a key with a value of 1 indicating no duplicates
for (var k in hash) {
if (hash[k] === 1) {
print "Unique element found: " + k;
}
}


What would be pseudocode for your implementation you mentioned with keeping track of a separate sum variable? I just used the value of the hash-key as the "sum".

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.
Undefeated TL Tecmo Super Bowl League Champion
phar
Profile Joined August 2011
United States1080 Posts
October 20 2013 21:25 GMT
#7536
Yea, it works great for simple things with small input. You just have to be very careful & aware of the limitations.
Who after all is today speaking about the destruction of the Armenians?
Shield
Profile Blog Joined August 2009
Bulgaria4824 Posts
October 21 2013 01:47 GMT
#7537
I'm still trying to figure out composition in practice not theory.

So, for example:


private SomeClass sc;

// constructor
public Main(SomeClass sc) {
this.sc = sc;
}

public int getSomeValue() {
// get some value from SomeClass
return sc.value;
}


Is SomeClass considered part of composition?
phar
Profile Joined August 2011
United States1080 Posts
Last Edited: 2013-10-21 02:55:49
October 21 2013 02:55 GMT
#7538
Yes. By having SomeClass as a field inside your other class instead of having your new class extend SomeClass, you're using composition instead of inheritance. Look at some of the com.google.common.collect guava libraries for good examples of things you can use for composition.

http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/ (most of the forwarding things, abstractiterator, etc)
http://stackoverflow.com/questions/3502066/guava-forwardinglist-usage-example
Who after all is today speaking about the destruction of the Armenians?
Shield
Profile Blog Joined August 2009
Bulgaria4824 Posts
October 21 2013 11:44 GMT
#7539
Right, thanks. I was wondering if MVC indeed uses composition but I guess that answers my question. The View knows about the Model, while the Controller knows about both.
Tobberoth
Profile Joined August 2010
Sweden6375 Posts
October 21 2013 12:23 GMT
#7540
On October 21 2013 20:44 darkness wrote:
Right, thanks. I was wondering if MVC indeed uses composition but I guess that answers my question. The View knows about the Model, while the Controller knows about both.

It depends on the implementation. You don't really need the View to hold the model in a composition pattern, you can use the observer pattern so that the view is only updated by events. Obviously the view still has to know about the model, but it doesn't have to hold the actual model object.
Prev 1 375 376 377 378 379 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 435
Free 156
Larva 129
firebathero 108
Bale 60
PianO 46
ToSsGirL 41
NaDa 31
ZergMaN 24
Noble 16
[ Show more ]
Nal_rA 12
IntoTheRainbow 9
ggaemo 1
League of Legends
JimRising 660
Counter-Strike
summit1g7205
Other Games
ceh9497
Happy257
Organizations
Other Games
gamesdonequick2429
BasetradeTV221
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
• lizZardDota253
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.