1
$\begingroup$

Let's say we have given array $A$ consisting of $n$ integers, and integer $K$. Now we want to count number of indexes $i$ such that $A_i<K$. What is the easiest way to pre-process the array and answer queries for different $K$ fast. Note that the elements of the array will be small up to 10ドル^5,ドル so it will be possible to count how many times each elements appears.

For example, let $A = \{1, 2, 3,0,0,2\}, K =3$ the answer is 5ドル,ドル because all $\{1,2,0,0,2\}$ are less than 3ドル$.

I know that we can implement this with segment tree and than answer queries in $O(\log N),ドル but I was thinking that we can implement easier solution that is easier to code.

asked Dec 23, 2017 at 14:48
$\endgroup$
2
  • 1
    $\begingroup$ Can't you just sort the array? Am I understanding the problem wrong? $\endgroup$ Commented Dec 23, 2017 at 15:06
  • $\begingroup$ What's the problem with doing what you suggest, i.e., just compute the counts for each possible $K$ as a preprocessing step? This is surely easy, and maybe more efficient than you expect. $\endgroup$ Commented Dec 23, 2017 at 16:07

2 Answers 2

4
$\begingroup$

Here is a $O(1)$ solution after $O(n)$ preprocessing step, assuming that all elements are less than some number $C$ (in your case 10ドル^5$) in pseudocode

count = new int[C] (array of integers)
for every a[i] in a 
 count[a[i]]++
for i = 1, i < C, i++ 
 count[i] += count[i-1] 

To Answer a query for a given k you just return count[k - 1]

answered Jan 2, 2018 at 0:42
$\endgroup$
2
  • $\begingroup$ That's not $O(n)$ preprocessing; it's $O(\max(n,C)),ドル which might be much slower if the array contains a large number (much larger than $n$). $\endgroup$ Commented Jan 2, 2018 at 2:12
  • $\begingroup$ @D.W. Quoted from the question : "Note that the elements of the array will be small up to 10ドル^5$" $\endgroup$ Commented Jan 2, 2018 at 5:22
3
$\begingroup$

As mentioned in comments, you can sort the array as a pre-process. Then answer to the query in $O(\log(n))$ using binary search. The implementation is common and easier.

answered Dec 23, 2017 at 15:41
$\endgroup$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.