Task 1
A non-empty array A consisting of N integers is given. Array A represents numbers on a tape.
Any integer P, such that 0 < P < N, splits this tape into two non-empty parts: A[0], A[1], ..., A[P − 1] and A[P], A[P + 1], ..., A[N − 1].
The difference between the two parts is the value of: |(A[0] + A[1] + ... + A[P − 1]) − (A[P] + A[P + 1] + ... + A[N − 1])|
In other words, it is the absolute difference between the sum of the first part and the sum of the second part.
For example, consider array A such that:
A[0] = 3
A[1] = 1
A[2] = 2
A[3] = 4
A[4] = 3
We can split this tape in four places:
P = 1, difference = |3 − 10| = 7
P = 2, difference = |4 − 9| = 5
P = 3, difference = |6 − 7| = 1
P = 4, difference = |10 − 3| = 7
Write a function:
function solution(A);
that, given a non-empty array A of N integers, returns the minimal difference that can be achieved.
For example, given:
A[0] = 3
A[1] = 1
A[2] = 2
A[3] = 4
A[4] = 3
the function should return 1, as explained above.
Write an efficient algorithm for the following assumptions:
N is an integer within the range [2..100,000];
each element of array A is an integer within the range [−1,000..1,000].
Solution
// you can write to stdout for debugging purposes, e.g.
// console.log('this is a debug message');
function solution(A) {
let arrFinal = []
for (let i = 0; i < A.length; i++) {
// first part
let firstPart = 0
for (let j = 0; j <=i; j++) {
firstPart = firstPart + A[j]
}
// second part
let secondPart = 0
for (let j = i + 1; j < A.length; j++) {
secondPart = secondPart + A[j]
}
// result
const result = Math.abs(firstPart - secondPart)
arrFinal.push(result)
}
let min = arrFinal[0]
arrFinal.forEach(() => {
if (element < min) {
min = element
}
})
return min
}
Issues
- No need to check last position
...
for (let i = 0; i < A.length - 1; i++) {
...
- Performance is not good when there are mini loops inside big loop
// Calculate the first part smarter inside the big loop
firstPart = firstPart + A[i]
// Calculate the second part smarter inside the big loop
secondPart = totalSum - firstPart
// Retrieve minimum value smarter inisde the big loop
if (result < minDifference) {
minDifference = result
}
Final
// you can write to stdout for debugging purposes, e.g.
// console.log('this is a debug message');
function solution(A) {
let minDifference = Infinity
const totalSum = A.reduce((prevValue, currElem) => {
return prevValue + currElem
}, 0)
let firstPart = 0
for (let i = 0; i < A.length - 1; i++) {
// first part
firstPart = firstPart + A[i]
// second part
const secondPart = totalSum - firstPart
// result
const result = Math.abs(firstPart - secondPart)
if (result < minDifference) {
minDifference = result
}
}
return minDifference
}
Task 2
A small frog wants to get to the other side of a river. The frog is initially located on one bank of the river (position 0) and wants to get to the opposite bank (position X+1). Leaves fall from a tree onto the surface of the river.
You are given an array A consisting of N integers representing the falling leaves. A[K] represents the position where one leaf falls at time K, measured in seconds.
The goal is to find the earliest time when the frog can jump to the other side of the river. The frog can cross only when leaves appear at every position across the river from 1 to X (that is, we want to find the earliest moment when all the positions from 1 to X are covered by leaves). You may assume that the speed of the current in the river is negligibly small, i.e. the leaves do not change their positions once they fall in the river.
For example, you are given integer X = 5 and array A such that:
A[0] = 1
A[1] = 3
A[2] = 1
A[3] = 4
A[4] = 2
A[5] = 3
A[6] = 5
A[7] = 4
content_copy
In second 6, a leaf falls into position 5. This is the earliest time when leaves appear in every position across the river.
Write a function:
class Solution { public int solution(int X, int[] A); }
content_copy
that, given a non-empty array A consisting of N integers and integer X, returns the earliest time when the frog can jump to the other side of the river.
If the frog is never able to jump to the other side of the river, the function should return −1.
For example, given X = 5 and array A such that:
A[0] = 1
A[1] = 3
A[2] = 1
A[3] = 4
A[4] = 2
A[5] = 3
A[6] = 5
A[7] = 4
content_copy
the function should return 6, as explained above.
Write an efficient algorithm for the following assumptions:
N and X are integers within the range [1..100,000];
each element of array A is an integer within the range [1..X].
Solution
// you can write to stdout for debugging purposes, e.g.
// console.log('this is a debug message');
function solution(X, A) {
// Expectation
let objExpect = {}
for (let i = 1; i < X + 1; i++) {
objExpect[i] = 'true'
}
// Loop array
const objCheck = A.reduce((prevValue, currElem, index, array) => {
if (currElem <= X && currElem > 0 && prevValue[currElem] === undefined) {
prevValue[currElem] = index
}
return prevValue
}, {})
// Check
for (const key in objExpect) {
if (objCheck[key] === undefined) return -1
}
const valuesArray = Object.values(objCheck)
const max = valuesArray.reduce((prev, curr) => (curr > prev ? curr : prev), valuesArray[0])
return max
}
Improvement
- No need to create this object to check,
// Expectation
//let objExpect = {}
//for (let i = 1; i < X + 1; i++) {
// objExpect[i] = 'true'
//}
// Check
if (Object.keys(objCheck).length !== X) {
return -1
}
- Use this to get the maximum value
Math.max(...Object.values(objCheck))
Final
// you can write to stdout for debugging purposes, e.g.
// console.log('this is a debug message');
function solution(X, A) {
// Loop array
const objCheck = A.reduce((prevValue, currElem, index, array) => {
if (currElem <= X && prevValue[currElem] === undefined) {
prevValue[currElem] = index
}
return prevValue
}, {})
// Check if all positions are covered
if (Object.keys(objCheck).length !== X) {
return -1
}
return Math.max(...Object.values(objCheck))
}
Leave a Reply