Find Sum in Array Certificate Solution

This Python program is designed to calculate the sum of elements in an array based on a set of queries. Each query specifies a range within the array and a value to be added to the sum if the element is zero. The program reads the array and the queries from the standard input, performs the calculations, and writes the results to a file.

Secure your next interview 🎯

CodeRankGPT is a tool powered by GPT-4 that quietly assists you during your coding interview, providing the solutions you need.
In real-time and absolutely undetectable 🥷

Here is the Find Sum in Array Certificate Solution from HackerRank using CodeRankGPT:

The solution works by first creating two cumulative sum arrays: one for the input numbers and another for the count of zeros in the input numbers. Then, for each query, it calculates the sum of the numbers in the specified range by subtracting the cumulative sum at the start of the range from the cumulative sum at the end of the range. If an element in the range is zero, the specified value is added to the sum. This approach allows the program to calculate the sum for each query in constant time, regardless of the size of the range.


import math
import os
import random
import re
import sys

def findSum(numbers, queries):
    a = [0]
    b = [0]
    for x in numbers:
        a.append(a[-1] + x)
        b.append(b[-1] + (x == 0))
    return [a[r] - a[l - 1] + x * (b[r] - b[l - 1]) for l, r, x in queries]

if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    numbers_count = int(input().strip())

    numbers = []

    for _ in range(numbers_count):
        numbers_item = int(input().strip())
        numbers.append(numbers_item)

    queries_rows = int(input().strip())
    queries_columns = int(input().strip())

    queries = []

    for _ in range(queries_rows):
        queries.append(list(map(int, input().rstrip().split())))

    result = findSum(numbers, queries)

    fptr.write('\n'.join(map(str, result)))
    fptr.write('\n')

    fptr.close()

If you have a HackerRank Certification test or a coding interview coming up, you can use CodeRankGPT to your advantage. It will assist you during your test and help ensure you get the certification or the job.

AI is here now, and other candidates might be using it to get ahead and win the job. 🧐

Built on Unicorn Platform