0

Given an unsorted array such as 9 4 4 9 2 2, I need an efficient algorithm that will allow me to know the starting location and ending location of each digit in that array, when that array is sorted. For example, for the array above, the digit 2 will have a starting index of 0 and an ending index of 1. The digit 4 will have a starting index of 2 and an ending index of 3, and the digit 9 will have a starting index of 4 and an ending index of 5 (when sorted). Anyone know how to do this in an efficient way? Is there a way to do it without sorting the array first?

1 Answer 1

5

You can make use of the fact that there are only ten distinct elements.

First, iterate over the array once, counting the zeroes, the ones, the twos, etc.

From these counts you can easily work out the starting and the ending position of each digit in the sorted array.

This is a variant of Counting Sort, except that we don't actually populate the sorted array.

Sign up to request clarification or add additional context in comments.

4 Comments

So essentially create a really simple hash table?
@SGM1: A ten-element array.
Yea 0 representing 1, 1 rep 2, ... etc then just add 1 to their respective position? Correct?
Yes, it takes O(n) space (n is the maximum number of unique elements possible.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.