-3

Given an array of integers, we have to answer certain queries where each query has 2 integers. These 2 integers are the 2 indices of the given array and we have to find the median of the numbers present between the 2 indices (inclusive of the given indices.)

Well sorting the array for each query is the most basic solution. Can this be solved with the help of segment trees or range queries?

P3A
  • 141
  • 9
  • Well I am not able to think anything which has a better complexity than the brute force solution which involves sorting the array for each query. So currently I don't have any code snippet. – P3A Oct 17 '16 at 08:43
  • Well for all those users who have down voted the question, can u give me the reason for doing so because I am not able to understand what's wrong with it. – P3A Oct 17 '16 at 08:47

1 Answers1

0

Here's how to do this in Python:

import numpy as np

def median(arr):

    arr_sort = sorted(arr)
    n = len(arr)
    n_over_two = int(n/2)
    if (n%2 == 0):
        return (arr_sort[n_over_two-1]+arr_sort[n_over_two])/2.0
    else:
        return arr_sort[n_over_two]

tmp = [5,4,3,2,1]
print(median(tmp))

tmp = [2,10,2,10,7]
print(median(tmp))

tmp = [4, 3, 2, 1]
print(median(tmp))

This works for any array. Taking median of a subset of an array just involves standard indexing of that array in python (inclusive of lower index, exclusive of upper - if you want inclusive of upper, add one):

anArray=[0,0,0,1,2,3,4,10,10,10,10]
print(anArray[3:7])
print(median(anArray[3:7]))
T3am5hark
  • 786
  • 5
  • 9
  • Well the above brute force solution has non-optimal time complexity. Do u have any thoughts related to range queries for improving the time complexity. – P3A Oct 17 '16 at 08:45