Skip to content

Instantly share code, notes, and snippets.

@markhallen
Created April 10, 2018 13:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save markhallen/6f838db3f65fc41b4cad952e4f596d92 to your computer and use it in GitHub Desktop.
Save markhallen/6f838db3f65fc41b4cad952e4f596d92 to your computer and use it in GitHub Desktop.
def sumInRange(nums, queries)
sum = 0
startIndices = {}
endIndices = {}
m = 1000000007
queries.each do |q|
startIndices[q[0]].nil? ? startIndices[q[0]] = 1 : startIndices[q[0]] += 1
endIndices[q[1]].nil? ? endIndices[q[1]] = 1 : endIndices[q[1]] += 1
end
multiplier = 0
nums.each_with_index do |value, index|
multiplier += startIndices[index] unless startIndices[index].nil?
sum += value * multiplier
multiplier -= endIndices[index] unless endIndices[index].nil?
end
result = sum%m
result += m if result < 0
result
end
@markhallen
Copy link
Author

You have an array of integers nums and an array queries, where queries[i] is a pair of indices (0-based). Find the sum of the elements in nums from the indices at queries[i][0] to queries[i][1] (inclusive) for each query, then add all of the sums for all the queries together. Return that number modulo 109 + 7.

Example

For nums = [3, 0, -2, 6, -3, 2] and queries = [[0, 2], [2, 5], [0, 5]], the output should be
sumInRange(nums, queries) = 10.

The array of results for queries is [1, 3, 6], so the answer is 1 + 3 + 6 = 10.

Input/Output

[execution time limit] 4 seconds (rb)

[input] array.integer nums

An array of integers.

Guaranteed constraints:
1 ≤ nums.length ≤ 105,
-1000 ≤ nums[i] ≤ 1000.

[input] array.array.integer queries

An array containing sets of integers that represent the indices to query in the nums array.

Guaranteed constraints:
1 ≤ queries.length ≤ 3 · 105,
queries[i].length = 2,
0 ≤ queries[i][j] ≤ nums.length - 1,
queries[i][0] ≤ queries[i][1].

[output] integer

An integer that is the sum of all of the sums gotten from querying nums, taken modulo 109 + 7.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment