15,940,921 members
See more:
Hi All,

What I have tried:

Hi All,

Posted
Updated 30-Jul-22 5:11am

## Solution 1

Have first a look to 'Solution 2'. It is much easier and universal and in general better ;)

Therefore I will not give you the solution, but a hint.

Instanciate two arrays of integers, both with the size N.
Let's name them:
```Values    // The values you need to evalate
Counts   // Don't forget to initialize all elements with 0
```

`Values` will hold the numbers you need to evaluate.
Loop over `Values` and count the corresponding number in `Counts`. Something like:
```countIx= Values[valueIx] - 1;  // Think about why here '-1'
Counts[countIx]= Counts[countIx] + 1;```

After all that you can loop over `Counts` and e.g. show how many time a number occured in `Values`.

Hint: What is fundamental here is that the indices of the array Count have a unique relationship to the values in Values. Try to understand the relationship, it has to do with the '-1' mentioned above.

Important: Be aware, this solution works only because of the restriction that the numbers to evaluate need to be in the range 1...N.

I hope it gives you an idea.

v6
Richard MacCutchan 30-Jul-22 11:19am
One assumes that the code would check that each number is in range before adding it to the first array.
0x01AA 30-Jul-22 11:22am
You are correct, anyway a strange solution. Solution 2 is much better and it is in your hands to make it the top answer ;)

## Solution 2

0x01AA has suggested a good idea, but a simpler (and more efficient) solution is to sort the array of values. Once in order, duplicates are next to each other, so a single pass through the array will identify if it contains any duplicates very quickly and easily as they will be next to each other.

Have a think about it, and you'll see what I mean.

If you are having problems getting started at all, then this may help: How to Write Code to Solve a Problem, A Beginner's Guide[^]

0x01AA 30-Jul-22 11:17am
5. And more, your solution works also in case the 'values' are not in the range '1...N'.
Sometimes(?) my brain is shorted, *blush* :D

'more efficient': Now sorting is not cheap. But again, your solution is much better/universal.
OriginalGriff 30-Jul-22 14:10pm
Sorting isn't free, but Quicksort doesn't use too much memory and is pretty quick (there are "cheaper" sorting algorithms if the sample size is small enough).

Having a count array that is the sample space size can get very expensive in terms of memory at large samples!

But you know this - I'm only mentioning it because it's likely the OP doesn't!