I'm trying to write a function that takes an array of unsorted positive integers N elements long.

The function should return the same array (no new allocations) with all duplicated integers replaced with -1 and moved to the end of the array.

So for example, the string:


1136788999

becomes ...

136789-1-1-1-1

Does anyone have a code snippet that accomplishes this? Sounds like a hash table could be the best approach here, but not sure.

Thanks much in advance!

~Steve

I'm trying to write a function that takes an array of unsorted positive integers N elements long.

The function should return the same array (no new allocations) with all duplicated integers replaced with -1 and moved to the end of the array.

So for example, the string:


1136788999

becomes ...

136789-1-1-1-1

Does anyone have a code snippet that accomplishes this? Sounds like a hash table could be the best approach here, but not sure.

Thanks much in advance!

~Steve

Yeah I'd agree with that. Go with the hasttable.

Yeah I'd agree with that. Go with the hasttable.

Thank you. I'm a bit new at this and having trouble getting started. So for the example given, how would you start? Very much obliged.

Before that, please confirm. What is the input parameter of the function? is it an array of integers? or a string?
since you mention that the function must return the same array (no allocation), meaning that the input parameter is also an array.
but in your example, you mention it about a string.


Regards,

Lok

Sorry, forgot to asking.. is all the integers are 1-digit (0 to 9)?

regards,

Lok

Easy then, no need to use any hashtable, just use array of boolean.

private bool[] flag = new bool[10];

each time you iterate the integer array, check against the flag array using the current integer value as it's index. if the flag[integer[loop_index]] == false, leave it as it is, then change it to true.
but if it's already true, meaning the integer value already exists, so shift the integer array contents by -1, started from the already exists integer value, and replace the last integer-array value with -1.

Hope that logic will help.

Regards,

Lok

This article has been dead for over six months. Start a new discussion instead.