Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

algorithm: find count of numbers within a given range

Tags:

c++

algorithm

given an unsorted number array where there can be duplicates, pre-process the array so that to find the count of numbers within a given range, the time is O(1).

For example, 7,2,3,2,4,1,4,6. The count of numbers both >= 2 and <= 5 is 5. (2,2,3,4,4).

like image 896
user697417 Avatar asked Apr 07 '11 19:04

user697417


People also ask

How do you check if a number is within a range?

If x is in range, then it must be greater than or equal to low, i.e., (x-low) >= 0. And must be smaller than or equal to high i.e., (high – x) <= 0. So if result of the multiplication is less than or equal to 0, then x is in range.

Which function will count the number of elements in the given range?

Use the COUNT function to get the number of entries in a number field that is in a range or array of numbers. For example, you can enter the following formula to count the numbers in the range A1:A20: =COUNT(A1:A20). In this example, if five of the cells in the range contain numbers, the result is 5.

How do you calculate the number of a range?

given an unsorted number array where there can be duplicates, pre-process the array so that to find the count of numbers within a given range, the time is O(1). For example, 7,2,3,2,4,1,4,6 . The count of numbers both >= 2 and <= 5 is 5 . (2,2,3,4,4) .

How do you find the number of values in a given range divisible by a given value?

Let B = b * M and A = a * M The count of numbers divisible by 'M' between A and B will be equal to b - a. Example: A = 25, B = 70, M = 10. Now, a = 2, b = 7. Count = 7 - 2 = 5.


2 Answers

Sort the array. For each element in the sorted array, insert that element into a hash table, with the value of the element as the key, and its position in the array as the associated value. Any values that are skipped, you'll need to insert as well.

To find the number of items in a range, look up the position of the value at each end of the range in the hash table, and subtract the lower from the upper to find the size of the range.

like image 140
Jerry Coffin Avatar answered Sep 25 '22 02:09

Jerry Coffin


This sounds suspiciously like one of those clever interview questions some interviewers like to ask, which is usually associated with hints along the way to see how you think.

Regardless... one possible way of implementing this is to make a list of the counts of numbers equal to or less than the list index.

For example, from your list above, generate the list: 0, 1, 3, 4, 6, 6, 7, 8. Then you can count the numbers between 2 and 5 by subtracting list[1] from list[5].

like image 41
jkerian Avatar answered Sep 23 '22 02:09

jkerian