Is Smooth
Description
We define the middle of the array arr as follows:
- if
arrcontains an odd number of elements, its middle is the element whose index number is the same when counting from the beginning of the array and from its end; - if
arrcontains an even number of elements, its middle is the sum of the two elements whose index numbers when counting from the beginning and from the end of the array differ by one.
An array is called smooth if its first and its last elements are equal to one another and to the middle. Given an array arr, determine if it is smooth or not.
Example
-
For
arr = [7, 2, 2, 5, 10, 7], the output should be
isSmooth(arr) = true.The first and the last elements of
arrare equal to7, and its middle also equals2 + 5 = 7. Thus, the array is smooth and the output istrue. -
For
arr = [-5, -5, 10], the output should be
isSmooth(arr) = false.The first and middle elements are equal to
-5, but the last element equals10. Thus,arris not smooth and the output isfalse.
Input/Output
-
[execution time limit] 4 seconds (js)
-
[input] array.integer arr
The given array.
Guaranteed constraints:
2 ≤ arr.length ≤ 105,
-109 ≤ arr[i] ≤ 109. -
[output] boolean
trueifarris smooth,falseotherwise.
[JavaScript (ES6)] Syntax Tips
1
2
3
4
5
6
// Prints help message to the console
// Returns a string
function helloWorld(name) {
console.log("This prints to the console when you Run Tests");
return "Hello, " + name;
}
Solution
1
2
3
4
5
function isSmooth(arr) {
var midPos = Math.floor(arr.length / 2);
var mid = arr[midPos] + (arr.length % 2 ? 0 : arr[midPos - 1]);
return arr[0] === mid && mid === arr[arr.length - 1];
}