Skip to main content

Simple Array Sum

Simple Array Sum

Easy

Calculate the sum of elements in an array.

ArrayMathImplementation
View Problem

Problem Statement

Given an array of integers, find the sum of its elements.

Function Description: Complete the simpleArraySum function. It should return the sum of the array elements as an integer.

Parameters:

  • ar: an array of integers

Input Format:

  • The first line contains an integer n, the size of the array.
  • The second line contains n space-separated integers representing the array's elements.

Output Format:

  • Print the sum of the array's elements as a single integer.

Example:

Input:
6
1 2 3 4 10 11

Output:
31

Try It Yourself

TypeScript

function simpleArraySum(ar: number[]): number {
// Your solution here
}

Go

func simpleArraySum(ar []int32) int32 {
// Your solution here
}

Solution

Click to reveal solution

This is a straightforward problem that requires iterating through the array and summing all elements.

TypeScript Solution

function simpleArraySum(ar: number[]): number {
return ar.reduce((sum, num) => sum + num, 0);
}

// Complete HackerRank solution with I/O handling
function main() {
const input = require('fs').readFileSync('/dev/stdin', 'utf8').trim().split('
');
const arCount = parseInt(input[0]);
const ar = input[1].split(' ').map(Number);

const result = simpleArraySum(ar);
console.log(result);
}

if (require.main === module) {
main();
}
Time:O(n)
Space:O(1)

Go Solution

package main

import (
"bufio"
"fmt"
"os"
"strconv"
"strings"
)

func simpleArraySum(ar []int32) int32 {
var sum int32 = 0
for _, num := range ar {
sum += num
}
return sum
}

func main() {
reader := bufio.NewReader(os.Stdin)

// Read array count
arCountStr, _ := reader.ReadString('
')
arCount, _ := strconv.Atoi(strings.TrimSpace(arCountStr))

// Read array elements
arStr, _ := reader.ReadString('
')
arStrings := strings.Fields(arStr)
ar := make([]int32, arCount)

for i, s := range arStrings {
val, _ := strconv.Atoi(s)
ar[i] = int32(val)
}

result := simpleArraySum(ar)
fmt.Println(result)
}
Time:O(n)
Space:O(1)

Algorithm:

  1. Read the array size n from input
  2. Read the array elements from input and convert to integers
  3. Iterate through the array and sum all elements
  4. Return/print the result