Click here to Skip to main content
15,885,216 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I'm trying to figure out the runtime complexity of findRange shown below, which finds the bottom and top index given a sorted array a and key key.
If key is not found then return -1 -1.

int[] a = new int[] { 1, 2, 2, 3, 3, 5, 5, 5, 5 };
findRange(a, 5) => 5 8

I'm coming up with the solution O(2 * log(#times_key_appears)* log n) => O((log n)^2)
Is this correct?
Is there a better algorithmic solution out there?

Java
public void findRange(int[] a, int key) {
    int bsLeft = bsLeft(a, 0, a.length , key, -1);
    System.out.print(bsLeft);
    System.out.print(" ");
    System.out.println(bsRight(a, bsLeft, a.length , key, -1));
}

public int bsLeft(int[] a, int startIndex, int lastIndex, int key, int found){
    int value = Arrays.binarySearch(a, startIndex, lastIndex, key);
    if (value < 0) {
        return found;
    }
    return bsLeft(a, startIndex, value -1, key, value);
}

public int bsRight(int[] a, int startIndex, int lastIndex, int key, int found){
    int value = Arrays.binarySearch(a, startIndex , lastIndex, key);
    if (value < 0) {
        return found;
    }
    return bsRight(a, value + 1, lastIndex, key, value);
}
Posted

1 solution

I'd have to understand your problem to know the best solution.

Are you free to change the forms of your stored data? It might best to preprocess that data one time into the form I mention below.

For example, you could only store unique values and have a parallel container that stores the count at each index. Of course, rather than have a parallel container, you could have a structure that contains the item and the count.

Item: 1, 2, 3, 5
Count: 1, 2, 2, 5

You can find the item using a regular binary search in O(log2 N) time, and then merely take that index for the item you found (for 5, the index would be 3), and add the count to find the top of the range, which for your example would be 3 + 5 = 8.

The issue with the structure you have is that it makes using a binary search difficult - I'd rearrange the data to be better.

By the way, if the data changes, that is, you are inserting and/or removing items from the list often, then a red-black tree would be a better solution as constantly inserting and sorting the array would be inefficient. Even in that case, I think storing a structure with the item and the count of the item would be best.
 
Share this answer
 
v3
Comments
slothbury 21-May-15 15:52pm    
Thanks for this answer! It has give me some things to consider when creating the structure of the code

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900